CommonUtil.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using IPTools.Core;
  7. using Magicodes.ExporterAndImporter.Core.Models;
  8. using System.Xml;
  9. using System.Xml.Linq;
  10. using System.Xml.Serialization;
  11. namespace Admin.NET.Core;
  12. /// <summary>
  13. /// 通用工具类
  14. /// </summary>
  15. public static class CommonUtil
  16. {
  17. /// <summary>
  18. /// 根据字符串获取固定整型哈希值
  19. /// </summary>
  20. /// <param name="str"></param>
  21. /// <returns></returns>
  22. public static int GetFixedHashCode(string str)
  23. {
  24. if (string.IsNullOrWhiteSpace(str)) return 0;
  25. unchecked
  26. {
  27. int hash1 = (5381 << 16) + 5381;
  28. int hash2 = hash1;
  29. for (int i = 0; i < str.Length; i += 2)
  30. {
  31. hash1 = ((hash1 << 5) + hash1) ^ str[i];
  32. if (i == str.Length - 1)
  33. break;
  34. hash2 = ((hash2 << 5) + hash2) ^ str[i + 1];
  35. }
  36. return Math.Abs(hash1 + (hash2 * 1566083941));
  37. }
  38. }
  39. /// <summary>
  40. /// 生成百分数
  41. /// </summary>
  42. /// <param name="PassCount"></param>
  43. /// <param name="allCount"></param>
  44. /// <returns></returns>
  45. public static string ExecPercent(decimal PassCount, decimal allCount)
  46. {
  47. string res = "";
  48. if (allCount > 0)
  49. {
  50. var value = (double)Math.Round(PassCount / allCount * 100, 1);
  51. if (value < 0)
  52. res = Math.Round(value + 5 / Math.Pow(10, 0 + 1), 0, MidpointRounding.AwayFromZero).ToString();
  53. else
  54. res = Math.Round(value, 0, MidpointRounding.AwayFromZero).ToString();
  55. }
  56. if (res == "") res = "0";
  57. return res + "%";
  58. }
  59. /// <summary>
  60. /// 获取服务地址
  61. /// </summary>
  62. /// <returns></returns>
  63. public static string GetLocalhost()
  64. {
  65. string result = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Host.Value}";
  66. // 代理模式:获取真正的本机地址
  67. // X-Original-Host=原始请求
  68. // X-Forwarded-Server=从哪里转发过来
  69. if (App.HttpContext.Request.Headers.ContainsKey("Origin")) // 配置成完整的路径如(结尾不要带"/"),比如 https://www.abc.com
  70. result = $"{App.HttpContext.Request.Headers["Origin"]}";
  71. else if (App.HttpContext.Request.Headers.ContainsKey("X-Original")) // 配置成完整的路径如(结尾不要带"/"),比如 https://www.abc.com
  72. result = $"{App.HttpContext.Request.Headers["X-Original"]}";
  73. else if (App.HttpContext.Request.Headers.ContainsKey("X-Original-Host"))
  74. result = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Headers["X-Original-Host"]}";
  75. return result;
  76. }
  77. /// <summary>
  78. /// 对象序列化XML
  79. /// </summary>
  80. /// <typeparam name="T"></typeparam>
  81. /// <param name="obj"></param>
  82. /// <returns></returns>
  83. public static string SerializeObjectToXml<T>(T obj)
  84. {
  85. if (obj == null) return string.Empty;
  86. var xs = new XmlSerializer(obj.GetType());
  87. var stream = new MemoryStream();
  88. var setting = new XmlWriterSettings
  89. {
  90. Encoding = new UTF8Encoding(false), // 不包含BOM
  91. Indent = true // 设置格式化缩进
  92. };
  93. using (var writer = XmlWriter.Create(stream, setting))
  94. {
  95. var ns = new XmlSerializerNamespaces();
  96. ns.Add("", ""); // 去除默认命名空间
  97. xs.Serialize(writer, obj, ns);
  98. }
  99. return Encoding.UTF8.GetString(stream.ToArray());
  100. }
  101. /// <summary>
  102. /// 字符串转XML格式
  103. /// </summary>
  104. /// <param name="xmlStr"></param>
  105. /// <returns></returns>
  106. public static XElement SerializeStringToXml(string xmlStr)
  107. {
  108. try
  109. {
  110. return XElement.Parse(xmlStr);
  111. }
  112. catch
  113. {
  114. return null;
  115. }
  116. }
  117. /// <summary>
  118. /// 导出模板Excel
  119. /// </summary>
  120. /// <returns></returns>
  121. public static async Task<IActionResult> ExportExcelTemplate<T>(string fileName = null) where T : class, new()
  122. {
  123. IImporter importer = new ExcelImporter();
  124. var res = await importer.GenerateTemplateBytes<T>();
  125. return new FileContentResult(res, "application/octet-stream") { FileDownloadName = $"{(string.IsNullOrEmpty(fileName) ? typeof(T).Name : fileName)}.xlsx" };
  126. }
  127. /// <summary>
  128. /// 导出数据excel
  129. /// </summary>
  130. /// <returns></returns>
  131. public static async Task<IActionResult> ExportExcelData<T>(ICollection<T> data, string fileName = null) where T : class, new()
  132. {
  133. var export = new ExcelExporter();
  134. var res = await export.ExportAsByteArray<T>(data);
  135. return new FileContentResult(res, "application/octet-stream") { FileDownloadName = $"{(string.IsNullOrEmpty(fileName) ? typeof(T).Name : fileName)}.xlsx" };
  136. }
  137. /// <summary>
  138. /// 导出数据excel,包括字典转换
  139. /// </summary>
  140. /// <returns></returns>
  141. public static async Task<IActionResult> ExportExcelData<TSource, TTarget>(ISugarQueryable<TSource> query, Func<TSource, TTarget, TTarget> action = null)
  142. where TSource : class, new() where TTarget : class, new()
  143. {
  144. var PropMappings = GetExportPropertMap<TSource, TTarget>();
  145. var data = query.ToList();
  146. //相同属性复制值,字典值转换
  147. var result = new List<TTarget>();
  148. foreach (var item in data)
  149. {
  150. var newData = new TTarget();
  151. foreach (var dict in PropMappings)
  152. {
  153. var targeProp = dict.Value.Item3;
  154. if (targeProp != null)
  155. {
  156. var propertyInfo = dict.Value.Item2;
  157. var sourceVal = propertyInfo.GetValue(item, null);
  158. if (sourceVal == null)
  159. {
  160. continue;
  161. }
  162. var map = dict.Value.Item1;
  163. if (map != null && map.ContainsKey(sourceVal))
  164. {
  165. var newVal = map[sourceVal];
  166. targeProp.SetValue(newData, newVal);
  167. }
  168. else
  169. {
  170. if (targeProp.PropertyType.FullName == propertyInfo.PropertyType.FullName)
  171. {
  172. targeProp.SetValue(newData, sourceVal);
  173. }
  174. else
  175. {
  176. var newVal = sourceVal.ToString().ParseTo(targeProp.PropertyType);
  177. targeProp.SetValue(newData, newVal);
  178. }
  179. }
  180. }
  181. if (action != null)
  182. {
  183. newData = action(item, newData);
  184. }
  185. }
  186. result.Add(newData);
  187. }
  188. var export = new ExcelExporter();
  189. var res = await export.ExportAsByteArray(result);
  190. return new FileContentResult(res, "application/octet-stream") { FileDownloadName = typeof(TTarget).Name + ".xlsx" };
  191. }
  192. /// <summary>
  193. /// 导入数据Excel
  194. /// </summary>
  195. /// <param name="file"></param>
  196. /// <returns></returns>
  197. public static async Task<ICollection<T>> ImportExcelData<T>([Required] IFormFile file) where T : class, new()
  198. {
  199. IImporter importer = new ExcelImporter();
  200. var res = await importer.Import<T>(file.OpenReadStream());
  201. var message = string.Empty;
  202. if (res.HasError)
  203. {
  204. if (res.Exception != null)
  205. message += $"\r\n{res.Exception.Message}";
  206. foreach (DataRowErrorInfo drErrorInfo in res.RowErrors)
  207. {
  208. int rowNum = drErrorInfo.RowIndex;
  209. foreach (var item in drErrorInfo.FieldErrors)
  210. message += $"\r\n{item.Key}:{item.Value}(文件第{drErrorInfo.RowIndex}行)";
  211. }
  212. message += "\r\n字段缺失:" + string.Join(",", res.TemplateErrors.Select(m => m.RequireColumnName).ToList());
  213. throw Oops.Oh("导入异常:" + message);
  214. }
  215. return res.Data;
  216. }
  217. /// <summary>
  218. /// 导入Excel数据并错误标记
  219. /// </summary>
  220. /// <typeparam name="T"></typeparam>
  221. /// <param name="file"></param>
  222. /// <param name="importResultCallback"></param>
  223. /// <returns></returns>
  224. public static async Task<ICollection<T>> ImportExcelData<T>([Required] IFormFile file, Func<ImportResult<T>, ImportResult<T>> importResultCallback = null) where T : class, new()
  225. {
  226. IImporter importer = new ExcelImporter();
  227. var resultStream = new MemoryStream();
  228. var res = await importer.Import<T>(file.OpenReadStream(), resultStream, importResultCallback);
  229. resultStream.Seek(0, SeekOrigin.Begin);
  230. var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
  231. App.GetRequiredService<SysCacheService>().Remove(CacheConst.KeyExcelTemp + userId);
  232. App.GetRequiredService<SysCacheService>().Set(CacheConst.KeyExcelTemp + userId, resultStream, TimeSpan.FromMinutes(5));
  233. var message = string.Empty;
  234. if (res.HasError)
  235. {
  236. if (res.Exception != null)
  237. message += $"\r\n{res.Exception.Message}";
  238. foreach (DataRowErrorInfo drErrorInfo in res.RowErrors)
  239. {
  240. int rowNum = drErrorInfo.RowIndex;
  241. foreach (var item in drErrorInfo.FieldErrors)
  242. message += $"\r\n{item.Key}:{item.Value}(文件第{drErrorInfo.RowIndex}行)";
  243. }
  244. if (res.TemplateErrors.Count > 0)
  245. message += "\r\n字段缺失:" + string.Join(",", res.TemplateErrors.Select(m => m.RequireColumnName).ToList());
  246. if (message.Length > 200)
  247. message = message.Substring(0, 200) + "...\r\n异常过多,建议下载错误标记文件查看详细错误信息并重新导入。";
  248. throw Oops.Oh("导入异常:" + message);
  249. }
  250. return res.Data;
  251. }
  252. /// <summary>
  253. /// 导入数据Excel
  254. /// </summary>
  255. /// <typeparam name="T"></typeparam>
  256. /// <param name="file"></param>
  257. /// <returns></returns>
  258. public static async Task<List<T>> ImportExcelDataAsync<T>([Required] IFormFile file) where T : class, new()
  259. {
  260. var sysFileService = App.GetRequiredService<SysFileService>();
  261. var newFile = await sysFileService.UploadFile(new UploadFileInput { File = file });
  262. var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, newFile.FilePath!, newFile.Id + newFile.Suffix);
  263. IImporter importer = new ExcelImporter();
  264. var res = await importer.Import<T>(filePath);
  265. // 删除文件
  266. _ = sysFileService.DeleteFile(new DeleteFileInput { Id = newFile.Id });
  267. if (res == null)
  268. throw Oops.Oh("导入数据为空");
  269. if (res.Exception != null)
  270. throw Oops.Oh("导入异常:" + res.Exception);
  271. if (res.TemplateErrors?.Count > 0)
  272. throw Oops.Oh("模板异常:" + res.TemplateErrors.Select(x => $"[{x.RequireColumnName}]{x.Message}").Join("\n"));
  273. return res.Data.ToList();
  274. }
  275. // 例:List<Dm_ApplyDemo> ls = CommonUtil.ParseList<Dm_ApplyDemoInport, Dm_ApplyDemo>(importResult.Data);
  276. /// <summary>
  277. /// 对象转换 含字典转换
  278. /// </summary>
  279. /// <typeparam name="TSource"></typeparam>
  280. /// <typeparam name="TTarget"></typeparam>
  281. /// <param name="data"></param>
  282. /// <param name="action"></param>
  283. /// <returns></returns>
  284. public static List<TTarget> ParseList<TSource, TTarget>(IEnumerable<TSource> data, Func<TSource, TTarget, TTarget> action = null) where TTarget : new()
  285. {
  286. var propMappings = GetImportPropertMap<TSource, TTarget>();
  287. // 相同属性复制值,字典值转换
  288. var result = new List<TTarget>();
  289. foreach (var item in data)
  290. {
  291. var newData = new TTarget();
  292. foreach (var dict in propMappings)
  293. {
  294. var targeProp = dict.Value.Item3;
  295. if (targeProp != null)
  296. {
  297. var propertyInfo = dict.Value.Item2;
  298. var sourceVal = propertyInfo.GetValue(item, null);
  299. if (sourceVal == null)
  300. continue;
  301. var map = dict.Value.Item1;
  302. if (map != null && map.ContainsKey(sourceVal.ToString()))
  303. {
  304. var newVal = map[sourceVal.ToString()];
  305. targeProp.SetValue(newData, newVal);
  306. }
  307. else
  308. {
  309. if (targeProp.PropertyType.FullName == propertyInfo.PropertyType.FullName)
  310. {
  311. targeProp.SetValue(newData, sourceVal);
  312. }
  313. else
  314. {
  315. var newVal = sourceVal.ToString().ParseTo(targeProp.PropertyType);
  316. targeProp.SetValue(newData, newVal);
  317. }
  318. }
  319. }
  320. }
  321. if (action != null)
  322. newData = action(item, newData);
  323. if (newData != null)
  324. result.Add(newData);
  325. }
  326. return result;
  327. }
  328. /// <summary>
  329. /// 获取导入属性映射
  330. /// </summary>
  331. /// <typeparam name="TSource"></typeparam>
  332. /// <typeparam name="TTarget"></typeparam>
  333. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  334. private static Dictionary<string, Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>> GetImportPropertMap<TSource, TTarget>() where TTarget : new()
  335. {
  336. // 整理导入对象的属性名称,<字典数据,原属性信息,目标属性信息>
  337. var propMappings = new Dictionary<string, Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>>();
  338. var dictService = App.GetRequiredService<SqlSugarRepository<SysDictData>>();
  339. var tSourceProps = typeof(TSource).GetProperties().ToList();
  340. var tTargetProps = typeof(TTarget).GetProperties().ToDictionary(u => u.Name);
  341. foreach (var propertyInfo in tSourceProps)
  342. {
  343. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  344. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  345. {
  346. var targetProp = tTargetProps[attrs.TargetPropName];
  347. var mappingValues = dictService.Context.Queryable<SysDictType, SysDictData>((u, a) =>
  348. new JoinQueryInfos(JoinType.Inner, u.Id == a.DictTypeId))
  349. .Where(u => u.Code == attrs.TypeCode)
  350. .Where((u, a) => u.Status == StatusEnum.Enable && a.Status == StatusEnum.Enable)
  351. .Select((u, a) => new
  352. {
  353. Label = a.Value,
  354. Value = a.Code
  355. }).ToList()
  356. .ToDictionary(u => u.Label, u => u.Value.ParseTo(targetProp.PropertyType));
  357. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>(mappingValues, propertyInfo, targetProp));
  358. }
  359. else
  360. {
  361. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<string, object>, PropertyInfo, PropertyInfo>(
  362. null, propertyInfo, tTargetProps.ContainsKey(propertyInfo.Name) ? tTargetProps[propertyInfo.Name] : null));
  363. }
  364. }
  365. return propMappings;
  366. }
  367. /// <summary>
  368. /// 获取导出属性映射
  369. /// </summary>
  370. /// <typeparam name="TSource"></typeparam>
  371. /// <typeparam name="TTarget"></typeparam>
  372. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  373. private static Dictionary<string, Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>> GetExportPropertMap<TSource, TTarget>() where TTarget : new()
  374. {
  375. // 整理导入对象的属性名称,<字典数据,原属性信息,目标属性信息>
  376. var propMappings = new Dictionary<string, Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>>();
  377. var dictService = App.GetRequiredService<SqlSugarRepository<SysDictData>>();
  378. var targetProps = typeof(TTarget).GetProperties().ToList();
  379. var sourceProps = typeof(TSource).GetProperties().ToDictionary(u => u.Name);
  380. foreach (var propertyInfo in targetProps)
  381. {
  382. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  383. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  384. {
  385. var targetProp = sourceProps[attrs.TargetPropName];
  386. var mappingValues = dictService.Context.Queryable<SysDictType, SysDictData>((u, a) =>
  387. new JoinQueryInfos(JoinType.Inner, u.Id == a.DictTypeId))
  388. .Where(u => u.Code == attrs.TypeCode)
  389. .Where((u, a) => u.Status == StatusEnum.Enable && a.Status == StatusEnum.Enable)
  390. .Select((u, a) => new
  391. {
  392. Label = a.Value,
  393. Value = a.Code
  394. }).ToList()
  395. .ToDictionary(u => u.Value.ParseTo(targetProp.PropertyType), u => u.Label);
  396. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>(mappingValues, targetProp, propertyInfo));
  397. }
  398. else
  399. {
  400. propMappings.Add(propertyInfo.Name, new Tuple<Dictionary<object, string>, PropertyInfo, PropertyInfo>(
  401. null, sourceProps.ContainsKey(propertyInfo.Name) ? sourceProps[propertyInfo.Name] : null, propertyInfo));
  402. }
  403. }
  404. return propMappings;
  405. }
  406. /// <summary>
  407. /// 获取属性映射
  408. /// </summary>
  409. /// <typeparam name="TTarget"></typeparam>
  410. /// <returns>整理导入对象的 属性名称, 字典数据,原属性信息,目标属性信息 </returns>
  411. private static Dictionary<string, Tuple<string, string>> GetExportDicttMap<TTarget>() where TTarget : new()
  412. {
  413. // 整理导入对象的属性名称,目标属性名,字典Code
  414. var propMappings = new Dictionary<string, Tuple<string, string>>();
  415. var tTargetProps = typeof(TTarget).GetProperties();
  416. foreach (var propertyInfo in tTargetProps)
  417. {
  418. var attrs = propertyInfo.GetCustomAttribute<ImportDictAttribute>();
  419. if (attrs != null && !string.IsNullOrWhiteSpace(attrs.TypeCode))
  420. {
  421. propMappings.Add(propertyInfo.Name, new Tuple<string, string>(attrs.TargetPropName, attrs.TypeCode));
  422. }
  423. }
  424. return propMappings;
  425. }
  426. /// <summary>
  427. /// 解析IP地址
  428. /// </summary>
  429. /// <param name="ip"></param>
  430. /// <returns></returns>
  431. public static (string ipLocation, double? longitude, double? latitude) GetIpAddress(string ip)
  432. {
  433. try
  434. {
  435. var ipInfo = IpTool.SearchWithI18N(ip); // 国际化查询,默认中文 中文zh-CN、英文en
  436. var addressList = new List<string>() { ipInfo.Country, ipInfo.Province, ipInfo.City, ipInfo.NetworkOperator };
  437. return (string.Join(" ", addressList.Where(u => u != "0" && !string.IsNullOrWhiteSpace(u)).ToList()), ipInfo.Longitude, ipInfo.Latitude); // 去掉0及空并用空格连接
  438. }
  439. catch
  440. {
  441. // 不做处理
  442. }
  443. return ("未知", 0, 0);
  444. }
  445. /// <summary>
  446. /// 获取客户端设备信息(操作系统+浏览器)
  447. /// </summary>
  448. /// <param name="userAgent"></param>
  449. /// <returns></returns>
  450. public static string GetClientDeviceInfo(string userAgent)
  451. {
  452. try
  453. {
  454. if (userAgent != null)
  455. {
  456. var client = Parser.GetDefault().Parse(userAgent);
  457. if (client.Device.IsSpider)
  458. return "爬虫";
  459. return $"{client.OS.Family} {client.OS.Major} {client.OS.Minor}" +
  460. $"|{client.UA.Family} {client.UA.Major}.{client.UA.Minor} / {client.Device.Family}";
  461. }
  462. }
  463. catch
  464. { }
  465. return "未知";
  466. }
  467. }