Deserialize

image_pdfimage_print
   
 

using System;
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
class Employee : ISerializable {
    private string name;
    private int age;
    private string address;

    public Employee(string name, int age, string address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    private Employee(SerializationInfo info, StreamingContext context) {
        name = info.GetString("Name");
        age = info.GetInt32("Age");
        try {
            address = info.GetString("Address");
        } catch (SerializationException) {
            address = null;
        }
    }

    public string Name {
        get { return name; }
        set { name = value; }
    }

    public int Age {
        get { return age; }
        set { age = value; }
    }

    public string Address {
        get { return address; }
        set { address = value; }
    }

    public void GetObjectData(SerializationInfo inf, StreamingContext con) {
        inf.AddValue("Name", name);
        inf.AddValue("Age", age);

        if ((con.State & StreamingContextStates.File) == 0) {
            inf.AddValue("Address", address);
        }
    }

    public override string ToString() {
        StringBuilder str = new StringBuilder();

        str.AppendFormat("Name: {0}
", Name);
        str.AppendFormat("Age: {0}
", Age);
        str.AppendFormat("Address: {0}
", Address);

        return str.ToString();
    }
}

public class MainClass {
    public static void Main(string[] args) {
        Employee roger = new Employee("R", 56, "L");
        Console.WriteLine(roger);
        Stream str = File.Create("r.bin");
        BinaryFormatter bf = new BinaryFormatter();
        bf.Context = new StreamingContext(StreamingContextStates.CrossAppDomain);
        bf.Serialize(str, roger);
        str.Close();

        str = File.OpenRead("r.bin");
        bf = new BinaryFormatter();
        roger = (Employee)bf.Deserialize(str);
        str.Close();
        Console.WriteLine(roger);
        str = File.Create("r.bin");
        bf = new BinaryFormatter();
        bf.Context = new StreamingContext(StreamingContextStates.File);
        bf.Serialize(str, roger);
        str.Close();

        str = File.OpenRead("r.bin");
        bf = new BinaryFormatter();
        roger = (Employee)bf.Deserialize(str);
        str.Close();
        Console.WriteLine(roger);

    }
}

           
         
     


illustrates binary serialization

image_pdfimage_print


   
 
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/


 /*
  Example15_19.cs illustrates binary serialization
*/

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

// the Customer class gives us something to serialize
[Serializable]
class Customer
{
  // some private data members
  private int CustomerNumber;
  private string CustomerName;
  private string CustomerCountry;

  // the WriteCustomer method formats info to the screen
  public void WriteCustomer()
  {
    Console.WriteLine("Customer Number: " + this.CustomerNumber);
    Console.WriteLine("Customer Name: " + this.CustomerName);
    Console.WriteLine("Customer Country: " + this.CustomerCountry);
  }

  // the constructor accepts all the info to create a customer
  public Customer(
    int newCustomerNumber, 
    string newCustomerName, 
    string newCustomerCountry)
  {
    this.CustomerNumber = newCustomerNumber;
    this.CustomerName = newCustomerName;
    this.CustomerCountry = newCustomerCountry;
  }
}

public class Example15_19 
{

  public static void Main() 
  {

    // create a new customer and dump to screen
    Customer MyCustomer = new Customer(1, "X Corporation", "France");
    MyCustomer.WriteCustomer();

    // Create a FileStream to hold the serialized customer
    FileStream serializeStream = new FileStream("c:MyCustomer.dat", 
     FileMode.Create);

    // use the CLR's binary formatting support
    BinaryFormatter bf = new BinaryFormatter();

    // serialize the object
    bf.Serialize(serializeStream, MyCustomer);
    serializeStream.Flush();
    serializeStream.Close();

    // retrieve the serialized version to a second object and dump that
    FileStream retrieveStream = new FileStream("c:MyCustomer.dat",
     FileMode.Open);
    Customer NewCustomer = (Customer) bf.Deserialize(retrieveStream);
    NewCustomer.WriteCustomer();
  }

}


           
         
     


Set XML tag name for Serialization

image_pdfimage_print
   
 
using System;
using System.IO;
using System.Xml.Serialization;

public class Serializer {

  public static void Main(string [] args) {
    Personnel personnel = CreatePersonnel();
    XmlSerializer serializer = new XmlSerializer(typeof(Personnel));
    using (FileStream stream = File.OpenWrite("Employees.xml")) {
      serializer.Serialize(stream, personnel);
    }
  }
  
  private static Personnel CreatePersonnel() {
    Personnel personnel = new Personnel();
    personnel.Employees = new Employee [] {new Employee()};
    personnel.Employees[0].FirstName = "Joe";
    personnel.Employees[0].MiddleInitial = "M";
    personnel.Employees[0].LastName = "Lee";
    
    personnel.Employees[0].Addresses = new Address [] {new Address()};
    personnel.Employees[0].Addresses[0].AddressType = AddressType.Home;
    personnel.Employees[0].Addresses[0].Street = new string [] {"999 Colluden"};
    personnel.Employees[0].Addresses[0].City = "Vancouver";
    personnel.Employees[0].Addresses[0].State = State.BC;
    personnel.Employees[0].Addresses[0].Zip = "V5V 4X7";
    
    personnel.Employees[0].HireDate = new DateTime(2001,1,1);
    
    return personnel;
  }
}


[Serializable]
public enum AddressType {
  Home,
  Office
}

[Serializable]
public enum State {
  [XmlEnum(Name="British C")]BC,
  [XmlEnum(Name="Sask")]SK
}

[Serializable]
public class Address {
  [XmlAttribute(AttributeName="type")]  public AddressType AddressType;
  [XmlElement(ElementName="street")]    public string[] Street;
  [XmlElement(ElementName="city")]      public string City;
  [XmlElement(ElementName="state")]     public State State;
  [XmlElement(ElementName="zip")]       public string Zip;
}

[Serializable]
public class TelephoneNumber {
  [XmlAttribute(AttributeName="type")] public AddressType AddressType;
  [XmlElement(ElementName="areacode")] public string AreaCode;
  [XmlElement(ElementName="exchange")] public string Exchange;
  [XmlElement(ElementName="number")]   public string Number;
}

[Serializable]
public class Employee {
  [XmlAttribute(AttributeName="firstname")]      public string FirstName;
  [XmlAttribute(AttributeName="middleinitial")]  public string MiddleInitial;
  [XmlAttribute(AttributeName="lastname")]       public string LastName;
  
  [XmlArray(ElementName="addresses")]
  [XmlArrayItem(ElementName="address")]      public Address [] Addresses;
  [XmlArray(ElementName="telephones")] 
  [XmlArrayItem(ElementName="telephone")]    public TelephoneNumber [] TelephoneNumbers;
  
  [XmlAttribute(AttributeName="hiredate")]   public DateTime HireDate;
}

[Serializable]
[XmlRoot(ElementName="personnel")]
public class Personnel {
  [XmlElement(ElementName="employee")]
  public Employee [] Employees;
}


           
         
     


Serial Employee class

image_pdfimage_print
   
 

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

class SoapTest
{
   public static void Main()
   {
      SerialEmployee emp1 = new SerialEmployee();
      SerialEmployee emp2 = new SerialEmployee();

      emp1.EmployeeID = 1;
      emp1.LastName = "B";
      emp1.FirstName = "K";
      emp1.YearsService = 12;
      emp1.Salary = 35000.50;

      emp2.EmployeeID = 2;
      emp2.LastName = "B";
      emp2.FirstName = "J";
      emp2.YearsService = 9;
      emp2.Salary = 23700.30;

      Stream str = new FileStream("soaptest.xml", FileMode.Create, FileAccess.ReadWrite);
      IFormatter formatter = new SoapFormatter();

      formatter.Serialize(str, emp1);
      formatter.Serialize(str, emp2);
      str.Close();
   }
}


[Serializable]
public class SerialEmployee
{
   public int EmployeeID;
   public string LastName;
   public string FirstName;
   public int YearsService;
   public double Salary;

   public SerialEmployee()
   {
      EmployeeID = 0;
      LastName = null;
      FirstName = null;
      YearsService = 0;
      Salary = 0.0;
   }
}

           
         
     


C# Serialization

image_pdfimage_print


   
 
/*
A Programmer's Introduction to C# (Second Edition)
by Eric Gunnerson

Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/
// 32 - .NET Frameworks OverviewSerialization
// copyright 2000 Eric Gunnerson
// file=serial.cs
// compile with: csc serial.cs
using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;

public class FrameworksOverviewSerialization
{
    public static void Main()
    {
        MyRow row = new MyRow();
        row.Add(new MyElement("Gumby"));
        row.Add(new MyElement("Pokey"));
        
        Console.WriteLine("Initial value");
        Console.WriteLine("{0}", row);
        
        // write to binary, read it back
        Stream streamWrite = File.Create("MyRow.bin");
        BinaryFormatter binaryWrite = new BinaryFormatter();
        binaryWrite.Serialize(streamWrite, row);
        streamWrite.Close();
        
        Stream streamRead = File.OpenRead("MyRow.bin");
        BinaryFormatter binaryRead = new BinaryFormatter();
        MyRow rowBinary = (MyRow) binaryRead.Deserialize(streamRead);
        streamRead.Close();
        
        Console.WriteLine("Values after binary serialization");
        Console.WriteLine("{0}", rowBinary);
        
        // write to SOAP (XML), read it back
        streamWrite = File.Create("MyRow.xml");
        SoapFormatter soapWrite = new SoapFormatter();
        soapWrite.Serialize(streamWrite, row);
        streamWrite.Close();
        
        streamRead = File.OpenRead("MyRow.xml");
        SoapFormatter soapRead = new SoapFormatter();
        MyRow rowSoap = (MyRow) soapRead.Deserialize(streamRead);
        streamRead.Close();
        
        Console.WriteLine("Values after SOAP serialization");
        Console.WriteLine("{0}", rowSoap);
    }
}

[Serializable]
public class MyElement
{
    public MyElement(string name)
    {
        this.name = name;
        this.cacheValue = 15;
    }
    public override string ToString()
    {
        return(String.Format("{0}: {1}", name, cacheValue));
    }
    string name;
    // this field isn't persisted.
    [NonSerialized]
    int cacheValue;
}
[Serializable]
public class MyRow
{
    public void Add(MyElement my)
    {
        row.Add(my);
    }
    
    public override string ToString()
    {
        string temp = null;
        foreach (MyElement my in row)
        temp += my.ToString() + "
"; 
        return(temp);
    }
    
    ArrayList row = new ArrayList();    
}



           
         
     


Serialize hiearchy classes

image_pdfimage_print


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

    public class RoomApp
    {
    public static void Main()
    {
      // Make a room and listen to the tunes.
      Console.WriteLine("Made a My Room...");
      MyRoom myAuto = new MyRoom("My", 50, false, true);
      myAuto.TurnOnRadio(true);
      myAuto.GoUnderWater();

      // Now save this room to a binary stream.
      FileStream myStream = File.Create("RoomData.dat");
      BinaryFormatter myBinaryFormat = new BinaryFormatter();
      myBinaryFormat.Serialize(myStream, myAuto);
      myStream.Close();
      Console.WriteLine("Saved room to roomdata.dat.");

      // Read in the Room from the binary stream.
      Console.WriteLine("Reading room from binary file.");
      myStream = File.OpenRead("RoomData.dat");
      MyRoom roomFromDisk = (MyRoom)myBinaryFormat.Deserialize(myStream);
      Console.WriteLine(roomFromDisk.PetName + " is alive!");
      roomFromDisk.TurnOnRadio(true);
      myStream.Close();
      
    }
    }  
  
  
  [Serializable]
    public class Radio
    {
    [NonSerialized]
    private int objectIDNumber = 9;

        public Radio(){}
    public void On(bool state)
    {
      if(state == true)
        Console.WriteLine("Music is on...");
      else
        Console.WriteLine("No tunes...");        
    }
    }


  [Serializable]
    public class Room
    {
    protected string petName;
    protected int maxInternetSpeed;
    protected Radio theRadio = new Radio();

        public Room(string petName, int maxInternetSpeed)
        {
      this.petName = petName;
      this.maxInternetSpeed = maxInternetSpeed;
        }
    public Room() {}

    public String PetName
    {
      get { return petName; }
      set { petName = value; }
    }
    public int MaxInternetSpeed
    {
      get { return maxInternetSpeed; }
      set { maxInternetSpeed = value; }
    }

    public void TurnOnRadio(bool state)
    {
      theRadio.On(state);
    }
    }


  [Serializable]
    public class MyRoom : Room
    {
    protected bool isFlightWorthy;
    protected bool isSeaWorthy;

    public MyRoom(string petName, int maxInternetSpeed, 
              bool canFly, bool canSubmerge)
      : base(petName, maxInternetSpeed)
        {
      this.isFlightWorthy = canFly;
      this.isSeaWorthy = canSubmerge;
    }
    public MyRoom(){}

    public void Fly()
    {
      if(isFlightWorthy)
        Console.WriteLine("Taking off!");
      else
        Console.WriteLine("Falling off cliff!");
    }

    public void GoUnderWater()
    {
      if(isSeaWorthy)
        Console.WriteLine("Diving....");
      else
        Console.WriteLine("Drowning!!!");      
    }
    }
    


           
         
     


NonSerialized attributes

image_pdfimage_print


   
 

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

    public class RoomApp
    {
    public static void Main()
    {
      // Make a room and listen to the tunes.
      Console.WriteLine("Made a My Room...");
      MyRoom myAuto = new MyRoom("My", 50, false, true);
      myAuto.TurnOnRadio(true);
      myAuto.GoUnderWater();

      // Now save this room to a binary stream.
      FileStream myStream = File.Create("RoomData.dat");
      BinaryFormatter myBinaryFormat = new BinaryFormatter();
      myBinaryFormat.Serialize(myStream, myAuto);
      myStream.Close();
      Console.WriteLine("Saved room to roomdata.dat.");

      // Read in the Room from the binary stream.
      Console.WriteLine("Reading room from binary file.");
      myStream = File.OpenRead("RoomData.dat");
      MyRoom roomFromDisk = (MyRoom)myBinaryFormat.Deserialize(myStream);
      Console.WriteLine(roomFromDisk.PetName + " is alive!");
      roomFromDisk.TurnOnRadio(true);
      myStream.Close();
      
    }
    }  
  
  
  [Serializable]
    public class Radio
    {
    [NonSerialized]
    private int objectIDNumber = 9;

        public Radio(){}
    public void On(bool state)
    {
      if(state == true)
        Console.WriteLine("Music is on...");
      else
        Console.WriteLine("No tunes...");        
    }
    }


  [Serializable]
    public class Room
    {
    protected string petName;
    protected int maxInternetSpeed;
    protected Radio theRadio = new Radio();

        public Room(string petName, int maxInternetSpeed)
        {
      this.petName = petName;
      this.maxInternetSpeed = maxInternetSpeed;
        }
    public Room() {}

    public String PetName
    {
      get { return petName; }
      set { petName = value; }
    }
    public int MaxInternetSpeed
    {
      get { return maxInternetSpeed; }
      set { maxInternetSpeed = value; }
    }

    public void TurnOnRadio(bool state)
    {
      theRadio.On(state);
    }
    }


  [Serializable]
    public class MyRoom : Room
    {
    protected bool isFlightWorthy;
    protected bool isSeaWorthy;

    public MyRoom(string petName, int maxInternetSpeed, 
              bool canFly, bool canSubmerge)
      : base(petName, maxInternetSpeed)
        {
      this.isFlightWorthy = canFly;
      this.isSeaWorthy = canSubmerge;
    }
    public MyRoom(){}

    public void Fly()
    {
      if(isFlightWorthy)
        Console.WriteLine("Taking off!");
      else
        Console.WriteLine("Falling off cliff!");
    }

    public void GoUnderWater()
    {
      if(isSeaWorthy)
        Console.WriteLine("Diving....");
      else
        Console.WriteLine("Drowning!!!");      
    }
    }