CommonFun.cs 11 KB

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