Click here to Skip to main content
Click here to Skip to main content
Articles » Languages » C# » General » Downloads
 
Add your own
alternative version

Tagged as

Achieve Persistence Through Serialization

, 6 Jan 2011 CPOL
This article compares the two common types of serialization in aspects of data access, readability, and runtime cost.
/// Copyright Trestan Chen.
/// 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.
/// Remove the tick count codes from SerializeWithEncrypt and DeSerializeWithEncrypt to use it in your working project.
/// 

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 void TSerialize(object theObject, string sFileName)
        {
            BinaryFormatter btFormatter = new BinaryFormatter();
            FileStream theFileStream = new FileStream(sFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
            btFormatter.Serialize(theFileStream, theObject);
            theFileStream.Close();
        }

        public static object TDeSerialize(string sFileName)
        {
            if (sFileName == null || sFileName == "" || !File.Exists(sFileName))
            {
                return null;
            }
            FileStream theFileStream = new FileStream(sFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryFormatter btFormatter = new BinaryFormatter();
            object theObj = btFormatter.Deserialize(theFileStream);
            theFileStream.Close();
            return theObj;
        }

        public static void SerializeWithEncrypt(object theObject, string sFileName)
        {
            MemoryStream theMS = new MemoryStream();
            BinaryFormatter btFormatter = new BinaryFormatter();
            btFormatter.Serialize(theMS, theObject);
            theMS.Seek(0, SeekOrigin.Begin);
            byte[] temp = theMS.ToArray();

            temp = Encrypt(temp);
            //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();
        }

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

            byte[] temp = File.ReadAllBytes(sFileName);

            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
        }

        // Encryption came from .net.
        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;
        }

        public static string getHostIP()
        {
            try
            {
                string hostname = System.Net.Dns.GetHostName();
                System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(hostname);
                if (ipEntry.AddressList.Length > 0)
                {
                    return ipEntry.AddressList[0].ToString();
                }
            }
            catch (Exception ex) { }
            return "";
        }
    }
}

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)

Share

About the Author

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 6 Jan 2011
Article Copyright 2011 by trestan
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid