CommonFun.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. #endregion
  191. #region decimal 截取
  192. /// <summary>
  193. ///
  194. /// </summary>
  195. /// <param name="d"></param>
  196. /// <param name="n"></param>
  197. /// <returns></returns>
  198. public static decimal CutDecimalWithN(decimal d, int n)
  199. {
  200. string strDecimal = d.ToString();
  201. int index = strDecimal.IndexOf(".");
  202. if (index == -1 || strDecimal.Length < index + n + 1)
  203. {
  204. strDecimal = string.Format("{0:F" + n + "}", d);
  205. }
  206. else
  207. {
  208. int length = index;
  209. if (n != 0)
  210. {
  211. length = index + n + 1;
  212. }
  213. strDecimal = strDecimal.Substring(0, length);
  214. }
  215. return Decimal.Parse(strDecimal);
  216. }
  217. public static decimal CutDecimalWithN(decimal? d, int n)
  218. {
  219. if (d == null)
  220. {
  221. return Decimal.MinValue;
  222. }
  223. return CutDecimalWithN(Convert.ToDecimal(d), n);
  224. }
  225. #endregion
  226. #region 团组模块 - 汇率相关存储解析
  227. /// <summary>
  228. /// 团组模块 - 汇率相关 To List
  229. /// </summary>
  230. /// <param name="rateStr"></param>
  231. /// <returns></returns>
  232. public static List<CurrencyInfo> GetCurrencyChinaToList(string? rateStr)
  233. {
  234. List<CurrencyInfo> currencyInfos = new List<CurrencyInfo>();
  235. if (string.IsNullOrEmpty(rateStr)) return currencyInfos;
  236. if (rateStr.Contains("|"))
  237. {
  238. string[] currencyArr = rateStr.Split("|");
  239. foreach (string currency in currencyArr)
  240. {
  241. string[] currency1 = currency.Split(":");
  242. string[] currency2 = currency1[0].Split("(");
  243. CurrencyInfo rateInfo = new CurrencyInfo()
  244. {
  245. CurrencyCode = currency2[1].Replace(")", "").TrimEnd(),
  246. CurrencyName = currency2[0],
  247. Rate = decimal.Parse(currency1[1]),
  248. };
  249. currencyInfos.Add(rateInfo);
  250. }
  251. }
  252. return currencyInfos;
  253. }
  254. /// <summary>
  255. /// 团组模块 - 汇率相关存储解析 To String
  256. /// </summary>
  257. /// <param name="rates"></param>
  258. /// <returns></returns>
  259. public static string GetCurrencyChinaToString(List<CurrencyInfo> rates)
  260. {
  261. string rateStr = string.Empty;
  262. if (rates.Count <= 0) return rateStr;
  263. foreach (CurrencyInfo rate in rates)
  264. {
  265. //存储方式: 美元(USD):6.2350|.......|墨西哥比索(MXN):1.0000
  266. rateStr += string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  267. }
  268. if (rateStr.Length > 0)
  269. {
  270. rateStr = rateStr.Substring(0, rateStr.Length - 1);
  271. }
  272. return rateStr;
  273. }
  274. #endregion
  275. #region 验证身份证号码
  276. /// <summary>
  277. /// 正则表达式
  278. /// 验证身份证号码
  279. /// </summary>
  280. /// <param name="idNumber"></param>
  281. /// <returns></returns>
  282. public static bool ValidateIdNumber(this string idNumber)
  283. {
  284. 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)$";
  285. Regex regex = new Regex(pattern);
  286. return regex.IsMatch(idNumber);
  287. }
  288. #endregion
  289. }