Click here to Skip to main content
15,889,462 members
Articles / Programming Languages / XML

SOAP serialization

Rate me:
Please Sign up or sign in to vote.
3.43/5 (7 votes)
15 Jul 20032 min read 91.4K   1.6K   23   7
An article on object serialization in .NET

Introduction

As programmers, we use serialization for storage of classes and data structures. With the advent of .NET, serialization is becoming something like a standard and there are fundamental reasons for that - .NET has everything for serialization (well almost). Typically, the serialization process consists of creation of the serializer, opening of the stream and invocation of the serializer. You do that again and again and eventually realize that there is a pattern which might be hidden inside some generic class.

Background

There are many articles about serialization in .NET last time. Some of them describe basic operations with serialization, some more advanced describe the classes for serialization. This article is another approach to create a generic class for serialization.

The goal: the class should serialize itself, to be self contained, be simple.

Using the Code

Generally, this class should look something like:

C#
Class GSerialized : BaseSerializable
{     
    // some custom stuff 
    int MyVarInt1;
    int MyVarInt2;
    SomeClassType another_var; 
    // may be some methods ...and so on 
}

In other words, the class has to be derived from some generic class that implements basic serialization.

Another solution is the implementation of the methods of Serializable interface. Both approaches have pros and cons. Methods for implementing Serializable interface are well explained in different articles and manuals. From my point of view, this approach is more complicated and therefore less elegant.

The solution I am proposing is the creation of an abstract serialization class. The abstract class named BaseSerializable has basic functionality to serialize and deserialize itself.

However, the implementation of BaseSerializable is not entirely generic, due to the limitations of C#. Namely:

In the constructor of derived class, the protected variable ChildObjectRef must be set to this. That is the only flaw of C# implementation of the generic BaseSerializable class. (In C++, that could have been implemented in an entirely generic manner through template mechanism.)

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

namespace UtilLib
{
    [Serializable]
    public abstract class BaseSerializable
    {
        protected object ChildObjectRef;

        public BaseSerializable()
        {
        }

        public void _Serialize(string FullPath)
        {
            if (FullPath == null)
            {
                throw new Exception("_Serialize: Path not set");
            }

            string DirName = Path.GetDirectoryName(FullPath);

            FileStream s = null;

            if (!((DirName == null) || (DirName.Trim().Length == 0)))
            {
                if (!Directory.Exists(DirName))
                {
                    Directory.CreateDirectory(DirName);
                }
            }

            s = new FileStream(FullPath, FileMode.Create);
            SoapFormatter sf = new SoapFormatter();
            sf.Serialize(s, ChildObjectRef);
            s.Close();
        }

        public object _Deserialize(string FullPath)
        {
            FileStream s = new FileStream(FullPath, FileMode.Open);
            SoapFormatter sf = new SoapFormatter();
            object msc = (object)sf.Deserialize(s);
            s.Close();
            return msc;
        }
    }
}

How to Create Your Class?

Easy. Your serializable class will look like the class below:

C#
using System;
using System;
using UtilLib;
using System.Collections;
[Serializable]

public class MySerialClass : BaseSerializable{
    public int MyDummyInteger; // could be private 
    public string MyDummySting; // could be private ..
    public ArrayList MyDummyArrayList; // or another serializable object 

    public MySerialClass ()
    {
        ChildObjectRef = this; // that is mandatory !!
    }
    // My methods below, if any
}

How to Use the Class?

Here is a code snippet:

C#
MySerialClass MyDataKeeper_1 = new MySerialClass();

// fill it with data
MyDataKeeper_1.MyDummySting = "Dummy_String";
MyDataKeeper_1.MyDummyInteger = 4545;
ArrayList al = new ArrayList();
al.add("hello");
al.add("by");
MyDataKeeper_1. MyDummyArrayList = al;

// serialize it
MyDataKeeper_1._Serialize("test.xml");


// deserialization
MySerialClass MyDataKeeper_2 = new MySerialClass();

Try
{
    MyDataKeeper_2 = (MySerialClass)MyDataKeeper_2._Deserialize("test.xml");
}
catch
{
    // your code here if deserialization fails for any reason.
}

Demo Project

Demo project consists of two parts. The first one is Windows forms, that demonstrates saving and restoring custom data to test.XML file. The second part is a console demo.

History

  • This is version 1.0.0.

License

This article has no explicit license attached to it, but may contain usage terms in the article text or the download files themselves. If in doubt, please contact the author via the discussion board below.

A list of licenses authors might use can be found here.


Written By
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralSerializing Delegates and Sending it to Remote Machine Pin
Identity Undisclosed27-Dec-04 6:42
Identity Undisclosed27-Dec-04 6:42 
GeneralRe: Serializing Delegates and Sending it to Remote Machine Pin
Nehal Kanani20-Jan-06 0:08
Nehal Kanani20-Jan-06 0:08 
GeneralExtending this approach Pin
Anuj Sareen12-Nov-03 23:16
Anuj Sareen12-Nov-03 23:16 
GeneralRe: Extending this approach Pin
Alex_114-Nov-03 10:54
Alex_114-Nov-03 10:54 
Generalserializing path Pin
Member 43216822-Oct-03 21:13
Member 43216822-Oct-03 21:13 
GeneralRe: serializing path Pin
Alex_126-Oct-03 17:16
Alex_126-Oct-03 17:16 
GeneralMFC C++ and Java Pin
SeanV23-Jul-03 2:46
SeanV23-Jul-03 2:46 
Is there a protocol issue when Serializing data using Serialize method of MFC C++ over a TCP Socket to a Java App. If not how can this be done?

The model is: A java client connect a server written in C++ and Serialization of a Class or an Object containg data takes place. If you can help me I'll be very happy.

Cheers
Sean V

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.