You are on page 1of 30

Welcome!

[Object Serialization in C#]

Basic Meaning of Serialization
‹

Process of converting the state of an Object to a linear sequence of data. Process where an object is converted to a form able to be stored or transported to a different place Process of storing the object instance to a disk file. Serialization stores state of the object i.e. member variable values to disk.

‹

‹

Role of Object Graphs
‹ When a given object is serialized to a stream, any associated

‹ ‹ ‹

‹

object references required by the root object are automatically serialized as well. The chain of related objects serialized to a stream is collectively referred to as an Object Graph Provides a simple way to document how a set of objects refer to each other. To establish the relations among objects in a graph, each object is assigned a unique value, followed by a graph of all related items. Numbers have no real meaning to the outside world.

A simple Object graph that models these relationships is shown below. which “ has a “ Radio.Simple Example ‹ Creating a set of classes that model some automobiles. ‹ ‹ . Top most Class – Car.Another class named JamesBondCar extends the basic Car type.

ref 2]. [JamesBondCar 1.Object Graph 2 Car 3 James Bond Car 1 Representation Radio [Car 3. ref 2] . [Radio 2]. ref 3.

and so on. An object graph consists of: „ The object being serialized. „ Any objects those secondary objects refer to. „ Any objects the original object references. .Object Graph ‹ The beautiful thing about the default Serialization process is that the graph representing the relationships among your Objects is established automatically behind the Scenes. ‹ The object graph is the term for the set of objects that are actually serialized.

Configuring Objects for Serialization ‹ ‹ Use of [Serializable] attribute If some members should not participate in Serialization you can mark such fields with the [NonSerialized] attribute.Member variables that do not need to be remmembered. ‹ . The Radio class which has been marked serializable except for a single member variable.

Configuring Objects for Serialization //this class can participate in the .NET serialization [Serializable] Public class Radio { //this member will not participate [NonSerialized] private int objectIDNumber = 9. //other serialized state data …… public Radio(){} public void On(bool state){…} } .

Formatters namespace contains 2 additional namespaces – (*.Soap) ‹ The BinaryFormatter type serializes your object graph to a stream using a compact binary format.Choosing a serialization Formatter ‹ Next task is to choose which format should be used when persisting your object graph.Runtime.Binary and *. ‹ The SoapFormatter represents your graph as SOAP(Simple Object Access Protocol) message that is expressed using XML data representation. . ‹ System.Serialization.

Soap.Serialization. all you to do is specify the following directive://Persist object graph using a binary format! using System. ‹ For SoapFormatters you must set a reference to System. .Runtime.Runtime.Formatters.Binary.dll and use the following //Persist object graph using a SOAP format! using System.Runtime.Serialization.Choosing a serialization Formatter ‹ To serialize your objects using a binary format.Soap.Formatters.Formatters.Serialization.

IRemotingFormatter interface overloads the above methods for remoting centric persistence.Derived from IFormatter interface. IFormatter defines the key Serialize() and Deserialze() methods.Choosing a serialization Formatter ‹ Implementation of IFormatter and IRemotingFormatter by the formatters. ‹ ‹ .

Returns a generic System.Serialization using Binary formatter ‹ BinaryFormatter Members Members Deserialize() Meaning in Life Deserializes a stream of bytes to an object graph. .Requires Streamderived type as its first parameter. Serialize() .object type and so need to impose an explicit cast Serializes an object or graph of related objects to a stream.

Serialization. reference to System.Xml. except for the Constructor which requires type information of the item as well as the name of the XML namespace of the *. .xml file. ‹ SOAP formatter is similar to the Binary formatter ‹ For Xml formatter .Xml.Serialization using SOAP/XML Formatter. ‹ Similar to SOAP and Binary formatter .dll needed and the following directive is used Using System.

Difference between the 3 Types ‹ Binary Serialization . . also called Shallow serailization ‹ Web Services uses the SOAP Serialization and Remoting uses the BinarySerialization.Custom Serialization.They are called deep Serailization.Light and compact used in Remoting ‹ SOAP Serialization – interoperable use SOAP and used in web Services ‹ XML Serialization .

//Move the object graph into the file stream using a binary format BinaryFormatter myBinaryFormat = new BinaryFormatter(). true). Using System.GoUnderWater(). //Create a file stream to hold the object’s state. myAuto.Runtime. false. myAuto. myBinaryFormat.Create(“CarData.dat”).TurnOnRadio(true).Close().Sample Example ‹ Using Binary Formatter Using System. FileStream myStream = File. } . myAuto).Serialization. myStream.Formatters. Public static void Main() { //Make a car and change some state data JamesBondCar myAuto = new JamesBondCar(“Fred”.IO.Binary. 50.Serialize(myStream.

Serialize(myStream.xml”).Formatters.Create(“CarSoapData. myAuto). Public static void Main() { //Save the same previous car using a Soap format.xml”). FileStream myStream = File. JamesBondCar carFrom Soap = (JamesBondCar )mySoapFormat.Sample Example ‹ Using SOAP Formatter Using System.Close(). //Read in the Car from the Xml file myStream = File.Runtime. } .IO.Serialization.OpenRead(“CarSoapData. mySoapFormat.Soap. myStream.Deserialize(mystream). Using System.Close(). myStream. SoapFormatter mySoapFormat = new SoapFormatter().

} .IO.Xml.Close().OpenRead(“CarXmlData.Create(“CarXmlData.xml”).Serialize(myStream. XmlSerializer myXmlFormat = new XmlSerializer (typeof(JamesBondCar). myStream. Using System.Sample Example ‹ Using XML Formatter Using System.Close(). Public static void Main() { //Save the same previous car using a Soap format.xml”). myAuto). myXmlFormat.Serialization.Deserialize(mystream). myStream. JamesBondCar carFrom Soap = (JamesBondCar ) myXmlFormat . //Read in the Car from the Xml file myStream = File. FileStream myStream = File. “Cars”).

Serialization Namespace Core types Formatter – An abstract base class that provides base functionality for runtime serialization formatters. Serailization Info – Used by objects that have custom serialization behavior.Runtime. SerializationBinder – An abstract base class that provides functionality to serialize a type to a stream. ObjectManager – Keep tracks of Objects as they are being deserialized.This class is a “property bag”that allows you to establish name/value pairs to represent the state of an object .SerializationInfo holds together all the data needed to serailize or deserialize an object.Customizing the Serialization Process ‹ System. ObjectIDGenerator – Generates Ids for Objects in an object graph.

dll) „ Objects’ stateful information. contained within a SerializationInfo type.Customizing the Serialization Process ‹ In addition two Key Interfaces used for Serialization are – IFormatter and Iserializable. .MyClasses.Foo) „ Assembly name containing the object(e. ‹ Necessary Information required during Serialization – „ Qualified name of Object(e.g. MyNamespace.g myAsm.

The Serialization Process SerailizationInfo SerailizationInfo My Object Stream Formatter Some storage device SerailizationInfo Stream My Object Formatter Deserailize() .

The Serialization Process ‹ First step is to implement the ISerializable interface. „ //When u wish to tweak the serialization process //implement the ISerializable public interface Iserializable { public virtual void GetObjectData(SerializationInfo info. } ‹ GetObjectData() – Populates the SerializationInfo param with the a series of name/value pairs. ‹ . StreamingContext context).

The Serialization Process ‹ Must provide a special constructor with the following signature. [Serializable] Class SomeClass : Iserializable { private SomeClass(SerializationInfo si. StreamingContext ctx) { } } ‹ Params are SerializationInfo and StreamingContext .

.The most information member of this type is the State Property which contains the value from the StreamingContextStates enumeration.The Serialization Process ‹ StreamingContext contains info. About the source or destination of the bits.

Streaming Context States ‹ StreamingContextStates Enumeration members are „ All „ Clone „ CrossAppDomain „ CrossMachine „ CrossProcess „ File „ Other „ Persistence „ Remoting .

Simple example of Custom Serialization Public class CustomCarType :ISerializable { Public string petName. maxSpeed = i. int i) { petName = s. Public int maxSpeed. } . Public CustomCarType(string s.

AddValue(‘CapPetName”.AddValue(‘maxSpeed”. si. } . StreamingContext ctx) { si.ToUpper()). petName.Simple example of Custom Serialization //Return state info to the formatter Public void GetObjectData(SerializationInfo si. maxSpeed).

StreamingContext ctx) { petName = si. maxSpeed = si.GetString(“CarPetName”).GetInt32(“maxSpeed”).Simple example of Custom Serialization //Rehydrate a new object based on the incoming //Serializationinfo type Private CustomCarType(SerializationInfo si. } } .

dat”) BinaryFormatter myFormatter = new BinaryFormatter(). return 0. mySteam = File.dat”). } .Deserialize(myStream).Create(“CarData. myAuto).Open(“CarData. myFormatter. myStream.close().Serialize(myStream. Stream myStream = File.Simple example of Custom Serialization Public static int Main(string[] args) { CustomCarType myAuto = new CustomCarType(“Sid”. 50). //special constructor called CustomCarType carFromDisk = (CustomCarType)myFormatter.

codeproject.com .ondotnet.References ‹ Andrew Torelsen’s – C# and the .asp ‹ http://www.com/Purgatory/Serializ ation_in_NET.NET Platform ‹ http://www.

Thank You…. Vipin .