ConvertHelper.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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 specified value.
  141. /// </summary>
  142. /// <typeparam name="T">Type of the result value</typeparam>
  143. /// <param name="value">The value.</param>
  144. /// <returns></returns>
  145. public static T ConvertTo<T>(this object value)
  146. {
  147. if((value != null) && (value.GetType() == typeof(string)))
  148. {
  149. return StringTo<T>((string)value);
  150. }
  151. if (value == null) return default(T);
  152. return (T)ChangeType(value, typeof(T));
  153. }
  154. /// <summary>
  155. /// Converts the specified value.
  156. /// </summary>
  157. /// <typeparam name="T">Type of the result value</typeparam>
  158. /// <param name="value">The value.</param>
  159. /// <param name="defaultValue">The default value if convert failed.</param>
  160. /// <returns></returns>
  161. public static T ConvertTo<T>(this object value, T defaultValue)
  162. {
  163. try
  164. {
  165. return ConvertTo<T>(value);
  166. }
  167. catch
  168. {
  169. return defaultValue;
  170. }
  171. }
  172. /// <summary>
  173. /// Converts byte array to binary string
  174. /// </summary>
  175. /// <param name="array">The array.</param>
  176. /// <returns></returns>
  177. public static string ToString(this byte[] array)
  178. {
  179. char[] chars = new char[array.Length / sizeof(char)];
  180. System.Buffer.BlockCopy(array, 0, chars, 0, array.Length);
  181. return new string(chars);
  182. }
  183. /// <summary>
  184. /// Converts char array to binary string
  185. /// </summary>
  186. /// <param name="array">The array.</param>
  187. /// <returns></returns>
  188. public static string ToString(this char[] array)
  189. {
  190. return new string(array);
  191. }
  192. /// <summary>
  193. /// Converts binary string to byte array.
  194. /// </summary>
  195. /// <param name="value">The value.</param>
  196. /// <returns></returns>
  197. public static byte[] ToByteArray(this string value)
  198. {
  199. byte[] bytes = new byte[value.Length * sizeof(char)];
  200. System.Buffer.BlockCopy(value.ToCharArray(), 0, bytes, 0, bytes.Length);
  201. return bytes;
  202. }
  203. /// <summary>
  204. /// Strings to base24.
  205. /// </summary>
  206. /// <param name="value">The value.</param>
  207. /// <returns></returns>
  208. public static string ToBase24(this string value)
  209. {
  210. const string sel = "BCDFGHJKMPQRTVWXY2346789";
  211. int i = 0;
  212. int Pos = 0;
  213. char[] Buf = new char[value.Length << 1];
  214. while ((i = Pos) < value.Length)
  215. {
  216. Buf[i << 1] = sel[(value[Pos]) >> 4];
  217. Buf[(i << 1) + 1] = sel[23 - (value[Pos] & 0x0F)];
  218. Pos++;
  219. }
  220. return new string(Buf);
  221. }
  222. /// <summary>
  223. /// Strings from base24.
  224. /// </summary>
  225. /// <param name="value">The value.</param>
  226. /// <returns></returns>
  227. public static string FromBase24(this string value)
  228. {
  229. const string sel = "BCDFGHJKMPQRTVWXY2346789";
  230. if (value.Length % 2 != 0)
  231. return null;
  232. int[] NPos = new int[2];
  233. char[] N = new char[2];
  234. char[] Buf = new char[value.Length >> 1];
  235. for (int i = 0; i < (value.Length >> 1); i++)
  236. {
  237. NPos[0] = sel.IndexOf(value[i << 1]);
  238. NPos[1] = 23 - sel.IndexOf(value[(i << 1) + 1]);
  239. if (NPos[0] < 0 || NPos[1] < 0)
  240. {
  241. return null;
  242. }
  243. Buf[i] = ((char)((NPos[0] << 4) | NPos[1]));
  244. }
  245. return new string(Buf);
  246. }
  247. /// <summary>
  248. /// Converts to base64 (UTF8).
  249. /// </summary>
  250. /// <param name="value">The value.</param>
  251. /// <returns></returns>
  252. public static string ToBase64(this string value)
  253. {
  254. return ToBase64(value, Encoding.UTF8);
  255. }
  256. /// <summary>
  257. /// String to base64 string.
  258. /// </summary>
  259. /// <param name="value">The value.</param>
  260. /// <param name="encoding">The encoding.</param>
  261. /// <returns></returns>
  262. public static string ToBase64(this string value, Encoding encoding)
  263. {
  264. return Convert.ToBase64String(encoding.GetBytes(value));
  265. }
  266. /// <summary>
  267. /// String from base64 string.
  268. /// </summary>
  269. /// <param name="value">The value.</param>
  270. /// <returns></returns>
  271. public static string FromBase64(this string value)
  272. {
  273. return Encoding.UTF8.GetString(Convert.FromBase64String(value));
  274. }
  275. /// <summary>
  276. /// Convert strings to type T
  277. /// </summary>
  278. /// <param name="value">The value.</param>
  279. /// <param name="type">The type.</param>
  280. /// <param name="defaultValue">The default value.</param>
  281. /// <returns></returns>
  282. public static object StringTo(string value, Type type, object defaultValue)
  283. {
  284. if (value != null)
  285. {
  286. try
  287. {
  288. return StringTo(value, type);
  289. }
  290. catch
  291. {
  292. }
  293. }
  294. return defaultValue;
  295. }
  296. /// <summary>
  297. /// Convert strings to type T
  298. /// </summary>
  299. /// <param name="value">The value.</param>
  300. /// <param name="type">The type.</param>
  301. /// <returns></returns>
  302. public static object StringTo(this string value, Type type)
  303. {
  304. if (type == typeof(Guid))
  305. {
  306. if (string.IsNullOrWhiteSpace(value)) return Guid.Empty;
  307. System.ComponentModel.GuidConverter guidConverter = new System.ComponentModel.GuidConverter();
  308. return guidConverter.ConvertFromString(value);
  309. }
  310. else if (type == typeof(byte[]))
  311. {
  312. return Convert.FromBase64String(value);
  313. }
  314. else if (type == typeof(char[]))
  315. {
  316. return Encoding.GetEncoding(850).GetChars((Convert.FromBase64String(value)));
  317. }
  318. else if (typeof(Enum).IsAssignableFrom(type))
  319. {
  320. return Enum.Parse(type, value);
  321. }
  322. else
  323. {
  324. return Convert.ChangeType(value, type);
  325. }
  326. }
  327. /// <summary>
  328. /// Convert strings to type T
  329. /// </summary>
  330. /// <typeparam name="T">The type string convert to.</typeparam>
  331. /// <param name="value">The value.</param>
  332. /// <param name="defaultValue">The default value.</param>
  333. /// <returns></returns>
  334. public static T StringTo<T>(this string value, T defaultValue)
  335. {
  336. return (T)StringTo(value, typeof(T), defaultValue);
  337. }
  338. /// <summary>
  339. /// Convert strings to type T
  340. /// </summary>
  341. /// <typeparam name="T"></typeparam>
  342. /// <param name="value">The value.</param>
  343. /// <returns></returns>
  344. public static T StringTo<T>(this string value)
  345. {
  346. return (T)StringTo(value, typeof(T), default(T));
  347. }
  348. /// <summary>
  349. /// Convert the type to string.
  350. /// </summary>
  351. /// <param name="value">The value.</param>
  352. /// <param name="defaultValue">The default value.</param>
  353. /// <returns></returns>
  354. public static string StringFrom(this object value, string defaultValue)
  355. {
  356. try
  357. {
  358. return StringFrom(value);
  359. }
  360. catch
  361. {
  362. }
  363. return defaultValue;
  364. }
  365. /// <summary>
  366. /// Convert the type to string.
  367. /// </summary>
  368. /// <param name="value">The value.</param>
  369. /// <returns></returns>
  370. public static string StringFrom(this object value)
  371. {
  372. if ((value == null) || (value == DBNull.Value)) return null;
  373. if (value.GetType() == typeof(Guid))
  374. {
  375. System.ComponentModel.GuidConverter guidConverter = new System.ComponentModel.GuidConverter();
  376. return guidConverter.ConvertToString(value);
  377. }
  378. if (value.GetType() == typeof(DateTime))
  379. {
  380. return ((DateTime)value).ToString("o");
  381. }
  382. if (value.GetType() == typeof(byte[]))
  383. {
  384. return Convert.ToBase64String((byte[])value);
  385. }
  386. if (value.GetType() == typeof(char[]))
  387. {
  388. return Convert.ToBase64String(Encoding.GetEncoding(850).GetBytes((char[])value));
  389. }
  390. if (typeof(Enum).IsAssignableFrom(value.GetType()))
  391. {
  392. return Enum.GetName(value.GetType(), value);
  393. }
  394. return (string)Convert.ChangeType(value, typeof(string));
  395. }
  396. }
  397. }