CommonFun.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. using OASystem.Domain.ViewModels.Financial;
  2. using OASystem.Domain.ViewModels.Groups;
  3. using System.Globalization;
  4. using System.Reflection;
  5. using System.Reflection.Metadata;
  6. namespace OASystem.Infrastructure.Tools;
  7. /// <summary>
  8. /// 工具类
  9. /// </summary>
  10. public static class CommonFun
  11. {
  12. public static string GUID => Guid.NewGuid().ToString("N");
  13. public static bool IsNull(this string s)
  14. {
  15. return string.IsNullOrWhiteSpace(s);
  16. }
  17. public static bool NotNull(this string s)
  18. {
  19. return !string.IsNullOrWhiteSpace(s);
  20. }
  21. public static int GetRandom(int minNum, int maxNum)
  22. {
  23. var seed = BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0);
  24. return new Random(seed).Next(minNum, maxNum);
  25. }
  26. public static string GetSerialNumber(string prefix = "")
  27. {
  28. return prefix + DateTime.Now.ToString("yyyyMMddHHmmssfff") + GetRandom(1000, 9999).ToString();
  29. }
  30. public static string ToJson(this object obj)
  31. {
  32. return JsonSerializer.Serialize(obj);
  33. }
  34. public static T ToObject<T>(this string json)
  35. {
  36. return JsonSerializer.Deserialize<T>(json);
  37. }
  38. public static object GetDefaultVal(string typename)
  39. {
  40. return typename switch
  41. {
  42. "Boolean" => false,
  43. "DateTime" => default(DateTime),
  44. "Date" => default(DateTime),
  45. "Double" => 0.0,
  46. "Single" => 0f,
  47. "Int32" => 0,
  48. "String" => string.Empty,
  49. "Decimal" => 0m,
  50. _ => null,
  51. };
  52. }
  53. public static void CoverNull<T>(T model) where T : class
  54. {
  55. if (model == null)
  56. {
  57. return;
  58. }
  59. var typeFromHandle = typeof(T);
  60. var properties = typeFromHandle.GetProperties();
  61. var array = properties;
  62. for (var i = 0; i < array.Length; i++)
  63. {
  64. var propertyInfo = array[i];
  65. if (propertyInfo.GetValue(model, null) == null)
  66. {
  67. propertyInfo.SetValue(model, GetDefaultVal(propertyInfo.PropertyType.Name), null);
  68. }
  69. }
  70. }
  71. public static void CoverNull<T>(List<T> models) where T : class
  72. {
  73. if (models.Count == 0)
  74. {
  75. return;
  76. }
  77. foreach (var model in models)
  78. {
  79. CoverNull(model);
  80. }
  81. }
  82. public static bool ToBool(this object thisValue, bool errorvalue = false)
  83. {
  84. if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out bool reval))
  85. {
  86. return reval;
  87. }
  88. return errorvalue;
  89. }
  90. #region 文件操作
  91. public static FileInfo[] GetFiles(string directoryPath)
  92. {
  93. if (!IsExistDirectory(directoryPath))
  94. {
  95. throw new DirectoryNotFoundException();
  96. }
  97. var root = new DirectoryInfo(directoryPath);
  98. return root.GetFiles();
  99. }
  100. public static bool IsExistDirectory(string directoryPath)
  101. {
  102. return Directory.Exists(directoryPath);
  103. }
  104. public static string ReadFile(string Path)
  105. {
  106. string s;
  107. if (!File.Exists(Path))
  108. s = "不存在相应的目录";
  109. else
  110. {
  111. var f2 = new StreamReader(Path, Encoding.Default);
  112. s = f2.ReadToEnd();
  113. f2.Close();
  114. f2.Dispose();
  115. }
  116. return s;
  117. }
  118. public static void FileMove(string OrignFile, string NewFile)
  119. {
  120. File.Move(OrignFile, NewFile);
  121. }
  122. public static void CreateDir(string dir)
  123. {
  124. if (dir.Length == 0) return;
  125. if (!Directory.Exists(dir))
  126. Directory.CreateDirectory(dir);
  127. }
  128. #endregion
  129. #region IP
  130. /// <summary>
  131. /// 是否为ip
  132. /// </summary>
  133. /// <param name="ip"></param>
  134. /// <returns></returns>
  135. public static bool IsIP(string ip)
  136. {
  137. return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
  138. }
  139. public static string GetIP(HttpRequest request)
  140. {
  141. if (request == null)
  142. {
  143. return "";
  144. }
  145. var ip = request.Headers["X-Real-IP"].FirstOrDefault();
  146. if (ip.IsNull())
  147. {
  148. ip = request.Headers["X-Forwarded-For"].FirstOrDefault();
  149. }
  150. if (ip.IsNull())
  151. {
  152. ip = request.HttpContext?.Connection?.RemoteIpAddress?.ToString();
  153. }
  154. if (ip.IsNull() || !IsIP(ip))
  155. {
  156. ip = "127.0.0.1";
  157. }
  158. return ip;
  159. }
  160. #endregion
  161. #region 随机数
  162. /// <summary>
  163. /// 根据自定义随机包含的字符获取指定长度的随机字符
  164. /// </summary>
  165. /// <param name="length">随机字符长度</param>
  166. /// <returns>随机字符</returns>
  167. public static string GetRandomStr(int length)
  168. {
  169. string a = "ABCDEFGHJKLMNPQRSTUVWXYZ012356789";
  170. StringBuilder sb = new StringBuilder();
  171. for (int i = 0; i < length; i++)
  172. {
  173. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  174. }
  175. return sb.ToString();
  176. }
  177. /// <summary>
  178. /// 根据自定义随机包含的字符获取指定长度的随机字符
  179. /// </summary>
  180. /// <param name="length">随机字符长度</param>
  181. /// <returns>随机字符</returns>
  182. public static string GetRandomAllStr(int length)
  183. {
  184. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz012356789";
  185. StringBuilder sb = new StringBuilder();
  186. for (int i = 0; i < length; i++)
  187. {
  188. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  189. }
  190. return sb.ToString();
  191. }
  192. /// <summary>
  193. /// 根据自定义随机包含的字符获取指定长度的随机字母(含大小写)
  194. /// </summary>
  195. /// <param name="length">随机字符长度</param>
  196. /// <returns>随机字符</returns>
  197. public static string GetRandomLetter(int length)
  198. {
  199. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz";
  200. StringBuilder sb = new StringBuilder();
  201. for (int i = 0; i < length; i++)
  202. {
  203. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  204. }
  205. return sb.ToString();
  206. }
  207. /// <summary>
  208. /// 生成不重复随机数字
  209. /// 操作者:037
  210. /// 2021-07-26 15:39
  211. /// </summary>
  212. /// <param name="CodeCount">输入字符串长度</param>
  213. /// <returns>字符串</returns>
  214. public static string GetRandomNumber(int len)
  215. {
  216. string allChar = "0,1,2,3,4,5,6,7,8,9";
  217. string[] allCharArray = allChar.Split(',');
  218. string RandomCode = "";
  219. int temp = -1;
  220. Random rand = new Random();
  221. for (int i = 0; i < len; i++)
  222. {
  223. if (temp != -1)
  224. {
  225. rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
  226. }
  227. int t = rand.Next(allCharArray.Length - 1);
  228. while (temp == t)
  229. {
  230. t = rand.Next(allCharArray.Length - 1);
  231. }
  232. temp = t;
  233. RandomCode += allCharArray[t];
  234. }
  235. return RandomCode;
  236. }
  237. #endregion
  238. #region decimal 截取
  239. /// <summary>
  240. ///
  241. /// </summary>
  242. /// <param name="d"></param>
  243. /// <param name="n"></param>
  244. /// <returns></returns>
  245. public static decimal CutDecimalWithN(decimal d, int n)
  246. {
  247. string strDecimal = d.ToString();
  248. int index = strDecimal.IndexOf(".");
  249. if (index == -1 || strDecimal.Length < index + n + 1)
  250. {
  251. strDecimal = string.Format("{0:F" + n + "}", d);
  252. }
  253. else
  254. {
  255. int length = index;
  256. if (n != 0)
  257. {
  258. length = index + n + 1;
  259. }
  260. strDecimal = strDecimal.Substring(0, length);
  261. }
  262. return Decimal.Parse(strDecimal);
  263. }
  264. public static decimal CutDecimalWithN(decimal? d, int n)
  265. {
  266. if (d == null)
  267. {
  268. return Decimal.MinValue;
  269. }
  270. return CutDecimalWithN(Convert.ToDecimal(d), n);
  271. }
  272. #endregion
  273. #region decimal 保留两位小数
  274. /// <summary>
  275. /// decimal 保留两位小数 不四舍五入
  276. /// </summary>
  277. /// <param name="number"></param>
  278. /// <returns></returns>
  279. public static decimal DecimalsKeepTwo(this decimal myDecimal)
  280. {
  281. var subDecimal = Math.Floor(myDecimal * 100) / 100;//保留两位小数,直接截取
  282. return subDecimal;
  283. }
  284. #endregion
  285. #region 团组模块 - 汇率相关存储解析
  286. /// <summary>
  287. /// 团组模块 - 汇率相关 To List
  288. /// </summary>
  289. /// <param name="rateStr"></param>
  290. /// <returns></returns>
  291. public static List<CurrencyInfo> GetCurrencyChinaToList(string? rateStr)
  292. {
  293. List<CurrencyInfo> currencyInfos = new List<CurrencyInfo>();
  294. if (string.IsNullOrEmpty(rateStr)) return currencyInfos;
  295. if (rateStr.Contains("|"))
  296. {
  297. string[] currencyArr = rateStr.Split("|");
  298. foreach (string currency in currencyArr)
  299. {
  300. string[] currency1 = currency.Split(":");
  301. string[] currency2 = currency1[0].Split("(");
  302. CurrencyInfo rateInfo = new CurrencyInfo()
  303. {
  304. CurrencyCode = currency2[1].Replace(")", "").TrimEnd(),
  305. CurrencyName = currency2[0],
  306. Rate = decimal.Parse(currency1[1]),
  307. };
  308. currencyInfos.Add(rateInfo);
  309. }
  310. }
  311. return currencyInfos;
  312. }
  313. /// <summary>
  314. /// 团组模块 - 汇率相关存储解析 To String
  315. /// </summary>
  316. /// <param name="rates"></param>
  317. /// <returns></returns>
  318. public static string GetCurrencyChinaToString(List<CurrencyInfo> rates)
  319. {
  320. string rateStr = string.Empty;
  321. if (rates.Count <= 0) return rateStr;
  322. foreach (CurrencyInfo rate in rates)
  323. {
  324. //存储方式: 美元(USD):6.2350|.......|墨西哥比索(MXN):1.0000
  325. rateStr += string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  326. }
  327. if (rateStr.Length > 0)
  328. {
  329. rateStr = rateStr.Substring(0, rateStr.Length - 1);
  330. }
  331. return rateStr;
  332. }
  333. #endregion
  334. #region 验证身份证号码
  335. /// <summary>
  336. /// 正则表达式
  337. /// 验证身份证号码
  338. /// </summary>
  339. /// <param name="idNumber"></param>
  340. /// <returns></returns>
  341. public static bool ValidateIdNumber(this string idNumber)
  342. {
  343. string pattern = @"^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}(\d|X)$";
  344. Regex regex = new Regex(pattern);
  345. return regex.IsMatch(idNumber);
  346. }
  347. #endregion
  348. #region string格式日期格式化
  349. /// <summary>
  350. /// string格式日期格式化
  351. /// </summary>
  352. /// <param name="dateStr"></param>
  353. /// <param name="format">
  354. /// 格式化标准
  355. /// yyyy-MM-dd yyyy/MM/dd
  356. /// </param>
  357. /// <returns></returns>
  358. public static string DateFormat(this string dateStr, string format)
  359. {
  360. if (!string.IsNullOrEmpty(dateStr))
  361. {
  362. if (!string.IsNullOrEmpty(format))
  363. {
  364. DateTime result;
  365. if (DateTime.TryParse(dateStr, out result))
  366. {
  367. return result.ToString(format);
  368. }
  369. }
  370. }
  371. return "";
  372. }
  373. #endregion
  374. /// <summary>
  375. /// List to DataTable
  376. /// 集合转换成datatable
  377. /// </summary>
  378. /// <typeparam name="T"></typeparam>
  379. /// <param name="aIList"></param>
  380. /// <returns></returns>
  381. public static DataTable GetDataTableFromIList<T>(List<T> aIList)
  382. {
  383. DataTable _returnTable = new DataTable();
  384. if (aIList != null && aIList.Count > 0)
  385. {
  386. object _baseObj = aIList[0];
  387. Type objectType = _baseObj.GetType();
  388. PropertyInfo[] properties = objectType.GetProperties();
  389. DataColumn _col;
  390. foreach (PropertyInfo property in properties)
  391. {
  392. _col = new DataColumn();
  393. _col.ColumnName = (string)property.Name;
  394. _col.DataType = property.PropertyType;
  395. _returnTable.Columns.Add(_col);
  396. }
  397. //Adds the rows to the table
  398. DataRow _row;
  399. foreach (object objItem in aIList)
  400. {
  401. _row = _returnTable.NewRow();
  402. foreach (PropertyInfo property in properties)
  403. {
  404. _row[property.Name] = property.GetValue(objItem, null);
  405. }
  406. _returnTable.Rows.Add(_row);
  407. }
  408. }
  409. return _returnTable;
  410. }
  411. }