Serialize hiearchy classes


   
 
    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


   
 

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

           
         
     


Working with the Serializable Attribute

   
 
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
   
[Serializable]
class Point2D
{
    public int X;
    public int Y;
}
   
class MyMainClass
{
    public static void Main()
    {
        Point2D My2DPoint = new Point2D();
   
        My2DPoint.X = 100;
        My2DPoint.Y = 200;
   
        Stream WriteStream = File.Create("Point2D.bin");
        BinaryFormatter BinaryWrite = new BinaryFormatter();
        BinaryWrite.Serialize(WriteStream, My2DPoint);
        WriteStream.Close();
   
        Point2D ANewPoint = new Point2D();
   
        Console.WriteLine("New Point Before Deserialization: ({0}, {1})", ANewPoint.X, ANewPoint.Y);
        Stream ReadStream = File.OpenRead("Point2D.bin");
        BinaryFormatter BinaryRead = new BinaryFormatter();
        ANewPoint = (Point2D)BinaryRead.Deserialize(ReadStream);
        ReadStream.Close();
        Console.WriteLine("New Point After Deserialization: ({0}, {1})", ANewPoint.X, ANewPoint.Y);
    }
}
           
         
     


Use XML Serialization with Custom Objects


   
 

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

public class SerializeXml {
    private static void Main() {
        CarList catalog = new CarList("New List", DateTime.Now.AddYears(1));
        Car[] cars = new Car[2];
        cars[0] = new Car("Car 1", 12342.99m);
        cars[1] = new Car("Car 2", 21234123.9m);
        catalog.Cars = cars;

        XmlSerializer serializer = new XmlSerializer(typeof(CarList));
        FileStream fs = new FileStream("CarList.xml", FileMode.Create);
        serializer.Serialize(fs, catalog);
        fs.Close();

        catalog = null;

        // Deserialize the order from the file.
        fs = new FileStream("CarList.xml", FileMode.Open);
        catalog = (CarList)serializer.Deserialize(fs);

        // Serialize the order to the Console window.
        serializer.Serialize(Console.Out, catalog);
    }
}


[XmlRoot("carList")]
public class CarList {

    [XmlElement("catalogName")]
    public string ListName;
    
    // Use the date data type (and ignore the time portion in the serialized XML).
    [XmlElement(ElementName="expiryDate", DataType="date")]
    public DateTime ExpiryDate;
    
    [XmlArray("cars")]
    [XmlArrayItem("car")]
    public Car[] Cars;

    public CarList() {
    }

    public CarList(string catalogName, DateTime expiryDate) {
        this.ListName = catalogName;
        this.ExpiryDate = expiryDate;
    }
}

public class Car {

    [XmlElement("carName")]
    public string CarName;
    
    [XmlElement("carPrice")]
    public decimal CarPrice;
    
    [XmlElement("inStock")]
    public bool InStock;
    
    [XmlAttributeAttribute(AttributeName="id", DataType="integer")]
    public string Id;

    public Car() {
    }
    public Car(string carName, decimal carPrice) {
        this.CarName = carName;
        this.CarPrice = carPrice;
    }
}
           
         
     


Three types of Serialization: Binary, Soap, XML

   
  
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Xml.Serialization;
using System.Collections;

[Serializable]
public class Radio {
    public bool hasTweeters;
    public bool hasSubWoofers;
    public double[] stationPresets;

    [NonSerialized]
    public string radioID = "001";
}

[Serializable]
public class Car {
    public Radio theRadio = new Radio();
    public bool isHatchBack;
}

[Serializable, XmlRoot(Namespace = "http://www.yoursite.com")]
public class JamesBondCar : Car {
    public JamesBondCar(bool SkyWorthy, bool SeaWorthy) {
        canFly = SkyWorthy;
        canSubmerge = SeaWorthy;
    }
    public JamesBondCar() { }
    [XmlAttribute]
    public bool canFly;
    [XmlAttribute]
    public bool canSubmerge;
}

class Program {
    static void Main(string[] args) {
        JamesBondCar jbc = new JamesBondCar();
        jbc.canFly = true;
        jbc.canSubmerge = false;
        jbc.theRadio.stationPresets = new double[] { 89.3, 105.1, 97.1 };
        jbc.theRadio.hasTweeters = true;

        BinaryFormatter binFormat = new BinaryFormatter();
        Stream fStream = new FileStream("CarData.dat",FileMode.Create, FileAccess.Write, FileShare.None);
        binFormat.Serialize(fStream, jbc);
        fStream.Close();
        fStream = File.OpenRead("CarData.dat");
        JamesBondCar carFromDisk =(JamesBondCar)binFormat.Deserialize(fStream);
        Console.WriteLine("Can this car fly? : {0}", carFromDisk.canFly);
        fStream.Close();
        SoapFormatter soapForamt = new SoapFormatter();
        fStream = new FileStream("CarData.soap",FileMode.Create, FileAccess.Write, FileShare.None);
        soapForamt.Serialize(fStream, jbc);
        fStream.Close();
        XmlSerializer xmlForamt = new XmlSerializer(typeof(JamesBondCar),new Type[] { typeof(Radio), typeof(Car) });
        fStream = new FileStream("CarData.xml",FileMode.Create, FileAccess.Write, FileShare.None);
        xmlForamt.Serialize(fStream, jbc);
        fStream.Close();

        ArrayList myCars = new ArrayList();
        myCars.Add(new JamesBondCar(true, true));
        myCars.Add(new JamesBondCar(true, false));
        myCars.Add(new JamesBondCar(false, true));
        myCars.Add(new JamesBondCar(false, false));

        fStream = new FileStream("CarCollection.xml",FileMode.Create, FileAccess.Write, FileShare.None);

        xmlForamt = new XmlSerializer(typeof(ArrayList),new Type[] { typeof(JamesBondCar), typeof(Car), typeof(Radio) });
        xmlForamt.Serialize(fStream, myCars);
        fStream.Close();
    }
}

   
     


Serialize and DeSerialize

   
  

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

class Program {
    static void Main(string[] args) {
        Person me = new Person();
        me.Age = 38;
        me.WeightInPounds = 200;

        Console.WriteLine(me.Age);
        Console.WriteLine(me.WeightInPounds);

        Stream s = File.Open("Me.dat", FileMode.Create);

        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(s, me);
        s.Close();

        s = File.Open("Me.dat", FileMode.Open);
        bf = new BinaryFormatter();
        object o = bf.Deserialize(s);
        Person p = o as Person;
        if (p != null)
            Console.WriteLine("DeSerialized Person aged: {0} weight: {1}", p.Age, p.WeightInPounds);
        s.Close();
    }
}

[Serializable]
public class Person {
    public Person() {
    }

    public int Age;
    public int WeightInPounds;
}

   
     


Deserialize Object

   
  

using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
[Serializable]
public class BookRecord {
    public String title;
    public int asin;

    public BookRecord(String title, int asin) {
        this.title = title;
        this.asin = asin;
    }
}
public class DeserializeObject {
    public static void Main() {
        FileStream streamIn = new FileStream(@"book.obj", FileMode.Open);
        BinaryFormatter bf = new BinaryFormatter();
        BookRecord book = (BookRecord)bf.Deserialize(streamIn);
        streamIn.Close();
        Console.Write(book.title + " " + book.asin);
    }
}