Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, 3 November 2014

Encrypt or Decrypt the Data

Include the following class to manage cryptography in the project.

public class EncryptDecrypt
    {       
        private const string initVector = "tu89geji340t89u2";
        private const int keysize = 256;

        public static string Encrypt(string Text, string Key)
        {
            byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(Text);
            PasswordDeriveBytes password = new PasswordDeriveBytes(Key, null);
            byte[] keyBytes = password.GetBytes(keysize / 8);
            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptoStream.FlushFinalBlock();
            byte[] Encrypted = memoryStream.ToArray();
            memoryStream.Close();
            cryptoStream.Close();
            return Convert.ToBase64String(Encrypted);
        }

        public static string Decrypt(string EncryptedText, string Key)
        {
            byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
          //  byte[] DeEncryptedText = Convert.FromBase64String(EncryptedText);
            EncryptedText = EncryptedText.Replace(" ", "+");
            byte[] DeEncryptedText = Convert.FromBase64String(EncryptedText);
            PasswordDeriveBytes password = new PasswordDeriveBytes(Key, null);
            byte[] keyBytes = password.GetBytes(keysize / 8);
            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;
            ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
            MemoryStream memoryStream = new MemoryStream(DeEncryptedText);
            CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
            byte[] plainTextBytes = new byte[DeEncryptedText.Length];
            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            memoryStream.Close();
            cryptoStream.Close();
            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
        }
    }
 

Saturday, 9 November 2013

Common Functions of C#

Common required functions of C#

To Convert Date to String and vice e versa.

public static string ToDate2String(DateTime dt)
    {
        string DateFormat = "MM/dd/yyyy";
        return dt.ToString(DateFormat);
    }
public static DateTime ToString2Date(string dt)
    {
        string DateFormat = "MM/dd/yyyy";
        return DateTime.ParseExact(dt, DateFormat, CultureInfo.InvariantCulture);
    }



To Convert List to DataTable

public static DataTable ListToDataTable<T>(IEnumerable<T> list)
    {
        DataTable table = new DataTable();
        if (list != null)
        {
            PropertyDescriptorCollection properties =
                TypeDescriptor.GetProperties(typeof(T));
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(
                    prop.Name,
                    (prop.PropertyType.IsGenericType &&
                     prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                        ? Nullable.GetUnderlyingType(prop.PropertyType)
                        : prop.PropertyType
                    );
            foreach (T item in list)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
        }
        return table;
    }



To Write the Error of the Project.

    public static void WriteError(Exception ex)
    {
        string err = null;
        try
        {
            string path = "~/ErrorLogs/" + DateTime.Today.ToString("dd-MMM-yy") + ".txt";
            if (!File.Exists(HttpContext.Current.Server.MapPath(path)))
                File.Create(HttpContext.Current.Server.MapPath(path)).Close();
            using (StreamWriter w = File.AppendText(HttpContext.Current.Server.MapPath(path)))
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                w.WriteLine("\r\nLog Entry : ");
                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                err = "Error in: " + HttpContext.Current.Request.Url.ToString() + Environment.NewLine +
                           "File Name : " + trace.GetFrame(0).GetFileName() + Environment.NewLine +
                           "Line : " + trace.GetFrame(0).GetFileLineNumber() + Environment.NewLine +
                           "Column: " + trace.GetFrame(0).GetFileColumnNumber() + Environment.NewLine +
                           "Error Message:" + ex.Message + Environment.NewLine +
                           "TargetSite:" + ex.TargetSite.ToString();
                w.WriteLine(err);
                w.WriteLine("__________________________");
                w.Flush();
                w.Close();
            }
        }
        catch (Exception exc)
        {
            WriteError(exc);
        }
    }