Friday 22 August 2014

Create a custom dependency resolver in ASP.NET MVC4 with IDependencyResolver, SOLID programming

In this post, I will talk about the interface IDependencyResolver and how to use it to build a customized IOC container in ASP.NET MVC4.
In the S.O.L.I.D paradigm, the D says :
" If a class needs one or more dependencies, those dependencies should be provided to the class as abstraction".
In C# language, abstraction means interface. The interface contains some methods signatures but never show how implementations of those methods are done.

A dependency resolver is a "solution" to "resolve" the problem :
"Given an abstraction (interface), how to search and return its real implementation, and if some more implementations are available how to filter them to return the right one ?"
 
This mechanism is also known as Inversion Of Control.

There are several way to feed the class with all dependencies. The most common way is using the class constructor like

public class HomeController(Interface1 interface1, Interface2 interface2 .... InterfaceN interfaceN)

The startup project was a basic MVC project template.


Components framed in orange should be manually create, the global.asax.cs should be modified in this lab.

The IUserService looks like :


IProductService :

ProductService :
ComplexUserService :


DemoController :

I have to notice that the implementation below is commonly used. We should avoid to use it because it's against the S.O.L.I.D. As we can see, the class DemoController is highly coupled to ComplexUserService and ProductService. It would be better if DemoController only know the interface from which they inherit. 





Index.cshtml


 
The interface IDependencyResolver is an interface defined in the namespace System.Web.Mvc :


By inheriting this class, we have to implement two methods :

public object GetService(Type serviceType) : is a 1-to-1 relationship between the "serviceType" ( concretely the interface) and the real implementation ( the return concrete object )
public IEnumerable<object> GetServices(Type serviceType) : is a 1-to-N relationship between the interface ( serviceType ) and all class inheriting this interface.

The full code is shown below.


Global.asax.cs

 
The last line sets the DependencySolverController instance as a resolver in the current domain.
When querying the url http://localhost/Demo/Index, the ASP.NET MVC engine knows that a resolver should be used and all controllers instantiation will be forwarded to the resolver. The resolver uses its internal property Mappings to do the Interface-class resolution.

The current implementation of the IDependencyResolver is just a simple working demo. Many frameworks already exist and are commonly used in many projects : Castle Windsor, Unity, StructureMap, NInject, ....



Friday 15 August 2014

Value type vs Reference Type - C# performance comparison

In this post, I will talk about the main difference between the value type and the reference type in C# and how each of them can impact the performance of your program. 
I will demonstrate it with a concrete case where the performance ratio is around 1000%. 

You can find here a quick introduction ( FYI : the link also says that the type "String" is a reference type rather than a value type).
-Value types are bool, byte,char, decimal, double, enum, float, int, long, sbyte,short, struct, uint, ulong , ushort.
-Reference types are String, class,All arrays (even if their elements are value types),Delegates.

.A data type is a value type if it holds the data within its own memory allocation
.A reference type contains a pointer to another memory location that holds the data
When we pass an object as an input to a function, the notion of value/reference type is also important.

1-void PerformOp(ValueType input)
2-void PerformOp(ReferenceType input)

When calling the function 1, the value type input is stored in a special region of the memory called Stack. Stack region are fully managed by the CPU and we don't care of any memory allocation task. The Stack performs a First Into Last Out mode. At the exit of this function, ALL of variable are popped out of the stack.

When calling the function 2, the reference type input is stored in an another region called Heap.It's another region of the memory where the access is slightly slower than IO on the Stack, because the program need to use pointer ( or address reference) to access the content referenced by this address.

At this point, we have seen the main difference between a value/reference type and program should perform quickly if we use value type.
Is it really the case ? Yes, I can say that using a value type is really mandatory if I need to perform a heavy operation.

In this demo, I use 2 objects : MyClass  and MyStruct.I put all the program at the end of this post ( for now you can ignore the content )
Those objects have the same properties. The only difference is that MyClass is a normal class ( so a reference type ) and MyStruct is a struct ( value type).
The program contains a function FillValueType(MyStruct) and FillReference(MyClass) to build a mock object of each type by filling all the properties by a random values.
There also 2 functions named PerformOpOnHeap(MyClass) and PerformOpOnStack(MyStruct).

I use 2 parallel threads inside which I put a stopwatch to measure N iterations call of  PerformOpOnHeap and PerformOpOnStack.Both functions do exactly the same stuff.


Metric :


Conclusion :
As shown in the diagram, the manipulation of a value type is better than working with a reference value. As from 1000 items, it is a better choice to find a way to transform a class to a struct equivalent and then work with the struct , back again to the class at the end of the heavy operation.

In industry, during a financial project where a lot of process should be performed against a huge list of elements, I often used this trick.

Despite of this result, you must know that the memory stack is limited in size so you have to take care of how the function should be optimized. Remember that when the function exits, all associated stack data are popped out. So it may be better to call the function one or more time rather than having the whole process executed once to avoid a stack memory exception.

Full source code used in this post :
using System;
using System.Diagnostics;
using System.Reflection;
using System.Threading.Tasks;

namespace ClassVsStruct
{
    class Program
    {
        static void Main(string[] args)
        {

            var dMyStruct = new MyStruct();
            var dFilledStruct = FillValueType(dMyStruct);

            var dMyClass = new MyClass();
            FillReference(dMyClass);
            //change the loops value
            var loops = 0;
            Task.Factory.StartNew(() =>
            {
                var ws = new Stopwatch();
                ws.Start();
                Console.WriteLine("Start task PerformOpOnHeap");
                for (var i = 0; i < loops; i++)
                {                   
                    PerformOpOnHeap(dMyClass);                 
                }
                ws.Stop();
                Console.WriteLine("PerformOpOnHeap ends after : " + ws.ElapsedMilliseconds + " ms"); 
            });

            Task.Factory.StartNew(() =>
            {
                var ws = new Stopwatch();
                ws.Start();
                Console.WriteLine("Start task PerformOpOnStack");
                for (var i = 0; i < loops; i++)
                {
                    PerformOpOnStack(dMyStruct);                  
                }
                ws.Stop();
                Console.WriteLine("PerformOpOnStack ends after : " + ws.ElapsedMilliseconds + " ms");
            });
          
         
            Console.WriteLine("End");

            Console.ReadLine();
        }

        /// <summary>
        /// Return a random string
        /// </summary>
        /// <returns></returns>
        static private string GenerateString()
        {
            return Guid.NewGuid().ToString();
        }

        static MyStruct FillValueType(object obj)
        {
            var objType = obj.GetType();
            var i =0;
            foreach (var propertyInfo in objType.GetProperties())
            {
                i++;
                if (propertyInfo.PropertyType == typeof(string))
                {
                  
                        obj.GetType()
                            .GetProperty(propertyInfo.Name)
                            .SetValue(obj, GenerateString(), BindingFlags.GetProperty, null, null, null);
                   
                }
             
                else if (propertyInfo.PropertyType == typeof(DateTime?))
                {
                    obj.GetType()
                       .GetProperty(propertyInfo.Name)
                       .SetValue(obj, DateTime.Now, BindingFlags.GetProperty, null, null, null);
                }
                else if (propertyInfo.PropertyType == typeof(double?))
                {
                    obj.GetType()
                       .GetProperty(propertyInfo.Name)
                       .SetValue(obj, 1565498798.8978D, BindingFlags.GetProperty, null, null, null);
                }
            }
            Console.WriteLine("Number of loop " + i);
            return (MyStruct)obj;
        }

        static void FillReference(object obj)
        {
            var objType = obj.GetType();
            var i = 0;
            foreach (var propertyInfo in objType.GetProperties())
            {
                i++;
                if (propertyInfo.PropertyType == typeof(string))
                {

                    obj.GetType()
                        .GetProperty(propertyInfo.Name)
                        .SetValue(obj, GenerateString(), BindingFlags.GetProperty, null, null, null);

                }

                else if (propertyInfo.PropertyType == typeof(DateTime?))
                {
                    obj.GetType()
                       .GetProperty(propertyInfo.Name)
                       .SetValue(obj, DateTime.Now, BindingFlags.GetProperty, null, null, null);
                }
                else if (propertyInfo.PropertyType == typeof(double?))
                {
                    obj.GetType()
                       .GetProperty(propertyInfo.Name)
                       .SetValue(obj, 1565498798.8978D, BindingFlags.GetProperty, null, null, null);
                }
            }
            Console.WriteLine("Number of loop " + i);
        }

        static MyStruct PerformOpOnStack(MyStruct sStruct)
        {
            var objType = sStruct.GetType();
           
            foreach (var propertyInfo in objType.GetProperties())
            {
                if (propertyInfo.PropertyType == typeof (string))
                {
                    var pProperty = sStruct.GetType()
                        .GetProperty(propertyInfo.Name);
                    var currentValue =
                        pProperty.GetValue(sStruct, BindingFlags.Public, null, null, null);
                    pProperty
                        .SetValue(sStruct, currentValue+GenerateString()+"b", BindingFlags.GetProperty, null, null, null);
                }

                else if (propertyInfo.PropertyType == typeof(DateTime?))
                {
                    sStruct.GetType()
                       .GetProperty(propertyInfo.Name)
                       .SetValue(sStruct, DateTime.Now, BindingFlags.GetProperty, null, null, null);
                }
                else if (propertyInfo.PropertyType == typeof(double?))
                {
                    sStruct.GetType()
                       .GetProperty(propertyInfo.Name)
                       .SetValue(sStruct, 1565498798.8978D, BindingFlags.GetProperty, null, null, null);
                }
            }
           
            return sStruct;
        }

        static void PerformOpOnHeap(MyClass cClass)
        {
            var objType = cClass.GetType();
         
            foreach (var propertyInfo in objType.GetProperties())
            {
                if (propertyInfo.PropertyType == typeof(string))
                {
                    var pProperty = cClass.GetType()
                        .GetProperty(propertyInfo.Name);
                    var currentValue =
                        pProperty.GetValue(cClass, BindingFlags.Public, null, null, null);
                    pProperty
                        .SetValue(cClass, currentValue + GenerateString() + "b", BindingFlags.GetProperty, null, null, null);
                }
                else if (propertyInfo.PropertyType == typeof(DateTime?))
                {
                    cClass.GetType()
                       .GetProperty(propertyInfo.Name)
                       .SetValue(cClass, DateTime.Now, BindingFlags.GetProperty, null, null, null);
                }
                else if (propertyInfo.PropertyType == typeof(double?))
                {
                    cClass.GetType()
                       .GetProperty(propertyInfo.Name)
                       .SetValue(cClass, 1565498798.8978D, BindingFlags.GetProperty, null, null, null);
                }
            }
         
        }
    }

    public class MyClass
    {

        public string SuperPropertyString1 { get; set; }
        public string SuperPropertyString2 { get; set; }
        public string SuperPropertyString3 { get; set; }
        public string SuperPropertyString4 { get; set; }
        public string SuperPropertyString5 { get; set; }
        public string SuperPropertyString6 { get; set; }
        public string SuperPropertyString7 { get; set; }
        public string SuperPropertyString8 { get; set; }
        public string SuperPropertyString9 { get; set; }
        public string SuperPropertyString10 { get; set; }
        public string SuperPropertyString11 { get; set; }
        public string SuperPropertyString12 { get; set; }
        public string SuperPropertyString13 { get; set; }
        public string SuperPropertyString14 { get; set; }
        public string SuperPropertyString15 { get; set; }
        public string SuperPropertyString16 { get; set; }
        public string SuperPropertyString17 { get; set; }
        public string SuperPropertyString18 { get; set; }
        public string SuperPropertyString19 { get; set; }
        public string SuperPropertyString20 { get; set; }

        public DateTime? SuperPropertyDateTime1 { get; set; }
        public DateTime? SuperPropertyDateTime2 { get; set; }
        public DateTime? SuperPropertyDateTime3 { get; set; }
        public DateTime? SuperPropertyDateTime4 { get; set; }
        public DateTime? SuperPropertyDateTime5 { get; set; }
        public DateTime? SuperPropertyDateTime6 { get; set; }
        public DateTime? SuperPropertyDateTime7 { get; set; }
        public DateTime? SuperPropertyDateTime8 { get; set; }
        public DateTime? SuperPropertyDateTime9 { get; set; }
        public DateTime? SuperPropertyDateTime10 { get; set; }
        public DateTime? SuperPropertyDateTime11 { get; set; }
        public DateTime? SuperPropertyDateTime12 { get; set; }
        public DateTime? SuperPropertyDateTime13 { get; set; }
        public DateTime? SuperPropertyDateTime14 { get; set; }
        public DateTime? SuperPropertyDateTime15 { get; set; }
        public DateTime? SuperPropertyDateTime16 { get; set; }
        public DateTime? SuperPropertyDateTime17 { get; set; }
        public DateTime? SuperPropertyDateTime18 { get; set; }
        public DateTime? SuperPropertyDateTime19 { get; set; }
        public DateTime? SuperPropertyDateTime20 { get; set; }


        public double? SuperPropertyDouble1 { get; set; }
        public double? SuperPropertyDouble2 { get; set; }
        public double? SuperPropertyDouble3 { get; set; }
        public double? SuperPropertyDouble4 { get; set; }
        public double? SuperPropertyDouble5 { get; set; }
        public double? SuperPropertyDouble6 { get; set; }
        public double? SuperPropertyDouble7 { get; set; }
        public double? SuperPropertyDouble8 { get; set; }
        public double? SuperPropertyDouble9 { get; set; }
        public double? SuperPropertyDouble10 { get; set; }
        public double? SuperPropertyDouble11 { get; set; }
        public double? SuperPropertyDouble12 { get; set; }
        public double? SuperPropertyDouble13 { get; set; }
        public double? SuperPropertyDouble14 { get; set; }
        public double? SuperPropertyDouble15 { get; set; }
        public double? SuperPropertyDouble16 { get; set; }
        public double? SuperPropertyDouble17 { get; set; }
        public double? SuperPropertyDouble18 { get; set; }
        public double? SuperPropertyDouble19 { get; set; }
        public double? SuperPropertyDouble20 { get; set; }



    }
    
    public struct MyStruct
    {
       
        public string SuperPropertyString1 { get; set; }
        public string SuperPropertyString2 { get; set; }
        public string SuperPropertyString3 { get; set; }
        public string SuperPropertyString4 { get; set; }
        public string SuperPropertyString5 { get; set; }
        public string SuperPropertyString6 { get; set; }
        public string SuperPropertyString7 { get; set; }
        public string SuperPropertyString8 { get; set; }
        public string SuperPropertyString9 { get; set; }
        public string SuperPropertyString10 { get; set; }
        public string SuperPropertyString11 { get; set; }
        public string SuperPropertyString12 { get; set; }
        public string SuperPropertyString13 { get; set; }
        public string SuperPropertyString14 { get; set; }
        public string SuperPropertyString15 { get; set; }
        public string SuperPropertyString16 { get; set; }
        public string SuperPropertyString17 { get; set; }
        public string SuperPropertyString18 { get; set; }
        public string SuperPropertyString19 { get; set; }
        public string SuperPropertyString20 { get; set; }

        public DateTime? SuperPropertyDateTime1 { get; set; }
        public DateTime? SuperPropertyDateTime2 { get; set; }
        public DateTime? SuperPropertyDateTime3 { get; set; }
        public DateTime? SuperPropertyDateTime4 { get; set; }
        public DateTime? SuperPropertyDateTime5 { get; set; }
        public DateTime? SuperPropertyDateTime6 { get; set; }
        public DateTime? SuperPropertyDateTime7 { get; set; }
        public DateTime? SuperPropertyDateTime8 { get; set; }
        public DateTime? SuperPropertyDateTime9 { get; set; }
        public DateTime? SuperPropertyDateTime10 { get; set; }
        public DateTime? SuperPropertyDateTime11 { get; set; }
        public DateTime? SuperPropertyDateTime12 { get; set; }
        public DateTime? SuperPropertyDateTime13 { get; set; }
        public DateTime? SuperPropertyDateTime14 { get; set; }
        public DateTime? SuperPropertyDateTime15 { get; set; }
        public DateTime? SuperPropertyDateTime16 { get; set; }
        public DateTime? SuperPropertyDateTime17 { get; set; }
        public DateTime? SuperPropertyDateTime18 { get; set; }
        public DateTime? SuperPropertyDateTime19 { get; set; }
        public DateTime? SuperPropertyDateTime20 { get; set; }


        public double? SuperPropertyDouble1 { get; set; }
        public double? SuperPropertyDouble2 { get; set; }
        public double? SuperPropertyDouble3 { get; set; }
        public double? SuperPropertyDouble4 { get; set; }
        public double? SuperPropertyDouble5 { get; set; }
        public double? SuperPropertyDouble6 { get; set; }
        public double? SuperPropertyDouble7 { get; set; }
        public double? SuperPropertyDouble8 { get; set; }
        public double? SuperPropertyDouble9 { get; set; }
        public double? SuperPropertyDouble10 { get; set; }
        public double? SuperPropertyDouble11 { get; set; }
        public double? SuperPropertyDouble12 { get; set; }
        public double? SuperPropertyDouble13 { get; set; }
        public double? SuperPropertyDouble14 { get; set; }
        public double? SuperPropertyDouble15 { get; set; }
        public double? SuperPropertyDouble16 { get; set; }
        public double? SuperPropertyDouble17 { get; set; }
        public double? SuperPropertyDouble18 { get; set; }
        public double? SuperPropertyDouble19 { get; set; }
        public double? SuperPropertyDouble20 { get; set; }



    }
}




Saturday 9 August 2014

Create generic type object by using Activator class

This post aims to show how to create an object from a generic class using the activator class.
Given the class :
public class MyObject
{
        public string Name { get; set; }

}
We can instantiate a new MyObject object by :
var newObject =   (MyObject)Activator.CreateInstance(typeof(MyObject));

What happens if the class looks like :

  public class DataObject<T>
    {
        public DataObject(string name)
        {
            Name = name;
        }
        public string Name { get; set; }
        public List<T> ContenList { get; set; }
    } 
 We can achieve this goal with :

 var dataObjectBody = (DataObject<string>)Activator.CreateInstance(typeof(DataObject<>).MakeGenericType(typeof(string)),"Foody");
 The MakeGenericType tells that we want to use the generic T as a string type.
The "Foody" value is used for the constructor name parameter when the Activator.CreateInstance creates the object at runtime.

In the case where the class uses a multi generic type like:
 public class DataObject1<T,TU>
    {
        public DataObject1(string name)
        {
            Name = name;
        }
        public string Name { get; set; }
        public List<T> ContenListT { get; set; }
        public List<TU> ContenListU { get; set; }
    } 
The same method is being used, we need to do small changes on the arguments

 var obj1 =
                (DataObject1<string, string>)
                    Activator.CreateInstance(typeof (DataObject1<,>).MakeGenericType(typeof (string), typeof (string)),
                        "Foody");


Json.NET vs JavascriptSerializer performance comparison

In this post, I will talk about Json.NET and the native JavascriptSerializer libraries.
Json.NET, mostly known under NewtonSoft.Json is a library specialized into de/serialization to json format. The library becomes a standard as from VS 2012 as jquery was as from VS 2010.It is available here.
JavascrtipSerializer is a .NET native object  doing the same stuff as Json.NET, this class belongs to the  System.Web.Script.Serialization namespace.

As seen in the home page of Json.NET, it seems to be 250% faster than the javascriptSerializer. In this post, I will try to build a litte enterprise level scenario to see what really happens in background.

Version used :
- Json.NET 6.0.0.0, the latest release at writing
- .NET Framework 4.0

In this labs, I will use two simples objects named SuperObject and ObjectChild

SuperObject has :
- 20 string properties 
-  20 double properties
- 20 datetime? properties
- 20 List<ObjectChild> properties

ObjectChild has :
- 20 string properties 
- 20 double properties
- 20 datetime? properties

Its simulates a massive structure and hierachy that is close to industrial scenario : object are fetched from the database, all of its properties are set, all dependencies are loaded and the final object is serialized ( JsonResult, WEB.API ) into Json then send to the client (view).

I have filled all those properties automatically by using some reflexion trick.
- Guid string was injected to all string type
- DateTime.Now for all DateTime? type
- A large number for the double type

All tests are done on a DELL quad core i7 720qm laptop which allow me to use multithreading on the test program. The full source code is at the end of this post.


Results :
 

 For a small object size ( 1 to 10 nested object ), JavascriptSerializer is bit faster than the Json.NET. The difference is around 2/3, so I have to consider that for a simple structure with a small data, JavascriptSerializer is more effficient  and more lightweight ( see diagram below).
When the data increase, my choice goes on Json.NET serializer. It becomes very efficient tool if we want to get data faster. For 1000 nested object number, Json.NET takes "only" 7500 ms to execute, JavascriptSerializer 23seconds.


The both tools serialize object to json format. The json string length is different. JavascriptSerializer wins every time on this metric. If you need to return a lightweight data, use JavascriptSerializer. It is usefull if the client is on a low-bandwidth location.
As example for 1000 nested object number, Json.NET produces 65464018 chars and 61503685 for JSerializer, a difference of 33960333 chars !

 For the same object serialized earlier, the deserialization result is unexpected. In all of my study case, the JavascriptSerializer performs very quickly. So in all deserialization , I will use JavascriptSerializer.Deserialize method.



What happens if I use Json.NET for serialization and JavascriptSerializer for deserialization ?
No issue. Even if the produced json string  is not the same, each of these tools can independently deserialize the string to the right object without data loose.

Conclusion:
- When deserializing, use JavascriptSerializer.Deserialize
- If reducing the amount of data is a must, using JavascriptSerializer may do the job
- For small data, it's up to you.
- For complex and heavy structure of data, use Json.NET to serialize.
- For optimization, think to serialize with Json.NET and deserialize with JavascriptSerializer.