Click here to Skip to main content
15,893,486 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.
/// this code is provided as is, bugs are probable, free for any use, no responsibility accepted :-)
/// Please contact trestan88@yahoo.ca,for any questions and suggestions.
/// 
using System;
using System.Xml.Serialization;
using System.IO;
using System.ComponentModel;
using System.Security.Cryptography;
using System.Runtime.Serialization.Formatters.Binary;

namespace Trestan
{
    public static class Utility
    {
        public static string ObjectToString(object theObject)
        {
            TypeConverter tc = TypeDescriptor.GetConverter(theObject.GetType());
            return tc.ConvertToString(theObject);
        }

        public static object ObjectFromString(Type theType, string strInstance)
        {
            TypeConverter tc = TypeDescriptor.GetConverter(theType);
            return tc.ConvertFromString(strInstance);
        }

        public static void SerializeWithEncrypt(object theObject, string sFileName)
        {
            long tick = DateTime.Now.Ticks;
            MemoryStream theMS = new MemoryStream();
            BinaryFormatter btFormatter = new BinaryFormatter();
            btFormatter.Serialize(theMS, theObject);
            theMS.Seek(0, SeekOrigin.Begin);
            byte[] temp = theMS.ToArray();
            Console.WriteLine("Time used to serialize to memory stream: " + (DateTime.Now.Ticks - tick) / 10000000F);
            tick = DateTime.Now.Ticks;

            // SampleEncryption(temp);  // The simple method is much faster.
            temp = Encrypt(temp);
            Console.WriteLine("Time used to encrypt: " + (DateTime.Now.Ticks - tick) / 10000000F);
            tick = DateTime.Now.Ticks;
            //Output to a file.
            FileStream theFileStream = new FileStream(sFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
            BinaryWriter theBW = new BinaryWriter(theFileStream);

            theBW.Write(temp, 0, temp.Length);
            theBW.Close();
            theFileStream.Close();
            theMS.Dispose();
            Console.WriteLine("Time used to write to file: " + (DateTime.Now.Ticks - tick) / 10000000F);
            Console.WriteLine("End of a test\n");
        }

        public static object DeSerializeWithDecrypt(string sFileName)
        {
            if (sFileName == null || sFileName == "" || !File.Exists(sFileName))
            {
                return null;
            }
            byte[] temp = File.ReadAllBytes(sFileName);

            // SampleEncryption(temp);
            temp = Decrypt(temp);

            MemoryStream theMS = new MemoryStream(temp);
            BinaryFormatter btFormatter = new BinaryFormatter();
            object theObj = btFormatter.Deserialize(theMS);
            theMS.Dispose();
            return theObj;
        }

        public static void SampleEncryption(byte[] theData)
        {
            // You can run an encrytion algorithm here.
            // Google "C# byte encrypt", to find ready-to-use code.
            #region a simply encryption
            System.Collections.BitArray theBits = new System.Collections.BitArray(theData);
            theBits.Not();
            byte[] bt = System.Text.Encoding.Default.GetBytes("this is a test.add up to the same length");
            byte[] theKey = new byte[theData.Length];

            int count = 0;
            int limit = theData.Length - bt.Length;
            while (count < limit)
            {
                bt.CopyTo(theKey, count);
                count += bt.Length;
            }

            System.Collections.BitArray key = new System.Collections.BitArray(theKey);
            theBits.Xor(key);
            theBits.CopyTo(theData, 0);
            #endregion a simply encryption
        }

        public static byte[] Encrypt(byte[] theData)
        {
            byte[] byKey = { 0x6A, 0x87, 0x98, 0x59, 0x38, 0xB7, 0x5F, 0xF1 };
            byte[] IV = { 0xBE, 0xD5, 0xA6, 0x4B, 0x95, 0xC6, 0xCC, 0x4B };

            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            ICryptoTransform desencrypt = DES.CreateEncryptor(byKey, IV);
            byte[] result = desencrypt.TransformFinalBlock(theData, 0, theData.Length);
            return result;
        }

        public static byte[] Decrypt(byte[] theData)
        {
            byte[] byKey = { 0x6A, 0x87, 0x98, 0x59, 0x38, 0xB7, 0x5F, 0xF1 };
            byte[] IV = { 0xBE, 0xD5, 0xA6, 0x4B, 0x95, 0xC6, 0xCC, 0x4B };
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();

            ICryptoTransform desencrypt = DES.CreateDecryptor(byKey, IV);
            byte[] result = desencrypt.TransformFinalBlock(theData, 0, theData.Length);
            return result;
        }
    }
}

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