Sunday, March 01, 2009

Binary Serialization example

Serialization in .NET allows us to take an instance of an object and convert it into a format that is easily transmittable over the network, or even stored in a database or file system.
This object will actually be an instance of a custom type, including any properties or fields you may have set.
Serialization is the process of converting an object into a stream of bytes which is easily transferable over the network and storing its current state on any permanent storage media like file or database for later use.
De-serialization is the reverse process of Serialization, where the stored object is taken and the original object is recreated.
.NET provides classes through its System.Runtime.Serialization namespaces that can be used for serializing and de-serializing objects.

Serialization can be divided into following types:
· Binary Serialization: Binary serialization allows the serialization of an object into a binary stream and restoration from a binary stream into an object.
· XML Serialization: XML serialization allows the public properties and fields of an object to be reduced to an XML document that describes the publicly visible state of the object.
· SOAP Serialization: SOAP serialization is similar to XML serialization in that the objects being serialized are persisted as XML.

Below is example how to make a serialize class
And how to serialize and deserialize class.
_
Private Class pvt_clsTest
Public strName As String = String.Empty
End Class


Private Sub pvt_SearializeMe()
Try
Dim cls As New pvt_clsTest
cls.strName = Me.txtNeedToSerialize.Text
Dim mem As New MemoryStream()
Dim binaryFormat As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
binaryFormat.Serialize(mem, cls)
Session("arr") = mem.GetBuffer
Me.txtSerialize.Text = mem.ToString
mem.Close()
Catch ex As Exception
Throw ex
End Try
End Sub

Private Sub pvt_DeserializeMe(ByVal arr As Byte())
Dim ascEn As New ASCIIEncoding
Dim mem As New MemoryStream(arr)
mem.Position = 0
Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Dim cls As pvt_clsTest = CType(bf.Deserialize(mem), pvt_clsTest)
Me.txtDeserialize.Text = cls.strName
mem.Close()

End Sub

for more information visit : http://www.indiandotnet.wordpress.com
Thanks
Rajat Jaiswal