Showing posts with label Performance. Show all posts
Showing posts with label Performance. Show all posts

Friday, July 12, 2013

Microsoft .Net Framework implementation of Generics in Custom Linked List C#

What is Generics ?

Generics is the Concept of defining a common Template for all kind of data type. It ensure the Type Safety.
Same class or same Algorithm can be derived for all kind of Data Types . generally it is defined  by "T" character.

Feature and Advancement of Generics are , 
1. It increases the Performance of a application.
2. Reusable code.

Let's we see the Generics concepts implemented in Linked List
LinkedList  is a data structure used to store the data in linear manner. LinkedList Node stores the data internally, Node consists of additional information which will have the address of next item which is added to the linked list.

Data's are iterate from head to the tail using the address of next item ,which is present in the current node
Here a,b,c,d,e,f are the data's .

a is stored in address  1000, Point the next data by there address 2000
is stored in address  2000, Point the next data by there address 3000
is stored in address  3000, Point the next data by there address 4000
is stored in address  4000, Point the next data by there address 5000
is stored in address  5000, Point the next data by there address 6000
is stored in address   6000, Point the next data by there address 7000





So Let we create a Common LinkedListNode class which will support all data type.

Now we create a custom Linked list with one method "Add" and iterate the data through foreach 

class Program
    {
    
    
        public static void Main(string[] args)
        {
            LinkedList<int> list1=new LinkedList<int>();
            list1.Add(2);
            list1.Add(4);
            list1.Add(5);
            foreach(int j in list1)
                Console.WriteLine("Number {0}",j);
        
            LinkedList<string> list2=new LinkedList<string>();
            list2.Add("C#");
            list2.Add("Java");
            list2.Add("Sql");
            foreach(string k in list2)
                Console.WriteLine("String {0} ",k);
                    
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }

output




We see the implementation of Generics in LinkedListNode . Node consists of Value which will store the data and Prev , Next store the address of Previous and Next Value.

      public class LinkedListNode<T>
    {
        private T _value;
        public T Value
        {
            get {return _value;}
        }
      
        private LinkedListNode<T> _next;
        public LinkedListNode
<T> Next
        {
            get{return _next;}
            internal set{_next = value;}
        }
      
        private LinkedListNode
<T> _prev;
        public LinkedListNode<T> Prev
        {          
            get{return _prev;}
            internal set{_prev = value;}
        }
      
        public LinkedListNode(T value)
        {
            this._value = value;  
        }              
    }
   
Now the LinkedList will store the LinkedListNode on addition of each value.This class is implemented simply actually it can be implemented by adding more methods and properties. like Remove,Exists,Length etc.

   public class LinkedList
<T>:IEnumerable<T>
    {
        private LinkedListNode
<T> _first;
        public LinkedListNode<T> First
        {
            get {return _first;}
        }
      
        private LinkedListNode
<T> _last;
        public LinkedListNode<T> Last
        {          
            get {return _last;}
        }
      
        public void Add(T value)
        {
            LinkedListNode
<T> node=new LinkedListNode<T>(value);
            if(_first==null)
            {
                _first = node;  /* Now assign the value to first node */
                _last = _first;
            }
            else
            {
                _last.Next = node;
                _last=node;
            }
        }
      
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
      
        public IEnumerator GetEnumerator
<T>()
        {
            LinkedListNode
<T> cur=_first;
            while(cur!=null)
            {
                yield return cur.Value;
                cur = cur.Next;
            }
        }
    }
     From this article we can see the basic information of custom implementation of Generic LinkedList .

Thursday, July 11, 2013

Microsoft .Net Framework internal implementation Binary Search in List (Collection) - Data structure

                 In Dotnet framework System.Collections is a namespace where we can find the collection class like Stack, Queue, LinkedList ,List etc.Now in this article we are going to see the real implementation of List inside the framework and explanation of how we are using the List in our code.

                          It is designed to be fast for internal implementations, It contains lot of useful operation such as Binary Search,Sort etc.The methods on List are not virtual and so cannot be overridden.Let we see the How to code List and get the data from that collection. In List  T refers to the datatype of the collection , so because of this declaration boxing and unboxing are avoided in storing and retrieve the data from collection. We can store any type . Each type have individual object.




Output : 




Now let we see the implementation of Binary Search in List class internally in framework. This algorithm is used to find the Element exist in List and return the index of that element.

Binary Search is actually implemented in Array , It is called from List for check the item exists.

Code for Binary Search Tree :









From this article we can see the Algorthim BinarySearch used for search the item exist in List

Monday, July 8, 2013

PreGenerated XmlSerializers.dll in ASP.Net Web Service - Increases Web Service Performance

In .Net , XmlSerializers Generates a temprory  assembly for serializing and deserializing your class for Performance reasons, It can be generated on the runtime or pregenerated the assembly during compilation of your ASP.Net web service.

How it is Works in Asp.Net web service ?

When we call a web service from a client for the First time , you will notice that Asp.net service take lit bit time to load, this is because it has to generate the XmlSerializer.dll at the runtime in system temp location    "%SYSTEMROOT%\Temp " for the first time invocation .After the first invocation it will become better because the service have the code to Serialize and deSerialize the Response .

One each request it will generate the dll at runtime in temp location, If the dll is not present there in Temp folder. some times this dll will be deleted by AntiVirus by consider it as Serialization.dll virus in temp folder.

To see the Generated XmlSerializer.dll code we can enable it through web.Config. Add the following code in the web.config file of your Asp.Net web service application . Enable the debug mode.

 <configuration>
    <system.diagnostics>
       <switches>
          <add name="XmlSerialization.Compilation" value="1" />
       </switches>
    </system.diagnostics>
</configuration>

Now you can see the XmlSerialization.dll in the temp location, if you want to generate it at particular path, then that can be done by following code in  web.Config. Create "c:\\dllfolder" directory and Make sure your hosting application have access rights to the folder. c:\\dllfolder

<system.xml.serialization> 
<xmlSerializer tempFilesLocation="c:\\dllfolder"/>
</system.xml.serialization>

During build a project in VS the XmlSerialzer.dll is auto generated. This can be stopped by following steps.
  1. In VS, right-click your project file and select "Properties"
  2. Click the "Build" tab
  3. Change the "Generate serialization assembly" dropdown from "Auto" to "Off"
  4. Rebuild and it will be gone

Now Let we start how to PreGenerate the XmlSerialization.dll .

Overall Steps for the PreGenerated XmlSerializers.dll 
Step by step:
1. Add the locations of the tools used to the path environment variable.
2. Use wsdl.exe .NET SDK utility to generate the proxy c# code file from the wsdl file.
3. Compile the c# proxy into a dll.
4. Use sgen.exe .NET SDK utility to generate an Xml Serialization dll for the proxy.
5. Remove out the all occurrences of XmlIncludeAttribute from the c# proxy class.
6. Insert XmlSerializerAssemblyAttribute present in the generated serialization dll.
7. Recompile the proxy dll with the reference to the serialization dll.

Step 1
           Create a Sample Calculator service and host in local server.Code for Calculator service is mention below.























                  
Here due to avoid manual step of generate the proxy class i have create a client application which will create proxy automatically by reference the web service.
 Service address is "http://localhost:30967/Calculator.asmx"

Step 2
           Now call this web Service from your client Application by adding web Reference using following steps.

This step is for client application which are in .Net Project 2.0
 2.1 Right click your project in VS.
 2.2 Select Add Web Reference.
 2.3 Paste your hosted URL for this Calculator application.
 2.4 Give Web Reference name and add it

This step for Client application which are in .Net Project 3.0 or 3.5
 1. Right click your project in VS.
 2. Select Add Service Reference .
 3. click the Advance Button which is present in bottom of the screen. which will launch a another screen.
 4. Click the Add Web Reference button , follow the steps from 2.3 to 2.4





Step 3. 
        Now go to visual studio command prompt and iterate to the project sub folders , which contains the proxy for service class 




       In My application it is named as Reference.cs , you can can see the service class name inside the file. This is the proxy class.Copy the file and create a new sub folder and paste the file there with rename the file as Calculator.cs

 Step 3.1  Open that cs file and change the constructor like add an parameter "string url"

 Step 3.2  Comment the global:: line and assign the url input parameter to This.Url
  public Calculator(string url)
 {
            this.Url = url;   //global::SampleProject.Properties.Settings.Default.SampleProject_CalSer_Calculator;
 }
       Now execute the following command in command prompt of VS, This will create a library  in the visual studio installation path inside VC folder.
csc  /t:library  /out:calser.dll "C:\SampleProject\Web References\CalSer\Calculator.cs"


Step 4 :
             Following  Use the sgen tool to pre-generate the XmlSerializers.dll for the Calser.dll . Dll will be generated in the same folder where Calser.dll presents.Generation of dll will take few seconds.

Now execute the following command in command prompt of VS

             sgen /p  "C:\SampleProject\Web References\cal\Calser.dll"

Step 5:
         Open the Calculator.cs and comment out all occurrences of  a particular attribute present in file , which is very important “[System.Xml.Serialization.XmlIncludeAttribute”

Step 6:
          Add the attribute to the existing attribute which is present on top of the proxy class ,This attribute will tell that an XmlSerializer.dll is binded to this proxy class this should be called at runtime on each invocation “[System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = "calser.XmlSerializers")]”

 [System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = "calser.XmlSerializers")]
public partial class Calculator : System.Web.Services.Protocols.SoapHttpClientProtocol 
{

}

Step 7:
       Now again compile and generate a Calser.dll which consisits reference of XmlSerializer.Dll in proxy class ,Dll is generated in the VC folder inside the visual studio installation directory

       Now execute the following command in command prompt of VS
csc  /t:library  /out:calser.dll "C:\SampleProject\Web References\CalSer\Calculator.cs"

Step 8: 
        Now Add the Reference Calser.dll to your Project and call the Constructor of that class by passing the valid Url, You can see the difference in performance of calling a getting a response from ASP.NET Webserivce

             CalSer.Calculator addop = new CalSer.Calculator(@"http://localhost:30967/Calculator.asmx");
            CalSer.CalResponse addres = addop.Add(1020);
            if(addres.Result=="Success")
            Response.Write(addres.value);

         Thats it, From this article you can find out how we can improve the performance of Asp.Net Web Service call.

Note :
    1. Whenever the service code is changes ,you have to recompile the Dll.