13 Haz

Set the GDAL_DATA Environment Variable Programmatically in C#

You can set programmatically to the GDAL_DATA environment variable as follow.

Sample code:


string path = @"C:\gdal\";
SetValueNewVariable("GDAL_DATA", path + "\\data");
SetValueNewVariable("GEOTIFF_CSV", path + "\\data");
SetValueNewVariable("GDAL_DRIVER_PATH", path + "\\gdalplugins");

private static void SetValueNewVariable(string var, string value)
{
    if (System.Environment.GetEnvironmentVariable(var) == null)
       System.Environment.SetEnvironmentVariable(var, value);
}

13 Haz

Zip and Unzip Files Programmatically in C#

There are many zip library which used to be popular. I will show you two of them.(7Zip and .NET ZipArchive)
7-Zip is a open source file archiver with a high compression ratio. Most of the source code is under the GNU LGPL license.
For more information:
http://www.7-zip.org/

You can use 7-zip library for zip and unzip to the files as follow:


            //Firstly, you should set 7z.dll path.
            SevenZipExtractor.SetLibraryPath(@"C:\7z.dll");

            //Test Code:
            string[] filePaths = new string[]
            {
                @"C:\Folder1\file1.jpg",
                @"C:\Folder1\file2.txt",
                @"C:\Folder1\file1.png",
            };
            ZipFiles(filePaths, @"C:\zippedFile2.zip");

            ZipFolder(@"C:\Folder1", @"C:\zippedFile1.zip", "password");
            Unzip(@"C:\zippedFile1.zip", @"C:\Folder2", "password");

Sample methods(using 7-Zip):


        public void ZipFiles(string[] filePaths, string outputFilePath, string password = null)
        {
            var tmp = new SevenZipCompressor();
            tmp.ScanOnlyWritable = true;
            tmp.CompressFilesEncrypted(outputFilePath, password, filePaths);
        }

        public void ZipFolder(string folderPath, string outputFilePath, string password = null)
        {
            var tmp = new SevenZipCompressor();
            tmp.ScanOnlyWritable = true;
            tmp.CompressDirectory(folderPath, outputFilePath, password);
        }

        public void Unzip(string zippedFilePath, string outputFolderPath, string password = null)
        {
            SevenZipExtractor tmp = null;
            if (!string.IsNullOrEmpty(password))
                tmp = new SevenZipExtractor(zippedFilePath, password);
            else
                tmp = new SevenZipExtractor(zippedFilePath);

            tmp.ExtractArchive(outputFolderPath);
        }

In .NET framework 4.5, System.IO.Compression namespace get some new classes that allow you to work with zip files programmatically.
Sample code:


            //Zip files
            ZipArchive zip = ZipFile.Open(filePath, ZipArchiveMode.Create);
            foreach (string file in filePaths)
            {
                zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
            }
            zip.Dispose();

            //Unzip
            ZipFile.CreateFromDirectory(folderPath, zippedFilePath);
            ZipFile.ExtractToDirectory(zippedFilePath, outputFolderPath);
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