You are on page 1of 11

Serialization in DotNet

Serialization is the Process of objects getting transformed to stream of bytes to be stored in a File, Memory or a Database. The Main Purpose of Serialization is to Save the State of the object in order to recreate it when needed. The reverse of this Process is called as De-Serialization. Serialization as said before stores the state of the object in Stream of bytes which can be stored in a File, Database or in Memory. Using which a developer can easily recreate the same instance of the object with all its properties whenever required. Different Serialization Formats A. Binary Format: Binary formatter is the most efficient way to serialize objects that will only be read by .NET framework-based applications. This formatter class is in the System.Runtime.Serialization.Formatters.Binary B. Soap Format : This XML Based formatter is easily read by .NET and non-.NET framework based applications . A) Working sample of Binary Formatter : 1) You need to write the Serializable Class <Serializable()> _ Class SerializeObjects Dim name As String Public Property EmpName() As String Get Return name End Get Set(ByVal value As String) name = value End Set End Property
End

Class

2) Now The class in which the Serialization will take place


Imports System.IO Imports System.Runtime.Serialization.Formatters.Binary Class BinaryExample

Shared Sub Main()

Dim ser As New SerializeObjects ser.EmpName = "Hefin" Dim binFor As New BinaryFormatter() binFor.Serialize(File.Create("Demo.bin"), ser) End Sub
End

Class

B) Working sample of the SOAP formatter The Serializable class remains the same only thing that changes is the class where the serialization will take place. NOTE : A reference to the Namespace System.Runtime.Serialization.Formatters.Soap needs to be added.
Imports System.IO Imports System.Runtime.Serialization.Formatters.Soap Class SoapExample

Shared Sub Main() Dim ser As New SerializeObjects ser.EmpName = "Hefin" Dim soapFor As New SoapFormatter() soapFor.Serialize(File.Create("Demo.xml"), ser) End Sub
End

Class

De-Serialization :- The reverse of the serialization process is called the De-Serialization . De-Serialization of the SOAP Serialized Object
Imports System.IO Imports System.Runtime.Serialization.Formatters.Soap Class SoapExample

Shared Sub Main() Dim ser As New SerializeObjects

Dim soapFor As New SoapFormatter()

ser = soapFor.Deserialize(File.Open("Demo.xml", FileMode.Open)) Console.WriteLine(ser.EmpName) End Sub


End

Class

De-Serialization of the Binary Serialized Object


Imports System.IO Imports System.Runtime.Serialization.Formatters.Binary Class BinaryExample

Shared Sub Main() Dim ser As New SerializeObjects

Dim binFor As New BinaryFormatter() ser = binFor.Deserialize(File.Open("Demo.xml", FileMode.Open)) Console.WriteLine(ser.EmpName) End Sub
End

Class

Serialization XML Serialization Object Serialization is a process through which an object's state is transformed into some serial data format, such as XML or binary format, in order to be stored for some later use. In other words, the object is "dehydrated" and put away until we need to use it again. Some good uses for serialization/deserialization include: 1. 2. 3. 4. 5. 6. Storing user preferences in an object. Maintaining security information across pages and applications. Modification of XML documents without using the DOM. Passing an object from on application to another. Passing an object from one domain to another. Passing an object through a firewall as an XML string.

XML Serialization: It is limited that it can serialize only public members. Required Namespace : Imports System.Xml Imports System.Xml.Serialization Create XSD file from Class Object instance into XML file Create one web project and add Person.vb class file. Imports System Imports System.Xml Imports System.Xml.Serialization Namespace XMLSerialization ''' <summary> ''' Summary description for Person. ''' </summary> <XmlRoot("Class_Person")> _ Public Class Person Private m_sName As String Private m_iAge As Integer Public Sub New() End Sub <XmlElement("Property_Name")> _ Public Property Name() As String Get Return m_sName End Get Set(ByVal value As String) m_sName = value End Set End Property <XmlElement("Property_Age")> _ Public Property Age() As Integer Get Return m_iAge End Get Set(ByVal value As Integer) m_iAge = value End Set End Property Public Function Hello() As String Return "Hi! My name is " + Name + " and I am " + Age.ToString() + " years old" End Function Public Function GoodBye() As String Return "So long" End Function End Class End Namespace

[XMLRoot()] and [XMLElement()] these are the .net attributes and tell the serializer where the various members of this object will appear in the XML document and what they will be named. Without these, serialization cannot take place. Dim objXmlSer As New XmlSerializer(GetType(Person)) Dim objLucky As New Person() Dim objStrWrt As StreamWriter objLucky.Name = "Myname" objLucky.Age = 30 Response.Write(objLucky.Hello()) Response.Write(objLucky.GoodBye()) objStrWrt = New StreamWriter(Server.MapPath("abc.xml")) objXmlSer.Serialize(objStrWrt, objLucky) objStrWrt.Close() First of al, we declare and instantiate an XMLSerializer object. The typeof() function describes what type of object it's going to be serializing. Then we assign Name and Age properties of the Person object. Then we used to see the output of that object by calling Hello() and GoodBye() functions. Then we initiates a StreamWriter object and that it will be writing to a file call abc.xml. We then call the Serialize() method of the XMLSerializer object and send it our person object to be serialized as well as the StreamWriter object so it will write the resulting XML to the file specified. Then we close the StreamWriter. The Abc.Xml file is look like. <Xml version="1.0" encoding="utf-8" ?> <c- <Class_Person xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Property_Name>TestProperty1 </Property_Name> <Property_Age>30</Property_Age> </Class_Person> Create class object from XML file XML file into Object instance. Now, make some changes in your abc.xml file. <xml version="1.0" encoding="utf-8" ?> <Class_Person xmlns:xsd= "http://www.w3.org/2001/XMLSchema" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"> <Property_Name>TestProperty2</Property_Name> <Property_Age>32</Property_Age> </Class_Person> First create instance of Person class. Next, we create an instance of StreamReader object and feed it the stored XML file. Then we instantiate the Person object by calling the deserialize() method of the XMLSerializer object. This method use the StreamReader object to read the content of the XML file. You have to explicitly casting the type to Person type.

Dim objDesPerson As New Person() Dim objStrRdr As StreamReader objStrRdr = New StreamReader(Server.MapPath("abc.xml")) Dim objXmlSer As New XmlSerializer(GetType(Person)) objDesPerson = DirectCast(objXmlSer.Deserialize(objStrRdr), Person) Response.Write(objDesPerson.Name) Response.Write(objDesPerson.Age.ToString()) objStrRdr.Close() Binary Serialization Public Class Article Public sTitle As String Public sAuthor As String Public sText As String End Class Not much to this class, just a few string variables. Lets suppose that we need to write an instance of this call tout to disk. To do this, we can use binary serialization. This will create a binary file that can be read back in as an instance of Article. To do this, we will need to implement 2 methods GetObjectData and Overloaded Constructor. It will requires following namespace: Imports System.Runtime.Serialization Imports System.Runtime.Serialization.Formatters.Binary First we will make the class with serializable attribute and implements the ISerializable interface. [Serializable()] Public Class Articles Implements ISerializable End Class We have to implements GetObjectData method of ISerializable interface. Public Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext) info.AddValue("Title", sTitle) info.AddValue("Author", sAuthor) info.AddValue("Text", sText) End Sub This method will allow you to serialize the objects to disk. We could add any code in here that we wanted to customize the way the data is serialized. Now we need a method to retrieve the data from a serialized object then we will use a overloaded constructor for this.

Public Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) sTitle = Convert.ToString(info.GetValue("Title", GetType(String))) sAuthor = Convert.ToString(info.GetValue("Author", GetType(String))) sText = Convert.ToString(info.GetValue("Text", GetType(String))) End Sub The empty constructor is added here so that you can create a new Article object without deserialized one. Now we have a class that can be serialized and deserialized. For serializing this class we have to create methods like Serializing the object Public Sub serialize(ByVal fileName As String) Dim s As New FileStream(fileName, FileMode.Create, FileAccess.ReadWrite) Dim B As New BinaryFormatter() B.Serialize(s, Me) s.Close() End Sub Here first we create an instance of FileStream class which, will create file and open it in read and write mode. Next we create an instance of BinaryForamtter class. This class have Seralize method which take parameters FileStream and Instance which you want to serialize. DeSerializing the object Public Function deSerialize(ByVal fileName As String) As Articles Dim Fs As New FileStream(fileName, FileMode.Open, FileAccess.Read) Dim F As New BinaryFormatter() Dim s1 As Articles = DirectCast(F.Deserialize(Fs), Articles) Fs.Close() Return s1 End Function Here again create an instance of BinaryFormatter. The method Deserialize() will take parameter of FileStream object which point to the binary file which you want to deserialize. You have to do explicit casting of Article type during Deserializing. Create One Project For Serializing Create one Articles.vb class file Imports System Imports System.IO Imports System.Runtime.Serialization Imports System.Runtime.Serialization.Formatters.Binary Namespace BinarySerialization <Serializable()> _ Public Class Articles Implements ISerializable

Public sTitle As String Public sAuthor As String Public sText As String Public Sub New() End Sub Public Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) sTitle = Convert.ToString(info.GetValue("Title", GetType(String))) sAuthor = Convert.ToString(info.GetValue("Author", GetType(String))) sText = Convert.ToString(info.GetValue("Text", GetType(String))) End Sub Public Sub serialize(ByVal fileName As String) Dim s As FileStream s = New FileStream(fileName, FileMode.Create, FileAccess.ReadWrite) Dim B As New BinaryFormatter() B.Serialize(s, Me) s.Close() End Sub Public Function deSerialize(ByVal fileName As String) As Articles Dim Fs As New FileStream(fileName, FileMode.Open, FileAccess.Read) Dim F As New BinaryFormatter() Dim s1 As Articles = DirectCast(F.Deserialize(Fs), Articles) Fs.Close() Return s1 End Function #Region "ISerializable Members" Public Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext) info.AddValue("Title", sTitle) info.AddValue("Author", sAuthor) info.AddValue("Text", sText) End Sub #End Region End Class End Namespace Create one webForm1.aspx page for testing the binary serialization. 'Binary Serialization of the object Dim c1 As New Articles() c1.sTitle = "My Title" c1.sAuthor = "Author Name" c1.sText = "This is my Text" c1.serialize("C:\123.txt") 'deserialization of the object Dim c2 As Articles = c1.deSerialize("C:\123.txt") Response.Write(c2.sTitle) Response.Write(c2.sAuthor) Response.Write(c2.sText)

13.24.1.Class binary Serialization


Imports Imports Imports Imports Imports System System.IO System.Runtime.Serialization System.Runtime.Serialization.Formatters.Binary System.Runtime.Serialization.Formatters.Soap

Public Class Tester Public Shared Sub Main Dim myClsSerializable As New ClsSerializable() SerializeBinary(myClsSerializable) Console.WriteLine(FileContent(False)) Dim myFileStream As FileStream myFileStream = New FileStream("test.dat", FileMode.Open, FileAccess.R ead) Dim myFormatter As New BinaryFormatter() myClsSerializable = CType(myFormatter.Deserialize(myFileStream), ClsS erializable) Console.WriteLine(myClsSerializable.intNumber.ToString) Console.WriteLine(myClsSerializable.lngNumber.ToString) Console.WriteLine(myClsSerializable.strDemo) End Sub Private Dim Dim Dim Dim Try ss.Read) If blnBinary = True Then For i = 1 To myFileStream.Length strContent += myFileStream.ReadByte.ToString + " " Next Else myStreamReader = New StreamReader(myFileStream) strContent = myStreamReader.ReadToEnd End If myFileStream.Flush() myFileStream.Close() Return strContent Catch ex As IOException Console.WriteLine(ex.Message) End Try

Shared Function FileContent(ByVal blnBinary As Boolean) As String strContent As String myStreamReader As StreamReader myFileStream As FileStream i As Integer myFileStream = New FileStream("test.dat", FileMode.Open, FileAcce

End Function Private Shared Sub SerializeBinary(ByVal myClsSerializable As ClsSerializ able) Dim myFileStream As FileStream = New FileStream("test.dat", FileMode. Create, FileAccess.Write) Dim myBFormatter As BinaryFormatter = New BinaryFormatter() myBFormatter.Serialize(myFileStream, myClsSerializable) myFileStream.Flush() myFileStream.Close() End Sub End Class <Serializable()> Public Class ClsSerializable Public intNumber As Integer = 254 Public strDemo As String = "This is a poublic test string" Private strpDemo As String = "This is a private test string" <NonSerialized()> Public lngNumber As Long = 123456

End Class

Binary Serialization Example


[TOC]
Imports System Imports System.IO Imports System.Runtime.Serialization.Formatters.Binary Imports CenterSpace.NMath.Core Namespace CenterSpace.NMath.Core.Examples.VisualBasic ' A .NET example in VB.NET showing how to serialize and deserialize an NMath object ' in binary format. Module SoapSerializationExample Private filename As String = "data.dat" Sub Main() Console.WriteLine() ' Delete old file, if it exists If (File.Exists(filename)) Then Console.WriteLine("Deleting old file") File.Delete(filename) End If

' Create vector Dim u As New DoubleVector("[ 5.6 4.2 5.3 -0.004 434 ]") ' Persist to file Dim stream As FileStream = File.Create(filename) Dim formatter As New BinaryFormatter() Console.WriteLine("Serializing vector") formatter.Serialize(stream, u) stream.Close() ' Restore from file stream = File.OpenRead(filename) Console.WriteLine("Deserializing vector") Dim v As DoubleVector = formatter.Deserialize(stream) stream.Close() Console.WriteLine() Console.WriteLine("Press Enter Key") Console.Read() End Sub End Module End Namespace

You might also like