Friday, September 22, 2006

.NET : Serialization

What is serialization?

@ Serialization is the process of converting an object into a stream of bytes in order to persist it to memory, a database, or a file.

Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
The object is serialized to a stream, which carries not just the data, but information about the object's type, such as its version, culture, and assembly name.

@ Hah hah, teleportation in science fiction is a good example of serialization, although which is not currently supported by .NET Framework. ;-)

Why use serialization?

@ The two most important reasons are:
to persist the state of an object to a storage medium so an exact copy can be re-created at a later stage,
to send the object by value from one application domain to another.

Scenarioes of using serialization

@ Through serialization, a developer can perform actions like
1. send the object to a remote application by means of a Web Service,
2. pass an object through a firewall as an XML string,
3. maintain security or user-specific information across applications.
4. save session state in ASP.NET
5. copy objects to the Clipboard in Windows Forms
6. pass objects by value from one application domain to another, used by Remoting.

How to serialize and unserialize?

@ How to serialize an object?
At a high level, the steps are:
1. Create a Stream object, to hold the serialized output.
2. Create a BinaryFormatter object, to do serialize work.
3. Call the BinaryFormatter.Serialize method to serialize the object and output the result to the stream.
Dim DataToBeSerialized As String = "This is the content to store in a file."
Dim FileStreamForHolding As FileStream = New FileStream("SeriaziedString.Data", FileMode.Create)
Dim OneBinaryFormatter As BinaryFormatter = New BinaryFormatter
OneBinaryFormatter.Serialize(FileStreamForHolding , DataToBeSerialized)
FileStreamForHolding .Close

@ How to deserialize an object?
At a high level, the steps are:
1. Create a Stream object, to read the serializd output.
2. Create a new object to store the deserialized data.
3. Create a BinaryFormatter object.
4. Call the BinaryFormatter.Deserialize method to deserialized the object, and cast it to the correct type.
Dim FileStreamForReading As FileStream = New FileStream("SerializedString.Data", FileMode.Open)
Dim ObjectToStore As String = ""
Dim BinaryFormatterWorking As BinaryFormatter = New BinaryFormatter
ObjectToStore = CType(BinaryFormatterWorking.Deserialized(FileStreamForReading), String)
FileStreamForReading.Close

@ It is a good practice to make ALL calsses serializable enven if you do not immediately require serialization.

@ To create a class that can be serialized, add the Serializable attribute.