Initial_commit_SecMPS_v2
This commit is contained in:
14
api_sqlsugar/VolPro.Core/Utilities/ApiAuthorizeRequire.cs
Normal file
14
api_sqlsugar/VolPro.Core/Utilities/ApiAuthorizeRequire.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public class ApiAuthorizeRequire
|
||||
{
|
||||
public static void Require()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
39
api_sqlsugar/VolPro.Core/Utilities/DateTimeExtension.cs
Normal file
39
api_sqlsugar/VolPro.Core/Utilities/DateTimeExtension.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
using System.IO;
|
||||
using System.Collections;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public static class DateTimeExtension
|
||||
{
|
||||
/// <summary>
|
||||
/// 实现由C# 的时间到 Javascript 的时间的转换
|
||||
/// returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
|
||||
/// </summary>
|
||||
/// <param name="dt"></param>
|
||||
/// <returns></returns>
|
||||
public static double UnixTicks(this DateTime dt)
|
||||
{
|
||||
DateTime d1 = new DateTime(1970, 1, 1);
|
||||
DateTime d2 = dt.AddHours(8).ToUniversalTime();
|
||||
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
|
||||
return ts.TotalMilliseconds;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将毫秒值转成 C# DateTime 类型
|
||||
/// </summary>
|
||||
/// <param name="time"></param>
|
||||
/// <returns></returns>
|
||||
public static DateTime ConvertTime(this long time)
|
||||
{
|
||||
DateTime timeStamp = new DateTime(1970, 1, 1); //得到1970年的时间戳
|
||||
long t = (time + 8 * 60 * 60) * 10000000 + timeStamp.Ticks;
|
||||
DateTime dt = new DateTime(t);
|
||||
return dt;
|
||||
}
|
||||
}
|
||||
}
|
||||
45
api_sqlsugar/VolPro.Core/Utilities/DateTimeHelper.cs
Normal file
45
api_sqlsugar/VolPro.Core/Utilities/DateTimeHelper.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
using System.IO;
|
||||
|
||||
using System.Text;
|
||||
using System;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public class DateTimeHelper
|
||||
{
|
||||
public static string FriendlyDate(DateTime? date)
|
||||
{
|
||||
if (!date.HasValue) return string.Empty;
|
||||
|
||||
string strDate = date.Value.ToString("yyyy-MM-dd");
|
||||
string vDate = string.Empty;
|
||||
if(DateTime.Now.ToString("yyyy-MM-dd")==strDate)
|
||||
{
|
||||
vDate = "今天";
|
||||
}
|
||||
else if (DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") == strDate)
|
||||
{
|
||||
vDate = "明天";
|
||||
}
|
||||
else if (DateTime.Now.AddDays(2).ToString("yyyy-MM-dd") == strDate)
|
||||
{
|
||||
vDate = "后天";
|
||||
}
|
||||
else if (DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") == strDate)
|
||||
{
|
||||
vDate = "昨天";
|
||||
}
|
||||
else if (DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd") == strDate)
|
||||
{
|
||||
vDate = "前天";
|
||||
}
|
||||
else
|
||||
{
|
||||
vDate = strDate;
|
||||
}
|
||||
|
||||
return vDate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
46
api_sqlsugar/VolPro.Core/Utilities/DynamicPropertyBag .cs
Normal file
46
api_sqlsugar/VolPro.Core/Utilities/DynamicPropertyBag .cs
Normal file
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Dynamic;
|
||||
using System.IO;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
/// <summary>
|
||||
/// 动态属性Bag
|
||||
/// </summary>
|
||||
public class DynamicPropertyBag : DynamicObject
|
||||
{
|
||||
private Dictionary<string, object> storage = new Dictionary<string, object>();
|
||||
|
||||
public override bool TryGetMember(GetMemberBinder binder, out object result)
|
||||
{
|
||||
if (storage.ContainsKey(binder.Name))
|
||||
{
|
||||
result = storage[binder.Name];
|
||||
return true;
|
||||
}
|
||||
result = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
public override bool TrySetMember(SetMemberBinder binder, object value)
|
||||
{
|
||||
string key = binder.Name;
|
||||
if (storage.ContainsKey(key))
|
||||
storage[key] = value;
|
||||
else
|
||||
storage.Add(key, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
StringWriter message = new StringWriter();
|
||||
foreach (var item in storage)
|
||||
message.WriteLine("{0}:\t{1}", item.Key, item.Value);
|
||||
return message.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
806
api_sqlsugar/VolPro.Core/Utilities/EPPlusHelper.cs
Normal file
806
api_sqlsugar/VolPro.Core/Utilities/EPPlusHelper.cs
Normal file
@@ -0,0 +1,806 @@
|
||||
using OfficeOpenXml;
|
||||
using OfficeOpenXml.Style;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Data;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using VolPro.Core.DBManager;
|
||||
using VolPro.Core.Extensions;
|
||||
using VolPro.Core.Infrastructure;
|
||||
using VolPro.Entity.DomainModels;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public class EPPlusHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 导入模板(仅限框架导出模板使用)(202.05.07)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="exportColumns">指定导出的列</param>
|
||||
/// <param name="ignoreColumns">忽略不导出的列(如果设置了exportColumns,ignoreColumns不会生效)</param>
|
||||
/// <returns></returns>
|
||||
|
||||
public static WebResponseContent ReadToDataTable<T>(string path,
|
||||
Expression<Func<T, object>> exportColumns = null,
|
||||
List<string> ignoreTemplate = null,
|
||||
Func<string, ExcelWorksheet, ExcelRange, int, int, string> readValue = null,
|
||||
Expression<Func<T, Dictionary<object, string>>> headerMap = null,
|
||||
int importStartRowIndex=1,
|
||||
Expression<Func<T, object>> ignoreSelectValidationColumns = null)
|
||||
{
|
||||
WebResponseContent responseContent = new WebResponseContent();
|
||||
|
||||
FileInfo file = new FileInfo(path);
|
||||
if (!file.Exists) return responseContent.Error("未找到上传的文件", true);
|
||||
|
||||
List<T> entities = new List<T>();
|
||||
using (ExcelPackage package = new ExcelPackage(file))
|
||||
{
|
||||
if (package.Workbook.Worksheets.Count == 0 ||
|
||||
package.Workbook.Worksheets.FirstOrDefault().Dimension.End.Row <= 1)
|
||||
return responseContent.Error("No data");
|
||||
//2020.08.11修复获取表结构信息时,表为别名时查不到数据的问题
|
||||
//typeof(T).GetEntityTableName()
|
||||
List<CellOptions> cellOptions = GetExportColumnInfo(typeof(T).Name, false, false, columns: exportColumns?.GetExpressionToArray());
|
||||
//设置忽略的列
|
||||
if (exportColumns != null)
|
||||
{
|
||||
cellOptions = cellOptions
|
||||
.Where(x => exportColumns.GetExpressionToArray().Select(s => s.ToLower()).Contains(x.ColumnName.ToLower()))
|
||||
.ToList();
|
||||
}
|
||||
else if (ignoreTemplate != null)
|
||||
{
|
||||
cellOptions = cellOptions
|
||||
.Where(x => !ignoreTemplate.Select(s => s.ToLower()).Contains(x.ColumnName.ToLower()))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
Dictionary<string, string> headerMapDic = GetHeaderMap(headerMap);
|
||||
ExcelWorksheet sheetFirst = package.Workbook.Worksheets.FirstOrDefault();
|
||||
|
||||
for (int j = sheetFirst.Dimension.Start.Column, k = sheetFirst.Dimension.End.Column; j <= k; j++)
|
||||
{
|
||||
string columnCNName = sheetFirst.Cells[importStartRowIndex, j].Value?.ToString()?.Trim();
|
||||
if (!string.IsNullOrEmpty(columnCNName))
|
||||
{
|
||||
CellOptions options = null;
|
||||
|
||||
if (headerMapDic != null && headerMapDic.ContainsValue(columnCNName))
|
||||
{
|
||||
string field = headerMapDic.Where(x => x.Value == columnCNName).Select(s => s.Key).FirstOrDefault();
|
||||
options = cellOptions.Where(x => x.ColumnName == field).FirstOrDefault();
|
||||
}
|
||||
else
|
||||
{
|
||||
options = cellOptions.Where(x => x.ColumnCNName.Translator() == columnCNName).FirstOrDefault();
|
||||
}
|
||||
|
||||
if (options == null)
|
||||
{
|
||||
return responseContent.Error("[{$ts}]不是模板中的列".TranslatorReplace(columnCNName, true));
|
||||
}
|
||||
if (options.Index > 0)
|
||||
{
|
||||
return responseContent.Error("[{$ts}]列名重复".TranslatorReplace(columnCNName, true));
|
||||
}
|
||||
options.Index = j;
|
||||
}
|
||||
}
|
||||
if (cellOptions.Exists(x => x.Index == 0))
|
||||
{
|
||||
var errorOps = cellOptions.Where(x => x.Index == 0).Select(s => s.ColumnCNName.Translator() + "," + s.ColumnName);
|
||||
return responseContent.Error($"{"导入文件列未找到字段".Translator()}:{string.Join("; ", errorOps)}");
|
||||
}
|
||||
string[] ignoreSelectValidationFields = new string[] { };
|
||||
if (ignoreSelectValidationColumns != null)
|
||||
{
|
||||
ignoreSelectValidationFields = ignoreSelectValidationColumns.GetExpressionToArray();
|
||||
}
|
||||
|
||||
PropertyInfo[] propertyInfos = typeof(T).GetProperties()
|
||||
.Where(x => cellOptions.Select(s => s.ColumnName).Contains(x.Name))
|
||||
.ToArray();
|
||||
ExcelWorksheet sheet = package.Workbook.Worksheets.FirstOrDefault();
|
||||
for (int m = importStartRowIndex + 1, n = sheet.Dimension.End.Row; m <= n; m++)
|
||||
{
|
||||
T entity = Activator.CreateInstance<T>();
|
||||
for (int j = sheet.Dimension.Start.Column, k = sheet.Dimension.End.Column; j <= k; j++)
|
||||
{
|
||||
//0.1234324小数处理
|
||||
//if (sheet.Cells[m, j].Value is double dbvalue)
|
||||
//{
|
||||
// dbvalue.ToString("0.#####");
|
||||
//}
|
||||
|
||||
string value = sheet.Cells[m, j].Value?.ToString();
|
||||
//2022.06.20增加原生excel读取方法
|
||||
if (readValue != null)
|
||||
{
|
||||
value = readValue(value, sheet, sheet.Cells[m, j], m, j);
|
||||
}
|
||||
|
||||
CellOptions options = cellOptions.Where(x => x.Index == j).FirstOrDefault();
|
||||
PropertyInfo property = propertyInfos.Where(x => x.Name == options.ColumnName).FirstOrDefault();
|
||||
//2021.06.04优化判断
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
if (options.Requierd)
|
||||
{
|
||||
return responseContent.Error("第[{$ts}]行,[{$ts}]验证未通过,不能为空".TranslatorFormat(m, options.ColumnCNName), false);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
//验证字典数据
|
||||
//2020.09.20增加判断数据源是否有值
|
||||
if (!string.IsNullOrEmpty(options.DropNo) && !string.IsNullOrEmpty(value) && !ignoreSelectValidationFields.Contains(property.Name))
|
||||
{
|
||||
if (options.KeyValues == null)
|
||||
{
|
||||
return responseContent.Error("[{$ts}]数据字典缺失".TranslatorFormat(options.ColumnCNName), false);
|
||||
}
|
||||
string key = null;
|
||||
//2022.11.21增加导入多选的支持
|
||||
if ((options.EditType == "selectList" || options.EditType == "checkbox" || options.EditType == "treeSelect") && !string.IsNullOrEmpty(value))
|
||||
{
|
||||
var cellValues = value.Replace(",", ",").Split(",").Where(x => !string.IsNullOrEmpty(x)).ToArray();
|
||||
var keys = options.KeyValues.Where(x => cellValues.Contains(x.Value))
|
||||
.Select(s => s.Key).ToArray();
|
||||
if (cellValues.Length == keys.Length)
|
||||
{
|
||||
key = string.Join(",", keys);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
key = options.KeyValues.Where(x => x.Value == value)
|
||||
.Select(s => s.Key)
|
||||
.FirstOrDefault();
|
||||
}
|
||||
|
||||
if (key == null)//&& options.Requierd
|
||||
{
|
||||
//小于20个字典项,直接提示所有可选value
|
||||
string values = (string.Join(',', options.KeyValues.Take(300).Select(s => s.Value.Translator())));
|
||||
string msg = "第[{$ts}]行,[{$ts}]验证未通过,只能填写[{$ts}]".TranslatorFormat(m, options.ColumnCNName, values);
|
||||
return responseContent.Error("第[{$ts}]行,[{$ts}]验证未通过".TranslatorFormat(m, options.ColumnCNName) + "," + options.ColumnCNName, false);
|
||||
}
|
||||
//将值设置为数据字典的Key,如果导入为是/否字典项,存在表中应该对为1/0
|
||||
value = key;
|
||||
}
|
||||
else if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?))
|
||||
{
|
||||
//2021.06.04增加日期格式处理
|
||||
if (value.Length == 5 && int.TryParse(value, out int days))
|
||||
{
|
||||
property.SetValue(entity, new DateTime(1900, 1, 1).AddDays(days - 2));
|
||||
}
|
||||
else
|
||||
{
|
||||
property.SetValue(entity, value.ChangeType(property.PropertyType));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
//验证导入与实体数据类型是否相同
|
||||
(bool, string, object) result = property.ValidationProperty(value, options.Requierd);
|
||||
|
||||
if (!result.Item1)
|
||||
{
|
||||
return responseContent.Error($"第{m}行[{options.ColumnCNName}]验证未通过,{result.Item2}");
|
||||
}
|
||||
|
||||
property.SetValue(entity, value.ChangeType(property.PropertyType));
|
||||
}
|
||||
entity.SetCreateDefaultVal();
|
||||
entities.Add(entity);
|
||||
}
|
||||
}
|
||||
return responseContent.OK(null, entities);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="table"></param>
|
||||
/// <param name="columnCNName">key为字段名, ValueTuple<string, int>为字段中文名及列宽度</param>
|
||||
/// <param name="dicNos"> List<ValueTuple<string, string, string>>item1列名,item2 字典value,item3字典name </param>
|
||||
/// <returns>返回文件保存的路径</returns>
|
||||
public static string Export(DataTable table, List<CellOptions> cellOptions, string savePath, string fileName)
|
||||
{
|
||||
if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
|
||||
|
||||
//获取所有有值的数据源
|
||||
var dicNoKeys = cellOptions
|
||||
.Where(x => !string.IsNullOrEmpty(x.DropNo) && x.KeyValues != null && x.KeyValues.Keys.Count > 0)
|
||||
.Select(x => new { x.DropNo, x.ColumnName }).Distinct().ToList();
|
||||
|
||||
|
||||
|
||||
using (ExcelPackage package = new ExcelPackage())
|
||||
{
|
||||
var worksheet = package.Workbook.Worksheets.Add("sheet1");
|
||||
for (int i = 0; i < table.Columns.Count; i++)
|
||||
{
|
||||
using (ExcelRange range = worksheet.Cells[1, i + 1])
|
||||
{
|
||||
worksheet.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
|
||||
worksheet.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(Color.Gray); //背景色
|
||||
worksheet.Cells[1, i + 1].Style.Font.Color.SetColor(Color.White);
|
||||
}
|
||||
CellOptions options = cellOptions.Where(x => x.ColumnName == table.Columns[i].ColumnName).FirstOrDefault();
|
||||
if (options != null)
|
||||
{
|
||||
worksheet.Column(i + 1).Width = options.ColumnWidth / 6.00;
|
||||
worksheet.Cells[1, i + 1].Value = options.ColumnCNName;
|
||||
}
|
||||
else
|
||||
{
|
||||
worksheet.Column(i + 1).Width = 15;
|
||||
worksheet.Cells[1, i + 1].Value = table.Columns[i].ColumnName;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < table.Rows.Count; i++)
|
||||
{
|
||||
for (int j = 0; j < table.Columns.Count; j++)
|
||||
{
|
||||
string cellValue = (table.Rows[i][j] ?? "").ToString();
|
||||
if (dicNoKeys.Exists(x => x.ColumnName == table.Columns[j].ColumnName))
|
||||
{
|
||||
cellOptions.Where(x => x.ColumnName == table.Columns[j].ColumnName)
|
||||
.Select(s => s.KeyValues)
|
||||
.FirstOrDefault()
|
||||
.TryGetValue(cellValue, out string result);
|
||||
cellValue = result ?? cellValue;
|
||||
}
|
||||
worksheet.Cells[i + 2, j + 1].Value = cellValue;
|
||||
}
|
||||
}
|
||||
package.SaveAs(new FileInfo(savePath + fileName));
|
||||
}
|
||||
return savePath + fileName;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 下载导出模板(仅限框架导出模板使用)(202.05.07)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="exportColumns">指定导出的列</param>
|
||||
/// <param name="ignoreColumns">忽略不导出的列(如果设置了exportColumns,ignoreColumns不会生效)</param>
|
||||
/// <param name="savePath">导出文件的绝对路径</param>
|
||||
/// <param name="fileName">导出的文件名+后缀,如:123.xlsx</param>
|
||||
/// <returns></returns>
|
||||
public static string ExportTemplate<T>(List<string> exportColumns, List<string> ignoreColumns, string savePath, string fileName,
|
||||
Expression<Func<T, Dictionary<object, string>>> headerMap = null)
|
||||
{
|
||||
return Export<T>(null, exportColumns, ignoreColumns, savePath, fileName, true, headerMap);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 下载导出模板(仅限框架导出模板使用)(202.05.07)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="exportColumns">指定导出的列</param>
|
||||
/// <param name="ignoreColumns">忽略不导出的列(如果设置了exportColumns,ignoreColumns不会生效)</param>
|
||||
/// <param name="savePath">导出文件的绝对路径</param>
|
||||
/// <param name="fileName">导出的文件名+后缀,如:123.xlsx</param>
|
||||
/// <returns></returns>
|
||||
public static string ExportTemplate<T>(Expression<Func<T, object>> exportColumns, List<string> ignoreColumns, string savePath, string fileName,
|
||||
Expression<Func<T, Dictionary<object, string>>> headerMap = null)
|
||||
{
|
||||
return Export<T>(null, exportColumns?.GetExpressionToArray(), ignoreColumns, savePath, fileName, true, headerMap);
|
||||
}
|
||||
/// <summary>
|
||||
/// 下载导出模板(仅限框架导出模板使用)(202.05.07)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="ignoreColumns">忽略不导出的列</param>
|
||||
/// <param name="savePath">导出文件的绝对路径</param>
|
||||
/// <param name="fileName">导出的文件名+后缀,如:123.xlsx</param>
|
||||
/// <returns></returns>
|
||||
public static string ExportTemplate<T>(List<string> ignoreColumns, string savePath, string fileName)
|
||||
{
|
||||
return Export<T>(null, null, ignoreColumns, savePath, fileName, true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 导出excel文件(导入功能里的导出模板也使用的此功能,list传的null,导出的文件只有模板的标题)
|
||||
/// (202.05.07)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="list"></param>
|
||||
/// <param name="cellOptions">对应代码生成器的配置</param>
|
||||
/// <param name="ignore">忽略不导出的字段</param>
|
||||
/// <param name="savePath"></param>
|
||||
/// <param name="fileName"></param>
|
||||
/// <param name="template"></param>
|
||||
/// <returns></returns>
|
||||
public static string Export<T>(List<T> list, Expression<Func<T, object>> ignore, string savePath, string fileName, bool template = false)
|
||||
{
|
||||
return Export(list, null, ignore?.GetExpressionProperty(), savePath, fileName, template);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 导出excel文件(导入功能里的导出模板也使用的此功能,list传的null,导出的文件只有模板的标题)
|
||||
/// (202.05.07)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="list">导出的对象</param>
|
||||
/// <param name="exportColumns">指定导出的列</param>
|
||||
/// <param name="ignoreColumns">忽略不导出的列(如果设置了exportColumns,ignoreColumns不会生效)</param>
|
||||
/// <param name="savePath">保存路径</param>
|
||||
/// <param name="fileName">保存的文件名</param>
|
||||
/// <param name="template">是否为下载模板</param>
|
||||
/// <returns></returns>
|
||||
public static string Export<T>(List<T> list, IEnumerable<string> exportColumns, IEnumerable<string> ignoreColumns, string savePath,
|
||||
string fileName, bool template = false, Expression<Func<T, Dictionary<object, string>>> headerMap = null)
|
||||
{
|
||||
if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
|
||||
|
||||
//获取代码生成器对应的配置信息
|
||||
// List<CellOptions> cellOptions = GetExportColumnInfo(typeof(T).GetEntityTableName(), template);
|
||||
//2020.06.02修复使用表别名时读取不到配置信息
|
||||
List<CellOptions> cellOptions = GetExportColumnInfo(typeof(T).Name, template, columns: exportColumns?.ToArray());
|
||||
string fullPath = savePath + fileName;
|
||||
//获取所有有值的数据源
|
||||
var dicNoKeys = cellOptions
|
||||
.Where(x => !string.IsNullOrEmpty(x.DropNo) && x.KeyValues != null && x.KeyValues.Keys.Count > 0)
|
||||
.Select(x => new { x.DropNo, x.ColumnName, x.SearchType, x.EditType }).Distinct().ToList();
|
||||
//2021.01.24修复多选类型,导出excel文件没有转换数据源的问题
|
||||
var selectList = dicNoKeys.Where(x => x.SearchType == "checkbox" || x.SearchType == "selectList" || x.SearchType == "treeSelect" || x.EditType == "checkbox" || x.EditType == "selectList" || x.EditType == "treeSelect")
|
||||
.Select(s => s.ColumnName).ToArray();
|
||||
|
||||
List<PropertyInfo> propertyInfo = null;
|
||||
|
||||
/*导出时,代码生成器中的表配置信息Sys_TableInfo/Sys_TableColumn必须与当前数据库相同,否则导出来可能没有数据*/
|
||||
|
||||
//2020.06.02优化读取导出列配置信息
|
||||
//导出指定的列
|
||||
//如果指定了导出的标题列,忽略的标题列不再起作用
|
||||
if (exportColumns != null && exportColumns.Count() > 0)
|
||||
{
|
||||
propertyInfo = new List<PropertyInfo>();
|
||||
var properties = typeof(T).GetProperties();
|
||||
foreach (var name in exportColumns)
|
||||
{
|
||||
var property = properties.Where(x => x.Name.ToLower() == name.ToLower()).FirstOrDefault();
|
||||
if (property != null)
|
||||
{
|
||||
propertyInfo.Add(property);
|
||||
}
|
||||
}
|
||||
//propertyInfo =
|
||||
// typeof(T).GetProperties()
|
||||
// .Where(x => exportColumns.Select(g => g.ToLower()).Contains(x.Name.ToLower())).ToList();
|
||||
////.Where(x => cellOptions.Select(s => s.ColumnName) //获取代码生成器配置的列
|
||||
////.Contains(x.Name)).ToList();
|
||||
}
|
||||
else if (ignoreColumns != null && ignoreColumns.Count() > 0)
|
||||
{
|
||||
propertyInfo = typeof(T).GetProperties()
|
||||
.Where(x => !ignoreColumns.Select(g => g.ToLower()).Contains(x.Name.ToLower()))
|
||||
.Where(x => cellOptions.Select(s => s.ColumnName).Contains(x.Name)) //获取代码生成器配置的列
|
||||
.ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
//默认导出代码生成器中配置【是否显示】=是的列
|
||||
propertyInfo = typeof(T).GetProperties()
|
||||
.Where(x => cellOptions.Select(s => s.ColumnName).Contains(x.Name)) //获取代码生成器配置的列
|
||||
.ToList();
|
||||
/*
|
||||
* 如果propertyInfo查出来的长度=0
|
||||
* 1、代码生成器中的配置信息是否同步到当前数据库
|
||||
* 2、代码生成器中的配置列名与model的字段是否大小写一致
|
||||
*/
|
||||
}
|
||||
string[] dateArr = null;
|
||||
if (!template)
|
||||
{
|
||||
dateArr = propertyInfo.Where(x => x.PropertyType == typeof(DateTime)
|
||||
|| x.PropertyType == typeof(DateTime?))
|
||||
.Select(s => s.Name).ToArray();
|
||||
}
|
||||
Dictionary<string, string> headerMapDic = GetHeaderMap(headerMap);
|
||||
const long imageLimitBytes = 10 * 1024 * 1024; // 10MB
|
||||
long embeddedImageBytes = 0;
|
||||
using (ExcelPackage package = new ExcelPackage())
|
||||
{
|
||||
var worksheet = package.Workbook.Worksheets.Add("sheet1");
|
||||
for (int i = 0; i < propertyInfo.Count; i++)
|
||||
{
|
||||
string columnName = propertyInfo[i].Name;
|
||||
using (ExcelRange range = worksheet.Cells[1, i + 1])
|
||||
{
|
||||
worksheet.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
|
||||
//默认灰色背景,白色字体
|
||||
Color backgroundColor = Color.Gray;
|
||||
//字体颜色
|
||||
Color fontColor = Color.White;
|
||||
//下载模板并且是必填项,将表格设置为黄色
|
||||
if (template)
|
||||
{
|
||||
fontColor = Color.Black;
|
||||
if (cellOptions.Exists(x => x.ColumnName == columnName && x.Requierd))
|
||||
{
|
||||
backgroundColor = Color.Yellow; //黄色必填
|
||||
}
|
||||
else
|
||||
{
|
||||
backgroundColor = Color.White;
|
||||
}
|
||||
}
|
||||
worksheet.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(backgroundColor); //背景色
|
||||
worksheet.Cells[1, i + 1].Style.Font.Color.SetColor(fontColor);//字体颜色
|
||||
}
|
||||
CellOptions options = cellOptions.Where(x => x.ColumnName == columnName).FirstOrDefault();
|
||||
if (options == null)
|
||||
{
|
||||
columnName = propertyInfo[i].GetDisplayName();
|
||||
}
|
||||
worksheet.Column(i + 1).Width = options == null ? 15 : options.ColumnWidth / 6.00;
|
||||
|
||||
if (headerMapDic != null && headerMapDic.TryGetValue(columnName, out string name))
|
||||
{
|
||||
columnName = name;
|
||||
}
|
||||
else if (options != null)
|
||||
{
|
||||
columnName = options.ColumnCNName;
|
||||
}
|
||||
worksheet.Cells[1, i + 1].Value = columnName.Translator();
|
||||
}
|
||||
//下载模板直接返回
|
||||
if (template)
|
||||
{
|
||||
package.SaveAs(new FileInfo(fullPath));
|
||||
return fullPath;
|
||||
}
|
||||
//2021.01.24修复多选类型,导出excel文件没有转换数据源的问题
|
||||
IEnumerable<string> GetListValues(string cellValues, string propertyName)
|
||||
{
|
||||
var values = cellValues.Split(",");
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
{
|
||||
cellOptions.Where(x => x.ColumnName == propertyName)
|
||||
.Select(s => s.KeyValues)
|
||||
.FirstOrDefault()
|
||||
.TryGetValue(values[i], out string result);
|
||||
yield return result ?? values[i];
|
||||
}
|
||||
|
||||
}
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
for (int j = 0; j < propertyInfo.Count; j++)
|
||||
{
|
||||
object cellValue = null;
|
||||
// 6year年、4date年月日、5month年月
|
||||
int? viewType = cellOptions.Where(c => c.ColumnName == propertyInfo[j].Name).Select(s => s.ViewType).FirstOrDefault();
|
||||
if (viewType == 6 || viewType == 5 || viewType == 4)
|
||||
{
|
||||
cellValue = propertyInfo[j].GetValue(list[i]);
|
||||
if (cellValue != null)
|
||||
{
|
||||
if (viewType == 6)
|
||||
{
|
||||
cellValue = ((DateTime)cellValue).Year;
|
||||
}
|
||||
else if (viewType == 5)
|
||||
{
|
||||
cellValue = ((DateTime)cellValue).ToString("yyyy-MM");
|
||||
}
|
||||
else
|
||||
{
|
||||
cellValue = ((DateTime)cellValue).ToString("yyyy-MM-dd");
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (dateArr != null && dateArr.Contains(propertyInfo[j].Name))
|
||||
{
|
||||
object value = propertyInfo[j].GetValue(list[i]);
|
||||
cellValue = value == null ? "" : ((DateTime)value).ToString("yyyy-MM-dd HH:mm:sss");
|
||||
}
|
||||
else
|
||||
{
|
||||
cellValue = propertyInfo[j].GetValue(list[i]);
|
||||
}
|
||||
if (cellValue != null && dicNoKeys.Exists(x => x.ColumnName == propertyInfo[j].Name))
|
||||
{
|
||||
//2021.01.24修复多选类型,导出excel文件没有转换数据源的问题
|
||||
if (selectList.Contains(propertyInfo[j].Name))
|
||||
{
|
||||
cellValue = string.Join(",", GetListValues(cellValue.ToString(), propertyInfo[j].Name));
|
||||
}
|
||||
else
|
||||
{
|
||||
cellOptions.Where(x => x.ColumnName == propertyInfo[j].Name)
|
||||
.Select(s => s.KeyValues)
|
||||
.FirstOrDefault()
|
||||
.TryGetValue(cellValue.ToString(), out string result);
|
||||
cellValue = result ?? cellValue;
|
||||
}
|
||||
|
||||
}
|
||||
//图片导出(直接插入图片,优先使用本地/相对路径;累计超过10MB后改为链接)
|
||||
if (viewType == 1 && cellValue != null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
{
|
||||
string imgPath = cellValue.ToString();
|
||||
if (!string.IsNullOrWhiteSpace(imgPath))
|
||||
{
|
||||
bool isHttp = imgPath.StartsWith("http", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// 相对或本地路径:转换为绝对路径后嵌入图片(总大小超 10MB 则改为链接)
|
||||
if (!isHttp)
|
||||
{
|
||||
imgPath = ("".MapPath(true) + "\\" + imgPath).ReplacePath();
|
||||
if (File.Exists(imgPath))
|
||||
{
|
||||
var fileInfo = new FileInfo(imgPath);
|
||||
long imgBytes = fileInfo.Length;
|
||||
bool canEmbed = embeddedImageBytes + imgBytes <= imageLimitBytes;
|
||||
|
||||
if (canEmbed)
|
||||
{
|
||||
var picture = worksheet.Drawings.AddPicture($"img_{i}_{j}_{Guid.NewGuid():N}", fileInfo);
|
||||
// EPPlus 坐标基于 0;数据区行号 i+2,列号 j+1
|
||||
picture.SetPosition(i + 1, 1, j, 1); // 向下/右偏移 1 像素,避免覆盖边框
|
||||
picture.SetSize(80, 80); // 统一缩放到 80x80 像素
|
||||
|
||||
// 适配行高/列宽,避免图片被裁剪
|
||||
double targetRowHeight = 60; // 点
|
||||
if (worksheet.Row(i + 2).Height < targetRowHeight)
|
||||
{
|
||||
worksheet.Row(i + 2).Height = targetRowHeight;
|
||||
}
|
||||
double targetColWidth = 15; // 约等于常规宽度,必要时可调整
|
||||
if (worksheet.Column(j + 1).Width < targetColWidth)
|
||||
{
|
||||
worksheet.Column(j + 1).Width = targetColWidth;
|
||||
}
|
||||
|
||||
worksheet.Cells[i + 2, j + 1].Value = null; // 清空文字
|
||||
embeddedImageBytes += imgBytes;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 累计大小超过限制:改用文件超链接展示
|
||||
var fileUri = new Uri(fileInfo.FullName);
|
||||
worksheet.Cells[i + 2, j + 1].Hyperlink = fileUri;
|
||||
worksheet.Cells[i + 2, j + 1].Value = Path.GetFileName(imgPath);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 文件不存在则退回原值,至少保留可见信息
|
||||
worksheet.Cells[i + 2, j + 1].Value = cellValue;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 网络路径暂不下载,保底用超链接展示
|
||||
if (Uri.TryCreate(imgPath, UriKind.Absolute, out Uri uri))
|
||||
{
|
||||
worksheet.Cells[i + 2, j + 1].Hyperlink = uri;
|
||||
worksheet.Cells[i + 2, j + 1].Value = Path.GetFileName(imgPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (propertyInfo[j].PropertyType == typeof(long) || propertyInfo[j].PropertyType == typeof(long?))
|
||||
{
|
||||
worksheet.Cells[i + 2, j + 1].Style.Numberformat.Format = "@";
|
||||
cellValue = cellValue?.ToString();
|
||||
}
|
||||
worksheet.Cells[i + 2, j + 1].Value = cellValue;
|
||||
}
|
||||
}
|
||||
package.SaveAs(new FileInfo(fullPath));
|
||||
}
|
||||
return fullPath;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取导出的列的数据信息
|
||||
/// </summary>
|
||||
/// <param name="tableName"></param>
|
||||
/// <param name="temlate">是否为下载模板</param>
|
||||
/// filterKeyValue是否过滤Key相同的数据
|
||||
/// <returns></returns>
|
||||
private static List<CellOptions> GetExportColumnInfo(string tableName, bool temlate = false, bool filterKeyValue = true, string[] columns = null)
|
||||
{
|
||||
//&& x.IsDisplay == 1&&x.IsReadDataset==0只导出代码生器中设置为显示并且不是只读的列,可根据具体业务设置导出列
|
||||
// && x.IsReadDataset == 0
|
||||
//2020.06.02增加不区分大表名大小写: 原因mysql可能是表名是小写,但生成model的时候强制大写
|
||||
//x => x.TableName.ToLower() == tableName.ToLower()
|
||||
var query = DBServerProvider.DbContext.Set<Sys_TableColumn>().Where(x => x.TableName.ToLower() == tableName.ToLower());
|
||||
if (columns != null && columns.Length > 0)
|
||||
{
|
||||
query = query.Where(x => columns.Contains(x.ColumnName));
|
||||
}
|
||||
else
|
||||
{
|
||||
query = query.Where(x => x.IsDisplay == 1);
|
||||
}
|
||||
List<CellOptions> cellOptions = query.OrderByDescending(x => x.OrderNo).Select(c => new CellOptions()
|
||||
{
|
||||
ColumnName = c.ColumnName,
|
||||
ColumnCNName = c.ColumnCnName,
|
||||
DropNo = c.DropNo,
|
||||
Requierd = c.IsNull > 0 ? false : true,
|
||||
ColumnWidth = c.ColumnWidth ?? 90,
|
||||
EditType = c.EditType,
|
||||
SearchType = c.SearchType,
|
||||
//{ key: 1, value: 'img' },
|
||||
// { key: 2, value: 'excel' },
|
||||
// { key: 3, value: 'file' },
|
||||
// { key: 6, value: 'year(年)' },
|
||||
// { key: 4, value: 'date(年月日)' },
|
||||
// { key: 5, value: 'month(年月)' }
|
||||
ViewType = c.IsImage
|
||||
|
||||
}).ToList();
|
||||
|
||||
|
||||
if (temlate) return cellOptions;
|
||||
|
||||
var dicNos = cellOptions.Where(x => !string.IsNullOrEmpty(x.DropNo)).Select(c => c.DropNo);
|
||||
|
||||
if (dicNos.Count() == 0) return cellOptions;
|
||||
|
||||
var dictionaries = DictionaryManager.GetDictionaries(dicNos);
|
||||
//获取绑定字典数据源下拉框的值
|
||||
foreach (string dicNo in dicNos.Distinct())
|
||||
{
|
||||
Dictionary<string, string> keyValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
List<Sys_DictionaryList> dictionaryLists = dictionaries
|
||||
.Where(x => x.DicNo == dicNo && x.Sys_DictionaryList != null)
|
||||
.Select(s => s.Sys_DictionaryList).FirstOrDefault();
|
||||
if (dictionaryLists == null || dictionaryLists.Count == 0) continue;
|
||||
foreach (var item in dictionaryLists)
|
||||
{
|
||||
////filterKeyValue为true过滤keyvalue相不的项,key==value相同的则不处理
|
||||
if (filterKeyValue && item.DicName == item.DicValue) continue;
|
||||
if (keyValues.ContainsKey(item.DicValue)) continue;
|
||||
keyValues.Add(item.DicValue, item.DicName);
|
||||
}
|
||||
|
||||
foreach (CellOptions options in cellOptions.Where(x => x.DropNo == dicNo))
|
||||
{
|
||||
options.KeyValues = keyValues;
|
||||
}
|
||||
}
|
||||
return cellOptions;
|
||||
}
|
||||
|
||||
public static string ExportGeneralExcel(
|
||||
List<Dictionary<string, object>> rows,
|
||||
string fileName,
|
||||
string path = null,
|
||||
Action<ExcelWorksheet, int, int, object> onFillCell = null,
|
||||
Action<ExcelWorksheet> saveBefore = null)
|
||||
{
|
||||
return ExportGeneralExcel(rows.Select(item => item as IDictionary<string, object>).ToList(), fileName, path, onFillCell, saveBefore);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 2021.01.10增加通过excel导出功能
|
||||
/// </summary>
|
||||
/// <param name="rows"></param>
|
||||
/// <param name="fileName"></param>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="onFillCell"></param>
|
||||
/// <param name="saveBefore"></param>
|
||||
/// <returns></returns>
|
||||
public static string ExportGeneralExcel(
|
||||
List<IDictionary<string, object>> rows,
|
||||
string fileName,
|
||||
string path = null,
|
||||
Action<ExcelWorksheet, int, int, object> onFillCell = null,
|
||||
Action<ExcelWorksheet> saveBefore = null)
|
||||
{
|
||||
path = path ?? $"Download/ExcelExport/{DateTime.Now.ToString("yyyyyMMdd")}/";
|
||||
string fullPath = path.MapPath();
|
||||
fileName = Guid.NewGuid() + "_" + fileName;
|
||||
if (!Directory.Exists(fullPath)) Directory.CreateDirectory(fullPath);
|
||||
|
||||
using (ExcelPackage package = new ExcelPackage())
|
||||
{
|
||||
var worksheet = package.Workbook.Worksheets.Add("sheet1");
|
||||
int j = 0;
|
||||
foreach (var item in rows[0])
|
||||
{
|
||||
object cellValue = item.Key;
|
||||
|
||||
int i = 0;
|
||||
worksheet.Cells[1 + i, j + 1].Value = cellValue;
|
||||
//worksheet.Column(j + 1).Width = 11;
|
||||
worksheet.Row(i + 1).Height = 20;//设置行高
|
||||
var style = worksheet.Cells[i + 1, j + 1].Style;
|
||||
style.Fill.PatternType = ExcelFillStyle.Solid;
|
||||
style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//水平居中
|
||||
style.VerticalAlignment = ExcelVerticalAlignment.Center;//垂直剧中
|
||||
style.Font.Bold = true;//字体为粗体
|
||||
//style
|
||||
style.Fill.BackgroundColor.SetColor(Color.FromArgb(216, 216, 216));//背景色
|
||||
style.Border.BorderAround(ExcelBorderStyle.Thin, Color.FromArgb(191, 191, 191));//边框
|
||||
|
||||
onFillCell?.Invoke(worksheet, i, j, cellValue);
|
||||
j++;
|
||||
}
|
||||
for (int i = 0; i < rows.Count; i++)
|
||||
{
|
||||
var row = rows[i];
|
||||
j = 0;
|
||||
foreach (var item in row)
|
||||
{
|
||||
object cellValue = item.Value;
|
||||
worksheet.Cells[i + 2, j + 1].Value = cellValue;
|
||||
|
||||
onFillCell?.Invoke(worksheet, i + 1, j, cellValue);
|
||||
j++;
|
||||
}
|
||||
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
|
||||
for (var col = 1; col <= worksheet.Dimension.End.Column; col++)
|
||||
{
|
||||
worksheet.Column(col).Width = worksheet.Column(col).Width + 2;
|
||||
}
|
||||
}
|
||||
saveBefore?.Invoke(worksheet);
|
||||
package.SaveAs(new FileInfo(fullPath + fileName));
|
||||
}
|
||||
return path + fileName;
|
||||
}
|
||||
private static Dictionary<string, string> GetHeaderMap<T>(Expression<Func<T, Dictionary<object, string>>> headerMap = null)
|
||||
{
|
||||
if (headerMap == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
Dictionary<string, string> headerMapDic = headerMapDic = new Dictionary<string, string>();
|
||||
|
||||
foreach (var exp in ((ListInitExpression)headerMap.Body).Initializers)
|
||||
{
|
||||
string key = exp.Arguments[0] is MemberExpression ?
|
||||
(exp.Arguments[0] as MemberExpression).Member.Name.ToString()
|
||||
: ((exp.Arguments[0] as UnaryExpression).Operand as MemberExpression).Member.Name;
|
||||
headerMapDic.Add(key, ((exp.Arguments[1] as ConstantExpression).Value.ToString()));
|
||||
}
|
||||
return headerMapDic;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public class CellOptions
|
||||
{
|
||||
public string ColumnName { get; set; }//导出表的列
|
||||
public string ColumnCNName { get; set; }//导出列的中文名
|
||||
public string DropNo { get; set; }//字典编号
|
||||
public int ColumnWidth { get; set; }//导出列的宽度,代码生成维护的宽度
|
||||
public bool Requierd { get; set; } //是否必填
|
||||
public int Index { get; set; }//列所在模板的序号(导入用)
|
||||
//2021.01.24修复多选类型,导出excel文件没有转换数据源的问题
|
||||
public string EditType { get; set; }
|
||||
public string SearchType { get; set; }
|
||||
public int? ViewType { get; set; }
|
||||
//对应字典项维护的Key,Value
|
||||
public Dictionary<string, string> KeyValues { get; set; }
|
||||
//public string Value { get; set; } //对应字典项维护的Value
|
||||
//public string Name { get; set; } //对应字典项显示的名称
|
||||
}
|
||||
}
|
||||
339
api_sqlsugar/VolPro.Core/Utilities/FileHelper.cs
Normal file
339
api_sqlsugar/VolPro.Core/Utilities/FileHelper.cs
Normal file
@@ -0,0 +1,339 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using VolPro.Core.Extensions;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public class FileHelper
|
||||
{
|
||||
private static object _filePathObj = new object();
|
||||
|
||||
/// <summary>
|
||||
/// 通过迭代器读取平面文件行内容(必须是带有\r\n换行的文件,百万行以上的内容读取效率存在问题,适用于100M左右文件,行100W内,超出的会有卡顿)
|
||||
/// </summary>
|
||||
/// <param name="fullPath">文件全路径</param>
|
||||
/// <param name="page">分页页数</param>
|
||||
/// <param name="pageSize">分页大小</param>
|
||||
/// <param name="seekEnd"> 是否最后一行向前读取,默认从前向后读取</param>
|
||||
/// <returns></returns>
|
||||
public static IEnumerable<string> ReadPageLine(string fullPath, int page, int pageSize, bool seekEnd = false)
|
||||
{
|
||||
if (page <= 0)
|
||||
{
|
||||
page = 1;
|
||||
}
|
||||
fullPath = fullPath.ReplacePath();
|
||||
var lines = File.ReadLines(fullPath, Encoding.UTF8);
|
||||
if (seekEnd)
|
||||
{
|
||||
int lineCount = lines.Count();
|
||||
int linPageCount = (int)Math.Ceiling(lineCount / (pageSize * 1.00));
|
||||
//超过总页数,不处理
|
||||
if (page > linPageCount)
|
||||
{
|
||||
page = 0;
|
||||
pageSize = 0;
|
||||
}
|
||||
else if (page == linPageCount)//最后一页,取最后一页剩下所有的行
|
||||
{
|
||||
pageSize = lineCount - (page - 1) * pageSize;
|
||||
if (page == 1)
|
||||
{
|
||||
page = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
page = lines.Count() - page * pageSize;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
page = lines.Count() - page * pageSize;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
page = (page - 1) * pageSize;
|
||||
}
|
||||
lines = lines.Skip(page).Take(pageSize);
|
||||
|
||||
var enumerator = lines.GetEnumerator();
|
||||
int count = 1;
|
||||
while (enumerator.MoveNext() || count <= pageSize)
|
||||
{
|
||||
yield return enumerator.Current;
|
||||
count++;
|
||||
}
|
||||
enumerator.Dispose();
|
||||
}
|
||||
public static bool FileExists(string path)
|
||||
{
|
||||
return File.Exists(path.ReplacePath());
|
||||
}
|
||||
|
||||
public static string GetCurrentDownLoadPath()
|
||||
{
|
||||
return ("Download\\").MapPath();
|
||||
}
|
||||
|
||||
public static bool DirectoryExists(string path)
|
||||
{
|
||||
return Directory.Exists(path.ReplacePath());
|
||||
}
|
||||
|
||||
|
||||
public static string Read_File(string fullpath, string filename, string suffix)
|
||||
{
|
||||
return ReadFile((fullpath + "\\" + filename + suffix).MapPath());
|
||||
}
|
||||
public static string ReadFile(string fullName)
|
||||
{
|
||||
// Encoding code = Encoding.GetEncoding(); //Encoding.GetEncoding("gb2312");
|
||||
string temp = fullName.MapPath().ReplacePath();
|
||||
string str = "";
|
||||
if (!File.Exists(temp))
|
||||
{
|
||||
return str;
|
||||
}
|
||||
StreamReader sr = null;
|
||||
try
|
||||
{
|
||||
sr = new StreamReader(temp);
|
||||
str = sr.ReadToEnd(); // 读取文件
|
||||
}
|
||||
catch { }
|
||||
sr?.Close();
|
||||
sr?.Dispose();
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 取后缀名
|
||||
/// </summary>
|
||||
/// <param name="filename">文件名</param>
|
||||
/// <returns>.gif|.html格式</returns>
|
||||
public static string GetPostfixStr(string filename)
|
||||
{
|
||||
int start = filename.LastIndexOf(".");
|
||||
int length = filename.Length;
|
||||
string postfix = filename.Substring(start, length - start);
|
||||
return postfix;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="path">路径 </param>
|
||||
/// <param name="fileName">文件名</param>
|
||||
/// <param name="content">写入的内容</param>
|
||||
/// <param name="appendToLast">是否将内容添加到未尾,默认不添加</param>
|
||||
public static void WriteFile(string path, string fileName, string content, bool appendToLast = false)
|
||||
{
|
||||
path = path.ReplacePath();
|
||||
fileName = fileName.ReplacePath();
|
||||
if (!Directory.Exists(path))//如果不存在就创建file文件夹
|
||||
Directory.CreateDirectory(path);
|
||||
|
||||
using (FileStream stream = File.Open(path + fileName, FileMode.OpenOrCreate, FileAccess.Write))
|
||||
{
|
||||
byte[] by = Encoding.Default.GetBytes(content);
|
||||
if (appendToLast)
|
||||
{
|
||||
stream.Position = stream.Length;
|
||||
}
|
||||
else
|
||||
{
|
||||
stream.SetLength(0);
|
||||
}
|
||||
stream.Write(by, 0, by.Length);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 追加文件
|
||||
/// </summary>
|
||||
/// <param name="Path">文件路径</param>
|
||||
/// <param name="strings">内容</param>
|
||||
public static void FileAdd(string Path, string strings)
|
||||
{
|
||||
StreamWriter sw = File.AppendText(Path.ReplacePath());
|
||||
sw.Write(strings);
|
||||
sw.Flush();
|
||||
sw.Close();
|
||||
sw.Dispose();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 拷贝文件
|
||||
/// </summary>
|
||||
/// <param name="OrignFile">原始文件</param>
|
||||
/// <param name="NewFile">新文件路径</param>
|
||||
public static void FileCoppy(string OrignFile, string NewFile)
|
||||
{
|
||||
File.Copy(OrignFile.ReplacePath(), NewFile.ReplacePath(), true);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 删除文件
|
||||
/// </summary>
|
||||
/// <param name="Path">路径</param>
|
||||
public static void FileDel(string Path)
|
||||
{
|
||||
File.Delete(Path.ReplacePath());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 移动文件
|
||||
/// </summary>
|
||||
/// <param name="OrignFile">原始路径</param>
|
||||
/// <param name="NewFile">新路径</param>
|
||||
public static void FileMove(string OrignFile, string NewFile)
|
||||
{
|
||||
File.Move(OrignFile.ReplacePath(), NewFile.ReplacePath());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在当前目录下创建目录
|
||||
/// </summary>
|
||||
/// <param name="OrignFolder">当前目录</param>
|
||||
/// <param name="NewFloder">新目录</param>
|
||||
public static void FolderCreate(string OrignFolder, string NewFloder)
|
||||
{
|
||||
Directory.SetCurrentDirectory(OrignFolder.ReplacePath());
|
||||
Directory.CreateDirectory(NewFloder.ReplacePath());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建文件夹
|
||||
/// </summary>
|
||||
/// <param name="Path"></param>
|
||||
public static void FolderCreate(string Path)
|
||||
{
|
||||
// 判断目标目录是否存在如果不存在则新建之
|
||||
if (!Directory.Exists(Path.ReplacePath()))
|
||||
Directory.CreateDirectory(Path.ReplacePath());
|
||||
}
|
||||
|
||||
|
||||
public static void FileCreate(string Path)
|
||||
{
|
||||
FileInfo CreateFile = new FileInfo(Path.ReplacePath()); //创建文件
|
||||
if (!CreateFile.Exists)
|
||||
{
|
||||
FileStream FS = CreateFile.Create();
|
||||
FS.Close();
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 递归删除文件夹目录及文件
|
||||
/// </summary>
|
||||
/// <param name="dir"></param>
|
||||
/// <returns></returns>
|
||||
public static void DeleteFolder(string dir)
|
||||
{
|
||||
dir = dir.ReplacePath();
|
||||
if (Directory.Exists(dir)) //如果存在这个文件夹删除之
|
||||
{
|
||||
foreach (string d in Directory.GetFileSystemEntries(dir))
|
||||
{
|
||||
if (File.Exists(d))
|
||||
File.Delete(d); //直接删除其中的文件
|
||||
else
|
||||
DeleteFolder(d); //递归删除子文件夹
|
||||
}
|
||||
Directory.Delete(dir, true); //删除已空文件夹
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 指定文件夹下面的所有内容copy到目标文件夹下面
|
||||
/// </summary>
|
||||
/// <param name="srcPath">原始路径</param>
|
||||
/// <param name="aimPath">目标文件夹</param>
|
||||
public static void CopyDir(string srcPath, string aimPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
aimPath = aimPath.ReplacePath();
|
||||
// 检查目标目录是否以目录分割字符结束如果不是则添加之
|
||||
if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
|
||||
aimPath += Path.DirectorySeparatorChar;
|
||||
// 判断目标目录是否存在如果不存在则新建之
|
||||
if (!Directory.Exists(aimPath))
|
||||
Directory.CreateDirectory(aimPath);
|
||||
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
|
||||
//如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
|
||||
//string[] fileList = Directory.GetFiles(srcPath);
|
||||
string[] fileList = Directory.GetFileSystemEntries(srcPath.ReplacePath());
|
||||
//遍历所有的文件和目录
|
||||
foreach (string file in fileList)
|
||||
{
|
||||
//先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
|
||||
|
||||
if (Directory.Exists(file))
|
||||
CopyDir(file, aimPath + Path.GetFileName(file));
|
||||
//否则直接Copy文件
|
||||
else
|
||||
File.Copy(file, aimPath + Path.GetFileName(file), true);
|
||||
}
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
throw new Exception(ee.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取文件夹大小
|
||||
/// </summary>
|
||||
/// <param name="dirPath">文件夹路径</param>
|
||||
/// <returns></returns>
|
||||
public static long GetDirectoryLength(string dirPath)
|
||||
{
|
||||
dirPath = dirPath.ReplacePath();
|
||||
if (!Directory.Exists(dirPath))
|
||||
return 0;
|
||||
long len = 0;
|
||||
DirectoryInfo di = new DirectoryInfo(dirPath);
|
||||
foreach (FileInfo fi in di.GetFiles())
|
||||
{
|
||||
len += fi.Length;
|
||||
}
|
||||
DirectoryInfo[] dis = di.GetDirectories();
|
||||
if (dis.Length > 0)
|
||||
{
|
||||
for (int i = 0; i < dis.Length; i++)
|
||||
{
|
||||
len += GetDirectoryLength(dis[i].FullName);
|
||||
}
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定文件详细属性
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件详细路径</param>
|
||||
/// <returns></returns>
|
||||
public static string GetFileAttibe(string filePath)
|
||||
{
|
||||
string str = "";
|
||||
filePath = filePath.ReplacePath();
|
||||
System.IO.FileInfo objFI = new System.IO.FileInfo(filePath);
|
||||
str += "详细路径:" + objFI.FullName + "<br>文件名称:" + objFI.Name + "<br>文件长度:" + objFI.Length.ToString() + "字节<br>创建时间" + objFI.CreationTime.ToString() + "<br>最后访问时间:" + objFI.LastAccessTime.ToString() + "<br>修改时间:" + objFI.LastWriteTime.ToString() + "<br>所在目录:" + objFI.DirectoryName + "<br>扩展名:" + objFI.Extension;
|
||||
return str;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace VolPro.Core.Utilities.GatewayApiHelper
|
||||
{
|
||||
internal class GatewayService
|
||||
{
|
||||
}
|
||||
}
|
||||
19
api_sqlsugar/VolPro.Core/Utilities/HttpContext.cs
Normal file
19
api_sqlsugar/VolPro.Core/Utilities/HttpContext.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public static class HttpContext
|
||||
{
|
||||
private static IHttpContextAccessor _accessor;
|
||||
|
||||
public static Microsoft.AspNetCore.Http.HttpContext Current => _accessor.HttpContext;
|
||||
|
||||
internal static void Configure(IHttpContextAccessor accessor)
|
||||
{
|
||||
_accessor = accessor;
|
||||
}
|
||||
}
|
||||
}
|
||||
70
api_sqlsugar/VolPro.Core/Utilities/HttpManager.cs
Normal file
70
api_sqlsugar/VolPro.Core/Utilities/HttpManager.cs
Normal file
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public class HttpManager
|
||||
{
|
||||
//public static Task<string> HttpPostAsync(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
|
||||
//{
|
||||
// HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||||
// request.Method = "POST";
|
||||
// if (!string.IsNullOrEmpty(contentType))
|
||||
// {
|
||||
// request.ContentType = contentType;
|
||||
// }
|
||||
// if (headers != null)
|
||||
// {
|
||||
// foreach (var header in headers)
|
||||
// request.Headers[header.Key] = header.Value;
|
||||
// }
|
||||
|
||||
// try
|
||||
// {
|
||||
// byte[] bytes = Encoding.UTF8.GetBytes(postData ?? "");
|
||||
// using (Stream sendStream = request.GetRequestStream())
|
||||
// {
|
||||
// sendStream.Write(bytes, 0, bytes.Length);
|
||||
// }
|
||||
|
||||
// using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
|
||||
// {
|
||||
// Stream responseStream = response.GetResponseStream();
|
||||
// StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
|
||||
// return streamReader.ReadToEndAsync();
|
||||
// }
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// return Task.FromResult(ex.Message);
|
||||
// }
|
||||
|
||||
//}
|
||||
//public static Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null)
|
||||
//{
|
||||
// try
|
||||
// {
|
||||
// HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||||
// if (headers != null)
|
||||
// {
|
||||
// foreach (var header in headers)
|
||||
// request.Headers[header.Key] = header.Value;
|
||||
// }
|
||||
// using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
|
||||
// {
|
||||
// Stream responseStream = response.GetResponseStream();
|
||||
// StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
|
||||
// return streamReader.ReadToEndAsync();
|
||||
// }
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// return Task.FromResult(ex.Message);
|
||||
// }
|
||||
//}
|
||||
}
|
||||
}
|
||||
90
api_sqlsugar/VolPro.Core/Utilities/IdWorker.cs
Normal file
90
api_sqlsugar/VolPro.Core/Utilities/IdWorker.cs
Normal file
@@ -0,0 +1,90 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public class IdWorker
|
||||
{
|
||||
private static long machineId;
|
||||
private static long datacenterId;
|
||||
private static long sequence = 0L;
|
||||
private static long twepoch = 1288834974657L;
|
||||
private static long machineIdBits = 5L;
|
||||
private static long datacenterIdBits = 5L;
|
||||
private static long maxMachineId = -1L ^ (-1L << (int)machineIdBits);
|
||||
private static long maxDatacenterId = -1L ^ (-1L << (int)datacenterIdBits);
|
||||
private static long sequenceBits = 12L;
|
||||
private static long machineIdShift = sequenceBits;
|
||||
private static long datacenterIdShift = sequenceBits + machineIdBits;
|
||||
private static long timestampLeftShift = sequenceBits + machineIdBits + datacenterIdBits;
|
||||
private static long sequenceMask = -1L ^ (-1L << (int)sequenceBits);
|
||||
private static long lastTimestamp = -1L;
|
||||
|
||||
private static object lockSnowObj = new object();
|
||||
|
||||
public IdWorker(long machineId = 1, long datacenterId = 1)
|
||||
{
|
||||
if (machineId > maxMachineId || machineId < 0)
|
||||
{
|
||||
throw new Exception("machineId can't be greater than maxMachineId or less than 0");
|
||||
}
|
||||
if (datacenterId > maxDatacenterId || datacenterId < 0)
|
||||
{
|
||||
throw new Exception("datacenterId can't be greater than maxDatacenterId or less than 0");
|
||||
}
|
||||
IdWorker.machineId = machineId;
|
||||
IdWorker.datacenterId = datacenterId;
|
||||
}
|
||||
|
||||
public long NextId()
|
||||
{
|
||||
lock (lockSnowObj)
|
||||
{
|
||||
long timestamp = TimeGen();
|
||||
if (timestamp < lastTimestamp)
|
||||
{
|
||||
throw new Exception("Clock moved backwards. Refusing to generate id for " + (lastTimestamp - timestamp) + " milliseconds");
|
||||
}
|
||||
|
||||
if (lastTimestamp == timestamp)
|
||||
{
|
||||
sequence = (sequence + 1) & sequenceMask;
|
||||
if (sequence == 0)
|
||||
{
|
||||
// 如果在同一毫秒内生成的ID数量超过了限制,等待下一毫秒
|
||||
timestamp = TilNextMillis(lastTimestamp);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
sequence = 0L;
|
||||
}
|
||||
|
||||
lastTimestamp = timestamp;
|
||||
|
||||
return ((timestamp - twepoch) << (int)timestampLeftShift) |
|
||||
(datacenterId << (int)datacenterIdShift) |
|
||||
(machineId << (int)machineIdShift) |
|
||||
sequence;
|
||||
}
|
||||
}
|
||||
|
||||
private long TilNextMillis(long lastTimestamp)
|
||||
{
|
||||
long timestamp = TimeGen();
|
||||
while (timestamp <= lastTimestamp)
|
||||
{
|
||||
timestamp = TimeGen();
|
||||
}
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
private long TimeGen()
|
||||
{
|
||||
return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
98
api_sqlsugar/VolPro.Core/Utilities/JwtHelper.cs
Normal file
98
api_sqlsugar/VolPro.Core/Utilities/JwtHelper.cs
Normal file
@@ -0,0 +1,98 @@
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using VolPro.Core.Configuration;
|
||||
using VolPro.Core.Extensions;
|
||||
using VolPro.Entity.DomainModels;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public class JwtHelper
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 生成JWT
|
||||
/// </summary>
|
||||
/// <param name="serInfo"></param>
|
||||
/// <returns></returns>
|
||||
public static string IssueJwt(UserInfo userInfo, int? expir = null)
|
||||
{
|
||||
string exp = $"{new DateTimeOffset(DateTime.Now.AddMinutes(expir ?? (ManageUser.UserContext.MenuType == 1 ? 43200 : AppSetting.ExpMinutes))).ToUnixTimeSeconds()}";
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
//new Claim(ClaimTypes.Name,userInfo.UserName ),
|
||||
//new Claim(ClaimTypes.Role,userInfo.Role_Id ),
|
||||
new Claim(JwtRegisteredClaimNames.Jti,userInfo.User_Id.ToString()),
|
||||
new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
|
||||
new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
|
||||
//JWT过期时间
|
||||
//验证是否过期 从User读取过期 时间,再将时间戳转换成日期,如果时间在半个小时内即将过期,通知前台刷新JWT
|
||||
//int val= HttpContext.User.Claims.Where(x => x.Type == JwtRegisteredClaimNames.Exp).FirstOrDefault().Value;
|
||||
//new DateTime(621355968000000000 + (long)val* (long)10000000, DateTimeKind.Utc).ToLocalTime()
|
||||
//默认设置jwt过期时间120分钟
|
||||
new Claim (JwtRegisteredClaimNames.Exp,exp),
|
||||
new Claim(JwtRegisteredClaimNames.Iss,AppSetting.Secret.Issuer),
|
||||
new Claim(JwtRegisteredClaimNames.Aud,AppSetting.Secret.Audience),
|
||||
};
|
||||
|
||||
//秘钥16位
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSetting.Secret.JWT));
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
JwtSecurityToken securityToken = new JwtSecurityToken(issuer: AppSetting.Secret.Issuer, claims: claims, signingCredentials: creds);
|
||||
string jwt = new JwtSecurityTokenHandler().WriteToken(securityToken);
|
||||
return jwt;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解析
|
||||
/// </summary>
|
||||
/// <param name="jwtStr"></param>
|
||||
/// <returns></returns>
|
||||
public static UserInfo SerializeJwt(string jwtStr)
|
||||
{
|
||||
var jwtHandler = new JwtSecurityTokenHandler();
|
||||
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
|
||||
UserInfo userInfo = new UserInfo
|
||||
{
|
||||
User_Id = Convert.ToInt32(jwtToken.Id),
|
||||
Role_Id = (jwtToken.Payload[ClaimTypes.Role] ?? 0).GetInt(),
|
||||
UserName = jwtToken.Payload[ClaimTypes.Name]?.ToString()
|
||||
};
|
||||
return userInfo;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取过期时间
|
||||
/// </summary>
|
||||
/// <param name="jwtStr"></param>
|
||||
/// <returns></returns>
|
||||
public static DateTime GetExp(string jwtStr)
|
||||
{
|
||||
var jwtHandler = new JwtSecurityTokenHandler();
|
||||
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
|
||||
|
||||
DateTime expDate = (jwtToken.Payload[JwtRegisteredClaimNames.Exp] ?? 0).GetInt().GetTimeSpmpToDate();
|
||||
return expDate;
|
||||
}
|
||||
public static bool IsExp(string jwtStr)
|
||||
{
|
||||
return GetExp(jwtStr) < DateTime.Now;
|
||||
}
|
||||
|
||||
public static int GetUserId(string jwtStr)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new JwtSecurityTokenHandler().ReadJwtToken(jwtStr).Id.GetInt();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
109
api_sqlsugar/VolPro.Core/Utilities/MailHelper.cs
Normal file
109
api_sqlsugar/VolPro.Core/Utilities/MailHelper.cs
Normal file
@@ -0,0 +1,109 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Mail;
|
||||
using System.Text;
|
||||
using VolPro.Core.Configuration;
|
||||
using VolPro.Core.Extensions;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public static class MailHelper
|
||||
{
|
||||
private static string address { get; set; }
|
||||
private static string authPwd { get; set; }
|
||||
private static string name { get; set; }
|
||||
private static string host { get; set; }
|
||||
private static int port;
|
||||
private static bool enableSsl { get; set; }
|
||||
static MailHelper()
|
||||
{
|
||||
IConfigurationSection section = AppSetting.GetSection("Mail");
|
||||
address = section["Address"];
|
||||
authPwd = section["AuthPwd"];
|
||||
name = section["Name"];
|
||||
host = section["Host"];
|
||||
port = section["Port"].GetInt();
|
||||
enableSsl = section["EnableSsl"].GetBool();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送邮件
|
||||
/// </summary>
|
||||
/// <param name="title">标题</param>
|
||||
/// <param name="content">内容</param>
|
||||
/// <param name="list">收件人</param>
|
||||
public static void Send(string title, string content, string[] list)
|
||||
{
|
||||
Send(title, content, false, null, list);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送邮件
|
||||
/// </summary>
|
||||
/// <param name="title">标题</param>
|
||||
/// <param name="content">内容</param>
|
||||
/// <param name="attachmentPath">附件</param>
|
||||
/// <param name="list">收件人</param>
|
||||
public static void Send(string title, string content, string attachmentPath, string[] list)
|
||||
{
|
||||
Send(title, content, false, attachmentPath, list);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送邮件
|
||||
/// </summary>
|
||||
/// <param name="title">标题</param>
|
||||
/// <param name="content">内容</param>
|
||||
/// <param name="IsBodyHtml">是否html</param>
|
||||
/// <param name="list">收件人</param>
|
||||
public static void Send(string title, string content, bool IsBodyHtml, string[] list)
|
||||
{
|
||||
Send(title, content, IsBodyHtml, null, list);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送邮件
|
||||
/// </summary>
|
||||
/// <param name="title">标题</param>
|
||||
/// <param name="content">内容</param>
|
||||
/// <param name="IsBodyHtml">是否html</param>
|
||||
/// <param name="attachmentPath">附件</param>
|
||||
/// <param name="list">收件人</param>
|
||||
public static void Send(string title, string content, bool IsBodyHtml, string attachmentPath, string[] list)
|
||||
{
|
||||
Console.WriteLine(AppSetting.GetSection("ModifyMember")["DateUTCField"]);
|
||||
MailMessage message = new MailMessage
|
||||
{
|
||||
From = new MailAddress(address, name)//发送人邮箱
|
||||
};
|
||||
foreach (var item in list)
|
||||
{
|
||||
message.To.Add(item);//收件人地址
|
||||
}
|
||||
|
||||
message.Subject = title;//发送邮件的标题
|
||||
|
||||
message.Body = content;//发送邮件的内容
|
||||
message.IsBodyHtml = IsBodyHtml;
|
||||
// 添加附件
|
||||
if (!string.IsNullOrEmpty(attachmentPath) && File.Exists(attachmentPath))
|
||||
{
|
||||
Attachment attachment = new Attachment(attachmentPath);
|
||||
message.Attachments.Add(attachment);
|
||||
}
|
||||
//配置smtp服务地址
|
||||
using SmtpClient client = new SmtpClient
|
||||
{
|
||||
Host = host,
|
||||
Port = port,//端口587
|
||||
EnableSsl = enableSsl,
|
||||
//发送人邮箱与授权密码
|
||||
Credentials = new NetworkCredential(address, authPwd)
|
||||
};
|
||||
client.Send(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
550
api_sqlsugar/VolPro.Core/Utilities/NPOIHelper.cs
Normal file
550
api_sqlsugar/VolPro.Core/Utilities/NPOIHelper.cs
Normal file
@@ -0,0 +1,550 @@
|
||||
//using NPOI.HPSF;
|
||||
//using NPOI.HSSF.UserModel;
|
||||
//using NPOI.SS.UserModel;
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Data;
|
||||
//using System.IO;
|
||||
//using System.Text;
|
||||
|
||||
//namespace VolPro.Core.Utilities
|
||||
//{
|
||||
// public class NPOIHelper
|
||||
// {
|
||||
// /// <summary>
|
||||
// /// DataTable 导出到 Excel 的 MemoryStream
|
||||
// /// </summary>
|
||||
// /// <param name="dtSource">源 DataTable</param>
|
||||
// /// <param name="strHeaderText">表头文本 空值未不要表头标题</param>
|
||||
// /// <returns></returns>
|
||||
// public static MemoryStream ExportExcel(DataTable dtSource, string strHeaderText)
|
||||
// {
|
||||
// HSSFWorkbook workbook = new HSSFWorkbook();
|
||||
// ISheet sheet = workbook.CreateSheet();
|
||||
// #region 文件属性
|
||||
// DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
|
||||
// dsi.Company = "517best.com";
|
||||
// workbook.DocumentSummaryInformation = dsi;
|
||||
// SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
|
||||
// si.Author = "517best.com";
|
||||
// si.ApplicationName = "517best.com";
|
||||
// si.LastAuthor = "517best.com";
|
||||
// si.Comments = "";
|
||||
// si.Title = "";
|
||||
// si.Subject = "";
|
||||
// si.CreateDateTime = DateTime.Now;
|
||||
// workbook.SummaryInformation = si;
|
||||
// #endregion
|
||||
// ICellStyle dateStyle = workbook.CreateCellStyle();
|
||||
// IDataFormat format = workbook.CreateDataFormat();
|
||||
// dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
|
||||
// int[] arrColWidth = new int[dtSource.Columns.Count];
|
||||
// foreach (DataColumn item in dtSource.Columns)
|
||||
// {
|
||||
// arrColWidth[item.Ordinal] = Encoding.GetEncoding("gb2312").GetBytes(item.ColumnName.ToString()).Length;
|
||||
// }
|
||||
// for (int i = 0; i < dtSource.Rows.Count; i++)
|
||||
// {
|
||||
// for (int j = 0; j < dtSource.Columns.Count; j++)
|
||||
// {
|
||||
// int intTemp = Encoding.GetEncoding("gb2312").GetBytes(dtSource.Rows[i][j].ToString()).Length;
|
||||
// if (intTemp > arrColWidth[j])
|
||||
// {
|
||||
// arrColWidth[j] = intTemp;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// int rowIndex = 0;
|
||||
// int intTop = 0;
|
||||
// foreach (DataRow row in dtSource.Rows)
|
||||
// {
|
||||
// #region 新建表、填充表头、填充列头,样式
|
||||
// if (rowIndex == 65535 || rowIndex == 0)
|
||||
// {
|
||||
// if (rowIndex != 0)
|
||||
// {
|
||||
// sheet = workbook.CreateSheet();
|
||||
// }
|
||||
// intTop = 0;
|
||||
// #region 表头及样式
|
||||
// {
|
||||
// if (strHeaderText.Length > 0)
|
||||
// {
|
||||
// IRow headerRow = sheet.CreateRow(intTop);
|
||||
// intTop += 1;
|
||||
// headerRow.HeightInPoints = 25;
|
||||
// headerRow.CreateCell(0).SetCellValue(strHeaderText);
|
||||
// ICellStyle headStyle = workbook.CreateCellStyle();
|
||||
// headStyle.Alignment = HorizontalAlignment.Center;
|
||||
// IFont font = workbook.CreateFont();
|
||||
// font.FontHeightInPoints = 20;
|
||||
// font.Boldweight = 700;
|
||||
// headStyle.SetFont(font);
|
||||
// headerRow.GetCell(0).CellStyle = headStyle;
|
||||
// sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
|
||||
|
||||
// }
|
||||
// }
|
||||
// #endregion
|
||||
// #region 列头及样式
|
||||
// {
|
||||
// IRow headerRow = sheet.CreateRow(intTop);
|
||||
// intTop += 1;
|
||||
// ICellStyle headStyle = workbook.CreateCellStyle();
|
||||
// headStyle.Alignment = HorizontalAlignment.Center;
|
||||
// IFont font = workbook.CreateFont();
|
||||
// font.Boldweight = 700;
|
||||
// headStyle.SetFont(font);
|
||||
// foreach (DataColumn column in dtSource.Columns)
|
||||
// {
|
||||
// headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
|
||||
// headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
|
||||
// //设置列宽
|
||||
// sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
|
||||
// }
|
||||
|
||||
|
||||
// }
|
||||
// #endregion
|
||||
// rowIndex = intTop;
|
||||
// }
|
||||
// #endregion
|
||||
// #region 填充内容
|
||||
// IRow dataRow = sheet.CreateRow(rowIndex);
|
||||
// foreach (DataColumn column in dtSource.Columns)
|
||||
// {
|
||||
// ICell newCell = dataRow.CreateCell(column.Ordinal);
|
||||
// string drValue = row[column].ToString();
|
||||
// switch (column.DataType.ToString())
|
||||
// {
|
||||
// case "System.String"://字符串类型
|
||||
// newCell.SetCellValue(drValue);
|
||||
// break;
|
||||
// case "System.DateTime"://日期类型
|
||||
// DateTime dateV;
|
||||
// DateTime.TryParse(drValue, out dateV);
|
||||
// newCell.SetCellValue(dateV);
|
||||
// newCell.CellStyle = dateStyle;//格式化显示
|
||||
// break;
|
||||
// case "System.Boolean"://布尔型
|
||||
// bool boolV = false;
|
||||
// bool.TryParse(drValue, out boolV);
|
||||
// newCell.SetCellValue(boolV);
|
||||
// break;
|
||||
// case "System.Int16":
|
||||
// case "System.Int32":
|
||||
// case "System.Int64":
|
||||
// case "System.Byte":
|
||||
// int intV = 0;
|
||||
// int.TryParse(drValue, out intV);
|
||||
// newCell.SetCellValue(intV);
|
||||
// break;
|
||||
// case "System.Decimal":
|
||||
// case "System.Double":
|
||||
// double doubV = 0;
|
||||
// double.TryParse(drValue, out doubV);
|
||||
// newCell.SetCellValue(doubV);
|
||||
// break;
|
||||
// case "System.DBNull"://空值处理
|
||||
// newCell.SetCellValue("");
|
||||
// break;
|
||||
// default:
|
||||
// newCell.SetCellValue("");
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// #endregion
|
||||
// rowIndex++;
|
||||
// }
|
||||
// using (MemoryStream ms = new MemoryStream())
|
||||
// {
|
||||
// workbook.Write(ms);
|
||||
// ms.Flush();
|
||||
// ms.Position = 0;
|
||||
// return ms;
|
||||
// }
|
||||
// }
|
||||
// /// <summary>
|
||||
// /// DaataTable 导出到 Excel 文件
|
||||
// /// </summary>
|
||||
// /// <param name="dtSource">源 DataaTable</param>
|
||||
// /// <param name="strHeaderText">表头文本</param>
|
||||
// /// <param name="strFileName">保存位置(文件名及路径)</param>
|
||||
// public static void ExportExcel(DataTable dtSource, string strHeaderText, string strFileName)
|
||||
// {
|
||||
// using (MemoryStream ms = ExportExcel(dtSource, strHeaderText))
|
||||
// {
|
||||
// using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
|
||||
// {
|
||||
// byte[] data = ms.ToArray();
|
||||
// fs.Write(data, 0, data.Length);
|
||||
// fs.Flush();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 读取 excel
|
||||
// /// 默认第一行为标头
|
||||
// /// </summary>
|
||||
// /// <param name="strFileName">excel 文档路径</param>
|
||||
// /// <returns></returns>
|
||||
// public static DataTable ImportExcel(string strFileName)
|
||||
// {
|
||||
// DataTable dt = new DataTable();
|
||||
// HSSFWorkbook hssfworkbook;
|
||||
// using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
|
||||
// {
|
||||
// hssfworkbook = new HSSFWorkbook(file);
|
||||
// }
|
||||
// ISheet sheet = hssfworkbook.GetSheetAt(0);
|
||||
// System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
|
||||
// IRow headerRow = sheet.GetRow(0);
|
||||
// int cellCount = headerRow.LastCellNum;
|
||||
// for (int j = 0; j < cellCount; j++)
|
||||
// {
|
||||
// ICell cell = headerRow.GetCell(j);
|
||||
// dt.Columns.Add(cell.ToString());
|
||||
// }
|
||||
// for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
|
||||
// {
|
||||
// IRow row = sheet.GetRow(i);
|
||||
// if (row.GetCell(row.FirstCellNum) != null && row.GetCell(row.FirstCellNum).ToString().Length > 0)
|
||||
// {
|
||||
// DataRow dataRow = dt.NewRow();
|
||||
// for (int j = row.FirstCellNum; j < cellCount; j++)
|
||||
// {
|
||||
// if (row.GetCell(j) != null)
|
||||
// {
|
||||
|
||||
// dataRow[j] = row.GetCell(j).ToString();
|
||||
|
||||
// }
|
||||
// }
|
||||
// dt.Rows.Add(dataRow);
|
||||
// }
|
||||
// }
|
||||
// return dt;
|
||||
|
||||
// }
|
||||
|
||||
|
||||
// /// <summary>
|
||||
// /// DataSet 导出到 Excel 的 MemoryStream
|
||||
// /// </summary>
|
||||
// /// <param name="dsSource">源 DataSet</param>
|
||||
// /// <param name="strHeaderText">表头文本 空值未不要表头标题(多个表对应多个表头以英文逗号(,)分开,个数应与表相同)</param>
|
||||
// /// <returns></returns>
|
||||
// public static MemoryStream ExportExcel(DataSet dsSource, string strHeaderText)
|
||||
// {
|
||||
|
||||
// HSSFWorkbook workbook = new HSSFWorkbook();
|
||||
|
||||
// #region 文件属性
|
||||
// DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
|
||||
// dsi.Company = "517best.com";
|
||||
// workbook.DocumentSummaryInformation = dsi;
|
||||
// SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
|
||||
// si.Author = "517best.com";
|
||||
// si.ApplicationName = "517best.com";
|
||||
// si.LastAuthor = "517best.com";
|
||||
// si.Comments = "";
|
||||
// si.Title = "";
|
||||
// si.Subject = "";
|
||||
// si.CreateDateTime = DateTime.Now;
|
||||
// workbook.SummaryInformation = si;
|
||||
// #endregion
|
||||
|
||||
// #region 注释
|
||||
|
||||
|
||||
// //ICellStyle dateStyle = workbook.CreateCellStyle();
|
||||
// //IDataFormat format = workbook.CreateDataFormat();
|
||||
// //dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
|
||||
|
||||
// //ISheet sheet = workbook.CreateSheet();
|
||||
// //int[] arrColWidth = new int[dtSource.Columns.Count];
|
||||
// //foreach (DataColumn item in dtSource.Columns)
|
||||
// //{
|
||||
// // arrColWidth[item.Ordinal] = Encoding.GetEncoding("gb2312").GetBytes(item.ColumnName.ToString()).Length;
|
||||
// //}
|
||||
// //for (int i = 0; i < dtSource.Rows.Count; i++)
|
||||
// //{
|
||||
// // for (int j = 0; j < dtSource.Columns.Count; j++)
|
||||
// // {
|
||||
// // int intTemp = Encoding.GetEncoding("gb2312").GetBytes(dtSource.Rows[i][j].ToString()).Length;
|
||||
// // if (intTemp > arrColWidth[j])
|
||||
// // {
|
||||
// // arrColWidth[j] = intTemp;
|
||||
// // }
|
||||
// // }
|
||||
// //}
|
||||
// //int rowIndex = 0;
|
||||
// //int intTop = 0;
|
||||
// //foreach (DataRow row in dtSource.Rows)
|
||||
// //{
|
||||
// // #region 新建表、填充表头、填充列头,样式
|
||||
// // if (rowIndex == 65535 || rowIndex == 0)
|
||||
// // {
|
||||
// // if (rowIndex != 0)
|
||||
// // {
|
||||
// // sheet = workbook.CreateSheet();
|
||||
// // }
|
||||
// // intTop = 0;
|
||||
// // #region 表头及样式
|
||||
// // {
|
||||
// // if (strHeaderText.Length > 0)
|
||||
// // {
|
||||
// // IRow headerRow = sheet.CreateRow(intTop);
|
||||
// // intTop += 1;
|
||||
// // headerRow.HeightInPoints = 25;
|
||||
// // headerRow.CreateCell(0).SetCellValue(strHeaderText);
|
||||
// // ICellStyle headStyle = workbook.CreateCellStyle();
|
||||
// // headStyle.Alignment = HorizontalAlignment.CENTER;
|
||||
// // IFont font = workbook.CreateFont();
|
||||
// // font.FontHeightInPoints = 20;
|
||||
// // font.Boldweight = 700;
|
||||
// // headStyle.SetFont(font);
|
||||
// // headerRow.GetCell(0).CellStyle = headStyle;
|
||||
// // sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
|
||||
|
||||
// // }
|
||||
// // }
|
||||
// // #endregion
|
||||
// // #region 列头及样式
|
||||
// // {
|
||||
// // IRow headerRow = sheet.CreateRow(intTop);
|
||||
// // intTop += 1;
|
||||
// // ICellStyle headStyle = workbook.CreateCellStyle();
|
||||
// // headStyle.Alignment = HorizontalAlignment.CENTER;
|
||||
// // IFont font = workbook.CreateFont();
|
||||
// // font.Boldweight = 700;
|
||||
// // headStyle.SetFont(font);
|
||||
// // foreach (DataColumn column in dtSource.Columns)
|
||||
// // {
|
||||
// // headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
|
||||
// // headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
|
||||
// // //设置列宽
|
||||
// // sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
|
||||
// // }
|
||||
|
||||
|
||||
// // }
|
||||
// // #endregion
|
||||
// // rowIndex = intTop;
|
||||
// // }
|
||||
// // #endregion
|
||||
// // #region 填充内容
|
||||
// // IRow dataRow = sheet.CreateRow(rowIndex);
|
||||
// // foreach (DataColumn column in dtSource.Columns)
|
||||
// // {
|
||||
// // ICell newCell = dataRow.CreateCell(column.Ordinal);
|
||||
// // string drValue = row[column].ToString();
|
||||
// // switch (column.DataType.ToString())
|
||||
// // {
|
||||
// // case "System.String"://字符串类型
|
||||
// // newCell.SetCellValue(drValue);
|
||||
// // break;
|
||||
// // case "System.DateTime"://日期类型
|
||||
// // DateTime dateV;
|
||||
// // DateTime.TryParse(drValue, out dateV);
|
||||
// // newCell.SetCellValue(dateV);
|
||||
// // newCell.CellStyle = dateStyle;//格式化显示
|
||||
// // break;
|
||||
// // case "System.Boolean"://布尔型
|
||||
// // bool boolV = false;
|
||||
// // bool.TryParse(drValue, out boolV);
|
||||
// // newCell.SetCellValue(boolV);
|
||||
// // break;
|
||||
// // case "System.Int16":
|
||||
// // case "System.Int32":
|
||||
// // case "System.Int64":
|
||||
// // case "System.Byte":
|
||||
// // int intV = 0;
|
||||
// // int.TryParse(drValue, out intV);
|
||||
// // newCell.SetCellValue(intV);
|
||||
// // break;
|
||||
// // case "System.Decimal":
|
||||
// // case "System.Double":
|
||||
// // double doubV = 0;
|
||||
// // double.TryParse(drValue, out doubV);
|
||||
// // newCell.SetCellValue(doubV);
|
||||
// // break;
|
||||
// // case "System.DBNull"://空值处理
|
||||
// // newCell.SetCellValue("");
|
||||
// // break;
|
||||
// // default:
|
||||
// // newCell.SetCellValue("");
|
||||
// // break;
|
||||
// // }
|
||||
// // }
|
||||
// // #endregion
|
||||
// // rowIndex++;
|
||||
// //}
|
||||
// #endregion
|
||||
|
||||
// string[] strNewText = strHeaderText.Split(Convert.ToChar(","));
|
||||
// if (dsSource.Tables.Count == strNewText.Length)
|
||||
// {
|
||||
// for (int i = 0; i < dsSource.Tables.Count; i++)
|
||||
// {
|
||||
// ExportFromDSExcel(workbook, dsSource.Tables[i], strNewText[i]);
|
||||
// }
|
||||
// }
|
||||
|
||||
// using (MemoryStream ms = new MemoryStream())
|
||||
// {
|
||||
// workbook.Write(ms);
|
||||
// ms.Flush();
|
||||
// ms.Position = 0;
|
||||
// return ms;
|
||||
// }
|
||||
// }
|
||||
// /// <summary>
|
||||
// /// DataTable 导出到 Excel 的 MemoryStream
|
||||
// /// </summary>
|
||||
// /// <param name="workbook">源 workbook</param>
|
||||
// /// <param name="dtSource">源 DataTable</param>
|
||||
// /// <param name="strHeaderText">表头文本 空值未不要表头标题(多个表对应多个表头以英文逗号(,)分开,个数应与表相同)</param>
|
||||
// /// <returns></returns>
|
||||
// public static void ExportFromDSExcel(HSSFWorkbook workbook, DataTable dtSource, string strHeaderText)
|
||||
// {
|
||||
// ICellStyle dateStyle = workbook.CreateCellStyle();
|
||||
// IDataFormat format = workbook.CreateDataFormat();
|
||||
// dateStyle.DataFormat = format.GetFormat("yyyy-MM-dd HH:mm:ss");
|
||||
// ISheet sheet = workbook.CreateSheet(strHeaderText);
|
||||
|
||||
// int[] arrColWidth = new int[dtSource.Columns.Count];
|
||||
// foreach (DataColumn item in dtSource.Columns)
|
||||
// {
|
||||
// arrColWidth[item.Ordinal] = Encoding.GetEncoding("gb2312").GetBytes(item.ColumnName.ToString()).Length;
|
||||
// }
|
||||
// for (int i = 0; i < dtSource.Rows.Count; i++)
|
||||
// {
|
||||
// for (int j = 0; j < dtSource.Columns.Count; j++)
|
||||
// {
|
||||
// int intTemp = Encoding.GetEncoding("gb2312").GetBytes(dtSource.Rows[i][j].ToString()).Length;
|
||||
// if (intTemp > arrColWidth[j])
|
||||
// {
|
||||
// arrColWidth[j] = intTemp;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// int rowIndex = 0;
|
||||
// int intTop = 0;
|
||||
// foreach (DataRow row in dtSource.Rows)
|
||||
// {
|
||||
// #region 新建表、填充表头、填充列头,样式
|
||||
// if (rowIndex == 65535 || rowIndex == 0)
|
||||
// {
|
||||
// if (rowIndex != 0)
|
||||
// {
|
||||
// sheet = workbook.CreateSheet();
|
||||
// }
|
||||
// intTop = 0;
|
||||
// #region 表头及样式
|
||||
// {
|
||||
// if (strHeaderText.Length > 0)
|
||||
// {
|
||||
// IRow headerRow = sheet.CreateRow(intTop);
|
||||
// intTop += 1;
|
||||
// headerRow.HeightInPoints = 25;
|
||||
// headerRow.CreateCell(0).SetCellValue(strHeaderText);
|
||||
// ICellStyle headStyle = workbook.CreateCellStyle();
|
||||
// headStyle.Alignment = HorizontalAlignment.Center;
|
||||
// IFont font = workbook.CreateFont();
|
||||
// font.FontHeightInPoints = 20;
|
||||
// font.Boldweight = 700;
|
||||
// headStyle.SetFont(font);
|
||||
// headerRow.GetCell(0).CellStyle = headStyle;
|
||||
// sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
|
||||
|
||||
// }
|
||||
// }
|
||||
// #endregion
|
||||
// #region 列头及样式
|
||||
// {
|
||||
// IRow headerRow = sheet.CreateRow(intTop);
|
||||
// intTop += 1;
|
||||
// ICellStyle headStyle = workbook.CreateCellStyle();
|
||||
// headStyle.Alignment = HorizontalAlignment.Center;
|
||||
// IFont font = workbook.CreateFont();
|
||||
// font.Boldweight = 700;
|
||||
// headStyle.SetFont(font);
|
||||
// foreach (DataColumn column in dtSource.Columns)
|
||||
// {
|
||||
// headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
|
||||
// headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
|
||||
// //设置列宽
|
||||
// // sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); // 设置设置列宽 太长会报错 修改2014 年9月22日
|
||||
// int dd = (arrColWidth[column.Ordinal] + 1) * 256;
|
||||
|
||||
// if (dd > 200 * 256)
|
||||
// {
|
||||
// dd = 100 * 256;
|
||||
// }
|
||||
|
||||
|
||||
// sheet.SetColumnWidth(column.Ordinal, dd);
|
||||
// }
|
||||
|
||||
|
||||
// }
|
||||
// #endregion
|
||||
// rowIndex = intTop;
|
||||
// }
|
||||
// #endregion
|
||||
// #region 填充内容
|
||||
// IRow dataRow = sheet.CreateRow(rowIndex);
|
||||
// foreach (DataColumn column in dtSource.Columns)
|
||||
// {
|
||||
// ICell newCell = dataRow.CreateCell(column.Ordinal);
|
||||
// string drValue = row[column].ToString();
|
||||
// switch (column.DataType.ToString())
|
||||
// {
|
||||
// case "System.String"://字符串类型
|
||||
// newCell.SetCellValue(drValue);
|
||||
// break;
|
||||
// case "System.DateTime"://日期类型
|
||||
// if (drValue.Length > 0)
|
||||
// {
|
||||
// DateTime dateV;
|
||||
// DateTime.TryParse(drValue, out dateV);
|
||||
// newCell.SetCellValue(dateV);
|
||||
// newCell.CellStyle = dateStyle;//格式化显示
|
||||
// }
|
||||
// else { newCell.SetCellValue(drValue); }
|
||||
// break;
|
||||
// case "System.Boolean"://布尔型
|
||||
// bool boolV = false;
|
||||
// bool.TryParse(drValue, out boolV);
|
||||
// newCell.SetCellValue(boolV);
|
||||
// break;
|
||||
// case "System.Int16":
|
||||
// case "System.Int32":
|
||||
// case "System.Int64":
|
||||
// case "System.Byte":
|
||||
// int intV = 0;
|
||||
// int.TryParse(drValue, out intV);
|
||||
// newCell.SetCellValue(intV);
|
||||
// break;
|
||||
// case "System.Decimal":
|
||||
// case "System.Double":
|
||||
// double doubV = 0;
|
||||
// double.TryParse(drValue, out doubV);
|
||||
// newCell.SetCellValue(doubV);
|
||||
// break;
|
||||
// case "System.DBNull"://空值处理
|
||||
// newCell.SetCellValue("");
|
||||
// break;
|
||||
// default:
|
||||
// newCell.SetCellValue("");
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// #endregion
|
||||
// rowIndex++;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
20
api_sqlsugar/VolPro.Core/Utilities/PDFHelper/IPDFService.cs
Normal file
20
api_sqlsugar/VolPro.Core/Utilities/PDFHelper/IPDFService.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace VolPro.Core.Utilities.PDFHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// pdf接口
|
||||
/// </summary>
|
||||
public interface IPDFService
|
||||
{
|
||||
/// <summary>
|
||||
/// 创建PDF
|
||||
/// </summary>
|
||||
/// <param name="htmlContent">传入html字符串</param>
|
||||
/// <returns></returns>
|
||||
byte[] CreatePDF(string htmlContent);
|
||||
|
||||
}
|
||||
}
|
||||
62
api_sqlsugar/VolPro.Core/Utilities/PDFHelper/PDFService.cs
Normal file
62
api_sqlsugar/VolPro.Core/Utilities/PDFHelper/PDFService.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
|
||||
//using WkHtmlToPdfDotNet;
|
||||
//using WkHtmlToPdfDotNet.Contracts;
|
||||
|
||||
//namespace VolPro.Core.Utilities.PDFHelper
|
||||
//{
|
||||
// /// <summary>
|
||||
// /// pdf实现
|
||||
// /// </summary>
|
||||
// public class PDFService : IPDFService
|
||||
// {
|
||||
// private IConverter _converter;
|
||||
// public PDFService(IConverter converter)
|
||||
// {
|
||||
// _converter = converter;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 创建PDF
|
||||
// /// </summary>
|
||||
// /// <param name="htmlContent">传入html字符串</param>
|
||||
// /// <returns></returns>
|
||||
// public byte[] CreatePDF(string htmlContent)
|
||||
// {
|
||||
// var globalSettings = new GlobalSettings
|
||||
// {
|
||||
// ColorMode = ColorMode.Color,
|
||||
// Orientation = Orientation.Portrait,
|
||||
// PaperSize = PaperKind.A4,
|
||||
// //Margins = new MarginSettings
|
||||
// //{
|
||||
// // Top = 10,
|
||||
// // Left = 0,
|
||||
// // Right = 0,
|
||||
// //},
|
||||
// DocumentTitle = "SuZong PDF Report",
|
||||
// };
|
||||
// var objectSettings = new ObjectSettings
|
||||
// {
|
||||
// PagesCount = true,
|
||||
// HtmlContent = htmlContent,
|
||||
// //Page = "www.baidu.com", //USE THIS PROPERTY TO GENERATE PDF CONTENT FROM AN HTML PAGE 这里是用现有的网页生成PDF
|
||||
// //WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "styles.css") },
|
||||
// WebSettings = { DefaultEncoding = "utf-8" },
|
||||
// //HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
|
||||
// //FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Report Footer" }
|
||||
// //允许本地文件访问
|
||||
// LoadSettings = new LoadSettings { BlockLocalFileAccess = false }
|
||||
// };
|
||||
// var pdf = new HtmlToPdfDocument()
|
||||
// {
|
||||
// GlobalSettings = globalSettings,
|
||||
// Objects = { objectSettings }
|
||||
// };
|
||||
|
||||
// var file = _converter.Convert(pdf);
|
||||
// //return File(file, "application/pdf");
|
||||
// return file;
|
||||
// }
|
||||
|
||||
// }
|
||||
//}
|
||||
@@ -0,0 +1,63 @@
|
||||
using Newtonsoft.Json;
|
||||
using VolPro.Core.Enums;
|
||||
using VolPro.Core.Extensions;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public class ApiResponseContent
|
||||
{
|
||||
public ApiResponseContent()
|
||||
{
|
||||
}
|
||||
public ApiResponseContent(int status)
|
||||
{
|
||||
this.Status = status;
|
||||
}
|
||||
[JsonProperty(PropertyName = "message")]
|
||||
/// <summary>
|
||||
/// 返回消息
|
||||
/// </summary>
|
||||
public string Message { get; set; }
|
||||
[JsonProperty(PropertyName = "status")]
|
||||
/// <summary>
|
||||
/// 返回状态
|
||||
/// </summary>
|
||||
public int Status { get; set; }
|
||||
[JsonProperty(PropertyName = "data")]
|
||||
/// <summary>
|
||||
/// 所有返回的业务数据
|
||||
/// </summary>
|
||||
public object Data { get; set; }
|
||||
|
||||
public ApiResponseContent OK(string msg = null)
|
||||
{
|
||||
return this.Set(ResponseType.OperSuccess, msg, ApiStatutsCode.Ok);
|
||||
}
|
||||
|
||||
public ApiResponseContent Set(ResponseType responseType, ApiStatutsCode? status = null)
|
||||
{
|
||||
return this.Set(responseType, null, status);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="responseData"></param>
|
||||
/// <param name="responseType">返回消息类型</param>
|
||||
/// <param name="msg">返回消息,若msg为null,则取responseType的描述信息</param>
|
||||
/// <param name="status">返回状态,目前只有0、失败,1、成功,2、token过期</param>
|
||||
public ApiResponseContent Set(ResponseType responseType, string msg, ApiStatutsCode? status = null)
|
||||
{
|
||||
if (status != null)
|
||||
this.Status = (int)status;
|
||||
if (!string.IsNullOrEmpty(msg))
|
||||
{
|
||||
this.Message = msg;
|
||||
return this;
|
||||
}
|
||||
if (!string.IsNullOrEmpty(this.Message))
|
||||
return this;
|
||||
this.Message = responseType.GetMsg();
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using VolPro.Core.Enums;
|
||||
using VolPro.Core.Extensions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Newtonsoft.Json;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using VolPro.Core.Const;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public static class FilterResponse
|
||||
{
|
||||
public static void GetContentResult(FilterContext context, IActionResult actionResult)
|
||||
{
|
||||
GetContentResult(context, actionResult, null);
|
||||
}
|
||||
|
||||
public static void SetActionResult(ActionExecutingContext context, WebResponseContent responseData)
|
||||
{
|
||||
context.Result = new ContentResult()
|
||||
{
|
||||
Content = new { status = false, message = responseData.Message }.Serialize(),
|
||||
ContentType = ApplicationContentType.JSON,
|
||||
StatusCode = (int)HttpStatusCode.Unauthorized
|
||||
};
|
||||
}
|
||||
|
||||
public static void GetContentResult(FilterContext context, IActionResult actionResult, WebResponseContent responseData)
|
||||
{
|
||||
responseData = responseData ?? new WebResponseContent();
|
||||
responseData.Set(ResponseType.ServerError);
|
||||
|
||||
if (context.HttpContext.IsAjaxRequest())
|
||||
{
|
||||
actionResult = new ContentResult()
|
||||
{
|
||||
Content = JsonConvert.SerializeObject(responseData),
|
||||
ContentType = ApplicationContentType.JSON,
|
||||
StatusCode = (int)HttpStatusCode.InternalServerError
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
string desc = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(responseData.Message));
|
||||
actionResult = new ContentResult()
|
||||
{
|
||||
Content = $@"<html><head><title></title></head><body>{desc}</body></html>",
|
||||
ContentType = "text/html",
|
||||
StatusCode = (int)HttpStatusCode.InternalServerError
|
||||
};
|
||||
}
|
||||
//writelog
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using VolPro.Core.Enums;
|
||||
using VolPro.Core.Extensions;
|
||||
using VolPro.Core.Language;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public class WebResponseContent
|
||||
{
|
||||
public WebResponseContent()
|
||||
{
|
||||
}
|
||||
public WebResponseContent(bool status)
|
||||
{
|
||||
this.Status = status;
|
||||
}
|
||||
public bool Status { get; set; }
|
||||
public string Code { get; set; }
|
||||
public string Message { get; set; }
|
||||
//public string Message { get; set; }
|
||||
public object Data { get; set; }
|
||||
|
||||
public WebResponseContent OK()
|
||||
{
|
||||
this.Status = true;
|
||||
return this;
|
||||
}
|
||||
public WebResponseContent OKData(object data)
|
||||
{
|
||||
this.Status = true;
|
||||
this.Data = data;
|
||||
return this;
|
||||
}
|
||||
public WebResponseContent OKData(string message, object data, bool ts = false)
|
||||
{
|
||||
this.Message = ts ? message?.Translator() : message;
|
||||
this.Status = true;
|
||||
this.Data = data;
|
||||
return this;
|
||||
}
|
||||
public static WebResponseContent Instance
|
||||
{
|
||||
get { return new WebResponseContent(); }
|
||||
}
|
||||
public WebResponseContent OK(string message = null, object data = null, bool ts = true)
|
||||
{
|
||||
this.Status = true;
|
||||
this.Message = ts ? message?.Translator() : message;
|
||||
this.Data = data;
|
||||
return this;
|
||||
}
|
||||
public WebResponseContent OKDataToString(object data = null)
|
||||
{
|
||||
this.Status = true;
|
||||
this.Data = data.Serialize();
|
||||
return this;
|
||||
}
|
||||
public WebResponseContent OK(ResponseType responseType, bool ts = true)
|
||||
{
|
||||
return Set(responseType, true, true);
|
||||
}
|
||||
public WebResponseContent Error(string message = null, bool ts = false)
|
||||
{
|
||||
this.Status = false;
|
||||
this.Message = ts ? message?.Translator() : message;
|
||||
return this;
|
||||
}
|
||||
public WebResponseContent Error(ResponseType responseType, bool ts = false)
|
||||
{
|
||||
return Set(responseType, false, ts);
|
||||
}
|
||||
public WebResponseContent Set(ResponseType responseType, bool ts = false)
|
||||
{
|
||||
bool? b = null;
|
||||
return this.Set(responseType, b, ts);
|
||||
}
|
||||
public WebResponseContent Set(ResponseType responseType, bool? status, bool ts = false)
|
||||
{
|
||||
return this.Set(responseType, null, status, ts);
|
||||
}
|
||||
public WebResponseContent Set(ResponseType responseType, string msg, bool ts = false)
|
||||
{
|
||||
bool? b = null;
|
||||
return this.Set(responseType, msg, b);
|
||||
}
|
||||
public WebResponseContent Set(ResponseType responseType, string msg, bool? status, bool ts = false)
|
||||
{
|
||||
if (status != null)
|
||||
{
|
||||
this.Status = (bool)status;
|
||||
}
|
||||
this.Code = ((int)responseType).ToString();
|
||||
if (!string.IsNullOrEmpty(msg))
|
||||
{
|
||||
Message = ts ? msg.Translator() : msg;
|
||||
return this;
|
||||
}
|
||||
|
||||
Message = responseType.GetMsg();
|
||||
if (ts)
|
||||
{
|
||||
Message = Message.Translator();
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
73
api_sqlsugar/VolPro.Core/Utilities/SecurityEncDecrypt.cs
Normal file
73
api_sqlsugar/VolPro.Core/Utilities/SecurityEncDecrypt.cs
Normal file
@@ -0,0 +1,73 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using VolPro.Core.Services;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public class SecurityEncDecrypt
|
||||
{
|
||||
#region
|
||||
private static byte[] Keys = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
|
||||
/// <summary>
|
||||
/// DES加密字符串
|
||||
/// </summary>
|
||||
/// <param name="encryptString">待加密的字符串</param>
|
||||
/// <param name="encryptKey">加密密钥,要求为16位</param>
|
||||
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
|
||||
|
||||
public static string EncryptDES(string encryptString, string encryptKey)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 16));
|
||||
byte[] rgbIV = Keys;
|
||||
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
|
||||
var DCSP = Aes.Create();
|
||||
MemoryStream mStream = new MemoryStream();
|
||||
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
|
||||
cStream.Write(inputByteArray, 0, inputByteArray.Length);
|
||||
cStream.FlushFinalBlock();
|
||||
return Convert.ToBase64String(mStream.ToArray());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception("数据库密码加密异常" + ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DES解密字符串
|
||||
/// </summary>
|
||||
/// <param name="decryptString">待解密的字符串</param>
|
||||
/// <param name="decryptKey">解密密钥,要求为16位,和加密密钥相同</param>
|
||||
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
|
||||
|
||||
public static string DecryptDES(string decryptString, string decryptKey)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 16));
|
||||
byte[] rgbIV = Keys;
|
||||
byte[] inputByteArray = Convert.FromBase64String(decryptString);
|
||||
var DCSP = Aes.Create();
|
||||
MemoryStream mStream = new MemoryStream();
|
||||
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
|
||||
Byte[] inputByteArrays = new byte[inputByteArray.Length];
|
||||
cStream.Write(inputByteArray, 0, inputByteArray.Length);
|
||||
cStream.FlushFinalBlock();
|
||||
return Encoding.UTF8.GetString(mStream.ToArray());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error("解密异常:str:" + decryptString + ",Key:" + decryptKey+"---"+ ex.Message);
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
39
api_sqlsugar/VolPro.Core/Utilities/VierificationCode.cs
Normal file
39
api_sqlsugar/VolPro.Core/Utilities/VierificationCode.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public static class VierificationCode
|
||||
{
|
||||
private static readonly string[] _chars = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
|
||||
public static string RandomText()
|
||||
{
|
||||
string code = "";//产生的随机数
|
||||
int temp = -1;
|
||||
Random rand = new Random();
|
||||
for (int i = 1; i < 5; i++)
|
||||
{
|
||||
if (temp != -1)
|
||||
{
|
||||
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
|
||||
}
|
||||
int t = rand.Next(61);
|
||||
if (temp != -1 && temp == t)
|
||||
{
|
||||
return RandomText();
|
||||
}
|
||||
temp = t;
|
||||
code += _chars[t];
|
||||
}
|
||||
return code;
|
||||
}
|
||||
public static string CreateBase64Imgage(string code)
|
||||
{
|
||||
return VierificationCodeServices.CreateBase64Image(code);
|
||||
}
|
||||
}
|
||||
}
|
||||
103
api_sqlsugar/VolPro.Core/Utilities/VierificationCodeServices.cs
Normal file
103
api_sqlsugar/VolPro.Core/Utilities/VierificationCodeServices.cs
Normal file
@@ -0,0 +1,103 @@
|
||||
using SkiaSharp;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace VolPro.Core.Utilities
|
||||
{
|
||||
public static class VierificationCodeServices
|
||||
{
|
||||
static VierificationCodeServices()
|
||||
{
|
||||
}
|
||||
private static readonly SKColor[] colors = { SKColors.Black, SKColors.Green, SKColors.Brown };
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="code"></param>
|
||||
/// <returns></returns>
|
||||
public static string CreateBase64Image(string code)
|
||||
{
|
||||
var random = new Random();
|
||||
var info = new SKImageInfo((int)code.Length * 18, 32);
|
||||
using var bitmap = new SKBitmap(info);
|
||||
using var canvas = new SKCanvas(bitmap);
|
||||
|
||||
canvas.Clear(SKColors.White);
|
||||
|
||||
using var pen = new SKPaint();
|
||||
pen.FakeBoldText = true;
|
||||
pen.Style = SKPaintStyle.Fill;
|
||||
pen.TextSize = 20;// 0.6f * info.Width * pen.TextSize / pen.MeasureText(code);
|
||||
|
||||
//绘制随机字符
|
||||
for (int i = 0; i < code.Length; i++)
|
||||
{
|
||||
pen.Color = random.GetRandom(colors);//随机颜色索引值
|
||||
|
||||
pen.Typeface = SKTypeface.FromFamilyName("DejaVu Sans", 700, 20, SKFontStyleSlant.Italic);//配置字体
|
||||
var point = new SKPoint()
|
||||
{
|
||||
X = i * 16,
|
||||
Y = 22// info.Height - ((i + 1) % 2 == 0 ? 2 : 4),
|
||||
|
||||
};
|
||||
canvas.DrawText(code.Substring(i, 1), point, pen);//绘制一个验证字符
|
||||
|
||||
}
|
||||
|
||||
// 绘制噪点
|
||||
var points = Enumerable.Range(0, 100).Select(
|
||||
_ => new SKPoint(random.Next(bitmap.Width), random.Next(bitmap.Height))
|
||||
).ToArray();
|
||||
canvas.DrawPoints(
|
||||
SKPointMode.Points,
|
||||
points,
|
||||
pen);
|
||||
|
||||
//绘制贝塞尔线条
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
var p1 = new SKPoint(0, 0);
|
||||
var p2 = new SKPoint(0, 0);
|
||||
var p3 = new SKPoint(0, 0);
|
||||
var p4 = new SKPoint(0, 0);
|
||||
|
||||
var touchPoints = new SKPoint[] { p1, p2, p3, p4 };
|
||||
|
||||
using var bPen = new SKPaint();
|
||||
bPen.Color = random.GetRandom(colors);
|
||||
bPen.Style = SKPaintStyle.Stroke;
|
||||
|
||||
using var path = new SKPath();
|
||||
path.MoveTo(touchPoints[0]);
|
||||
path.CubicTo(touchPoints[1], touchPoints[2], touchPoints[3]);
|
||||
canvas.DrawPath(path, bPen);
|
||||
}
|
||||
return bitmap.ToBase64String(SKEncodedImageFormat.Png);
|
||||
}
|
||||
|
||||
public static T GetRandom<T>(this Random random, T[] tArray)
|
||||
{
|
||||
if (random == null) random = new Random();
|
||||
return tArray[random.Next(tArray.Length)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SKBitmap转Base64String
|
||||
/// </summary>
|
||||
/// <param name="bitmap"></param>
|
||||
/// <param name="format"></param>
|
||||
/// <returns></returns>
|
||||
public static string ToBase64String(this SKBitmap bitmap, SKEncodedImageFormat format)
|
||||
{
|
||||
using var memStream = new MemoryStream();
|
||||
using var wstream = new SKManagedWStream(memStream);
|
||||
bitmap.Encode(wstream, format, 32);
|
||||
memStream.TryGetBuffer(out ArraySegment<byte> buffer);
|
||||
return $"{Convert.ToBase64String(buffer.Array, 0, (int)memStream.Length)}";
|
||||
}
|
||||
}
|
||||
}
|
||||
717
api_sqlsugar/VolPro.Core/Utilities/XmlHelper.cs
Normal file
717
api_sqlsugar/VolPro.Core/Utilities/XmlHelper.cs
Normal file
@@ -0,0 +1,717 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Xml.Linq;
|
||||
using System.Xml;
|
||||
using System.Data;
|
||||
using System.Configuration;
|
||||
|
||||
/// 这个是用VS2010写的,如果用VS2005,请去掉System.Linq和System.Xml.Linq的引用
|
||||
/// 可以将此文件直接编译成dll,今后程序只需要引用该dll后开头添加using XmlLibrary;即可。
|
||||
namespace Rattan.Basic.Utility
|
||||
{
|
||||
/// <summary>
|
||||
/// XMLHelper参数
|
||||
/// </summary>
|
||||
public class XmlParameter
|
||||
{
|
||||
private string _name;
|
||||
private string _innerText;
|
||||
private string _namespaceOfPrefix;
|
||||
private AttributeParameter[] _attributes;
|
||||
|
||||
public XmlParameter() { }
|
||||
public XmlParameter(string name, params AttributeParameter[] attParas) : this(name, null, null, attParas) { }
|
||||
public XmlParameter(string name, string innerText, params AttributeParameter[] attParas) : this(name, innerText, null, attParas) { }
|
||||
public XmlParameter(string name, string innerText, string namespaceOfPrefix, params AttributeParameter[] attParas)
|
||||
{
|
||||
this._name = name;
|
||||
this._innerText = innerText;
|
||||
this._namespaceOfPrefix = namespaceOfPrefix;
|
||||
this._attributes = attParas;
|
||||
}
|
||||
/// <summary>
|
||||
/// 节点名称
|
||||
/// </summary>
|
||||
public string Name
|
||||
{
|
||||
get { return this._name; }
|
||||
set { this._name = value; }
|
||||
}
|
||||
/// <summary>
|
||||
/// 节点文本
|
||||
/// </summary>
|
||||
public string InnerText
|
||||
{
|
||||
get { return this._innerText; }
|
||||
set { this._innerText = value; }
|
||||
}
|
||||
/// <summary>
|
||||
/// 节点前缀xmlns声明(命名空间URI)
|
||||
/// </summary>
|
||||
public string NamespaceOfPrefix
|
||||
{
|
||||
get { return this._namespaceOfPrefix; }
|
||||
set { this._namespaceOfPrefix = value; }
|
||||
}
|
||||
/// <summary>
|
||||
/// 节点属性集
|
||||
/// </summary>
|
||||
public AttributeParameter[] Attributes
|
||||
{
|
||||
get { return this._attributes; }
|
||||
set { this._attributes = value; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 节点属性参数
|
||||
/// </summary>
|
||||
public class AttributeParameter
|
||||
{
|
||||
private string _name;
|
||||
private string _value;
|
||||
|
||||
public AttributeParameter() { }
|
||||
public AttributeParameter(string attributeName, string attributeValue)
|
||||
{
|
||||
this._name = attributeName;
|
||||
this._value = attributeValue;
|
||||
}
|
||||
/// <summary>
|
||||
/// 属性名称
|
||||
/// </summary>
|
||||
public string Name
|
||||
{
|
||||
get { return this._name; }
|
||||
set { this._name = value; }
|
||||
}
|
||||
/// <summary>
|
||||
/// 属性值
|
||||
/// </summary>
|
||||
public string Value
|
||||
{
|
||||
get { return this._value; }
|
||||
set { this._value = value; }
|
||||
}
|
||||
}
|
||||
|
||||
public class XMLHelper
|
||||
{
|
||||
private static string _xPath;
|
||||
/// <summary>
|
||||
/// xml文件路径
|
||||
/// </summary>
|
||||
public static string XmlPath
|
||||
{
|
||||
get { return _xPath; }
|
||||
set { _xPath = value; }
|
||||
}
|
||||
private static string _configName = "XmlPath";
|
||||
/// <summary>
|
||||
/// 配置文件节点名称,请设置在AppSettings节点下
|
||||
/// </summary>
|
||||
public static string ConfigName
|
||||
{
|
||||
get { return _configName; }
|
||||
set { _configName = value; GetConfig(); }
|
||||
}
|
||||
/// <summary>
|
||||
/// 从配置文件读取xml路径
|
||||
/// </summary>
|
||||
static void GetConfig()
|
||||
{
|
||||
//if (string.IsNullOrEmpty(_xPath))
|
||||
//{
|
||||
// try
|
||||
// {
|
||||
// _xPath = ConfigurationManager.AppSettings[_configName];
|
||||
// }
|
||||
// catch { }
|
||||
//}
|
||||
}
|
||||
static XMLHelper() { GetConfig(); }
|
||||
|
||||
#region private AppendChild
|
||||
/// <summary>
|
||||
/// 添加一个子节点
|
||||
/// </summary>
|
||||
/// <param name="xDoc">XmlDocument对象</param>
|
||||
/// <param name="parentNode">父节点</param>
|
||||
/// <param name="xlParameter">Xml参数</param>
|
||||
private static void AppendChild(XmlDocument xDoc, XmlNode parentNode, params XmlParameter[] xlParameter)
|
||||
{
|
||||
foreach (XmlParameter xpar in xlParameter)
|
||||
{
|
||||
XmlNode newNode = xDoc.CreateNode(XmlNodeType.Element, xpar.Name, null);
|
||||
string ns = string.IsNullOrEmpty(xpar.NamespaceOfPrefix) ? "" : newNode.GetNamespaceOfPrefix(xpar.NamespaceOfPrefix);
|
||||
foreach (AttributeParameter attp in xpar.Attributes)
|
||||
{
|
||||
XmlNode attr = xDoc.CreateNode(XmlNodeType.Attribute, attp.Name, ns == "" ? null : ns);
|
||||
attr.Value = attp.Value;
|
||||
newNode.Attributes.SetNamedItem(attr);
|
||||
}
|
||||
newNode.InnerText = xpar.InnerText;
|
||||
parentNode.AppendChild(newNode);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region private AddEveryNode
|
||||
private static void AddEveryNode(XmlDocument xDoc, XmlNode parentNode, params XmlParameter[] paras)
|
||||
{
|
||||
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
|
||||
foreach (XmlNode xns in nlst)
|
||||
{
|
||||
if (xns.Name == parentNode.Name)
|
||||
{
|
||||
AppendChild(xDoc, xns, paras);
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (XmlNode xn in xns)
|
||||
{
|
||||
if (xn.Name == parentNode.Name)
|
||||
{
|
||||
AppendChild(xDoc, xn, paras);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region private GetXmlDom
|
||||
/// <summary>
|
||||
/// 获得一个XmlDocument对象
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private static XmlDocument GetXmlDom()
|
||||
{
|
||||
XmlDocument xdoc = new XmlDocument();
|
||||
xdoc.Load(_xPath);
|
||||
return xdoc;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region CreateXmlFile
|
||||
/// <summary>
|
||||
/// 创建一个XML文档,成功创建后操作路径将直接指向该文件
|
||||
/// </summary>
|
||||
/// <param name="fileName">文件物理路径名</param>
|
||||
/// <param name="rootNode">根结点名称</param>
|
||||
/// <param name="elementName">元素节点名称</param>
|
||||
/// <param name="xmlParameter">XML参数</param>
|
||||
public static void CreateXmlFile(string fileName, string rootNode, string elementName, params XmlParameter[] xmlParameter)
|
||||
{
|
||||
XmlDocument xDoc = new XmlDocument();
|
||||
XmlNode xn = xDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
|
||||
xDoc.AppendChild(xn);
|
||||
XmlNode root = xDoc.CreateElement(rootNode);
|
||||
xDoc.AppendChild(root);
|
||||
XmlNode ln = xDoc.CreateNode(XmlNodeType.Element, elementName, null);
|
||||
AppendChild(xDoc, ln, xmlParameter);
|
||||
root.AppendChild(ln);
|
||||
try
|
||||
{
|
||||
xDoc.Save(fileName);
|
||||
_xPath = fileName;
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 创建一个XML文档,成功创建后操作路径将直接指向该文件
|
||||
/// </summary>
|
||||
/// <param name="fileName">文件物理路径名</param>
|
||||
/// <param name="xmlString">xml字符串</param>
|
||||
public static void CreateXmlFile(string fileName, string xmlString)
|
||||
{
|
||||
XmlDocument xDoc = new XmlDocument();
|
||||
try
|
||||
{
|
||||
xDoc.LoadXml(xmlString);
|
||||
xDoc.Save(fileName);
|
||||
_xPath = fileName;
|
||||
}
|
||||
catch { throw; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region AddNewNode
|
||||
/// <summary>
|
||||
/// 添加新节点
|
||||
/// </summary>
|
||||
/// <param name="parentNode">新节点的父节点对象</param>
|
||||
/// <param name="xmlParameter">Xml参数对象</param>
|
||||
public static void AddNewNode(XmlNode parentNode, params XmlParameter[] xmlParameter)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
if (parentNode.Name == xDoc.DocumentElement.Name)
|
||||
{
|
||||
XmlNode newNode = xDoc.CreateNode(XmlNodeType.Element, xDoc.DocumentElement.ChildNodes[0].Name, null);
|
||||
AppendChild(xDoc, newNode, xmlParameter);
|
||||
xDoc.DocumentElement.AppendChild(newNode);
|
||||
}
|
||||
else
|
||||
{
|
||||
AddEveryNode(xDoc, parentNode, xmlParameter);
|
||||
}
|
||||
xDoc.Save(_xPath);
|
||||
}
|
||||
/// <summary>
|
||||
/// 添加新节点
|
||||
/// </summary>
|
||||
/// <param name="xDoc">XmlDocument对象</param>
|
||||
/// <param name="parentName">新节点的父节点名称</param>
|
||||
/// <param name="xmlParameter">XML参数对象</param>
|
||||
public static void AddNewNode(string parentName, params XmlParameter[] xmlParameter)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
XmlNode parentNode = GetNode(xDoc, parentName);
|
||||
if (parentNode == null) return;
|
||||
if (parentNode.Name == xDoc.DocumentElement.Name)
|
||||
{
|
||||
XmlNode newNode = xDoc.CreateNode(XmlNodeType.Element, xDoc.DocumentElement.ChildNodes[0].Name, null);
|
||||
AppendChild(xDoc, newNode, xmlParameter);
|
||||
xDoc.DocumentElement.AppendChild(newNode);
|
||||
}
|
||||
else
|
||||
{
|
||||
AddEveryNode(xDoc, parentNode, xmlParameter);
|
||||
}
|
||||
xDoc.Save(_xPath);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region AddAttribute
|
||||
/// <summary>
|
||||
/// 添加节点属性
|
||||
/// </summary>
|
||||
/// <param name="node">节点对象</param>
|
||||
/// <param name="namespaceOfPrefix">该节点的命名空间URI</param>
|
||||
/// <param name="attributeName">新属性名称</param>
|
||||
/// <param name="attributeValue">属性值</param>
|
||||
public static void AddAttribute(XmlNode node, string namespaceOfPrefix, string attributeName, string attributeValue)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
string ns = string.IsNullOrEmpty(namespaceOfPrefix) ? "" : node.GetNamespaceOfPrefix(namespaceOfPrefix);
|
||||
XmlNode xn = xDoc.CreateNode(XmlNodeType.Attribute, attributeName, ns == "" ? null : ns);
|
||||
xn.Value = attributeValue;
|
||||
node.Attributes.SetNamedItem(xn);
|
||||
xDoc.Save(_xPath);
|
||||
}
|
||||
/// <summary>
|
||||
/// 添加节点属性
|
||||
/// </summary>
|
||||
/// <param name="node">节点对象</param>
|
||||
/// <param name="namespaceOfPrefix">该节点的命名空间URI</param>
|
||||
/// <param name="attributeParameters">节点属性参数</param>
|
||||
public static void AddAttribute(XmlNode node, string namespaceOfPrefix, params AttributeParameter[] attributeParameters)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
string ns = string.IsNullOrEmpty(namespaceOfPrefix) ? "" : node.GetNamespaceOfPrefix(namespaceOfPrefix);
|
||||
foreach (AttributeParameter attp in attributeParameters)
|
||||
{
|
||||
XmlNode xn = xDoc.CreateNode(XmlNodeType.Attribute, attp.Name, ns == "" ? null : ns);
|
||||
xn.Value = attp.Value;
|
||||
node.Attributes.SetNamedItem(xn);
|
||||
}
|
||||
xDoc.Save(_xPath);
|
||||
}
|
||||
/// <summary>
|
||||
/// 添加节点属性
|
||||
/// </summary>
|
||||
/// <param name="nodeName">节点名称</param>
|
||||
/// <param name="namespaceOfPrefix">该节点的命名空间URI</param>
|
||||
/// <param name="attributeName">新属性名称</param>
|
||||
/// <param name="attributeValue">属性值</param>
|
||||
public static void AddAttribute(string nodeName, string namespaceOfPrefix, string attributeName, string attributeValue)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
XmlNodeList xlst = xDoc.DocumentElement.ChildNodes;
|
||||
for (int i = 0; i < xlst.Count; i++)
|
||||
{
|
||||
XmlNode node = GetNode(xlst[i], nodeName);
|
||||
if (node == null) break;
|
||||
AddAttribute(node, namespaceOfPrefix, attributeName, attributeValue);
|
||||
}
|
||||
xDoc.Save(_xPath);
|
||||
}
|
||||
/// <summary>
|
||||
/// 添加节点属性
|
||||
/// </summary>
|
||||
/// <param name="nodeName">节点名称</param>
|
||||
/// <param name="namespaceOfPrefix">该节点的命名空间URI</param>
|
||||
/// <param name="attributeParameters">节点属性参数</param>
|
||||
public static void AddAttribute(string nodeName, string namespaceOfPrefix, params AttributeParameter[] attributeParameters)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
XmlNodeList xlst = xDoc.DocumentElement.ChildNodes;
|
||||
for (int i = 0; i < xlst.Count; i++)
|
||||
{
|
||||
XmlNode node = GetNode(xlst[i], nodeName);
|
||||
if (node == null) break;
|
||||
AddAttribute(node, namespaceOfPrefix, attributeParameters);
|
||||
}
|
||||
xDoc.Save(_xPath);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region GetNode
|
||||
/// <summary>
|
||||
/// 获取指定节点名称的节点对象
|
||||
/// </summary>
|
||||
/// <param name="nodeName">节点名称</param>
|
||||
/// <returns></returns>
|
||||
public static XmlNode GetNode(string nodeName)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
if (xDoc.DocumentElement.Name == nodeName) return (XmlNode)xDoc.DocumentElement;
|
||||
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
|
||||
foreach (XmlNode xns in nlst) // 遍历所有子节点
|
||||
{
|
||||
if (xns.Name == nodeName) return xns;
|
||||
else
|
||||
{
|
||||
XmlNode xn = GetNode(xns, nodeName);
|
||||
if (xn != null) return xn; /// V1.0.0.3添加节点判断
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取指定节点名称的节点对象
|
||||
/// </summary>
|
||||
/// <param name="node">节点对象</param>
|
||||
/// <param name="nodeName">节点名称</param>
|
||||
/// <returns></returns>
|
||||
public static XmlNode GetNode(XmlNode node, string nodeName)
|
||||
{
|
||||
foreach (XmlNode xn in node)
|
||||
{
|
||||
if (xn.Name == nodeName) return xn;
|
||||
else
|
||||
{
|
||||
XmlNode tmp = GetNode(xn, nodeName);
|
||||
if (tmp != null) return tmp;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取指定节点名称的节点对象
|
||||
/// </summary>
|
||||
/// <param name="index">节点索引</param>
|
||||
/// <param name="nodeName">节点名称</param>
|
||||
public static XmlNode GetNode(int index, string nodeName)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
|
||||
if (nlst.Count <= index) return null;
|
||||
if (nlst[index].Name == nodeName) return (XmlNode)nlst[index];
|
||||
foreach (XmlNode xn in nlst[index])
|
||||
{
|
||||
return GetNode(xn, nodeName);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取指定节点名称的节点对象
|
||||
/// </summary>
|
||||
/// <param name="node">节点对象</param>
|
||||
/// <param name="nodeName">节点名称</param>
|
||||
/// <param name="innerText">节点内容</param>
|
||||
public static XmlNode GetNode(XmlNode node, string nodeName, string innerText)
|
||||
{
|
||||
foreach (XmlNode xn in node)
|
||||
{
|
||||
if (xn.Name == nodeName && xn.InnerText == innerText) return xn;
|
||||
else
|
||||
{
|
||||
XmlNode tmp = GetNode(xn, nodeName, innerText);
|
||||
if (tmp != null) return tmp;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取指定节点名称的节点对象
|
||||
/// </summary>
|
||||
/// <param name="nodeName">节点名称</param>
|
||||
/// <param name="innerText">节点内容</param>
|
||||
public static XmlNode GetNode(string nodeName, string innerText)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
|
||||
foreach (XmlNode xns in nlst) // 遍历所有子节点
|
||||
{
|
||||
if (xns.Name == nodeName && xns.InnerText == innerText) return xns;
|
||||
XmlNode tmp = GetNode(xns, nodeName, innerText);
|
||||
if (tmp != null) return tmp;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取指定节点名称的节点对象
|
||||
/// </summary>
|
||||
/// <param name="xmlParameter">XML参数</param>
|
||||
public static XmlNode GetNode(XmlParameter xmlParameter)
|
||||
{
|
||||
return GetNode(xmlParameter.Name, xmlParameter.InnerText);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取指定节点名称的节点对象
|
||||
/// </summary>
|
||||
/// <param name="node">节点对象</param>
|
||||
/// <param name="xmlParameter">XML参数</param>
|
||||
public static XmlNode GetNode(XmlNode node, XmlParameter xmlParameter)
|
||||
{
|
||||
return GetNode(node, xmlParameter.Name, node.InnerText);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region UpdateNode
|
||||
private static void UpdateNode(XmlNode node, XmlParameter xmlParameter)
|
||||
{
|
||||
node.InnerText = xmlParameter.InnerText;
|
||||
for (int i = 0; i < xmlParameter.Attributes.Length; i++)
|
||||
{
|
||||
for (int j = 0; j < node.Attributes.Count; j++)
|
||||
{
|
||||
if (node.Attributes[j].Name == xmlParameter.Attributes[i].Name)
|
||||
{
|
||||
node.Attributes[j].Value = xmlParameter.Attributes[i].Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private static void UpdateNode(XmlNode node, string innerText, AttributeParameter[] attributeParameters)
|
||||
{
|
||||
node.InnerText = innerText;
|
||||
for (int i = 0; i < attributeParameters.Length; i++)
|
||||
{
|
||||
for (int j = 0; j < node.Attributes.Count; j++)
|
||||
{
|
||||
if (node.Attributes[j].Name == attributeParameters[i].Name)
|
||||
{
|
||||
node.Attributes[j].Value = attributeParameters[i].Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 修改节点的内容
|
||||
/// </summary>
|
||||
/// <param name="index">节点索引</param>
|
||||
/// <param name="xmlParameter">XML参数对象</param>
|
||||
public static void UpdateNode(int index, XmlParameter xmlParameter)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
|
||||
if (nlst.Count <= index) return;
|
||||
if (nlst[index].Name == xmlParameter.Name)
|
||||
{
|
||||
UpdateNode(nlst[index], xmlParameter);
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (XmlNode xn in nlst[index])
|
||||
{
|
||||
XmlNode xnd = GetNode(xn, xmlParameter.Name);
|
||||
if (xnd != null)
|
||||
{
|
||||
UpdateNode(xnd, xmlParameter);
|
||||
}
|
||||
}
|
||||
}
|
||||
xDoc.Save(_xPath);
|
||||
}
|
||||
/// <summary>
|
||||
/// 修改节点的内容
|
||||
/// </summary>
|
||||
/// <param name="index">节点索引</param>
|
||||
/// <param name="nodeName">节点名称</param>
|
||||
/// <param name="newInnerText">修改后的内容</param>
|
||||
public static void UpdateNode(int index, string nodeName, string newInnerText)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
|
||||
if (nlst.Count <= index) return;
|
||||
if (nlst[index].Name == nodeName)
|
||||
{
|
||||
nlst[index].InnerText = newInnerText;
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (XmlNode xn in nlst[index])
|
||||
{
|
||||
XmlNode xnd = GetNode(xn, nodeName);
|
||||
if (xnd != null)
|
||||
{
|
||||
xnd.InnerText = newInnerText;
|
||||
}
|
||||
}
|
||||
}
|
||||
xDoc.Save(_xPath);
|
||||
}
|
||||
/// <summary>
|
||||
/// 修改节点的内容
|
||||
/// </summary>
|
||||
/// <param name="xmlParameter">XmlParameter对象</param>
|
||||
/// <param name="innerText">修改后的内容</param>
|
||||
/// <param name="attributeParameters">需要修改的属性</param>
|
||||
public static void UpdateNode(XmlParameter xmlParameter, string innerText, params AttributeParameter[] attributeParameters)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
|
||||
foreach (XmlNode xns in nlst) // 遍历所有子节点
|
||||
{
|
||||
if (xns.Name == xmlParameter.Name && xns.InnerText == xmlParameter.InnerText)
|
||||
{
|
||||
UpdateNode(xns, innerText, attributeParameters);
|
||||
break;
|
||||
}
|
||||
XmlNode tmp = GetNode(xns, xmlParameter);
|
||||
if (tmp != null)
|
||||
{
|
||||
UpdateNode(tmp, innerText, attributeParameters);
|
||||
break;
|
||||
}
|
||||
}
|
||||
xDoc.Save(_xPath);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region DeleteNode
|
||||
/// <summary>
|
||||
/// 删除节点
|
||||
/// </summary>
|
||||
/// <param name="index">节点索引</param>
|
||||
public static void DeleteNode(int index)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
|
||||
nlst[index].ParentNode.RemoveChild(nlst[index]);
|
||||
xDoc.Save(_xPath);
|
||||
}
|
||||
/// <summary>
|
||||
/// 删除节点
|
||||
/// </summary>
|
||||
/// <param name="nodeList">需要删除的节点对象</param>
|
||||
public static void DeleteNode(params XmlNode[] nodeList)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
foreach (XmlNode xnl in nodeList)
|
||||
{
|
||||
foreach (XmlNode xn in xDoc.DocumentElement.ChildNodes)
|
||||
{
|
||||
if (xnl.Equals(xn))
|
||||
{
|
||||
xn.ParentNode.RemoveChild(xn);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
xDoc.Save(_xPath);
|
||||
}
|
||||
/// <summary>
|
||||
/// 删除节点
|
||||
/// </summary>
|
||||
/// <param name="xDoc">XmlDocument对象</param>
|
||||
/// <param name="nodeName">节点名称</param>
|
||||
/// <param name="nodeText">节点内容</param>
|
||||
public static void DeleteNode(string nodeName, string nodeText)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
foreach (XmlNode xn in xDoc.DocumentElement.ChildNodes)
|
||||
{
|
||||
if (xn.Name == nodeName)
|
||||
{
|
||||
if (xn.InnerText == nodeText)
|
||||
{
|
||||
xn.ParentNode.RemoveChild(xn);
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
XmlNode node = GetNode(xn, nodeName);
|
||||
if (node != null && node.InnerText == nodeText)
|
||||
{
|
||||
node.ParentNode.ParentNode.RemoveChild(node.ParentNode);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
xDoc.Save(_xPath);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region SetAttribute
|
||||
/// <summary>
|
||||
/// 修改属性值
|
||||
/// </summary>
|
||||
/// <param name="elem">元素对象</param>
|
||||
/// <param name="attps">属性参数</param>
|
||||
private static void SetAttribute(XmlElement elem, params AttributeParameter[] attps)
|
||||
{
|
||||
foreach (AttributeParameter attp in attps)
|
||||
{
|
||||
elem.SetAttribute(attp.Name, attp.Value);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 修改属性值
|
||||
/// </summary>
|
||||
/// <param name="xmlParameter">XML参数</param>
|
||||
/// <param name="attributeParameters">属性参数</param>
|
||||
public static void SetAttribute(XmlParameter xmlParameter, params AttributeParameter[] attributeParameters)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
|
||||
foreach (XmlNode xns in nlst) // 遍历所有子节点
|
||||
{
|
||||
if (xns.Name == xmlParameter.Name && xns.InnerText == xmlParameter.InnerText)
|
||||
{
|
||||
SetAttribute((XmlElement)xns, attributeParameters);
|
||||
break;
|
||||
}
|
||||
XmlNode tmp = GetNode(xns, xmlParameter);
|
||||
if (tmp != null)
|
||||
{
|
||||
SetAttribute((XmlElement)tmp, attributeParameters);
|
||||
break;
|
||||
}
|
||||
}
|
||||
xDoc.Save(_xPath);
|
||||
}
|
||||
/// <summary>
|
||||
/// 修改属性值
|
||||
/// </summary>
|
||||
/// <param name="xmlParameter">XML参数</param>
|
||||
/// <param name="attributeValue">新属性值</param>
|
||||
public static void SetAttribute(XmlParameter xmlParameter, string attributeName, string attributeValue)
|
||||
{
|
||||
XmlDocument xDoc = GetXmlDom();
|
||||
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
|
||||
foreach (XmlNode xns in nlst) // 遍历所有子节点
|
||||
{
|
||||
if (xns.Name == xmlParameter.Name && xns.InnerText == xmlParameter.InnerText)
|
||||
{
|
||||
((XmlElement)xns).SetAttribute(attributeName, attributeValue);
|
||||
break;
|
||||
}
|
||||
XmlNode tmp = GetNode(xns, xmlParameter);
|
||||
if (tmp != null)
|
||||
{
|
||||
((XmlElement)tmp).SetAttribute(attributeName, attributeValue);
|
||||
break;
|
||||
}
|
||||
}
|
||||
xDoc.Save(_xPath);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user