Saturday, August 11, 2012

Binary Soap XML and Custom Serialization in Dot Net

Serialization
Find the solution of following Questions:
Ques: What is serialization and deserialization?
Ques: Why we use serialization?
Ques: How to serialize an object?
Ques: Define: Custom,XML, Binary Soap and XML serialization.

Why Serialization:
·     To persist the state of an object to a storage medium so an exact copy can be recreated at a later stage. Although it can be done without serialization but Serialization provides a convenient mechanism for achieving this objective with minimal effort when we have a large application with thousands of objects
·         To send the object by value from one application domain to another.

Example:
1: serialization is used to save session state in ASP.NET and to copy objects to the clipboard in Windows Forms.
2: It is also used by remoting to pass objects by value from one application domain to another

What is Serialization:
Serialization can be defined as the process of storing the state of an object instance to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, is converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created

1. Serialization is a process of converting an object into a stream of data so that it can be is easily transmittable over the network or can be continued in a persistent storage location.  This storage location can be a physical file, database or ASP.NET Cache.
2. Serialization is the technology that enables an object to be converted into a linear stream of data that can be easily passed across process boundaries and machines.  This stream of data needs to be in a format that can be understood by both ends of a communication channel so that the object can be serialized and reconstructed easily.

Advantage:
Using serialization is the ability to transmit data across the network in a cross-platform-compatible format, as well as saving it in a persistent or non-persistent storage medium in a non-proprietary format.

Serialization is used by Remoting, Web Services SOAP for transmitting data between a server and a client.  The Remoting technology of .NET makes use of serialization to pass objects by value from one application domain to another.

De-serialization is the reverse; it is the process of reconstructing the same object later.

Figure :
Dot net serialization and deserialization

The Serializable Attribute
In order for a class to be serializable, it must have the attribute SerializableAttribute set and all its members must also be serializable, except if they are ignored with the attribute NonSerialized  Attribute.  However, the private and public members of a class are always serialized by default.  The SerializationAttribute is only used for the binary serialization.  The code snippet below shows the usage of Serializable attribute.
[Serializable]
public class MyObject 
{
  public int n1 = 0;
  public int n2 = 0;
  public String str = null;
}

Selective Serialization


By default, all members of a class are serialized, including private members. To reduce the amount of data serialized to the stream, you can inhibit serialization of members that are not required to reconstitute the class by attaching the NonSerialized attribute to those members


[Serializable]
public class MyObject 
{
  public int n1;
  [NonSerialized] public int n2;
  public String str;
}

Types of Serialization

Serialization can be of the following types:
1.     Binary Serialization
2.     SOAP Serialization
3.     XML Serialization
4.     Custom Serialization

Binary Serialization

The necessary information that is required to create an exact binary copy of the object is saved onto the storage media.


Public void BinarySerialize(string filename, Employee emp)

{

  FileStream fileStreamObject;
  try

  {
    fileStreamObject =new FileStream(filename, FileMode.Create);

    BinaryFormatter binaryFormatter =new BinaryFormatter();

    binaryFormatter.Serialize(fileStreamObject, emp);
  }
  finally

  {
    fileStreamObject.Close();
  }
}
The following code listing shows how we can implement binary de-serialization.

Public static object BinaryDeserialize(string filename)

{

  FileStream fileStreamObject; 

  try

  {

    fileStreamObject =new FileStream(filename, FileMode.Open);

    BinaryFormatter binaryFormatter =new BinaryFormatter();

    return (binaryFormatter.Deserialize(fileStreamObject));

  }
  finally

  {
    fileStreamObject.Close();
  }
}


SOAP Serialization
In order to use SOAP serialization in .NET we have to add a reference to System.Runtime.Serialization.Formatters.Soap in the application.  The basic advantage of SOAP serialization is portability.  The SoapFormatter serializes objects into SOAP messages or parses SOAP messages and extracts serialized objects from the message. 


publicvoid SOAPSerialize(string filename,Employee employeeObject)

{

  FileStream fileStreamObject =new FileStream(filename, FileMode.Create);

  SoapFormatter soapFormatter =new SoapFormatter();

  soapFormatter.Serialize(fileStreamObject, employeeObject);
  fileStreamObject.Close();
The following code listing shows how we can implement de-serialization using the SOAP protocol.

publicstaticobject SOAPDeserialize(string filename)

{

  FileStream fileStreamObject =new FileStream(filename, FileMode.Open);

  SoapFormatter soapFormatter =new SoapFormatter();

  object obj = (object)soapFormatter.Deserialize(fileStreamObject);

  fileStreamObject.Close();
  return obj;

}


Xml  Serialization
XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format (in this case, XML) for storage or transport. Because XML is an open standard, the XML stream can be processed by any application, as needed, regardless of platform

Note: XmlSerializer does not use the ISerializable interface; rather, it uses the IXmlSerializable interface.  The XmlSerializer class can only serialize the public properties of the class


publicvoid XMLSerialize(Employee emp, String filename)

{

  XmlSerializer serializer =null;

  FileStream stream =null;

  try

  {
    serializer =new XmlSerializer(typeof(Employee));

    stream =new FileStream(filename, FileMode.Create, FileAccess.Write);

    serializer.Serialize(stream, emp);
  }
  finally

  {
    if (stream !=null)

      stream.Close();
  }
}



The following code listing shows how we can implement XML de-serialization.

public static Employee XMLDeserialize(String filename)

{

  XmlSerializer serializer =null;

  FileStream stream =null;

  Employee emp =new Employee();

  try

  {
    serializer =new XmlSerializer(typeof(Employee));

    stream =new FileStream(filename, FileMode.Open);

    emp = (Employee)serializer.Deserialize(stream);

  }
  finally

  {
    if (stream !=null)

      stream.Close();
  }
  return emp;

}



Custom Serialization
In some cases, the default serialization techniques provided by .NET may not be sufficient in real life.  This is when we require implementing custom serialization.  It is possible to implement custom serialization in .NET by implementing the ISerializable interface..  This interface allows an object to take control of its own serialization and de-serialization process.  It gives us a great deal of flexibility in the way we can save and restore objects.  The ISerializable interface consists of a single method, GetObjectData, which accepts two parameters.
The SerializationInfo class serves as the container for all the data we want to serialize.  The AddValue method is called to add the objects we want to serialize to this container.  The implementing class needs to have the GetObjectData method and a special constructor which is used by the common language runtime during the process of de-serialization.  The following code listing shows how we can implement Custom Serialization.

public class Employee: ISerializable

{

  private int empCode;

  private string empName;

  protected Employee(SerializationInfo serializationInfo, StreamingContext

    streamingContext)
  {
    this.empCode = serializationInfo.GetInt32("empCode");

    this.empName = serializationInfo.GetString("empName");

  }


  public void ISerializable.GetObjectData(SerializationInfo serializationInfo,

  StreamingContext streamingContext)
  {
    serializationInfo.AddValue("empCode"this.empCode);

    serializationInfo.AddValue("empName"this.empName);

  }
}


More related links:


0 comments:

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Powered by Code Imagine