CommonFun.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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)
  161. {
  162. return "";
  163. }
  164. var ip = request.Headers["X-Real-IP"].FirstOrDefault();
  165. if (ip.IsNull())
  166. {
  167. ip = request.Headers["X-Forwarded-For"].FirstOrDefault();
  168. }
  169. if (ip.IsNull())
  170. {
  171. ip = request.HttpContext?.Connection?.RemoteIpAddress?.ToString();
  172. }
  173. if (ip.IsNull() || !IsIP(ip))
  174. {
  175. ip = "127.0.0.1";
  176. }
  177. return ip;
  178. }
  179. #endregion
  180. #region 随机数
  181. /// <summary>
  182. /// 根据自定义随机包含的字符获取指定长度的随机字符
  183. /// </summary>
  184. /// <param name="length">随机字符长度</param>
  185. /// <returns>随机字符</returns>
  186. public static string GetRandomStr(int length)
  187. {
  188. string a = "ABCDEFGHJKLMNPQRSTUVWXYZ012356789";
  189. StringBuilder sb = new StringBuilder();
  190. for (int i = 0; i < length; i++)
  191. {
  192. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  193. }
  194. return sb.ToString();
  195. }
  196. /// <summary>
  197. /// 根据自定义随机包含的字符获取指定长度的随机字符
  198. /// </summary>
  199. /// <param name="length">随机字符长度</param>
  200. /// <returns>随机字符</returns>
  201. public static string GetRandomAllStr(int length)
  202. {
  203. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz012356789";
  204. StringBuilder sb = new StringBuilder();
  205. for (int i = 0; i < length; i++)
  206. {
  207. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  208. }
  209. return sb.ToString();
  210. }
  211. /// <summary>
  212. /// 根据自定义随机包含的字符获取指定长度的随机字母(含大小写)
  213. /// </summary>
  214. /// <param name="length">随机字符长度</param>
  215. /// <returns>随机字符</returns>
  216. public static string GetRandomLetter(int length)
  217. {
  218. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz";
  219. StringBuilder sb = new StringBuilder();
  220. for (int i = 0; i < length; i++)
  221. {
  222. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  223. }
  224. return sb.ToString();
  225. }
  226. /// <summary>
  227. /// 生成不重复随机数字
  228. /// 操作者:037
  229. /// 2021-07-26 15:39
  230. /// </summary>
  231. /// <param name="CodeCount">输入字符串长度</param>
  232. /// <returns>字符串</returns>
  233. public static string GetRandomNumber(int len)
  234. {
  235. string allChar = "0,1,2,3,4,5,6,7,8,9";
  236. string[] allCharArray = allChar.Split(',');
  237. string RandomCode = "";
  238. int temp = -1;
  239. Random rand = new Random();
  240. for (int i = 0; i < len; i++)
  241. {
  242. if (temp != -1)
  243. {
  244. rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
  245. }
  246. int t = rand.Next(allCharArray.Length - 1);
  247. while (temp == t)
  248. {
  249. t = rand.Next(allCharArray.Length - 1);
  250. }
  251. temp = t;
  252. RandomCode += allCharArray[t];
  253. }
  254. return RandomCode;
  255. }
  256. #endregion
  257. #region decimal 截取
  258. /// <summary>
  259. ///
  260. /// </summary>
  261. /// <param name="d"></param>
  262. /// <param name="n"></param>
  263. /// <returns></returns>
  264. public static decimal CutDecimalWithN(decimal d, int n)
  265. {
  266. string strDecimal = d.ToString();
  267. int index = strDecimal.IndexOf(".");
  268. if (index == -1 || strDecimal.Length < index + n + 1)
  269. {
  270. strDecimal = string.Format("{0:F" + n + "}", d);
  271. }
  272. else
  273. {
  274. int length = index;
  275. if (n != 0)
  276. {
  277. length = index + n + 1;
  278. }
  279. strDecimal = strDecimal.Substring(0, length);
  280. }
  281. return Decimal.Parse(strDecimal);
  282. }
  283. public static decimal CutDecimalWithN(decimal? d, int n)
  284. {
  285. if (d == null)
  286. {
  287. return Decimal.MinValue;
  288. }
  289. return CutDecimalWithN(Convert.ToDecimal(d), n);
  290. }
  291. #endregion
  292. #region decimal 保留两位小数
  293. /// <summary>
  294. /// decimal 保留两位小数 不四舍五入
  295. /// </summary>
  296. /// <param name="number"></param>
  297. /// <returns></returns>
  298. public static decimal DecimalsKeepTwo(this decimal myDecimal)
  299. {
  300. var subDecimal = Math.Floor(myDecimal * 100) / 100;//保留两位小数,直接截取
  301. return subDecimal;
  302. }
  303. #endregion
  304. #region 团组模块 - 汇率相关存储解析
  305. /// <summary>
  306. /// 团组模块 - 汇率相关 To List
  307. /// </summary>
  308. /// <param name="rateStr"></param>
  309. /// <returns></returns>
  310. public static List<CurrencyInfo> GetCurrencyChinaToList(string? rateStr)
  311. {
  312. List<CurrencyInfo> currencyInfos = new List<CurrencyInfo>();
  313. if (string.IsNullOrEmpty(rateStr)) return currencyInfos;
  314. if (rateStr.Contains("|"))
  315. {
  316. string[] currencyArr = rateStr.Split("|");
  317. foreach (string currency in currencyArr)
  318. {
  319. string[] currency1 = currency.Split(":");
  320. string[] currency2 = currency1[0].Split("(");
  321. CurrencyInfo rateInfo = new CurrencyInfo()
  322. {
  323. CurrencyCode = currency2[1].Replace(")", "").TrimEnd(),
  324. CurrencyName = currency2[0],
  325. Rate = decimal.Parse(currency1[1]),
  326. };
  327. currencyInfos.Add(rateInfo);
  328. }
  329. }
  330. return currencyInfos;
  331. }
  332. /// <summary>
  333. /// 团组模块 - 汇率相关存储解析 To String
  334. /// </summary>
  335. /// <param name="rates"></param>
  336. /// <returns></returns>
  337. public static string GetCurrencyChinaToString(List<CurrencyInfo> rates)
  338. {
  339. string rateStr = string.Empty;
  340. if (rates.Count <= 0) return rateStr;
  341. if (rates.Count == 1 )
  342. {
  343. var rate = rates[0];
  344. return string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  345. }
  346. foreach (CurrencyInfo rate in rates)
  347. {
  348. //存储方式: 美元(USD):6.2350|.......|墨西哥比索(MXN):1.0000
  349. rateStr += string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  350. }
  351. if (rateStr.Length > 0)
  352. {
  353. rateStr = rateStr.Substring(0, rateStr.Length - 1);
  354. }
  355. return rateStr;
  356. }
  357. #endregion
  358. #region 验证身份证号码
  359. /// <summary>
  360. /// 正则表达式
  361. /// 验证身份证号码
  362. /// </summary>
  363. /// <param name="idNumber"></param>
  364. /// <returns></returns>
  365. public static bool IsValidChineseId(this string idNumber)
  366. {
  367. 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])$";
  368. Regex regex = new Regex(pattern);
  369. return regex.IsMatch(idNumber);
  370. }
  371. /// <summary>
  372. /// 通过身份证提取生日
  373. /// </summary>
  374. /// <param name="identityCard"></param>
  375. /// <returns></returns>
  376. public static DateTime? GetBirthDateFromIdentityCard(string identityCard)
  377. {
  378. // 身份证号码正则表达式验证,支持18位身份证号码
  379. if (!Regex.IsMatch(identityCard, @"^\d{17}(\d|X|x)$"))
  380. {
  381. return null;
  382. }
  383. // 获取出生日期(8位数字)
  384. string birthDateString = identityCard.Substring(6, 8);
  385. // 尝试将出生日期字符串转换为DateTime类型
  386. if (DateTime.TryParse(birthDateString, out DateTime birthDate))
  387. {
  388. return birthDate;
  389. }
  390. return null;
  391. }
  392. /// <summary>
  393. /// 通过身份证判断性别
  394. /// </summary>
  395. /// <param name="idNumber"></param>
  396. /// <returns>0 男1 女 -1 未设置</returns>
  397. /// <exception cref="ArgumentException"></exception>
  398. public static int GetGenderFromIdentityCard(string idNumber)
  399. {
  400. if (string.IsNullOrEmpty(idNumber) || idNumber.Length != 18)
  401. return -1;
  402. char genderChar = idNumber[16];
  403. return int.Parse(genderChar.ToString()) % 2 == 0 ? 1 :0;
  404. }
  405. #endregion
  406. #region string格式日期格式化
  407. /// <summary>
  408. /// string格式日期格式化
  409. /// </summary>
  410. /// <param name="dateStr"></param>
  411. /// <param name="format">
  412. /// 格式化标准
  413. /// yyyy-MM-dd yyyy/MM/dd
  414. /// </param>
  415. /// <returns></returns>
  416. public static string DateFormat(this string dateStr, string format)
  417. {
  418. if (!string.IsNullOrEmpty(dateStr))
  419. {
  420. if (!string.IsNullOrEmpty(format))
  421. {
  422. DateTime result;
  423. if (DateTime.TryParse(dateStr, out result))
  424. {
  425. return result.ToString(format);
  426. }
  427. }
  428. }
  429. return "";
  430. }
  431. #endregion
  432. /// <summary>
  433. /// List to DataTable
  434. /// 集合转换成datatable
  435. /// </summary>
  436. /// <typeparam name="T"></typeparam>
  437. /// <param name="aIList"></param>
  438. /// <returns></returns>
  439. public static DataTable GetDataTableFromIList<T>(List<T> aIList)
  440. {
  441. DataTable _returnTable = new DataTable();
  442. if (aIList != null && aIList.Count > 0)
  443. {
  444. object _baseObj = aIList[0];
  445. Type objectType = _baseObj.GetType();
  446. PropertyInfo[] properties = objectType.GetProperties();
  447. DataColumn _col;
  448. foreach (PropertyInfo property in properties)
  449. {
  450. _col = new DataColumn();
  451. _col.ColumnName = (string)property.Name;
  452. _col.DataType = property.PropertyType;
  453. _returnTable.Columns.Add(_col);
  454. }
  455. //Adds the rows to the table
  456. DataRow _row;
  457. foreach (object objItem in aIList)
  458. {
  459. _row = _returnTable.NewRow();
  460. foreach (PropertyInfo property in properties)
  461. {
  462. _row[property.Name] = property.GetValue(objItem, null);
  463. }
  464. _returnTable.Rows.Add(_row);
  465. }
  466. }
  467. return _returnTable;
  468. }
  469. /// <summary>
  470. /// List to DataTable
  471. /// 集合转换成datatable
  472. /// </summary>
  473. public static DataTable ToDataTableArray(IList list)
  474. {
  475. DataTable result = new DataTable();
  476. if (list.Count > 0)
  477. {
  478. PropertyInfo[] propertys = list[0].GetType().GetProperties();
  479. foreach (PropertyInfo pi in propertys)
  480. {
  481. try
  482. {
  483. result.Columns.Add(pi.Name, pi.PropertyType);
  484. }
  485. catch (Exception ex)
  486. {
  487. Console.WriteLine($"{pi.Name}:{ex.Message}");
  488. }
  489. }
  490. for (int i = 0; i < list.Count; i++)
  491. {
  492. ArrayList tempList = new ArrayList();
  493. foreach (PropertyInfo pi in propertys)
  494. {
  495. object obj = pi.GetValue(list[i], null);
  496. tempList.Add(obj);
  497. }
  498. object[] array = tempList.ToArray();
  499. result.LoadDataRow(array, true);
  500. }
  501. }
  502. return result;
  503. }
  504. /// <summary>
  505. ///获取指定月份起止日期
  506. /// </summary>
  507. /// <param name="year"></param>
  508. /// <param name="month"></param>
  509. /// <returns></returns>
  510. public static (DateTime StartDate, DateTime EndDate) GetMonthStartAndEndDates(int year, int month)
  511. {
  512. var calendar = new GregorianCalendar();
  513. var daysInMonth = calendar.GetDaysInMonth(year, month);
  514. var startDate = new DateTime(year, month, 1);
  515. var endDate = new DateTime(year, month, daysInMonth);
  516. return (startDate, endDate);
  517. }
  518. /// <summary>
  519. /// 验证json字符串是否合法
  520. /// </summary>
  521. /// <param name="jsonString"></param>
  522. /// <returns></returns>
  523. public static bool IsValidJson(string jsonString)
  524. {
  525. try
  526. {
  527. JToken.Parse(jsonString);
  528. return true;
  529. }
  530. catch (JsonReaderException)
  531. {
  532. return false;
  533. }
  534. }
  535. /// <summary>
  536. /// 常见的双字姓氏列表
  537. /// </summary>
  538. private static readonly HashSet<string> commonDoubleSurnames = new HashSet<string>
  539. {
  540. "欧阳", "司马", "上官", "夏侯", "诸葛", "东方", "赫连", "皇甫", "尉迟", "公羊",
  541. "澹台", "公冶", "宗政", "濮阳", "淳于", "单于", "太叔", "申屠", "公孙", "仲孙",
  542. "轩辕", "令狐", "钟离", "宇文", "长孙", "慕容", "鲜于", "闾丘", "司徒", "司空",
  543. "亓官", "司寇", "仉督", "子车", "颛孙", "端木", "巫马", "公西", "漆雕", "乐正",
  544. "壤驷", "公良", "拓跋", "夹谷", "宰父", "谷梁", "晋楚", "闫法", "汝鄢", "涂钦",
  545. "段干", "百里", "东郭", "南门", "呼延", "归海", "羊舌", "微生", "岳帅", "缑亢",
  546. "况后", "有琴", "梁丘", "左丘", "东门", "西门", "商牟", "佘佴", "伯赏", "南宫"
  547. };
  548. /// <summary>
  549. /// 中文名字取姓氏和名字
  550. /// </summary>
  551. /// <param name="fullName"></param>
  552. /// <returns>姓:lastName 名:firstName</returns>
  553. public static (string lastName, string firstName) GetLastNameAndFirstName(string fullName)
  554. {
  555. if (string.IsNullOrEmpty(fullName) || fullName.Length < 2) return ("", "");
  556. // 尝试匹配双字姓氏
  557. if (fullName.Length > 2)
  558. {
  559. string potentialDoubleSurname = fullName.Substring(0, 2);
  560. if (commonDoubleSurnames.Contains(potentialDoubleSurname))
  561. {
  562. string lastName = potentialDoubleSurname;
  563. string firstName = fullName.Substring(2);
  564. return (lastName, firstName);
  565. }
  566. }
  567. // 默认单字姓氏
  568. string singleSurname = fullName.Substring(0, 1);
  569. string remainingName = fullName.Substring(1);
  570. return (singleSurname, remainingName);
  571. }
  572. /// <summary>
  573. /// 中文名字转拼音
  574. /// </summary>
  575. /// <param name="chineseName"></param>
  576. /// <returns></returns>
  577. /// <exception cref="ArgumentException"></exception>
  578. public static string ConvertToPinyin(string chineseName)
  579. {
  580. if (string.IsNullOrEmpty(chineseName)) return "";
  581. HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat
  582. {
  583. ToneType = HanyuPinyinToneType.WITHOUT_TONE,
  584. VCharType = HanyuPinyinVCharType.WITH_V,
  585. CaseType = HanyuPinyinCaseType.UPPERCASE
  586. };
  587. string pinyin = string.Empty;
  588. foreach (char ch in chineseName)
  589. {
  590. if (PinyinHelper.ToHanyuPinyinStringArray(ch) != null)
  591. {
  592. pinyin += PinyinHelper.ToHanyuPinyinStringArray(ch, format)[0];
  593. }
  594. else
  595. {
  596. pinyin += ch;
  597. }
  598. }
  599. return pinyin;
  600. }
  601. }