UtilMethods.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Linq.Expressions;
  8. using System.Reflection;
  9. using System.Runtime.CompilerServices;
  10. using System.Security.Cryptography;
  11. using System.Text;
  12. using System.Text.RegularExpressions;
  13. namespace SqlSugar.BzTDengineCore
  14. {
  15. public class UtilMethods
  16. {
  17. public static long ToUnixTimestamp(DateTime dateTime)
  18. {
  19. // If the DateTime is Utc, use ToUnixTimeMilliseconds directly
  20. if (dateTime.Kind == DateTimeKind.Utc)
  21. {
  22. return new DateTimeOffset(dateTime).ToUnixTimeMilliseconds();
  23. }
  24. else
  25. {
  26. // Convert local DateTime to Utc before converting to Unix timestamp
  27. return new DateTimeOffset(dateTime.ToUniversalTime()).ToUnixTimeMilliseconds();
  28. }
  29. }
  30. internal static DateTime GetMinDate(ConnectionConfig currentConnectionConfig)
  31. {
  32. if (currentConnectionConfig.MoreSettings == null)
  33. {
  34. return Convert.ToDateTime("1900-01-01");
  35. }
  36. else if (currentConnectionConfig.MoreSettings.DbMinDate == null)
  37. {
  38. return Convert.ToDateTime("1900-01-01");
  39. }
  40. else
  41. {
  42. return currentConnectionConfig.MoreSettings.DbMinDate.Value;
  43. }
  44. }
  45. internal static DateTime ConvertFromDateTimeOffset(DateTimeOffset dateTime)
  46. {
  47. if (dateTime.Offset.Equals(TimeSpan.Zero))
  48. return dateTime.UtcDateTime;
  49. else if (dateTime.Offset.Equals(TimeZoneInfo.Local.GetUtcOffset(dateTime.DateTime)))
  50. return DateTime.SpecifyKind(dateTime.DateTime, DateTimeKind.Local);
  51. else
  52. return dateTime.DateTime;
  53. }
  54. internal static object To(object value, Type destinationType)
  55. {
  56. return To(value, destinationType, CultureInfo.InvariantCulture);
  57. }
  58. internal static object To(object value, Type destinationType, CultureInfo culture)
  59. {
  60. if (value != null)
  61. {
  62. destinationType = UtilMethods.GetUnderType(destinationType);
  63. var sourceType = value.GetType();
  64. var destinationConverter = TypeDescriptor.GetConverter(destinationType);
  65. if (destinationConverter != null && destinationConverter.CanConvertFrom(value.GetType()))
  66. return destinationConverter.ConvertFrom(null, culture, value);
  67. var sourceConverter = TypeDescriptor.GetConverter(sourceType);
  68. if (sourceConverter != null && sourceConverter.CanConvertTo(destinationType))
  69. return sourceConverter.ConvertTo(null, culture, value, destinationType);
  70. if (destinationType.IsEnum && value is int)
  71. return Enum.ToObject(destinationType, (int)value);
  72. if (!destinationType.IsInstanceOfType(value))
  73. return Convert.ChangeType(value, destinationType, culture);
  74. }
  75. return value;
  76. }
  77. public static bool IsAnyAsyncMethod(StackFrame[] methods)
  78. {
  79. bool isAsync = false;
  80. foreach (var item in methods)
  81. {
  82. if (UtilMethods.IsAsyncMethod(item.GetMethod()))
  83. {
  84. isAsync = true;
  85. break;
  86. }
  87. }
  88. return isAsync;
  89. }
  90. public static bool IsAsyncMethod(MethodBase method)
  91. {
  92. if (method == null)
  93. {
  94. return false;
  95. }
  96. if (method.DeclaringType != null)
  97. {
  98. if (method.DeclaringType.GetInterfaces().Contains(typeof(IAsyncStateMachine)))
  99. {
  100. return true;
  101. }
  102. }
  103. var name = method.Name;
  104. if (name.Contains("OutputAsyncCausalityEvents"))
  105. {
  106. return true;
  107. }
  108. if (name.Contains("OutputWaitEtwEvents"))
  109. {
  110. return true;
  111. }
  112. if (name.Contains("ExecuteAsync"))
  113. {
  114. return true;
  115. }
  116. Type attType = typeof(AsyncStateMachineAttribute);
  117. var attrib = (AsyncStateMachineAttribute)method.GetCustomAttribute(attType);
  118. return (attrib != null);
  119. }
  120. public static StackTraceInfo GetStackTrace()
  121. {
  122. StackTrace st = new StackTrace(true);
  123. StackTraceInfo info = new StackTraceInfo();
  124. info.MyStackTraceList = new List<StackTraceInfoItem>();
  125. info.SugarStackTraceList = new List<StackTraceInfoItem>();
  126. for (int i = 0; i < st.FrameCount; i++)
  127. {
  128. var frame = st.GetFrame(i);
  129. if (frame.GetMethod().Module.Name.ToLower() != "sqlsugar.dll" && frame.GetMethod().Name.First() != '<')
  130. {
  131. info.MyStackTraceList.Add(new StackTraceInfoItem()
  132. {
  133. FileName = frame.GetFileName(),
  134. MethodName = frame.GetMethod().Name,
  135. Line = frame.GetFileLineNumber()
  136. });
  137. }
  138. else
  139. {
  140. info.SugarStackTraceList.Add(new StackTraceInfoItem()
  141. {
  142. FileName = frame.GetFileName(),
  143. MethodName = frame.GetMethod().Name,
  144. Line = frame.GetFileLineNumber()
  145. });
  146. }
  147. }
  148. return info;
  149. }
  150. internal static T To<T>(object value)
  151. {
  152. return (T)To(value, typeof(T));
  153. }
  154. internal static Type GetUnderType(Type oldType)
  155. {
  156. Type type = Nullable.GetUnderlyingType(oldType);
  157. return type == null ? oldType : type;
  158. }
  159. public static string ReplaceSqlParameter(string itemSql, SugarParameter itemParameter, string newName)
  160. {
  161. itemSql = Regex.Replace(itemSql, string.Format(@"{0} ", "\\" + itemParameter.ParameterName), newName + " ", RegexOptions.IgnoreCase);
  162. itemSql = Regex.Replace(itemSql, string.Format(@"{0}\)", "\\" + itemParameter.ParameterName), newName + ")", RegexOptions.IgnoreCase);
  163. itemSql = Regex.Replace(itemSql, string.Format(@"{0}\,", "\\" + itemParameter.ParameterName), newName + ",", RegexOptions.IgnoreCase);
  164. itemSql = Regex.Replace(itemSql, string.Format(@"{0}$", "\\" + itemParameter.ParameterName), newName, RegexOptions.IgnoreCase);
  165. itemSql = Regex.Replace(itemSql, string.Format(@"\+{0}\+", "\\" + itemParameter.ParameterName), "+" + newName + "+", RegexOptions.IgnoreCase);
  166. itemSql = Regex.Replace(itemSql, string.Format(@"\+{0} ", "\\" + itemParameter.ParameterName), "+" + newName + " ", RegexOptions.IgnoreCase);
  167. itemSql = Regex.Replace(itemSql, string.Format(@" {0}\+", "\\" + itemParameter.ParameterName), " " + newName + "+", RegexOptions.IgnoreCase);
  168. itemSql = Regex.Replace(itemSql, string.Format(@"\|\|{0}\|\|", "\\" + itemParameter.ParameterName), "||" + newName + "||", RegexOptions.IgnoreCase);
  169. itemSql = Regex.Replace(itemSql, string.Format(@"\={0}\+", "\\" + itemParameter.ParameterName), "=" + newName + "+", RegexOptions.IgnoreCase);
  170. itemSql = Regex.Replace(itemSql, string.Format(@"{0}\|\|", "\\" + itemParameter.ParameterName), newName + "||", RegexOptions.IgnoreCase);
  171. return itemSql;
  172. }
  173. internal static Type GetRootBaseType(Type entityType)
  174. {
  175. var baseType = entityType.BaseType;
  176. while (baseType != null && baseType.BaseType != UtilConstants.ObjType)
  177. {
  178. baseType = baseType.BaseType;
  179. }
  180. return baseType;
  181. }
  182. internal static Type GetUnderType(PropertyInfo propertyInfo, ref bool isNullable)
  183. {
  184. Type unType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);
  185. isNullable = unType != null;
  186. unType = unType ?? propertyInfo.PropertyType;
  187. return unType;
  188. }
  189. internal static Type GetUnderType(PropertyInfo propertyInfo)
  190. {
  191. Type unType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);
  192. unType = unType ?? propertyInfo.PropertyType;
  193. return unType;
  194. }
  195. internal static bool IsNullable(PropertyInfo propertyInfo)
  196. {
  197. Type unType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);
  198. return unType != null;
  199. }
  200. internal static bool IsNullable(Type type)
  201. {
  202. Type unType = Nullable.GetUnderlyingType(type);
  203. return unType != null;
  204. }
  205. //internal static T IsNullReturnNew<T>(T returnObj) where T : new()
  206. //{
  207. // if (returnObj.IsNullOrEmpty())
  208. // {
  209. // returnObj = new T();
  210. // }
  211. // return returnObj;
  212. //}
  213. public static object ChangeType2(object value, Type type)
  214. {
  215. if (value == null && type.IsGenericType) return Activator.CreateInstance(type);
  216. if (value == null) return null;
  217. if (type == value.GetType()) return value;
  218. if (type.IsEnum)
  219. {
  220. if (value is string)
  221. return Enum.Parse(type, value as string);
  222. else
  223. return Enum.ToObject(type, value);
  224. }
  225. if (!type.IsInterface && type.IsGenericType)
  226. {
  227. Type innerType = type.GetGenericArguments()[0];
  228. object innerValue = ChangeType(value, innerType);
  229. return Activator.CreateInstance(type, new object[] { innerValue });
  230. }
  231. if (value is string && type == typeof(Guid)) return new Guid(value as string);
  232. if (value is string && type == typeof(Version)) return new Version(value as string);
  233. if (!(value is IConvertible)) return value;
  234. return Convert.ChangeType(value, type);
  235. }
  236. internal static T ChangeType<T>(T obj, Type type)
  237. {
  238. return (T)Convert.ChangeType(obj, type);
  239. }
  240. internal static T ChangeType<T>(T obj)
  241. {
  242. return (T)Convert.ChangeType(obj, typeof(T));
  243. }
  244. internal static DateTimeOffset GetDateTimeOffsetByDateTime(DateTime date)
  245. {
  246. date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
  247. DateTimeOffset utcTime2 = date;
  248. return utcTime2;
  249. }
  250. //internal static void RepairReplicationParameters(ref string appendSql, SugarParameter[] parameters, int addIndex, string append = null)
  251. //{
  252. // if (appendSql.HasValue() && parameters.HasValue())
  253. // {
  254. // foreach (var parameter in parameters.OrderByDescending(it => it.ParameterName.Length))
  255. // {
  256. // //Compatible with.NET CORE parameters case
  257. // var name = parameter.ParameterName;
  258. // string newName = name + append + addIndex;
  259. // appendSql = ReplaceSqlParameter(appendSql, parameter, newName);
  260. // parameter.ParameterName = newName;
  261. // }
  262. // }
  263. //}
  264. internal static string GetPackTable(string sql, string shortName)
  265. {
  266. return string.Format(" ({0}) {1} ", sql, shortName);
  267. }
  268. public static Func<string, object> GetTypeConvert(object value)
  269. {
  270. if (value is int || value is uint || value is int? || value is uint?)
  271. {
  272. return x => Convert.ToInt32(x);
  273. }
  274. else if (value is short || value is ushort || value is short? || value is ushort?)
  275. {
  276. return x => Convert.ToInt16(x);
  277. }
  278. else if (value is long || value is long? || value is ulong? || value is long?)
  279. {
  280. return x => Convert.ToInt64(x);
  281. }
  282. else if (value is DateTime || value is DateTime?)
  283. {
  284. return x => Convert.ToDateTime(x);
  285. }
  286. else if (value is bool || value is bool?)
  287. {
  288. return x => Convert.ToBoolean(x);
  289. }
  290. return null;
  291. }
  292. internal static string GetTypeName(object value)
  293. {
  294. if (value == null)
  295. {
  296. return null;
  297. }
  298. else
  299. {
  300. return value.GetType().Name;
  301. }
  302. }
  303. internal static string GetParenthesesValue(string dbTypeName)
  304. {
  305. if (Regex.IsMatch(dbTypeName, @"\(.+\)"))
  306. {
  307. dbTypeName = Regex.Replace(dbTypeName, @"\(.+\)", "");
  308. }
  309. dbTypeName = dbTypeName.Trim();
  310. return dbTypeName;
  311. }
  312. internal static T GetOldValue<T>(T value, Action action)
  313. {
  314. action();
  315. return value;
  316. }
  317. internal static object DefaultForType(Type targetType)
  318. {
  319. return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
  320. }
  321. internal static Int64 GetLong(byte[] bytes)
  322. {
  323. return Convert.ToInt64(string.Join("", bytes).PadRight(20, '0'));
  324. }
  325. public static object GetPropertyValue<T>(T t, string PropertyName)
  326. {
  327. return t.GetType().GetProperty(PropertyName).GetValue(t, null);
  328. }
  329. internal static string GetMD5(string myString)
  330. {
  331. MD5 md5 = new MD5CryptoServiceProvider();
  332. byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString);
  333. byte[] targetData = md5.ComputeHash(fromData);
  334. string byte2String = null;
  335. for (int i = 0; i < targetData.Length; i++)
  336. {
  337. byte2String += targetData[i].ToString("x");
  338. }
  339. return byte2String;
  340. }
  341. //public static string EncodeBase64(string code)
  342. //{
  343. // if (code.IsNullOrEmpty()) return code;
  344. // string encode = "";
  345. // byte[] bytes = Encoding.GetEncoding("utf-8").GetBytes(code);
  346. // try
  347. // {
  348. // encode = Convert.ToBase64String(bytes);
  349. // }
  350. // catch
  351. // {
  352. // encode = code;
  353. // }
  354. // return encode;
  355. //}
  356. public static string ConvertNumbersToString(string value)
  357. {
  358. string[] splitInt = value.Split(new char[] { '9' }, StringSplitOptions.RemoveEmptyEntries);
  359. var splitChars = splitInt.Select(s => Convert.ToChar(
  360. Convert.ToInt32(s, 8)
  361. ).ToString());
  362. return string.Join("", splitChars);
  363. }
  364. public static string ConvertStringToNumbers(string value)
  365. {
  366. StringBuilder sb = new StringBuilder();
  367. foreach (char c in value)
  368. {
  369. int cAscil = (int)c;
  370. sb.Append(Convert.ToString(c, 8) + "9");
  371. }
  372. return sb.ToString();
  373. }
  374. //public static string DecodeBase64(string code)
  375. //{
  376. // try
  377. // {
  378. // if (code.IsNullOrEmpty()) return code;
  379. // string decode = "";
  380. // byte[] bytes = Convert.FromBase64String(code);
  381. // try
  382. // {
  383. // decode = Encoding.GetEncoding("utf-8").GetString(bytes);
  384. // }
  385. // catch
  386. // {
  387. // decode = code;
  388. // }
  389. // return decode;
  390. // }
  391. // catch
  392. // {
  393. // return code;
  394. // }
  395. //}
  396. public static void DataInoveByExpresson<Type>(Type[] datas, MethodCallExpression callExpresion)
  397. {
  398. var methodInfo = callExpresion.Method;
  399. foreach (var item in datas)
  400. {
  401. if (callExpresion.Arguments.Count == 0)
  402. {
  403. methodInfo.Invoke(item, null);
  404. }
  405. else
  406. {
  407. List<object> methodParameters = new List<object>();
  408. foreach (var callItem in callExpresion.Arguments)
  409. {
  410. var parameter = callItem.GetType().GetProperties().FirstOrDefault(it => it.Name == "Value");
  411. if (parameter == null)
  412. {
  413. var value = LambdaExpression.Lambda(callItem).Compile().DynamicInvoke();
  414. methodParameters.Add(value);
  415. }
  416. else
  417. {
  418. var value = parameter.GetValue(callItem, null);
  419. methodParameters.Add(value);
  420. }
  421. }
  422. methodInfo.Invoke(item, methodParameters.ToArray());
  423. }
  424. }
  425. }
  426. public static Dictionary<string, T> EnumToDictionary<T>()
  427. {
  428. Dictionary<string, T> dic = new Dictionary<string, T>();
  429. if (!typeof(T).IsEnum)
  430. {
  431. return dic;
  432. }
  433. string desc = string.Empty;
  434. foreach (var item in Enum.GetValues(typeof(T)))
  435. {
  436. var key = item.ToString().ToLower();
  437. if (!dic.ContainsKey(key))
  438. dic.Add(key, (T)item);
  439. }
  440. return dic;
  441. }
  442. //public static object ConvertDataByTypeName(string ctypename,string value)
  443. //{
  444. // var item = new ConditionalModel() {
  445. // CSharpTypeName = ctypename,
  446. // FieldValue = value
  447. // };
  448. // if (item.CSharpTypeName.EqualCase(UtilConstants.DecType.Name))
  449. // {
  450. // return Convert.ToDecimal(item.FieldValue);
  451. // }
  452. // else if (item.CSharpTypeName.EqualCase(UtilConstants.DobType.Name))
  453. // {
  454. // return Convert.ToDouble(item.FieldValue);
  455. // }
  456. // else if (item.CSharpTypeName.EqualCase(UtilConstants.DateType.Name))
  457. // {
  458. // return Convert.ToDateTime(item.FieldValue);
  459. // }
  460. // else if (item.CSharpTypeName.EqualCase(UtilConstants.IntType.Name))
  461. // {
  462. // return Convert.ToInt32(item.FieldValue);
  463. // }
  464. // else if (item.CSharpTypeName.EqualCase(UtilConstants.LongType.Name))
  465. // {
  466. // return Convert.ToInt64(item.FieldValue);
  467. // }
  468. // else if (item.CSharpTypeName.EqualCase(UtilConstants.ShortType.Name))
  469. // {
  470. // return Convert.ToInt16(item.FieldValue);
  471. // }
  472. // else if (item.CSharpTypeName.EqualCase(UtilConstants.DateTimeOffsetType.Name))
  473. // {
  474. // return UtilMethods.GetDateTimeOffsetByDateTime(Convert.ToDateTime(item.FieldValue));
  475. // }
  476. // else
  477. // {
  478. // return item.FieldValue;
  479. // }
  480. //}
  481. }
  482. }