SOAP Serialization with C# and .NET

Posted on Updated on


In the previous post, we discussed binary serialization with C# and .NET. In this short article we are going to dive into some specific examples of use of the SoapFormatter class to SOAP serialize objects to XML and deserialize from XML back into objects.

We will discuss SOAP a little later in this article 🙂

SOAP Serialization with the SoapFormatter class

To get started, let’s create a simple class, add some attributes to help us control how properties are serialized, then we’ll serialize and deserialize the object.

To get started, let’s create a C# Console Application that we will call SoapSerializationSample.

Create the Soap Serialization Sample Console project
Create the Soap Serialization Sample Console project

Next, we will add a class to the project. We will call this class Sample.

Let’s now add two properties – Name and Value as shown below then decorate the class with the Serializable attribute.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SoapSerializationSample
{
    [Serializable]
    public class Sample
    {
        public string Name
        {
            get;
            set;
        }

        public Int32 Value
        {
            get;
            set;
        }
    }
}

As you can see, this class is very simple and is a great starting point for examining SOAP serialization.

The Serializable attribute signals the .NET runtime that instances of this class can be serialized. To use serialization, this attribute must be in place at the class level.

Before we write the serialization code, let’s first add the references shown in the illustration below:

System.Serialization.Runtime References
System.Serialization.Runtime References

Next, let’s add the following using statements to our Program class:

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

In our Program.cs class’s Main() method, we are going to write some simple code that uses the SoapFormatter to serialize an instance of our Sample object into a Soap XML stream.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

namespace SoapSerializationSample
{
    class Program
    {
        static void Main(string[] args)
        {
            //create an instance of our Sample class
            //which we will serialize below
            Sample sample = new Sample();
            sample.Name = "John Nelson";
            sample.Value = 44;

            //create a FileStream to accept the output
            FileStream fileStream = new FileStream(@"c:\temp\MySoapFile.dat", FileMode.Create);

            //create a SoapFormatter to serialize the object
            SoapFormatter formatter = new SoapFormatter();

            //serialize the object to the .dat file
            formatter.Serialize(fileStream, sample);
        }
    }
}

When we press F5 and run the application, the SoapFormatter serializes the Sample object to our MySoapFile.dat file. If we open this file in Visual Studio, we see something that looks like this:

SoapFormatter XML Output
SoapFormatter XML Output

So, some of you are probably looking at this output and screaming “this is NOT well-formed XML!” and you are right! This file does not contain an xml declaration does not contain opening and closing xml tags. Though an in-depth discussion of SOAP is well beyond the purpose and scope of this article, it will be beneficial to briefly discuss the parts of a SOAP message.

What is SOAP?

Soap is an acronym for Simple Object Access Protocol. It is basically an XML-based protocol for transmitting data between computers and is designed for for data communication via the internet and provides the transport mechanism for web services. SOAP is language and platform independent.

SOAP Message Structure

SOAP messages are encoded as XML documents. These documents begin with a mandatory <Envelope> element and may or may not contain a <Header> element. The <Body> element is mandatory for all SOAP messages, so we would expect to always see that. A <Fault> element may or may not be contained within the <Body> element and is used to provide information about exceptions or errors that may have occurred while the message was processed.

<Envelope> Element

The <Envelope> element is the start and end of the message. The entire SOAP message is contained within the <Envelope> element. Every <Envelope> element must contain exactly one <Body> element – no exceptions! The <Envelope> will change if the version of the message changes.

<Header> Element

<Header> elements are optional within the <Envelope> element and there can be multiple <Header> elements in a SOAP message.

<Body> Element

The <Body> element contains the actual data being transmitted in the SOAP message. You can think of it as the “guts” of the message or the payload of the message.

<Fault> Element

If you have ever worked with WCF, you are familiar with the FaultExceptions. When an error occurs during processing by a web service, information pertaining to that error can be encapsulated within a <Fault> block. If a <Fault> element is included in a SOAP message, there can only be one.

Learning More About SOAP

If you are interested in learning more about the SOAP standard, try this link.

Deserializing with the SoapFormatter

Deserializing with the SoapFormatter is as simple as serializing. See the code below:

//create a FileStream to open the .dat file
FileStream fileStream = new FileStream(@"c:\temp\MySoapFile.dat", FileMode.Open);

//create a SoapFormatter to deserialize the object
SoapFormatter formatter = new SoapFormatter();

//serialize the object to the .dat file
Sample deserializedSample = (Sample)formatter.Deserialize(fileStream);

//show the object properties
Console.WriteLine("The deserialized object:");
Console.WriteLine(String.Format("Name: {0}", deserializedSample.Name));
Console.WriteLine(String.Format("Value: {0}", deserializedSample.Value.ToString()));

Console.Read();

When we press F5 and run our application, we see the values of our object displayed in the console window:

SoapFormatter.Deserialize()
SoapFormatter.Deserialize()

3 thoughts on “SOAP Serialization with C# and .NET

    dineshramitc said:
    July 2, 2014 at 1:38 pm

    Reblogged this on Dinesh Ram Kali..

    Like

    ஜெகதீஸ்வரன் said:
    October 16, 2014 at 2:03 am

    Nice one,. can u suggest any article about the soap with header serialization,.

    Like

    Ray said:
    April 22, 2015 at 2:07 am

    I ran into a “Missing Root Element” exception while I was trying to Deserialize the with the soapformatter. Can you assist with this?

    Here is the code:

    // Creates instance of class to be serizalized
    SerializationSOAP SoapSerial = new SerializationSOAP();
    SoapSerial.Name = “Ray Mulligan Jr.”;
    SoapSerial.Value = 24;

    // Create a FileStream object to accept the output
    FileStream FS = new FileStream(“C:\\SerialzationExample.txt”,
    FileMode.Create);

    // Create a SoapFormatter to serialize the object
    SoapFormatter SFormatter = new SoapFormatter();

    // serizal the object of the .txt file
    SFormatter.Serialize(FS, SoapSerial);

    // Creates SoapFormatter to Deserialize object
    SoapFormatter SF = new SoapFormatter();

    //serialize the object to the .dat file
    SerializationSOAP DeserializeObject =
    (SerializationSOAP)SF.Deserialize(FS);

    // output the object’s properties
    Console.WriteLine(“Deserialized object the”);
    Console.WriteLine(String.Format(“Name: {0}”,
    DeserializeObject.Name));
    Console.WriteLine(String.Format(“Value {0}”,
    DeserializeObject.Value.ToString()));
    Console.Read();
    }

    Like

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