CommonFun.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. using Newtonsoft.Json.Linq;
  2. using Newtonsoft.Json;
  3. using NPOI.SS.Formula.Functions;
  4. using OASystem.Domain.ViewModels.Financial;
  5. using OASystem.Domain.ViewModels.Groups;
  6. using System.Collections;
  7. using System.Globalization;
  8. using System.Reflection;
  9. using System.Reflection.Metadata;
  10. using System.Security.Cryptography;
  11. using Pinyin4net.Format;
  12. using Pinyin4net;
  13. namespace OASystem.Infrastructure.Tools;
  14. /// <summary>
  15. /// 工具类
  16. /// </summary>
  17. public static class CommonFun
  18. {
  19. public static string GUID => Guid.NewGuid().ToString("N");
  20. public static bool IsNull(this string s)
  21. {
  22. return string.IsNullOrWhiteSpace(s);
  23. }
  24. public static bool NotNull(this string s)
  25. {
  26. return !string.IsNullOrWhiteSpace(s);
  27. }
  28. public static int GetRandom(int minNum, int maxNum)
  29. {
  30. var seed = BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0);
  31. return new Random(seed).Next(minNum, maxNum);
  32. }
  33. public static string GetSerialNumber(string prefix = "")
  34. {
  35. return prefix + DateTime.Now.ToString("yyyyMMddHHmmssfff") + GetRandom(1000, 9999).ToString();
  36. }
  37. public static string ToJson(this object obj)
  38. {
  39. return System.Text.Json.JsonSerializer.Serialize(obj);
  40. }
  41. public static T ToObject<T>(this string json)
  42. {
  43. return System.Text.Json.JsonSerializer.Deserialize<T>(json);
  44. }
  45. public static object GetDefaultVal(string typename)
  46. {
  47. return typename switch
  48. {
  49. "Boolean" => false,
  50. "DateTime" => default(DateTime),
  51. "Date" => default(DateTime),
  52. "Double" => 0.0,
  53. "Single" => 0f,
  54. "Int32" => 0,
  55. "String" => string.Empty,
  56. "Decimal" => 0m,
  57. _ => null,
  58. };
  59. }
  60. public static void CoverNull<T>(T model) where T : class
  61. {
  62. if (model == null)
  63. {
  64. return;
  65. }
  66. var typeFromHandle = typeof(T);
  67. var properties = typeFromHandle.GetProperties();
  68. var array = properties;
  69. for (var i = 0; i < array.Length; i++)
  70. {
  71. var propertyInfo = array[i];
  72. if (propertyInfo.GetValue(model, null) == null)
  73. {
  74. propertyInfo.SetValue(model, GetDefaultVal(propertyInfo.PropertyType.Name), null);
  75. }
  76. }
  77. }
  78. public static void CoverNull<T>(List<T> models) where T : class
  79. {
  80. if (models.Count == 0)
  81. {
  82. return;
  83. }
  84. foreach (var model in models)
  85. {
  86. CoverNull(model);
  87. }
  88. }
  89. public static bool ToBool(this object thisValue, bool errorvalue = false)
  90. {
  91. if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out bool reval))
  92. {
  93. return reval;
  94. }
  95. return errorvalue;
  96. }
  97. #region 文件操作
  98. public static FileInfo[] GetFiles(string directoryPath)
  99. {
  100. if (!IsExistDirectory(directoryPath))
  101. {
  102. throw new DirectoryNotFoundException();
  103. }
  104. var root = new DirectoryInfo(directoryPath);
  105. return root.GetFiles();
  106. }
  107. public static bool IsExistDirectory(string directoryPath)
  108. {
  109. return Directory.Exists(directoryPath);
  110. }
  111. public static string ReadFile(string Path)
  112. {
  113. string s;
  114. if (!File.Exists(Path))
  115. s = "不存在相应的目录";
  116. else
  117. {
  118. var f2 = new StreamReader(Path, Encoding.Default);
  119. s = f2.ReadToEnd();
  120. f2.Close();
  121. f2.Dispose();
  122. }
  123. return s;
  124. }
  125. public static void FileMove(string OrignFile, string NewFile)
  126. {
  127. File.Move(OrignFile, NewFile);
  128. }
  129. public static void CreateDir(string dir)
  130. {
  131. if (dir.Length == 0) return;
  132. if (!Directory.Exists(dir))
  133. Directory.CreateDirectory(dir);
  134. }
  135. /// <summary>
  136. /// 验证文件名称
  137. /// </summary>
  138. /// <param name="fileName"></param>
  139. /// <returns></returns>
  140. public static string ValidFileName(string fileName)
  141. {
  142. if (string.IsNullOrEmpty(fileName)) return Guid.NewGuid().ToString();
  143. // 获取非法文件名字符
  144. char[] invalidChars = Path.GetInvalidFileNameChars();
  145. return new string(fileName.Where(c => !invalidChars.Contains(c)).ToArray());
  146. }
  147. #endregion
  148. #region IP
  149. /// <summary>
  150. /// 是否为ip
  151. /// </summary>
  152. /// <param name="ip"></param>
  153. /// <returns></returns>
  154. public static bool IsIP(string ip)
  155. {
  156. 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?)$");
  157. }
  158. public static string GetIP(HttpRequest request)
  159. {
  160. if (request == null) return "";
  161. var ip = request.Headers["X-Real-IP"].FirstOrDefault();
  162. if (ip.IsNull())
  163. {
  164. ip = request.Headers["X-Forwarded-For"].FirstOrDefault();
  165. }
  166. if (ip.IsNull())
  167. {
  168. ip = request.HttpContext?.Connection?.RemoteIpAddress?.ToString();
  169. }
  170. if (ip.IsNull() || !IsIP(ip))
  171. {
  172. ip = "127.0.0.1";
  173. }
  174. return ip;
  175. }
  176. #endregion
  177. #region 随机数
  178. /// <summary>
  179. /// 根据自定义随机包含的字符获取指定长度的随机字符
  180. /// </summary>
  181. /// <param name="length">随机字符长度</param>
  182. /// <returns>随机字符</returns>
  183. public static string GetRandomStr(int length)
  184. {
  185. string a = "ABCDEFGHJKLMNPQRSTUVWXYZ012356789";
  186. StringBuilder sb = new StringBuilder();
  187. for (int i = 0; i < length; i++)
  188. {
  189. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  190. }
  191. return sb.ToString();
  192. }
  193. /// <summary>
  194. /// 根据自定义随机包含的字符获取指定长度的随机字符
  195. /// </summary>
  196. /// <param name="length">随机字符长度</param>
  197. /// <returns>随机字符</returns>
  198. public static string GetRandomAllStr(int length)
  199. {
  200. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz012356789";
  201. StringBuilder sb = new StringBuilder();
  202. for (int i = 0; i < length; i++)
  203. {
  204. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  205. }
  206. return sb.ToString();
  207. }
  208. /// <summary>
  209. /// 根据自定义随机包含的字符获取指定长度的随机字母(含大小写)
  210. /// </summary>
  211. /// <param name="length">随机字符长度</param>
  212. /// <returns>随机字符</returns>
  213. public static string GetRandomLetter(int length)
  214. {
  215. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz";
  216. StringBuilder sb = new StringBuilder();
  217. for (int i = 0; i < length; i++)
  218. {
  219. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  220. }
  221. return sb.ToString();
  222. }
  223. /// <summary>
  224. /// 生成不重复随机数字
  225. /// 操作者:037
  226. /// 2021-07-26 15:39
  227. /// </summary>
  228. /// <param name="CodeCount">输入字符串长度</param>
  229. /// <returns>字符串</returns>
  230. public static string GetRandomNumber(int len)
  231. {
  232. string allChar = "0,1,2,3,4,5,6,7,8,9";
  233. string[] allCharArray = allChar.Split(',');
  234. string RandomCode = "";
  235. int temp = -1;
  236. Random rand = new Random();
  237. for (int i = 0; i < len; i++)
  238. {
  239. if (temp != -1)
  240. {
  241. rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
  242. }
  243. int t = rand.Next(allCharArray.Length - 1);
  244. while (temp == t)
  245. {
  246. t = rand.Next(allCharArray.Length - 1);
  247. }
  248. temp = t;
  249. RandomCode += allCharArray[t];
  250. }
  251. return RandomCode;
  252. }
  253. #endregion
  254. #region decimal 截取
  255. /// <summary>
  256. ///
  257. /// </summary>
  258. /// <param name="d"></param>
  259. /// <param name="n"></param>
  260. /// <returns></returns>
  261. public static decimal CutDecimalWithN(decimal d, int n)
  262. {
  263. string strDecimal = d.ToString();
  264. int index = strDecimal.IndexOf(".");
  265. if (index == -1 || strDecimal.Length < index + n + 1)
  266. {
  267. strDecimal = string.Format("{0:F" + n + "}", d);
  268. }
  269. else
  270. {
  271. int length = index;
  272. if (n != 0)
  273. {
  274. length = index + n + 1;
  275. }
  276. strDecimal = strDecimal.Substring(0, length);
  277. }
  278. return Decimal.Parse(strDecimal);
  279. }
  280. public static decimal CutDecimalWithN(decimal? d, int n)
  281. {
  282. if (d == null)
  283. {
  284. return Decimal.MinValue;
  285. }
  286. return CutDecimalWithN(Convert.ToDecimal(d), n);
  287. }
  288. #endregion
  289. #region decimal 保留两位小数
  290. /// <summary>
  291. /// decimal 保留两位小数 不四舍五入
  292. /// </summary>
  293. /// <param name="number"></param>
  294. /// <returns></returns>
  295. public static decimal DecimalsKeepTwo(this decimal myDecimal)
  296. {
  297. var subDecimal = Math.Floor(myDecimal * 100) / 100;//保留两位小数,直接截取
  298. return subDecimal;
  299. }
  300. #endregion
  301. #region 团组模块 - 汇率相关存储解析
  302. /// <summary>
  303. /// 团组模块 - 汇率相关 To List
  304. /// </summary>
  305. /// <param name="rateStr"></param>
  306. /// <returns></returns>
  307. public static List<CurrencyInfo> GetCurrencyChinaToList(string? rateStr)
  308. {
  309. List<CurrencyInfo> currencyInfos = new List<CurrencyInfo>();
  310. if (string.IsNullOrEmpty(rateStr)) return currencyInfos;
  311. if (rateStr.Contains("|"))
  312. {
  313. string[] currencyArr = rateStr.Split("|");
  314. foreach (string currency in currencyArr)
  315. {
  316. string[] currency1 = currency.Split(":");
  317. string[] currency2 = currency1[0].Split("(");
  318. CurrencyInfo rateInfo = new CurrencyInfo()
  319. {
  320. CurrencyCode = currency2[1].Replace(")", "").TrimEnd(),
  321. CurrencyName = currency2[0],
  322. Rate = decimal.Parse(currency1[1]),
  323. };
  324. currencyInfos.Add(rateInfo);
  325. }
  326. }
  327. return currencyInfos;
  328. }
  329. /// <summary>
  330. /// 团组模块 - 汇率相关存储解析 To String
  331. /// </summary>
  332. /// <param name="rates"></param>
  333. /// <returns></returns>
  334. public static string GetCurrencyChinaToString(List<CurrencyInfo>? rates)
  335. {
  336. string rateStr = string.Empty;
  337. if (rates == null) return rateStr;
  338. if (rates.Count <= 0) return rateStr;
  339. if (rates.Count == 1 )
  340. {
  341. var rate = rates[0];
  342. return string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  343. }
  344. foreach (CurrencyInfo rate in rates)
  345. {
  346. //存储方式: 美元(USD):6.2350|.......|墨西哥比索(MXN):1.0000
  347. rateStr += string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  348. }
  349. if (rateStr.Length > 0)
  350. {
  351. rateStr = rateStr.Substring(0, rateStr.Length - 1);
  352. }
  353. return rateStr;
  354. }
  355. #endregion
  356. #region 验证身份证号码
  357. /// <summary>
  358. /// 正则表达式
  359. /// 验证身份证号码
  360. /// </summary>
  361. /// <param name="idNumber"></param>
  362. /// <returns></returns>
  363. public static bool IsValidChineseId(this string idNumber)
  364. {
  365. 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])$";
  366. Regex regex = new Regex(pattern);
  367. return regex.IsMatch(idNumber);
  368. }
  369. /// <summary>
  370. /// 通过身份证提取生日
  371. /// </summary>
  372. /// <param name="identityCard"></param>
  373. /// <returns></returns>
  374. public static DateTime? GetBirthDateFromIdentityCard(string identityCard)
  375. {
  376. // 身份证号码正则表达式验证,支持18位身份证号码
  377. if (!Regex.IsMatch(identityCard, @"^\d{17}(\d|X|x)$"))
  378. {
  379. return null;
  380. }
  381. // 获取出生日期(8位数字)
  382. string birthDateString = identityCard.Substring(6, 8);
  383. // 尝试将出生日期字符串转换为DateTime类型
  384. if (DateTime.TryParse(birthDateString, out DateTime birthDate))
  385. {
  386. return birthDate;
  387. }
  388. return null;
  389. }
  390. /// <summary>
  391. /// 通过身份证判断性别
  392. /// </summary>
  393. /// <param name="idNumber"></param>
  394. /// <returns>0 男1 女 -1 未设置</returns>
  395. /// <exception cref="ArgumentException"></exception>
  396. public static int GetGenderFromIdentityCard(string idNumber)
  397. {
  398. if (string.IsNullOrEmpty(idNumber) || idNumber.Length != 18)
  399. return -1;
  400. char genderChar = idNumber[16];
  401. return int.Parse(genderChar.ToString()) % 2 == 0 ? 1 :0;
  402. }
  403. #endregion
  404. #region string格式日期格式化
  405. /// <summary>
  406. /// string格式日期格式化
  407. /// </summary>
  408. /// <param name="dateStr"></param>
  409. /// <param name="format">
  410. /// 格式化标准
  411. /// yyyy-MM-dd yyyy/MM/dd
  412. /// </param>
  413. /// <returns></returns>
  414. public static string DateFormat(this string dateStr, string format)
  415. {
  416. if (!string.IsNullOrEmpty(dateStr))
  417. {
  418. if (!string.IsNullOrEmpty(format))
  419. {
  420. DateTime result;
  421. if (DateTime.TryParse(dateStr, out result))
  422. {
  423. return result.ToString(format);
  424. }
  425. }
  426. }
  427. return "";
  428. }
  429. #endregion
  430. /// <summary>
  431. /// List to DataTable
  432. /// 集合转换成datatable
  433. /// </summary>
  434. /// <typeparam name="T"></typeparam>
  435. /// <param name="aIList"></param>
  436. /// <returns></returns>
  437. public static DataTable GetDataTableFromIList<T>(List<T> aIList)
  438. {
  439. DataTable _returnTable = new DataTable();
  440. if (aIList != null && aIList.Count > 0)
  441. {
  442. object _baseObj = aIList[0];
  443. Type objectType = _baseObj.GetType();
  444. PropertyInfo[] properties = objectType.GetProperties();
  445. DataColumn _col;
  446. foreach (PropertyInfo property in properties)
  447. {
  448. _col = new DataColumn();
  449. _col.ColumnName = (string)property.Name;
  450. _col.DataType = property.PropertyType;
  451. _returnTable.Columns.Add(_col);
  452. }
  453. //Adds the rows to the table
  454. DataRow _row;
  455. foreach (object objItem in aIList)
  456. {
  457. _row = _returnTable.NewRow();
  458. foreach (PropertyInfo property in properties)
  459. {
  460. _row[property.Name] = property.GetValue(objItem, null);
  461. }
  462. _returnTable.Rows.Add(_row);
  463. }
  464. }
  465. return _returnTable;
  466. }
  467. /// <summary>
  468. /// List to DataTable
  469. /// 集合转换成datatable
  470. /// </summary>
  471. public static DataTable ToDataTableArray(IList list)
  472. {
  473. DataTable result = new DataTable();
  474. if (list.Count > 0)
  475. {
  476. PropertyInfo[] propertys = list[0].GetType().GetProperties();
  477. foreach (PropertyInfo pi in propertys)
  478. {
  479. try
  480. {
  481. result.Columns.Add(pi.Name, pi.PropertyType);
  482. }
  483. catch (Exception ex)
  484. {
  485. Console.WriteLine($"{pi.Name}:{ex.Message}");
  486. }
  487. }
  488. for (int i = 0; i < list.Count; i++)
  489. {
  490. ArrayList tempList = new ArrayList();
  491. foreach (PropertyInfo pi in propertys)
  492. {
  493. object obj = pi.GetValue(list[i], null);
  494. tempList.Add(obj);
  495. }
  496. object[] array = tempList.ToArray();
  497. result.LoadDataRow(array, true);
  498. }
  499. }
  500. return result;
  501. }
  502. /// <summary>
  503. ///获取指定月份起止日期
  504. /// </summary>
  505. /// <param name="year"></param>
  506. /// <param name="month"></param>
  507. /// <returns></returns>
  508. public static (DateTime StartDate, DateTime EndDate) GetMonthStartAndEndDates(int year, int month)
  509. {
  510. var calendar = new GregorianCalendar();
  511. var daysInMonth = calendar.GetDaysInMonth(year, month);
  512. var startDate = new DateTime(year, month, 1);
  513. var endDate = new DateTime(year, month, daysInMonth);
  514. return (startDate, endDate);
  515. }
  516. /// <summary>
  517. /// 验证json字符串是否合法
  518. /// </summary>
  519. /// <param name="jsonString"></param>
  520. /// <returns></returns>
  521. public static bool IsValidJson(string jsonString)
  522. {
  523. try
  524. {
  525. JToken.Parse(jsonString);
  526. return true;
  527. }
  528. catch (JsonReaderException)
  529. {
  530. return false;
  531. }
  532. }
  533. /// <summary>
  534. /// 常见的双字姓氏列表
  535. /// </summary>
  536. private static readonly HashSet<string> commonDoubleSurnames = new HashSet<string>
  537. {
  538. "欧阳", "司马", "上官", "夏侯", "诸葛", "东方", "赫连", "皇甫", "尉迟", "公羊",
  539. "澹台", "公冶", "宗政", "濮阳", "淳于", "单于", "太叔", "申屠", "公孙", "仲孙",
  540. "轩辕", "令狐", "钟离", "宇文", "长孙", "慕容", "鲜于", "闾丘", "司徒", "司空",
  541. "亓官", "司寇", "仉督", "子车", "颛孙", "端木", "巫马", "公西", "漆雕", "乐正",
  542. "壤驷", "公良", "拓跋", "夹谷", "宰父", "谷梁", "晋楚", "闫法", "汝鄢", "涂钦",
  543. "段干", "百里", "东郭", "南门", "呼延", "归海", "羊舌", "微生", "岳帅", "缑亢",
  544. "况后", "有琴", "梁丘", "左丘", "东门", "西门", "商牟", "佘佴", "伯赏", "南宫"
  545. };
  546. /// <summary>
  547. /// 中文名字取姓氏和名字
  548. /// </summary>
  549. /// <param name="fullName"></param>
  550. /// <returns>姓:lastName 名:firstName</returns>
  551. public static (string lastName, string firstName) GetLastNameAndFirstName(string fullName)
  552. {
  553. if (string.IsNullOrEmpty(fullName) || fullName.Length < 2) return ("", "");
  554. // 尝试匹配双字姓氏
  555. if (fullName.Length > 2)
  556. {
  557. string potentialDoubleSurname = fullName.Substring(0, 2);
  558. if (commonDoubleSurnames.Contains(potentialDoubleSurname))
  559. {
  560. string lastName = potentialDoubleSurname;
  561. string firstName = fullName.Substring(2);
  562. return (lastName, firstName);
  563. }
  564. }
  565. // 默认单字姓氏
  566. string singleSurname = fullName.Substring(0, 1);
  567. string remainingName = fullName.Substring(1);
  568. return (singleSurname, remainingName);
  569. }
  570. /// <summary>
  571. /// 中文名字转拼音
  572. /// </summary>
  573. /// <param name="chineseName"></param>
  574. /// <returns></returns>
  575. /// <exception cref="ArgumentException"></exception>
  576. public static string ConvertToPinyin(string chineseName)
  577. {
  578. if (string.IsNullOrEmpty(chineseName)) return "";
  579. HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat
  580. {
  581. ToneType = HanyuPinyinToneType.WITHOUT_TONE,
  582. VCharType = HanyuPinyinVCharType.WITH_V,
  583. CaseType = HanyuPinyinCaseType.UPPERCASE
  584. };
  585. string pinyin = string.Empty;
  586. foreach (char ch in chineseName)
  587. {
  588. if (PinyinHelper.ToHanyuPinyinStringArray(ch) != null)
  589. {
  590. pinyin += PinyinHelper.ToHanyuPinyinStringArray(ch, format)[0];
  591. }
  592. else
  593. {
  594. pinyin += ch;
  595. }
  596. }
  597. return pinyin;
  598. }
  599. }