Naz-Tek Services, Inc.

Writing Software To Provide Strategic Advantage

Home     Development Guidelines     Design Patterns     Knowledgebase     Trainingbase     Blog Feed     Events     Tools     About Us     Contact Us      
Memory Management     Event Handling     Multi-Threading     Serialization      

Simple serialization

The following sample demonstrates serializing and de-serializing a class, called Person

[C#]

using System;

using System.IO;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Soap;

 

namespace NazTek.Sample.Serialization

{

    public class TestSerialization

    {

        private const string DATA_FILE = @"C:\Documents and Settings\All Users\Desktop\temp.xml";

        public static void Main (string[] s)

        {

            TestSerialization ts = new TestSerialization();

            ts.Serialize();

            ts.DeSerialize();

        }

        public void Serialize()

        {

            Person person = new Person("Bob", 35);

            Stream stream = File.Open(DATA_FILE, FileMode.Create);

            SoapFormatter formatter = new SoapFormatter();

            formatter.Serialize(stream, person);

            stream.Close();

        }

        public void DeSerialize()

        {

            Stream stream = File.Open(DATA_FILE, FileMode.Open);

            SoapFormatter formatter = new SoapFormatter();

            Person person = (Person)formatter.Deserialize(stream);

            Console.WriteLine("The person's name is {0} and age is {1}", person.Name, person.Age);

            Console.ReadLine();

            stream.Close();

        }

    }

    /// <summary>

    /// Class to serialize

    /// </summary>

    [Serializable]

    public class Person

    {

        private int _age;

        private string _name;

        private DateTime _instanceDate;

        public string Name { get { return _name; } }

        public int Age { get { return _age; } }

        public DateTime InstanceDate { get { return _instanceDate; } }

        public Person(string name, int age)

        {

            _age = age;

            _name = name;

            _instanceDate = DateTime.Now;

        }

    }

}

Advanced serialization

If you want to serialize a class whose code you can’t modify, take the following steps:

  1. If the class doesn’t implement ISerializable
    1. Extend the class and implement ISerializable
    2. Virtualize the ISerializable.GetObjectData for it’s own subclasses
    3. Continue on with the following steps
  2. If the class implements ISerializable, like, System.Exception or the Person class in the sample below
    1. Extend the class, e.g., Employee
    2. Tag the class with Serializable attribute
    3. Provide a de-serialization constructor with the signature: Employee(SerializationInfo info, StreamingContext context)
    4. Override the GetObjectData method

[C#]

using System;

using System.IO;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Soap;

 

namespace NazTek.Sample.Serialization

{

    public class TestSerialization

    {

        private const string DATA_FILE = @"C:\Documents and Settings\All Users\Desktop\temp.xml";

        public static void Main (string[] s)

        {

            TestSerialization ts = new TestSerialization();

            ts.Serialize();

            ts.DeSerialize();

        }

        public void Serialize()

        {

            Person employee = new Employee("E123", "Bob", 35);

            Stream stream = File.Open(DATA_FILE, FileMode.Create);

            SoapFormatter formatter = new SoapFormatter();

            formatter.Serialize(stream, employee);

            stream.Close();

        }

        public void DeSerialize()

        {

            Stream stream = File.Open(DATA_FILE, FileMode.Open);

            SoapFormatter formatter = new SoapFormatter();

            Employee employee = (Employee)formatter.Deserialize(stream);

            Console.WriteLine("The employee's id is {0}, name is {1} and age is {2}", employee.EmployeeId, employee.Name, employee.Age);

            Console.ReadLine();

            stream.Close();

        }

    }

    /// <summary>

    /// A class whose code is unavailable for modification but is in need of serialization

    /// </summary>

    public class Person : ISerializable

    {

        private int _age;

        private string _name;

        private DateTime _instanceDate;

        public string Name { get { return _name; } }

        public int Age { get { return _age; } }

        public DateTime InstanceDate { get { return _instanceDate; } }

        public Person(string name, int age)

        {

            _age = age;

            _name = name;

            _instanceDate = DateTime.Now;

        }

        public virtual void GetObjectData(SerializationInfo info, StreamingContext context)

        {

            info.AddValue("Age", _age);

            info.AddValue("Name", _name);

            info.AddValue("InstanceDate", _instanceDate);

        }

    }

    /// <summary>

    /// Class to serialize

    /// </summary>

    [Serializable]

    public class Employee : Person

    {

        private string _employeeId;

        public string EmployeeId { get { return _employeeId; } }

        public Employee(string employeeId, string name, int age)

            : base(name, age)

        {

            _employeeId = employeeId;

        }

        public Employee(SerializationInfo info, StreamingContext context)

            : base(info.GetValue("Name", Type.GetType("System.String")).ToString(), Convert.ToInt32(info.GetValue("Age", Type.GetType("System.Int32"))))

        {

            _employeeId = info.GetValue("EmployeeId", Type.GetType("System.String")).ToString();

        }

        public override void GetObjectData(SerializationInfo info, StreamingContext context)

        {

            base.GetObjectData(info, context);

            info.AddValue("EmployeeId", _employeeId);

        }

    }

}