Sie sind auf Seite 1von 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.

Simple Example

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

Object Graph
2 Car 3 James Bond Car 1
Representation

Radio

[Car 3, ref 2], [Radio 2], [JamesBondCar 1, ref 3, ref 2]

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. An object graph consists of:
The object being serialized. Any objects the original object references. Any objects those secondary objects refer to, and so on.

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){} }

Choosing a serialization Formatter

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

Choosing a serialization Formatter

To serialize your objects using a binary format, all you to do is specify the following directive://Persist object graph using a binary format! using System.Runtime.Serialization.Formatters.Binary;

For SoapFormatters you must set a reference to System.Runtime.Serialization.Formatters.Soap.dll and use the following
//Persist object graph using a SOAP format! using System.Runtime.Serialization.Formatters.Soap;

Choosing a serialization Formatter

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

Serialization using Binary formatter

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

Serialize()

Serialization using SOAP/XML Formatter.

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

Difference between the 3 Types

Binary Serialization - Light and compact used in Remoting SOAP Serialization interoperable use SOAP and used in web Services XML Serialization - Custom Serialization, also called Shallow serailization Web Services uses the SOAP Serialization and Remoting uses the BinarySerialization.They are called deep Serailization.

Sample Example
Using Binary Formatter

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

Sample Example
Using SOAP Formatter

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

Sample Example
Using XML Formatter

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

Customizing the Serialization Process

System.Runtime.Serialization Namespace Core types

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

Customizing the Serialization Process

In addition two Key Interfaces used for Serialization are IFormatter and Iserializable. Necessary Information required during Serialization
Qualified name of Object(e.g.

MyNamespace.MyClasses.Foo) Assembly name containing the object(e.g myAsm.dll) Objects stateful information, contained within a SerializationInfo type.

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, StreamingContext context); }

GetObjectData() Populates the SerializationInfo param

with the a series of name/value pairs.

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 Serialization Process

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

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; Public int maxSpeed; Public CustomCarType(string s, int i) { petName = s; maxSpeed = i; }

Simple example of Custom Serialization

//Return state info to the formatter Public void GetObjectData(SerializationInfo si, StreamingContext ctx) { si.AddValue(CapPetName, petName.ToUpper()); si.AddValue(maxSpeed, maxSpeed); }

Simple example of Custom Serialization

//Rehydrate a new object based on the incoming //Serializationinfo type Private CustomCarType(SerializationInfo si, StreamingContext ctx) { petName = si.GetString(CarPetName); maxSpeed = si.GetInt32(maxSpeed); } }

Simple example of Custom Serialization

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

References

Andrew Torelsens C# and the .NET Platform http://www.codeproject.com/Purgatory/Serializ ation_in_NET.asp http://www.ondotnet.com

Thank You. Vipin

Das könnte Ihnen auch gefallen