CommonFun.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. using NPOI.SS.Formula.Functions;
  2. using OASystem.Domain.ViewModels.Financial;
  3. using OASystem.Domain.ViewModels.Groups;
  4. using System.Collections;
  5. using System.Globalization;
  6. using System.Reflection;
  7. using System.Reflection.Metadata;
  8. using System.Security.Cryptography;
  9. namespace OASystem.Infrastructure.Tools;
  10. /// <summary>
  11. /// 工具类
  12. /// </summary>
  13. public static class CommonFun
  14. {
  15. public static string GUID => Guid.NewGuid().ToString("N");
  16. public static bool IsNull(this string s)
  17. {
  18. return string.IsNullOrWhiteSpace(s);
  19. }
  20. public static bool NotNull(this string s)
  21. {
  22. return !string.IsNullOrWhiteSpace(s);
  23. }
  24. public static int GetRandom(int minNum, int maxNum)
  25. {
  26. var seed = BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0);
  27. return new Random(seed).Next(minNum, maxNum);
  28. }
  29. public static string GetSerialNumber(string prefix = "")
  30. {
  31. return prefix + DateTime.Now.ToString("yyyyMMddHHmmssfff") + GetRandom(1000, 9999).ToString();
  32. }
  33. public static string ToJson(this object obj)
  34. {
  35. return JsonSerializer.Serialize(obj);
  36. }
  37. public static T ToObject<T>(this string json)
  38. {
  39. return JsonSerializer.Deserialize<T>(json);
  40. }
  41. public static object GetDefaultVal(string typename)
  42. {
  43. return typename switch
  44. {
  45. "Boolean" => false,
  46. "DateTime" => default(DateTime),
  47. "Date" => default(DateTime),
  48. "Double" => 0.0,
  49. "Single" => 0f,
  50. "Int32" => 0,
  51. "String" => string.Empty,
  52. "Decimal" => 0m,
  53. _ => null,
  54. };
  55. }
  56. public static void CoverNull<T>(T model) where T : class
  57. {
  58. if (model == null)
  59. {
  60. return;
  61. }
  62. var typeFromHandle = typeof(T);
  63. var properties = typeFromHandle.GetProperties();
  64. var array = properties;
  65. for (var i = 0; i < array.Length; i++)
  66. {
  67. var propertyInfo = array[i];
  68. if (propertyInfo.GetValue(model, null) == null)
  69. {
  70. propertyInfo.SetValue(model, GetDefaultVal(propertyInfo.PropertyType.Name), null);
  71. }
  72. }
  73. }
  74. public static void CoverNull<T>(List<T> models) where T : class
  75. {
  76. if (models.Count == 0)
  77. {
  78. return;
  79. }
  80. foreach (var model in models)
  81. {
  82. CoverNull(model);
  83. }
  84. }
  85. public static bool ToBool(this object thisValue, bool errorvalue = false)
  86. {
  87. if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out bool reval))
  88. {
  89. return reval;
  90. }
  91. return errorvalue;
  92. }
  93. #region 文件操作
  94. public static FileInfo[] GetFiles(string directoryPath)
  95. {
  96. if (!IsExistDirectory(directoryPath))
  97. {
  98. throw new DirectoryNotFoundException();
  99. }
  100. var root = new DirectoryInfo(directoryPath);
  101. return root.GetFiles();
  102. }
  103. public static bool IsExistDirectory(string directoryPath)
  104. {
  105. return Directory.Exists(directoryPath);
  106. }
  107. public static string ReadFile(string Path)
  108. {
  109. string s;
  110. if (!File.Exists(Path))
  111. s = "不存在相应的目录";
  112. else
  113. {
  114. var f2 = new StreamReader(Path, Encoding.Default);
  115. s = f2.ReadToEnd();
  116. f2.Close();
  117. f2.Dispose();
  118. }
  119. return s;
  120. }
  121. public static void FileMove(string OrignFile, string NewFile)
  122. {
  123. File.Move(OrignFile, NewFile);
  124. }
  125. public static void CreateDir(string dir)
  126. {
  127. if (dir.Length == 0) return;
  128. if (!Directory.Exists(dir))
  129. Directory.CreateDirectory(dir);
  130. }
  131. /// <summary>
  132. /// 验证文件名称
  133. /// </summary>
  134. /// <param name="fileName"></param>
  135. /// <returns></returns>
  136. public static string ValidFileName(string fileName)
  137. {
  138. if (string.IsNullOrEmpty(fileName)) return Guid.NewGuid().ToString();
  139. // 获取非法文件名字符
  140. char[] invalidChars = Path.GetInvalidFileNameChars();
  141. return new string(fileName.Where(c => !invalidChars.Contains(c)).ToArray());
  142. }
  143. #endregion
  144. #region IP
  145. /// <summary>
  146. /// 是否为ip
  147. /// </summary>
  148. /// <param name="ip"></param>
  149. /// <returns></returns>
  150. public static bool IsIP(string ip)
  151. {
  152. 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?)$");
  153. }
  154. public static string GetIP(HttpRequest request)
  155. {
  156. if (request == null)
  157. {
  158. return "";
  159. }
  160. var ip = request.Headers["X-Real-IP"].FirstOrDefault();
  161. if (ip.IsNull())
  162. {
  163. ip = request.Headers["X-Forwarded-For"].FirstOrDefault();
  164. }
  165. if (ip.IsNull())
  166. {
  167. ip = request.HttpContext?.Connection?.RemoteIpAddress?.ToString();
  168. }
  169. if (ip.IsNull() || !IsIP(ip))
  170. {
  171. ip = "127.0.0.1";
  172. }
  173. return ip;
  174. }
  175. #endregion
  176. #region 随机数
  177. /// <summary>
  178. /// 根据自定义随机包含的字符获取指定长度的随机字符
  179. /// </summary>
  180. /// <param name="length">随机字符长度</param>
  181. /// <returns>随机字符</returns>
  182. public static string GetRandomStr(int length)
  183. {
  184. string a = "ABCDEFGHJKLMNPQRSTUVWXYZ012356789";
  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 GetRandomAllStr(int length)
  198. {
  199. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz012356789";
  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. /// </summary>
  210. /// <param name="length">随机字符长度</param>
  211. /// <returns>随机字符</returns>
  212. public static string GetRandomLetter(int length)
  213. {
  214. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz";
  215. StringBuilder sb = new StringBuilder();
  216. for (int i = 0; i < length; i++)
  217. {
  218. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  219. }
  220. return sb.ToString();
  221. }
  222. /// <summary>
  223. /// 生成不重复随机数字
  224. /// 操作者:037
  225. /// 2021-07-26 15:39
  226. /// </summary>
  227. /// <param name="CodeCount">输入字符串长度</param>
  228. /// <returns>字符串</returns>
  229. public static string GetRandomNumber(int len)
  230. {
  231. string allChar = "0,1,2,3,4,5,6,7,8,9";
  232. string[] allCharArray = allChar.Split(',');
  233. string RandomCode = "";
  234. int temp = -1;
  235. Random rand = new Random();
  236. for (int i = 0; i < len; i++)
  237. {
  238. if (temp != -1)
  239. {
  240. rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
  241. }
  242. int t = rand.Next(allCharArray.Length - 1);
  243. while (temp == t)
  244. {
  245. t = rand.Next(allCharArray.Length - 1);
  246. }
  247. temp = t;
  248. RandomCode += allCharArray[t];
  249. }
  250. return RandomCode;
  251. }
  252. #endregion
  253. #region decimal 截取
  254. /// <summary>
  255. ///
  256. /// </summary>
  257. /// <param name="d"></param>
  258. /// <param name="n"></param>
  259. /// <returns></returns>
  260. public static decimal CutDecimalWithN(decimal d, int n)
  261. {
  262. string strDecimal = d.ToString();
  263. int index = strDecimal.IndexOf(".");
  264. if (index == -1 || strDecimal.Length < index + n + 1)
  265. {
  266. strDecimal = string.Format("{0:F" + n + "}", d);
  267. }
  268. else
  269. {
  270. int length = index;
  271. if (n != 0)
  272. {
  273. length = index + n + 1;
  274. }
  275. strDecimal = strDecimal.Substring(0, length);
  276. }
  277. return Decimal.Parse(strDecimal);
  278. }
  279. public static decimal CutDecimalWithN(decimal? d, int n)
  280. {
  281. if (d == null)
  282. {
  283. return Decimal.MinValue;
  284. }
  285. return CutDecimalWithN(Convert.ToDecimal(d), n);
  286. }
  287. #endregion
  288. #region decimal 保留两位小数
  289. /// <summary>
  290. /// decimal 保留两位小数 不四舍五入
  291. /// </summary>
  292. /// <param name="number"></param>
  293. /// <returns></returns>
  294. public static decimal DecimalsKeepTwo(this decimal myDecimal)
  295. {
  296. var subDecimal = Math.Floor(myDecimal * 100) / 100;//保留两位小数,直接截取
  297. return subDecimal;
  298. }
  299. #endregion
  300. #region 团组模块 - 汇率相关存储解析
  301. /// <summary>
  302. /// 团组模块 - 汇率相关 To List
  303. /// </summary>
  304. /// <param name="rateStr"></param>
  305. /// <returns></returns>
  306. public static List<CurrencyInfo> GetCurrencyChinaToList(string? rateStr)
  307. {
  308. List<CurrencyInfo> currencyInfos = new List<CurrencyInfo>();
  309. if (string.IsNullOrEmpty(rateStr)) return currencyInfos;
  310. if (rateStr.Contains("|"))
  311. {
  312. string[] currencyArr = rateStr.Split("|");
  313. foreach (string currency in currencyArr)
  314. {
  315. string[] currency1 = currency.Split(":");
  316. string[] currency2 = currency1[0].Split("(");
  317. CurrencyInfo rateInfo = new CurrencyInfo()
  318. {
  319. CurrencyCode = currency2[1].Replace(")", "").TrimEnd(),
  320. CurrencyName = currency2[0],
  321. Rate = decimal.Parse(currency1[1]),
  322. };
  323. currencyInfos.Add(rateInfo);
  324. }
  325. }
  326. return currencyInfos;
  327. }
  328. /// <summary>
  329. /// 团组模块 - 汇率相关存储解析 To String
  330. /// </summary>
  331. /// <param name="rates"></param>
  332. /// <returns></returns>
  333. public static string GetCurrencyChinaToString(List<CurrencyInfo> rates)
  334. {
  335. string rateStr = string.Empty;
  336. if (rates.Count <= 0) return rateStr;
  337. if (rates.Count == 1 )
  338. {
  339. var rate = rates[0];
  340. return string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  341. }
  342. foreach (CurrencyInfo rate in rates)
  343. {
  344. //存储方式: 美元(USD):6.2350|.......|墨西哥比索(MXN):1.0000
  345. rateStr += string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  346. }
  347. if (rateStr.Length > 0)
  348. {
  349. rateStr = rateStr.Substring(0, rateStr.Length - 1);
  350. }
  351. return rateStr;
  352. }
  353. #endregion
  354. #region 验证身份证号码
  355. /// <summary>
  356. /// 正则表达式
  357. /// 验证身份证号码
  358. /// </summary>
  359. /// <param name="idNumber"></param>
  360. /// <returns></returns>
  361. public static bool IsValidChineseId(this string idNumber)
  362. {
  363. string pattern = @"^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$";
  364. Regex regex = new Regex(pattern);
  365. return regex.IsMatch(idNumber);
  366. }
  367. /// <summary>
  368. /// 通过身份证提取生日
  369. /// </summary>
  370. /// <param name="identityCard"></param>
  371. /// <returns></returns>
  372. public static DateTime? GetBirthDateFromIdentityCard(string identityCard)
  373. {
  374. // 身份证号码正则表达式验证,支持18位身份证号码
  375. if (!Regex.IsMatch(identityCard, @"^\d{17}(\d|X|x)$"))
  376. {
  377. return null;
  378. }
  379. // 获取出生日期(8位数字)
  380. string birthDateString = identityCard.Substring(6, 8);
  381. // 尝试将出生日期字符串转换为DateTime类型
  382. if (DateTime.TryParse(birthDateString, out DateTime birthDate))
  383. {
  384. return birthDate;
  385. }
  386. return null;
  387. }
  388. /// <summary>
  389. /// 通过身份证判断性别
  390. /// </summary>
  391. /// <param name="idNumber"></param>
  392. /// <returns>0 男1 女 -1 未设置</returns>
  393. /// <exception cref="ArgumentException"></exception>
  394. public static int GetGenderFromIdentityCard(string idNumber)
  395. {
  396. if (string.IsNullOrEmpty(idNumber) || idNumber.Length != 18)
  397. return -1;
  398. char genderChar = idNumber[16];
  399. return int.Parse(genderChar.ToString()) % 2 == 0 ? 1 :0;
  400. }
  401. #endregion
  402. #region string格式日期格式化
  403. /// <summary>
  404. /// string格式日期格式化
  405. /// </summary>
  406. /// <param name="dateStr"></param>
  407. /// <param name="format">
  408. /// 格式化标准
  409. /// yyyy-MM-dd yyyy/MM/dd
  410. /// </param>
  411. /// <returns></returns>
  412. public static string DateFormat(this string dateStr, string format)
  413. {
  414. if (!string.IsNullOrEmpty(dateStr))
  415. {
  416. if (!string.IsNullOrEmpty(format))
  417. {
  418. DateTime result;
  419. if (DateTime.TryParse(dateStr, out result))
  420. {
  421. return result.ToString(format);
  422. }
  423. }
  424. }
  425. return "";
  426. }
  427. #endregion
  428. /// <summary>
  429. /// List to DataTable
  430. /// 集合转换成datatable
  431. /// </summary>
  432. /// <typeparam name="T"></typeparam>
  433. /// <param name="aIList"></param>
  434. /// <returns></returns>
  435. public static DataTable GetDataTableFromIList<T>(List<T> aIList)
  436. {
  437. DataTable _returnTable = new DataTable();
  438. if (aIList != null && aIList.Count > 0)
  439. {
  440. object _baseObj = aIList[0];
  441. Type objectType = _baseObj.GetType();
  442. PropertyInfo[] properties = objectType.GetProperties();
  443. DataColumn _col;
  444. foreach (PropertyInfo property in properties)
  445. {
  446. _col = new DataColumn();
  447. _col.ColumnName = (string)property.Name;
  448. _col.DataType = property.PropertyType;
  449. _returnTable.Columns.Add(_col);
  450. }
  451. //Adds the rows to the table
  452. DataRow _row;
  453. foreach (object objItem in aIList)
  454. {
  455. _row = _returnTable.NewRow();
  456. foreach (PropertyInfo property in properties)
  457. {
  458. _row[property.Name] = property.GetValue(objItem, null);
  459. }
  460. _returnTable.Rows.Add(_row);
  461. }
  462. }
  463. return _returnTable;
  464. }
  465. /// <summary>
  466. /// List to DataTable
  467. /// 集合转换成datatable
  468. /// </summary>
  469. public static DataTable ToDataTableArray(IList list)
  470. {
  471. DataTable result = new DataTable();
  472. if (list.Count > 0)
  473. {
  474. PropertyInfo[] propertys = list[0].GetType().GetProperties();
  475. foreach (PropertyInfo pi in propertys)
  476. {
  477. try
  478. {
  479. result.Columns.Add(pi.Name, pi.PropertyType);
  480. }
  481. catch (Exception ex)
  482. {
  483. Console.WriteLine($"{pi.Name}:{ex.Message}");
  484. }
  485. }
  486. for (int i = 0; i < list.Count; i++)
  487. {
  488. ArrayList tempList = new ArrayList();
  489. foreach (PropertyInfo pi in propertys)
  490. {
  491. object obj = pi.GetValue(list[i], null);
  492. tempList.Add(obj);
  493. }
  494. object[] array = tempList.ToArray();
  495. result.LoadDataRow(array, true);
  496. }
  497. }
  498. return result;
  499. }
  500. /// <summary>
  501. ///获取指定月份起止日期
  502. /// </summary>
  503. /// <param name="year"></param>
  504. /// <param name="month"></param>
  505. /// <returns></returns>
  506. public static (DateTime StartDate, DateTime EndDate) GetMonthStartAndEndDates(int year, int month)
  507. {
  508. var calendar = new GregorianCalendar();
  509. var daysInMonth = calendar.GetDaysInMonth(year, month);
  510. var startDate = new DateTime(year, month, 1);
  511. var endDate = new DateTime(year, month, daysInMonth);
  512. return (startDate, endDate);
  513. }
  514. }