using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;

public class CommonFunctions : IDisposable
{
    public CommonFunctions()
    {

    }
    //Methods
    #region Encryption Methods
    /// <summary>
    ///  function to convert a string to MD5 encrypted format with a salt. 
    /// </summary>
    /// <param name="sPassword"></param>
    /// <returns></returns>
    public static string Encrypt(string toEncrypt, bool useHashing)
    {
        byte[] keyArray;
        //toEncrypt = toEncrypt.Replace("/", "-!*!*!*-").Replace("&", "-!a!a!a-").Replace("+", "-!b!b!b-").ToString().Trim();
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

        System.Configuration.AppSettingsReader settingsReader =
                                            new AppSettingsReader();
        // Get the key from config file

        string key = (string)settingsReader.GetValue("SecurityKey",
                                                         typeof(String));
        //System.Windows.Forms.MessageBox.Show(key);
        //If hashing use get hashcode regards to your key
        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            //Always release the resources and flush data
            // of the Cryptographic service provide. Best Practice

            hashmd5.Clear();
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        tdes.Key = keyArray;
        //mode of operation. there are other 4 modes.
        //We choose ECB(Electronic code Book)
        tdes.Mode = CipherMode.ECB;
        //padding mode(if any extra byte added)

        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateEncryptor();
        //transform the specified region of bytes array to resultArray
        byte[] resultArray =
          cTransform.TransformFinalBlock(toEncryptArray, 0,
          toEncryptArray.Length);
        //Release resources held by TripleDes Encryptor
        tdes.Clear();
        //Return the encrypted data into unreadable string format
        return Convert.ToBase64String(resultArray, 0, resultArray.Length).Replace("/", "-!*!*!*-").Replace("&", "-!a!a!a-").Replace("+", "-!b!b!b-").ToString().Trim(); ;
    }

    internal static string CheckUploadFileExtFileformat(IEnumerable<HttpPostedFileBase> fileuploadimages, string v)
    {
        throw new NotImplementedException();
    }

    public static string Decrypt(string cipherString, bool useHashing)
    {
        byte[] keyArray;
        cipherString = cipherString.Replace("-!*!*!*-", "/").Replace("-!a!a!a-", "&").Replace("-!b!b!b-", "+").ToString().Trim();
        //get the byte code of the string

        byte[] toEncryptArray = Convert.FromBase64String(cipherString);

        System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
        //Get your key from config file to open the lock!
        string key = (string)settingsReader.GetValue("SecurityKey",
                                                     typeof(String));

        if (useHashing)
        {
            //if hashing was used get the hash code with regards to your key
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            //release any resource held by the MD5CryptoServiceProvider

            hashmd5.Clear();
        }
        else
        {
            //if hashing was not implemented get the byte code of the key
            keyArray = UTF8Encoding.UTF8.GetBytes(key);
        }

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        tdes.Key = keyArray;
        //mode of operation. there are other 4 modes. 
        //We choose ECB(Electronic code Book)

        tdes.Mode = CipherMode.ECB;
        //padding mode(if any extra byte added)
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(
                             toEncryptArray, 0, toEncryptArray.Length);
        //Release resources held by TripleDes Encryptor                
        tdes.Clear();
        //return the Clear decrypted TEXT
        return UTF8Encoding.UTF8.GetString(resultArray);


    }
    #endregion
    #region Injection Methods
    public static bool CheckUrl(string Url)
    {
        return false;
    }
    //
    public static bool XssAttack(string Url)
    {

        string[] exp = new string[] { "<", ">", "alert","script","<embed","<form","iframe","<object","<layer"};
        bool result = true;
        bool result1 = true;
        if (Url != null && Url != "")
        {
            foreach (string c in exp)
            {
                result = Regex.IsMatch(Url, c);
                result1 = Regex.IsMatch(Url, HttpUtility.UrlEncode(c));
                if (result || result1)
                {
                    return true;
                }
            }
        }
        return false;
        
    }

    public static bool CheckSpecialCharAliasString(string StringText)
    {


        Match m = Regex.Match(StringText, @"[^a-zA-Z0-9-]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        while (m.Success)
        {
            return false;
        }
        return true;
    }

    public static bool AliasStringDiscussionTitle(string StringText)
    {

        Match m = Regex.Match(StringText, @"[^a-zA-Z0-9- ()*$!@_\"":.]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        while (m.Success)
        {
            return false;
        }
        return true;
    }

    public static bool CheckSpecialCharQueryString(string StringText)
    {
        Match m = Regex.Match(StringText, @"[^a-zA-Z0-9- ]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        while (m.Success)
        {
            return false;
        }
        return true;
    }
    public static string ReplaceforAlias(string StringText)
    {
        StringText = Regex.Replace(StringText.ToLower().Replace(" ", "-").Replace("--", "-"), @"[^a-zA-Z0-9-]+", "");
        return StringText;

    }
    public static string ReplaceText(string StringText)
    {

        StringText = StringText.Replace("'", "").Replace("&", "").Replace("*", "").Replace("^", "").Replace("<", "").Replace(">", "").Replace(";", "").Replace("?", "").Replace("=", "").Replace("_", "").Replace("#", "").Replace("--", "").Replace("!", "").Replace("script", "");
        return StringText;

    }
    public static string ReplaceurlText(string StringText)
    {

        StringText = StringText.Replace("'", "").Replace("&", "").Replace("*", "").Replace("^", "").Replace("<", "").Replace(">", "").Replace(";", "").Replace("?", "").Replace("=", "").Replace("#", "").Replace("--", "").Replace("!", "").Replace("script", "");
        return StringText;

    }
    public static string ReplaceSpecialCharTextBoxString(string StringText)
    {

        StringText = StringText.Replace("<", "").Replace("/", "").Replace(">", "").Replace(";", "").Replace("'", "").Replace("--", "").Replace("=", "");
        return StringText;

    }
    public static bool Checkdigit(string StringText)
    {
        Match m = Regex.Match(StringText, @"[^0-9]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        while (m.Success)
        {
            return false;
        }
        return true;
    }
    public static bool Checkcharacter(string StringText)
    {
        Match m = Regex.Match(StringText, @"[^a-zA-Z]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        while (m.Success)
        {
            return false;
        }
        return true;
    }
    public static bool Checknumeric(string StringText)
    {
        Match m = Regex.Match(StringText, @"[^0-9]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        while (m.Success)
        {
            return false;
        }
        return true;
    }
    public static bool Checklink(string link)
    {
        return Uri.IsWellFormedUriString(link, UriKind.RelativeOrAbsolute);
    }
    public static bool CheckSpecialCharFileNameString(string StringText)
    {
        var isValid = !string.IsNullOrEmpty(StringText) &&
              StringText.IndexOfAny(Path.GetInvalidFileNameChars()) < 0;
        return isValid;
    }
    public static bool CheckSpecialCharTextBoxString(string StringText)
    {
        string[] exp = new string[] { "<", "/", ">", ";", "'", "--", "=" };
        bool result = false;
        if (StringText != null && StringText != "")
        {
            foreach (string c in exp)
            {
                result = Regex.IsMatch(StringText, c);
                if (result)
                {
                    return false;
                }
            }
        }
        return true;

        // Match m = Regex.Match(StringText, @"[^a-zA-Z0-9\s.-@&-,]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        //while (m.Success)
        //{
        //    return false;
        //}

    }
    public static bool CheckSpecialCharTitle(string StringText)
    {
        string[] exp = new string[] { "<", ">", ";", "--", "=" };
        bool result = false;
        if (StringText != null && StringText != "")
        {
            foreach (string c in exp)
            {
                result = Regex.IsMatch(StringText, c);
                if (result)
                {
                    return false;
                }
            }
        }
        return true;

        // Match m = Regex.Match(StringText, @"[^a-zA-Z0-9\s.-@&-,]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        //while (m.Success)
        //{
        //    return false;
        //}

    }

    //public static bool CheckSpecialCharTextBoxString(string StringText)
    //{

    //    Match m = Regex.Match(StringText, @"[^a-zA-Z0-9\s.,-@&-]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    //   while (m.Success)
    //   {
    //       return false;
    //   }
    //   return true;
    //}

    public static bool CheckSpecialCharTextAreaString(string StringText)
    {
        if (StringText != null && StringText != "")
        {
            if (

                         StringText.Contains("<script") ||
                StringText.Contains("xp_") ||
                StringText.Contains(";--") ||
                StringText.Contains("--;") ||
                StringText.Contains("@@") ||
                StringText.Contains("/*") ||
                StringText.Contains("*/") ||
                StringText.Contains("<applet") ||
                StringText.Contains("<body") ||
                StringText.Contains("<embed") ||
                StringText.Contains("<layer") ||
                StringText.Contains("<ilayer") ||
                StringText.Contains("<object") ||
                StringText.Contains("<meta") ||
                StringText.Contains("<frame"))
            { return false; }
            else
            { return true; }
        }
        else { return true; }

    }
    public static bool CheckSpecialCharTextAreaSEOOther(string StringText)
    {

        if (
            StringText.Contains("xp_") ||
            StringText.Contains(";--") ||
            StringText.Contains("--;") ||
            StringText.Contains("@@") ||
            StringText.Contains("/*") ||
            StringText.Contains("*/") ||
            StringText.Contains("<applet") ||
            StringText.Contains("<body") ||
            StringText.Contains("<embed") ||
            StringText.Contains("<layer") ||
            StringText.Contains("<ilayer") ||
            StringText.Contains("<object") ||
            StringText.Contains("<frame"))
        { return false; }
        else
        { return true; }

    }
    public static bool CheckCertificteSpecialCharTextAreaString(string StringText)
    {

        if (

            StringText.Contains("xp_") ||
            StringText.Contains(";--") ||
            StringText.Contains("--;") ||
            StringText.Contains("@@") ||
            StringText.Contains("/*") ||
            StringText.Contains("*/") ||
            StringText.Contains("<applet") ||
            StringText.Contains("<body") ||
            StringText.Contains("<embed") ||
            StringText.Contains("<layer") ||
            StringText.Contains("<ilayer") ||
            StringText.Contains("<object") ||
            StringText.Contains("<meta") ||
            StringText.Contains("<frame"))
        { return false; }
        else
        { return true; }

    }

    #endregion

    #region input Methods
    public static string CheckUploadFileExt(FileUpload fileupload, string format)
    {
        if (fileupload.PostedFile.ContentLength == 0)
        {
            return "Invalid file content!";
        }
        string UploadfileName = fileupload.PostedFile.FileName;
        string FileExt = System.IO.Path.GetExtension(UploadfileName);
        if (!format.Contains(FileExt.ToLower()))
        {
            return "File is not in currect format please upload " + format + " file!";
        }
        try
        {
            if (fileupload.PostedFile.ContentLength <= 204800000)
            {

                return "success";
            }
            else
            {
                return "Unable to upload,file exceeds maximum limit";
            }
        }
        catch (UnauthorizedAccessException ex)
        {
            return ex.Message + "Permission to upload file denied";
        }
    }
    [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
    private extern static System.UInt32 FindMimeFromData(System.UInt32 pBC,
[MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,
[MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
System.UInt32 cbSize, [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,
System.UInt32 dwMimeFlags,
out System.UInt32 ppwzMimeOut,
System.UInt32 dwReserverd);
    public static string CheckUploadDocumnetFileExt(HttpPostedFileBase fileupload, string format)
    {
        if (fileupload == null)
        {
            return "Invalid file content!";
        }
        string UploadfileName = fileupload.FileName;
        byte[] document = new byte[fileupload.ContentLength];
        fileupload.InputStream.Read(document, 0, fileupload.ContentLength);
        System.UInt32 mimetype;
        FindMimeFromData(0, null, document, 256, null, 0, out mimetype, 0);
        System.IntPtr mimeTypePtr = new IntPtr(mimetype);
        string mime = Marshal.PtrToStringUni(mimeTypePtr);
        Marshal.FreeCoTaskMem(mimeTypePtr);
        string cmime = GetMimeTypeByWindowsRegistry(format);

        if (mime != cmime)
        {
            //  file is Invalid  
            return "Invalid File Format";

        }
        string FileExt = System.IO.Path.GetExtension(UploadfileName);
        if (!format.Contains(FileExt.ToLower()))
        {
            return "File is not in currect format please upload " + format + " file!";
        }
        try
        {
            if (fileupload.ContentLength <= 5000000)
            {

                return "success";
            }
            else
            {
                return "Unable to upload,file exceeds maximum limit";
            }
        }
        catch (UnauthorizedAccessException ex)
        {
            return ex.Message + "Permission to upload file denied";
        }
    }
    public static string GetMimeTypeByWindowsRegistry(string fileNameOrExtension)
    {
        string mimeType = "application/unknown";
        string ext = (fileNameOrExtension.Contains(".")) ? System.IO.Path.GetExtension(fileNameOrExtension).ToLower() : "." + fileNameOrExtension;
        Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
        if (regKey != null && regKey.GetValue("Content Type") != null) mimeType = regKey.GetValue("Content Type").ToString();
        return mimeType;
    }
    public static string CheckUploadFileExt(HttpPostedFileBase fileupload, string format)
    {
        if (fileupload == null)
        {
            return "Invalid file content!";
        }
        string UploadfileName = fileupload.FileName;
        string FileExt = System.IO.Path.GetExtension(UploadfileName);
        if (!format.Contains(FileExt.ToLower()))
        {
            return "File is not in currect format please upload " + format + " file!";
        }
        try
        {
            if (fileupload.ContentLength <= 204800000)
            {

                return "success";
            }
            else
            {
                return "Unable to upload,file exceeds maximum limit";
            }
        }
        catch (UnauthorizedAccessException ex)
        {
            return ex.Message + "Permission to upload file denied";
        }
    }

    public static string CheckUploadFileDimention(FileUpload fileupload, int width, int height)
    {

        try
        {
            string UploadedImageType = fileupload.PostedFile.ContentType.ToString().ToLower();
            string UploadedImageFileName = fileupload.PostedFile.FileName;

            System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(fileupload.PostedFile.InputStream);

            float UploadedImageWidth = UploadedImage.PhysicalDimension.Width;
            float UploadedImageHeight = UploadedImage.PhysicalDimension.Height;

            if (UploadedImageWidth != width || UploadedImageHeight != height)
            {
                return "Image size should be " + width.ToString() + "*" + height.ToString() + "!";
            }
            else
            {
                return "";
            }
        }
#pragma warning disable CS0168 // The variable 'ex' is declared but never used
        catch (Exception ex)
#pragma warning restore CS0168 // The variable 'ex' is declared but never used
        {
            return "Please contact Admin";
        }


    }
    public static string CheckUploadFileDimention(HttpPostedFileBase fileupload, int width, int height)
    {

        try
        {
            string UploadedImageType = fileupload.ContentType.ToString().ToLower();
            string UploadedImageFileName = fileupload.FileName;

            System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(fileupload.InputStream);

            float UploadedImageWidth = UploadedImage.PhysicalDimension.Width;
            float UploadedImageHeight = UploadedImage.PhysicalDimension.Height;

            if (UploadedImageWidth != width || UploadedImageHeight != height)
            {
                return "Image size should be " + width.ToString() + "*" + height.ToString() + "!";
            }
            else
            {
                return "";
            }
        }
#pragma warning disable CS0168 // The variable 'ex' is declared but never used
        catch (Exception ex)
#pragma warning restore CS0168 // The variable 'ex' is declared but never used
        {
            return "Please contact Admin";
        }


    }
    public static string CheckUploadMaxFileDimention(FileUpload fileupload, int width, int height)
    {

        try
        {
            string UploadedImageType = fileupload.PostedFile.ContentType.ToString().ToLower();
            string UploadedImageFileName = fileupload.PostedFile.FileName;

            System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(fileupload.PostedFile.InputStream);

            float UploadedImageWidth = UploadedImage.PhysicalDimension.Width;
            float UploadedImageHeight = UploadedImage.PhysicalDimension.Height;

            if (UploadedImageWidth > width || UploadedImageHeight > height)
            {
                return "Image size should be less than  " + width.ToString() + "*" + height.ToString() + "!";
            }
            else
            {
                return "";
            }
        }
#pragma warning disable CS0168 // The variable 'ex' is declared but never used
        catch (Exception ex)
#pragma warning restore CS0168 // The variable 'ex' is declared but never used
        {
            return "Please contact Admin";
        }


    }
    public static bool CheckInteger(string Recordid)
    {
        int number1 = 0;
        bool result = int.TryParse(Recordid, out number1);
        return result;
    }
    public static bool IsValidEmail(string email)
    {
        try
        {
            var addr = new System.Net.Mail.MailAddress(email);
            return addr.Address == email;
        }
        catch
        {
            return false;
        }
    }
    public static DataTable ConvertxmlToDataTable(String xmldata)
    {
        DataTable dt = new DataTable();
        if (xmldata.Length > 20)
        {
            DataSet ds = new DataSet();
            StringReader reader = new StringReader(xmldata);
            ds.ReadXml(reader);
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }
        }
        return dt;
    }
    public static string UniqueValue(string CommonValue)
    {
        Random random = new Random();
        int randomnumber = random.Next(0, 100);
        string UniqueValue = CommonValue.ToString().Trim() + DateTime.Now.Day.ToString().Trim() + DateTime.Now.Month.ToString().Trim() + DateTime.Now.Year.ToString().Trim() + DateTime.Now.Hour.ToString().Trim() + DateTime.Now.Minute.ToString().Trim() + DateTime.Now.Second.ToString().Trim() + randomnumber.ToString().Trim();
        return UniqueValue;
    }
    #endregion
    public static void ResizeImage(string sourcePath, string targetPath, string newFilename, string originalFilename, int newWidth, int newHeight)
    {
        using (var image = System.Drawing.Image.FromFile(sourcePath + originalFilename))
        {
            //var newWidth = (int)(image.Width * scaleFactor);
            //var newHeight = (int)(image.Height * scaleFactor);
            var thumbnailImg = new Bitmap(newWidth, newHeight);
            var thumbGraph = Graphics.FromImage(thumbnailImg);
            thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
            thumbGraph.DrawImage(image, imageRectangle);
            thumbnailImg.Save(targetPath + newFilename, image.RawFormat);
        }
    }
    public static void resizeImageCrop(string path, string newpath, string newFilename, string originalFilename, int canvasWidth, int canvasHeight)
    {
        System.Drawing.Image image = System.Drawing.Image.FromFile(path + originalFilename);
        int originalWidth = Convert.ToInt32(image.Width);
        int originalHeight = Convert.ToInt32(image.Height);
        System.Drawing.Image thumbnail =
            new Bitmap(canvasWidth, canvasHeight); // changed parm names
        System.Drawing.Graphics graphic =
                     System.Drawing.Graphics.FromImage(thumbnail);

        graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphic.SmoothingMode = SmoothingMode.HighQuality;
        graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphic.CompositingQuality = CompositingQuality.HighQuality;

        /* ------------------ new code --------------- */

        // Figure out the ratio
        double ratioX = (double)canvasWidth / (double)originalWidth;
        double ratioY = (double)canvasHeight / (double)originalHeight;
        // use whichever multiplier is smaller
        double ratio = ratioX < ratioY ? ratioX : ratioY;

        // now we can get the new height and width
        int newHeight = Convert.ToInt32(originalHeight * ratio);
        int newWidth = Convert.ToInt32(originalWidth * ratio);

        // Now calculate the X,Y position of the upper-left corner 
        // (one of these will always be zero)
        int posX = Convert.ToInt32((canvasWidth - (originalWidth * ratio)) / 2);
        int posY = Convert.ToInt32((canvasHeight - (originalHeight * ratio)) / 2);

        graphic.Clear(Color.White); // white padding
        graphic.DrawImage(image, posX, posY, newWidth, newHeight);

        /* ------------- end new code ---------------- */

        System.Drawing.Imaging.ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
        EncoderParameters encoderParameters = Encoderparameter();
        thumbnail.Save(newpath + newFilename, info[1], encoderParameters);
    }
    public static EncoderParameters Encoderparameter()
    {
        EncoderParameters parameters = new EncoderParameters(3);
        parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 24L);
        parameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
        parameters.Param[2] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionLZW);
        return parameters;
    }
    public static bool IsLocalUrl(string url)
    {
        return !url.StartsWith("http:", StringComparison.OrdinalIgnoreCase)
                    && !url.StartsWith("https:", StringComparison.OrdinalIgnoreCase)
                    && Uri.IsWellFormedUriString(url, UriKind.Relative);
    }
    public static ImageCodecInfo GetEncoderInfo(String mimeType)
    {
        int j;
        ImageCodecInfo[] encoders;
        encoders = ImageCodecInfo.GetImageEncoders();
        for (j = 0; j < encoders.Length; ++j)
        {
            if (encoders[j].FilenameExtension.ToLower().Contains(mimeType))
                return encoders[j];
        }
        return null;
    }

    public static bool checkExistance(string connString, CommandType cmdType, string cmdText, params SqlParameter[] cmdParameters)
    {
        bool isExists = false;
        SqlCommand cmd = new SqlCommand();
        SqlConnection conn = new SqlConnection(connString);
        try
        {
            PrepareCommand(cmd, conn, cmdType, cmdText, cmdParameters);
            SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            cmd.Parameters.Clear();
            if (sdr.HasRows)
            {
                isExists = true;
            }
            //sdr.Close();
        }
        catch
        {
            // conn.Close();
            //throw;
        }
        return isExists;
    }



    #region P R E P A R E  C O M M A N D

    /// <summary>
    /// Prepare a command for execution
    /// </summary>
    /// <param name="cmd">SqlCommand object</param>
    /// <param name="conn">SqlConnection object</param>
    /// <param name="cmdType">ComandType object(stored procedure or text)</param>
    /// <param name="cmdText">SqlParameters to use in the command</param>
    /// <param name="cmdParameters"></param>
    private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, CommandType cmdType, string cmdText, params SqlParameter[] cmdParameters)
    {
        if (conn.State != ConnectionState.Open)
            conn.Open();
        cmd.Connection = conn;
        cmd.CommandType = cmdType;
        cmd.CommandText = cmdText;
        if (cmdParameters != null)
        {
            foreach (SqlParameter param in cmdParameters)
            {
                cmd.Parameters.Add(param);
            }
        }
        conn.Close();
    }




    #endregion

    public static string getTimeAgo(string strDate)
    {
        string strTime = string.Empty;
        if (IsDate(Convert.ToString(strDate)))
        {
            TimeSpan t = DateTime.Now - Convert.ToDateTime(strDate);
            double deltaSeconds = t.TotalSeconds;

            double deltaMinutes = deltaSeconds / 60.0f;
            int minutes;

            if (deltaSeconds < 5)
            {
                return "Just now";
            }
            else if (deltaSeconds < 60)
            {
                return Math.Floor(deltaSeconds) + " seconds ago";
            }
            else if (deltaSeconds < 120)
            {
                return "A minute ago";
            }
            else if (deltaMinutes < 60)
            {
                return Math.Floor(deltaMinutes) + " minutes ago";
            }
            else if (deltaMinutes < 120)
            {
                return "An hour ago";
            }
            else if (deltaMinutes < (24 * 60))
            {
                minutes = (int)Math.Floor(deltaMinutes / 60);
                return minutes + " hours ago";
            }
            else if (deltaMinutes < (24 * 60 * 2))
            {
                return "Yesterday";
            }
            else if (deltaMinutes < (24 * 60 * 7))
            {
                minutes = (int)Math.Floor(deltaMinutes / (60 * 24));
                return minutes + " days ago";
            }
            else if (deltaMinutes < (24 * 60 * 14))
            {
                return "Last week";
            }
            else if (deltaMinutes < (24 * 60 * 31))
            {
                minutes = (int)Math.Floor(deltaMinutes / (60 * 24 * 7));
                return minutes + " weeks ago";
            }
            else if (deltaMinutes < (24 * 60 * 61))
            {
                return "Last month";
            }
            else if (deltaMinutes < (24 * 60 * 365.25))
            {
                minutes = (int)Math.Floor(deltaMinutes / (60 * 24 * 30));
                return minutes + " months ago";
            }
            else if (deltaMinutes < (24 * 60 * 731))
            {
                return "Last year";
            }

            minutes = (int)Math.Floor(deltaMinutes / (60 * 24 * 365));
            return minutes + " years ago";
        }
        else
        {
            return "";
        }
    }
    public static bool IsDate(string o)
    {
        DateTime tmp;
        return DateTime.TryParse(o, out tmp);
    }
    public static string RemoveQueryStringByKey(string url, params string[] key)
    {
        var uri = new Uri(url);

        // this gets all the query string key value pairs as a collection
        var newQueryString = HttpUtility.ParseQueryString(uri.Query);

        // this removes the key if exists
        for (int i = 0; i < key.Length; i++)
        {
            newQueryString.Remove(key[i]);
        }

        // this gets the page path from root without QueryString
        string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path);

        return newQueryString.Count > 0
            ? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
            : pagePathWithoutQueryString;
    }
    public static string RemoveQueryString(string url)
    {
        var uri = new Uri(url);
        // this gets the page path from root without QueryString
        string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path);
        return pagePathWithoutQueryString;
    }
    public static IpProperties IPDetails(string ipAddress)
    {
        string ipResponse = IPRequestHelper("http://ip-api.com/xml/" + ipAddress);
        using (TextReader sr = new StringReader(ipResponse))
        {
            using (System.Data.DataSet dataBase = new System.Data.DataSet())
            {
                IpProperties ipProperties = new IpProperties();
                dataBase.ReadXml(sr);
                if (dataBase.Tables[0].Rows[0][0].ToString() != "fail")
                {
                    ipProperties.Status = dataBase.Tables[0].Rows[0][0].ToString();
                    ipProperties.Country = dataBase.Tables[0].Rows[0][1].ToString();
                    ipProperties.CountryCode = dataBase.Tables[0].Rows[0][2].ToString();
                    ipProperties.Region = dataBase.Tables[0].Rows[0][3].ToString();
                    ipProperties.RegionName = dataBase.Tables[0].Rows[0][4].ToString();
                    ipProperties.City = dataBase.Tables[0].Rows[0][5].ToString();
                    ipProperties.Zip = dataBase.Tables[0].Rows[0][6].ToString();
                    ipProperties.Lat = dataBase.Tables[0].Rows[0][7].ToString();
                    ipProperties.Lon = dataBase.Tables[0].Rows[0][8].ToString();
                    ipProperties.TimeZone = dataBase.Tables[0].Rows[0][9].ToString();
                    ipProperties.ISP = dataBase.Tables[0].Rows[0][10].ToString();
                    ipProperties.ORG = dataBase.Tables[0].Rows[0][11].ToString();
                    ipProperties.AS = dataBase.Tables[0].Rows[0][12].ToString();
                    ipProperties.Query = dataBase.Tables[0].Rows[0][13].ToString();
                }

                return ipProperties;
            }
        }
    }
    public static string IPRequestHelper(string url)
    {
        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();

        StreamReader responseStream = new StreamReader(objResponse.GetResponseStream());
        string responseRead = responseStream.ReadToEnd();

        responseStream.Close();
        //responseStream.Dispose();

        return responseRead;
    }
    public static string GetIP4Address()
    {
        System.Web.HttpContext context = System.Web.HttpContext.Current;
        String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (!string.IsNullOrEmpty(ip))
        {
            ip = ip.Split(',')[0];
        }
        else
        {
            ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }
        return ip;
    }
    public static T Deserialize<T>(string context)
    {
        string jsonData = context;

        //cast to specified objectType
        var obj = (T)new JavaScriptSerializer().Deserialize<T>(jsonData);
        return obj;
    }
    public static string EncodeTo64(string toEncode)
    {
        byte[] toEncodeAsBytes
              = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
        string returnValue
              = System.Convert.ToBase64String(toEncodeAsBytes);
        return returnValue;
    }
    public static string DecodeFrom64(string encodedData)
    {
        byte[] encodedDataAsBytes
            = System.Convert.FromBase64String(encodedData);
        string returnValue =
           System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
        return returnValue;
    }
    public static int Email_Send(string subject, string mailtoCollection, string mailbody)
    {
        MailMessage Msg;
        int i = 0;
        using (Msg = new MailMessage())
        {
            // Sender e-mail address.
            Msg.From = new MailAddress(ConfigurationManager.AppSettings["mailfrom"].ToString().Trim());
            // Recipient e-mail address.
            string[] mailtoCollection1 = mailtoCollection.Split(',');
            foreach (string str in mailtoCollection1)
            {
                Msg.To.Add(new MailAddress(str));
            }
            //Msg.To.Add((mailcollection));
            //Msg.To.Add(new MailAddress(mailto));
            //Msg.To.Add(new MailAddress("ajeetkumar.kumar36@gmail.com"));
            Msg.Subject = subject;
            Msg.Body = mailbody;
            Msg.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();

            smtp.Host = ConfigurationManager.AppSettings["smtp"].ToString().Trim();
            smtp.Port = Int32.Parse(ConfigurationManager.AppSettings["port"].ToString().Trim());
            //smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["mailfrom"].ToString().Trim(), ConfigurationManager.AppSettings["mailpassword"].ToString().Trim());
            //smtp.UseDefaultCredentials = false;
            smtp.EnableSsl = true;

   //         ServicePointManager.ServerCertificateValidationCallback =
   //delegate (object s, X509Certificate certificate,
   //         X509Chain chain, SslPolicyErrors sslPolicyErrors)
   //{ return true; };
   //         smtp.UseDefaultCredentials = false;
            try
            {
                smtp.Send(Msg);
                //Msg.Dispose();
                i = 1;

            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.ToString());
            }
            finally
            {

            }
            return i;
        }
    }
    public static string getadminemailid(int role)
    {
        string query = "select UserEmail from tblUserLogin where Role="+role+" and status='1'";
        DataLayer obj = DataLayer.Instance;
        DataTable dt = obj.SelectDatatable(query);
        string email = "";
        if (dt.Rows.Count > 0)
        {
            foreach (DataRow dr in dt.Rows)
            {
                email += dr["UserEmail"].ToString().Trim() + ",";
            }
            if (email.Length > 0)
            {
                email = email.Substring(0, email.Length - 1);
            }

        }
        return email;
    }
    public static string GetWord_Number(string text, int count)
    {
        string word = "";
        if (text != null)
        {
            string[] split = text.Split(' ');
            int wordlength = (split.Length > count) ? count : split.Length;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < wordlength; i++)
            {
                sb.Append(split[i].ToString().Trim() + " ");
            }
            word = sb.ToString().Substring(0, sb.ToString().Length - 1);
        }
        return word;
    }
    public static string GetWord_CharacterLength(string text, int count)
    {
        string word = "";
        if (text != null)
        {
            int charlength = (text.ToString().Trim().Length > count) ? count : text.Length;
            text = text.ToString().Trim().Substring(0, charlength).ToString().Trim();
            string[] split = text.Split(' ');
            int wordlength = (split.Length == 1) ? 1 : split.Length;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < wordlength; i++)
            {
                sb.Append(split[i].ToString().Trim() + " ");
            }
            word = sb.ToString().Substring(0, sb.ToString().Length - 1);
        }
        return word;
    }
    public static string GetFirstParagraph(string htmltext)
    {
        Match m = Regex.Match(htmltext, @"<p\s*(.+?)\s*>\s*(.+?)\s*</p>");
        if (m.Success)
        {
            string v1 = m.Groups[0].Value.ToString().Trim();
            int l1 = v1.IndexOf(">");
            int l2 = v1.IndexOf("</");
            string v2 = v1.Substring(l1 + 1, v1.Length - l1 - 5);
            //string v1= m.Groups[1].Value.ToString();
            //string v2 = m.Groups[2].Value.ToString();
            //string v3 = m.Captures[1].ToString().Trim();
            return v2;
        }
        else
        {
            return htmltext;
        }
    }
    public static string ShortenString_LastWord(string content, int maxlength)
    {
        if (content.Length <= maxlength)
            return content;
        // Remove the folder structure
        content = content.ToString().Trim();
        int lastIndex = content.LastIndexOf(" ");
        string LastWord = content.Substring(lastIndex + 1, content.Length - lastIndex - 1);
        int firstIndex = maxlength - LastWord.Length - 3;
        string FirstPartContent = content.Substring(0, firstIndex);
        string NewContent = FirstPartContent + "..." + LastWord;

        return NewContent;
    }
    public static string ShortenString(string content, int maxlength)
    {
        if (content.Length <= maxlength)
            return content;
        // Remove the folder structure
        content = content.ToString().Trim();
        int lastIndex = content.LastIndexOf(" ");
        string LastWord = content.Substring(lastIndex + 1, content.Length - lastIndex - 1);
        int firstIndex = maxlength;
        string FirstPartContent = content.Substring(0, firstIndex);
        string NewContent = FirstPartContent + "...";

        return NewContent;
    }
    public static string GetFirstParagraph1(string htmltext)
    {
        Match m = Regex.Match(htmltext, @"<p\s*(.+?)\s*>\s*(.+?)\s*</p>");
        if (m.Success)
        {
            return m.ToString();
        }
        else
        {
            return htmltext;
        }
    }

    public static string RemoveHtmlTag(string input)
    {
        return Regex.Replace(input, "<.*?>", String.Empty);
    }
    public static string ReadFromTxt(string path)
    {
        string footer = "";
        using (StreamReader sr = new StreamReader(path))
        {
            footer = sr.ReadToEnd();
        }
        return footer;

    }
    public static string ReplaceQueryStringParam(string currentPageUrl, string paramToReplace, string newValue)
    {
        string urlWithoutQuery = currentPageUrl.IndexOf('?') >= 0
            ? currentPageUrl.Substring(0, currentPageUrl.IndexOf('?'))
            : currentPageUrl;

        string queryString = currentPageUrl.IndexOf('?') >= 0
            ? currentPageUrl.Substring(currentPageUrl.IndexOf('?'))
            : null;

        var queryParamList = queryString != null
            ? HttpUtility.ParseQueryString(queryString)
            : HttpUtility.ParseQueryString(string.Empty);

        if (queryParamList[paramToReplace] != null)
        {
            queryParamList[paramToReplace] = newValue;
        }
        else
        {
            queryParamList.Add(paramToReplace, newValue);
        }
        return String.Format("{0}?{1}", urlWithoutQuery, queryParamList);
    }
    public static void Create_Directory(string path, string directoryname)
    {
        string targetpath1 = path + "/" + directoryname;
        DirectoryInfo ObjSearchDir = new DirectoryInfo(targetpath1);
        if (!ObjSearchDir.Exists)
        {
            Directory.CreateDirectory(targetpath1);
            SetAccessRights(directoryname, path);
        }
    }
    public static void SetAccessRights(string FileName, string FilePath)
    {
        string file = FilePath + "/" + FileName;
        FileSecurity fileSecurity = File.GetAccessControl(file);
        AuthorizationRuleCollection rules = fileSecurity.GetAccessRules(true, true, typeof(NTAccount));

        foreach (FileSystemAccessRule rule in rules)
        {
            string name = rule.IdentityReference.Value;

            if (rule.FileSystemRights != FileSystemRights.FullControl)
            {
                FileSecurity newFileSecurity = File.GetAccessControl(file);
                FileSystemAccessRule newRule = new FileSystemAccessRule(name, FileSystemRights.FullControl, AccessControlType.Allow);
                newFileSecurity.AddAccessRule(newRule);
                File.SetAccessControl(file, newFileSecurity);
            }
        }
    }
    public static void RemoveDirectories(string strpath)
    {
        //This condition is used to delete all files from the Directory
        foreach (string file in Directory.GetFiles(strpath))
        {
            File.Delete(file);
        }
        //This condition is used to check all child Directories and delete files
        foreach (string subfolder in Directory.GetDirectories(strpath))
        {
            RemoveDirectories(subfolder);
        }
        Directory.Delete(strpath);
    }
    public static DataTable GetExcelData(string strNewPath, string filename)
    {

        //Select Distint project from excelSheet 
        DataSet Ds = new DataSet();
        string strFileType = System.IO.Path.GetExtension(filename).ToString().ToLower();
        string connString = "";
        if (strFileType.Trim() == ".xls")
        {
            connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
        }
        else if (strFileType.Trim() == ".xlsx")
        {
            connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
        }

        OleDbConnection oconn = new OleDbConnection(connString);

        OleDbCommand ocmd = new OleDbCommand("select * from [Sheet1$]", oconn);
        OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ocmd);
        oconn.Open();

        ExcelAdapter.Fill(Ds);
        DataTable dt = Ds.Tables[0];
        oconn.Close();
        oconn.Dispose();
        return dt;
    }
    public static bool CreateSqlTable(DataTable dt, string tablename)
    {
        bool result = true;
        string strconnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString().Trim();
        string table = "";
        table += "IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + tablename + "]') AND type in (N'U'))";
        table += "BEGIN ";
        table += "create table " + tablename + "";
        table += "(";
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            if (i != dt.Columns.Count - 1)
                table += "[" + dt.Columns[i].ColumnName + "]" + " " + "varchar(1000)" + ",";
            else
                table += "[" + dt.Columns[i].ColumnName + "]" + " " + "varchar(1000)";
        }
        table += ") ";
        table += "END";

        InsertQuery(table, strconnection);
        dt = removeMisMatchColumn(dt, tablename);
        if (dt != null)
        {
            table += " truncate table " + tablename + " ";
            InsertQuery(table, strconnection);
            CopyData(strconnection, dt, tablename);
        }
        else
        {
            result = false;
        }
        return result;
    }
    public static void InsertQuery(string qry, string connection)
    {


        SqlConnection _connection = new SqlConnection(connection);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = qry;
        cmd.Connection = _connection;
        _connection.Open();
        cmd.ExecuteNonQuery();
        _connection.Close();
    }
    public static DataTable removeMisMatchColumn(DataTable csvTable, string tablename)
    {
        DataLayer obj = DataLayer.Instance;
        string query = "Select * from " + tablename;
        DataTable dtDB = obj.SelectDatatable(query);
        DataTable newcsv = new DataTable();
        newcsv = csvTable.Copy();
        //newcsv = csvTable;
        if (dtDB != null && dtDB.Rows.Count > 0)
        {
            int count = csvTable.Columns.Count;
            for (int i = 0; i < count; i++)
            {
                string dbcolumn = csvTable.Columns[i].ToString().Trim();
                if (dtDB.Columns[dbcolumn] == null)
                {
                    int count1 = csvTable.Columns.Count;
                    newcsv.Columns.Remove(dbcolumn);
                    newcsv.AcceptChanges();
                }
            }
            if (newcsv.Columns.Count != dtDB.Columns.Count)
            {
                newcsv = null;
            }
        }
        return newcsv;
    }
    public static Validate checkPasswordComplexity(string password, int Length, string patternsToEscape = "", bool caseSensitivty = true, bool numericDigits = true, bool SpecialCharacter = true)
    {
        Validate vl = new Validate();
        bool valid = true;
        string result = "";
        if (password.Length <= Length)
        {
            valid = false;

        }
        if (caseSensitivty == true)
        {

            int hasUpperCase = Regex.Match(password, "[A-Z]").Length;
            if (hasUpperCase < 0)
            {
                valid = false;
                result += " , one upper case";
            }
            int hasLowerCase = Regex.Match(password, "[A-Z]").Length;
            if (hasLowerCase <= 0)
            {
                valid = false;
                result += " , one lower case";
            }
        }
        if (numericDigits == true)
        {
            int hasNumbers = Regex.Match(password, "[0-9]").Length;
            if (hasNumbers <= 0)
            {
                valid = false;
                result += " , one numeric";
            }
        }
        if (SpecialCharacter == true)
        {
            int hasSpecial = Regex.Match(password, "[!@#$&*]").Length;
            if (hasSpecial <= 0)
            {
                valid = false;
                result += " , one special character";
            }
        }
        if (patternsToEscape != "")
        {
            int hasLowerCase = Regex.Match(password, @"" + patternsToEscape + "").Length;
            if (hasLowerCase <= 0)
            {
                valid = false;
            }
        }
        vl.IsValid = valid;
        string mesg = (result != "") ? "and must has atleast " + result.Substring(1, result.Length - 1) : "";
        vl.Message = "Password must has " + Length + " character length " + mesg;
        return vl;
    }

    public static void CopyData(string connStr, DataTable dt, string tablename)
    {
        using (SqlBulkCopy bulkCopy =
        new SqlBulkCopy(connStr, SqlBulkCopyOptions.TableLock))
        {
            bulkCopy.DestinationTableName = tablename;
            bulkCopy.WriteToServer(dt);
        }
    }

    bool disposed = false;
    // Instantiate a SafeHandle instance.
    System.Runtime.InteropServices.SafeHandle handle = new Microsoft.Win32.SafeHandles.SafeFileHandle(IntPtr.Zero, true);
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
            handle.Dispose();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            // Free any other managed objects here.
            //
        }

        // Free any unmanaged objects here.
        //
        disposed = true;
    }
}
public class IpProperties
{
    public string Status { get; set; }
    public string Country { get; set; }
    public string CountryCode { get; set; }
    public string Region { get; set; }
    public string RegionName { get; set; }
    public string City { get; set; }
    public string Zip { get; set; }
    public string Lat { get; set; }
    public string Lon { get; set; }
    public string TimeZone { get; set; }
    public string ISP { get; set; }
    public string ORG { get; set; }
    public string AS { get; set; }
    public string Query { get; set; }
}
public class Validate
{
    public bool IsValid { get; set; }
    public string Message { get; set; }
}
