Click here to Skip to main content
Licence 
First Posted 15 Jul 2003
Views 70,100
Bookmarked 23 times

SOAP serialization

By | 15 Jul 2003 | Article
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 :

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 cones. 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 entirely generic manner through template mechanism)

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:

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.

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 deserealization 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. 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

About the Author

Alex Sivokho



Australia Australia

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralSerializing Delegates and Sending it to Remote Machine PinmemberIbraheem Khan6:42 27 Dec '04  
GeneralRe: Serializing Delegates and Sending it to Remote Machine PinmemberNehal Kanani0:08 20 Jan '06  
GeneralExtending this approach PinmemberAnuj Sareen23:16 12 Nov '03  
GeneralRe: Extending this approach PinmemberAlex_110:54 14 Nov '03  
Generalserializing path Pinmemberfilippo.santovito21:13 22 Oct '03  
GeneralRe: serializing path PinmemberAlex_117:16 26 Oct '03  
GeneralMFC C++ and Java PinmemberSeanV2:46 23 Jul '03  

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 16 Jul 2003
Article Copyright 2003 by Alex Sivokho
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid