using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data.SqlTypes; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Web.Mvc; using MileageTraker.Web.Models; namespace MileageTraker.Web.Utility { public static class CustomExtensions { public static string Wordify(this string str) { return str.Aggregate( String.Empty, (current, c) => current + (Char.IsUpper(c) ? " " + c : c.ToString())); } private static T GetAttribute(this Enum enumeration) where T : Attribute { var type = enumeration.GetType(); var memInfo = type.GetMember(enumeration.ToString()); if (memInfo.Length > 0) { var attributes = memInfo[0].GetCustomAttributes(typeof (T), false); if (attributes.Length > 0) return (T) attributes[0]; } return null; } public static string GetDisplayName(this Enum enumeration) { var displayAttribute = GetAttribute(enumeration); return displayAttribute != null ? displayAttribute.Name : enumeration.ToString(); } public static string GetDisplayShortName(this Enum enumeration) { var displayAttribute = GetAttribute(enumeration); return displayAttribute != null ? (!String.IsNullOrEmpty(displayAttribute.ShortName) ? displayAttribute.ShortName : displayAttribute.Name) : enumeration.ToString(); } public static Dictionary GetInputSizeClass(this HtmlHelper helper) { var inputSize = (string)helper.ViewData.ModelMetadata.AdditionalValues["InputSize"]; //var cls = !string.IsNullOrEmpty(inputSize) ? new { @class = inputSize } : null; var dictionary = new Dictionary {{"class", inputSize}}; return dictionary; } public static IEnumerable GetSelectListItems(this Enum enumeration) { var type = enumeration.GetType(); return Enum.GetValues(type) .OfType().Select(e => new SelectListItem { Text = e.GetDisplayName(), Value = e.ToString(), Selected = e.Equals(enumeration) }); } public static Enum ParseWithDisplayNames(this Type enumType, string item) { Func f = s => string.Equals(s, item, StringComparison.CurrentCultureIgnoreCase); return Enum.GetValues(enumType) .OfType().First(e => e.GetAllNameVariants().Any(f)); } public static bool IsValidValue(this Type enumType, string item) { Func f = s => string.Equals(s, item, StringComparison.CurrentCultureIgnoreCase); return Enum.GetValues(enumType) .OfType().Any(e => e.GetAllNameVariants().Any(f)); } public static IEnumerable GetAllNameVariants(this Enum enumeration) { yield return enumeration.ToString(); yield return enumeration.GetDisplayName(); yield return enumeration.GetDisplayShortName(); } public static Expression> GetEqualsPredicate(this MileageLogType mileLogType) { Expression> predicate; switch (mileLogType) { case MileageLogType.NonCommuting: predicate = l => l.LogType.Value == 1; break; case MileageLogType.Commuting: predicate = l => l.LogType.Value == 2; break; case MileageLogType.GasPurchase: predicate = l => l.LogType.Value == 3; break; default: throw new ArgumentOutOfRangeException(); } return predicate; } public static IEnumerable ToSelectList(this Type enumType, string selectedItem, string noItemSelected) { var items = (from item in Enum.GetValues(enumType).OfType() let title = item.GetDisplayName() select new SelectListItem { Value = item.ToString(), Text = title, Selected = selectedItem == item.ToString() }).ToList(); return new SelectList(new[] {new SelectListItem {Text = noItemSelected}}.Concat(items), "Value", "Text"); } public static string GetName(this MemberInfo propertyMember) { var displayAttr = propertyMember.GetCustomAttributes(typeof (DisplayAttribute), true).FirstOrDefault() as DisplayAttribute; return displayAttr != null ? displayAttr.Name : propertyMember.Name; } public static object GetValue(this PropertyInfo propertyMember, object obj) { var value = propertyMember.GetValue(obj, null); var displayAttr = propertyMember.GetCustomAttributes(typeof (DisplayFormatAttribute), true).FirstOrDefault() as DisplayFormatAttribute; if (displayAttr != null) { if (value == null && !String.IsNullOrEmpty(displayAttr.NullDisplayText)) return displayAttr.NullDisplayText; if (!String.IsNullOrEmpty(displayAttr.DataFormatString)) return String.Format(displayAttr.DataFormatString, value); } return value; } public static IEnumerable GetPropertyNames(this Type type) { return from property in type.GetProperties() select property.GetName(); } public static bool IsSqlMinValue(this DateTime dt) { return dt == SqlDateTime.MinValue.Value; } public static string ToVerboseStringHistoric(this TimeSpan ts) { if (ts.TotalDays < 1) return "Today"; if (ts.TotalDays < 2) return "Yesterday"; var sb = new StringBuilder(); Action b = (var, name) => { if (var > 0) { if (sb.Length > 0) sb.Append(", "); sb.Append(var + " " + name); if (var > 1) sb.Append("s"); } }; var timeLeft = ts; var years = timeLeft.Days/365; //no leap year accounting b(years, "year"); timeLeft -= new TimeSpan(years*365, 0, 0, 0); var months = timeLeft.Days/30; //naive guess at month size b(months, "month"); timeLeft -= new TimeSpan(months*30, 0, 0, 0); var weeks = timeLeft.Days/7; b(weeks, "week"); timeLeft -= new TimeSpan(weeks*7, 0, 0, 0); var days = timeLeft.Days; b(days, "day"); sb.Append(" ago"); return sb.ToString(); } public static bool IsCollection(this Type type) { Func isCollection = t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof (ICollection<>); return isCollection(type) || type.GetInterfaces().Any(isCollection); } public static string LowercaseFirst(string s) { // Check for empty string. if (String.IsNullOrEmpty(s)) { return String.Empty; } // Return char and concat substring. return Char.ToLower(s[0]) + s.Substring(1); } public static IEnumerable GetNumbers() { var i = 0; while (true) yield return i++; } /// /// Users with activity date greater than this value are online /// public static DateTime UserOnlineThreshold() { return DateTime.Now.Subtract( TimeSpan.FromMinutes( Convert.ToDouble( System.Web.Security.Membership.UserIsOnlineTimeWindow))); } public static Dictionary> YearMonthList(IEnumerable dates) { var tuples = from d in dates orderby d descending select Tuple.Create(d.Year.ToString(), d.Month.ToString()); return GroupTuple(tuples); //return // (from d in dates // orderby d.Year descending // group d by d.Year // into yg // select // new // { // Year = yg.Key.ToString(), // MonthList = // (from o in yg // orderby o.Month descending // group o by o.Month // into mg // select mg.Key.ToString()).ToList() // }).ToDictionary(arg => arg.Year, arg => arg.MonthList); } public static Dictionary> GroupTuple(IEnumerable> tuples) { return (from t in tuples group t by t.Item1 into yg select new { Item1 = yg.Key, Item2List = (from o in yg group o by o.Item2 into mg select mg.Key).ToList() }).ToDictionary(arg => arg.Item1, arg => arg.Item2List); } //public static IEnumerable ToSelectList( // this IEnumerable enumerable, // Func text, // Func value, // string selectedValue = null, // string defaultOption = null) //{ // var items = enumerable.Select(f => new SelectListItem // { // Text = text(f), // Value = value(f), // Selected = value(f) == selectedValue, // }).ToList(); // if (!string.IsNullOrEmpty(defaultOption)) // { // items.Insert(0, new SelectListItem // { // Text = defaultOption, // Value = "-1" // }); // } // return items; //} //public static IEnumerable ToSelectList( // this IEnumerable enumerable, // string selectedValue = null, // string defaultOption = null) //{ // return enumerable.ToSelectList(t => t.ToString(), t => t.ToString()); //} } }