Tuesday, April 8, 2008

.Net Serialization (Code Snippets)

Serialization is the process of saving the state of an object into persistant medium for storage in file system, transmission over network or passing data between processes.

The serialized file is having information about the data being serialized so that on deserialization you get exactly the same data that you serialized. The data can be serialized as a binary file, xml or SOAP file.
Serialization is used for persisting complex data and not primitive types.

Binary Serializing an ArrayList
BinaryFormatter class is used for binary serializing and deserializing an object.
Create a strem to hold the serialized file. Call the Serialize method of BinaryFormatter.

using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Diagnostics;

BinaryFormatter bf;
FileStream fs;
private void btnSerialize_Click(object sender, EventArgs e)
{
ArrayList al = new ArrayList();
al.Add("Shalvin");
al.Add("Aravindakshan");
fs = new FileStream("c:\\Shalvin.data", FileMode.Create);
bf = new BinaryFormatter();
bf.Serialize(fs, al);
fs.Close();
MessageBox.Show("File serialized successfully");
Process.Start("notepad", "c:\\Shalvin.data");
}

Binary Deserializing an ArrayList

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

FileStream fs;
BinaryFormatter bf;
private void Form1_Load(object sender, EventArgs e)
{
fs = new FileStream("c:\\Shalvin.data", FileMode.Open);
bf = new BinaryFormatter();
ArrayList al = (ArrayList)bf.Deserialize(fs);
listBox1.DataSource = al;
}

Binary Serializing a Hybrid Dictionary

HybridDictionary is optimized for key-based item retrieval from both small and large collections.

using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

HybridDictionary hd;
FileStream fs;
BinaryFormatter bf;

private void Form1_Load(object sender, EventArgs e)
{
hd = new HybridDictionary();
hd.Add("Sh", "Shalvin");
hd.Add("Sa", "Saji");

foreach (DictionaryEntry de in hd)
listBox1.Items.Add(de.Key + " " + de.Value);

fs = new FileStream(@"c:\Sh.data", FileMode.Create);
bf = new BinaryFormatter();
bf.Serialize(fs, hd);
fs.Close();
}

Creating a Very Simple Contact Management Form

We will take up creating a simple data entry form of a contact management form. To make things simple I am tracking only the name and phone no. Unlike similar systems I am not making use of database.
Instead I am serializing the data in the FormClosing event.
In the form load event I am checking for the existence of the serialized file. If the file does not exist I manually creating DataTable, DataRows and DataColumns.
If the serialized file does exist then I am deserialising it and bringing the data to the grid.









































using System.IO;
using System.Runtime.Serialization.Formatters.Binary;


DataTable dt;
DataColumn dc;
DataRow dr;
BinaryFormatter bf = new BinaryFormatter();
FileStream fs;
private void Form1_Load(object sender, EventArgs e)
{
if(File.Exists("c:\\Contacts.dat"))
{
FileStream fs = new FileStream("c:\\Contacts.dat", FileMode.Open);
dt = (DataTable)bf.Deserialize(fs);
dataGridView1.DataSource = dt;
fs.Close();
}
else{
dt = new DataTable("Contacts");
dc = new DataColumn("Name");
dt.Columns.Add(dc);
dc = new DataColumn("Phone");
dt.Columns.Add(dc);

dataGridView1.DataSource = dt;
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
dr = dt.NewRow();
dr["Name"] = txtName.Text;
dr["Phone"] = txtPhone.Text;
dt.Rows.Add(dr);
}
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
fs = new FileStream("c:\\Contacts.dat", FileMode.Create);
bf.Serialize(fs, dt);
fs.Close();
}

XmlSerializing and Deserializing ArrayList

XML Serialization should be the choice if you are working in heterogeneous platform. The process is similar except that you use XMLSerializer of System.Xml.Serialization namespace and should specify the type using typeof at the time of initializing the XMLSerializer.

using System.IO;
using System.Collections;
using System.Xml.Serialization;
private void btnSerialize_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(@"c:\ShalvinAl.xml", FileMode.Create);
XmlSerializer xs = new XmlSerializer(typeof(ArrayList));
ArrayList al;
al = new ArrayList();
al.Add("Shalvin.com");
al.Add("shalvinpd.blogspot.com");
xs.Serialize(fs, al);
fs.Close();
MessageBox.Show("File serialized");
System.Diagnostics.Process.Start("iexplore", @"c:\ShalvinAl.xml");
}

private void btnDeserialize_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(@"c:\ShalvinAl.xml", FileMode.Open);
XmlSerializer xs = new XmlSerializer(typeof(ArrayList));
ArrayList al = (ArrayList)xs.Deserialize(fs);
listBox1.DataSource = al;
}


Serializing a Class
For serializing a class you should add the Serializable attribute to the class.
//Person.cs

[Serializable]
class Person
{
public string name;
public string Specialization;

public Person(string _name, string _Specialization)
{
name = _name;
Specialization = _Specialization;
}
public Person() { }

public override string ToString()
{
return name + " is Specializting in " + Specialization ;
}
}

using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
private void btnSerialize_Click(object sender, EventArgs e)
{
Person sp = new Person("Shalvin", "ASP.Net");

// Create file to save the data to
FileStream fs = new FileStream("c:\\Person.Dat", FileMode.Create);

// Create a BinaryFormatter object to perform the serialization
BinaryFormatter bf = new BinaryFormatter();

// Use the BinaryFormatter object to serialize the data to the file
bf.Serialize(fs, sp);

// Close the file
fs.Close();

System.Diagnostics.Process.Start("notepad", "c:\\Person.Dat");
}

Windows Generated Code for Contact Management System


private void InitializeComponent()
{
this.btnAdd = new System.Windows.Forms.Button();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.txtPhone = new System.Windows.Forms.TextBox();
this.txtName = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnAdd
//
this.btnAdd.Location = new System.Drawing.Point(209, 58);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(29, 23);
this.btnAdd.TabIndex = 11;
this.btnAdd.Text = "+";
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(26, 87);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(240, 150);
this.dataGridView1.TabIndex = 10;
//
// txtPhone
//
this.txtPhone.Location = new System.Drawing.Point(103, 61);
this.txtPhone.Name = "txtPhone";
this.txtPhone.Size = new System.Drawing.Size(100, 20);
this.txtPhone.TabIndex = 9;
//
// txtName
//
this.txtName.Location = new System.Drawing.Point(103, 29);
this.txtName.Name = "txtName";
this.txtName.Size = new System.Drawing.Size(100, 20);
this.txtName.TabIndex = 8;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(52, 68);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(38, 13);
this.label2.TabIndex = 7;
this.label2.Text = "Phone";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(52, 36);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 6;
this.label1.Text = "Name";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.dataGridView1);
this.Controls.Add(this.txtPhone);
this.Controls.Add(this.txtName);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Shalvin Contact Management System";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.TextBox txtPhone;
private System.Windows.Forms.TextBox txtName;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;



Related Blogs
System.IO Namespace in .Net


Happy Programming
shalvin.com

No comments:

Post a Comment