CommonFun.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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. public static decimal CutDecimalWithN(decimal? d, int n)
  276. {
  277. if (d == null)
  278. {
  279. return Decimal.MinValue;
  280. }
  281. return CutDecimalWithN(Convert.ToDecimal(d), n);
  282. }
  283. #endregion
  284. #region decimal 保留两位小数
  285. /// <summary>
  286. /// decimal 保留两位小数 不四舍五入
  287. /// </summary>
  288. /// <param name="number"></param>
  289. /// <returns></returns>
  290. public static decimal DecimalsKeepTwo(this decimal myDecimal)
  291. {
  292. var subDecimal = Math.Floor(myDecimal * 100) / 100;//保留两位小数,直接截取
  293. return subDecimal;
  294. }
  295. #endregion
  296. #region 团组模块 - 汇率相关存储解析
  297. /// <summary>
  298. /// 团组模块 - 汇率相关 To List
  299. /// </summary>
  300. /// <param name="rateStr"></param>
  301. /// <returns></returns>
  302. public static List<CurrencyInfo> GetCurrencyChinaToList(string? rateStr)
  303. {
  304. List<CurrencyInfo> currencyInfos = new List<CurrencyInfo>();
  305. if (string.IsNullOrEmpty(rateStr)) return currencyInfos;
  306. if (rateStr.Contains("|"))
  307. {
  308. string[] currencyArr = rateStr.Split("|");
  309. foreach (string currency in currencyArr)
  310. {
  311. string[] currency1 = currency.Split(":");
  312. string[] currency2 = currency1[0].Split("(");
  313. CurrencyInfo rateInfo = new CurrencyInfo()
  314. {
  315. CurrencyCode = currency2[1].Replace(")", "").TrimEnd(),
  316. CurrencyName = currency2[0],
  317. Rate = decimal.Parse(currency1[1]),
  318. };
  319. currencyInfos.Add(rateInfo);
  320. }
  321. }
  322. return currencyInfos;
  323. }
  324. /// <summary>
  325. /// 团组模块 - 汇率相关存储解析 To String
  326. /// </summary>
  327. /// <param name="rates"></param>
  328. /// <returns></returns>
  329. public static string GetCurrencyChinaToString(List<CurrencyInfo>? rates)
  330. {
  331. string rateStr = string.Empty;
  332. if (rates == null) return rateStr;
  333. if (rates.Count <= 0) return rateStr;
  334. if (rates.Count == 1)
  335. {
  336. var rate = rates[0];
  337. return string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  338. }
  339. foreach (CurrencyInfo rate in rates)
  340. {
  341. //存储方式: 美元(USD):6.2350|.......|墨西哥比索(MXN):1.0000
  342. rateStr += string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  343. }
  344. if (rateStr.Length > 0)
  345. {
  346. rateStr = rateStr.Substring(0, rateStr.Length - 1);
  347. }
  348. return rateStr;
  349. }
  350. #endregion
  351. #region 验证身份证号码
  352. /// <summary>
  353. /// 正则表达式
  354. /// 验证身份证号码
  355. /// </summary>
  356. /// <param name="idNumber"></param>
  357. /// <returns></returns>
  358. public static bool IsValidChineseId(this string idNumber)
  359. {
  360. 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])$";
  361. Regex regex = new Regex(pattern);
  362. return regex.IsMatch(idNumber);
  363. }
  364. /// <summary>
  365. /// 通过身份证提取生日
  366. /// </summary>
  367. /// <param name="identityCard"></param>
  368. /// <returns></returns>
  369. public static DateTime? GetBirthDateFromIdentityCard(string identityCard)
  370. {
  371. // 身份证号码正则表达式验证,支持18位身份证号码
  372. if (!Regex.IsMatch(identityCard, @"^\d{17}(\d|X|x)$"))
  373. {
  374. return null;
  375. }
  376. // 获取出生日期(8位数字)
  377. string birthDateString = identityCard.Substring(6, 8);
  378. // 尝试将出生日期字符串转换为DateTime类型
  379. if (DateTime.TryParse(birthDateString, out DateTime birthDate))
  380. {
  381. return birthDate;
  382. }
  383. return null;
  384. }
  385. /// <summary>
  386. /// 通过身份证判断性别
  387. /// </summary>
  388. /// <param name="idNumber"></param>
  389. /// <returns>0 男1 女 -1 未设置</returns>
  390. /// <exception cref="ArgumentException"></exception>
  391. public static int GetGenderFromIdentityCard(string idNumber)
  392. {
  393. if (string.IsNullOrEmpty(idNumber) || idNumber.Length != 18)
  394. return -1;
  395. char genderChar = idNumber[16];
  396. return int.Parse(genderChar.ToString()) % 2 == 0 ? 1 : 0;
  397. }
  398. #endregion
  399. #region string格式日期格式化
  400. /// <summary>
  401. /// string格式日期格式化
  402. /// </summary>
  403. /// <param name="dateStr"></param>
  404. /// <param name="format">
  405. /// 格式化标准
  406. /// yyyy-MM-dd yyyy/MM/dd
  407. /// </param>
  408. /// <returns></returns>
  409. public static string DateFormat(this string dateStr, string format)
  410. {
  411. if (!string.IsNullOrEmpty(dateStr))
  412. {
  413. if (!string.IsNullOrEmpty(format))
  414. {
  415. DateTime result;
  416. if (DateTime.TryParse(dateStr, out result))
  417. {
  418. return result.ToString(format);
  419. }
  420. }
  421. }
  422. return "";
  423. }
  424. #endregion
  425. /// <summary>
  426. /// List to DataTable
  427. /// 集合转换成datatable
  428. /// </summary>
  429. /// <typeparam name="T"></typeparam>
  430. /// <param name="aIList"></param>
  431. /// <returns></returns>
  432. public static DataTable GetDataTableFromIList<T>(List<T> aIList)
  433. {
  434. DataTable _returnTable = new DataTable();
  435. if (aIList != null && aIList.Count > 0)
  436. {
  437. object _baseObj = aIList[0];
  438. Type objectType = _baseObj.GetType();
  439. PropertyInfo[] properties = objectType.GetProperties();
  440. DataColumn _col;
  441. foreach (PropertyInfo property in properties)
  442. {
  443. _col = new DataColumn();
  444. _col.ColumnName = (string)property.Name;
  445. _col.DataType = property.PropertyType;
  446. _returnTable.Columns.Add(_col);
  447. }
  448. //Adds the rows to the table
  449. DataRow _row;
  450. foreach (object objItem in aIList)
  451. {
  452. _row = _returnTable.NewRow();
  453. foreach (PropertyInfo property in properties)
  454. {
  455. _row[property.Name] = property.GetValue(objItem, null);
  456. }
  457. _returnTable.Rows.Add(_row);
  458. }
  459. }
  460. return _returnTable;
  461. }
  462. /// <summary>
  463. /// List to DataTable
  464. /// 集合转换成datatable
  465. /// </summary>
  466. public static DataTable ToDataTableArray(IList list)
  467. {
  468. DataTable result = new DataTable();
  469. if (list.Count > 0)
  470. {
  471. PropertyInfo[] propertys = list[0].GetType().GetProperties();
  472. foreach (PropertyInfo pi in propertys)
  473. {
  474. try
  475. {
  476. result.Columns.Add(pi.Name, pi.PropertyType);
  477. }
  478. catch (Exception ex)
  479. {
  480. Console.WriteLine($"{pi.Name}:{ex.Message}");
  481. }
  482. }
  483. for (int i = 0; i < list.Count; i++)
  484. {
  485. ArrayList tempList = new ArrayList();
  486. foreach (PropertyInfo pi in propertys)
  487. {
  488. object obj = pi.GetValue(list[i], null);
  489. tempList.Add(obj);
  490. }
  491. object?[] array = tempList.ToArray();
  492. result.LoadDataRow(array, true);
  493. }
  494. }
  495. return result;
  496. }
  497. /// <summary>
  498. ///获取指定月份起止日期
  499. /// </summary>
  500. /// <param name="year"></param>
  501. /// <param name="month"></param>
  502. /// <returns></returns>
  503. public static (DateTime StartDate, DateTime EndDate) GetMonthStartAndEndDates(int year, int month)
  504. {
  505. var calendar = new GregorianCalendar();
  506. var daysInMonth = calendar.GetDaysInMonth(year, month);
  507. var startDate = new DateTime(year, month, 1);
  508. var endDate = new DateTime(year, month, daysInMonth);
  509. return (startDate, endDate);
  510. }
  511. /// <summary>
  512. /// 验证json字符串是否合法
  513. /// </summary>
  514. /// <param name="jsonString"></param>
  515. /// <returns></returns>
  516. public static bool IsValidJson(string jsonString)
  517. {
  518. try
  519. {
  520. JToken.Parse(jsonString);
  521. return true;
  522. }
  523. catch (JsonReaderException)
  524. {
  525. return false;
  526. }
  527. }
  528. /// <summary>
  529. /// 常见的双字姓氏列表
  530. /// </summary>
  531. private static readonly HashSet<string> commonDoubleSurnames = new HashSet<string>
  532. {
  533. "欧阳", "司马", "上官", "夏侯", "诸葛", "东方", "赫连", "皇甫", "尉迟", "公羊",
  534. "澹台", "公冶", "宗政", "濮阳", "淳于", "单于", "太叔", "申屠", "公孙", "仲孙",
  535. "轩辕", "令狐", "钟离", "宇文", "长孙", "慕容", "鲜于", "闾丘", "司徒", "司空",
  536. "亓官", "司寇", "仉督", "子车", "颛孙", "端木", "巫马", "公西", "漆雕", "乐正",
  537. "壤驷", "公良", "拓跋", "夹谷", "宰父", "谷梁", "晋楚", "闫法", "汝鄢", "涂钦",
  538. "段干", "百里", "东郭", "南门", "呼延", "归海", "羊舌", "微生", "岳帅", "缑亢",
  539. "况后", "有琴", "梁丘", "左丘", "东门", "西门", "商牟", "佘佴", "伯赏", "南宫"
  540. };
  541. /// <summary>
  542. /// 中文名字取姓氏和名字
  543. /// </summary>
  544. /// <param name="fullName"></param>
  545. /// <returns>姓:lastName 名:firstName</returns>
  546. public static (string lastName, string firstName) GetLastNameAndFirstName(string fullName)
  547. {
  548. if (string.IsNullOrEmpty(fullName) || fullName.Length < 2) return ("", "");
  549. // 尝试匹配双字姓氏
  550. if (fullName.Length > 2)
  551. {
  552. string potentialDoubleSurname = fullName.Substring(0, 2);
  553. if (commonDoubleSurnames.Contains(potentialDoubleSurname))
  554. {
  555. string lastName = potentialDoubleSurname;
  556. string firstName = fullName.Substring(2);
  557. return (lastName, firstName);
  558. }
  559. }
  560. // 默认单字姓氏
  561. string singleSurname = fullName.Substring(0, 1);
  562. string remainingName = fullName.Substring(1);
  563. return (singleSurname, remainingName);
  564. }
  565. /// <summary>
  566. /// 中文名字转拼音
  567. /// </summary>
  568. /// <param name="chineseName"></param>
  569. /// <returns></returns>
  570. /// <exception cref="ArgumentException"></exception>
  571. public static string ConvertToPinyin(string chineseName)
  572. {
  573. if (string.IsNullOrEmpty(chineseName)) return "";
  574. return PinyinHelper.GetPinyin(chineseName, "").ToUpper();
  575. }
  576. }