+ All Categories
Home > Documents > Object Serailization in CSharp

Object Serailization in CSharp

Date post: 02-Apr-2018
Category:
Upload: ponni-molu
View: 249 times
Download: 0 times
Share this document with a friend

of 30

Transcript
  • 7/27/2019 Object Serailization in CSharp

    1/30

    Welcome!

    [Object Serialization in C#]

  • 7/27/2019 Object Serailization in CSharp

    2/30

  • 7/27/2019 Object Serailization in CSharp

    3/30

    Role of Object Graphs

    When a given object is serialized to a stream, any associated

    object references required by the root object areautomatically 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 allrelated items.

    Numbers have no real meaning to the outside world.

  • 7/27/2019 Object Serailization in CSharp

    4/30

    Simple Example

    Creating a set of classes that model some

    automobiles.

    Top most Class Car, which has a

    Radio.Another class namedJamesBondCar

    extends the basic Cartype.

    A simple Object graph that models these

    relationships is shown below.

  • 7/27/2019 Object Serailization in CSharp

    5/30

    Object Graph

    3

    2

    1

    Car

    Radio

    James Bond Car

    Representation

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

  • 7/27/2019 Object Serailization in CSharp

    6/30

  • 7/27/2019 Object Serailization in CSharp

    7/30

    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.

  • 7/27/2019 Object Serailization in CSharp

    8/30

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

    }

  • 7/27/2019 Object Serailization in CSharp

    9/30

    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.

  • 7/27/2019 Object Serailization in CSharp

    10/30

    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;

  • 7/27/2019 Object Serailization in CSharp

    11/30

    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.

  • 7/27/2019 Object Serailization in CSharp

    12/30

    Serialization using Binary formatter

    BinaryFormatter Members

    .Members Meaning in Life

    Deserialize() Deserializes a stream of bytes

    to an object graph.Returns ageneric System.object type and

    so need to impose an explicit

    cast

    Serialize() Serializes an object or graph of

    related objects to a

    stream.Requires Stream-

    derived type as its first

    parameter.

  • 7/27/2019 Object Serailization in CSharp

    13/30

    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.

  • 7/27/2019 Object Serailization in CSharp

    14/30

    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 arecalled deep Serailization.

  • 7/27/2019 Object Serailization in CSharp

    15/30

    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();}

  • 7/27/2019 Object Serailization in CSharp

    16/30

    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 filemyStream = File.OpenRead(CarSoapData.xml);

    JamesBondCar carFrom Soap =

    (JamesBondCar )mySoapFormat.Deserialize(mystream);

    myStream.Close();}

  • 7/27/2019 Object Serailization in CSharp

    17/30

    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();

    }

  • 7/27/2019 Object Serailization in CSharp

    18/30

    Customizing the Serialization Process

    System.Runtime.Serialization Namespace Core types

    Formatter An abstract base class that provides basefunctionality for runtime serialization formatters.

    ObjectIDGenerator Generates Ids for Objects in an objectgraph.

    ObjectManager Keep tracks of Objects as they are beingdeserialized.

    SerializationBinder An abstract base class that providesfunctionality to serialize a type to a stream.

    Serailization Info Used by objects that have customserialization behavior.SerializationInfo holds together all thedata needed to serailize or deserialize an object.This class isa property bagthat allows you to establish name/value pairs

    to represent the state of an object

  • 7/27/2019 Object Serailization in CSharp

    19/30

    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 aSerializationInfo type.

  • 7/27/2019 Object Serailization in CSharp

    20/30

    The Serialization Process

    My Object Formatter

    FormatterMy Object

    SerailizationInfo

    Deserailize()

    SerailizationInfo

    SerailizationInfo

    Stream

    Stream

    Some storage

    device

  • 7/27/2019 Object Serailization in CSharp

    21/30

    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 paramwith the a series of name/value pairs.

  • 7/27/2019 Object Serailization in CSharp

    22/30

    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 andStreamingContext

  • 7/27/2019 Object Serailization in CSharp

    23/30

    The Serialization Process

    StreamingContext contains info. About the source

    or destination of the bits.The most informationmember of this type is the State Property which

    contains the value from the

    StreamingContextStates enumeration.

  • 7/27/2019 Object Serailization in CSharp

    24/30

    Streaming Context States

    StreamingContextStates Enumeration members are

    All

    Clone

    CrossAppDomain

    CrossMachine CrossProcess

    File

    Other Persistence

    Remoting

  • 7/27/2019 Object Serailization in CSharp

    25/30

    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;

    }

  • 7/27/2019 Object Serailization in CSharp

    26/30

    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);

    }

  • 7/27/2019 Object Serailization in CSharp

    27/30

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

    }

  • 7/27/2019 Object Serailization in CSharp

    28/30

    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 calledCustomCarType carFromDisk =(CustomCarType)myFormatter.Deserialize(myStream);

    return 0;

    }

  • 7/27/2019 Object Serailization in CSharp

    29/30

    References

    Andrew Torelsens C# and the .NET Platform

    http://www.codeproject.com/Purgatory/Serialization_in_NET.asp

    http://www.ondotnet.com

    http://www.codeproject.com/Purgatory/Serialization_in_NET.asphttp://www.codeproject.com/Purgatory/Serialization_in_NET.asphttp://www.ondotnet.com/http://www.ondotnet.com/http://www.codeproject.com/Purgatory/Serialization_in_NET.asphttp://www.codeproject.com/Purgatory/Serialization_in_NET.asp
  • 7/27/2019 Object Serailization in CSharp

    30/30

    Thank You.

    Vipin


Recommended