CommonFun.cs 11 KB

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