October 31, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Serialization/Deserialization in .NET

  • November 18, 2003
  • By Mark Strawmyer
  • Send Email »
  • More Articles »

Using SOAP and Binary Serialization

SOAP and binary serialization are essential if you are planning to transport objects across a network. The SOAP formatter is ideal for sending the object via HTTP, while the binary is more ideal because of its more lightweight and compact nature. The XML serializer cannot prepare an object for transportation by itself. It also ignores private member fields and properties.

XML Serialization Sample Code

By simply adding the [Serializable] attribute to the top of the sample class above, we now can use the SOAP or binary formatter to serialize our object to the respective format. The following code demonstrates using the SOAP formatter.

TestData obj = new TestData();obj.Name = "testing";obj.IgnoreMe = "ignore";IFormatter formatter = new  System.Runtime.Serialization.Formatters.Soap.SoapFormatter();Stream stream = new FileStream("c:\\MyFile.xml", FileMode.Create,                               FileAccess.Write, FileShare.None);formatter.Serialize(stream, obj);stream.Close();

Resulting SOAP

It is important to notice how the SoapFormatter does not pay any attention to any of the XML attributes we had previously assigned our class above.

<SOAP-ENV:Envelope  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd="http://www.w3.org/2001/XMLSchema"  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"  xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0"  SOAP-ENV:encodingStyle=    "http://schemas.xmlsoap.org/soap/encoding/">  <SOAP-ENV:Body><a1:TestData id="ref-1"  xmlns:a1="http://schemas.microsoft.com/clr/nsassem/  CodeGuru.Serialization/  CodeGuru.Serialization%2C%20Version%3D1.0.1404.42352%2C%20  Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"><_Identity>0</_Identity><_Name id="ref-3">testing</_Name><_IgnoreMe id="ref-4">ignore</_IgnoreMe></a1:TestData>  </SOAP-ENV:Body></SOAP-ENV:Envelope>

Implementing the ISerializable Interface

Simply putting the [Serializable] attribute on top of a class is a simple way to make an object serializable. This alone works great if you have basic needs when serializing an object. What happens when you need control over the serialization process and what is ultimately put into the serialized format? This is the purpose of the ISerializable interface. It provides an interface that gives you complete flexibility in the items contained within the serialized format. The interface requires that a constructor be overridden that is used to recreate an instance of the object from a serialized version of the data, also known as deserialization. The second method involved is GetObjectData, which is responsible for controlling the actual values put into the serialized version of the object.

ISerializable Interface Sample Code

The following code refines our sample class defined earlier. It now implements an additional constructor used to deserialize an object, and the GetObjectData method is used to control the serialization process. Now, when the SOAP or binary formatter objects are used to serialize an object, they produce the version controlled by the GetObjectData method.

using System;using System.Runtime.Serialization;using System.Xml.Serialization;namespace CodeGuru.Serialization{  [Serializable]  public class TestData : ISerializable  {    private int _Identity = 0;    private string _Name = "";    public string Name    {      get { return this._Name; }      set { this._Name = value; }    }    private string _IgnoreMe = "";    public string IgnoreMe    {      get { return this._IgnoreMe; }      set { this._IgnoreMe = value; }    }    public TestData()    {    }    protected TestData(SerializationInfo info,                       StreamingContext context)    {      this._Identity = info.GetInt32("_Identity");      this._Name = info.GetString("_Name");    }    void ISerializable.GetObjectData(SerializationInfo info,                                     StreamingContext context)    {      info.AddValue("_Identity", this._Identity);      info.AddValue("_Name", this._Name);    }  }}

Resulting SOAP

<SOAP-ENV:Envelope  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd="http://www.w3.org/2001/XMLSchema"  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"  xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0"  SOAP-ENV:encodingStyle=    "http://schemas.xmlsoap.org/soap/encoding/">  <SOAP-ENV:Body><a1:TestData id="ref-1" xmlns:a1=  "http://schemas.microsoft.com/clr/nsassem/CodeGuru.Serialization/  CodeGuru.Serialization%2C%20Version%3D1.0.1404.42999%2C%20  Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"><_Identity>0</_Identity><_Name id="ref-3">testing</_Name></a1:TestData>  </SOAP-ENV:Body></SOAP-ENV:Envelope>

Summary

You now have seen various ways in which objects can be serialized. This will allow you to store objects in a file, a database, or in an ASP session state and then deserialize them back into original form.

Future Columns

The topic of the next column is yet to be determined. If you have something in particular that you would like to see explained here, you could reach me at mstrawmyer@crowechizek.com.

About the Author

Mark Strawmyer, MCSD, MCSE, MCDBA is a Senior Architect of .NET applications for large- and mid-size organizations. Mark is a technology leader with Crowe Chizek in Indianapolis, Indiana. He specializes in architecture, design, and development of Microsoft-based solutions. You can reach Mark at mstrawmyer@crowechizek.com.

# # #





Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel