Monday, May 05, 2008

How to Serialize Object in Dot Net

What is Serialization?

     Serialization is the process of storing the state of an object to the stream of bytes. Using serialization one can store the object in to memory stream or file system in such a way that the original object can be retrieve from persistent medium using DeSerialization.

     One can make the class serialize by adding [Serializable] attribute at the top of class and the dot net framework automatically serialize object of that class when ever required. For example you can store only serializable data in ViewState. So if you have a class which has [Serializable] attribute, the dot net framework automatically serialize it and store it in ViewState. You  do not have to write any code for serialization.

      In this article I used a Person class (shown in Fig - (1)) which has few fields with different datatypes. We will Serialize and Deserialize the object of Person class using CustomSerialization class (shown in Fig (2)).

   1: /// <summary>
   2: /// Summary description for Person
   3: /// </summary>
   4: [Serializable]
   5: public class Person
   6: {
   7:     private string mstrName;
   8:     private string mstrCity;
   9:     [NonSerialized]
  10:     private string mstrPhone;
  11:     private int mintPinCode;
  12:     
  13:  
  14:     public int PinCode
  15:     {
  16:         get { return mintPinCode; }
  17:         set { mintPinCode = value; }
  18:     }
  19:     
  20:     public string Phone
  21:     {
  22:         get { return mstrPhone; }
  23:         set { mstrPhone = value; }
  24:     }
  25:     
  26:     public string City
  27:     {
  28:         get { return mstrCity; }
  29:         set { mstrCity = value; }
  30:     }
  31:     
  32:     public string Name
  33:     {
  34:         get { return mstrName; }
  35:         set { mstrName = value; }
  36:     }
  37:     
  38:     
  39: }

Fig - (1) Person class which we will use for serialization.


   One can add [NonSerialized] attribute for the field that one do not wants to serialize. You can see that we have used [NonSerialized] attribute to mstrPhone field.


   Below is CustomSerialization class which includes the method for Serialization and DeSerialization. We need to import System.Runtime.Serialization and System.Runtime.Serialization.Formatters.Binary namespace.



   1: using System;
   2: using System.Data;
   3: using System.Configuration;
   4: using System.Web;
   5: using System.Web.Security;
   6: using System.Web.UI;
   7: using System.Web.UI.WebControls;
   8: using System.Web.UI.WebControls.WebParts;
   9: using System.Web.UI.HtmlControls;
  10: using System.IO;
  11: using System.Runtime.Serialization;
  12: using System.Runtime.Serialization.Formatters.Binary;
  13:  
  14:  
  15: /// <summary>
  16: /// Summary description for CustomSerialization
  17: /// </summary>
  18: public class CustomSerialization
  19: {
  20:     /// <summary>
  21:     /// Serialize Data
  22:     /// </summary>
  23:     /// <param name="objData">Data to be Serialized</param>
  24:     /// <returns>MemoryStream</returns>
  25:     public static MemoryStream SerializData(Object objData)
  26:     {
  27:         MemoryStream msMemoryStream = new MemoryStream();         
  28:  
  29:         IFormatter objIFormatter = new BinaryFormatter();
  30:         objIFormatter.Serialize(msMemoryStream, objData);
  31:         msMemoryStream.Position = 0;
  32:  
  33:         return msMemoryStream;
  34:     }
  35:  
  36:     /// <summary>
  37:     /// Deserialize Data
  38:     /// </summary>
  39:     /// <param name="msData">Memory Stream containing serialized data</param>
  40:     /// <returns>Object</returns>
  41:     public static object DeSerializData(MemoryStream msData)
  42:     {
  43:         IFormatter objIFormatter = new BinaryFormatter();
  44:         return objIFormatter.Deserialize(msData);
  45:     }
  46: }

Fig - (2) Custom Serialization class to serialize and deserialize the data.


   Code shows a part of web page code behind which shows code for serialization.



   1: public Person objPerson
   2:    {
   3:        get 
   4:        {
   5:            if (ViewState["objPerson"] == null)
   6:                ViewState["objPerson"] = new Person();
   7:            return (Person)ViewState["objPerson"]; 
   8:        }
   9:        set 
  10:        { 
  11:            ViewState["objPerson"] = value; 
  12:        }
  13:    }
  14:  
  15:    public MemoryStream msStreamData
  16:    {
  17:        get
  18:        {
  19:            if (ViewState["msStreamData"] == null)
  20:                ViewState["msStreamData"] = new MemoryStream();
  21:            return (MemoryStream)ViewState["msStreamData"];
  22:        }
  23:        set
  24:        {
  25:            ViewState["msStreamData"] = value;
  26:        }
  27:    }
  28:    
  29:  
  30:    protected void Page_Load(object sender, EventArgs e)
  31:    {
  32:        if (!Page.IsPostBack)
  33:        {           
  34:            objPerson.Name = "Chirag";
  35:            objPerson.City = "Ahmedabad";
  36:            objPerson.Phone = "1234";
  37:            objPerson.PinCode = 3456;            
  38:        }
  39:    }
  40:  
  41:    protected void btnSerializeData_Click(object sender, EventArgs e)
  42:    {
  43:        msStreamData = CustomSerialization.SerializData(objPerson);
  44:    }
  45:  
  46:    protected void btnDeSerializeData_Click(object sender, EventArgs e)
  47:    {
  48:        Person objData = (Person)CustomSerialization.DeSerializData(msStreamData);
  49:    }

Fig - (3) Web Page code behind class


     One thing to note here is, the constructor of Person class will not called when the object is deserialize. 


Happy Programming !!!

1 comment:

Arun Pal said...

the post is good. It helps me very much.