Fetch Class utilities

 using Infragistics.Web.Mvc;

using Microsoft.ProjectOxford.Face.Contract;

using OfficeOpenXml;

using OfficeOpenXml.Style;

using System;

using System.Collections.Generic;

using System.Configuration;

using System.IO;

using System.Linq;

using System.Net;

using System.Text;

using System.Text.RegularExpressions;

using System.Threading.Tasks;

using System.Web;

using AI_Portal_Cloud.Utilities;

using System.Collections.Specialized;

using Newtonsoft.Json;

using Microsoft.ProjectOxford.Face;

using System.Data;

using System.Reflection;

using System.Resources;

using AI_Portal_Cloud.Resources;

using System.Security.Cryptography;


namespace AI_Portal_Cloud.CommanClass

{

    public class clsUtilities

    {

        private static Random random = new Random();

        /// <summary>

        /// get user's machine IP address

        /// </summary>

        /// <returns></returns>

        public static string GetClientIpAddr()

        {

            string strIP = String.Empty;

            HttpRequest httpReq = HttpContext.Current.Request;


            //test for non-standard proxy server designations of client's IP

            if (httpReq.ServerVariables["HTTP_CLIENT_IP"] != null)

            {

                strIP = httpReq.ServerVariables["HTTP_CLIENT_IP"].ToString();

            }

            else if (httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)

            {

                strIP = httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();

            }

            //test for host address reported by the server

            else if

            (

                //if exists

                (httpReq.UserHostAddress.Length != 0)

                &&

                //and if not localhost IPV6 or localhost name

                ((httpReq.UserHostAddress != "::1") || (httpReq.UserHostAddress != "localhost"))

            )

            {

                strIP = httpReq.UserHostAddress;

            }

            //finally, if all else fails, get the IP from a web scrape of another server

            else

            {

                WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");

                using (WebResponse response = request.GetResponse())

                using (StreamReader sr = new StreamReader(response.GetResponseStream()))

                {

                    strIP = sr.ReadToEnd();

                }

                //scrape ip from the html

                int i1 = strIP.IndexOf("Address: ") + 9;

                int i2 = strIP.LastIndexOf("</body>");

                strIP = strIP.Substring(i1, i2 - i1);

            }

            return strIP;

        }

        

        public static string getRealIpAddr()

        {

            string strIP = String.Empty;

            HttpRequest httpReq = HttpContext.Current.Request;


            //test for non-standard proxy server designations of client's IP

            if (httpReq.ServerVariables["HTTP_CLIENT_IP"] != null)

            {

                strIP = httpReq.ServerVariables["HTTP_CLIENT_IP"].ToString();

            }

            else if (httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)

            {

                strIP = httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();

            }

            //test for host address reported by the server

            else if

            (

                //if exists

                (httpReq.UserHostAddress.Length != 0)

                &&

                //and if not localhost IPV6 or localhost name

                ((httpReq.UserHostAddress != "::1") || (httpReq.UserHostAddress != "localhost"))

            )

            {

                strIP = httpReq.UserHostAddress;

            }

            //finally, if all else fails, get the IP from a web scrape of another server

            else

            {

                WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");

                using (WebResponse response = request.GetResponse())

                using (StreamReader sr = new StreamReader(response.GetResponseStream()))

                {

                    strIP = sr.ReadToEnd();

                }

                //scrape ip from the html

                int i1 = strIP.IndexOf("Address: ") + 9;

                int i2 = strIP.LastIndexOf("</body>");

                strIP = strIP.Substring(i1, i2 - i1);

            }

            return strIP;

        }


        public User GetUserDetails()

        {

            User objUser = new User();


            return objUser;

        }


        public static string ReadConfigValue(string key)

        {

            string configValue;


            configValue = ConfigurationManager.AppSettings[key];

            if (configValue == null)

                throw new Exception(key + " not found in web.config");


            return configValue;

        }


        public static string GetQueryStringValue(string key)

        {

            string strVal = "";

            //strVal = HttpContext.Current.Request.QueryString.Get(key);

            if (!string.IsNullOrEmpty(strVal))

            {

                strVal = "";

            }

            return strVal;

        }


        public static string TimeAgo(DateTime dt)

        {

            TimeSpan span = DateTime.Now - dt;

            //if (span.Days > 365)

            //{

            //    int years = (span.Days / 365);

            //    if (span.Days % 365 != 0)

            //        years += 1;

            //    return String.Format("{0} {1} ago",

            //    years, years == 1 ? "year" : "years");

            //}

            //if (span.Days > 30)

            //{

            //    int months = (span.Days / 30);

            //    if (span.Days % 31 != 0)

            //        months += 1;

            //    return String.Format("{0} {1} ago",

            //    months, months == 1 ? "month" : "months");

            //}

            if (span.Days > 0)

            {

                //return String.Format("{0} {1} ago",

                //span.Days, span.Days == 1 ? "day" : "days");

                return dt.ToString("dddd, MMM dd, yyyy, hh:mm tt");

            }

            if (span.Hours > 0)

                return String.Format("{0} {1} ago",

                span.Hours, span.Hours == 1 ? "hour" : "hours");

            if (span.Minutes > 0)

                return String.Format("{0} {1} ago",

                span.Minutes, span.Minutes == 1 ? "minute" : "minutes");

            if (span.Seconds > 5)

                return String.Format("{0} seconds ago", span.Seconds);

            if (span.Seconds <= 5)

                return "a few seconds ago";

            return "";

        }


        public static string ReplaceWordSpecialChars(string text)

        {

            var s = text;

            // smart single quotes and apostrophe

            s = Regex.Replace(s, "[\u2018\u2019\u201A]", "'");

            // smart double quotes

            s = Regex.Replace(s, "[\u201C\u201D\u201E]", "\"");

            // ellipsis

            s = Regex.Replace(s, "\u2026", "...");

            // dashes

            s = Regex.Replace(s, "[\u2013\u2014]", "-");

            // circumflex

            s = Regex.Replace(s, "\u02C6", "^");

            // open angle bracket

            s = Regex.Replace(s, "\u2039", "<");

            // close angle bracket

            s = Regex.Replace(s, "\u203A", ">");

            // spaces

            s = Regex.Replace(s, "[\u02DC\u00A0]", " ");

            // replace with new line

            s = Regex.Replace(s, @"\r\n?|\n", "<br/>");


            return s;

        }


        public static string CallREST_ServiceWithAuthentication(string strURL, string strMethod, string strInputData, bool isDefaultCredential = false,

            Dictionary<string, string> dicHeaderKeyValues = null, bool isProxyEnabled = true)

        {

            string strResponse = "";

            //https use then by pass

            System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

            WebClient webclient = new WebClient();


            if (isDefaultCredential == true)

            {

                webclient.Credentials = CredentialCache.DefaultCredentials;

            }

            else

            {

                NetworkCredential credential = new NetworkCredential(ReadConfigValue("WindowsUserID"), ReadConfigValue("WindowsPsw"));

                webclient.Credentials = credential;

            }

            if (isProxyEnabled == true)

            {

                //webclient.Proxy = new WebProxy(ReadConfigValue("ProxyIP"), Convert.ToInt32(ReadConfigValue("ProxyPort")));

                webclient.Proxy = WebRequest.GetSystemWebProxy();

            }

            if (dicHeaderKeyValues != null)

            {

                foreach (KeyValuePair<string, string> kvp in dicHeaderKeyValues)

                {

                    webclient.Headers.Add(kvp.Key, kvp.Value);

                }

            }

            if (strMethod.ToUpper() == "POST")

            {

                webclient.Headers["content-type"] = "application/json";

                strResponse = webclient.UploadString(strURL, strInputData);

            }

            else

            {

                strResponse = webclient.DownloadString(strURL);

            }

            return strResponse.Trim();

        }


        public static string GetWindowsID()

        {

            string str = HttpContext.Current.User.Identity.Name;

            if (HttpContext.Current.User.Identity.Name.Contains("\\") == true)

            {

                return HttpContext.Current.User.Identity.Name;

            }

            else

                return "";

        }


        public static string GetGlassName(Glasses enumGlasses)

        {

            string retVal = "";

            try

            {

                if (enumGlasses == Glasses.NoGlasses)

                {

                    retVal = "No Glasses";

                }

                else if (enumGlasses == Glasses.ReadingGlasses)

                {

                    retVal = "Reading Glasses";

                }

                else if (enumGlasses == Glasses.Sunglasses)

                {

                    retVal = "Sun Glasses";

                }

                else if (enumGlasses == Glasses.SwimmingGoggles)

                {

                    retVal = "Swimming Goggles";

                }

            }

            catch

            {

            }

            return retVal;

        }


        public static string GetEmotionName(Microsoft.ProjectOxford.Common.Contract.EmotionScores Emotion)

        {

            string retVal = "Neutral";

            float val = 0.0f;

            try

            {

                if (Emotion.Anger >= val)

                {

                    val = Emotion.Anger;

                    retVal = "Anger";

                }

                if (Emotion.Contempt >= val)

                {

                    val = Emotion.Contempt;

                    retVal = "Contempt";

                }

                if (Emotion.Disgust >= val)

                {

                    val = Emotion.Disgust;

                    retVal = "Disgust";

                }

                if (Emotion.Fear >= val)

                {

                    val = Emotion.Fear;

                    retVal = "Fear";

                }

                if (Emotion.Happiness >= val)

                {

                    val = Emotion.Happiness;

                    retVal = "Happiness";

                }

                if (Emotion.Neutral >= val)

                {

                    val = Emotion.Neutral;

                    retVal = "Neutral";

                }

                if (Emotion.Sadness >= val)

                {

                    val = Emotion.Sadness;

                    retVal = "Sadness";

                }

                if (Emotion.Surprise >= val)

                {

                    val = Emotion.Surprise;

                    retVal = "Surprise";

                }

            }

            catch

            {

            }

            return retVal;

        }


        public static string GetHairColor(HairColor[] hairColor)

        {

            string retVal = "";

            double val = 0;

            HairColorType intVal = 0;

            try

            {

                foreach (var item in hairColor)

                {

                    if (item.Confidence >= val)

                    {

                        val = item.Confidence;

                        intVal = item.Color;

                    }

                }


                if (intVal == HairColorType.White)

                {

                    retVal = "White";

                }

                else if (intVal == HairColorType.Gray)

                {

                    retVal = "Gray";

                }

                else if (intVal == HairColorType.Blond)

                {

                    retVal = "Blond";

                }

                else if (intVal == HairColorType.Brown)

                {

                    retVal = "Brown";

                }

                else if (intVal == HairColorType.Red)

                {

                    retVal = "Red";

                }

                else if (intVal == HairColorType.Black)

                {

                    retVal = "Black";

                }

                else if (intVal == HairColorType.Other)

                {

                    retVal = "Other";

                }

            }

            catch

            {

            }

            return retVal;

        }


        public static string GetAccessoriesType(Accessory[] accessory, AccessoryType accessoryType)

        {

            string retVal = "N";

            try

            {

                foreach (var item in accessory)

                {

                    if (item.Type == accessoryType)

                    {

                        if (item.Confidence > 0)

                        {

                            retVal = "Y";

                        }

                    }

                }

            }

            catch

            {

            }

            return retVal;

        }


        public static string GetBlurLevel(BlurLevel blurLevel)

        {

            string retVal = "";

            try

            {

                if (blurLevel == BlurLevel.High)

                {

                    retVal = "High";

                }

                else if (blurLevel == BlurLevel.Low)

                {

                    retVal = "Low";

                }

                else if (blurLevel == BlurLevel.Medium)

                {

                    retVal = "Medium";

                }

            }

            catch

            {

            }

            return retVal;

        }


        public static void sendErrMsgToAdmin(string strMessage)

        {

            try

            {

                System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();

                mm.To.Add(new System.Net.Mail.MailAddress(ReadConfigValue("MailTo")));

                if (!string.IsNullOrWhiteSpace(ReadConfigValue("MailTo")))

                {

                    mm.CC.Add(new System.Net.Mail.MailAddress(ReadConfigValue("MailCc")));

                }

                mm.From = new System.Net.Mail.MailAddress(ReadConfigValue("MailFrom"));

                mm.Subject = ReadConfigValue("MailSubject");

                mm.Body = strMessage;

                System.Net.Mail.SmtpClient smtCliend = new System.Net.Mail.SmtpClient();

                smtCliend.Host = ReadConfigValue("SMTPClientHost");

                smtCliend.Port = Convert.ToInt32(ReadConfigValue("SMTPClientPort"));

                smtCliend.Send(mm);

            }

            catch (Exception)

            {

            }

        }


        public static string ApplyFilterExpr(System.Collections.Specialized.NameValueCollection queryString)

        {

            List<FilterExpression> exprs = GetFilterExpressions(queryString);

            StringBuilder builder = new StringBuilder();

            int count = 0;


            for (int i = 0; i < exprs.Count; i++)

            {

                if (count != 0 && count <= exprs.Count - 1)

                {

                    builder.Append(exprs[i].Logic.ToLower() == "AND".ToLower() ? " AND " : " OR ");

                }

                count++;


                string condition = exprs[i].Condition;

                string expr = exprs[i].Expr.Replace("'", "''");

                string colKey = exprs[i].Key;

                var dt = DateTime.Now;


                switch (condition.ToLower())

                {

                    case "startswith":

                        builder.Append(colKey + " like '" + expr + "%'");

                        break;

                    case "contains":

                        builder.Append(colKey + " like '%" + expr + "%'");

                        break;

                    case "endswith":

                        builder.Append(colKey + " like '%" + expr + "'");

                        break;

                    case "equals":

                        builder.Append(colKey + " = '" + expr + "'");

                        break;

                    case "doesnotequal":

                        builder.Append(colKey + " <> '" + expr + "'");

                        break;

                    case "doesnotcontain":

                        builder.Append(colKey + " not like '%" + expr + "%'");

                        break;

                    case "lessthan":

                        builder.Append(colKey + " < '" + expr + "'");

                        break;

                    case "greaterthan":

                        builder.Append(colKey + " > '" + expr + "'");

                        break;

                    case "lessthanorequalto":

                        builder.Append(colKey + " <= '" + expr + "'");

                        break;

                    case "greaterthanorequalto":

                        builder.Append(colKey + " >= '" + expr + "'");

                        break;

                    case "true":

                        builder.Append(colKey + " = 1");

                        break;

                    case "false":

                        builder.Append(colKey + " = 0");

                        break;

                    case "on":

                        dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(double.Parse(expr)).ToUniversalTime();

                        //builder.Append("(" + colKey + ".Value.Day == " + dt.Day + " AND " + colKey +

                        //   ".Value.Year == " + dt.Year + " AND " + colKey + ".Value.Month == " + dt.Month + ")");

                        builder.Append("(DATEPART(day," + colKey + ") = " + dt.Day + " AND " + "DATEPART(year," + colKey +

                           ") = " + dt.Year + " AND " + "DATEPART(MONTH," + colKey + ") = " + dt.Month + ")");

                        break;

                    case "noton":

                        dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(double.Parse(expr)).ToUniversalTime();

                        //builder.Append("!(" + colKey + ".Value.Day == " + dt.Day + " AND " + colKey +

                        //   ".Value.Year == " + dt.Year + " AND " + colKey + ".Value.Month == " + dt.Month + ")");

                        builder.Append("(DATEPART(day," + colKey + ") <> " + dt.Day + " AND " + "DATEPART(year," + colKey +

                           ") <> " + dt.Year + " AND " + "DATEPART(MONTH," + colKey + ") <> " + dt.Month + ")");

                        break;

                    case "after":

                        dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(double.Parse(expr)).ToUniversalTime();

                        builder.Append("((" + colKey + ".Value.Year > " + dt.Year + " OR (" +

                           colKey + ".Value.Month > " + dt.Month + " AND " + colKey + ".Value.Year == " + dt.Year + ") OR (" +

                           colKey + ".Value.Day > " + dt.Day + " AND " + colKey + ".Value.Year == " + dt.Year + " AND " +

                           colKey + ".Value.Month == " + dt.Month + ")))");

                        break;

                    case "before":

                        dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(double.Parse(expr)).ToUniversalTime();

                        builder.Append("((" + colKey + ".Value.Year < " + dt.Year + " OR (" +

                                       colKey + ".Value.Month < " + dt.Month + " AND " + colKey + ".Value.Year == " + dt.Year + ") OR (" +

                                       colKey + ".Value.Day < " + dt.Day + " AND " + colKey + ".Value.Year == " + dt.Year + " AND " +

                                       colKey + ".Value.Month == " + dt.Month + ")))");

                        break;

                    case "today":

                        builder.Append("(" + colKey + ".Value.Day == " + DateTime.Now.Day + " AND " + colKey +

                         ".Value.Year == " + DateTime.Now.Year + " AND " + colKey + ".Value.Month == " + DateTime.Now.Month + ")");

                        break;

                    case "yesterday":

                        DateTime yesterday = DateTime.Now.AddDays(-1);

                        builder.Append("(" + colKey + ".Value.Day == " + yesterday.Day + " AND " + colKey +

                         ".Value.Year == " + yesterday.Year + " AND " + colKey + ".Value.Month == " + yesterday.Month + ")");

                        break;

                    case "thismonth":

                        builder.Append("(" + colKey + ".Value.Year == " + DateTime.Now.Year + " AND " + colKey + ".Value.Month == " + DateTime.Now.Month + ")");

                        break;

                    case "lastmonth":

                        builder.Append("(" + colKey + ".Value.Year == " + (DateTime.Now.Year - 1) + " AND " + colKey + ".Value.Month == " + (DateTime.Now.Month - 1) + ")");

                        break;

                    case "nextmonth":

                        builder.Append("(" + colKey + ".Value.Year == " + (DateTime.Now.Year - 1) + " AND " + colKey + ".Value.Month == " + (DateTime.Now.Month + 1) + ")");

                        break;

                    case "thisyear":

                        builder.Append(colKey + ".Value.Year == " + DateTime.Now.Year);

                        break;

                    case "lastyear":

                        builder.Append(colKey + ".Value.Year == " + (DateTime.Now.Year - 1));

                        break;

                    case "nextyear":

                        builder.Append(colKey + ".Value.Year == " + (DateTime.Now.Year + 1));

                        break;

                    default:

                        builder.Append("1=2");

                        break;

                }

            }

            if (builder.Length > 0)

            {

                return " and " + builder.ToString();

            }


            return "";

        }


        public static List<FilterExpression> GetFilterExpressions(NameValueCollection queryString)

        {

            List<FilterExpression> expressions = new List<FilterExpression>();

            // check the query string for sorting expressions

            foreach (string key in queryString.Keys)

            {

                if (!string.IsNullOrEmpty(key) && key.StartsWith("filter("))

                {

                    string columnKey = key.Substring(key.IndexOf("(")).Replace("(", "").Replace(")", "");

                    string logic = "AND";


                    if (queryString["filter"] != null && (queryString["filter"].ToLower() == "and" || queryString["filter"].ToLower() == "or"))

                    {

                        logic = queryString["filter"];

                    }


                    Regex filtersRegex = new Regex(@"[a-z]+\(.*?\)", RegexOptions.IgnoreCase);

                    MatchCollection m = filtersRegex.Matches(queryString[key]);

                    string[] filters = new string[m.Count];

                    int i = 0;

                    foreach (Match capture in m)

                    {

                        filters[i] = capture.Value;

                        i++;

                    }


                    // Handle multiple filters for the same column 

                    for (i = 0; i < filters.Length; i++)

                    {

                        FilterExpression e = new FilterExpression();

                        e.Logic = logic;

                        e.Key = columnKey;

                        e.Condition = filters[i].Substring(0, filters[i].IndexOf("("));

                        //if ((filters[i].StartsWith("contains()") || filters[i].StartsWith("equals()") || filters[i].StartsWith("startsWith()")

                        //        || filters[i].StartsWith("endsWith()") || filters[i].StartsWith("doesNotContain()") || filters[i].StartsWith("doesNotEqual()")

                        //    )

                        //    && (e.Condition != "null" && e.Condition != "notNull" && e.Condition != "empty" && e.Condition != "notEmpty")

                        //    && (e.Condition != "today" && e.Condition != "yesterday" && e.Condition != "thisMonth" && e.Condition != "nextMonth"

                        //    && e.Condition != "lastMonth" && e.Condition != "thisYear" && e.Condition != "nextYear" && e.Condition != "lastYear")

                        //    )

                        //{

                        //    continue;

                        //}

                        //else

                        //{

                        //    string tmp = filters[i].Substring(filters[i].IndexOf("("));

                        //    //e.Expr = filters[i].Substring(filters[i].IndexOf("(")).Replace("(", "").Replace(")", "");                            

                        //    e.Expr = filters[i].Substring(filters[i].IndexOf("(")+1);

                        //    e.Expr = e.Expr.Substring(0, e.Expr.Length - 1);

                        //}

                        string tmp = filters[i].Substring(filters[i].IndexOf("("));

                        e.Expr = filters[i].Substring(filters[i].IndexOf("(") + 1);

                        if (e.Expr.Length > 1)

                        {

                            e.Expr = e.Expr.Substring(0, e.Expr.Length - 1);

                        }

                        if (e.Condition.ToLower() == "startswith" || e.Condition.ToLower() == "contains" || e.Condition.ToLower() == "endswith" ||

                            e.Condition.ToLower() == "doesnotcontain")

                        {

                            if (e.Expr.IndexOf("[]") > -1)

                            {

                                e.Expr = e.Expr.Replace("[]", "[[]]");

                            }

                            else if (e.Expr.IndexOf("[") > -1)

                            {

                                e.Expr = e.Expr.Replace("[", "[[]");

                            }

                            if (e.Expr.IndexOf("_") > -1)

                            {

                                e.Expr = e.Expr.Replace("_", "[_]");

                            }

                            e.Expr = e.Expr.Replace("%", "[%]");

                        }

                        expressions.Add(e);

                    }

                }

            }


            return expressions;

        }


        //public static void ExportToExcel(DataTable tblReady, string strFileNameWithoutExtension = "Reports")

        //{

        //    DataTable tbl = tblReady.Clone();


        //    //' convert all the columns type to String 

        //    foreach (DataColumn col in tbl.Columns)

        //    {

        //        col.DataType = typeof(string);

        //    }


        //    tbl.Load(tblReady.CreateDataReader());


        //    //new code

        //    strFileNameWithoutExtension = strFileNameWithoutExtension.Replace(".xls", "");

        //    //using (ExcelPackage pck = new ExcelPackage())

        //    //{

        //    //    //Create the worksheet

        //    //    ExcelWorksheet ws = pck.Workbook.Worksheets.Add(strFileNameWithoutExtension);


        //    //    //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1

        //    //    ws.Cells["A1"].LoadFromDataTable(tbl, true);


        //    //    for (int i = 1; i <= tbl.Columns.Count; i++)

        //    //    {

        //    //        var cell = ws.Cells[1, i];

        //    //        cell.Style.Font.Bold = true;

        //    //        cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;

        //    //        cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;

        //    //        //cell.Style.Fill.PatternType = ExcelFillStyle.Solid;

        //    //        //cell.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(79, 129, 189));  //Set color to dark blue

        //    //        //cell.Style.Font.Color.SetColor(System.Drawing.Color.White);

        //    //    }


        //    //    ws.Cells.AutoFitColumns(5.50, 60.50);

        //    //    ws.Cells.Style.WrapText = true;


        //    //    var start = ws.Dimension.Start;

        //    //    var end = ws.Dimension.End;

        //    //    for (int row = start.Row; row <= end.Row; row++)

        //    //    { // Row by row...

        //    //        for (int col = start.Column; col <= end.Column; col++)

        //    //        { // ... Cell by cell...

        //    //            ws.Cells[row, col].Style.Border.Top.Style = ExcelBorderStyle.Thin;

        //    //            ws.Cells[row, col].Style.Border.Left.Style = ExcelBorderStyle.Thin;

        //    //            ws.Cells[row, col].Style.Border.Right.Style = ExcelBorderStyle.Thin;

        //    //            ws.Cells[row, col].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;

        //    //        }

        //    //    }


        //    //    ws.Cells.Style.Font.Size = 10;

        //    //    //ws.Cells.IsRichText = true;


        //    //    //Write it back to the client

        //    //    HttpContext.Current.Response.Clear();

        //    //    HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        //    //    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;  filename=" + strFileNameWithoutExtension + ".xlsx");

        //    //    HttpContext.Current.Response.BinaryWrite(pck.GetAsByteArray());

        //    //    HttpContext.Current.Response.Flush();

        //    //    HttpContext.Current.Response.End();

        //}


        public static string GetMediaTypeWithQualityHeaderValue(string ContentType)

        {

            string val = ContentType;

            if (ContentType.ToLower().Contains("charset"))

            {

                val = ContentType.Substring(0, ContentType.IndexOf(";"));

            }

            return val;

        }


        public static List<T> ConvertDataTable<T>(DataTable dt)

        {

            List<T> data = new List<T>();

            foreach (DataRow row in dt.Rows)

            {

                T item = GetItem<T>(row);

                data.Add(item);

            }

            return data;

        }


        private static T GetItem<T>(DataRow dr)

        {

            Type temp = typeof(T);

            T obj = Activator.CreateInstance<T>();


            foreach (DataColumn column in dr.Table.Columns)

            {

                foreach (PropertyInfo pro in temp.GetProperties())

                {

                    if (pro.Name == column.ColumnName)

                    {

                        pro.SetValue(obj, (dr[column.ColumnName] == DBNull.Value ? null : dr[column.ColumnName]), null);

                    }

                    else

                        continue;

                }

            }

            return obj;

        }


        public static T ConvertFromDBVal<T>(object obj)

        {

            if (obj == null || obj == DBNull.Value)

            {

                return default(T); // returns the default value for the type

            }

            else

            {

                return (T)obj;

            }

        }


        public static string GetCurrentUTCForSQLFormat()

        {

            return DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff");

        }


        public static string GetBase64StringForImage(string imgPath)

        {

            try

            {

                byte[] imageBytes = System.IO.File.ReadAllBytes(imgPath);

                string base64String = Convert.ToBase64String(imageBytes);

                return base64String;

            }

            catch (Exception ex)

            {

                return ex.Message;

            }

        }


        public static void SendMail(string from, string to, string cc, string subject, string strMessage)

        {

            System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();


            if (string.IsNullOrWhiteSpace(to) && string.IsNullOrWhiteSpace(cc))

            {

                throw new Exception("SendMail: To or CC parameter cannot be blank.");

            }


            //process to

            if (!string.IsNullOrWhiteSpace(to))

            {

                string[] values = to.Split(';');

                for (int i = 0; i < values.Length; i++)

                {

                    values[i] = values[i].Trim();

                    if (!string.IsNullOrWhiteSpace(values[i]))

                    {

                        mm.To.Add(new System.Net.Mail.MailAddress(values[i].Trim()));

                    }

                }

            }

            //process cc

            if (!string.IsNullOrWhiteSpace(cc))

            {

                string[] CCvalues = cc.Split(';');

                for (int i = 0; i < CCvalues.Length; i++)

                {

                    CCvalues[i] = CCvalues[i].Trim();

                    if (!string.IsNullOrWhiteSpace(CCvalues[i]))

                    {

                        mm.CC.Add(new System.Net.Mail.MailAddress(CCvalues[i].Trim()));

                    }

                }

            }


            //from

            if (string.IsNullOrWhiteSpace(from))

            {

                mm.From = new System.Net.Mail.MailAddress(clsUtilities.ReadConfigValue("MailFrom"));

            }

            else

            {

                mm.From = new System.Net.Mail.MailAddress(from);

            }


            //subject

            if (string.IsNullOrWhiteSpace(subject))

            {

                mm.Subject = clsUtilities.ReadConfigValue("MailSubject");

            }

            else

            {

                mm.Subject = subject;

            }


            mm.Body = strMessage;

            mm.IsBodyHtml = true;

            System.Net.Mail.SmtpClient smtCliend = new System.Net.Mail.SmtpClient();

            smtCliend.Host = clsUtilities.ReadConfigValue("SMTPClientHost");

            smtCliend.Port = Convert.ToInt32(clsUtilities.ReadConfigValue("SMTPClientPort"));

            smtCliend.Send(mm);

        }


        public static TokenDetailServiceResponse GetTokenDetails(string tokenId, string requestFrom, string userAgent)

        {

            //get token details

            string strTokenURL = clsUtilities.ReadConfigValue("smg_connect") + @"/WebServices/Services2.svc/API/TokenDetail";

            Dictionary<string, string> TokenServiceHeader = new Dictionary<string, string>();

            if (string.IsNullOrWhiteSpace(tokenId))

            {

                throw new Exception("tokenId cannot be blank.");

            }

            else

            {

                TokenServiceHeader.Add("tokenId", tokenId);

            }

            if (!string.IsNullOrWhiteSpace(requestFrom))

            {

                TokenServiceHeader.Add("requestFrom", requestFrom);

            }

            if (!string.IsNullOrWhiteSpace(userAgent))

            {

                TokenServiceHeader.Add("user-agent", userAgent);

            }

            var TokenServiceResult = CallREST_ServiceWithAuthentication(strTokenURL, "GET", "", dicHeaderKeyValues: TokenServiceHeader);

            TokenDetailServiceResponse objTokenDetailServiceResponse = JsonConvert.DeserializeObject<TokenDetailServiceResponse>(TokenServiceResult);


            return objTokenDetailServiceResponse;

        }


        public static async Task<Face[]> UploadAndDetectFacesCustomized(string imageFilePath, IFaceServiceClient faceServiceClient)

        {

            using (Stream imageFileStream = System.IO.File.OpenRead(imageFilePath))

            {

                var faces = await faceServiceClient.DetectAsync(imageFileStream,

                    true,

                    false);

                return faces.ToArray();

            }

        }


        public class extResourceManager : LangText

        {

            private static global::System.Globalization.CultureInfo resourceCulture;


            /// <summary>

            ///   Overrides the current thread's CurrentUICulture property for all

            ///   resource lookups using this strongly typed resource class.

            /// </summary>

            [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]

            public static global::System.Globalization.CultureInfo Culture

            {

                get

                {

                    return resourceCulture;

                }

                set

                {

                    resourceCulture = value;

                }

            }


            public static string getKeyValue(string strKey)

            {

                return ResourceManager.GetString(strKey, resourceCulture);

            }

        }


        public static int checkMenuAccess(List<AI_Portal_Cloud.Utilities.ModelClasses.ParentMenuModel> list)

        {

            if(list !=null)

            {

                string url = HttpContext.Current.Request.Url.AbsolutePath;


                List<AI_Portal_Cloud.Utilities.ModelClasses.ParentMenuModel> resultScreenRole = list.Where(item => item.menu_form == url).ToList();

                return resultScreenRole.Count;

            }

            return 0;

        }


        public string GetDeviceNmBasedOnReq(HttpRequestBase objRequest)

        {

            string strDeviceType = "DESKTOP";

            string userAgent = objRequest.UserAgent;// objRequest.ServerVariables["HTTP_USER_AGENT"];


            if (string.IsNullOrWhiteSpace(userAgent))

            {

                return strDeviceType.ToUpper();

            }


            userAgent = userAgent.ToLower();


            if (userAgent.Contains("android"))

            {

                strDeviceType = "Android";

            }

            else if (userAgent.Contains("iphone"))

            {

                strDeviceType = "iPhone";

            }

            else if (userAgent.Contains("ipad"))

            {

                strDeviceType = "ipad";

            }

            else if (userAgent.Contains("mac os") || userAgent.Contains(" ios "))

            {

                strDeviceType = "iOS";

            }

            else if (userAgent.Contains("mobile"))

            {

                strDeviceType = "mobile";

            }

            else

            {

                strDeviceType = "Desktop";

            }


            //if (objRequest.Browser.IsMobileDevice)

            //{

            //    strDeviceType = "MOBILE";

            //}


            //string usrOS = userAgent.ToLower();

            //if (!objRequest.Browser.IsMobileDevice)

            //{

            //    if (usrOS.IndexOf("android") > 0)

            //        strDeviceType = "Android";

            //    else if (usrOS.IndexOf("ipad") > 0 | usrOS.IndexOf("iphone") > 0 | usrOS.IndexOf("ios") > 0)

            //        strDeviceType = "iOS";

            //    else

            //        strDeviceType = "Desktop";

            //}

            //else if (usrOS.IndexOf("android") > 0)

            //    strDeviceType = "Android";

            //else if (usrOS.IndexOf("ipad") > 0)

            //    strDeviceType = "ipad";

            //else if (usrOS.IndexOf("iphone") > 0)

            //    strDeviceType = "iphone";

            //else if (usrOS.IndexOf("ios") > 0)

            //    strDeviceType = "iOS";

            //else if (usrOS.IndexOf("windows phone") > 0)

            //    strDeviceType = "Window";

            //else

            //    strDeviceType = "Desktop";


            return strDeviceType.ToUpper();

        }

        public string GetDeviceNmBasedOnReq()

        {

            var objRequest = System.Web.HttpContext.Current.Request;

            string strDeviceType = "DESKTOP";

            string userAgent = objRequest.ServerVariables["HTTP_USER_AGENT"];


            if (objRequest.Browser.IsMobileDevice)

            {

                strDeviceType = "MOBILE";

            }


            string usrOS = userAgent.ToLower();

            if (!objRequest.Browser.IsMobileDevice)

            {

                if (usrOS.IndexOf("android") > 0)

                    strDeviceType = "Android";

                else if (usrOS.IndexOf("ipad") > 0 | usrOS.IndexOf("iphone") > 0 | usrOS.IndexOf("ios") > 0)

                    strDeviceType = "iOS";

                else

                    strDeviceType = "Desktop";

            }

            else if (usrOS.IndexOf("android") > 0)

                strDeviceType = "Android";

            else if (usrOS.IndexOf("ipad") > 0)

                strDeviceType = "ipad";

            else if (usrOS.IndexOf("iphone") > 0)

                strDeviceType = "iphone";

            else if (usrOS.IndexOf("ios") > 0)

                strDeviceType = "iOS";

            else if (usrOS.IndexOf("windows phone") > 0)

                strDeviceType = "Window";

            else

                strDeviceType = "Desktop";


            return strDeviceType.ToUpper();

        }


        public static void ExportToExcel(DataTable tblReady, string strFileNameWithoutExtension = "Reports")

        {

            DataTable tbl = tblReady.Clone();


            //' convert all the columns type to String 

            foreach (DataColumn col in tbl.Columns)

            {

                col.DataType = typeof(string);

            }


            tbl.Load(tblReady.CreateDataReader());


            //new code

            strFileNameWithoutExtension = strFileNameWithoutExtension.Replace(".xls", "");

            using (ExcelPackage pck = new ExcelPackage())

            {

                //Create the worksheet

                ExcelWorksheet ws = pck.Workbook.Worksheets.Add(strFileNameWithoutExtension);


                //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1

                ws.Cells["A1"].LoadFromDataTable(tbl, true);


                for (int i = 1; i <= tbl.Columns.Count; i++)

                {

                    var cell = ws.Cells[1, i];

                    cell.Style.Font.Bold = true;

                    cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;

                    cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;

                    //cell.Style.Fill.PatternType = ExcelFillStyle.Solid;

                    //cell.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(79, 129, 189));  //Set color to dark blue

                    //cell.Style.Font.Color.SetColor(System.Drawing.Color.White);

                }


                ws.Cells.AutoFitColumns(5.50, 60.50);

                ws.Cells.Style.WrapText = true;


                var start = ws.Dimension.Start;

                var end = ws.Dimension.End;

                for (int row = start.Row; row <= end.Row; row++)

                { // Row by row...

                    for (int col = start.Column; col <= end.Column; col++)

                    { // ... Cell by cell...

                        ws.Cells[row, col].Style.Border.Top.Style = ExcelBorderStyle.Thin;

                        ws.Cells[row, col].Style.Border.Left.Style = ExcelBorderStyle.Thin;

                        ws.Cells[row, col].Style.Border.Right.Style = ExcelBorderStyle.Thin;

                        ws.Cells[row, col].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;

                    }

                }


                ws.Cells.Style.Font.Size = 10;

                //ws.Cells.IsRichText = true;


                //Write it back to the client

                HttpContext.Current.Response.Clear();

                HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;  filename=" + strFileNameWithoutExtension + ".xlsx");

                HttpContext.Current.Response.BinaryWrite(pck.GetAsByteArray());

                HttpContext.Current.Response.Flush();

                HttpContext.Current.Response.End();

            }


        }

        public static string RandomString(int length)

        {

            const string chars = "abcdefghijklmnABCDEFGHIJKLMN!@#$%^&*0123456789";

            return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());

        }


        public static void CommonHeaderValidation(NameValueCollection headers, bool isTokenRequired = true)

        {

            if (string.IsNullOrWhiteSpace(headers["UUID"]))

                throw new Exception("Header param: UUID cannot be blank.");


            //if (string.IsNullOrWhiteSpace(headers["policy_app_name"]))

            //    throw new Exception("Header param: policy_app_name cannot be blank.");


            if (isTokenRequired == true)

            {

                if (string.IsNullOrWhiteSpace(headers["tokenId"]))

                    throw new Exception("Header param: tokenId cannot be blank.");

                //else if (string.IsNullOrWhiteSpace(headers["IsLoggedInAs"]))

                //    throw new Exception("Header param: IsLoggedInAs cannot be blank.");

                //else if (headers["IsLoggedInAs"].ToString() != "0" & headers["IsLoggedInAs"].ToString() != "1")

                //    throw new Exception("Header param: IsLoggedInAs is invalid.");

                //else if (headers["IsLoggedInAs"].ToString() == "1")

                //{

                //    if (string.IsNullOrWhiteSpace(headers["ParentTokenId"]))

                //        throw new Exception("Header param: ParentTokenId cannot be blank.");

                //}

            }


            if (string.IsNullOrWhiteSpace(headers["build_name"]))

                throw new Exception("Header param: build_name cannot be blank.");

        }


    

        public static string MaskEmailAddress(string input)

        {

            string result = string.Format("{0}******{1}{2}******{3}", input[0], input.Substring(input.IndexOf('@') - 1, 2), input.Substring(input.IndexOf('@') + 1, 1), input.Substring(input.LastIndexOf('.') - 1));

            return result;

        }


        public static int GetStatusCode(int defaultStatusCode,string msg)

        {

            if(msg.ToUpper()== "TOKEN_EXPIRED")

            {

                defaultStatusCode = 401;

            }

            else if (msg.ToUpper() == "INVALID_TOKEN")

            {

                defaultStatusCode = 402;

            }

            return defaultStatusCode;

        }

        public static void DownloadUserMasterTemplate()

        {

            //create copy of template

            string strTemplateFileName = "UserCreateExcel.xlsx";

            string sharedPath = clsUtilities.ReadConfigValue("UploadedFiles_Path1");

            string sourcePath = sharedPath + @"\" + strTemplateFileName;

            if (!File.Exists(sourcePath))

            {

                throw new Exception(strTemplateFileName + " not found.");

            }


            string targetPath = sharedPath + @"\UserMaster";

            if (!Directory.Exists(targetPath))

            {

                Directory.CreateDirectory(targetPath);

            }

            targetPath = Path.Combine(targetPath, Guid.NewGuid().ToString() + Path.GetExtension(strTemplateFileName));

            File.Copy(sourcePath, targetPath, true);


            //do changes in template

            FileInfo newFile = new FileInfo(targetPath);

            using (ExcelPackage pck = new ExcelPackage(newFile))

            {

                //Lock workbook

                //Additionally don't allow user to change sheet names

                //pck.Workbook.Protection.LockStructure = true;


                /*------Unit Summary------*/

                //var wsUnitSummary = pck.Workbook.Worksheets["Unit Planning Summary"];


                //wsUnitSummary.Cells["F14"].Value = "Past Actual" + Environment.NewLine + Prevyear;


                //unlock cell

                //wsUnitSummary.Cells[7, 3, 18, 3].Style.Locked = false;


                //Lock sheets

                //wsUnitSummary.Protection.IsProtected = true;


                /*------Unit Details------*/

                //var wsUnitDetails = pck.Workbook.Worksheets["Unit Planning Details"];


                //wsUnitDetails.Cells["D10"].Value = Currentyear;

                //wsUnitDetails.Cells["G10"].Value = company;

                //wsUnitDetails.Cells["M10"].Value = unit;

                //wsUnitDetails.Cells["D5"].Value = Currentyear;


                //unlock cell

                //wsUnitDetails.Cells[7, 4, 12, 15].Style.Locked = false;//manpower & QC

                //wsUnitDetails.Cells[16, 4, 23, 15].Style.Locked = false;//training

                //wsUnitDetails.Cells[25, 4, 26, 15].Style.Locked = false;//Review

                //wsUnitDetails.Cells[27, 3, 28, 15].Style.Locked = false;//Project of existing

                //wsUnitDetails.Cells[30, 3, 31, 15].Style.Locked = false;//Project of new


                //wsUnitDetails.Protection.AllowInsertRows = true;

                //wsUnitDetails.Protection.AllowDeleteRows = true;


                //Lock sheets

                //wsUnitDetails.Protection.IsProtected = true;


                //Write it back to the client

                HttpContext.Current.Response.Clear();

                HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;  filename=" + System.Uri.EscapeDataString(strTemplateFileName));

                HttpContext.Current.Response.BinaryWrite(pck.GetAsByteArray());

                HttpContext.Current.Response.Flush();

                HttpContext.Current.Response.End();

            }

        }


        public static string MIND_SSOEncrypt(string toEncrypt, bool useHashing = true)

        {

            byte[] keyArray;

            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            string key = "CPPKey";


            if (useHashing)

            {

                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();

                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));

                hashmd5.Clear();

            }

            else

                keyArray = UTF8Encoding.UTF8.GetBytes(key);


            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            tdes.Key = keyArray;

            tdes.Mode = CipherMode.ECB;

            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            tdes.Clear();

            return Convert.ToBase64String(resultArray, 0, resultArray.Length);

        }


        public static double ConvertRSStoMeter(double val)

        {

            double x = -65 - val;

            double tV = (x / 20.0);

            double tVal = Math.Round(Math.Pow(10, tV), 2);


            return tVal;

        }


        public static string urlDecode(string url, string param)

        {

            string paramsv = "";

            string[] paramparts = url.Split('?');

            if (paramparts.Length > 1)

            {

                string[] paramsq = paramparts[1].Split('&');

                if (param == "loginId")

                {

                    paramsv = After(paramsq[0], param + "=");

                }

                else if (param == "domain")

                {

                    paramsv = After(paramsq[1], param + "=");

                }

                else if (param == "Token")

                {

                    paramsv = After(paramsq[2], param + "=");

                }

                else if (param == "RMode")

                {

                    paramsv = After(paramsq[3], param + "=");

                }

                else if (param == "RComp")

                {

                    paramsv = After(paramsq[4], param + "=");

                }

                else if (param == "IdeaID")

                {

                    paramsv = After(paramsq[5], param + "=");

                }

            }

            return paramsv;

        }


        public static string After(string value, string a)

        {

            string[] splitstr = value.Split('=');

            string[] splitparam = a.Split('=');

            if (splitstr[0] == splitparam[0])

            {

                int posA = value.LastIndexOf(a);

                if (posA == -1)

                {

                    return "";

                }

                int adjustedPosA = posA + a.Length;

                if (adjustedPosA >= value.Length)

                {

                    return "";

                }

                return value.Substring(adjustedPosA);

            }

            else

            {

                return "";

            }

        }


        public static string TokenDecrypt(string cipherString, bool useHashing)

        {

            byte[] keyArray;

            //get the byte code of the string

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

            //Key like a public key

            string key = "CPPKey";

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

        }

    }

}


Comments

Popular posts from this blog

Npgsql query and format with output parameters

Npgsql Helper class