Friday 28 November 2014

C# Important Code Snippets and Utility Function


      public static bool isValidEmail(string email)
        {
            bool flag;
            string MatchEmailPattern = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
            flag = (email == null ? false : Regex.IsMatch(email, MatchEmailPattern));
            return flag;
        }
        public static bool isValidURL(string url)
        {
            return Regex.IsMatch(url, "(http|https)://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?");
        }

       public static string[] LASTMONTH()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int year = dateTime.Year;
            dateTime = DateTime.UtcNow.AddHours(5.5);
            int month = dateTime.Month;
            DateTime lastDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            lastDate = lastDate.AddDays(-1);
            if (month != 1)
            {
                month--;
            }
            DateTime firstDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }
 
      public static string[] LASTQTR()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int quarterNumber = (dateTime.Month - 1) / 3 + 1;
            if (quarterNumber != 1)
            {
                quarterNumber--;
            }
            dateTime = DateTime.UtcNow.AddHours(5.5);
            DateTime firstDate = new DateTime(dateTime.Year, (quarterNumber - 1) * 3 + 1, 1);
            dateTime = firstDate.AddMonths(3);
            DateTime lastDate = dateTime.AddDays(-1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }
  
      public static string[] LASTYEAR()
        {
            string[] dates = new string[2];
            int year = DateTime.UtcNow.AddHours(5.5).Year;
            year--;
            DateTime firstDate = new DateTime(Convert.ToInt32(year), 1, 1);
            DateTime lastDate = new DateTime(Convert.ToInt32(year), 12, 31);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }
  
     public static bool SendEmail(string server, string AuthUser, string password, string subject, string from, string recipients, string body, string fileNames)
        {
            int i;
            bool status = true;
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(server);
                mail.From = new MailAddress(from);
                char[] chrArray = new char[] { ',' };
                string[] strArrays = recipients.Split(chrArray);
                for (i = 0; i < (int)strArrays.Length; i++)
                {
                    string eachRecipient = strArrays[i];
                    if (!string.IsNullOrEmpty(eachRecipient))
                    {
                        mail.To.Add(eachRecipient);
                    }
                }
                mail.IsBodyHtml = true;
                mail.Subject = subject;
                body = HttpUtility.HtmlDecode(body);
                mail.Body = body;
                if (!string.IsNullOrEmpty(fileNames))
                {
                    Attachment attachment = null;
                    chrArray = new char[] { ',' };
                    strArrays = fileNames.Split(chrArray);
                    for (i = 0; i < (int)strArrays.Length; i++)
                    {
                        string eachAttachment = strArrays[i];
                        if ((string.IsNullOrEmpty(eachAttachment) ? false : File.Exists(eachAttachment)))
                        {
                            attachment = new Attachment(fileNames);
                            mail.Attachments.Add(attachment);
                        }
                    }
                }
                SmtpServer.Port = 25;
                SmtpServer.Credentials = new NetworkCredential(AuthUser, password);
                SmtpServer.EnableSsl = false;
                SmtpServer.Send(mail);
            }
            catch (Exception exception)
            {
                Exception e = exception;
                status = false;
                LogHandler.getInstance().Log(e);
            }
            return status;
        }
  
  public static string ArraytoString(object[] strArr)
        {
            string str;
            string str1;
            string returnString = string.Empty;
            if (strArr != null)
            {
                for (int i = 0; i < (int)strArr.Length; i++)
                {
                    if (strArr[i] == null)
                    {
                        str1 = null;
                    }
                    else
                    {
                        str1 = strArr[i].ToString();
                    }
                    if (!string.IsNullOrEmpty(str1))
                    {
                        returnString = string.Concat(returnString, strArr[i], (i < (int)strArr.Length - 1 ? "," : ""));
                    }
                }
                str = returnString;
            }
            else
            {
                str = null;
            }
            return str;
        }
  
  public static int getMonthsBetweenDates(DateTime startDate, DateTime endDate)
        {
            int count = 0;
            if (endDate > startDate)
            {
                int year = endDate.Year - startDate.Year;
                int month = endDate.Month - startDate.Month + 1;
                count = year * 12 + month;
            }
            return count;
        }
  
   public class PGUtil
    {
        private static WindowsImpersonationContext impersonationContext;

        public PGUtil()
        {
        }

        public static string[] AppendArrayElement(string[] array, object param)
        {
            string[] strArrays;
            if ((array == null ? false : param != null))
            {
                List list = array.ToList();
                list.Add(param.ToString());
                strArrays = list.ToArray();
            }
            else
            {
                strArrays = array;
            }
            return strArrays;
        }

        public static string ArraytoString(object[] strArr)
        {
            string str;
            string str1;
            string returnString = string.Empty;
            if (strArr != null)
            {
                for (int i = 0; i < (int)strArr.Length; i++)
                {
                    if (strArr[i] == null)
                    {
                        str1 = null;
                    }
                    else
                    {
                        str1 = strArr[i].ToString();
                    }
                    if (!string.IsNullOrEmpty(str1))
                    {
                        returnString = string.Concat(returnString, strArr[i], (i < (int)strArr.Length - 1 ? "," : ""));
                    }
                }
                str = returnString;
            }
            else
            {
                str = null;
            }
            return str;
        }

      

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
        public static extern bool CloseHandle(IntPtr handle);

        public static DataSet CreateDummyScalarDataSet(string columnValue)
        {
            return PGUtil.CreateDummyScalarDataSet(null, columnValue);
        }

        public static DataSet CreateDummyScalarDataSet(string columnName, string columnValue)
        {
            DataSet ds = null;
            try
            {
                ds = new DataSet();
                DataTable tbl = new DataTable();
                tbl.Columns.Add("Id");
                tbl.Rows.Add(new object[] { columnValue });
                ds.Tables.Add(tbl);
            }
            catch (Exception exception)
            {
                LogHandler.getInstance().Log(exception);
            }
            return ds;
        }

        public static int dateComparison(DateTime date1, DateTime date2)
        {
            return DateTime.Compare(date1, date2);
        }

        

        public static string FormatCSVstring(string inputString)
        {
            string str;
            string outPutString = string.Empty;
            try
            {
                inputString = PGUtil.escapeSpecialChar(inputString);
                string[] arrData = inputString.Split(new char[] { ',' });
                for (int i = 0; i < (int)arrData.Length; i++)
                {
                    string tempString = string.Format("'{0}'", arrData[i]);
                    outPutString = (i != 0 ? string.Concat(outPutString, ",", tempString) : tempString);
                }
                str = outPutString;
            }
            catch
            {
                str = inputString;
            }
            return str;
        }

        public static string FormatOracleDate(DateTime date)
        {
            string str;
            try
            {
                str = date.ToString("dd-MMM-yyyy");
            }
            catch
            {
                str = date.ToString();
            }
            return str;
        }

        public static string FormatSQLDate(string date)
        {
            string str;
            string str1;
            try
            {
                if (!date.Equals("NULL"))
                {
                    if (date == null)
                    {
                        str1 = null;
                    }
                    else
                    {
                        str1 = PGUtil.ToDateTime(date).ToString("yyyy-MM-dd");
                    }
                    str = str1;
                }
                else
                {
                    str = null;
                }
            }
            catch
            {
                str = date.ToString();
            }
            return str;
        }

        public static string FormatSQLDate(DateTime date)
        {
            string str;
            try
            {
                str = date.ToString("yyyy-MM-dd");
            }
            catch
            {
                str = date.ToString();
            }
            return str;
        }

        public static string FormatString(string formatString, params string[] values)
        {
            string str;
            if (!string.IsNullOrEmpty(formatString))
            {
                if (values == null)
                {
                    throw new ArgumentNullException("values");
                }
                for (int index = 0; index < (int)values.Length; index++)
                {
                    formatString = formatString.Replace(string.Concat("{", index, "}"), values[index]);
                }
                str = formatString;
            }
            else
            {
                str = formatString;
            }
            return str;
        }

        public static DateTime GetCurrentIndiaDate()
        {
            return DateTime.UtcNow.AddHours(5.5);
        }

        public static TimeSpan GetCurrentIndiaTime()
        {
            return DateTime.UtcNow.AddHours(5.5).TimeOfDay;
        }

        public static object GetDataFromSession(string key)
        {
            object returnValue = null;
            try
            {
                returnValue = HttpContext.Current.Session[key];
            }
            catch (Exception exception)
            {
                LogHandler.getInstance().Log(exception);
            }
            return returnValue;
        }

        public static T GetDataFromSession(string key)
        {
            T item;
            T returnValue = default(T);
            try
            {
                if (HttpContext.Current.Session[key] is T)
                {
                    item = (T)HttpContext.Current.Session[key];
                    return item;
                }
            }
            catch (Exception exception)
            {
                LogHandler.getInstance().Log(exception);
            }
            item = returnValue;
            return item;
        }

        public static int getMonthsBetweenDates(DateTime startDate, DateTime endDate)
        {
            int count = 0;
            if (endDate > startDate)
            {
                int year = endDate.Year - startDate.Year;
                int month = endDate.Month - startDate.Month + 1;
                count = year * 12 + month;
            }
            return count;
        }
 

        public static bool isValidEmail(string email)
        {
            bool flag;
            string MatchEmailPattern = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
            flag = (email == null ? false : Regex.IsMatch(email, MatchEmailPattern));
            return flag;
        }

        public static bool isValidURL(string url)
        {
            return Regex.IsMatch(url, "(http|https)://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?");
        }

        public static string[] LASTMONTH()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int year = dateTime.Year;
            dateTime = DateTime.UtcNow.AddHours(5.5);
            int month = dateTime.Month;
            DateTime lastDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            lastDate = lastDate.AddDays(-1);
            if (month != 1)
            {
                month--;
            }
            DateTime firstDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }

        public static string[] LASTQTR()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int quarterNumber = (dateTime.Month - 1) / 3 + 1;
            if (quarterNumber != 1)
            {
                quarterNumber--;
            }
            dateTime = DateTime.UtcNow.AddHours(5.5);
            DateTime firstDate = new DateTime(dateTime.Year, (quarterNumber - 1) * 3 + 1, 1);
            dateTime = firstDate.AddMonths(3);
            DateTime lastDate = dateTime.AddDays(-1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }

        public static string[] LASTYEAR()
        {
            string[] dates = new string[2];
            int year = DateTime.UtcNow.AddHours(5.5).Year;
            year--;
            DateTime firstDate = new DateTime(Convert.ToInt32(year), 1, 1);
            DateTime lastDate = new DateTime(Convert.ToInt32(year), 12, 31);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }

       
        public static string[] QTD()
        {
            string[] dates = new string[2];
            DateTime utcNow = DateTime.UtcNow.AddHours(5.5);
            int quarterNumber = (utcNow.Month - 1) / 3 + 1;
            utcNow = DateTime.UtcNow.AddHours(5.5);
            DateTime firstDate = new DateTime(utcNow.Year, (quarterNumber - 1) * 3 + 1, 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            utcNow = DateTime.UtcNow;
            dates[1] = PGUtil.FormatSQLDate(utcNow.AddHours(5.5));
            return dates;
        }

        public static void ReDimArray(ref string[] sourceArray, int newLength)
        {
            if (newLength >= (int)sourceArray.Length)
            {
                string[] newArray = new string[newLength];
                for (int i = 0; i < (int)sourceArray.Length; i++)
                {
                    newArray[i] = sourceArray[i];
                }
                sourceArray = newArray;
            }
        }

       

        public static bool SendEmail(string server, string AuthUser, string password, string subject, string from, string recipients, string body)
        {
            bool flag = PGUtil.SendEmail(server, AuthUser, password, subject, from, recipients, body, null);
            return flag;
        }

        public static bool SendEmail(string server, string AuthUser, string password, string subject, string from, string recipients, string body, string fileNames)
        {
            int i;
            bool status = true;
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(server);
                mail.From = new MailAddress(from);
                char[] chrArray = new char[] { ',' };
                string[] strArrays = recipients.Split(chrArray);
                for (i = 0; i < (int)strArrays.Length; i++)
                {
                    string eachRecipient = strArrays[i];
                    if (!string.IsNullOrEmpty(eachRecipient))
                    {
                        mail.To.Add(eachRecipient);
                    }
                }
                mail.IsBodyHtml = true;
                mail.Subject = subject;
                body = HttpUtility.HtmlDecode(body);
                mail.Body = body;
                if (!string.IsNullOrEmpty(fileNames))
                {
                    Attachment attachment = null;
                    chrArray = new char[] { ',' };
                    strArrays = fileNames.Split(chrArray);
                    for (i = 0; i < (int)strArrays.Length; i++)
                    {
                        string eachAttachment = strArrays[i];
                        if ((string.IsNullOrEmpty(eachAttachment) ? false : File.Exists(eachAttachment)))
                        {
                            attachment = new Attachment(fileNames);
                            mail.Attachments.Add(attachment);
                        }
                    }
                }
                SmtpServer.Port = 25;
                SmtpServer.Credentials = new NetworkCredential(AuthUser, password);
                SmtpServer.EnableSsl = false;
                SmtpServer.Send(mail);
            }
            catch (Exception exception)
            {
                Exception e = exception;
                status = false;
                LogHandler.getInstance().Log(e);
            }
            return status;
        }

        public static int timeComparison(TimeSpan time1, TimeSpan time2)
        {
            return TimeSpan.Compare(time1, time2);
        }

        public static bool ToBoolean(object str)
        {
            bool flag;
            try
            {
                flag = Convert.ToBoolean(str);
                return flag;
            }
            catch
            {
            }
            flag = false;
            return flag;
        }

        public static DateTime ToDateTime(object str)
        {
            DateTime dateTime = DateTime.MinValue;
            string strDate = str.ToString();
            try
            {
                dateTime = Convert.ToDateTime(strDate);
            }
            catch
            {
            }
            return dateTime;
        }

        public static string ToDBString(object obj)
        {
            return (obj == null || Convert.IsDBNull(obj) || string.IsNullOrEmpty(obj.ToString()) ? "NULL" : obj.ToString());
        }

        public static double ToDouble(object str)
        {
            double num;
            try
            {
                num = Convert.ToDouble(str);
                return num;
            }
            catch
            {
            }
            num = 0;
            return num;
        }

        public static int ToInt(object str)
        {
            int num;
            try
            {
                num = Convert.ToInt32(str);
                return num;
            }
            catch
            {
            }
            num = 0;
            return num;
        }

        public static long ToInt64(object str)
        {
            long num;
            try
            {
                num = Convert.ToInt64(str);
                return num;
            }
            catch
            {
            }
            num = (long)0;
            return num;
        }

        public static string ToString(object obj)
        {
            return (obj == null || Convert.IsDBNull(obj) ? "" : obj.ToString());
        }

        public static bool TryParseDate(object str)
        {
            DateTime dateTime = DateTime.MinValue;
            bool flag = true;
            str.ToString();
            try
            {
                dateTime = Convert.ToDateTime(str);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static bool tryParseInt(object num)
        {
            bool flag = true;
            try
            {
                Convert.ToInt32(num);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static bool TryParseRealNumber(object num)
        {
            bool flag = true;
            try
            {
                Convert.ToDouble(num);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static bool TryParseWholeNumber(object num)
        {
            bool flag1;
            bool flag = true;
            if (!(num as string).Contains("."))
            {
                try
                {
                    Convert.ToInt32(num);
                }
                catch
                {
                    flag = false;
                }
                flag1 = flag;
            }
            else
            {
                flag1 = false;
            }
            return flag1;
        }

        public static void UndoImpersonation()
        {
            PGUtil.impersonationContext.Undo();
        }

        public static string[] YTD()
        {
            string[] dates = new string[2];
            DateTime utcNow = DateTime.UtcNow.AddHours(5.5);
            int year = utcNow.Year;
            DateTime firstDate = new DateTime(Convert.ToInt32(year), 1, 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            utcNow = DateTime.UtcNow;
            dates[1] = PGUtil.FormatSQLDate(utcNow.AddHours(5.5));
            return dates;
        }
  

     private string GetActiveDirUserDetails(string userid)
    {
 System.DirectoryServices.DirectoryEntry dirEntry = default(System.DirectoryServices.DirectoryEntry);
 System.DirectoryServices.DirectorySearcher dirSearcher = default(System.DirectoryServices.DirectorySearcher);
 string domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
 try {
  dirEntry = new System.DirectoryServices.DirectoryEntry("LDAP://" + domainName);
  dirSearcher = new System.DirectoryServices.DirectorySearcher(dirEntry);
  dirSearcher.Filter = "(samAccountName=" + userid + ")";

  dirSearcher.PropertiesToLoad.Add("GivenName");
  //Users e-mail address
  dirSearcher.PropertiesToLoad.Add("sn");
  //Users last name
  SearchResult sr = dirSearcher.FindOne();
  //return false if user isn't found 
  if (sr == null) {
   return false;
  }
  System.DirectoryServices.DirectoryEntry de = sr.GetDirectoryEntry();
  dynamic userFirstLastName = de.Properties("sn").Value.ToString() + ", " + de.Properties("GivenName").Value.ToString();
  return userFirstLastName;
 // return false if exception occurs 
 } catch (Exception ex) {
  return ex.Message;
 }
    }
 
 }
  
  
  
  
  

HOW TO BUY ,CREATE & HOST OR DEPLOY YOUR OWN WEBSITE

Introduction A website is a collection of Web pages, images, videos or other digital assets that is hosted on...