13 Haz

C# Create A New Thread With/Without Parameter

This example shows how to create a new thread in .NET Framework.
First, create a new ThreadStart delegate.
The delegate points to a method that will be executed by the new thread.
Then, call Start method. If you want to pass a parameter to the thread,

Sample Code:


            //start without parameters
            Thread threadWithoutParameter = new Thread(new ThreadStart(delegate()
            {
                //do anything on background
            }));
            threadWithoutParameter.Start();

            //start with parameters
            Thread threadWithParameter = new Thread(new ParameterizedThreadStart(delegate(object obj)
            {
                //do anything on background
            }));
            object param = "Thread parameter";
            threadWithParameter.Start(param);

13 Haz

C# Generic XML Serialization

This example is the steps to serialize and deserialize an object as XML data. The sample generic class will only serialize “public” properties of a class.

Usage:

            
            CSharpCodeExampleData exData = new CSharpCodeExampleData();
            exData.Name = "Popular C# Examples Web Site";
            exData.Url = "http://www.csharpexamples.com";
            exData.AttributeWillBeIgnore = "This value won't be serialized";
            GenericXMLSerializer<CSharpCodeExampleData> serializer = new GenericXMLSerializer<CSharpCodeExampleData>();

            //Serialize
            string xml = serializer.Serialize(exData);

            //Deserialize
            CSharpCodeExampleData deserilizedObject = serializer.Deserialize(xml);

Generic Code:


    public class GenericXMLSerializer<T>
    {
        /// 
        /// Serializes the specified object and returns the xml value
        /// 
        /// 
        /// 
        public string Serialize(T obj)
        {
            string result = string.Empty;

            System.IO.StringWriter writer = new System.IO.StringWriter();
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            serializer.Serialize(writer, obj);
            result = writer.ToString();

            return result;
        }

        /// 
        ///  Deserializes the XML content to a specified object
        /// 
        /// 
        /// 
        public T Deserialize(string xml)
        {
            T result = default(T);

            if (!string.IsNullOrEmpty(xml))
            {
                System.IO.TextReader tr = new System.IO.StringReader(xml);
                System.Xml.XmlReader reader = System.Xml.XmlReader.Create(tr);
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

                if (serializer.CanDeserialize(reader))
                    result = (T)serializer.Deserialize(reader);
            }
            return result;
        }
    }

    /// 
    /// class example which will be serialized
    /// 
    public class CSharpCodeExampleData
    {
        [XmlAttribute("Url")]
        public string Url = null;
    
        [XmlAttribute("Name")]
        public string Name = null;

        [XmlIgnore]
        public string AttributeWillBeIgnore = null;
    } 

13 Haz

C# Stream Encryption and Decryption With Multi Algorithm Support

Short information about encryption:
There are many encryption algorithm. They are divided into two as symetric and asymmetric. Symmetric encryption and asymmetric encryption are performed using different processes. Symmetric encryption is performed on streams and is therefore useful to encrypt large amounts of data. Asymmetric encryption is performed on a small number of bytes and is therefore useful only for small amounts of data.

For more information:
http://msdn.microsoft.com/en-us/library/as0w18af%28v=vs.110%29.aspx

This example shows how to encrypt a string or stream data in .NET Framework.
You can encrypt/decrypt all data types(string, file etc.) using sample class.

Usage:

            string plainText = "This is a plain text.";
            CryptoService cryptoService = new CryptoService();
            byte[] data = Encoding.Unicode.GetBytes(plainText);
            byte[] key = Encoding.Unicode.GetBytes("key");
            byte[] cipherData = cryptoService.Encrypt(data, key);

            byte[] decryptedData = cryptoService.Decrypt(cipherData, key);
            string againPlainText = Encoding.Unicode.GetString(decryptedData);

Crypto Code:

    public class CryptoService
    {
        private CipherMode _cipherMode = CipherMode.CFB;
        private PaddingMode _paddingMode = PaddingMode.PKCS7;

        private static readonly byte[] _salt = new byte[] { 0x25, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x12, 0x3c };

        private EncryptionAlgorithm _algorithm = EncryptionAlgorithm.AES;
        public EncryptionAlgorithm Algorithm
        {
            get { return _algorithm; }
            set { _algorithm = value; }
        }
        
        public Stream Encrypt(Stream streamToEncrypt, byte[] key)
        {
            SymmetricAlgorithm algorithm = null;
            if (_algorithm == EncryptionAlgorithm.TripleDES)
                algorithm = new TripleDESCryptoServiceProvider();
            else if (_algorithm == EncryptionAlgorithm.AES)
                algorithm = new RijndaelManaged();
            else
                throw new ApplicationException("Unexpected algorithm type!");

            algorithm.Mode = _cipherMode;
            algorithm.Padding = _paddingMode;

            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(key, _salt, 100);
            algorithm.Key = rfc.GetBytes(algorithm.KeySize / 8);
            algorithm.IV = rfc.GetBytes(algorithm.BlockSize / 8);

            try
            {
                ICryptoTransform encryptor = algorithm.CreateEncryptor();
                using (CryptoStream cryptoStream = new CryptoStream(streamToEncrypt, encryptor, CryptoStreamMode.Read))
                {
                    MemoryStream ms = new MemoryStream();
                    CopyStream(cryptoStream, ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    return ms;
                }
            }
            finally
            {
                algorithm.Clear();
            }
        }

        public Stream Decrypt(Stream streamToDecrypt, byte[] key)
        {
            SymmetricAlgorithm algorithm = null;
            if (_algorithm == EncryptionAlgorithm.TripleDES)
                algorithm = new TripleDESCryptoServiceProvider();
            else if (_algorithm == EncryptionAlgorithm.AES)
                algorithm = new RijndaelManaged();
            else
                throw new ApplicationException("Unexpected algorithm type!");

            algorithm.Mode = _cipherMode;
            algorithm.Padding = _paddingMode;

            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(key, _salt, 100);
            algorithm.Key = rfc.GetBytes(algorithm.KeySize / 8);
            algorithm.IV = rfc.GetBytes(algorithm.BlockSize / 8);

            try
            {
                ICryptoTransform decryptor = algorithm.CreateDecryptor();
                using (CryptoStream cryptoStream = new CryptoStream(streamToDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    MemoryStream ms = new MemoryStream();
                    CopyStream(cryptoStream, ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    return ms;
                }
            }
            finally
            {
                algorithm.Clear();
            }
        }

        public byte[] Encrypt(byte[] dataToEncrypt, byte[] key)
        {
            MemoryStream ms = new MemoryStream(dataToEncrypt);
            Stream res = Encrypt(ms, key);
            if (res != null)
            {
                byte[] tmp = new byte[res.Length];
                res.Read(tmp, 0, tmp.Length);
                return tmp;
            }

            return null;
        }

        public byte[] Decrypt(byte[] dataToDecrypt, byte[] key)
        {
            MemoryStream ms = new MemoryStream(dataToDecrypt);
            Stream res = Decrypt(ms, key);
            if (res != null)
            {
                byte[] tmp = new byte[res.Length];
                res.Read(tmp, 0, tmp.Length);
                return tmp;
            }

            return null;
        }

        public void CopyStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[32768];
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);
            }
        }
    }

    public enum EncryptionAlgorithm
    {
        TripleDES,
        AES,
    }
13 Haz

C# IStream Implementation and IStream Wrapper Class Example

See example/usage below for istream implementation and wrapper. Attachment has two c# files includes MamagedIStream and IStreamWrapper class.

Usage IStreamWrapper and ManagedIStream:

            
            //IStreamWrapper  usage
            IStream iStream = null; // set a new instance
            IStreamWrapper sw = new IStreamWrapper(iStream);
            byte[] data = new byte[1];
            sw.Read(data, 0, 1);


            //ManagedIStream usage
            Stream ms = null; // set a new stream instance
            ManagedIStream managedIStream = new ManagedIStream(ms); // ManagedIStream class implements IStream interface.

Download Files:
CSharpExamples-Managed IStream and IStreamWrapper.RAR

13 Haz

C# Copy Stream Examples

Best ways to copy between two stream are like below. There is no special method for .NET Framework 3.5 and before. We writes a sample method using Read and Write methods in Stream class. But .NET Framework 4.0 and later, some methods are added to framework api.

        /// 
        /// code examples for .NET 3.5 and before
        /// 
        /// 
        /// 
        public static void CopyStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[32768];
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);
            }
        }

From .NET 4.0 on, there’s is the Stream.CopyTo method

            Stream inputStream = null;
            Stream outputStream = null;
            inputStream.CopyTo(outputStream);