Thursday, August 11, 2011

Serialization in .Net – Part-2 (Binary Serialization with Example)

Binary Serialization: (Light and compact used in Remoting)

 Binary serialization allows the serialization of an object into a binary stream and restoration from a binary stream into an object.

Binary serialization is a mechanism which writes the data to the output stream such that it can be used to re-construct the object automatically.

The term binary in its name implies that the necessary information that is required to create an exact binary copy of the object is saved onto the storage media.

A notable difference between Binary serialization and XML serialization is that Binary serialization preserves instance identity while XML serialization does not. In other words, in Binary serialization the entire object state is saved while in XML serialization only some of the object data is saved.

Binary serialization can handle graphs with multiple references to the same object; XML serialization will turn each reference into a reference to a unique object. The following code listing shows how we can implement binary serialization.

The BinaryFormatter used above is very efficient and produces a very compact byte stream. All objects serialized with this formatter can also be deserialized with it, which makes it an ideal tool for serializing objects that will be deserialized on the .NET platform.

It is important to note that constructors are not called when an object is deserialized. However, this violates some of the usual contracts the run time makes with the object writer, and developers should ensure they understand the ramifications when marking an object as serializable.
  • BinaryFormatter saves metadata (assembly and type information) on the output stream along with object data. This information is necessary to deserialize the data and rebuild the object in memory.

PROS
  • The output byte stream generated is compact

  • The serialization process is faster than using the other formatters.

  • This formatter can serialize generic and non generic collections (being the items within the collection serializable)

  • Serializes public and private members (deep serialization)

CONS
  • Format not readable by other techonolgies (just .NET Framework)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization; //<-- Namespace for Custom Serialization
                                    //(ISerializable,SerializationInfo,StreamingContext)
using System.Runtime.Serialization.Formatters.Binary;//<-- Namespace for Binary Serialization
using System.Xml.Serialization;//<-- Namespace for XML Serialization
using System.Runtime.Serialization.Formatters.Soap;//<--Namespace for Soap Serialization


namespace BinarySerializationByManishAgrahari
{
    [Serializable]//<-- This atribute is just required by BinaryFormatter and SoapFormatter
    public class Employee//<-- XMLSerializer needs that the class is defined as public 
    {
        public int id;
        public string name;//<-- public properties to serialize. They  will be serialize by the three formatters. 
        private string address;//<--this private field won't be serialized using XmlSerialization.
        //They will be serialized using Binary or Soap formatters 
        [NonSerialized] //<-- Using this attribute, the field "gender"
                        //won't be serialized (by any of the three serializers) 
//When using the BinaryFormatter or SoapFormatter classes to serialize an object,
//use the [NonSerialized] Attribute attribute to prevent a field from being serialized.
        public string gender;
        //let's create a method to set the private properties. 
        public void SetAddress(string address)
        {
            this.address = address;
        }

        public string GetAddress()
        {
            return this.address;
        }
    }

    class TestSerialization
    {

        public void BinarySerialize(string filename, Employee emp)
        {
            FileStream fileStreamObject = null;
            try
            {
                fileStreamObject = new FileStream(filename, FileMode.Create);
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(fileStreamObject, emp);
            }
            finally
            {
                fileStreamObject.Close();
            }
        }

        public object BinaryDeserialize(string filename)
        {
            FileStream fileStreamObject = null;
            try
            {
                fileStreamObject = new FileStream(filename, FileMode.Open);
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                return (binaryFormatter.Deserialize(fileStreamObject));
            }
            finally
            {
                fileStreamObject.Close();
            }
        }

        public static void Main()
        {
            Console.WriteLine("*********  Binary Serialization *********");
            String file = @"C:\\Binary_Serialization.txt";
            Employee objEmp = new Employee();
            objEmp.id = 1001;
            objEmp.name = "Manish Agrahari";
            objEmp.SetAddress("Noida");
            objEmp.gender = "Male";

            // Serializataion
            TestSerialization objTestSerialization = new TestSerialization();
            objTestSerialization.BinarySerialize(file, objEmp);
            Console.WriteLine("Object Saved on Location: " + file);

            // Deserialization
            Employee objEmployee = (Employee)objTestSerialization.BinaryDeserialize(file);
            Console.WriteLine("*********  After Deserialization *********");
            Console.WriteLine("Employee ID: " + objEmployee.id);
            Console.WriteLine("Employee Name: " + objEmployee.name);
            Console.WriteLine("Employee Address: " + objEmployee.GetAddress());
            Console.WriteLine("Employee Gender: " + objEmployee.gender); //<-- Here Gender will be blank during deserialization
            //Because It could not be serialized due to [NonSerialized] Attrubute
            Console.ReadLine();
        }
    }
}







Serialization in .Net – Part-1 (What is Serialization)
Serialization in .Net – Part-2 (Binary Serialization with Example)
Serialization in .Net – Part-3 (XML Serialization with Example)
Serialization in .Net – Part-4 (SOAP Serialization with Example)
Serialization in .Net – Part-5 (Custom Serialization with Example)

0 comments: