using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;


namespace CommonFunc
{
    public static class BasicFunc
    {
        /*Used to load variable or properties from DataRow*/
        public static string SetParamValue(this System.Data.DataRow row, string value)
        {
            return HttpUtility.HtmlDecode(Convert.ToString(row[value]).Trim());
        }
        
        /* Get details of IPAddress such as country, status, city etc*/
        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;
                }
            }
        }
        /*API to get IP Detail*/
        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;
        }
        /*Get IP Address of a network*/
        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;
        }
        /*Get number of words from String*/
        public static string GetWord_Number(string text, int NoOfWords)
        {
            string word = "";
            if (text != null)
            {
                string[] split = text.Split(' ');
                int wordlength = (split.Length > NoOfWords) ? NoOfWords : split.Length;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < NoOfWords; i++)
                {
                    sb.Append(split[i].ToString().Trim() + " ");
                }
                word = sb.ToString().Substring(0, sb.ToString().Length - 1);
            }
            return word;
        }
        /*Get number of Character from String*/
        public static string GetWord_CharacterLength(string text, int NoOfCharacter)
        {
            string word = "";
            if (text != null)
            {
                int charlength = (text.ToString().Trim().Length > NoOfCharacter) ? NoOfCharacter : 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;
        }
        /*Get first paragraph text from HmlText*/
        public static string GetFirstParagraphText(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;
            }
        }
        /*Get first paragraph from HmlText*/
        public static string GetFirstParagraph(string htmltext)
        {
            Match m = Regex.Match(htmltext, @"<p\s*(.+?)\s*>\s*(.+?)\s*</p>");
            if (m.Success)
            {
                return m.ToString();
            }
            else
            {
                return htmltext;
            }
        }
        /*Shorten your string with .... and last word at end
         Give number of character in noOfCharacter you require */
        public static string ShortenString_LastWord(string content, int noOfCharacter)
        {
            if (content.Length <= noOfCharacter)
                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 = noOfCharacter - LastWord.Length - 3;
            string FirstPartContent = content.Substring(0, firstIndex);
            string NewContent = FirstPartContent + "..." + LastWord;

            return NewContent;
        }
        /*Shorten your string with ....*/
        public static string ShortenString(string content, int noOfCharacter)
        {
            if (content.Length <= noOfCharacter)
                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 = noOfCharacter;
            string FirstPartContent = content.Substring(0, firstIndex);
            string NewContent = FirstPartContent + "...";

            return NewContent;
        }
        /*Convert Number to words*/
        public static string NumbersToWords(int inputNumber)
        {
            int inputNo = inputNumber;

            if (inputNo == 0)
                return "Zero";

            int[] numbers = new int[4];
            int first = 0;
            int u, h, t;
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            if (inputNo < 0)
            {
                sb.Append("Minus ");
                inputNo = -inputNo;
            }

            string[] words0 = {"" ,"One ", "Two ", "Three ", "Four ",
            "Five " ,"Six ", "Seven ", "Eight ", "Nine "};
            string[] words1 = {"Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ",
            "Fifteen ","Sixteen ","Seventeen ","Eighteen ", "Nineteen "};
            string[] words2 = {"Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ",
            "Seventy ","Eighty ", "Ninety "};
            string[] words3 = { "Thousand ", "Lakh ", "Crore " };

            numbers[0] = inputNo % 1000; // units
            numbers[1] = inputNo / 1000;
            numbers[2] = inputNo / 100000;
            numbers[1] = numbers[1] - 100 * numbers[2]; // thousands
            numbers[3] = inputNo / 10000000; // crores
            numbers[2] = numbers[2] - 100 * numbers[3]; // lakhs

            for (int i = 3; i > 0; i--)
            {
                if (numbers[i] != 0)
                {
                    first = i;
                    break;
                }
            }
            for (int i = first; i >= 0; i--)
            {
                if (numbers[i] == 0) continue;
                u = numbers[i] % 10; // ones
                t = numbers[i] / 10;
                h = numbers[i] / 100; // hundreds
                t = t - 10 * h; // tens
                if (h > 0) sb.Append(words0[h] + "Hundred ");
                if (u > 0 || t > 0)
                {
                    if (h > 0 || i == 0) sb.Append("and ");
                    if (t == 0)
                        sb.Append(words0[u]);
                    else if (t == 1)
                        sb.Append(words1[u]);
                    else
                        sb.Append(words2[t - 2] + words0[u]);
                }
                if (i != 0) sb.Append(words3[i - 1]);
            }
            return sb.ToString().TrimEnd();
        }
        /*Convert string array to arraylist*/
        public static ArrayList ArrayToArrayList(params string[] Content)
        {
            ArrayList list = new ArrayList();
            foreach (string item in Content)
            {
                list.Add(item);
            }
            return list;
        }
        /*Copy Properties value from one class to other*/
        public static T CopyPropertyValues<T>(T Destination, object Source)
        {
            var model = typeof(T);
            var properties = model.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
            foreach (var prop in properties)
            {
                string propname = prop.Name;
                var value = (Source.GetType().GetProperty(propname, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) != null) ? Source.GetType().GetProperty(propname, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance).GetValue(Source, null) : null;
                //prop.GetType().GetProperty(propname).SetValue(prop, value);
                prop.SetValue(Destination, value, null);
            }
            return Destination;
        }
        public static Int32 ToInt32(this string content)
        {
            if (content != null && content != "")
            {
                return Convert.ToInt32(content.Trim());
            }
            else
            {
                return 0;
            }
        }
        public static Int64 ToInt64(this string content)
        {
            if (content != null && content != "")
            {
                return Convert.ToInt64(content.Trim());
            }
            else
            {
                return 0;
            }
        }
        public static double ToDouble(this string content)
        {
            if (content != null && content != "")
            {
                return Convert.ToDouble(content.Trim());
            }
            else
            {
                return 0;
            }
        }
        public static DateTime ToDateTime(this string content)
        {

            if (content != null && content != "")
            {
                return Convert.ToDateTime(content.Trim());
            }
            else
            {
                return DateTime.Now;
            }
        }
        public static string JoinArray(this string[] items, string delimeter, bool lastDelimeter = false)
        {
            string content = "";
            foreach (var item in items)
            {
                content += item + delimeter;
            }
            if (lastDelimeter == false)
            {
                content = content.Substring(0, content.Length - delimeter.Length);
            }
            return content;
        }

    }
    public static class SerializeFunc
    {
        ///*Deserialize javascript content*/
        //public static T javaDeserialize<T>(string Content)
        //{
        //    //cast to specified objectType
        //    var obj = (T)new JavaScriptSerializer().Deserialize<T>(Content);
        //    return obj;
        //}
    }
    public class DirectoryFunc : IDisposable
    {
        private DirectoryFunc()
        { }
        /*create Directory*/
        public static void Create(string DirectoryPath, string DirectoryName)
        {
            string targetpath1 = DirectoryPath + "/" + DirectoryName;
            DirectoryInfo ObjSearchDir = new DirectoryInfo(targetpath1);
            if (!Directory.Exists(targetpath1))
            {
                Directory.CreateDirectory(targetpath1);
                SetAccessRights(DirectoryName, DirectoryPath);
            }
        }
        /*provide access rights to Directory*/
        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);
                }
            }
        }
        /*Remove Director*/
        public static void Remove(string DirectoryPath)
        {
            //This condition is used to delete all files from the Directory
            foreach (string file in Directory.GetFiles(DirectoryPath))
            {
                File.Delete(file);
            }
            //This condition is used to check all child Directories and delete files
            foreach (string subfolder in Directory.GetDirectories(DirectoryPath))
            {
                Remove(subfolder);
            }
            Directory.Delete(DirectoryPath);
        }
        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 static class UrlFunc
    {
        /*Remove query string from url. Give name of QueryString in Key*/
        public static string RemoveQueryStringByKey(this Uri url, params string[] key)
        {

            // this gets all the query string key value pairs as a collection
            var newQueryString = HttpUtility.ParseQueryString(url.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 = url.GetLeftPart(UriPartial.Path);

            return newQueryString.Count > 0
                ? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
                : pagePathWithoutQueryString;
        }
        /*Remove query string from url. Give name of QueryString in Key*/
        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;
        }
        /*Remove All query string from url*/
        public static string RemoveQueryString(this Uri url)
        {
            // this gets the page path from root without QueryString
            string pagePathWithoutQueryString = url.GetLeftPart(UriPartial.Path);
            return pagePathWithoutQueryString;
        }
        /*Remove All query string from url*/
        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;
        }
        /*Rename QueryString name*/
        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 class UploadFunc
    {
        /*Check file extension of uploaded File. It can check even if file extension of file is changed*/
        [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(this 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 correct 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;
        }
        /*Check file extension of uploaded File*/
        public static string CheckUploadFileExt(this HttpPostedFileBase fileupload, string format)
        {
            if (fileupload == null)
            {
                return "Invalid file content!";
            }
            format = format.ToLower();
            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";
            }
        }
        /*Check Dimension of uploaded Images*/
        public static string CheckUploadFileDimention(this 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";
            }


        }
        /*Check Max Dimension of uploaded Images*/
        public static string CheckUploadMaxFileDimention(this 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 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";
            }


        }
        /*Save Image by optmising*/
        public static void SaveAsOptimised(this HttpPostedFileBase file, string path)
        {
            System.Drawing.Imaging.Encoder myEncoder;
            string directory = Path.GetDirectoryName(path);
            string fileextension = Path.GetExtension(path);
            //if (!Directory.Exists(HttpContext.Current.Server.MapPath("/"+ directory)))
            //{

            //}
            Image imag = Image.FromStream(file.InputStream, true, true);
            myEncoder = System.Drawing.Imaging.Encoder.Quality;
            Bitmap originalBMP = new Bitmap(new Bitmap(imag));
            //int size = originalBMP;

            string pixelFormat = imag.PixelFormat.ToString();
            // Create a graphic based on the new bitmap
            Graphics oGraphics = Graphics.FromImage(originalBMP);

            // Set the properties for the new graphic file
            oGraphics.CompositingQuality = CompositingQuality.HighQuality;
            oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
            oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            // Draw the new graphic based on the resized bitmap
            oGraphics.DrawImage(originalBMP, 0, 0, originalBMP.Width, originalBMP.Height);
            System.Drawing.Imaging.ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo codecInfo = ImageCodecInfo.GetImageDecoders().First(codec => codec.FilenameExtension.Contains("*" + fileextension.ToUpper()));
            EncoderParameters encoderParameters = Encoderparameter(pixelFormat);
            // Save the new graphic file to the server
            originalBMP.Save(path, info[1], encoderParameters);

            // Once finished with the bitmap objects, we deallocate them.
            originalBMP.Dispose();
            oGraphics.Dispose();
        }
        public static EncoderParameters Encoderparameter(string pixelFormat = "")
        {
            EncoderParameters parameters = new EncoderParameters(3);
            parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 256L);
            if (pixelFormat == "Format8bppIndexed")
            {
                parameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 80L);
            }
            else if (pixelFormat == "Format24bppRgb")
            {
                parameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 70L);
            }
            else if (pixelFormat == "")
            {
                parameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 60L);
            }
            else
            {
                parameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 80L);
            }

            parameters.Param[2] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionLZW);
            return parameters;
        }
        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 string CustomFileName(HttpPostedFileBase file, string suffixname = "")
        {
            string strprofileimageNew = DateTime.Now.Ticks.ToString();
            string strprofileimageExt = System.IO.Path.GetExtension(file.FileName);
            string Backgroundimage = suffixname + strprofileimageNew + strprofileimageExt;
            return Backgroundimage;
        }
        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);
        }
        /*Save Image to Folder*/
        public static validate SaveImage(HttpPostedFileBase fileUpload, string FilePath, string FileName, bool Optimised = true, string Format = "", int width = 0, int height = 0, bool mandatory = true)
        {
            validate vm = new validate();
            if (fileUpload != null)
            {
                if (fileUpload.ContentLength > 0)
                {
                    vm = ValidationFunc.ImageValidate(fileUpload, Format, width, height);
                    if (vm.isValid == false)
                    {
                        return vm;
                    }
                    if (Optimised == true)
                    {
                        fileUpload.SaveAsOptimised(HttpContext.Current.Server.MapPath(FilePath + "/" + FileName));
                    }
                    else
                    {
                        fileUpload.SaveAs(HttpContext.Current.Server.MapPath(FilePath + "/" + FileName));
                    }
                    vm.isValid = true;
                }
            }
            else if (mandatory == true)
            {
                vm.isValid = false;
                vm.Message = "<b>Alter</b> No files selected by fileuploader!";
            }
            return vm;
        }
        public static validate SaveFile(HttpPostedFileBase fileUpload, string FilePath, string FileName, string Format = "", bool mandatory = false)
        {
            validate vm = new validate();
            if (fileUpload != null)
            {
                if (fileUpload.ContentLength > 0)
                {
                    if (fileUpload.CheckUploadFileExt(Format) != "success")
                    {
                        vm.Message = "Images - Invalid file format ! (Allowed | " + Format + " |)";
                        vm.isValid = false;
                        return vm;
                    }
                    fileUpload.SaveAs(HttpContext.Current.Server.MapPath(FilePath + "/" + FileName));
                    vm.isValid = true;
                }
            }
            else if (mandatory == true)
            {
                vm.isValid = false;
                vm.Message = "<b>Alter</b> No files selected by fileuploader!";
            }
            return vm;
        }
    }
    public static class DateFunc
    {
        public static string getTimeAgo(this DateTime strDate)
        {
            string strTime = string.Empty;
            if (CheckFunc.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 class ReplaceFunc
    {
        /*Remove unwanted character from Alias */
        public static string Alias(string StringText)
        {
            StringText = Regex.Replace(StringText.ToLower().Replace(" ", "-").Replace("--", "-"), @"[^a-zA-Z0-9-]+", "");
            return StringText;
        }
        public static string Text(string StringText)
        {

            StringText = StringText.Replace("'", "").Replace("&", "").Replace("*", "").Replace("^", "").Replace("<", "").Replace(">", "").Replace(";", "").Replace("?", "").Replace("=", "").Replace("_", "").Replace("#", "").Replace("--", "").Replace("!", "").Replace("script", "");
            return StringText;
        }
        /*Remove unwanted character from URL */
        public static string URLText(string StringText)
        {

            StringText = StringText.Replace("'", "").Replace("&", "").Replace("*", "").Replace("^", "").Replace("<", "").Replace(">", "").Replace(";", "").Replace("?", "").Replace("=", "").Replace("#", "").Replace("--", "").Replace("!", "").Replace("script", "");
            return StringText;
        }
        /*Remove unwanted character from textBox text */
        public static string SpecialCharTextBoxString(string StringText)
        {

            StringText = StringText.Replace("<", "").Replace("/", "").Replace(">", "").Replace(";", "").Replace("'", "").Replace("--", "").Replace("=", "");
            return StringText;
        }
    }
    public static class CheckFunc
    {
        /*Check a string is numeric*/
        public static bool IsNumeric(string StringText)
        {
            Match m = Regex.Match(StringText, @"[^0-9]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            while (m.Success)
            {
                return false;
            }
            return true;
        }
        /*Check a string is Character*/
        public static bool IsCharacter(string StringText)
        {
            Match m = Regex.Match(StringText, @"[^a-zA-Z]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            while (m.Success)
            {
                return false;
            }
            return true;
        }
        /*Check a string is date*/
        public static bool IsDate(string o)
        {
            DateTime tmp = Convert.ToDateTime("01/01/0001 00:00:00");
            var date= DateTime.Now;
            return DateTime.TryParse(o, out tmp);
        }
        /*Check a string is valid Url*/
        public static bool IsLink(this string link)
        {
            return Uri.IsWellFormedUriString(link, UriKind.RelativeOrAbsolute);
        }
        /*Check a string is Email*/
        public static bool IsEmail(string email)
        {
            try
            {
                var addr = new System.Net.Mail.MailAddress(email);
                return addr.Address == email;
            }
            catch
            {
                return false;
            }
        }
        /*Check a URL is Local*/
        public static bool IsLocalUrl(string url)
        {
            return !url.StartsWith("http:", StringComparison.OrdinalIgnoreCase)
                        && !url.StartsWith("https:", StringComparison.OrdinalIgnoreCase)
                        && Uri.IsWellFormedUriString(url, UriKind.Relative);
        }
        public static bool IsDouble(string text)
        {
            double tmp;
            return double.TryParse(text,out tmp);
        }
    }
    public static class ImageFunc
    {

    }
    public static class SpecialCharacterFunc
    {
        public static bool Alias(string StringText)
        {
            Match m = Regex.Match(StringText, @"[^a-zA-Z0-9-]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            while (m.Success)
            {
                return false;
            }
            return true;
        }
        public static validate Alias(params string[] StringText)
        {
            return ValidateString(@"[^a-zA-Z0-9-]+", StringText);
        }
        public static bool QueryString(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 DiscussionTitle(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 Title(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;
        }
        public static validate DiscussionTitle(params string[] StringText)
        {
            return ValidateString(@"[^a-zA-Z0-9- ()*$!@_\"":.]+", StringText);
        }
        public static validate Title(params string[] StringText)
        {
            string[] exp = new string[] { "<", ">", ";", "--", "=" };
            return ValidateString(BasicFunc.ArrayToArrayList(exp), StringText);
        }

        //Add Character except "a-zA-Z0-9-" to remove restriction from that charcter
        public static bool CustomiseRule(string StringText, string CharacterToAllow)
        {
            Match m = Regex.Match(StringText, @"[^a-zA-Z0-9-]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            while (m.Success)
            {
                return false;
            }
            return true;
        }
        //Add all Character to remove restriction from that charcter
        public static bool CustomiseCheckString(string StringText, string RegularExpression)
        {
            Match m = Regex.Match(StringText, @"" + RegularExpression + "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            while (m.Success)
            {
                return false;
            }
            return true;
        }
        public static validate CustomiseCheckStringWithMessage(string StringText, string RegularExpression)
        {
            return ValidateString(RegularExpression, StringText);
        }
        public static bool TextBoxString(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;
        }
        public static validate TextBoxString(params string[] StringText)
        {
            validate vm = new validate();
            string[] exp = new string[] { "<", "/", ">", ";", "--", "=" };
            bool result = false;
            string field = "";
            foreach (string text in StringText)
            {
                if (text != null && text != "")
                {
                    foreach (string c in exp)
                    {
                        result = Regex.IsMatch(text, c);
                        if (result)
                        {
                            field += "," + SqlHelp.GetParameterName(text);
                            vm.isValid = false;
                        }
                    }
                }
            }
            if (field != null && field != "")
            {
                vm.Message = "<b>Alert</b> Special Char not allowed for " + field.Substring(1, field.Length - 1) + "!";
            }
            else
            {
                vm.isValid = true;
            }
            return vm;
        }
        public static validate CustomizeTextBox(string charachter, string StringText)
        {
            ArrayList arlist = new ArrayList();
            arlist.Add("<");
            arlist.Add(">");
            arlist.Add(";");
            arlist.Add("--");
            arlist.Add("=");
            if (charachter.Length > 0)
            {
                foreach (string s in charachter.Split(','))
                {
                    arlist.Add(s);
                }
            }
            //string[] exp = new string[] { "<", ">", ";", "--", "=" };
            return ValidateString(arlist, StringText);
        }
        public static bool TextAreaString(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 validate TextAreaString(params string[] StringText)
        {
            var list = TextAreaSpecialCharList();
            return ValidateString(list, StringText);
        }
        /*Check text area for SEO Content*/
        public static bool TextAreaSEOOther(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 validate TextAreaSEOOther(params string[] StringText)
        {
            var list = TextAreaSpecialCharList("<script", "<meta");
            return ValidateString(list, StringText);
        }
        public static bool CheckCertificteTextAreaString(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; }

        }
        /*Check Special character for file name*/
        public static bool SpecialCharFileNameString(string StringText)
        {
            var isValid = !string.IsNullOrEmpty(StringText) &&
                  StringText.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) < 0;
            return isValid;
        }
        public static validate ValidateString(string regexString, params string[] StringText)
        {
            validate vm = new validate();
            string field = "";
            foreach (string text in StringText)
            {
                Match m = Regex.Match(text, regexString, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                while (m.Success)
                {
                    field += "," + SqlHelp.GetParameterName(text);
                    vm.isValid = false;
                }
            }
            if (field != null && field != "")
            {
                vm.Message = "<b>Alert</b> Special Char not allowed for " + field.Substring(1, field.Length - 1) + "!";
            }
            else
            {
                vm.isValid = true;
            }
            return vm;
        }
        public static validate ValidateString(ArrayList SpecialCharacterList, params string[] StringText)
        {
            validate vm = new validate();
            string field = "";
            foreach (string c in SpecialCharacterList)
            {
                foreach (string text in StringText)
                {
                    Match m = Regex.Match(text, c, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    while (m.Success)
                    {
                        field += "," + SqlHelp.GetParameterName(text);
                        vm.isValid = false;
                    }
                }
            }
            if (field != null && field != "")
            {
                vm.Message = "<b>Alert</b> Special Char not allowed for " + field.Substring(1, field.Length - 1) + "!";
            }
            else
            {
                vm.isValid = true;
            }
            return vm;
        }
        public static ArrayList TextAreaSpecialCharList(params string[] ListToRemove)
        {
            ArrayList list = new ArrayList();
            list.Add("<script");
            list.Add("xp_");
            list.Add(";--");
            list.Add("--;");
            list.Add("@@");
            list.Add("/*");
            list.Add("*/");
            list.Add("<applet");
            list.Add("<body");
            list.Add("<embed");
            list.Add("<layer");
            list.Add("<ilayer");
            list.Add("<object");
            list.Add("<meta");
            list.Add("<frame");
            foreach (string item in ListToRemove)
            {
                list.Remove(item);
            }
            return list;
        }
    }
    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 string Message { get; set; }
        public bool isValid { get; set; }
    }
    public class SaveData
    {
        public string Message { get; set; }
        public bool isSuccess { get; set; }
    }
}

