using System; using System.Text; using System.Linq; using System.Reflection; using System.ComponentModel; using System.Dynamic; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Collections; namespace EasyDevCore.Common { /// /// Helper for convert string to/from type /// public static class ConvertHelper { /// /// Hexes to byte. /// /// The hex string. /// public static byte[] HexToByte(this string hexString) { byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); return returnBytes; } /// /// Converts to hex. /// /// The values. /// public static string ToHex(this byte[] values) { var hex = new StringBuilder(values.Length * 2); foreach (byte b in values) { hex.AppendFormat("{0:X2}", b); } return hex.ToString(); } /// /// Changes the type. /// /// The value. /// Type of the conversion. /// public static object ChangeType(this object value, Type conversionType) { if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { if (value == null || value == DBNull.Value) { return null; } else { NullableConverter nullableConverter = new NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; } } if (typeof(Enum).IsAssignableFrom(conversionType)) { return Enum.GetName(value.GetType(), value); } return Convert.ChangeType(value, conversionType); } /// /// To the dynamic. /// /// The value. /// public static dynamic ToDynamic(this object value) { return TypeDescriptor.GetProperties(value.GetType()).OfType().Aggregate(new ExpandoObject() as IDictionary, (a, p) => { a.Add(p.Name, p.GetValue(value)); return a; }); } /// /// Extension method that turns a dictionary of string and object to an ExpandoObject /// public static ExpandoObject ToExpando(this IDictionary dictionary) { var expando = new ExpandoObject(); var expandoDic = expando as IDictionary; // go through the items in the dictionary and copy over the key value pairs) foreach (var kvp in dictionary) { // if the value can also be turned into an ExpandoObject, then do it! if (kvp.Value is IDictionary) { var expandoValue = ((IDictionary)kvp.Value).ToExpando(); expandoDic.Add(kvp.Key, expandoValue); } else if (kvp.Value is ICollection) { // iterate through the collection and convert any strin-object dictionaries // along the way into expando objects var itemList = new List(); foreach (var item in (ICollection)kvp.Value) { if (item is IDictionary) { var expandoItem = ((IDictionary)item).ToExpando(); itemList.Add(expandoItem); } else { itemList.Add(item); } } expandoDic.Add(kvp.Key, itemList); } else { expandoDic.Add(kvp); } } return expando; } /// /// Changes the type. /// /// The value. /// Type of the conversion. /// The default value. /// public static object ChangeType(this object value, Type conversionType, object defaultValue) { try { return ChangeType(value, conversionType); } catch { return defaultValue; } } /// /// Converts the to T type (if not success return default(T)). /// /// /// The value. /// public static T ConvertToWithDefault(this object value) { return ConvertTo(value, default(T)); } /// /// Converts the specified value. /// /// Type of the result value /// The value. /// public static T ConvertTo(this object value) { if((value != null) && (value.GetType() == typeof(string))) { return StringTo((string)value); } return (T)ChangeType(value, typeof(T)); } /// /// Converts the specified value. /// /// Type of the result value /// The value. /// The default value if convert failed. /// public static T ConvertTo(this object value, T defaultValue) { try { return ConvertTo(value); } catch { return defaultValue; } } /// /// Converts byte array to binary string /// /// The array. /// public static string ToString(this byte[] array) { char[] chars = new char[array.Length / sizeof(char)]; System.Buffer.BlockCopy(array, 0, chars, 0, array.Length); return new string(chars); } /// /// Converts char array to binary string /// /// The array. /// public static string ToString(this char[] array) { return new string(array); } /// /// Converts binary string to byte array. /// /// The value. /// public static byte[] ToByteArray(this string value) { byte[] bytes = new byte[value.Length * sizeof(char)]; System.Buffer.BlockCopy(value.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } /// /// Strings to base24. /// /// The value. /// public static string ToBase24(this string value) { const string sel = "BCDFGHJKMPQRTVWXY2346789"; int i = 0; int Pos = 0; char[] Buf = new char[value.Length << 1]; while ((i = Pos) < value.Length) { Buf[i << 1] = sel[(value[Pos]) >> 4]; Buf[(i << 1) + 1] = sel[23 - (value[Pos] & 0x0F)]; Pos++; } return new string(Buf); } /// /// Strings from base24. /// /// The value. /// public static string FromBase24(this string value) { const string sel = "BCDFGHJKMPQRTVWXY2346789"; if (value.Length % 2 != 0) return null; int[] NPos = new int[2]; char[] N = new char[2]; char[] Buf = new char[value.Length >> 1]; for (int i = 0; i < (value.Length >> 1); i++) { NPos[0] = sel.IndexOf(value[i << 1]); NPos[1] = 23 - sel.IndexOf(value[(i << 1) + 1]); if (NPos[0] < 0 || NPos[1] < 0) { return null; } Buf[i] = ((char)((NPos[0] << 4) | NPos[1])); } return new string(Buf); } /// /// Converts to base64 (UTF8). /// /// The value. /// public static string ToBase64(this string value) { return ToBase64(value, Encoding.UTF8); } /// /// String to base64 string. /// /// The value. /// The encoding. /// public static string ToBase64(this string value, Encoding encoding) { return Convert.ToBase64String(encoding.GetBytes(value)); } /// /// String from base64 string. /// /// The value. /// public static string FromBase64(this string value) { return Encoding.UTF8.GetString(Convert.FromBase64String(value)); } /// /// Convert strings to type T (if not success return default(T)). /// /// /// The value. /// public static T StringToWithDefault(this string value) { return (T)StringTo(value, typeof(T), default(T)); } /// /// Convert strings to type T /// /// The value. /// The type. /// The default value. /// public static object StringTo(string value, Type type, object defaultValue) { if (value != null) { try { return StringTo(value, type); } catch { } } return defaultValue; } /// /// Convert strings to type T /// /// The value. /// The type. /// public static object StringTo(this string value, Type type) { if (type == typeof(Guid)) { if (string.IsNullOrWhiteSpace(value)) return Guid.Empty; System.ComponentModel.GuidConverter guidConverter = new System.ComponentModel.GuidConverter(); return guidConverter.ConvertFromString(value); } else if (type == typeof(byte[])) { return Convert.FromBase64String(value); } else if (type == typeof(char[])) { return Encoding.GetEncoding(850).GetChars((Convert.FromBase64String(value))); } else if (typeof(Enum).IsAssignableFrom(type)) { return Enum.Parse(type, value); } else { return Convert.ChangeType(value, type); } } /// /// Convert strings to type T /// /// The type string convert to. /// The value. /// The default value. /// public static T StringTo(this string value, T defaultValue) { return (T)StringTo(value, typeof(T), defaultValue); } /// /// Convert strings to type T /// /// /// The value. /// public static T StringTo(this string value) { return (T)StringTo(value, typeof(T), default(T)); } /// /// Convert the type to string. /// /// The value. /// The default value. /// public static string StringFrom(this object value, string defaultValue) { try { return StringFrom(value); } catch { } return defaultValue; } /// /// Convert the type to string. /// /// The value. /// public static string StringFrom(this object value) { if ((value == null) || (value == DBNull.Value)) return null; if (value.GetType() == typeof(Guid)) { System.ComponentModel.GuidConverter guidConverter = new System.ComponentModel.GuidConverter(); return guidConverter.ConvertToString(value); } if (value.GetType() == typeof(DateTime)) { return ((DateTime)value).ToString("o"); } if (value.GetType() == typeof(byte[])) { return Convert.ToBase64String((byte[])value); } if (value.GetType() == typeof(char[])) { return Convert.ToBase64String(Encoding.GetEncoding(850).GetBytes((char[])value)); } if (typeof(Enum).IsAssignableFrom(value.GetType())) { return Enum.GetName(value.GetType(), value); } return (string)Convert.ChangeType(value, typeof(string)); } } }