CommonFun.cs 20 KB

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