CommonFun.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. using NPOI.SS.Formula.Functions;
  2. using OASystem.Domain.ViewModels.Financial;
  3. using OASystem.Domain.ViewModels.Groups;
  4. using System.Globalization;
  5. using System.Reflection;
  6. using System.Reflection.Metadata;
  7. namespace OASystem.Infrastructure.Tools;
  8. /// <summary>
  9. /// 工具类
  10. /// </summary>
  11. public static class CommonFun
  12. {
  13. public static string GUID => Guid.NewGuid().ToString("N");
  14. public static bool IsNull(this string s)
  15. {
  16. return string.IsNullOrWhiteSpace(s);
  17. }
  18. public static bool NotNull(this string s)
  19. {
  20. return !string.IsNullOrWhiteSpace(s);
  21. }
  22. public static int GetRandom(int minNum, int maxNum)
  23. {
  24. var seed = BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0);
  25. return new Random(seed).Next(minNum, maxNum);
  26. }
  27. public static string GetSerialNumber(string prefix = "")
  28. {
  29. return prefix + DateTime.Now.ToString("yyyyMMddHHmmssfff") + GetRandom(1000, 9999).ToString();
  30. }
  31. public static string ToJson(this object obj)
  32. {
  33. return JsonSerializer.Serialize(obj);
  34. }
  35. public static T ToObject<T>(this string json)
  36. {
  37. return JsonSerializer.Deserialize<T>(json);
  38. }
  39. public static object GetDefaultVal(string typename)
  40. {
  41. return typename switch
  42. {
  43. "Boolean" => false,
  44. "DateTime" => default(DateTime),
  45. "Date" => default(DateTime),
  46. "Double" => 0.0,
  47. "Single" => 0f,
  48. "Int32" => 0,
  49. "String" => string.Empty,
  50. "Decimal" => 0m,
  51. _ => null,
  52. };
  53. }
  54. public static void CoverNull<T>(T model) where T : class
  55. {
  56. if (model == null)
  57. {
  58. return;
  59. }
  60. var typeFromHandle = typeof(T);
  61. var properties = typeFromHandle.GetProperties();
  62. var array = properties;
  63. for (var i = 0; i < array.Length; i++)
  64. {
  65. var propertyInfo = array[i];
  66. if (propertyInfo.GetValue(model, null) == null)
  67. {
  68. propertyInfo.SetValue(model, GetDefaultVal(propertyInfo.PropertyType.Name), null);
  69. }
  70. }
  71. }
  72. public static void CoverNull<T>(List<T> models) where T : class
  73. {
  74. if (models.Count == 0)
  75. {
  76. return;
  77. }
  78. foreach (var model in models)
  79. {
  80. CoverNull(model);
  81. }
  82. }
  83. public static bool ToBool(this object thisValue, bool errorvalue = false)
  84. {
  85. if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out bool reval))
  86. {
  87. return reval;
  88. }
  89. return errorvalue;
  90. }
  91. #region 文件操作
  92. public static FileInfo[] GetFiles(string directoryPath)
  93. {
  94. if (!IsExistDirectory(directoryPath))
  95. {
  96. throw new DirectoryNotFoundException();
  97. }
  98. var root = new DirectoryInfo(directoryPath);
  99. return root.GetFiles();
  100. }
  101. public static bool IsExistDirectory(string directoryPath)
  102. {
  103. return Directory.Exists(directoryPath);
  104. }
  105. public static string ReadFile(string Path)
  106. {
  107. string s;
  108. if (!File.Exists(Path))
  109. s = "不存在相应的目录";
  110. else
  111. {
  112. var f2 = new StreamReader(Path, Encoding.Default);
  113. s = f2.ReadToEnd();
  114. f2.Close();
  115. f2.Dispose();
  116. }
  117. return s;
  118. }
  119. public static void FileMove(string OrignFile, string NewFile)
  120. {
  121. File.Move(OrignFile, NewFile);
  122. }
  123. public static void CreateDir(string dir)
  124. {
  125. if (dir.Length == 0) return;
  126. if (!Directory.Exists(dir))
  127. Directory.CreateDirectory(dir);
  128. }
  129. #endregion
  130. #region IP
  131. /// <summary>
  132. /// 是否为ip
  133. /// </summary>
  134. /// <param name="ip"></param>
  135. /// <returns></returns>
  136. public static bool IsIP(string ip)
  137. {
  138. 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?)$");
  139. }
  140. public static string GetIP(HttpRequest request)
  141. {
  142. if (request == null)
  143. {
  144. return "";
  145. }
  146. var ip = request.Headers["X-Real-IP"].FirstOrDefault();
  147. if (ip.IsNull())
  148. {
  149. ip = request.Headers["X-Forwarded-For"].FirstOrDefault();
  150. }
  151. if (ip.IsNull())
  152. {
  153. ip = request.HttpContext?.Connection?.RemoteIpAddress?.ToString();
  154. }
  155. if (ip.IsNull() || !IsIP(ip))
  156. {
  157. ip = "127.0.0.1";
  158. }
  159. return ip;
  160. }
  161. #endregion
  162. #region 随机数
  163. /// <summary>
  164. /// 根据自定义随机包含的字符获取指定长度的随机字符
  165. /// </summary>
  166. /// <param name="length">随机字符长度</param>
  167. /// <returns>随机字符</returns>
  168. public static string GetRandomStr(int length)
  169. {
  170. string a = "ABCDEFGHJKLMNPQRSTUVWXYZ012356789";
  171. StringBuilder sb = new StringBuilder();
  172. for (int i = 0; i < length; i++)
  173. {
  174. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  175. }
  176. return sb.ToString();
  177. }
  178. /// <summary>
  179. /// 根据自定义随机包含的字符获取指定长度的随机字符
  180. /// </summary>
  181. /// <param name="length">随机字符长度</param>
  182. /// <returns>随机字符</returns>
  183. public static string GetRandomAllStr(int length)
  184. {
  185. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz012356789";
  186. StringBuilder sb = new StringBuilder();
  187. for (int i = 0; i < length; i++)
  188. {
  189. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  190. }
  191. return sb.ToString();
  192. }
  193. /// <summary>
  194. /// 根据自定义随机包含的字符获取指定长度的随机字母(含大小写)
  195. /// </summary>
  196. /// <param name="length">随机字符长度</param>
  197. /// <returns>随机字符</returns>
  198. public static string GetRandomLetter(int length)
  199. {
  200. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz";
  201. StringBuilder sb = new StringBuilder();
  202. for (int i = 0; i < length; i++)
  203. {
  204. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  205. }
  206. return sb.ToString();
  207. }
  208. /// <summary>
  209. /// 生成不重复随机数字
  210. /// 操作者:037
  211. /// 2021-07-26 15:39
  212. /// </summary>
  213. /// <param name="CodeCount">输入字符串长度</param>
  214. /// <returns>字符串</returns>
  215. public static string GetRandomNumber(int len)
  216. {
  217. string allChar = "0,1,2,3,4,5,6,7,8,9";
  218. string[] allCharArray = allChar.Split(',');
  219. string RandomCode = "";
  220. int temp = -1;
  221. Random rand = new Random();
  222. for (int i = 0; i < len; i++)
  223. {
  224. if (temp != -1)
  225. {
  226. rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
  227. }
  228. int t = rand.Next(allCharArray.Length - 1);
  229. while (temp == t)
  230. {
  231. t = rand.Next(allCharArray.Length - 1);
  232. }
  233. temp = t;
  234. RandomCode += allCharArray[t];
  235. }
  236. return RandomCode;
  237. }
  238. #endregion
  239. #region decimal 截取
  240. /// <summary>
  241. ///
  242. /// </summary>
  243. /// <param name="d"></param>
  244. /// <param name="n"></param>
  245. /// <returns></returns>
  246. public static decimal CutDecimalWithN(decimal d, int n)
  247. {
  248. string strDecimal = d.ToString();
  249. int index = strDecimal.IndexOf(".");
  250. if (index == -1 || strDecimal.Length < index + n + 1)
  251. {
  252. strDecimal = string.Format("{0:F" + n + "}", d);
  253. }
  254. else
  255. {
  256. int length = index;
  257. if (n != 0)
  258. {
  259. length = index + n + 1;
  260. }
  261. strDecimal = strDecimal.Substring(0, length);
  262. }
  263. return Decimal.Parse(strDecimal);
  264. }
  265. public static decimal CutDecimalWithN(decimal? d, int n)
  266. {
  267. if (d == null)
  268. {
  269. return Decimal.MinValue;
  270. }
  271. return CutDecimalWithN(Convert.ToDecimal(d), n);
  272. }
  273. #endregion
  274. #region decimal 保留两位小数
  275. /// <summary>
  276. /// decimal 保留两位小数 不四舍五入
  277. /// </summary>
  278. /// <param name="number"></param>
  279. /// <returns></returns>
  280. public static decimal DecimalsKeepTwo(this decimal myDecimal)
  281. {
  282. var subDecimal = Math.Floor(myDecimal * 100) / 100;//保留两位小数,直接截取
  283. return subDecimal;
  284. }
  285. #endregion
  286. #region 团组模块 - 汇率相关存储解析
  287. /// <summary>
  288. /// 团组模块 - 汇率相关 To List
  289. /// </summary>
  290. /// <param name="rateStr"></param>
  291. /// <returns></returns>
  292. public static List<CurrencyInfo> GetCurrencyChinaToList(string? rateStr)
  293. {
  294. List<CurrencyInfo> currencyInfos = new List<CurrencyInfo>();
  295. if (string.IsNullOrEmpty(rateStr)) return currencyInfos;
  296. if (rateStr.Contains("|"))
  297. {
  298. string[] currencyArr = rateStr.Split("|");
  299. foreach (string currency in currencyArr)
  300. {
  301. string[] currency1 = currency.Split(":");
  302. string[] currency2 = currency1[0].Split("(");
  303. CurrencyInfo rateInfo = new CurrencyInfo()
  304. {
  305. CurrencyCode = currency2[1].Replace(")", "").TrimEnd(),
  306. CurrencyName = currency2[0],
  307. Rate = decimal.Parse(currency1[1]),
  308. };
  309. currencyInfos.Add(rateInfo);
  310. }
  311. }
  312. return currencyInfos;
  313. }
  314. /// <summary>
  315. /// 团组模块 - 汇率相关存储解析 To String
  316. /// </summary>
  317. /// <param name="rates"></param>
  318. /// <returns></returns>
  319. public static string GetCurrencyChinaToString(List<CurrencyInfo> rates)
  320. {
  321. string rateStr = string.Empty;
  322. if (rates.Count <= 0) return rateStr;
  323. if (rates.Count == 1 )
  324. {
  325. var rate = rates[0];
  326. return string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  327. }
  328. foreach (CurrencyInfo rate in rates)
  329. {
  330. //存储方式: 美元(USD):6.2350|.......|墨西哥比索(MXN):1.0000
  331. rateStr += string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  332. }
  333. if (rateStr.Length > 0)
  334. {
  335. rateStr = rateStr.Substring(0, rateStr.Length - 1);
  336. }
  337. return rateStr;
  338. }
  339. #endregion
  340. #region 验证身份证号码
  341. /// <summary>
  342. /// 正则表达式
  343. /// 验证身份证号码
  344. /// </summary>
  345. /// <param name="idNumber"></param>
  346. /// <returns></returns>
  347. public static bool ValidateIdNumber(this string idNumber)
  348. {
  349. string pattern = @"^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}(\d|X)$";
  350. Regex regex = new Regex(pattern);
  351. return regex.IsMatch(idNumber);
  352. }
  353. #endregion
  354. #region string格式日期格式化
  355. /// <summary>
  356. /// string格式日期格式化
  357. /// </summary>
  358. /// <param name="dateStr"></param>
  359. /// <param name="format">
  360. /// 格式化标准
  361. /// yyyy-MM-dd yyyy/MM/dd
  362. /// </param>
  363. /// <returns></returns>
  364. public static string DateFormat(this string dateStr, string format)
  365. {
  366. if (!string.IsNullOrEmpty(dateStr))
  367. {
  368. if (!string.IsNullOrEmpty(format))
  369. {
  370. DateTime result;
  371. if (DateTime.TryParse(dateStr, out result))
  372. {
  373. return result.ToString(format);
  374. }
  375. }
  376. }
  377. return "";
  378. }
  379. #endregion
  380. /// <summary>
  381. /// List to DataTable
  382. /// 集合转换成datatable
  383. /// </summary>
  384. /// <typeparam name="T"></typeparam>
  385. /// <param name="aIList"></param>
  386. /// <returns></returns>
  387. public static DataTable GetDataTableFromIList<T>(List<T> aIList)
  388. {
  389. DataTable _returnTable = new DataTable();
  390. if (aIList != null && aIList.Count > 0)
  391. {
  392. object _baseObj = aIList[0];
  393. Type objectType = _baseObj.GetType();
  394. PropertyInfo[] properties = objectType.GetProperties();
  395. DataColumn _col;
  396. foreach (PropertyInfo property in properties)
  397. {
  398. _col = new DataColumn();
  399. _col.ColumnName = (string)property.Name;
  400. _col.DataType = property.PropertyType;
  401. _returnTable.Columns.Add(_col);
  402. }
  403. //Adds the rows to the table
  404. DataRow _row;
  405. foreach (object objItem in aIList)
  406. {
  407. _row = _returnTable.NewRow();
  408. foreach (PropertyInfo property in properties)
  409. {
  410. _row[property.Name] = property.GetValue(objItem, null);
  411. }
  412. _returnTable.Rows.Add(_row);
  413. }
  414. }
  415. return _returnTable;
  416. }
  417. }