Friday, December 16, 2016

Custom cast support for objects


We are working with Hashtables a lot in a project, where we need to convert objects into hashtable and from hashtables

A way to do this is by adding custom casting in the class to the class type, and to add a method to convert to hashtable.

Example

   public class MyClass
    {
        public string Name;
        public int Id;
        public string Description;

        public static explicit operator MyClass(Hashtable hashtable)
        {
            MyClass mt = new MyClass();
            mt.Description = hashtable["Description"].ToString();
            mt.Id = int.Parse(hashtable["Id"].ToString());
            mt.Name = hashtable["Name"].ToString();
            return mt;
        }

        public Hashtable ToHashtable()
        {
            var hashtable = new Hashtable();
            hashtable["Name"] = "name";
            hashtable["Id"] = 1;
            hashtable["Description"] = "description";
            return hashtable;
        }
    }
Then simply we can do something like:
Hashtable hashtable = myClass.ToHashtable();

And 
MyClass casted = (MyClass) hashtable;
Example usage:
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass
            {
                Description = "description",
                Id = 1,
                Name = "name"
            };

            Hashtable hashtable = myClass.ToHashtable();
            Console.WriteLine("Hashtable: ");
            Console.WriteLine(hashtable["Name"]);
            Console.WriteLine(hashtable["Id"]);
            Console.WriteLine(hashtable["Description"]);


            MyClass casted = (MyClass) hashtable;
            Console.WriteLine("MyClass: ");
            Console.WriteLine(casted.Id);
            Console.WriteLine(casted.Description);
            Console.WriteLine(casted.Name);

            Console.ReadKey();
        }

Wednesday, December 14, 2016

Error CA2000 call System.IDisposable.Dispose on object

My code looked like


this.client.Setup(mock => mock.PostAsync(It.IsAny<IEnumerable<ids>>())).Returns(Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK)));

and i was getting the below style cop error

Severity Code Description Project File Line Suppression State
Error CA2000 In method 'MyMethod()', call System.IDisposable.Dispose on object 'new HttpResponseMessage(HttpStatusCode.OK)' before all references to it are out of scope. Catalog.Common.UnitTests code.cs 72 Active

To overcome this, if it is in single method, you can suppress the error

[SuppressMessage("Microsoft.Reliability",
                 "CA2000:DisposeObjectsBeforeLosingScope",
                 Justification = "Your reasons go here")]
OR you can change the code to be like below

this.client.Setup(mock => mock.PostAsync(It.IsAny<IEnumerable<ids>>())).Returns(Task.Run(() => { return new HttpResponseMessage(System.Net.HttpStatusCode.OK); }));