ConvertHelper.cs 31 KB

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