Monday 3 November 2014

Common Functions




This function will get File Upload Control as input and save the file with adding time stamp before the file name and returns the file name.

public string UploadFile(FileUpload fup)
    {
        string FileName,TimeStamp;
        TimeStamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        fup.SaveAs(HttpContext.Current.Server.MapPath("~/image/" + TimeStamp + "_" + fup.PostedFile.FileName));
        FileName = TimeStamp + "_" + fup.PostedFile.FileName;
        return FileName;
    }

This function will 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 Change Validators to Image

private void SetValidatorDisplay()
        {
            foreach (var validator in Page.Validators)
            {
                var reqvalidator = (validator as BaseValidator);
                if (reqvalidator != null)
                {
                    reqvalidator.Display = ValidatorDisplay.Dynamic;
                    if (!string.IsNullOrEmpty(reqvalidator.ErrorMessage))
                    {
                        if (!reqvalidator.ErrorMessage.Contains("<img"))
                        {
                            reqvalidator.ToolTip = reqvalidator.ErrorMessage;
                            string imagePath = General.VALIDATIONICON; // ADD VALIDATION IMAGE ICON TO DISPLAY VALIDATIONS
                           
                            reqvalidator.Text = @"<img src='" + imagePath + "' alt='" + reqvalidator.ToolTip + "'></img>";
                        }
                    }
                }
            }
        }


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);
        }
    }
 

Project Session Class to Manage Session in the Project

This Class is used to manage sessions in the system.

public class ProjectSession
    {
        public static long UserID
        {
            get
            {
                if ((HttpContext.Current.Session["UserID"]) == null)
                    return 0;
                else
                    return (long)HttpContext.Current.Session["UserID"];
            }
            set { HttpContext.Current.Session["UserID"] = value; }
        }
        public static string UserName
        {
            get
            {
                if ((HttpContext.Current.Session["UserName"]) == null)
                    return "";
                else
                    return (string)HttpContext.Current.Session["UserName"];
            }
            set { HttpContext.Current.Session["UserName"] = value; }
        }
        public static string LoginId
        {
            get
            {
                if ((HttpContext.Current.Session["LoginId"]) == null)
                    return "";
                else
                    return (string)HttpContext.Current.Session["LoginId"];
            }
            set { HttpContext.Current.Session["LoginId"] = value; }
        }
        public static long RoleID
        {
            get
            {
                if ((HttpContext.Current.Session["RoleID"]) == null)
                    return 0;
                else
                    return (long)HttpContext.Current.Session["RoleID"];
            }
            set { HttpContext.Current.Session["RoleID"] = value; }
        }
}