Files
MileageTraker/Web/Utility/CustomExtensions.cs
T

367 lines
10 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.SqlTypes;
using System.Globalization;
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()));
}
public static string ToTitleCase(this string str)
{
// http://stackoverflow.com/q/1943273/99492
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str);
}
private static T GetAttribute<T>(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<DisplayAttribute>(enumeration);
return displayAttribute != null ? displayAttribute.Name : enumeration.ToString();
}
public static string GetDisplayShortName(this Enum enumeration)
{
var displayAttribute = GetAttribute<DisplayAttribute>(enumeration);
return displayAttribute != null
? (!String.IsNullOrEmpty(displayAttribute.ShortName)
? displayAttribute.ShortName
: displayAttribute.Name)
: enumeration.ToString();
}
public static Dictionary<string, object> 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<string, object> {{"class", inputSize}};
return dictionary;
}
public static IEnumerable<SelectListItem> GetSelectListItems(this Enum enumeration)
{
var type = enumeration.GetType();
return Enum.GetValues(type)
.OfType<Enum>().Select(e =>
new SelectListItem
{
Text = e.GetDisplayName(),
Value = e.ToString(),
Selected = e.Equals(enumeration)
});
}
public static Enum ParseWithDisplayNames(this Type enumType, string item)
{
Func<string, bool> f = s => string.Equals(s, item, StringComparison.CurrentCultureIgnoreCase);
return Enum.GetValues(enumType)
.OfType<Enum>().First(e => e.GetAllNameVariants().Any(f));
}
public static bool IsValidValue(this Type enumType, string item)
{
Func<string, bool> f = s => string.Equals(s, item, StringComparison.CurrentCultureIgnoreCase);
return Enum.GetValues(enumType)
.OfType<Enum>().Any(e => e.GetAllNameVariants().Any(f));
}
public static IEnumerable<string> GetAllNameVariants(this Enum enumeration)
{
yield return enumeration.ToString();
yield return enumeration.GetDisplayName();
yield return enumeration.GetDisplayShortName();
}
public static Expression<Func<Log, bool>> GetEqualsPredicate(this MileageLogType mileLogType)
{
Expression<Func<Log, bool>> 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<SelectListItem> ToSelectList(this Type enumType, string selectedItem, string noItemSelected)
{
var items = (from item in Enum.GetValues(enumType).OfType<Enum>()
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 string GetNullDisplayText(this PropertyInfo propertyMember, object obj)
{
var value = propertyMember.GetValue(obj, null);
var displayAttr = GetDisplayAttribute(propertyMember);
if (displayAttr != null)
{
if (value == null && !String.IsNullOrEmpty(displayAttr.NullDisplayText))
return displayAttr.NullDisplayText;
}
return null;
}
public static string GetDataFormatString(this PropertyInfo propertyMember, object obj)
{
var value = propertyMember.GetValue(obj, null);
var displayAttr = GetDisplayAttribute(propertyMember);
if (displayAttr != null)
{
if (!String.IsNullOrEmpty(displayAttr.DataFormatString))
return displayAttr.DataFormatString;
}
return null;
}
private static DisplayFormatAttribute GetDisplayAttribute(PropertyInfo propertyMember)
{
var displayAttr =
propertyMember.GetCustomAttributes(typeof (DisplayFormatAttribute), true).FirstOrDefault() as DisplayFormatAttribute;
return displayAttr;
}
public static IEnumerable<string> 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<int, string> 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<Type, bool> 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<int> GetNumbers()
{
var i = 0;
while (true) yield return i++;
}
/// <summary>
/// Users with activity date greater than this value are online
/// </summary>
public static DateTime UserOnlineThreshold()
{
return DateTime.Now.Subtract(
TimeSpan.FromMinutes(
Convert.ToDouble(
System.Web.Security.Membership.UserIsOnlineTimeWindow)));
}
public static Dictionary<string, List<string>> YearMonthList(IEnumerable<DateTime> 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<string, List<string>> GroupTuple(IEnumerable<Tuple<string,string>> 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 bool IsNonStringEnumerable(this Type type)
{
if (type == null || type == typeof(string))
return false;
return typeof(IEnumerable).IsAssignableFrom(type);
}
public static bool IsHiddenFromModel(this MemberInfo propertyMember)
{
var hiddenInputAttribute =
propertyMember.GetCustomAttributes(typeof(HiddenInputAttribute), true).FirstOrDefault() as HiddenInputAttribute;
if (hiddenInputAttribute != null)
{
return !hiddenInputAttribute.DisplayValue;
}
return false;
}
//public static IEnumerable<SelectListItem> ToSelectList<T>(
// this IEnumerable<T> enumerable,
// Func<T, string> text,
// Func<T, string> 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<SelectListItem> ToSelectList<T>(
// this IEnumerable<T> enumerable,
// string selectedValue = null,
// string defaultOption = null)
//{
// return enumerable.ToSelectList(t => t.ToString(), t => t.ToString());
//}
}
}