TypeExtension.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. using SWRIS.Dtos;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Collections.ObjectModel;
  7. using System.ComponentModel;
  8. using System.Drawing;
  9. using System.Drawing.Imaging;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Reflection;
  13. using System.Text;
  14. using System.Text.RegularExpressions;
  15. using System.Windows;
  16. using System.Windows.Media.Imaging;
  17. namespace SWRIS.Extensions
  18. {
  19. public static class TypeExtension
  20. {
  21. public static string ToLogString(this Exception ex)
  22. {
  23. string result;
  24. if (ex == null)
  25. {
  26. result = string.Empty;
  27. }
  28. else
  29. {
  30. StringBuilder stringBuilder = new StringBuilder();
  31. stringBuilder.Append(" >>异常消息(Message):").AppendLine(ex.Message);
  32. stringBuilder.Append(" >>异常来源(Source):").AppendLine(ex.Source);
  33. stringBuilder.Append(" >>异常类型(ExceptionType):").AppendLine(ex.GetType().ToString());
  34. stringBuilder.Append(" >>原生异常类型(BaseExceptionType):").AppendLine(ex.GetBaseException().GetType().ToString());
  35. stringBuilder.Append(" >>出错的方法签名(TargetSite):").Append(ex.TargetSite);
  36. if (ex.Data.Count > 0)
  37. {
  38. stringBuilder.Append(Environment.NewLine);
  39. stringBuilder.Append(" >>自定义数据(Data):");
  40. StringBuilder stringBuilder2 = new StringBuilder();
  41. foreach (object obj in ex.Data)
  42. {
  43. DictionaryEntry dictionaryEntry = (DictionaryEntry)obj;
  44. stringBuilder2.Append(string.Concat(new object[]
  45. {
  46. "Key:",
  47. dictionaryEntry.Key,
  48. ",Value:",
  49. dictionaryEntry.Value,
  50. "; "
  51. }));
  52. }
  53. stringBuilder.Append(stringBuilder2);
  54. }
  55. if (!string.IsNullOrEmpty(ex.StackTrace))
  56. {
  57. stringBuilder.Append(Environment.NewLine);
  58. stringBuilder.Append(" >>堆栈信息(StackTrace):");
  59. stringBuilder.Append(Environment.NewLine);
  60. stringBuilder.Append(ex.StackTrace);
  61. }
  62. if (ex.InnerException != null)
  63. {
  64. stringBuilder.Append(Environment.NewLine);
  65. stringBuilder.Append(">>========================== 内部异常(InnerException)==========================");
  66. stringBuilder.Append(Environment.NewLine);
  67. stringBuilder.Append(ex.InnerException.ToLogString());
  68. }
  69. result = stringBuilder.ToString();
  70. }
  71. return result;
  72. }
  73. public static bool IsInvalid<T>(this IEnumerable<T> source)
  74. {
  75. return !source.IsValid<T>();
  76. }
  77. public static bool IsValid<T>(this IEnumerable<T> source)
  78. {
  79. return source != null && source.Any<T>();
  80. }
  81. public static bool IsNullOrEmpty(this string value)
  82. {
  83. return string.IsNullOrEmpty(value);
  84. }
  85. public static bool IsNullOrEmptyOrWhiteSpace(this string value)
  86. {
  87. bool flag = value.IsNullOrEmpty();
  88. if (!flag)
  89. {
  90. flag = value.Trim().IsNullOrEmpty();
  91. }
  92. return flag;
  93. }
  94. public static byte[] TranslateToBytes(this string hexString)
  95. {
  96. try
  97. {
  98. if (!Regex.IsMatch(hexString, @"^[0-9A-Fa-f]+H?$", RegexOptions.IgnoreCase))
  99. throw new ArgumentException("无效的十六进制格式");
  100. hexString = hexString.TrimEnd('H', 'h');
  101. if (hexString.Length != 4)
  102. throw new ArgumentException("字符串长度不正确");
  103. return (GetBigEndianBytes(Convert.ToUInt16(hexString, 16), 2));
  104. }
  105. catch (Exception ex)
  106. {
  107. Console.WriteLine($"识别码或序列号转化字节数组失败: {ex.Message}");
  108. return null;
  109. }
  110. }
  111. public static byte[] GetBigEndianBytes(uint value, int byteCount)
  112. {
  113. byte[] bytes = new byte[byteCount];
  114. for (int i = 0; i < byteCount; i++)
  115. {
  116. bytes[i] = (byte)(value >> (8 * (byteCount - 1 - i)));
  117. }
  118. return bytes;
  119. }
  120. /// <summary>
  121. /// 计算校验和(所有字节相加之和,取8位,溢出不计)
  122. /// </summary>
  123. public static byte CalculateChecksum(this byte[] data)
  124. {
  125. byte checksum = 0;
  126. foreach (byte b in data)
  127. {
  128. unchecked { checksum += b; }
  129. }
  130. return checksum;
  131. }
  132. /// <summary>
  133. /// 计算校验和(所有字节相加之和,取8位,溢出不计)
  134. /// </summary>
  135. public static byte CalculateChecksum(this IEnumerable<byte> data)
  136. {
  137. byte checksum = 0;
  138. foreach (byte b in data)
  139. {
  140. unchecked { checksum += b; }
  141. }
  142. return checksum;
  143. }
  144. public static void AddRange<T>(this ICollection<T> @this, IEnumerable<T> values)
  145. {
  146. foreach (T item in values)
  147. {
  148. @this.Add(item);
  149. }
  150. }
  151. public static BitmapImage ConvertBitmapToBitmapImage(this Bitmap bitmap)
  152. {
  153. MemoryStream stream = new MemoryStream();
  154. bitmap.Save(stream, ImageFormat.Bmp);
  155. BitmapImage image = new BitmapImage();
  156. image.BeginInit();
  157. image.StreamSource = stream;
  158. image.EndInit();
  159. return image;
  160. }
  161. public static bool? ShowDialog(this Window window, bool isMaskVisible)
  162. {
  163. bool? result = null;
  164. if (window != null)
  165. {
  166. if (isMaskVisible)
  167. {
  168. MainWindow mainWindow = Application.Current.MainWindow as MainWindow;
  169. mainWindow.IsMaskVisible = true;
  170. result = window.ShowDialog();
  171. mainWindow.IsMaskVisible = false;
  172. }
  173. else
  174. {
  175. result = window.ShowDialog();
  176. }
  177. }
  178. return result;
  179. }
  180. public static string GetDescription(this Enum @this)
  181. {
  182. return _CacheDescriptions.GetOrAdd(@this, delegate (Enum key)
  183. {
  184. Type type = key.GetType();
  185. FieldInfo field = type.GetField(key.ToString());
  186. return (field == null) ? key.GetDescriptions(",") : GetDescription(field);
  187. });
  188. }
  189. public static string GetDescriptions(this Enum @this, string separator = ",")
  190. {
  191. string[] array = @this.ToString().Split(new char[]
  192. {
  193. ','
  194. });
  195. string[] array2 = new string[array.Length];
  196. Type type = @this.GetType();
  197. for (int i = 0; i < array.Length; i++)
  198. {
  199. FieldInfo field = type.GetField(array[i].Trim());
  200. if (!(field == null))
  201. {
  202. array2[i] = GetDescription(field);
  203. }
  204. }
  205. return string.Join(separator, array2);
  206. }
  207. public static string GetDefaultValue(this Enum @this)
  208. {
  209. return _CacheDefaultValues.GetOrAdd(@this, delegate (Enum key)
  210. {
  211. Type type = key.GetType();
  212. FieldInfo field = type.GetField(key.ToString());
  213. return (field == null) ? key.GetDefaultValues(",") : GetDefaultValue(field);
  214. });
  215. }
  216. public static string GetDefaultValues(this Enum @this, string separator = ",")
  217. {
  218. string[] array = @this.ToString().Split(new char[]
  219. {
  220. ','
  221. });
  222. string[] array2 = new string[array.Length];
  223. Type type = @this.GetType();
  224. for (int i = 0; i < array.Length; i++)
  225. {
  226. FieldInfo field = type.GetField(array[i].Trim());
  227. if (!(field == null))
  228. {
  229. array2[i] = GetDefaultValue(field);
  230. }
  231. }
  232. return string.Join(separator, array2);
  233. }
  234. public static ObservableCollection<T> ConvertToObservableCollection<T>(this IEnumerable<T> from)
  235. {
  236. ObservableCollection<T> to = new ObservableCollection<T>();
  237. if (from != null)
  238. {
  239. foreach (var f in from)
  240. {
  241. to.Add(f);
  242. }
  243. }
  244. return to;
  245. }
  246. public static List<KeyAndValueDto> ToKeyAndDescriptionList(this Type type)
  247. {
  248. if (type.IsEnum)
  249. {
  250. List<KeyAndValueDto> list = new List<KeyAndValueDto>();
  251. Array _enumValues = Enum.GetValues(type);
  252. foreach (Enum value in _enumValues)
  253. {
  254. list.Add(new KeyAndValueDto()
  255. {
  256. Key = Convert.ToInt32(value),
  257. Value = GetDescription(value)
  258. });
  259. }
  260. return list;
  261. }
  262. return null;
  263. }
  264. private static string GetDefaultValue(FieldInfo field)
  265. {
  266. Attribute customAttribute = Attribute.GetCustomAttribute(field, typeof(DefaultValueAttribute), false);
  267. return (customAttribute == null) ? string.Empty : ((DefaultValueAttribute)customAttribute).Value.ToString();
  268. }
  269. private static string GetDescription(FieldInfo field)
  270. {
  271. Attribute customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false);
  272. return (customAttribute == null) ? string.Empty : ((DescriptionAttribute)customAttribute).Description;
  273. }
  274. private static readonly ConcurrentDictionary<Enum, string> _CacheDescriptions = new ConcurrentDictionary<Enum, string>();
  275. private static readonly ConcurrentDictionary<Enum, string> _CacheDefaultValues = new ConcurrentDictionary<Enum, string>();
  276. }
  277. }