CommonFun.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. #endregion
  132. #region IP
  133. /// <summary>
  134. /// 是否为ip
  135. /// </summary>
  136. /// <param name="ip"></param>
  137. /// <returns></returns>
  138. public static bool IsIP(string ip)
  139. {
  140. 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?)$");
  141. }
  142. public static string GetIP(HttpRequest request)
  143. {
  144. if (request == null)
  145. {
  146. return "";
  147. }
  148. var ip = request.Headers["X-Real-IP"].FirstOrDefault();
  149. if (ip.IsNull())
  150. {
  151. ip = request.Headers["X-Forwarded-For"].FirstOrDefault();
  152. }
  153. if (ip.IsNull())
  154. {
  155. ip = request.HttpContext?.Connection?.RemoteIpAddress?.ToString();
  156. }
  157. if (ip.IsNull() || !IsIP(ip))
  158. {
  159. ip = "127.0.0.1";
  160. }
  161. return ip;
  162. }
  163. #endregion
  164. #region 随机数
  165. /// <summary>
  166. /// 根据自定义随机包含的字符获取指定长度的随机字符
  167. /// </summary>
  168. /// <param name="length">随机字符长度</param>
  169. /// <returns>随机字符</returns>
  170. public static string GetRandomStr(int length)
  171. {
  172. string a = "ABCDEFGHJKLMNPQRSTUVWXYZ012356789";
  173. StringBuilder sb = new StringBuilder();
  174. for (int i = 0; i < length; i++)
  175. {
  176. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  177. }
  178. return sb.ToString();
  179. }
  180. /// <summary>
  181. /// 根据自定义随机包含的字符获取指定长度的随机字符
  182. /// </summary>
  183. /// <param name="length">随机字符长度</param>
  184. /// <returns>随机字符</returns>
  185. public static string GetRandomAllStr(int length)
  186. {
  187. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz012356789";
  188. StringBuilder sb = new StringBuilder();
  189. for (int i = 0; i < length; i++)
  190. {
  191. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  192. }
  193. return sb.ToString();
  194. }
  195. /// <summary>
  196. /// 根据自定义随机包含的字符获取指定长度的随机字母(含大小写)
  197. /// </summary>
  198. /// <param name="length">随机字符长度</param>
  199. /// <returns>随机字符</returns>
  200. public static string GetRandomLetter(int length)
  201. {
  202. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz";
  203. StringBuilder sb = new StringBuilder();
  204. for (int i = 0; i < length; i++)
  205. {
  206. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  207. }
  208. return sb.ToString();
  209. }
  210. /// <summary>
  211. /// 生成不重复随机数字
  212. /// 操作者:037
  213. /// 2021-07-26 15:39
  214. /// </summary>
  215. /// <param name="CodeCount">输入字符串长度</param>
  216. /// <returns>字符串</returns>
  217. public static string GetRandomNumber(int len)
  218. {
  219. string allChar = "0,1,2,3,4,5,6,7,8,9";
  220. string[] allCharArray = allChar.Split(',');
  221. string RandomCode = "";
  222. int temp = -1;
  223. Random rand = new Random();
  224. for (int i = 0; i < len; i++)
  225. {
  226. if (temp != -1)
  227. {
  228. rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
  229. }
  230. int t = rand.Next(allCharArray.Length - 1);
  231. while (temp == t)
  232. {
  233. t = rand.Next(allCharArray.Length - 1);
  234. }
  235. temp = t;
  236. RandomCode += allCharArray[t];
  237. }
  238. return RandomCode;
  239. }
  240. #endregion
  241. #region decimal 截取
  242. /// <summary>
  243. ///
  244. /// </summary>
  245. /// <param name="d"></param>
  246. /// <param name="n"></param>
  247. /// <returns></returns>
  248. public static decimal CutDecimalWithN(decimal d, int n)
  249. {
  250. string strDecimal = d.ToString();
  251. int index = strDecimal.IndexOf(".");
  252. if (index == -1 || strDecimal.Length < index + n + 1)
  253. {
  254. strDecimal = string.Format("{0:F" + n + "}", d);
  255. }
  256. else
  257. {
  258. int length = index;
  259. if (n != 0)
  260. {
  261. length = index + n + 1;
  262. }
  263. strDecimal = strDecimal.Substring(0, length);
  264. }
  265. return Decimal.Parse(strDecimal);
  266. }
  267. public static decimal CutDecimalWithN(decimal? d, int n)
  268. {
  269. if (d == null)
  270. {
  271. return Decimal.MinValue;
  272. }
  273. return CutDecimalWithN(Convert.ToDecimal(d), n);
  274. }
  275. #endregion
  276. #region decimal 保留两位小数
  277. /// <summary>
  278. /// decimal 保留两位小数 不四舍五入
  279. /// </summary>
  280. /// <param name="number"></param>
  281. /// <returns></returns>
  282. public static decimal DecimalsKeepTwo(this decimal myDecimal)
  283. {
  284. var subDecimal = Math.Floor(myDecimal * 100) / 100;//保留两位小数,直接截取
  285. return subDecimal;
  286. }
  287. #endregion
  288. #region 团组模块 - 汇率相关存储解析
  289. /// <summary>
  290. /// 团组模块 - 汇率相关 To List
  291. /// </summary>
  292. /// <param name="rateStr"></param>
  293. /// <returns></returns>
  294. public static List<CurrencyInfo> GetCurrencyChinaToList(string? rateStr)
  295. {
  296. List<CurrencyInfo> currencyInfos = new List<CurrencyInfo>();
  297. if (string.IsNullOrEmpty(rateStr)) return currencyInfos;
  298. if (rateStr.Contains("|"))
  299. {
  300. string[] currencyArr = rateStr.Split("|");
  301. foreach (string currency in currencyArr)
  302. {
  303. string[] currency1 = currency.Split(":");
  304. string[] currency2 = currency1[0].Split("(");
  305. CurrencyInfo rateInfo = new CurrencyInfo()
  306. {
  307. CurrencyCode = currency2[1].Replace(")", "").TrimEnd(),
  308. CurrencyName = currency2[0],
  309. Rate = decimal.Parse(currency1[1]),
  310. };
  311. currencyInfos.Add(rateInfo);
  312. }
  313. }
  314. return currencyInfos;
  315. }
  316. /// <summary>
  317. /// 团组模块 - 汇率相关存储解析 To String
  318. /// </summary>
  319. /// <param name="rates"></param>
  320. /// <returns></returns>
  321. public static string GetCurrencyChinaToString(List<CurrencyInfo> rates)
  322. {
  323. string rateStr = string.Empty;
  324. if (rates.Count <= 0) return rateStr;
  325. if (rates.Count == 1 )
  326. {
  327. var rate = rates[0];
  328. return string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  329. }
  330. foreach (CurrencyInfo rate in rates)
  331. {
  332. //存储方式: 美元(USD):6.2350|.......|墨西哥比索(MXN):1.0000
  333. rateStr += string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  334. }
  335. if (rateStr.Length > 0)
  336. {
  337. rateStr = rateStr.Substring(0, rateStr.Length - 1);
  338. }
  339. return rateStr;
  340. }
  341. #endregion
  342. #region 验证身份证号码
  343. /// <summary>
  344. /// 正则表达式
  345. /// 验证身份证号码
  346. /// </summary>
  347. /// <param name="idNumber"></param>
  348. /// <returns></returns>
  349. public static bool IsValidChineseId(this string idNumber)
  350. {
  351. 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])$";
  352. Regex regex = new Regex(pattern);
  353. return regex.IsMatch(idNumber);
  354. }
  355. /// <summary>
  356. /// 通过身份证提取生日
  357. /// </summary>
  358. /// <param name="identityCard"></param>
  359. /// <returns></returns>
  360. public static DateTime? GetBirthDateFromIdentityCard(string identityCard)
  361. {
  362. // 身份证号码正则表达式验证,支持18位身份证号码
  363. if (!Regex.IsMatch(identityCard, @"^\d{17}(\d|X|x)$"))
  364. {
  365. return null;
  366. }
  367. // 获取出生日期(8位数字)
  368. string birthDateString = identityCard.Substring(6, 8);
  369. // 尝试将出生日期字符串转换为DateTime类型
  370. if (DateTime.TryParse(birthDateString, out DateTime birthDate))
  371. {
  372. return birthDate;
  373. }
  374. return null;
  375. }
  376. /// <summary>
  377. /// 通过身份证判断性别
  378. /// </summary>
  379. /// <param name="idNumber"></param>
  380. /// <returns>0 男1 女 -1 未设置</returns>
  381. /// <exception cref="ArgumentException"></exception>
  382. public static int GetGenderFromIdentityCard(string idNumber)
  383. {
  384. if (string.IsNullOrEmpty(idNumber) || idNumber.Length != 18)
  385. return -1;
  386. char genderChar = idNumber[16];
  387. return int.Parse(genderChar.ToString()) % 2 == 0 ? 1 :0;
  388. }
  389. #endregion
  390. #region string格式日期格式化
  391. /// <summary>
  392. /// string格式日期格式化
  393. /// </summary>
  394. /// <param name="dateStr"></param>
  395. /// <param name="format">
  396. /// 格式化标准
  397. /// yyyy-MM-dd yyyy/MM/dd
  398. /// </param>
  399. /// <returns></returns>
  400. public static string DateFormat(this string dateStr, string format)
  401. {
  402. if (!string.IsNullOrEmpty(dateStr))
  403. {
  404. if (!string.IsNullOrEmpty(format))
  405. {
  406. DateTime result;
  407. if (DateTime.TryParse(dateStr, out result))
  408. {
  409. return result.ToString(format);
  410. }
  411. }
  412. }
  413. return "";
  414. }
  415. #endregion
  416. /// <summary>
  417. /// List to DataTable
  418. /// 集合转换成datatable
  419. /// </summary>
  420. /// <typeparam name="T"></typeparam>
  421. /// <param name="aIList"></param>
  422. /// <returns></returns>
  423. public static DataTable GetDataTableFromIList<T>(List<T> aIList)
  424. {
  425. DataTable _returnTable = new DataTable();
  426. if (aIList != null && aIList.Count > 0)
  427. {
  428. object _baseObj = aIList[0];
  429. Type objectType = _baseObj.GetType();
  430. PropertyInfo[] properties = objectType.GetProperties();
  431. DataColumn _col;
  432. foreach (PropertyInfo property in properties)
  433. {
  434. _col = new DataColumn();
  435. _col.ColumnName = (string)property.Name;
  436. _col.DataType = property.PropertyType;
  437. _returnTable.Columns.Add(_col);
  438. }
  439. //Adds the rows to the table
  440. DataRow _row;
  441. foreach (object objItem in aIList)
  442. {
  443. _row = _returnTable.NewRow();
  444. foreach (PropertyInfo property in properties)
  445. {
  446. _row[property.Name] = property.GetValue(objItem, null);
  447. }
  448. _returnTable.Rows.Add(_row);
  449. }
  450. }
  451. return _returnTable;
  452. }
  453. /// <summary>
  454. /// List to DataTable
  455. /// 集合转换成datatable
  456. /// </summary>
  457. public static DataTable ToDataTableArray(IList list)
  458. {
  459. DataTable result = new DataTable();
  460. if (list.Count > 0)
  461. {
  462. PropertyInfo[] propertys = list[0].GetType().GetProperties();
  463. foreach (PropertyInfo pi in propertys)
  464. {
  465. result.Columns.Add(pi.Name, pi.PropertyType);
  466. }
  467. for (int i = 0; i < list.Count; i++)
  468. {
  469. ArrayList tempList = new ArrayList();
  470. foreach (PropertyInfo pi in propertys)
  471. {
  472. object obj = pi.GetValue(list[i], null);
  473. tempList.Add(obj);
  474. }
  475. object[] array = tempList.ToArray();
  476. result.LoadDataRow(array, true);
  477. }
  478. }
  479. return result;
  480. }
  481. /// <summary>
  482. ///获取指定月份起止日期
  483. /// </summary>
  484. /// <param name="year"></param>
  485. /// <param name="month"></param>
  486. /// <returns></returns>
  487. public static (DateTime StartDate, DateTime EndDate) GetMonthStartAndEndDates(int year, int month)
  488. {
  489. var calendar = new GregorianCalendar();
  490. var daysInMonth = calendar.GetDaysInMonth(year, month);
  491. var startDate = new DateTime(year, month, 1);
  492. var endDate = new DateTime(year, month, daysInMonth);
  493. return (startDate, endDate);
  494. }
  495. }