ConvertHelper.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. using System;
  2. using System.Text;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.ComponentModel;
  6. using System.Dynamic;
  7. using System.Collections.Generic;
  8. using System.Diagnostics.CodeAnalysis;
  9. using System.Collections;
  10. namespace EasyDevCore.Common
  11. {
  12. /// <summary>
  13. /// Helper for convert string to/from type
  14. /// </summary>
  15. public static class ConvertHelper
  16. {
  17. /// <summary>
  18. /// Hexes to byte.
  19. /// </summary>
  20. /// <param name="hexString">The hex string.</param>
  21. /// <returns></returns>
  22. public static byte[] HexToByte(this string hexString)
  23. {
  24. byte[] returnBytes = new byte[hexString.Length / 2];
  25. for (int i = 0; i < returnBytes.Length; i++)
  26. returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
  27. return returnBytes;
  28. }
  29. /// <summary>
  30. /// Changes the type.
  31. /// </summary>
  32. /// <param name="value">The value.</param>
  33. /// <param name="conversionType">Type of the conversion.</param>
  34. /// <returns></returns>
  35. public static object ChangeType(this object value, Type conversionType)
  36. {
  37. if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
  38. {
  39. if (value == null || value == DBNull.Value)
  40. {
  41. return null;
  42. }
  43. else
  44. {
  45. NullableConverter nullableConverter = new NullableConverter(conversionType);
  46. conversionType = nullableConverter.UnderlyingType;
  47. }
  48. }
  49. if (typeof(Enum).IsAssignableFrom(conversionType))
  50. {
  51. return Enum.GetName(value.GetType(), value);
  52. }
  53. return Convert.ChangeType(value, conversionType);
  54. }
  55. /// <summary>
  56. /// To the dynamic.
  57. /// </summary>
  58. /// <param name="value">The value.</param>
  59. /// <returns></returns>
  60. public static dynamic ToDynamic(this object value)
  61. {
  62. return TypeDescriptor.GetProperties(value.GetType()).OfType<PropertyDescriptor>().Aggregate(new ExpandoObject() as IDictionary<string, object>,
  63. (a, p) => { a.Add(p.Name, p.GetValue(value)); return a; });
  64. }
  65. /// <summary>
  66. /// Extension method that turns a dictionary of string and object to an ExpandoObject
  67. /// </summary>
  68. public static ExpandoObject ToExpando(this IDictionary<string, object> dictionary)
  69. {
  70. var expando = new ExpandoObject();
  71. var expandoDic = expando as IDictionary<string, object>;
  72. // go through the items in the dictionary and copy over the key value pairs)
  73. foreach (var kvp in dictionary)
  74. {
  75. // if the value can also be turned into an ExpandoObject, then do it!
  76. if (kvp.Value is IDictionary<string, object>)
  77. {
  78. var expandoValue = ((IDictionary<string, object>)kvp.Value).ToExpando();
  79. expandoDic.Add(kvp.Key, expandoValue);
  80. }
  81. else if (kvp.Value is ICollection)
  82. {
  83. // iterate through the collection and convert any strin-object dictionaries
  84. // along the way into expando objects
  85. var itemList = new List<object>();
  86. foreach (var item in (ICollection)kvp.Value)
  87. {
  88. if (item is IDictionary<string, object>)
  89. {
  90. var expandoItem = ((IDictionary<string, object>)item).ToExpando();
  91. itemList.Add(expandoItem);
  92. }
  93. else
  94. {
  95. itemList.Add(item);
  96. }
  97. }
  98. expandoDic.Add(kvp.Key, itemList);
  99. }
  100. else
  101. {
  102. expandoDic.Add(kvp);
  103. }
  104. }
  105. return expando;
  106. }
  107. /// <summary>
  108. /// Changes the type.
  109. /// </summary>
  110. /// <param name="value">The value.</param>
  111. /// <param name="conversionType">Type of the conversion.</param>
  112. /// <param name="defaultValue">The default value.</param>
  113. /// <returns></returns>
  114. public static object ChangeType(this object value, Type conversionType, object defaultValue)
  115. {
  116. try
  117. {
  118. return ChangeType(value, conversionType);
  119. }
  120. catch
  121. {
  122. return defaultValue;
  123. }
  124. }
  125. /// <summary>
  126. /// Converts the specified value.
  127. /// </summary>
  128. /// <typeparam name="T">Type of the result value</typeparam>
  129. /// <param name="value">The value.</param>
  130. /// <returns></returns>
  131. public static T ConvertTo<T>(this object value)
  132. {
  133. if((value != null) && (value.GetType() == typeof(string)))
  134. {
  135. return StringTo<T>((string)value);
  136. }
  137. if (value == null) return default(T);
  138. return (T)ChangeType(value, typeof(T));
  139. }
  140. /// <summary>
  141. /// Converts the specified value.
  142. /// </summary>
  143. /// <typeparam name="T">Type of the result value</typeparam>
  144. /// <param name="value">The value.</param>
  145. /// <param name="defaultValue">The default value if convert failed.</param>
  146. /// <returns></returns>
  147. public static T ConvertTo<T>(this object value, T defaultValue)
  148. {
  149. try
  150. {
  151. return ConvertTo<T>(value);
  152. }
  153. catch
  154. {
  155. return defaultValue;
  156. }
  157. }
  158. /// <summary>
  159. /// Converts byte array to binary string
  160. /// </summary>
  161. /// <param name="array">The array.</param>
  162. /// <returns></returns>
  163. public static string ToString(this byte[] array)
  164. {
  165. char[] chars = new char[array.Length / sizeof(char)];
  166. System.Buffer.BlockCopy(array, 0, chars, 0, array.Length);
  167. return new string(chars);
  168. }
  169. /// <summary>
  170. /// Converts char array to binary string
  171. /// </summary>
  172. /// <param name="array">The array.</param>
  173. /// <returns></returns>
  174. public static string ToString(this char[] array)
  175. {
  176. return new string(array);
  177. }
  178. /// <summary>
  179. /// Converts binary string to byte array.
  180. /// </summary>
  181. /// <param name="value">The value.</param>
  182. /// <returns></returns>
  183. public static byte[] ToByteArray(this string value)
  184. {
  185. byte[] bytes = new byte[value.Length * sizeof(char)];
  186. System.Buffer.BlockCopy(value.ToCharArray(), 0, bytes, 0, bytes.Length);
  187. return bytes;
  188. }
  189. /// <summary>
  190. /// Strings to base24.
  191. /// </summary>
  192. /// <param name="value">The value.</param>
  193. /// <returns></returns>
  194. public static string ToBase24(this string value)
  195. {
  196. const string sel = "BCDFGHJKMPQRTVWXY2346789";
  197. int i = 0;
  198. int Pos = 0;
  199. char[] Buf = new char[value.Length << 1];
  200. while ((i = Pos) < value.Length)
  201. {
  202. Buf[i << 1] = sel[(value[Pos]) >> 4];
  203. Buf[(i << 1) + 1] = sel[23 - (value[Pos] & 0x0F)];
  204. Pos++;
  205. }
  206. return new string(Buf);
  207. }
  208. /// <summary>
  209. /// Strings from base24.
  210. /// </summary>
  211. /// <param name="value">The value.</param>
  212. /// <returns></returns>
  213. public static string FromBase24(this string value)
  214. {
  215. const string sel = "BCDFGHJKMPQRTVWXY2346789";
  216. if (value.Length % 2 != 0)
  217. return null;
  218. int[] NPos = new int[2];
  219. char[] N = new char[2];
  220. char[] Buf = new char[value.Length >> 1];
  221. for (int i = 0; i < (value.Length >> 1); i++)
  222. {
  223. NPos[0] = sel.IndexOf(value[i << 1]);
  224. NPos[1] = 23 - sel.IndexOf(value[(i << 1) + 1]);
  225. if (NPos[0] < 0 || NPos[1] < 0)
  226. {
  227. return null;
  228. }
  229. Buf[i] = ((char)((NPos[0] << 4) | NPos[1]));
  230. }
  231. return new string(Buf);
  232. }
  233. /// <summary>
  234. /// Converts to base64 (UTF8).
  235. /// </summary>
  236. /// <param name="value">The value.</param>
  237. /// <returns></returns>
  238. public static string ToBase64(this string value)
  239. {
  240. return ToBase64(value, Encoding.UTF8);
  241. }
  242. /// <summary>
  243. /// String to base64 string.
  244. /// </summary>
  245. /// <param name="value">The value.</param>
  246. /// <param name="encoding">The encoding.</param>
  247. /// <returns></returns>
  248. public static string ToBase64(this string value, Encoding encoding)
  249. {
  250. return Convert.ToBase64String(encoding.GetBytes(value));
  251. }
  252. /// <summary>
  253. /// String from base64 string.
  254. /// </summary>
  255. /// <param name="value">The value.</param>
  256. /// <returns></returns>
  257. public static string FromBase64(this string value)
  258. {
  259. return Encoding.UTF8.GetString(Convert.FromBase64String(value));
  260. }
  261. /// <summary>
  262. /// Convert strings to type T
  263. /// </summary>
  264. /// <param name="value">The value.</param>
  265. /// <param name="type">The type.</param>
  266. /// <param name="defaultValue">The default value.</param>
  267. /// <returns></returns>
  268. public static object StringTo(string value, Type type, object defaultValue)
  269. {
  270. if (value != null)
  271. {
  272. try
  273. {
  274. return StringTo(value, type);
  275. }
  276. catch
  277. {
  278. }
  279. }
  280. return defaultValue;
  281. }
  282. /// <summary>
  283. /// Convert strings to type T
  284. /// </summary>
  285. /// <param name="value">The value.</param>
  286. /// <param name="type">The type.</param>
  287. /// <returns></returns>
  288. public static object StringTo(this string value, Type type)
  289. {
  290. if (type == typeof(Guid))
  291. {
  292. if (string.IsNullOrWhiteSpace(value)) return Guid.Empty;
  293. System.ComponentModel.GuidConverter guidConverter = new System.ComponentModel.GuidConverter();
  294. return guidConverter.ConvertFromString(value);
  295. }
  296. else if (type == typeof(byte[]))
  297. {
  298. return Convert.FromBase64String(value);
  299. }
  300. else if (type == typeof(char[]))
  301. {
  302. return Encoding.GetEncoding(850).GetChars((Convert.FromBase64String(value)));
  303. }
  304. else if (typeof(Enum).IsAssignableFrom(type))
  305. {
  306. return Enum.Parse(type, value);
  307. }
  308. else
  309. {
  310. return Convert.ChangeType(value, type);
  311. }
  312. }
  313. /// <summary>
  314. /// Convert strings to type T
  315. /// </summary>
  316. /// <typeparam name="T">The type string convert to.</typeparam>
  317. /// <param name="value">The value.</param>
  318. /// <param name="defaultValue">The default value.</param>
  319. /// <returns></returns>
  320. public static T StringTo<T>(this string value, T defaultValue)
  321. {
  322. return (T)StringTo(value, typeof(T), defaultValue);
  323. }
  324. /// <summary>
  325. /// Convert strings to type T
  326. /// </summary>
  327. /// <typeparam name="T"></typeparam>
  328. /// <param name="value">The value.</param>
  329. /// <returns></returns>
  330. public static T StringTo<T>(this string value)
  331. {
  332. return (T)StringTo(value, typeof(T), default(T));
  333. }
  334. /// <summary>
  335. /// Convert the type to string.
  336. /// </summary>
  337. /// <param name="value">The value.</param>
  338. /// <param name="defaultValue">The default value.</param>
  339. /// <returns></returns>
  340. public static string StringFrom(this object value, string defaultValue)
  341. {
  342. try
  343. {
  344. return StringFrom(value);
  345. }
  346. catch
  347. {
  348. }
  349. return defaultValue;
  350. }
  351. /// <summary>
  352. /// Convert the type to string.
  353. /// </summary>
  354. /// <param name="value">The value.</param>
  355. /// <returns></returns>
  356. public static string StringFrom(this object value)
  357. {
  358. if ((value == null) || (value == DBNull.Value)) return null;
  359. if (value.GetType() == typeof(Guid))
  360. {
  361. System.ComponentModel.GuidConverter guidConverter = new System.ComponentModel.GuidConverter();
  362. return guidConverter.ConvertToString(value);
  363. }
  364. if (value.GetType() == typeof(DateTime))
  365. {
  366. return ((DateTime)value).ToString("o");
  367. }
  368. if (value.GetType() == typeof(byte[]))
  369. {
  370. return Convert.ToBase64String((byte[])value);
  371. }
  372. if (value.GetType() == typeof(char[]))
  373. {
  374. return Convert.ToBase64String(Encoding.GetEncoding(850).GetBytes((char[])value));
  375. }
  376. if (typeof(Enum).IsAssignableFrom(value.GetType()))
  377. {
  378. return Enum.GetName(value.GetType(), value);
  379. }
  380. return (string)Convert.ChangeType(value, typeof(string));
  381. }
  382. }
  383. }