Serializing an object into XML, Soap and Binary

Serializing an object into XML, Soap or a binary stream allows us to persist object data to a database/file system or transport objects across domain boundaries. Serialization is performed using
– System.Xml.Serialization.XmlSerializer for XML
– System.Runtime.Serialization.Formatters.Soap.SoapFormatter for soap
– System.Runtime.Serialization.Formatters.Binary.BinaryFormatter for binary

Once an object has been serialized into XML, soap or binary, we can deserialize the data back into the original object if we have the class definition to deserialize into!

Let’s look at an example.

Here is a class (Person) we’ll use to serialize. Note the attribute on the class [Serializable]. This is required for serialization to work.

[Serializable]
public class Person
{
    public Guid ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string DateOfBirth { get; set; }
}

Now we’ll create a form with 6 buttons. Three to serialize into XML, soap and binary and three to deserialize from XML, soap and binary into the person class. The form will also have a text box so we can see what the serialized data looks like and three text boxes to see the properties on the person object.

Here’s how the form should look.

serialize form

Now we’ll declare our person class at the top of the form.

private Person _person = null;

In the form load, add event handlers, initialize the person and disable the deserialize buttons (we’ll enable them when we have something to deserialize)

// text changed handlers
txtFirstName.TextChanged += new EventHandler(txtFirstName_TextChanged);
txtLastName.TextChanged += new EventHandler(txtLastName_TextChanged);
txtDob.TextChanged += new EventHandler(txtDob_TextChanged);

// button click handlers
btnXMLSerialize.Click += new EventHandler(btnXMLSerialize_Click);
btnBinarySerialize.Click += new EventHandler(btnBinarySerialize_Click);
btnSoapSerialize.Click += new EventHandler(btnSoapSerialize_Click);
btnSoapDeserialize.Click += new EventHandler(btnSoapDeserialize_Click);
btnXMLDeserialize.Click += new EventHandler(btnXMLDeserialize_Click);
btnBinaryDeserialize.Click += new EventHandler(btnBinaryDeserialize_Click);

// initialise person
_person = new Person();
_person.ID = Guid.NewGuid();
_person.FirstName = "Mike";
_person.LastName = "Carroll";
_person.DateOfBirth = "02/10/1984";

// bind the person
Bind();

// disable the deserialize buttons
btnBinaryDeserialize.Enabled = false;
btnSoapDeserialize.Enabled = false;
btnXMLDeserialize.Enabled = false;

The bind method simply binds the person properties to the three text boxes.

/// <summary>
/// Bind the person
/// </summary>
private void Bind()
{
    txtFirstName.Text = _person.FirstName;
    txtLastName.Text = _person.LastName;
    txtDob.Text = _person.DateOfBirth;
}

Now the serialize and deserialize events behind the button clicks.

/// <summary>
/// Serialize to xml
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnXMLSerialize_Click(object sender, EventArgs e)
{
    using (StringWriter textWriter = new StringWriter())
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(_person.GetType());
        serializer.Serialize(textWriter, _person);
        textBox1.Text = textWriter.ToString();
    }

    btnBinaryDeserialize.Enabled = false;
    btnSoapDeserialize.Enabled = false;
    btnXMLDeserialize.Enabled = true;
}

/// <summary>
/// Deserialize from xml
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnXMLDeserialize_Click(object sender, EventArgs e)
{
    using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(textBox1.Text)))
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(_person.GetType());
        _person = (Person)serializer.Deserialize(ms);
    }

    Bind();

    btnBinaryDeserialize.Enabled = false;
    btnSoapDeserialize.Enabled = false;
    btnXMLDeserialize.Enabled = false;

    textBox1.Text = string.Empty;
}

/// <summary>
/// Serialize into soap
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnSoapSerialize_Click(object sender, EventArgs e)
{
    System.Runtime.Serialization.Formatters.Soap.SoapFormatter sf = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
    using (MemoryStream ms = new MemoryStream())
    {
        sf.Serialize(ms, _person);
        ms.Position = 0;
        textBox1.Text = System.Text.ASCIIEncoding.ASCII.GetString(ms.ToArray());
    }

    btnBinaryDeserialize.Enabled = false;
    btnSoapDeserialize.Enabled = true;
    btnXMLDeserialize.Enabled = false;
}

/// <summary>
/// Deserialize from soap
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnSoapDeserialize_Click(object sender, EventArgs e)
{
    System.Runtime.Serialization.Formatters.Soap.SoapFormatter sf = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
    byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(textBox1.Text);
    using (MemoryStream ms = new MemoryStream(b))
    {
        _person = (Person)sf.Deserialize(ms);
    }

    Bind();

    btnBinaryDeserialize.Enabled = false;
    btnSoapDeserialize.Enabled = false;
    btnXMLDeserialize.Enabled = false;

    textBox1.Text = string.Empty;
}

/// <summary>
/// Serialize to binary
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnBinarySerialize_Click(object sender, EventArgs e)
{
    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
    using (MemoryStream ms = new MemoryStream())
    {
        bf.Serialize(ms, _person);
        ms.Position = 0;
        textBox1.Text = Convert.ToBase64String(ms.ToArray());
    }

    btnBinaryDeserialize.Enabled = true;
    btnSoapDeserialize.Enabled = false;
    btnXMLDeserialize.Enabled = false;
}

/// <summary>
/// Deserialize from binary
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnBinaryDeserialize_Click(object sender, EventArgs e)
{
    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new BinaryFormatter();
    byte[] b = Convert.FromBase64String(textBox1.Text);
    using (MemoryStream ms = new MemoryStream(b))
    {
        _person = (Person)bf.Deserialize(ms);
    }

    Bind();

    btnBinaryDeserialize.Enabled = false;
    btnSoapDeserialize.Enabled = false;
    btnXMLDeserialize.Enabled = false;

    textBox1.Text = string.Empty;
}

The last three events allow us to change the values in the object so we can see the different serialized data.

/// <summary>
/// set the date of birth on text changed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void txtDob_TextChanged(object sender, EventArgs e)
{
    _person.DateOfBirth = txtDob.Text;
}

/// <summary>
/// set the last name on text changed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void txtLastName_TextChanged(object sender, EventArgs e)
{
    _person.LastName = txtLastName.Text;
}

/// <summary>
/// set the first name on text changed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void txtFirstName_TextChanged(object sender, EventArgs e)
{
    _person.FirstName = txtFirstName.Text;
}

Now run the application. Click serialize to XML or to binary and you should see the serialized data in the large text box.

Serialized binary:

serialized bianry

Serialized Soap:

serialized soap

Serialized XML:

serialized xml

Once the data has been serialized, the deserialize buttons can be clicked to take the data from the text box and recreate the object to be rebound. If you change the values in the three textboxes, you’ll see the serialized data change.

So there we have it. Serialization and deserialization in C#!

Happy coding!

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s