Click here to Skip to main content
15,893,564 members
Articles / Programming Languages / C#

Achieve Persistence Through Serialization

Rate me:
Please Sign up or sign in to vote.
4.60/5 (7 votes)
6 Jan 2011CPOL5 min read 29.7K   342   15  
This article compares the two common types of serialization in aspects of data access, readability, and runtime cost.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Drawing;
using System.Xml.Serialization;

namespace Trestan
{
    #region Test Case 2
    /// Test Case 2: You can add more primary types in this class and the tests again.
    /// Test Result: All the buildin types should be supported.
    /// 
    #endregion
    public class BuildinType
    {
        static int instanceCount = 0;

        #region Test Case 7
        /// Test Case 7: Find test1.xml and open it in IE or a text editor. Search "InstanceCount".
        /// Test Result: The word can not be found.
        /// 
        #endregion
        public static int InstanceCount
        {
            get { return BuildinType.instanceCount; }
            set { BuildinType.instanceCount = value; }
        }

        int instanceID = instanceCount++;
        public int InstanceID
        {
            get { return instanceID; }
            set { instanceID = value; }
        }

        float number = 100.3F * instanceCount;
        public float Number
        {
            get { return number; }
            set { number = value; }
        }

        string description = "This is a test.";
        public string Description
        {
            get { return description; }
            set { description = value; }
        }
    }

    #region Test Case 3
    /// Test Case 3: A sample of derived class.
    /// Test Result: The public fields in both the derived class and the base class can be serialized,which can be verified in Test Case 1.
    /// 
    #endregion

    // Be carefull when using buildin class types. Not all of them contain a default constructor.
    public class DerivedClass : BuildinType
    {
        public enum STATE { INIT = 0, DONE = 1 };

        private STATE testState = STATE.DONE;
        public STATE TestState
        {
            get { return testState; }
            set { testState = value; }
        }

        #region Test Case 8
        /// Test Case 8: Uncomment the following construtor and run the program.
        /// Test Result: There should be an exception thrown when running deserialize.
        ///public DerivedClass( Version theVersion)
        ///{
        ///    testVersion = theVersion;
        ///}
        ///
        #endregion

        DateTime testTime = DateTime.Now;
        public DateTime TestTime
        {
            get { return testTime; }
            set { testTime = value; }
        }

        //Have to convert to string to be persistant.
        Font testFont = new Font("Times New Roman", 10F);

        #region Test Case 6
        /// Test Case 6: Remove the [XmlIgnore] and run the program.
        /// Test Result: There should be an exception thrown. 
        /// Well, you can put the build-in types one by one to find out "most of them non-serializable":)
        /// 
        #endregion
        [XmlIgnore]                 /// Remove this attribute for testing Test Case 6.
        public Font TestFont        //Accessors for general calling. 
        {
            get { return testFont; }
            set { testFont = value; }
        }

        #region Test Case 10
        /// Test Case 10: Comment out the following accessor and run the program.Refer to Program.cs for further instruction.
        /// Action: Check the value of testFont in the debugger visualizer window after deserialized.
        /// Test Result: The value of testFont is the above value during initialization, not the value assigned in Main().
        /// 
        #endregion
        public string StrFont       //Accessors for serialization.
        {
            get { return Utility.ObjectToString(testFont); }
            set { testFont = (Font)Utility.ObjectFromString(typeof(Font), value); }
        }

        #region Test Case 5
        /// Test Case 5: Repeat Test Case 1, search the word "testVersion".
        /// Test Result: It's not contained in the output.
        /// Private fields won't get serialized.
        /// 
        #endregion
        Version testVersion = Assembly.GetExecutingAssembly().GetName().Version;
    }

    #region Test Case 4
    /// Test Case 4: A sample class demonstrating simple collection types can be serialized.
    /// Action: Find test3.xml and open it in IE or a text editer.
    /// Test Result: The output file contains the data from the TestArray,TestList and ListQueue.
    /// 
    #endregion
    public class CollectionTypes
    {
        BuildinType test = new BuildinType();
        public BuildinType Test
        {
            get { return test; }
            set { test = value; }
        }

        BuildinType[] testArray = new BuildinType[10000];
        public BuildinType[] TestArray
        {
            get { return testArray; }
            set { testArray = value; }
        }

        List<BuildinType> testList = new List<BuildinType>();
        public List<BuildinType> TestList
        {
            get { return testList; }
            set { testList = value; }
        }

        // Not serializable.
        Queue<BuildinType> testQueue = new Queue<BuildinType>();
        //If you really want to do it, have to write your own queue class with default accessor.
        //Or, convert to a serializable type of collection.
        public List<BuildinType> ListQueue
        {
            get { return testQueue.ToList<BuildinType>(); }
            set
            {
                foreach (BuildinType one in value)
                {
                    testQueue.Enqueue(one);
                }
            }
        }

        public CollectionTypes()
        {
            for (int i = 0; i < 10000; i++)
            {
                BuildinType temp = new BuildinType();
                testArray[i] = temp;
                temp = new BuildinType();
                testQueue.Enqueue(temp);
            }

            testList.AddRange(testArray);
            testList.AddRange(testArray);
        }

        public void Dispose()
        {
            testList.Clear();
            testQueue.Clear();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
Canada Canada
Looking for something to do in the new year.

Comments and Discussions