CommonFun.cs 16 KB

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