.NET Serialization

Abstract
 
Serialization is another great feature of .NET. This article talks about overall serialization in the .NET Framework and various available types such as binary, XML, and SOAP. The prime objective of serialization is to persist and retrieve the state of an object. There are various scenarios where the ability to serialize objects is handy.
 
One Real-world example
 
A great example of binary serialization (I will cover later in this article) is the American Consulate website to apply for a US Visa. When you start filling in the US Visa forms online, it allows you to save the application. When this option is chosen then it actually uses binary serialization in the background and saves your application data on your machine in a .DAT file format (I will also cover later in this article).
 
Once your Visa application is saved, you can reopen the saved application (application's filename.dat) and continue working. The application is opened with data that you saved as it is, and this happens due to the De-Serialization feature (I will cover later in this article).
 
Understanding Serialization
 
Serialization demonstrates the process of encoding objects into some data formats, which facilitates their transmission across the network or to another medium. Objects can be serialized and later de-serialized to reconstitute into objects.
 
Essentially, serialization allows you to convert an object into a series of bytes and write those bytes into a stream object. You can then read those bytes to re-create the original object. As an analogy, serialization is frequently used in ASP.Net where classes need to be serializable in order to be stored in the view state for a page. Serialization also allows serialization of a single object or collection of objects.
 
Serialization in Action
 
To make an object available to serialization services, all you need to do is decorate each related class or structure with the [Serializable] attribute. If you determine that some members should not participate in the serialization scheme then you can mark such fields with the [NonSerialized] attribute. This can be helpful in reducing the size of persisted data.
 
In order to implement serialization into a .NET Framework application, the Serializable object must meet the following criteria:
  1. The object must have a Serializable attribute preceding the class declaration.
  2. If the class derives from another class then all parent classes must also be serializable.
  3. All the public and private member variables of the class must be serializable.
  4. You must import these namespaces as:
    1. using System.IO;  
    2. using System.Runtime.Serialization;  
    3. using System.Runtime.Serialization.Formatters; 
If you violate any of these notions then the .NET runtime throws a SeleizationException when you attempt to serialize the object. Once you configure your types to participate in the .NET serialization scheme by applying the necessary attributes, your next step is to choose which format you should use when persisting your object's state. Each possibility is represented by the following categories as BinaryFormatter, XMLSerializer, and SoapFormatter.
 

BinaryFormatter

 
The BinarySerializer implementation requires the following steps;
  1. To serialize an object, create a FileStream object with the name of the file you want to create on disk.
  2. Create a BinaryFormatter object and call its Serialize() method, passing in a reference to a FileStream object and a reference to the object you want to serialize.
  3. Now to deserialize an object, create a FileStream object that opens the file that contains the object that you want to be deserialized.
  4. Create a BinaryFormatter object and call its Deserialize() method, passing in a reference to a FileStream object.
  5. The BinaryFormatter.Deserialize() method returns an object. This object must be cast to the appropriate type.
Now we are creating a Test class having some property and a ToString() method. Here the serialization attribute preceding the Test class, tells the compiler that the instance of the Test class can be serialized.
 
Hence, we will persist in the state of the Test class in binary format as:
  1. [Serializable]  
  2. public class BinarySerialize  
  3. {  
  4.      public BinarySerialize (){ }  
  5.      public BinarySerialize (string fname,string lname)  
  6.      {  
  7.           this.FirstName = fname;  
  8.           this.Lastname = lname;  
  9.      }  
  10.      public string FirstName  
  11.      { getset;}  
  12.      public string LastName  
  13.      { getset;}  
  14.      public override string ToString()  
  15.      {  
  16.           return (FirstName + " " + LastName);  
  17.      }  

The following section describes the deserialization of the Test class object. Here, we first instantiate the Test class with an array of objects and populate it with three objects. The serialization process starts with the FileStream class reference fs. In the body of the try block, the FileStream object is created using the filename "test.dat". Next, a BinaryFormatter is created and it's Serialize() method is called passing in the reference to FileStream and reference of the array.
  1. static void Main(string[] args)  
  2. {  
  3.     BinarySerialize [] obj = new BinarySerialize [3];  
  4.     obj[0] = new Test("Vidya Vrat""Agarwal");  
  5.     obj[1] = new Test("Vamika""Agarwal");  
  6.     obj[2] = new Test("Arshika""Agarwal");  
  7.     Console.WriteLine("Before Serialization\n");  
  8.     for (int i = 0; i < obj.Length; i++)  
  9.     {  
  10.          Console.WriteLine(obj[i].ToString());  
  11.     }  
  12.     Console.WriteLine("_______________________");  
  13.     Console.WriteLine("After Serialization\n");             
  14.     //Serilaize object  
  15.     FileStream fs = null;  
  16.     Try  
  17.     {  
  18.          fs = new FileStream("test.dat", FileMode.Create);  
  19.          BinaryFormatter bf = new BinaryFormatter();  
  20.          bf.Serialize(fs, obj);  
  21.     }  
  22.     catch (SerializationException ex)  
  23.     {  
  24.          Console.WriteLine(ex.Message);  
  25.     }  
  26.     Finally  
  27.     {  
  28.          fs.Close();  
  29.     }             
  30.     //Deserilaize object             
  31.     fs = null;  
  32.     BinarySerialize[] DeObj= null;  
  33.     fs = new FileStream("test.dat", FileMode.Open);  
  34.     BinaryFormatter Debf = new BinaryFormatter();  
  35.     DeObj = (BinarySerialize[])Debf.Deserialize(fs);  
  36.     for (int i = 0; i < DeObj.Length;i++)  
  37.     {  
  38.          Console.WriteLine(DeObj[i].ToString());   
  39.     }  
  40.     Console.ReadKey();  

The deserialization process begins by setting the reference fs to null and creating a completely new array to house the deserialized array of Test objects. However, a new BinaryFormatter object is created and its Deserialized() method is called passing in a reference to the FileStream object. After successfully compiling this program, the output will be:
 
image1.png
 
The .dat file can be seen under your program's bin\debug folder.
 
image2.png
 

XMLSerializer

 
You can persist the state of an object to disk in XML format using the XMLSerializer class as in the following;
  1. Import System.Xml and System.Xml.Serialization namespace.
  2. To serialize an object, create a StreamWriter object with the name of the file you want to create on disk.
  3. Create an XMLSerializer object and call its Serialize() method, passing in a reference to a FileStream object and a reference to the object you want to serialize.
  4. Now to deserialize an object, create a FileStream object that opens the file that contains the object that you want to be deserialized.
  5. Create an XMLSerializer object and call its Deserialize() method, passing in a reference to a FileStream object.
  6. Finally, the Deserialize() method returns an object. This object must be cast to the appropriate type.
  1. static void Main(string[] args)  
  2. {  
  3.      XMLSerialize[] obj = new XMLSerialize[3];  
  4.      obj[0] = new Test("Vidya Vrat""Agarwal");  
  5.      obj[1] = new Test("Vamika""Agarwal");  
  6.      obj[2] = new Test("Arshika""Agarwal");  
  7.      Console.WriteLine("Before Serialization\n");  
  8.      for (int i = 0; i < obj.Length; i++)  
  9.      {  
  10.           Console.WriteLine(obj[i].ToString());  
  11.      }  
  12.      Console.WriteLine("_______________________");  
  13.      Console.WriteLine("After Serialization\n");  
  14.      //Serilaize object  
  15.      TextWriter tw = null;  
  16.      Try  
  17.      {  
  18.            tw = new StreamWriter("test.xml");  
  19.            XmlSerializer xs = new XmlSerializer(typeof(XMLSerialize[]));  
  20.            xs.Serialize(tw, obj);  
  21.      }  
  22.      catch (IOException ex)  
  23.      {  
  24.            Console.WriteLine(ex.Message);  
  25.      }  
  26.      Finally  
  27.      {  
  28.            tw.Close();  
  29.            tw = null;  
  30.      }  
  31.      //Deserilaize object                        
  32.      XMLSerialize[] DeObj= null;  
  33.      FileStream fs = null;  
  34.      Try  
  35.      {  
  36.           fs = new FileStream("test.xml", FileMode.Open);  
  37.           XmlSerializer xsDe = new XmlSerializer(typeof(XMLSerialize[]));  
  38.           DeObj = (Test[])xsDe.Deserialize(fs);  
  39.      }  
  40.      catch (IOException io)  
  41.      {  
  42.           Console.WriteLine(io.Message);  
  43.      }  
  44.      Finally  
  45.      {  
  46.            fs.Close();                   
  47.      }  
  48.      for (int i = 0; i < DeObj.Length;i++)  
  49.      {  
  50.            Console.WriteLine(DeObj[i].ToString());   
  51.      }  
  52.      Console.ReadKey();  

The .xml file can be seen under your program's bin\debug folder.
 
image3.png
 
After building and compiling this project, you can observe that the test.xml file is created in the solution directory. You will see the persisted state of the test class in XML encoding as in the following:
 
image4.png


Recommended Free Ebook
Similar Articles