using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Data; using System.Xml.Serialization; using System.IO; using System.Collections.Specialized; using System.Web; using System.ComponentModel; using System.Xml; using System.Xml.Linq; using System.Web.UI; using System.Text.RegularExpressions; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Linq.Expressions; using System.Net; using OfficeOpenXml; using System.Collections.Concurrent; namespace Utilities { public static class Extensions { private static ConcurrentDictionary> typeDictionary = new ConcurrentDictionary>(); public static IList GetPropertiesForType() { //variables var type = typeof(T); //add to dictionary typeDictionary.TryAdd(type, type.GetProperties().ToList()); //return return typeDictionary[type]; } public static T ToObject(this DataRow row) where T : new() { //variables IList properties = GetPropertiesForType(); //return return CreateItemFromRow(row, properties); } public static IList ToList(this DataTable table) where T : new() { //variables IList result = new List(); //foreach foreach (DataRow row in table.Rows) { result.Add(row.ToObject()); } //return return result; } private static T CreateItemFromRow(DataRow row, IList properties) where T : new() { //variables T item = new T(); //foreach foreach (var property in properties) { //make sure a column exists in the table with this property name if (row.Table.Columns.Contains(property.Name)) { //get the value from the current data row object value = row[property.Name]; //set property accordingly if (value != null & value != DBNull.Value) { SetProperty(item, property.Name, value); } } } //return return item; } public static string GetProperty(this T obj, string Property) { //reflection PropertyInfo propertyInfo = obj.GetType().GetProperty(Property, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); object property = null; //make sure property is valid if (propertyInfo != null) { property = propertyInfo.GetValue(obj, null); } //return value if (property != null) { return property.ToString(); } else { return string.Empty; } } public static T SetProperty(this T obj, string Property, object Value) { //reflection PropertyInfo prop = obj.GetType().GetProperty(Property, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); //trim strings if (Value.GetType() == typeof(string)) { Value = Value.ToString().Trim(); } //make sure property is valid if (prop != null && prop.CanWrite) { prop.SetValue(obj, Value, null); } //return return obj; } public static string Serialize(this T obj) { // Json.NET (Newtonsoft.Json) // https://www.nuget.org/packages/Newtonsoft.Json return Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented); } public static T Deserialize(string data) where T : new() { // Json.NET (Newtonsoft.Json) // https://www.nuget.org/packages/Newtonsoft.Json return Newtonsoft.Json.JsonConvert.DeserializeObject(data); } public static DataTable ToDataTable(this IList data) { // variables PropertyDescriptorCollection Properties = TypeDescriptor.GetProperties(typeof(T)); object[] values = new object[Properties.Count]; DataTable DT = new DataTable(); // columns foreach (PropertyDescriptor PropertyInfo in Properties) { // data column DataColumn DataColumn = new DataColumn(); // name DataColumn.ColumnName = PropertyInfo.Name; // data type if (PropertyInfo.PropertyType.Name.Contains("Nullable")) { DataColumn.DataType = typeof(String); } else { DataColumn.DataType = PropertyInfo.PropertyType; } // add to table DT.Columns.Add(DataColumn); } //for (int i = 0; i < Properties.Count; i++) //{ // PropertyDescriptor prop = Properties[i]; // DT.Columns.Add(prop.Name, prop.PropertyType); //} // rows foreach (T item in data) { for (int i = 0; i < values.Length; i++) { values[i] = Properties[i].GetValue(item); } DT.Rows.Add(values); } // return return DT; } public static string ToXml(this DataTable DT) { //variables DataSet DS = new DataSet("data"); string Xml = string.Empty; //datatable name DT.TableName = "r"; //load dataset DS.Tables.Add(DT); //mapping type foreach (DataTable t in DS.Tables) { foreach (DataColumn c in t.Columns) { c.ColumnMapping = MappingType.Attribute; } } //get xml data using (StringWriter sw = new StringWriter()) { DS.WriteXml(sw, XmlWriteMode.IgnoreSchema); Xml = sw.ToString(); } //return return Xml; } public static string ToCsv(this DataTable DT, string Delimiter = ",", bool Escape = true) { //variables StringBuilder sb = new StringBuilder(); IEnumerable columns = default(IEnumerable); //list fields columns = DT.Columns.Cast().Select(x => x.ColumnName); //delimiter override if (Delimiter.IsEqual("tab")) { Delimiter = "\t"; } //header sb.AppendLine(string.Join(Delimiter, columns)); //data foreach (DataRow r in DT.Rows) { //variables StringBuilder sbrow = new StringBuilder(); //columns foreach (DataColumn c in DT.Columns) { //variables object ValueIn = r[c.ColumnName]; string ValueOut = string.Empty; Type Type = ValueIn.GetType(); //format if (ValueIn == null || ValueIn.Equals(DBNull.Value)) { ValueOut = string.Empty; } else if (object.ReferenceEquals(ValueIn, typeof(DateTime))) { ValueOut = ValueIn.ToString(); } else if (Type.IsPrimitive && !object.ReferenceEquals(Type, typeof(string))) { ValueOut = ValueIn.ToString(); } else if (Escape) { ValueOut = string.Concat("\"", ValueIn.ToString().Replace("\"", "\"\""), "\""); } else { ValueOut = ValueIn.ToString().Replace(Delimiter, string.Empty); } //append value sbrow.Append(ValueOut); //append delimiter sbrow.Append(Delimiter); } //append line if (sbrow.ToString().EndsWith(Delimiter)) { sb.AppendLine(sbrow.ToString().TrimEnd(Delimiter.ToCharArray())); } else { sb.AppendLine(sbrow.ToString()); } } //return return sb.ToString(); } public static string Description(this Enum value) { // variables var enumType = value.GetType(); var field = enumType.GetField(value.ToString()); var attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); // return return attributes.Length == 0 ? value.ToString() : ((DescriptionAttribute)attributes[0]).Description; } public static void SetValue(this DropDownList control, string value) { // variables var ListItem = control.Items.Cast().Where(x => x.Value.IsEqual(value)).FirstOrDefault(); // clear selection control.ClearSelection(); // check for match if (ListItem != null) { ListItem.Selected = true; } } public static void AddEmpty(this DropDownList control, string text = "", string value = "") { // check for existing blank var ListItem = control.Items.Cast().Where(x => x.Value.IsBlank()).FirstOrDefault(); // add new blank item if (ListItem == null) { control.Items.Insert(0, new ListItem(text: text, value: value)); } } public static void SelectDefault(this DropDownList control) { // check if only one non-blank item exists if (control.Items.Cast().Where(x => x.Value.HasValue()).Count() == 1) { // select it control.Items.Cast().Where(x => x.Value.HasValue()).FirstOrDefault().Selected = true; } } public static void SetValue(this HtmlSelect control, string value) { // variables var ListItem = control.Items.Cast().Where(x => x.Value.IsEqual(value)).FirstOrDefault(); // check for match if (ListItem != null) { ListItem.Selected = true; } } public static void ClearSelection(this HtmlSelect control) { foreach (ListItem ListItem in control.Items) { ListItem.Selected = false; } } public static bool HasValue(this string Value) { return !Value.IsBlank(); } public static bool IsBlank(this string Value) { bool ReturnValue = true; if (Value != null) { ReturnValue = Value.Trim().Length == 0; } return ReturnValue; } public static bool IsEqual(this string Value, string CompareValue) { bool ReturnValue = false; if (Value != null && CompareValue != null) { ReturnValue = string.Compare(Value.Trim(), CompareValue.Trim(), StringComparison.OrdinalIgnoreCase) == 0; } return ReturnValue; } public static bool IsEqual(this string Value, params string[] CompareValues) { if (Value != null && CompareValues != null) { foreach (string CompareValue in CompareValues) { if (Value.IsEqual(CompareValue)) { return true; } } } return false; } public static bool ContainsValue(this string Value, string CompareValue) { bool ReturnValue = false; if (Value != null && CompareValue != null) { ReturnValue = Value.Trim().IndexOf(CompareValue.Trim(), StringComparison.OrdinalIgnoreCase) >= 0; } return ReturnValue; } public static bool ContainsValue(this string Value, params string[] CompareValues) { if (Value != null && CompareValues != null) { foreach (string CompareValue in CompareValues) { if (Value.ContainsValue(CompareValue)) { return true; } } } return false; } public static bool StartsWithValue(this string Value, string CompareValue) { bool ReturnValue = false; if (Value != null && CompareValue != null) { ReturnValue = Value.Trim().StartsWith(CompareValue.Trim(), StringComparison.OrdinalIgnoreCase); } return ReturnValue; } public static bool StartsWithValue(this string Value, params string[] CompareValues) { if (Value != null && CompareValues != null) { foreach (string CompareValue in CompareValues) { if (Value.StartsWithValue(CompareValue)) { return true; } } } return false; } public static bool EndsWithValue(this string Value, string CompareValue) { bool ReturnValue = false; if (Value != null && CompareValue != null) { ReturnValue = Value.Trim().EndsWith(CompareValue.Trim(), StringComparison.OrdinalIgnoreCase); } return ReturnValue; } public static bool EndsWithValue(this string Value, params string[] CompareValues) { if (Value != null && CompareValues != null) { foreach (string CompareValue in CompareValues) { if (Value.EndsWithValue(CompareValue)) { return true; } } } return false; } public static string ReplaceValue(this string Value, string Pattern, string Replacement) { return Regex.Replace(Value, Regex.Escape(Pattern), Replacement, RegexOptions.IgnoreCase); } public static bool IsValidDate(this string Value) { if (Regex.Match(Value, "\\d{6}|\\d{8}").Success) { Value = Regex.Replace(Value, "\\b(?\\d{2})(?\\d{2})(?\\d{2,4})\\b", "${month}-${day}-${year}"); } try { Convert.ToDateTime(Value); return true; } catch { return false; } } public static DateTime ConvertToDateTime(this string Value) { if (Value.IsValidDate()) { Value = Regex.Replace(Value, "\\b(?\\d{2})(?\\d{2})(?\\d{2,4})\\b", "${month}-${day}-${year}"); } try { return Convert.ToDateTime(Value); } catch { return DateTime.MinValue; } } public static bool IsValidNumber(this string Value) { // variables int Result = 0; // parse return Int32.TryParse(Value, out Result); } public static bool IsValidPhoneNumber(this string Value) { // allows phone number of the format: NPA = [2-9][0-8][0-9] Nxx = [2-9][0-9][0-9] Station = [0-9][0-9][0-9][0-9] return Regex.Match(Value, "^[01]?[- .]?(\\([2-9]\\d{2}\\)|[2-9]\\d{2})[- .]?\\d{3}[- .]?\\d{4}$").Success; } public static bool IsValidZip(this string Value) { return Regex.Match(Value, "^\\d{5}$").Success || Regex.Match(Value.ToUpper().Replace(" ", ""), "^[ABCEGHJKLMNPRSTVXY]\\d[A-Z]\\d[A-Z]\\d$").Success; } public static bool IsValidEmail(this string Value) { return Regex.Match(Value, "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$", RegexOptions.IgnoreCase).Success; } public static bool IsValidWebsite(this string Value) { return Regex.Match(Value, "^(http|https)://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?", RegexOptions.IgnoreCase).Success; } public static bool IsValidMMDDYYYY(this string Value) { return Regex.Match(Value, "(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d").Success; } public static bool IsValidMMYYYY(this string Value) { return Regex.Match(Value, "(0[1-9]|1[012])[- /.](19|20)\\d\\d").Success; } public static bool IsValidIPAddress(this string Value) { return Regex.Match(Value, "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b").Success; } public static Control FindControlRecursive(this Control root, string id) { if (root.ID == id) { return root; } foreach (Control c in root.Controls) { Control t = FindControlRecursive(c, id); if (t != null) { return t; } } return null; } public static IEnumerable GetAllControls(this Control Parent, System.Type Type = null) { if (Parent == null) { yield break; } if (Type == null || Parent.GetType().Equals(Type)) { yield return Parent; } foreach (Control Control in Parent.Controls) { foreach (Control x in Control.GetAllControls(Type)) { yield return x; } } } public static CookieContainer GetCookieContainer(this System.Web.HttpRequest SourceHttpRequest) { // variables System.Web.HttpCookieCollection SourceCookies = SourceHttpRequest.Cookies; CookieContainer CookieContainer = new CookieContainer(); if (SourceCookies.Count == 0) { return null; } // copy cookies to container for (int i = 0; i < SourceCookies.Count; i++) { // variables System.Web.HttpCookie cSource = SourceCookies[i]; if (cSource.Name.IsEqual("CookieName")) { Cookie cookieTarget = new Cookie() { Domain = SourceHttpRequest.Url.Host, Name = cSource.Name, Path = cSource.Path, Secure = cSource.Secure, Value = cSource.Value }; // add to container CookieContainer.Add(cookieTarget); } } // return return CookieContainer; } public static bool IsVowel(this char character) { return new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(char.ToLower(character)); } public static string ToDateShort(this string value) { // variables DateTime TempDate = DateTime.MinValue; // parse if (DateTime.TryParse(value, out TempDate)) { return TempDate.ToString("M/d/yyyy"); } else { return string.Empty; } } // e.g. https public static string Protocol(this HttpRequest Request) { return Request.Url.Scheme; } // e.g. pavey.azurewebsites.net public static string Host(this HttpRequest Request) { return Request.Url.Host.ToLower(); } // e.g. https://pavey.azurewebsites.net/debug/?x=1&y=2 public static string UrlHttps(this HttpRequest Request) { return string.Format("https://{0}{1}", Request.Host(), Request.RawUrl); } // e.g. http://pavey.azurewebsites.net/debug/?x=1&y=2 public static string UrlHttp(this HttpRequest Request) { return string.Format("http://{0}{1}", Request.Host(), Request.RawUrl); } // e.g. true if testing using an IP address instead of a fully qualified host name public static bool IsIPAddress(this HttpRequest Request) { return Request.Host().IsValidIPAddress(); } // e.g. true if testing using localhost public static bool IsLocalHost(this HttpRequest Request) { return Request.Host().ToLower().Equals("localhost"); } // e.g. dev.www public static List SubDomains(this HttpRequest Request) { // variables string[] MyArray = Request.Host().Split(".".ToCharArray()); List MySubDomains = new List(); // make sure this is not an ip address if (Request.IsIPAddress()) { return MySubDomains; } // make sure we have all the parts necessary if (MyArray == null) { return MySubDomains; } // last part is the tld (e.g. .com) // second to last part is the domain (e.g. mydomain) // the remaining parts are the sub-domain(s) if (MyArray.Length > 2) { for (int i = 0; i <= MyArray.Length - 3; i++) { MySubDomains.Add(MyArray[i]); } } // return return MySubDomains; } // e.g. www public static string SubDomain(this HttpRequest Request) { if (Request.SubDomains().Count > 0) { // handle cases where multiple sub-domains (e.g. dev.www) return Request.SubDomains().Last(); } else { // handle cases where no sub-domains return string.Empty; } } // e.g. azurewebsites.net public static string Domain(this HttpRequest Request) { // variables string[] MyArray = Request.Host().Split(".".ToCharArray()); // make sure this is not an ip address if (Request.IsIPAddress()) { return string.Empty; } // special case for localhost if (Request.IsLocalHost()) { return Request.Host().ToLower(); } // make sure we have all the parts necessary if (MyArray == null) { return string.Empty; } // make sure we have all the parts necessary if (MyArray.Length > 1) { return string.Format("{0}.{1}", MyArray[MyArray.Length - 2], MyArray[MyArray.Length - 1]); } // return empty string return string.Empty; } // e.g. https://pavey.azurewebsites.net/ public static string BaseUrl(this HttpRequest Request) { // variables string Authority = Request.Url.GetLeftPart(UriPartial.Authority).TrimStart('/').TrimEnd('/'); string ApplicationPath = Request.ApplicationPath.TrimStart('/').TrimEnd('/'); // add trailing slashes if necessary if (Authority.Length > 0) { Authority += "/"; } if (ApplicationPath.Length > 0) { ApplicationPath += "/"; } // return return string.Format("{0}{1}", Authority, ApplicationPath); } // e.g. default, default.aspx public static string PageName(this HttpRequest Request, bool IncludeExtension = false, bool IncludeQueryString = false) { // variables string AbsolutePath = Request.Url.AbsolutePath; string PageName = Path.GetFileName(AbsolutePath); string Extension = Path.GetExtension(AbsolutePath); string QueryString = Request.QueryString.ToString(); // remove extension if (!IncludeExtension && !IncludeQueryString && PageName.HasValue()) { PageName = PageName.Replace(Extension, string.Empty); } // include querystring if (IncludeQueryString && PageName.HasValue() && QueryString.HasValue()) { PageName = string.Format("{0}?{1}", PageName, QueryString); } // return return PageName; } public static byte[] ToExcel(this DataTable DT, string WorksheetName = "Data", bool AutoFormatDates = false) { // EPPlus // https://www.nuget.org/packages/EPPlus/ // variables byte[] Data = null; ExcelPackage ExcelPackage = new ExcelPackage(); ExcelWorksheet ExcelWorksheet = ExcelPackage.Workbook.Worksheets.Add(WorksheetName.HasValue() ? WorksheetName : "Data"); // load data table with column headings ExcelWorksheet.Cells["A1"].LoadFromDataTable(DT, true); // auto-format dates if (AutoFormatDates) { var DateColumns = from DataColumn d in DT.Columns where d.DataType == typeof(DateTime) || d.ColumnName.Contains("Date") select d.Ordinal + 1; foreach (var Column in DateColumns) { ExcelWorksheet.Cells[2, Column, DT.Rows.Count + 1, Column].Style.Numberformat.Format = "mm/dd/yyyy"; } } // get data as byte array Data = ExcelPackage.GetAsByteArray(); // cleanup ExcelPackage.Dispose(); // return byte array return Data; } public static DataTable ToDataTable(this Stream Data, bool HasHeader = true) { // EPPlus // https://www.nuget.org/packages/EPPlus/ // variables DataTable DT = new DataTable(); var RowStart = HasHeader ? 2 : 1; using (ExcelPackage ExcelPackage = new ExcelPackage()) { // load data from stream ExcelPackage.Load(Data); // worksheet ExcelWorksheet ExcelWorksheet = ExcelPackage.Workbook.Worksheets.First(); // create column headings foreach (var Cell in ExcelWorksheet.Cells[1, 1, 1, ExcelWorksheet.Dimension.End.Column]) { DT.Columns.Add(HasHeader ? Cell.Text : string.Format("Column {0}", Cell.Start.Column)); } // copy data from each row to the data table for (int RowNumber = RowStart; RowNumber <= ExcelWorksheet.Dimension.End.Row; RowNumber++) { // variables ExcelRange Row = ExcelWorksheet.Cells[RowNumber, 1, RowNumber, ExcelWorksheet.Dimension.End.Column]; DataRow DataRow = DT.NewRow(); // copy the data from each cell to the data row foreach (ExcelRangeBase cell in Row) { DataRow[cell.Start.Column - 1] = cell.Text; } // add row to data table DT.Rows.Add(DataRow); } } // return data table return DT; } } }