Sunday, November 30, 2014

Sunday, November 16, 2014

Method to automatic print

  public static void Print()
        {
            const string printerName =
               "Microsoft Office Document Image Writer";
            if (m_streams == null || m_streams.Count == 0)
                return;
            PrintDocument printDoc = new PrintDocument();
            printDoc.PrinterSettings.PrinterName = printerName;
            if (!printDoc.PrinterSettings.IsValid)
            {
                string msg = String.Format(
                   "Can't find printer \"{0}\".", printerName);
                return;
            }
            printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
            printDoc.Print();
        }
        private static void PrintPage(object sender, PrintPageEventArgs ev)
        {
            Metafile PageImage = new Metafile(m_streams[m_currentPageIndex]);
            ev.Graphics.DrawImage(PageImage, ev.PageBounds);
            Debug.Print(m_currentPageIndex.ToString());
            m_currentPageIndex++;
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
        }

Method to get the Sum of specified column in the datatable

  /// <summary>
        /// Returns the Sum of specified column in the datatable
        /// </summary>
        /// <param name="columnName"></param>
        /// <param name="dtSource"></param>
        /// <returns>Decimal. The source column should be in decimal format</returns>
        public static decimal GetColumnTotal(string columnName, DataTable dtSource)
        {
            decimal total = 0;
            try
            { total = dtSource.AsEnumerable().Sum(o => Convert.ToDecimal(o.Field<object>(columnName))); }
            catch
            { }
            return total;
        }

Method to get Quantity Value

  public static string GetQty(object value)
        {
            string qty = string.Empty;
            decimal amount;
            if (value != null && Decimal.TryParse(value.ToString(), out amount))
            {
                qty = amount.ToString("N");
            }
            return qty;
        }

Method to format Currency

 public static string GetCurrency(object value)
        {
            string currency = string.Empty;
            decimal amount;
            if (value != null && Decimal.TryParse(value.ToString(), out amount))
            {
                currency = amount.ToString("c");
            }
            return currency;
        }

For getting string as Html encoded

 /// <summary>
        /// For getting string as Html encoded
        /// </summary>
        /// <param name="orginalString"></param>
        /// <param name="limit"></param>
        /// <returns>string</returns>
        public static string GetEncodedString(object evelOrginalString)
        {
            string orginalString = HttpUtility.HtmlEncode(Convert.ToString(evelOrginalString));
            return orginalString;
        }

For getting string as Html decoded

 /// <summary>
        /// For getting string as Html decoded
        /// </summary>
        /// <param name="orginalString"></param>
        /// <param name="limit"></param>
        /// <returns>string</returns>
        public static string GetDecodedString(object evelOrginalString)
        {
            string orginalString = HttpUtility.HtmlDecode(Convert.ToString(evelOrginalString));
            return orginalString;
        }

Nullable Int

  public static int? NullableInt(string str)
        {
            int i;
            if (int.TryParse(str, out i))
                return i;
            return null;
        }

Method to get List of T elements

  public static List<T> GetResults<T>(T element, ObjectContext ctx, string cmd)
        {
            // List of T elements to be returned.
            List<T> results = null;

            // Execute the query
            if (cmd == "")
            {
                results = null;
            }
            else
            {
                results = ctx.ExecuteStoreQuery<T>(cmd, null).ToList();
            }

            // Return the results
            return results;
        }

Process multiline message

 /// <summary>
        /// Process multiline message
        /// </summary>
        /// <param name="heading"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public static string ProcessMessageList(string heading, List<string> messages)
        {
            StringBuilder messageText;
            messageText = new StringBuilder();
            messageText.Append(heading);
            messageText.Append(messages.Count > 0 ? ERPUtilityResources.MsgStart : string.Empty);
            foreach (string message in messages)
            {
                messageText.Append(string.Format(ERPUtilityResources.MsgFormat, message));
            }
            messageText.Append(messages.Count > 0 ? ERPUtilityResources.MsgEnd : string.Empty);
            return messageText.ToString();
        }

Generate Dynamic Script

 /// <summary>
        /// Add Date Time/Time script dynamically
        /// </summary>
        /// <param name="controlType"></param>
        /// <param name="controlID"></param>
        /// <returns></returns>
        public static string GenerateDynamicScript(string controlType, string controlID, string hdfToRange, string fromDate, string hdfFrmDate)
        {
            string script = string.Empty;
            switch ((ControlTypes)(Enum.Parse(typeof(ControlTypes), controlType)))
            {
                case ControlTypes.TimePicker:
                    script = "$('input:text[id$=" + controlID + "]').timepicker();";
                    break;
                case ControlTypes.DateTime:
                    script = "ERPScriptUtils.DatePickerCommon('" + controlID + "');";
                    script = script + "$('input:text[id$=" + controlID + "_Time]').timepicker();";
                    break;
                case ControlTypes.Date:
                    script = "ERPScriptUtils.DatePickerCommon('" + controlID + "');";
                    break;
                case ControlTypes.DateRange:
                    script = "ERPScriptUtils.AddDateRangeCommon('" + fromDate + "', '" + hdfFrmDate + "', '" + controlID + "', '" + hdfToRange + "', false, false);";
                    break;
                case ControlTypes.MonthPicker:
                    script = "ControlID= '" + controlID + "';";
                    break;
            }

            return script;
        }

HTML Decode field of object

  /// <summary>
        /// HTML Decode field of object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="item"></param>
        /// <param name="field"></param>
        public static void HtmlDecode<T>(T item, string field)
        {
            Type type;
            PropertyInfo fieldPropertyInfo;
            type = item.GetType();
            fieldPropertyInfo = type.GetProperty(field);
            if (fieldPropertyInfo.PropertyType == typeof(string))
                fieldPropertyInfo.SetValue(item, HttpUtility.HtmlDecode(Convert.ToString(fieldPropertyInfo.GetValue(item, null))), null);
        }

HTML Decode field in List

 /// <summary>
        /// HTML Decode field in List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="lst"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static List<T> HtmlDecode<T>(List<T> lst, string field)
        {
            lst.ForEach(itm => HtmlDecode(itm, field));
            return lst;
        }

Method to Get formated list of objects for auto complete

/// <summary>
        /// Get formated list of objects for auto complete
        /// </summary>
        /// <param name="dynamicList">List for formatting</param>
        /// <param name="textProperty1">First Text property name</param>
        /// <param name="textProperty2">Second Text property name</param>
        /// <param name="valueProperty">Value property name</param>
        /// <param name="isCombined">whether the two Text Properties are concantinated</param>
        /// <returns></returns>
        public static dynamic GetFormatedAutoCompleteList(dynamic dynamicList, string textProperty1, string textProperty2, string valueProperty, bool isCombined)
        {
            // Gets or sets list of objects for auto complete
            List<TextValue> textValueList;
            // Gets the type of dynamic object in the list
            Type type;
            // Gets or sets text property information from dynamic object
            PropertyInfo textPropertyInfo1;
            // Gets or sets text property information from dynamic object
            PropertyInfo textPropertyInfo2;
            // Gets or sets value property information from dynamic object
            PropertyInfo valuePropertyInfo;
            try
            {
                // initilize new instance of TextValue class
                textValueList = new List<TextValue>();
                // Iterate through each object in the dynamic list
                foreach (dynamic dynamicObject in dynamicList)
                {
                    // Sets type of dynamic object
                    type = dynamicObject.GetType();
                    // Sets text property information
                    textPropertyInfo1 = type.GetProperty(textProperty1);
                    // Sets text property information
                    textPropertyInfo2 = type.GetProperty(textProperty2);
                    // Sets value property information
                    valuePropertyInfo = type.GetProperty(valueProperty);
                    // Add object to text value list
                    textValueList.Add(new TextValue()
                    {
                        // Sets text propert after html decoding
                        Text = HttpUtility.HtmlDecode(string.Format(ERPUtilityResources.NameCodeFormat, Convert.ToString(textPropertyInfo1.GetValue(dynamicObject, null)),
                        Convert.ToString(textPropertyInfo2.GetValue(dynamicObject, null)))),
                        // Sets value property
                        Value = HttpUtility.HtmlDecode(Convert.ToString(valuePropertyInfo.GetValue(dynamicObject, null))),
                    });
                }
                // Returns formated list for auto complete
                return textValueList;
            }
            catch (Exception ex)
            {
                // throws exception to calling function
                throw ex;
            }
            finally
            {
                // Disposing used objects
                textValueList = null;
                type = null;
                textPropertyInfo1 = null;
                textPropertyInfo2 = null;
                valuePropertyInfo = null;
            }
        }

Method to Get formated list of objects for auto complete

  /// <summary>
        /// Get formated list of objects for auto complete
        /// </summary>
        /// <param name="dynamicList">List for formatting</param>
        /// <param name="textProperty1">Text property name</param>
        /// <param name="pairedProperty">Paired Text property name</param>
        /// <param name="valueProperty">Value property name</param>
        /// <returns></returns>
        public static dynamic GetFormatedAutoCompleteList(dynamic dynamicList, string textProperty, string pairedProperty, string valueProperty)
        {
            // Gets or sets list of objects for auto complete
            List<PairedValue> pairedValueList;
            // Gets the type of dynamic object in the list
            Type type;
            // Gets or sets text property information from dynamic object
            PropertyInfo textPropertyInfo;
            // Gets or sets value property information from dynamic object
            PropertyInfo valuePropertyInfo;
            // Gets or sets PairText property information from dynamic object
            PropertyInfo pairedPropertyInfo;
            try
            {
                // initilize new instance of TextValue class
                pairedValueList = new List<PairedValue>();
                // Iterate through each object in the dynamic list
                foreach (dynamic dynamicObject in dynamicList)
                {
                    // Sets type of dynamic object
                    type = dynamicObject.GetType();
                    // Sets text property information
                    textPropertyInfo = type.GetProperty(textProperty);
                    // Sets value property information
                    valuePropertyInfo = type.GetProperty(valueProperty);
                    // Add object to text value list
                    pairedPropertyInfo = type.GetProperty(pairedProperty);
                    pairedValueList.Add(new PairedValue()
                    {
                        // Sets text propert after html decoding
                        Text = HttpUtility.HtmlDecode(Convert.ToString(textPropertyInfo.GetValue(dynamicObject, null))),
                        // Sets value property
                        Value = HttpUtility.HtmlDecode(Convert.ToString(valuePropertyInfo.GetValue(dynamicObject, null))),
                        // Sets PairText property
                        PairText = HttpUtility.HtmlDecode(Convert.ToString(pairedPropertyInfo.GetValue(dynamicObject, null))),
                    });
                }
                // Returns formated list for auto complete
                return pairedValueList;
            }
            catch (Exception ex)
            {
                // throws exception to calling function
                throw ex;
            }
            finally
            {
                // Disposing used objects
                pairedValueList = null;
                type = null;
                textPropertyInfo = null;
                valuePropertyInfo = null;
                pairedPropertyInfo = null;
            }
        }

Method to Get formated list of objects for auto complete

   /// <summary>
        /// Get formated list of objects for auto complete
        /// </summary>
        /// <param name="dynamicList">List for formatting</param>
        /// <param name="textProperty">Text property name</param>
        /// <param name="valueProperty">Value property name</param>
        /// <returns></returns>
        public static dynamic GetFormatedAutoCompleteList(dynamic dynamicList, string textProperty, string valueProperty)
        {
            // Gets or sets list of objects for auto complete
            List<TextValue> textValueList;
            // Gets the type of dynamic object in the list
            Type type;
            // Gets or sets text property information from dynamic object
            PropertyInfo textPropertyInfo;
            // Gets or sets value property information from dynamic object
            PropertyInfo valuePropertyInfo;
            try
            {
                // initilize new instance of TextValue class
                textValueList = new List<TextValue>();
                // Iterate through each object in the dynamic list
                foreach (dynamic dynamicObject in dynamicList)
                {
                    // Sets type of dynamic object
                    type = dynamicObject.GetType();
                    // Sets text property information
                    textPropertyInfo = type.GetProperty(textProperty);
                    // Sets value property information
                    valuePropertyInfo = type.GetProperty(valueProperty);
                    // Add object to text value list
                    textValueList.Add(new TextValue()
                    {
                        // Sets text propert after html decoding
                        Text = HttpUtility.HtmlDecode(Convert.ToString(textPropertyInfo.GetValue(dynamicObject, null))),
                        // Sets value property
                        Value = HttpUtility.HtmlDecode(Convert.ToString(valuePropertyInfo.GetValue(dynamicObject, null))),
                    });
                }
                // Returns formated list for auto complete
                return textValueList;
            }
            catch (Exception ex)
            {
                // throws exception to calling function
                throw ex;
            }
            finally
            {
                // Disposing used objects
                textValueList = null;
                type = null;
                textPropertyInfo = null;
                valuePropertyInfo = null;
            }
        }

Method to initialize Entity Object

  /// <summary>
        /// Method to initialize Entity Object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T Initilize<T>()
        {
            T src = Activator.CreateInstance<T>();
            Type targetType = src.GetType();

            //    Loop through the source properties
            foreach (PropertyInfo p in targetType.GetProperties())
            {
                if (p.CanWrite)
                {
                    Type ptype = p.PropertyType;

                    if (ptype == typeof(byte))
                        p.SetValue(src, byte.MinValue, null);
                    if (ptype == typeof(string))
                        p.SetValue(src, string.Empty, null);
                    else if (ptype == typeof(int))
                        p.SetValue(src, (int)-1, null);
                    //else if (ptype == typeof(int?))
                    //    p.SetValue(src, (int)-1, null);
                    else if (ptype == typeof(Int64))
                        p.SetValue(src, (Int64)(-1), null);
                    //else if (ptype == typeof(Int64?))
                    //    p.SetValue(src, (Int64)(-1), null);
                    else if (ptype == typeof(Int32))
                        p.SetValue(src, (Int32)(-1), null);
                    //else if (ptype == typeof(Int32?))
                    //    p.SetValue(src, (Int32)(-1), null);
                    else if (ptype == typeof(short))
                        //p.SetValue(src, (short)255, null);
                        p.SetValue(src, (short)-1, null);
                    //else if (ptype == typeof(short?))
                    //    p.SetValue(src, (short)255, null);
                    else if (ptype == typeof(float))
                        p.SetValue(src, (float)(-1), null);
                    //else if (ptype == typeof(float?))
                    //    p.SetValue(src, (float)(-1), null);
                    else if (ptype == typeof(decimal))
                        p.SetValue(src, Convert.ToDecimal(-1), null);
                    //else if (ptype == typeof(decimal?))
                    //    p.SetValue(src, Convert.ToDecimal(-1), null);
                    else if (ptype == typeof(bool))
                        p.SetValue(src, false, null);
                    //else if (ptype == typeof(bool?))
                    //    p.SetValue(src, false, null);
                    else if (ptype == typeof(DateTime))
                        p.SetValue(src, DateTime.MinValue, null);
                    //else if (ptype == typeof(DateTime?))
                    //    p.SetValue(src, DateTime.MinValue, null);
                }
            }

            return src;
        }

Checking Security Exception using certificate

  /// <summary>
        /// Checking Security Exception using certificate
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="certificate"></param>
        /// <param name="chain"></param>
        /// <param name="sslPolicyErrors"></param>
        /// <returns></returns>
        public static bool IgnoreCertificateErrorHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

Method to Process Exception For Entity

 /// <summary>
        ///
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public static Exception ProcessServerException(string className, string methodName, Exception exception)
        {
            // Gets or sets update exception
            UpdateException updateException;

            // Checking Exception message ends with gti exception token (GTI_EXCEPTION)
            if (exception.Message.EndsWith(ERPUtilityResources.GTIExceptionWithToken) == false)
            {
                // Checking Exception is sql exception
                SqlException sqlException = exception.InnerException as SqlException;
                if (sqlException != null)
                {
                    // Returns a new exception to service class with class name - method name - sql exception exception with corresponding exception number as exception message
                    return new Exception(className + ERPUtilityResources.ExceptionToken + methodName + ERPUtilityResources.ExceptionToken + ERPUtilityResources.SqlException + sqlException.Number.ToString() + ERPUtilityResources.GTIExceptionDetailsWithToken + sqlException.Message + ERPUtilityResources.GTIExceptionWithToken);
                }
                else
                {
                    // Checking Exception is optimistic concurrency exception
                    OptimisticConcurrencyException concurrencyException = exception.InnerException as OptimisticConcurrencyException;
                    if (concurrencyException != null)
                    {
                        // Returns a new exception to service class with class name - method name - concurrency exception with corresponding exception number as exception message
                        return new Exception(className + ERPUtilityResources.ExceptionToken + methodName + ERPUtilityResources.ExceptionToken + ERPUtilityResources.OptimisticConcurrencyException + concurrencyException.GetHashCode().ToString() + ERPUtilityResources.GTIExceptionDetailsWithToken + concurrencyException.Message + ERPUtilityResources.GTIExceptionWithToken);
                    }
                    else
                    {
                        // Checking Exception is argument null exception
                        ArgumentNullException argException = exception as ArgumentNullException;
                        if (argException != null)
                        {
                            // Returns a new exception to service class with class name - method name - argument null exception with default exception number as exception message
                            return new Exception(className + ERPUtilityResources.ExceptionToken + methodName + ERPUtilityResources.ExceptionToken + ERPUtilityResources.ArgumentNullException + ERPUtilityResources.DefaultErrorNumber + ERPUtilityResources.GTIExceptionDetailsWithToken + argException.Message + ERPUtilityResources.GTIExceptionWithToken);
                        }
                        else
                        {
                            // Checking Exception is optimistic concurrency exception (concurrency exception from manager class)
                            concurrencyException = exception as OptimisticConcurrencyException;

                            if (concurrencyException != null)
                            {
                                // Returns a new exception to service class with class name - method name - concurrency exception with default exception number as exception message
                                return new Exception(className + ERPUtilityResources.ExceptionToken + methodName + ERPUtilityResources.ExceptionToken + ERPUtilityResources.OptimisticConcurrencyException + ERPUtilityResources.DefaultErrorNumber + ERPUtilityResources.GTIExceptionDetailsWithToken + concurrencyException.Message + ERPUtilityResources.GTIExceptionWithToken);
                            }
                            else
                            {
                                // Checking Exception is update exception (record already exists exception from manager class.thrown from manager class with page requirments)
                                updateException = exception as UpdateException;

                                if (updateException != null)
                                {
                                    if (updateException.Message.Equals(ERPUtilityResources.DateRangeException))
                                    {
                                        // Returns a new exception to service class with class name - method name - record already exists exception with default exception number as exception message
                                        return new Exception(className + ERPUtilityResources.ExceptionToken + methodName + ERPUtilityResources.ExceptionToken + ERPUtilityResources.DateRangeException + ERPUtilityResources.DefaultErrorNumber + ERPUtilityResources.GTIExceptionDetailsWithToken + updateException.Message + ERPUtilityResources.GTIExceptionWithToken);
                                    }
                                    else if (updateException.Message.Equals(ERPUtilityResources.OutofStockException))
                                    {
                                        // Returns a new exception to service class with class name - method name - out of stock exception with default exception number as exception message
                                        return new Exception(className + ERPUtilityResources.ExceptionToken + methodName + ERPUtilityResources.ExceptionToken + ERPUtilityResources.OutofStockException + ERPUtilityResources.ExceptionToken + ERPUtilityResources.DefaultErrorNumber + ERPUtilityResources.GTIExceptionDetailsWithToken + updateException.Message + ERPUtilityResources.GTIExceptionWithToken);
                                    }
                                    else if (updateException.Message.Equals(ERPUtilityResources.FromToRangeException))
                                    {
                                        // Returns a new exception to service class with class name - method name - out of stock exception with default exception number as exception message
                                        return new Exception(className + ERPUtilityResources.ExceptionToken + methodName + ERPUtilityResources.ExceptionToken + ERPUtilityResources.FromToRangeException + ERPUtilityResources.ExceptionToken + ERPUtilityResources.DefaultErrorNumber + ERPUtilityResources.GTIExceptionDetailsWithToken + updateException.Message + ERPUtilityResources.GTIExceptionWithToken);
                                    }
                                    else if (updateException.Message.Equals(ERPUtilityResources.ItemExistException))
                                    {
                                        // Returns a new exception to service class with class name - method name - out of stock exception with default exception number as exception message
                                        return new Exception(className + ERPUtilityResources.ExceptionToken + methodName + ERPUtilityResources.ExceptionToken + ERPUtilityResources.ItemExistException + ERPUtilityResources.ExceptionToken + ERPUtilityResources.DefaultErrorNumber + ERPUtilityResources.GTIExceptionDetailsWithToken + updateException.Message + ERPUtilityResources.GTIExceptionWithToken);
                                    }
                                    else if (updateException.Message.Equals(ERPUtilityResources.NoItemException))
                                    {
                                        // Returns a new exception to service class with class name - method name - out of stock exception with default exception number as exception message
                                        return new Exception(className + ERPUtilityResources.ExceptionToken + methodName + ERPUtilityResources.ExceptionToken + ERPUtilityResources.NoItemException + ERPUtilityResources.ExceptionToken + ERPUtilityResources.DefaultErrorNumber + ERPUtilityResources.GTIExceptionDetailsWithToken + updateException.Message + ERPUtilityResources.GTIExceptionWithToken);
                                    }
                                    else if (updateException.Message.Equals(ERPUtilityResources.ManyItemException))
                                    {
                                        // Returns a new exception to service class with class name - method name - out of stock exception with default exception number as exception message
                                        return new Exception(className + ERPUtilityResources.ExceptionToken + methodName + ERPUtilityResources.ExceptionToken + ERPUtilityResources.ManyItemException + ERPUtilityResources.ExceptionToken + ERPUtilityResources.DefaultErrorNumber + ERPUtilityResources.GTIExceptionDetailsWithToken + updateException.Message + ERPUtilityResources.GTIExceptionWithToken);
                                    }
                                    else if (updateException.Message.Equals(ERPUtilityResources.ActivityAircraftException))
                                    {
                                        // Returns a new exception to service class with class name - method name - out of stock exception with default exception number as exception message
                                        return new Exception(className + ERPUtilityResources.ExceptionToken + methodName + ERPUtilityResources.ExceptionToken + ERPUtilityResources.ActivityAircraftException + ERPUtilityResources.ExceptionToken + ERPUtilityResources.DefaultErrorNumber + ERPUtilityResources.GTIExceptionDetailsWithToken + updateException.Message + ERPUtilityResources.GTIExceptionWithToken);
                                    }
                                    else if (updateException.Message.Equals(ERPUtilityResources.ShiftAttendanceExistException))
                                    {
                                        // Returns a new exception to service class with class name - method name - out of stock exception with default exception number as exception message
                                        return new Exception(className + ERPUtilityResources.ExceptionToken + methodName + ERPUtilityResources.ExceptionToken + ERPUtilityResources.ShiftAttendanceExistException + ERPUtilityResources.ExceptionToken + ERPUtilityResources.DefaultErrorNumber + ERPUtilityResources.GTIExceptionDetailsWithToken + updateException.Message + ERPUtilityResources.GTIExceptionWithToken);
                                    }
                                    else
                                    {
                                        // Returns a new exception to service class with class name - method name - record already exists exception with default exception number as exception message
                                        return new Exception(className + ERPUtilityResources.ExceptionToken + methodName + ERPUtilityResources.ExceptionToken + ERPUtilityResources.RecordAlreadyExistsException + ERPUtilityResources.DefaultErrorNumber + ERPUtilityResources.GTIExceptionDetailsWithToken + updateException.Message + ERPUtilityResources.GTIExceptionWithToken);
                                    }
                                }
                                else
                                {
                                    // Returns a new exception to service class with class name - method name - unknown error with default exception number as exception message
                                    return new Exception(className + ERPUtilityResources.ExceptionToken + methodName + ERPUtilityResources.ExceptionToken + ERPUtilityResources.UnknownError + ERPUtilityResources.DefaultErrorNumber + ERPUtilityResources.GTIExceptionDetailsWithToken + exception.Message + ERPUtilityResources.GTIExceptionWithToken);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                return exception;
            }
        }

Method to Send Mail

 /// <summary>
        /// Send Mail
        /// </summary>
        /// <param name="subject"></param>
        /// <param name="message"></param>
        /// <param name="toEmailId"></param>     
        /// <modifiedby></modifiedby>
        /// <modifieddate></modifieddate>
        public static bool SendMail(string subject, string message, string toEmailId)
        {

            if ((toEmailId != string.Empty))
            {
                SmtpClient client = new SmtpClient();
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
                client.Host = ConfigurationManager.AppSettings["SmtpHost"];
                client.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]);
                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["SmtpEmail"], ConfigurationManager.AppSettings["SmtpPassword"]);
                client.UseDefaultCredentials = false;
                client.Credentials = credentials;

                MailMessage msg = new MailMessage();
                //msg.Priority = MailPriority.High;
                msg.From = new MailAddress(ConfigurationManager.AppSettings["SmtpEmail"]);
                string to = toEmailId;
                msg.To.Add(new MailAddress(to));
                msg.IsBodyHtml = true;
                msg.Subject = subject;
                msg.Body = message;
                try
                {
                    client.Send(msg);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            else
            {
                return false;
            }


                }

Method to format the input string

   /// <summary>
        /// format the input string;
        /// </summary>
        /// <param name="inputString"></param>
        /// <returns></returns>
        public static string FormatInputString(string inputString)
        {
            return "'" + inputString.Trim().Replace("'", "''") + "'";
        }

Method to Encrypt Eval Key

   public static string Encrypt(string queryString)
        {
            CryptoServices cryptoServicesObj;
            cryptoServicesObj = new CryptoServices();
            if (!string.IsNullOrEmpty(queryString))
            {
                return cryptoServicesObj.EncryptString(queryString, "56565656");
            }
            else
            {
                return queryString;
            }
        }

To Decrypt Eval Key

  /// <summary>
        /// To Decrypt Eval Key
        /// </summary>
        /// <param name="queryString"></param>
        /// <returns></returns>
        public static string DecryptKey(string queryString)
        {
            CryptoServices cryptoServicesObj;
            cryptoServicesObj = new CryptoServices();
            if (!string.IsNullOrEmpty(queryString))
            {
                return cryptoServicesObj.DecryptString(queryString, "56565656");
            }
            else
            {
                return queryString;
            }
        }

Get Hour Text from Double Value

  /// <summary>
        /// Get Hour Text from Double Value
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string GetHourText(double time)
        {
            string[] timeParts = new string[2];
            timeParts[0] = (((int)time) / 60).ToString("00");
            timeParts[1] = (((int)time) % 60).ToString("00");
            return string.Format(ERPUtilityResources.FormatTime, timeParts[0], timeParts[1]);
        }

Method to Process Exception


        /// <summary>
        ///
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public static string ProcessException(Exception exception)
        {
            // Gets or sets exception mode;stored in web.config;Admin/User
            string exceptionMode = ConfigurationManager.AppSettings[ERPUtilityResources.ExceptionMode];
            // Gets or sets exception details
            string[] exceptionDetails = exception.Message.Split(ERPUtilityResources.ExceptionToken.ToCharArray());
            // Gets or sets exception source;where from exception occured
            string exceptionSource = exceptionDetails[0];
            // Gets or sets exception details count;client exception have only 1 details
            int count = exceptionDetails.Count();
            // Gets or sets error message
            string errorMessage = String.Empty;
            // Gets or sets page name
            string pageName = String.Empty;
            // Gets or sets field name (eg.pageName fieldName already exists)
            string fieldName = String.Empty;
            // Checking exception details ends with GTI_EXCEPTION;then it comes from service side
            if (exceptionDetails[count - 1].Equals(ERPUtilityResources.GTIException))
            {
                // Gets or sets exception key;key is stored as count-4 to count-3 position in exception message
                string exceptionKey = exceptionDetails[count - 4] + ERPUtilityResources.ExceptionToken + exceptionDetails[count - 3];
                // Checking exception mode is admin
                if (exceptionMode.Equals(ERPUtilityResources.Admin))
                {
                    // Gets exception message from exception details;replacing GTI_EXCEPTION_DETAILS token from message
                    errorMessage = exceptionDetails[count - 2].Replace(ERPUtilityResources.GTIExceptionDetails, String.Empty);
                    // Checking no exception details found
                    if (errorMessage.Equals(String.Empty))
                    {
                        // Sets exception message to unknown
                        errorMessage = ERPUtilityResources.UnHandledException;
                    }
                    // Return exception message to client;by encoding it;shows using jquery message
                    return errorMessage.Replace(ERPUtilityResources.SingleQuoteCharacter, ERPUtilityResources.SpaceCharacter).Replace(ERPUtilityResources.DoubleQuoteCharacter, ERPUtilityResources.SpaceCharacter).Replace(ERPUtilityResources.EnterCharacter, ERPUtilityResources.BreakTag).Replace(ERPUtilityResources.CommaCharacter, ERPUtilityResources.BreakTag).Replace(ERPUtilityResources.EditEditConcurrencyException, ERPUtilityResources.Msg_Save_Error_Concurrent);
                }
                else
                {
                    // Gets error list hash table;stored in applicaton
                    Hashtable errorList = (Hashtable)HttpContext.Current.Application[ERPUtilityResources.ErrorTable];
                    // Gets  page list hash table;stored in applicaton
                    Hashtable pageList = (Hashtable)HttpContext.Current.Application[ERPUtilityResources.PageTable];
                    // Gets field list hash table;stored in applicaton
                    Hashtable fieldList = (Hashtable)HttpContext.Current.Application[ERPUtilityResources.FieldTable];
                    // Gets pageName from application using exception source as key in error hash table
                    pageName = (pageList == null || pageList[exceptionSource] == null) ? String.Empty : pageList[exceptionSource].ToString();
                    // Gets fieldName from application using exception source as key in field hash table
                    fieldName = (fieldList == null || fieldList[exceptionSource] == null) ? "Code" : fieldList[exceptionSource].ToString();
                    // Constucting error message by appending  page name + field name + error message
                    errorMessage = String.Format((errorList == null || errorList[exceptionKey] == null) ? String.Empty : errorList[exceptionKey].ToString(),
                                pageName, fieldName);
                    // Checking no error message is empty
                    if (errorMessage.Equals(String.Empty))
                    {
                        // Sets error message as unhandled exception
                        errorMessage = ERPUtilityResources.UnHandledException;
                    }
                    // Return exception message to client;by encoding it;shows using jquery message
                    return errorMessage.Replace(ERPUtilityResources.EnterCharacter, ERPUtilityResources.BreakTag).Replace(ERPUtilityResources.CommaCharacter, ERPUtilityResources.BreakTag);
                }
            }
            else
            {
                // Return client exception message to client;by encoding it;shows using jquery message
                return exception.Message.Replace(ERPUtilityResources.SingleQuoteCharacter, ERPUtilityResources.SpaceCharacter).Replace(ERPUtilityResources.DoubleQuoteCharacter, ERPUtilityResources.SpaceCharacter).Replace(ERPUtilityResources.EnterCharacter, ERPUtilityResources.BreakTag).Replace(ERPUtilityResources.CommaCharacter, ERPUtilityResources.BreakTag);
            }
        }

For formatting lengthy string in Grid

  /// <summary>
        /// For formatting lengthy string in Grid
        /// </summary>
        /// <param name="orginalString"></param>
        /// <param name="limit"></param>
        /// <returns>string</returns>
        public static string GetShortString(object evelOrginalString, int limit)
        {
            string orginalString = HttpUtility.HtmlDecode(Convert.ToString(evelOrginalString));
            return (orginalString.Length <= limit) ? orginalString : (orginalString.Substring(0, limit) + "..");
        }

Method to check if theme exists

  /// <summary>
        /// Method to check if theme exists
        /// </summary>
        /// <param name="themeName"></param>
        /// <returns></returns>
        public static bool ThemeExists(string themeName)
        {
            bool hasTheme = false;
            try
            {
                System.IO.DirectoryInfo themeInfo = new System.IO.DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/App_Themes"));
                System.IO.DirectoryInfo[] dirInfo = themeInfo.GetDirectories();
                var theme = dirInfo.AsEnumerable().Where(dir => dir.Name == themeName);
                hasTheme = (theme != null && theme.Count() > 0);
            }
            catch
            {
            }
            return hasTheme;
        }

Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...