Page d'Accueil

SOAP Serialization

 
 

Introduction

The .NET Framework supports a technique of serialization referred to as SOAP (which stands for Simple Object Access Protocol). This technique a little more related to XML but, although we haven't studied XML, you don't need to know anything about it to use SOAP serialization.

Practical LearningPractical Learning: Introducing SOAP Serialization

  1. Start a new Console Application named PropertyRental1
  2. To create a new class, on the main menu, click Project -> Add Class
  3. Set the Name to Property and press Enter
  4. Change the file as follows:
     
    using System;
    
    namespace PropertyRental1
    {
        public enum TypeOfProperty
        {
            Appartment,
            SingleFamily,
            Townhouse,
            Unknown
        }
    
        public enum Condition
        {
            Excellent,
            Good,
            NeedsRepair,
            Unknown
        }
    
        [Serializable]
        public class Property
        {
            private long propCode;
            private TypeOfProperty tp;
            private Condition cond;
            private short beds;
            private float baths;
            private int levels;
            private decimal val;
    
            public long PropertyCode
            {
                get { return propCode; }
                set { propCode = value; }
            }
    
            public TypeOfProperty PropertyType
            {
                get { return tp; }
                set { tp = value; }
            }
    
            public Condition PropertyCondition
            {
                get { return cond; }
                set { cond = value; }
            }
    
            public short Bedrooms
            {
                get { return beds; }
                set { beds = value; }
            }
    
            public float Bathrooms
            {
                get { return (baths <= 0) ? 0.00f : baths; }
                set { baths = value; }
            }
    
            public int Stories
            {
                get { return levels; }
                set { levels = value; }
            }
    
            public decimal MonthlyRent
            {
                get { return (val <= 0) ? 0.00M : val; }
                set { val = value; }
            }
    
            public Property()
            {
                Random rnd = new Random();
                propCode = rnd.Next(100000, 999999);
                tp = TypeOfProperty.Unknown;
                cond = Condition.Unknown;
                beds = 0;
                baths = 0.0f;
                levels = 0;
                val = 0.00M;
            }
        }
    }
  5. To create a new class, on the main menu, click Project -> Add Class
  6. Set the Name to PropertyListing and press Enter
  7. Change the file as follows:
     
    using System;
    
    namespace PropertyRental1
    {
        [Serializable]
        public class PropertyListing
        {
            private Property[] prop = new Property[100];
    
            public Property this[int i]
            {
                get { return prop[i]; }
                set { prop[i] = value; }
            }
        }
    }
  8. Save all

Serializing With SOAP

To serialize an object using SOAP, you follow the same steps we reviewed for the binary serialization with one addition that you must add a certain reference.

When creating the class whose objects would be serialized, mark it with the [Serializable] attribute. Here is an example:

[Serializable]
public class Car
{
    public string Make;
    public string Model;
    public uint   Year;
    public byte Color;
}

To support SOAP serialization, the .NET Framework provides the SoapFormatter class. This class is defined in the System.Runtime.Serialization.Formatters.Soap namespace that is part of the System.Runtime.Serialization.Formatters.Soap.dll assembly. In order to use The SoapFormatter class, you must reference this assembly. Then, you can create an object and initialize it as you see fit. Before saving it, as always, create a Stream-based object that would indicate the name (and location) of the file and the type of action to perform. Then, declare a SoapFormatter variable using its default constructor. To actually save the object, call the Serialize() method of this class. This method uses the same syntax as that of the BinaryFormatter class: it takes two arguments. The first is a Stream-based object. The second is the object that needs to be serialized.

Here is an example:

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

[Serializable]
public class Car
{
    public string  Make;
    public string  Model;
    public uint    Year;
    public byte    Color;
}

public static class Program
{
    public static int Main(string[] args)
    {
        Car vehicle = new Car();

        vehicle.Make  = "Volvo";
        vehicle.Model = "S40";
        vehicle.Year  = 2006;
        vehicle.Color = 3;

        FileStream stmCar =
            new FileStream("Car4.car",
                           FileMode.Create);
        SoapFormatter sopCar = new SoapFormatter();

        sopCar.Serialize(stmCar, vehicle);
        return 0;
    }
}
 

 

 

 

 

 

Practical Learning: Serializing With SOAP

  1. To add SOAP support to your project, on the main menu, click Project -> Add Reference...
  2. In the Add Reference dialog box and in the .NET tab, scroll down and select System.Runtime.Serialization.Formatters.Soap:

    Adding a reference to the System.Runtime.Serialization.Formatters.Soap.dll assembly

  3. Click OK
  4. Access the Program.cs file and change it as follows:
     
    using System;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Soap;
    
    namespace PropertyRental1
    {
        class Program
        {
            static PropertyListing CreateListing()
            {
                Random rnd = new Random();
                Property prop = new Property();
                PropertyListing listing = new PropertyListing();
    
                prop = new Property();
    
    	    // Create a few properties ready to be rented
                prop.PropertyCode = rnd.Next(100000, 999999);
                prop.PropertyType = TypeOfProperty.SingleFamily;
                prop.PropertyCondition = Condition.Excellent;
                prop.Bedrooms = 5;
                prop.Bathrooms = 3.5f;
                prop.Stories = 3;
                prop.MonthlyRent = 2650;
                listing[0] = prop;
    
                prop = new Property();
                prop.PropertyCode = rnd.Next(100000, 999999);
                prop.PropertyType = TypeOfProperty.Townhouse;
                prop.PropertyCondition = Condition.Excellent;
                prop.Bedrooms = 3;
                prop.Bathrooms = 2.5f;
                prop.Stories = 3;
                prop.MonthlyRent = 1750;
                listing[1] = prop;
    
                prop = new Property();
                prop.PropertyCode = rnd.Next(100000, 999999);
                prop.PropertyType = TypeOfProperty.SingleFamily;
                prop.PropertyCondition = Condition.Good;
                prop.Bedrooms = 4;
                prop.Bathrooms = 2.5f;
                prop.Stories = 2;
                prop.MonthlyRent = 2450;
                listing[2] = prop;
    
                prop = new Property();
                prop.PropertyCode = rnd.Next(100000, 999999);
                prop.PropertyType = TypeOfProperty.Appartment;
                prop.PropertyCondition = Condition.Excellent;
                prop.Bedrooms = 1;
                prop.Bathrooms = 1.0f;
                prop.Stories = 1;
                prop.MonthlyRent = 880;
                listing[3] = prop;
    
                prop = new Property();
                prop.PropertyCode = rnd.Next(100000, 999999);
                prop.PropertyType = TypeOfProperty.Townhouse;
                prop.PropertyCondition = Condition.Excellent;
                prop.Bedrooms = 3;
                prop.Bathrooms = 2.5f;
                prop.Stories = 2;
                prop.MonthlyRent = 1880;
                listing[4] = prop;
    
                prop = new Property();
                prop.PropertyCode = rnd.Next(100000, 999999);
                prop.PropertyType = TypeOfProperty.Appartment;
                prop.PropertyCondition = Condition.Good;
                prop.Bedrooms = 2;
                prop.Bathrooms = 1.0f;
                prop.Stories = 1;
                prop.MonthlyRent = 1050;
                listing[5] = prop;
                
    	    // Since we don't yet have a complete list of properties
    	    // Create some empty ones
                for (int i = 5; i < 100; i++)
                {
                    prop = new Property();
                   
                    listing[i] = prop;
                }
                return listing;
            }
    
            static int Main()
            {
                PropertyListing props = CreateListing();
                Property prop = new Property();
    
                FileStream prpStream =
                    new FileStream("properties.rnt",
                                   FileMode.Create);
                SoapFormatter prpSoap = new SoapFormatter();
    
                prpSoap.Serialize(prpStream, props);
    
                for (int i = 0; i < 16; i++)
                {
                    prop = props[i];
                    Console.WriteLine("{0}.----------------------------------",
    			 i + 1);
                    Console.WriteLine("Property #:   {0}", prop.PropertyCode);
                    Console.WriteLine("Type:         {0}", prop.PropertyType);
                    Console.WriteLine("Condition:    {0}",
    			prop.PropertyCondition);
                    Console.WriteLine("Bedrooms:     {0}", prop.Bedrooms);
                    Console.WriteLine("Bathrooms:    {0}", prop.Bathrooms);
                    Console.WriteLine("Stories:      {0}", prop.Stories);
                    Console.WriteLine("Market Value: {0}\n", prop.MonthlyRent);
                }
                Console.WriteLine("======================================");
                
                return 0;
            }
        }
    }
  5. Press Ctrl + F5 to execute the application

De-Serialization With SOAP

De-serialization in soap is performed exactly as done for the binary de-serialization. To support it, the SoapFormatter class is equipped with the Deserialize() method. This method uses the same syntax as its equivalent of the BinaryFormatter class. The approach to use it is also the same.

Here is an example:

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

[Serializable]
public class Car
{
    public string  Make;
    public string  Model;
    public uint    Year;
    public byte    Color;
}

public static class Program
{
    public static int Main(string[] args)
    {
        FileStream stmCar =
            new FileStream("Car4.car",
                           FileMode.Open);
        SoapFormatter sopCar = new SoapFormatter();
        Car vehicle = (Car)sopCar.Deserialize(stmCar);
        
        Console.WriteLine("Car Information");
        Console.WriteLine("Make: {0}",       vehicle.Make );
        Console.WriteLine("Model: {0}", vehicle.Model);
        Console.WriteLine("Year: {0}", vehicle.Year);
        Console.Write("Color: ");
        switch (vehicle.Color)
        {
            case 1:
                Console.WriteLine("Black");
                break;
            case 2:
                Console.WriteLine("Gray");
                break;
            case 3:
                Console.WriteLine("White");
                break;
            case 4:
                Console.WriteLine("Red");
                break;
            case 5:
                Console.WriteLine("Blue");
                break;
        }
        return 0;
    }
}
 

Practical Learning: Deserializing With SOAP

  1. To deserialize, change the contents of the Program.cs file as follows:
     
    using System;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Soap;
    
    namespace PropertyRental1
    {
        class Program
        {
            static int Main()
            {
                Property prop = new Property();
    
                // Open the list/collection of properties
                FileStream prpStream =
                    new FileStream("properties.rnt",
                                   FileMode.Open);
                SoapFormatter prpSoap = new SoapFormatter();
                PropertyListing props = 
    		(PropertyListing)prpSoap.Deserialize(prpStream);
                prpStream.Close();
    
                for (int i = 0; i < 16; i++)
                {
                    prop = props[i];
                    Console.WriteLine("{0}.----------------------------------",
    			 i + 1);
                    Console.WriteLine("Property #:   {0}", prop.PropertyCode);
                    Console.WriteLine("Type:         {0}", prop.PropertyType);
                    Console.WriteLine("Condition:    {0}",
    			 prop.PropertyCondition);
                    Console.WriteLine("Bedrooms:     {0}", prop.Bedrooms);
                    Console.WriteLine("Bathrooms:    {0}", prop.Bathrooms);
                    Console.WriteLine("Stories:      {0}", prop.Stories);
                    Console.WriteLine("Market Value: {0}\n", prop.MonthlyRent);
                }
                Console.WriteLine("======================================");
                
                return 0;
            }
        }
    }
  2. Press Ctrl + F5 to execute the application
  3. After viewing the result, close the DOS window
  4. To apply an example of updating the file, change the contents of the Program.cs file as follows:
     
    using System;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Soap;
    
    namespace PropertyRental1
    {
        class Program
        {
            static int Main()
            {
                Property prop = new Property();
    
                // Open the list/collection of properties
                FileStream prpStream =
                    new FileStream("properties.rnt",
                                   FileMode.Open);
                SoapFormatter prpSoap = new SoapFormatter();
                // Get the list of properties and store it in an array
                PropertyListing props = 
    		(PropertyListing)prpSoap.Deserialize(prpStream);
                // Close the stream while we are working on something else
                prpStream.Close();
    
                // To add a few properties, we will actually replace
                // some "empty" properties whose placeholders we defined earlier
                Random rnd = new Random();
                prop = new Property();
                prop.PropertyCode = rnd.Next(100000, 999999);
                prop.PropertyType = TypeOfProperty.Appartment;
                prop.PropertyCondition = Condition.Excellent;
                prop.Bedrooms = 2;
                prop.Bathrooms = 2.0f;
                prop.Stories = 1;
                prop.MonthlyRent = 1240;
                props[7] = prop;
    
                prop = new Property();
                prop.PropertyCode = rnd.Next(100000, 999999);
                prop.PropertyType = TypeOfProperty.SingleFamily;
                prop.PropertyCondition = Condition.Excellent;
                prop.Bedrooms = 3;
                prop.Bathrooms = 2.5f;
                prop.Stories = 3;
                prop.MonthlyRent = 1750;
                props[8] = prop;
    
                prop = new Property();
                prop.PropertyCode = rnd.Next(100000, 999999);
                prop.PropertyType = TypeOfProperty.SingleFamily;
                prop.PropertyCondition = Condition.Good;
                prop.Bedrooms = 5;
                prop.Bathrooms = 3.5f;
                prop.Stories = 3;
                prop.MonthlyRent = 3475;
                props[14] = prop;
    
                prop = new Property();
                prop.PropertyType = TypeOfProperty.Appartment;
                prop.PropertyCondition = Condition.Excellent;
                prop.Bedrooms = 2;
                prop.Bathrooms = 1.0f;
                prop.Stories = 1;
                prop.MonthlyRent = 1275;
                props[28] = prop;
    
                // Reopen the stream
                prpStream = new FileStream("properties.rnt",
                                           FileMode.Create);
                prpSoap = new SoapFormatter();
    
                // Open the file and save it
                prpSoap.Serialize(prpStream, props);
                prpStream.Close();
    
                // That's it
    
                for (int i = 0; i < 16; i++)
                {
                    prop = props[i];
                    Console.WriteLine("{0}.----------------------------------",
    			 i + 1);
                    Console.WriteLine("Property #:   {0}", prop.PropertyCode);
                    Console.WriteLine("Type:         {0}", prop.PropertyType);
                    Console.WriteLine("Condition:    {0}",
    			 prop.PropertyCondition);
                    Console.WriteLine("Bedrooms:     {0}", prop.Bedrooms);
                    Console.WriteLine("Bathrooms:    {0}", prop.Bathrooms);
                    Console.WriteLine("Stories:      {0}", prop.Stories);
                    Console.WriteLine("Market Value: {0}\n", prop.MonthlyRent);
                }
                Console.WriteLine("======================================");
    
                return 0;
            }
        }
    }
  5. Press Ctrl + F5 to execute the application
 

Home Copyright 2006-2007 Yevol