Thursday, September 16, 2010

Serialization in the .NET Framework

Serialization in .NET allows the programmer 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.

The first step in any serialization process is to take the instance of the object and convert it to a memory stream. From there we have the ability to perform any number of operations with (file IO, database IO, etc.).

There are 2 types of serialization. Binary serialization and xml serialization

Core Serialization Methods

#region Binary Serializers

public static System.IO.MemoryStream SerializeBinary(object request) {

System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =

new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

System.IO.MemoryStream memStream = new System.IO.MemoryStream();

serializer.Serialize(memStream, request);

return memStream;

}



public static object DeSerializeBinary(System.IO.MemoryStream memStream) {

memStream.Position=0;

System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer =

new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

object newobj = deserializer.Deserialize(memStream);

memStream.Close();

return newobj;

}

#endregion


#region XML Serializers
 
public static System.IO.MemoryStream SerializeSOAP(object request) {
  System.Runtime.Serialization.Formatters.Soap.SoapFormatter serializer =
  new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
  System.IO.MemoryStream memStream = new System.IO.MemoryStream();
  serializer.Serialize(memStream, request);
  return memStream;
}
 
public static object DeSerializeSOAP(System.IO.MemoryStream memStream) {
  object sr;
  System.Runtime.Serialization.Formatters.Soap.SoapFormatter deserializer =
  new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
  memStream.Position=0;
  sr = deserializer.Deserialize(memStream);
  memStream.Close();
  return sr;
}
#endregion

No comments:

Post a Comment