Tuesday, March 4, 2014

Making own Serializable class

To make the object to serialize in your own way better to implement ISerializableinside the class, specifying the members whose data need to be serialize inside method GetObjectData (a ISerializable member method) , parameter ofSerializationInfo will hold the key value pair kind of information to allow the Serialization.

Also class needs to have constructor having same signature of GetObjectData, so that at the time of de-serializing the serialized data will be passed via parameter of the constructor, as data are already added in Key Value pare kind of form in GetObjectData its easy to get restore the state to its member.

To illustrate the usage in application, the base class is used to make the member serialize

using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Generic;

namespace SerializationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            JaiHo objNewCompany = new JaiHo();
            objNewCompany.Country = "INDIA";
            objNewCompany.Employee.Add(new Employee("A", 1));
            objNewCompany.Employee.Add(new Employee("B", 2));
            objNewCompany.Name = "New Song";
            objNewCompany.NatureOfBusiness = "Music";

            Console.WriteLine("Before Serializing the object..");
            PrintObjectInfo(objNewCompany);

            SerializerHelper objSerializer = new SerializerHelper();
            objSerializer.Serialize(objNewCompany);

            JaiHo objDeserializedCompany = (JaiHo)objSerializer.DeSerialize();
            Console.WriteLine("After De-Serializing the object..");
            PrintObjectInfo(objDeserializedCompany);

            Console.ReadLine();

        }

        static void PrintObjectInfo(JaiHo objJaiHo)
        {
            string strInfo = string.Format("\r\n************************************" +
                "\r\nName of Company : {0} \r\nNaure of Business : {1}\r\n" +
                "Located In : {2} \r\n", objJaiHo.Name, objJaiHo.NatureOfBusiness, objJaiHo.Country);
            foreach (Employee objEmp in objJaiHo.Employee)
            {
                strInfo += string.Format("\tEmployee ID : {0}\t Employee Name : {1}\r\n", objEmp.ID, objEmp.Name);
            }
            Console.WriteLine(strInfo);
        }

    }

    class SerializerHelper : IDisposable
    {
        FileStream objStream = new FileStream("Data.dep"FileMode.Create);

        public void Serialize(object obj)
        {
            try
            {
                BinaryFormatter objFormatter = new BinaryFormatter();
                objFormatter.Serialize(objStream, obj);
            }
            catch (SerializationException e)
            {
                Console.WriteLine("Failed to serialize : " + e.Message);
                throw;
            }
        }

        public object DeSerialize()
        {
            object objReturn = null;
            try
            {
                BinaryFormatter objFormatter = new BinaryFormatter();
                objStream.Position = 0;
                objReturn = objFormatter.Deserialize(objStream);
            }
            catch (SerializationException e)
            {
                Console.WriteLine("Failed to serialize : " + e.Message);
                throw;
            }
            return objReturn;
        }

        public void Dispose()
        {
            objStream.Close();
        }
    }


    [Serializable]
    abstract class Company : ISerializable
    {
        private List<Employee> objEmployee;
        private string strName;

        public List<Employee> Employee
        {
            get { return objEmployee; }
            set { objEmployee = value; }
        }

        public string Name
        {
            get { return strName; }
            set { strName = value; }
        }


        /// Normal Constructor
        public Company()
        {
            objEmployee = new List<Employee>();
        }

        ///
        /// This Constructor required to restore the object state when de-serializing it.
        protected Company(SerializationInfo info, StreamingContext context)
        {
            Type objType = this.GetType();
            foreach (PropertyInfo propInfo in objType.GetProperties())
            {
                propInfo.SetValue(this, info.GetValue(propInfo.Name, propInfo.PropertyType), null);

            }
        }

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            Type objType = this.GetType();
            foreach (PropertyInfo propInfo in objType.GetProperties())
            {
                info.AddValue(propInfo.Name, propInfo.GetValue(thisnull), propInfo.PropertyType);
            }
        }

    }

    [Serializable]
    class JaiHo : Company
    {
        public JaiHo()
        { }

        /// This Constructor required to restore the object state when de-serializing it.
        private JaiHo(SerializationInfo info, StreamingContext context)
            : base(info, context)
        { }

        private string strNatureOfBusiness;
        private string strCountry;

        public string NatureOfBusiness
        {
            get { return strNatureOfBusiness; }
            set { strNatureOfBusiness = value; }
        }

        public string Country
        {
            get { return strCountry; }
            set { strCountry = value; }
        }

    }

    [Serializable]
    class Employee
    {
        private string strName;
        private int nID;

        public Employee()
        {
        }

        public Employee(string name, int ID)
        {
            this.strName = name;
            this.nID = ID;
        }

        public string Name
        {
            get { return strName; }
            set { strName = value; }
        }

        public int ID
        {
            get { return nID; }
            set { nID = value; }
        }
    }
}

No comments:

Post a Comment