5,691,626 members and growing! (13,621 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » .NET Framework » How To     Intermediate

How to serialize an object which is NOT marked as 'Serializable' using a surrogate.

By Naveen Karamchetti

Serialize an object which is NOT marked as 'Serializable' using a surrogate.
C#, .NET, Win2K, WinXP, Windows, Visual Studio, Dev

Posted: 2 May 2005
Updated: 2 May 2005
Views: 65,996
Bookmarked: 29 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
22 votes for this Article.
Popularity: 4.75 Rating: 3.54 out of 5
4 votes, 18.2%
1
1 vote, 4.5%
2
2 votes, 9.1%
3
4 votes, 18.2%
4
11 votes, 50.0%
5

Introduction

This article describes how to serialize an object which is not marked as 'Serializable' using a surrogate.

Background

Serialization is a process of converting an object in memory into a byte stream, suitable for transportation across the wire and persisting in a stable storage. Only an object that is marked as serializable can be serialized. The problem here is to serialize an object which is not marked as serializable.

Using the code

We will look into a step-by-step approach of "How to serialize an object which is not marked as 'Serializable' using a surrogate". For this purpose, consider a simple class called Vehicle, whose source code is not available. The code for the class Vehicle is shown below...

The Vehicle class is as follows:

    /// <SUMMARY>

    /// NOTE: It is assumed for this demo that the source code for this class

    /// is not available and this class cannot be marked as '[Serializable]'.

    /// </SUMMARY>

    public class Vehicle 
    {
        /// <SUMMARY>

        /// Make of the vehicle.

        /// </SUMMARY>

        private string _make;

        /// <SUMMARY>

        /// Model of the vehicle.

        /// </SUMMARY>

        private string _model;

        public string Make
        {
            get
            {
                return _make;
            }

            set
            {
                _make = value;
            }
        }

        public string Model
        {
            get
            {
                return _model;
            }

            set
            {
                _model = value;
            }
        }
    }

In order to serialize this class, a new class called VehicleSurrogate needs to be written. See the source code of the class VehicleSurrogate below...

    public class VehicleSurrogate : ISerializationSurrogate
    {
        /// This method is part of the interface ISerializationSurrogate

        public void GetObjectData(object obj, SerializationInfo info, 
                                                StreamingContext context)
        {
            Vehicle vehicle = obj as Vehicle;
            // Set the vehicle object's properties

            info.AddValue("Make", vehicle.Make);
            info.AddValue("Model", vehicle.Model);
        }

        /// This method is part of the interface ISerializationSurrogate

        public object SetObjectData(object obj, SerializationInfo info, 
                   StreamingContext context, ISurrogateSelector selector)
        {
            // Restore the vehicle object's properties

            Vehicle vehicle = obj as Vehicle;
            vehicle.Make  = info.GetString("Make");
            vehicle.Model = info.GetString("Model");
            
            // This is ignored.

            return null;
        }

The interface ISerializationSurrogate provides two methods needed to serialize and de-serializable objects. The properties can be set/retrieved as and when required. Now!! As for the client code, in order to put all this into use... look at the method SerializeUsingSurrogate():

        public void SerializeUsingSurrogate()
        {
            try
            {
                // Create a new instance of the vehicle class.

                // NOTE: It is assuming for this demo that the source 

                // code for this class

                // is not available.

                Vehicle vehicle = new Vehicle();
                vehicle.Make = "Cadillac";
                vehicle.Model = "2005";
                
                // 1. Create an instance of a Soap Formatter.

                IFormatter formatter = new SoapFormatter();

                // 2. Construct a SurrogateSelector object

                SurrogateSelector ss = new SurrogateSelector();

                // 3. Construct an instance of our serialization surrogate type

                VehicleSurrogate vss = new VehicleSurrogate();

                // 4. Tell the surrogate selector to use our object when a 

                //    Vehicle object is serialized/deserialized.

                // NOTE: AddSurrogate can be called multiple times to register

                // more types with their associated surrogate types

                ss.AddSurrogate(typeof(Vehicle), 
                    new StreamingContext(StreamingContextStates.All), vss);
                                
                // Creating a byte array to hold the data.

                byte[] bData = new byte[1024];

                MemoryStream memoryStream = new MemoryStream(bData);
                TextWriter textWriter = new StreamWriter(@"C:\Vehicle.xml");

                // 5. Have the formatter use our surrogate selector

                formatter.SurrogateSelector = ss;

                // Try to serialize a Vehicle object

                formatter.Serialize(memoryStream, vehicle);
                
                // Create a buffer to hold the data.

                StringBuilder buffer = new StringBuilder();

                for(int count = 0; count < bData.Length; count++)
                {
                    if ( bData[count] != '\0')
                    {
                        // Convert the char stream data to string.

                        buffer.Append( Convert.ToChar(bData[count]));
                    }
                }

                textWriter.WriteLine(buffer.ToString() );

                // clean up.

                textWriter.Close();
                buffer = null;
            }
            catch(Exception)
            {
                // Check for exception in case of a fault.

            }
        }

Let us walkthrough this code step-by-step...

  1. Create an instance of the Vehicle object and set its properties.
  2. Create an instance of the SoapFormatter object, this shall be used to add surrogate selectors.
  3. Create an instance of the SurrogateSelector.
  4. Construct an instance of our serialization surrogate type VehicleSurrogate.
  5. Add our surrogates using the method AddSurrogate of the SurrogateSelector object.
  6. Have the formatter use our surrogate selector using the formatter.SurrogateSelector.
  7. Try to serialize the Vehicle object.
  8. Create a buffer to hold the serialized data using StringBuilder object.

Points of Interest

A 'ISerializationSurrogate' can be used to provide custom serialization for objects which are not marked as serializable and for those whose source code is not available.

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

Naveen Karamchetti


Naveen Karamchetti has done his Masters (M.S.) in Software Engineering from B.I.T.S, Pilani and is based out of Fremont, CA.
The author has more than 8.5 yrs of experience in the IT industry, has started his career
starting from the good old days of using a Unix, Tcl/tk. The author has been associated with
several companies based out of Silicon Valley, California.

The author has won several programming awards within the organizations worked and is well-recognized. The author has also worked for Microsoft based at Redmond.

Hobbies include training, mentoring and research. Spends his free time travelling in the BART (Bay Area Rapid Transit) in Fremont, CA.
Occupation: Software Developer (Senior)
Location: United States United States

Other popular .NET Framework articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 21 of 21 (Total in Forum: 21) (Refresh)FirstPrevNext
QuestionPrinter Serializationmembernishanth13914:15 15 Oct '08  
QuestionDeserialize object is Error!memberSteven's life22:40 25 Mar '07  
GeneralWhat about serializing "Color"memberWolfram Steinke14:44 13 Feb '07  
Generalhow can i serialize an imagememberelfraga9:55 11 Jan '07  
GeneralIt's too simple&too troublememberfirstrose200021:07 11 Dec '06  
GeneralIs it possible to serialize class object in smartphone applicationsmemberguocang8:35 25 Jul '06  
Generalneed these include librariesmemberDan Lipsy9:20 7 Sep '05  
GeneralGreat, helped me solve the Font SoapFormatter problemsussMarc Ridey17:39 22 Aug '05  
GeneralGood article, but too simplemember636stevec6:25 13 May '05  
GeneralRe: Good article, but too simplememberNaveen Karamchetti5:22 18 May '05  
Generalusefulness?memberjan.limpens3:53 12 May '05  
GeneralRe: usefulness?sussAnonymous3:21 17 May '05  
GeneralRe: usefulness?memberNaveen Karamchetti5:21 18 May '05  
GeneralRe: usefulness?sussDrGUI12:48 18 May '05  
AnswerRe: usefulness?memberMaxtorM1238:26 7 May '07  
GeneralNice One!memberJaved Akhter Siddiqui20:37 9 May '05  
GeneralMissed codememberFregate16:51 9 May '05  
GeneralRe: Missed codememberNaveen Karamchetti20:08 9 May '05  
GeneralRe: Missed codememberJaved Akhter Siddiqui20:27 9 May '05  
GeneralCool :)memberleppie8:24 2 May '05  
GeneralRe: Cool :)memberNaveen Karamchetti4:17 4 May '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 2 May 2005
Editor: Rinish Biju
Copyright 2005 by Naveen Karamchetti
Everything else Copyright © CodeProject, 1999-2008
Web10 | Advertise on the Code Project