Click here to Skip to main content
15,892,575 members
Articles / Programming Languages / C#

Both XML and Binary Serializable Dictionary

Rate me:
Please Sign up or sign in to vote.
4.67/5 (12 votes)
3 Jan 2011CPOL3 min read 54.8K   1.4K   26  
Created a derived class from Dictionary which is both XML and binary serializable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System.Runtime.Serialization.Formatters.Binary;

namespace DictionarySerialization
{
    /// <summary>
    /// Serializable simple person class
    /// </summary>
    [Serializable]
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public SerializableDictionary<int, DateTime?> PersonChild { get; set; }
    }
    class Program
    {

        static void Main(string[] args)
        {
            //A simple type checking with both xml and binary serializable dictionary
           // SimpleTypeChecking();
            //Creating List of persion class to test the seriliaztion of derived dictionary class
            ComplexTypeChecking();
        }

        private static void ComplexTypeChecking()
        {
            List<Person> person = new List<Person>();
            var childDictionary = new SerializableDictionary<int, DateTime?>();
            childDictionary.Add(1, DateTime.Now);
            childDictionary.Add(2, null);
            person.Add(new Person() { Name = "Milton", Age = 27, PersonChild = childDictionary });
            person.Add(new Person() { Name = "Bashar", Age = 27, PersonChild = childDictionary });
            //Create a dictionary which is both xml and binary serializable
            SerializableDictionary<DateTime, List<Person>> serialization = new SerializableDictionary<DateTime, List<Person>>();
            serialization.Add(DateTime.Now, person);
            serialization.Add(DateTime.Now, person);
            serialization.Add(DateTime.Now, null);
            //output after xml serialization
            string xmlSerialized = SerializeObject<SerializableDictionary<DateTime, List<Person>>>(serialization);
            //Deserialized object after xml deserialization
            SerializableDictionary<DateTime, List<Person>> xmlDesialized = DeserializeObject<SerializableDictionary<DateTime, List<Person>>>(xmlSerialized);
            //
            SerializableDictionary<DateTime, List<Person>> deserialized1 = (SerializableDictionary<DateTime, List<Person>>)DeepClone(serialization);
        }

        private static void SimpleTypeChecking()
        {
            SerializableDictionary<int, string> serialization = new SerializableDictionary<int, string>();
            serialization.Add(1, "Milton");
            serialization.Add(2, "Bashar");
            //output after xml serialization
            string xmlSerialized = SerializeObject<SerializableDictionary<int,string>>(serialization);
            //Deserialized object after xml deserialization
            SerializableDictionary<int, string> xmlDesialized = DeserializeObject<SerializableDictionary<int, string>>(xmlSerialized);
            //
            SerializableDictionary<int, string> deserialized1 = (SerializableDictionary<int, string>)DeepClone(serialization);
        }

        #region Xml serialization
        public static T DeserializeObject<T>(String pXmlizedString)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

            return (T)xs.Deserialize(memoryStream);
        }
        public static String SerializeObject<T>(Object pObject)
        {
            try
            {
                String XmlizedString = null;
                MemoryStream memoryStream = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(typeof(T));
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

                xs.Serialize(xmlTextWriter, pObject);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
                return XmlizedString;
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e);
                return null;
            }
        }

        private static String UTF8ByteArrayToString(Byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            String constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        /// <summary>
        /// Converts the String to UTF8 Byte array and is used in De serialization
        /// </summary>
        /// <param name="pXmlString"></param>
        /// <returns></returns>
        private static Byte[] StringToUTF8ByteArray(String pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }
        #endregion

        #region Binary serialization and deserilization
        public static object DeepClone(object source)
        {
            Stream stream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, source);

            stream.Position = 0;
            return formatter.Deserialize(stream);
        }
        #endregion

    }
}

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
Software Developer
Bangladesh Bangladesh
Name SYED MD. ABUL BASHAR
Email ID: miltoncse00@gmail.com

I am now working as software engineer in Malaysia. I am from Bangladesh and I have completed my B.Sc (Engg.) in CSE from Rajshahi University of Engineering and Technology (RUET).I spend much time in learning latest technology.

My LinkedIn Profile : http://bd.linkedin.com/in/miltoncse00[^]

My blog :http://ciintelligence.blogspot.com/[^]

Comments and Discussions