Wednesday, March 7, 2018

Some Useful Extension Methods

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 public static T Clone<T>(this T o)
{
return o.ToJson().FromJson<T>();
}

public static bool In<T>(this T value, params T[] options)
{
return options.Contains(value);
}

public static bool Between<T>(this T value, T start, T end)
{
if (value is string) {
var result = value.ToString().CompareTo(start);
if (result < 0) { return false; }
result = value.ToString().CompareTo(end);
if (result > 0) { return false; }
}
else
{
return value.ToDecimal() >= start.ToDecimal() && value.ToDecimal() <= end.ToDecimal();
}

return false;
}

public static void SetValue(this object obj, string name, object value)
{
var p = obj.GetType().GetProperty(name);

if (p == null)
{
var f = obj.GetType().GetField(name);
if (f != null)
{
f.SetValue(obj, value);
}
}

if (p != null)
{
p.SetValue(obj, value);
}
}

public static string Sha256ComputeHexHash(this string text)
{
var sha = new System.Security.Cryptography.SHA256Managed();
var bytes = Encoding.Default.GetBytes(text);
var hash = sha.ComputeHash(bytes);
var hex = BitConverter.ToString(hash).Replace("-", "").ToLower();
return hex;
}

No comments:

Post a Comment