Serialization and de-Serialization in .NET
October 3, 2008
Serialization
While implementing a serialization mechanism in an object-oriented environment, we have to make a number of tradeoffs between ease of use and flexibility. The process can be automated to a large extent, provided you are given sufficient control over the process. For example, situations may arise where simple binary serialization is not sufficient, or there might be a specific reason to decide which fields in a class need to be serialized.
Objective:
To create the serialization program to add data to file in binaryformat and SOAPformat and then by using deserialization we retrieve data from the same file.
Steps to follow:
1. Declare Class hierarchy as [serializable]
2. Include namespace System.Runtime.Serialization.Formatters.Binary or System.Runtime.Serialization.Formatters.Soap
3. Create and intantiation of object.
4. Create and Intantiation of FileStream Object
5. Create and Instantiation of BinaryFormatter or SoapFormatter object
6. For Serialization: use method serialize of class BanaryFormatter/Soap Formatter
7. For DeSerialization: use method deserialize of class BanaryFormatter/Soap Formatter
Code For Person Class:
using System;
using System.Collections.Generic;
using System.Text;
namespace SerializationSample
{
// [Serializable] – To make class serializable
// Each and every base class must be declared as Serializable to make child class serializable.
[Serializable]
// Defination of base class Person
public class Person
{
private string _personName;
public string PersonName
{
get { return _personName; }
set { _personName = value; }
}
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
public Person(string name, int age)
{
_personName = name;
_age = age;
}
}
}
Code For Employee Class:
using System;
using System.Collections.Generic;
using System.Text;
namespace SerializationSample
{
// Full Hierarchi must be declared as [Serializable]
[Serializable]
// Defination of employee class begins .
// Base class is Person
public class employee:Person
{
private int _empid;
public int EmpId
{
get { return _empid; }
set { _empid = value; }
}
private decimal _basic;
public decimal Basic
{
get { return _basic; }
set { _basic = value; }
}
public employee(string _personName,int _age,int empid,decimal basic):base (_personName,_age)
{
_empid=empid;
_basic=basic;
}
}
}
// End of Defination of employee class
Code To Serialize and Deserialize Using Person and Employee Class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
// namespace for Binary formatter
using System.Runtime.Serialization.Formatters.Binary;
// namespace for Soap formatter
using System.Runtime.Serialization.Formatters.Soap;
// Starting for windows application
namespace SerializationSample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FileStream fstream=null;
//Binary formatter object declaration
BinaryFormatter binaryformat=null;
try
{
//Person p = new Person(“scott”, 25);
employee lk = new employee(“deependra”, 23, 77619, 20000);
//Instantiation of FileStream Object
fstream = new FileStream(“Person.txt”, FileMode.Create, FileAccess.Write);
// Instantiation of BinaryFormatter Object
binaryformat = new BinaryFormatter();
//Serialize method is called –
// arguments are <FileStream Object> and <ClassName which going to be serialized> .
// It stores object in file.
binaryformat.Serialize(fstream, lk);
MessageBox.Show(“Employee object in binary FORMAT “);
}
catch (Exception k)
{
MessageBox.Show(k.Message);
}
finally
{
fstream.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
BinaryFormatter binaryformat = null;
FileStream fstream = null;
try
{
fstream = new FileStream(“Person.txt”, FileMode.Open, FileAccess.Read);
binaryformat = new BinaryFormatter();
//Deserialization of employee object
//Input Parameters is FileStream object
//Return type is an object
employee lk = binaryformat.Deserialize(fstream) as employee;
// Showing the Data in Message Box Format
string message=string.Format(“Employee Name:{0}\nEmployee Age:{1} \nEmployee Id :{2}\nEmployee Basic:{3}”,lk.PersonName,lk.Age,lk.EmpId,lk.Basic);
MessageBox.Show(message);
}
catch(Exception ex)
{
MessageBox.Show(“ERROR:”,ex.Message);
}
finally
{
fstream.Close();
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
//DeSerialization using SoapFormatter
//Steps and Methods are same as Binary Formatter
private void button4_Click(object sender, EventArgs e)
{
SoapFormatter soapformat = null;
FileStream fstream = null;
try
{
fstream = new FileStream(“PersonSOAP.txt”, FileMode.Open, FileAccess.Read);
soapformat = new SoapFormatter();
Person p = soapformat.Deserialize(fstream) as Person;
string message = string.Format(“Person Name:{0}\nPerson Age:{1}”, p.PersonName, p.Age);
MessageBox.Show(message);
}
catch (Exception ex)
{
MessageBox.Show(“ERROR:”, ex.Message);
}
finally
{
fstream.Close();
}
}
//Serialization using SoapFormatter
//Steps and Methods are same as Binary Formatter
private void button3_Click(object sender, EventArgs e)
{
FileStream fstream = null;
SoapFormatter soapformat = null;
try
{
Person p = new Person(“scott”, 25);
fstream = new FileStream(“PersonSOAP.txt”, FileMode.Create, FileAccess.Write);
soapformat = new SoapFormatter();
soapformat.Serialize(fstream, p);
MessageBox.Show(“Person object in SOAP FORMAT”);
}
catch (Exception k)
{
MessageBox.Show(k.Message);
}
finally
{
fstream.Close();
}
}
}
}
Output:
Data shown here is store in Binary Format
ÿÿÿÿ JSerializationSample, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null SerializationSample.Person
_personName
_age
scott
Data shown here is store in SOAP Format
<SOAP-ENV:Envelope xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema” xmlns:SOAP-ENC=”http://schemas.xmlsoap.org/soap/encoding/” xmlns:SOAP-ENV=”http://schemas.xmlsoap.org/soap/envelope/” xmlns:clr=”http://schemas.microsoft.com/soap/encoding/clr/1.0″ SOAP-ENV:encodingStyle=”http://schemas.xmlsoap.org/soap/encoding/”>
<SOAP-ENV:Body>
<a1:Person id=”ref-1″ xmlns:a1=”http://schemas.microsoft.com/clr/nsassem/SerializationSample/SerializationSample%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull”>
<_personName id=”ref-3″>scott</_personName>
<_age>25</_age>
</a1:Person>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Entry Filed under: Uncategorized. .
Trackback this post | Subscribe to the comments via RSS Feed