Techniques To Serialize data in C Sharp

Several Techniques to serialize in .net

Using Formatters
using XmlSerialization
Implementing IXmlSerializable Interface ( will do in Later)

1. Formatters:

We can use BinaryFormatter and SoapFormatter provided in the following libs

using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;

Both work in same pattern to Serialize and Desrialize an Object. The Difference is Object Serialized/ Desierializtion by BinarryFormatter is only useful between .Net Compliant Platforms, while Objects Serialized by SoapFormatter are Accessible by most Platforms and tools.

2.XmlSerialaztion:

Keep in mind Following:

Class to be Serilized must be specified as public.
The member need to be Serialized should also be public
provide a parameteless constructor
We often need to Control Serilization of an object into an XML Format

System.Xml.Serialization provided us with several attributes to do this such as

  • XmlAttribute
  • XmlAttribute
  • XmlIgnore
  • XmlEnum
  • And many more for eg if we want XmlSerializer not to Serialize a method, following Attibute helps

    public bool shipDateSpecified
    {
     get     {        return this.shipDateFieldSpecified;     }
     set     {        this.shipDateFieldSpecified = value;     }
    } 
    

    [System.Xml.Serialization.XmlIgnoreAttribute()]

    We may also Use XmlSchhema Defination Tool provided with framwork to generate class Which Conforns to our requiremnts or “Schema”

    And then simply Serialize those classes.

    Follow these Steps:

    Go To VS Command Prompt from Tools Menu. If you don’t have one Follow this Top Post By Matthew Cochran

    http://www.c-sharpcorner.com/UploadFile/rmcochran/CommandPromptInStudioToolsMenu01152008103357AM/CommandPromptInStudioToolsMenu.aspx

    Then

    Create Schema “xsd” file or get one you need your classes to conforn to.
    open Command Prompt

    Type: xsd.exe filePath  /classes / languages:[ CS|VB ]
    

    For eg

    Xsd c:/FolderA/Schemas/mySchema.xsd  /classes/languages:CS
    

    Open the class generated by the tool and add it in your project
    Declare the Object of that class
    Populate class members as you like them
    Call XmlSerialize .Serialize method

    that’s it job done

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml.Serialization;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Runtime.Serialization.Formatters.Soap; </code>
    
    namespace SerializationSample
    {
    [Serializable]
    class Item : IDeserializationCallback
    {
    string name;
    int unitPrice;
    int quantity;
    [NonSerialized]
    int invoice;
    [OptionalField, NonSerialized]
    int salesTax;
    public Item(string _name, int _unitPrice, int _quantity)
    {
    name = _name;
    unitPrice = _unitPrice;
    quantity = _quantity;
    invoice = quantity * unitPrice;
    salesTax = (invoice / 100) * 15;
    }
    public override string ToString()
    {
    return "Name: " + name + " " + unitPrice + " * " + quantity + " --- " + invoice + "  Sales TAX: " + salesTax;
    }
    #region IDeserializationCallback Members
    public void OnDeserialization(object sender)
    {
    invoice = unitPrice * quantity;
    salesTax = (invoice / 100) * 15;
    }
    #endregion
    }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Runtime.Serialization.Formatters.Soap;
    using System.Xml.Serialization;
    namespace SerializationSample
    {
    class Program
    {
    public static void SerializeUsingBinFormatter(Item item)
    {
    // file path to serialize object
    string filePath = @"E:\PracticeFiles\ch4\BinFile.bin";
    FileStream fs = new FileStream(filePath, FileMode.Create);
    // declare binaryFormatter Object
    BinaryFormatter bFormatter = new BinaryFormatter();
    // Call Serialize, provide stream object and object to serialaize
    bFormatter.Serialize(fs, item);
    fs.Close();
    }
    public static Item DeSerializeUsingBinFormatter()
    {
    // file path to deserialize object
    string filePath = @"E:\PracticeFiles\ch4\BinFile.bin";
    FileStream fs = new FileStream(filePath, FileMode.Open);
    // declare binaryFormatter Object
    BinaryFormatter bFormatter = new BinaryFormatter();
    // provide stream to deserialize and Cast the result to appropriate object
    Item result = (Item)bFormatter.Deserialize(fs);
    fs.Close();
    return result;
    }
    public static void SerializeUsingSoapFormatter(Item item)
    {
    // file path to serialize object
    string filePath = @"E:\PracticeFiles\ch4\BinFile.bin";
    FileStream fs = new FileStream(filePath, FileMode.Create);
    SoapFormatter sFormatter = new SoapFormatter();
    sFormatter.Serialize(fs, item);
    fs.Close();
    }
    public static Item DeSerializeUsingSoapFormatter()
    {
    // file path to deserialize object
    string filePath = @"E:\PracticeFiles\ch4\BinFile.bin";
    FileStream fs = new FileStream(filePath, FileMode.Open);
    SoapFormatter sFormatter = new SoapFormatter();
    // provide stream to deserialize and Cast the result to appropriate object
    Item result = (Item)sFormatter.Deserialize(fs);
    fs.Close();
    return result;
    }
    static void Main(string[] args)
    {
    // Serialize using Binnary Formatter
    SerializeUsingBinFormatter(new Item("ObjectBinarySerializable", 5, 2));
    //Deserialize using Binary Formatter
    Console.WriteLine(DeSerializeUsingBinFormatter().ToString());
    // Serialize using Soap Formatter
    SerializeUsingSoapFormatter(new Item("ObjectSoapSerializable", 1111, 11));
    //Deserialize using Soap Formatter
    Console.WriteLine(DeSerializeUsingSoapFormatter().ToString());
    /*
    * Custom Serialization using  XmlSerialization
    * PurchaseOrderType is the main class, consists
    * of other object as
    * billTo of Type USAddress,
    * shipTo of Type USAddress,
    * string comment,
    * array of Type ItemsItem
    * */
    // See class USAddress
    USAddress address = new USAddress();
    address.city = "PW";
    address.country = "US";
    address.name = "asad";
    address.state = "LA";
    address.street = "123 lousiana close";
    address.zip = 22010;
    string comment = "No comments";
    ItemsItem Oitem = new ItemsItem();
    Oitem.comment = "no comment";
    Oitem.partNum = "678";
    Oitem.productName = "mouse";
    Oitem.quantity = "2";
    Oitem.USPrice = 30;
    ItemsItem[] itemArray = { Oitem };
    // See class PurchaseOrderType
    PurchaseOrderType pot = new PurchaseOrderType();
    pot.shipTo = address;
    pot.billTo = address;
    pot.comment = comment;
    pot.items = itemArray;
    pot.orderDate = DateTime.Now;
    pot.orderDateSpecified = true;
    // Create FileStream
    FileStream fs = new FileStream(@"E:\PracticeFiles\ch4\purchaseorder1.xml", FileMode.Create);
    // Create XmlSerializer Object
    XmlSerializer xs = new XmlSerializer(typeof(PurchaseOrderType));
    xs.Serialize(fs, pot);
    }
    }
    }
    
    Advertisements

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s