Browse Source

更新版本

master
赵新宇 4 weeks ago
parent
commit
1e28f2aa09
  1. 121
      API/Wood.Service/Controllers/CheryRecurringJobInputPageController.cs
  2. 16
      API/Wood.Service/Controllers/CheryRecurringJobOutPageController.cs
  3. 156
      API/Wood.Service/Controllers/NormalBaseController.cs
  4. 74
      API/Wood.Util/DataTableHelper.cs
  5. 157
      API/Wood.Util/EntityHelper.cs

121
API/Wood.Service/Controllers/CheryRecurringJobInputPageController.cs

@ -1,22 +1,29 @@
using Azure.Core;
using Dapper;
using Magicodes.ExporterAndImporter.Core.Extension;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Data;
using System.Drawing.Printing;
using System.Linq.Expressions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using TaskManager.Contracts.Dtos;
using TaskManager.Entity;
using TaskManager.EntityFramework;
using TaskManager.EntityFramework.Repository;
namespace TaskManager.Controllers
{
public class CheryRecurringJobInputPageController<T,OUTPUT> : CheryRecurringJobBaseController where T : BaseEntity
{
protected readonly IRepository<T> _repository;
public CheryRecurringJobInputPageController(HttpClient httpClient, JobDbContext jobDbContext, LogController log, IRepository<T> repository) : base(httpClient, jobDbContext, log)
{
_repository = repository;
}
protected override async Task DoExecutingAsync(string url, string path, string takName, string client)
@ -165,6 +172,116 @@ namespace TaskManager.Controllers
}
[HttpGet]
public async Task<ActionResult<IEnumerable<T>>> GetAll()
{
return await _repository.GetAllAsync() as List<T>;
}
[HttpGet("{id}")]
public async Task<ActionResult<T>> GetById(int id)
{
var entity = await _repository.GetByIdAsync(id);
if (entity == null) return NotFound();
return entity;
}
[HttpPost]
public async Task<ActionResult<T>> Create(T entity)
{
entity.CreationTime = DateTime.Now;
var createdEntity = await _repository.AddAsync(entity);
return new JsonResult(new { Code = 200, Message = "创建成功!" }); ;
}
[HttpPut("{id}")]
public async Task<IActionResult> Update(T entity)
{
var _first = await _repository.GetByIdAsync(entity.UId);
if (_first == null)
{
return new JsonResult(new { Code = 400, Message = "修改失败!" });
}
await _repository.UpdateAsync(entity);
return new JsonResult(new { Code = 200, Message = "修改成功!" });
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
await _repository.DeleteAsync(id);
return new JsonResult(new { Code = 200, Message = "删除成功!" }); ;
}
[HttpGet]
public async Task<ActionResult<PagedResult<T>>> GetPaged(
[FromQuery] int pageNumber = 1,
[FromQuery] int pageSize = 10,
[FromQuery] string sortBy = "",
[FromQuery] bool isAscending = true,
[FromQuery] Dictionary<string, string> filters = null)
{
var pagingParams = new PagingParams
{
PageNumber = pageNumber,
PageSize = pageSize,
SortBy = sortBy,
IsAscending = isAscending,
Filters = filters
};
// 可以在这里构建表达式树过滤条件
Expression<Func<T, bool>> filter = null;
var pagedResult = await _repository.GetPagedAsync(filter, pagingParams);
return Ok(pagedResult);
}
[HttpGet]
public async Task<FileStreamResult> Export([FromQuery] int pageNumber = 1,
[FromQuery] int pageSize = 10,
[FromQuery] string sortBy = "",
[FromQuery] bool isAscending = true,
[FromQuery] Dictionary<string, string> filters = null)
{
var pagingParams = new PagingParams
{
PageNumber = pageNumber,
PageSize = pageSize,
SortBy = sortBy,
IsAscending = isAscending,
Filters = filters
};
// 可以在这里构建表达式树过滤条件
Expression<Func<T, bool>> filter = null;
var pagedResult = await _repository.GetPagedAsync(null, pagingParams);
var dataTable = pagedResult.Data.ToDataTable();
return await ExportFile(dataTable, Guid.NewGuid().ToString() + ".xlsx");
}
protected async Task<FileStreamResult> ExportFile(DataTable dtos, string fileName)
{
var excelExporter = HttpContext.RequestServices.GetRequiredService<IExcelExporter>();
var res = await excelExporter.ExportAsByteArray(dtos);
return new FileStreamResult(new MemoryStream(res), "application/octet-stream") { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "_" + fileName };
}
}

16
API/Wood.Service/Controllers/CheryRecurringJobOutPageController.cs

@ -1,9 +1,11 @@
using Magicodes.ExporterAndImporter.Excel;
using Magicodes.ExporterAndImporter.Core.Extension;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Omu.ValueInjecter;
using System.Data;
using System.Linq.Expressions;
using System.Text.Json;
using System.Text.Json.Serialization;
@ -50,7 +52,7 @@ namespace TaskManager.Controllers
// 可以在这里构建表达式树过滤条件
Expression<Func<T, bool>> filter = null;
var pagedResult = await _repository.GetPagedAsync(filter, pagingParams);
return await ExportFile<T>(pagedResult.Data, Guid.NewGuid().ToString() + ".xlsx");
return await ExportFile(pagedResult.Data.ToDataTable(), Guid.NewGuid().ToString() + ".xlsx");
}
[NonAction]
@ -378,7 +380,15 @@ namespace TaskManager.Controllers
var pagedResult = await _repository.GetPagedAsync(filter, pagingParams);
return Ok(pagedResult);
}
protected async Task<FileStreamResult> ExportFile(DataTable dtos, string fileName)
{
var excelExporter = HttpContext.RequestServices.GetRequiredService<IExcelExporter>();
var res = await excelExporter.ExportAsByteArray(dtos);
return new FileStreamResult(new MemoryStream(res), "application/octet-stream") { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "_" + fileName };
}

156
API/Wood.Service/Controllers/NormalBaseController.cs

@ -16,6 +16,8 @@ using TaskManager.Entity;
using TaskManager.EntityFramework;
using TaskManager.EntityFramework.Repository;
using Wood.Util;
using Magicodes.ExporterAndImporter.Core.Extension;
namespace Wood.Service.Controllers
{
@ -139,7 +141,7 @@ namespace Wood.Service.Controllers
var pagedResult = await _repository.GetPagedAsync(null, pagingParams);
var dataTable=pagedResult.Data.ToDataTable();
var dataTable = pagedResult.Data.ToDataTable();
@ -194,155 +196,5 @@ namespace Wood.Service.Controllers
}
public static class DataTableHelper
{
/// <summary>
/// 将泛型列表转换为DataTable
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="list">泛型列表</param>
/// <param name="config">转换配置(可选)</param>
/// <returns>DataTable</returns>
public static DataTable ToDataTable<T>(this List<T> list, Action<DataTableConfig<T>> config = null)
{
if (list == null || list.Count == 0)
return new DataTable();
var tableConfig = new DataTableConfig<T>();
config?.Invoke(tableConfig);
var dataTable = new DataTable();
var properties = GetProperties(typeof(T), tableConfig);
// 创建列
foreach (var property in properties)
{
var columnType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
var columnName = tableConfig.ColumnMappings.TryGetValue(property.Name, out var mappedName)
? mappedName
: property.Name;
var column = new DataColumn(columnName, columnType);
dataTable.Columns.Add(column);
}
// 填充数据
foreach (var item in list)
{
var row = dataTable.NewRow();
foreach (var property in properties)
{
var columnName = tableConfig.ColumnMappings.TryGetValue(property.Name, out var mappedName)
? mappedName
: property.Name;
var value = property.GetValue(item);
row[columnName] = value ?? DBNull.Value;
}
dataTable.Rows.Add(row);
}
return dataTable;
}
/// <summary>
/// 获取需要转换的属性列表
/// </summary>
private static PropertyInfo[] GetProperties(Type type, DataTableConfig config)
{
var bindingFlags = BindingFlags.Public | BindingFlags.Instance;
if (config.IgnoreNonPublicProperties)
bindingFlags &= ~BindingFlags.NonPublic;
var properties = type.GetProperties(bindingFlags);
if (config.IgnoreProperties?.Count > 0)
{
properties = Array.FindAll(properties, p => !config.IgnoreProperties.Contains(p.Name));
}
if (config.OnlyIncludeProperties?.Count > 0)
{
properties = Array.FindAll(properties, p => config.OnlyIncludeProperties.Contains(p.Name));
}
return properties;
}
/// <summary>
/// 数据转换配置类
/// </summary>
public class DataTableConfig<T> : DataTableConfig
{
public new Dictionary<string, string> ColumnMappings { get; } = new Dictionary<string, string>();
/// <summary>
/// 设置列映射(属性名 -> 列名)
/// </summary>
public DataTableConfig<T> MapColumn(string propertyName, string columnName)
{
ColumnMappings[propertyName] = columnName;
return this;
}
/// <summary>
/// 设置忽略的属性
/// </summary>
public new DataTableConfig<T> IgnoreProperty(params string[] propertyNames)
{
base.IgnoreProperty(propertyNames);
return this;
}
/// <summary>
/// 设置只包含的属性
/// </summary>
public new DataTableConfig<T> OnlyIncludeProperty(params string[] propertyNames)
{
base.OnlyIncludeProperty(propertyNames);
return this;
}
/// <summary>
/// 设置是否忽略非公共属性(默认忽略)
/// </summary>
public new DataTableConfig<T> SetIgnoreNonPublicProperties(bool ignore = true)
{
base.SetIgnoreNonPublicProperties(ignore);
return this;
}
}
/// <summary>
/// 数据转换配置基类
/// </summary>
public class DataTableConfig
{
public HashSet<string> IgnoreProperties { get; } = new HashSet<string>();
public HashSet<string> OnlyIncludeProperties { get; } = new HashSet<string>();
public Dictionary<string, string> ColumnMappings { get; } = new Dictionary<string, string>();
public bool IgnoreNonPublicProperties { get; private set; } = true;
public DataTableConfig IgnoreProperty(params string[] propertyNames)
{
foreach (var name in propertyNames)
IgnoreProperties.Add(name);
return this;
}
public DataTableConfig OnlyIncludeProperty(params string[] propertyNames)
{
OnlyIncludeProperties.Clear();
foreach (var name in propertyNames)
OnlyIncludeProperties.Add(name);
return this;
}
public DataTableConfig SetIgnoreNonPublicProperties(bool ignore = true)
{
IgnoreNonPublicProperties = ignore;
return this;
}
}
}
}

74
API/Wood.Util/DataTableHelper.cs

@ -8,42 +8,42 @@ using System.Threading.Tasks;
namespace Wood.Util
{
public static class DataTableHelper
{
public static DataTable ListToDataTable<T>(List<T> entitys)
{
//检查实体集合不能为空
if (entitys == null || entitys.Count < 1)
{
throw new Exception("需转换的集合为空");
}
//取出第一个实体的所有Propertie
Type entityType = entitys[0]!.GetType();
PropertyInfo[] entityProperties = entityType.GetProperties();
//public static class DataTableHelper
//{
// public static DataTable ListToDataTable<T>(List<T> entitys)
// {
// //检查实体集合不能为空
// if (entitys == null || entitys.Count < 1)
// {
// throw new Exception("需转换的集合为空");
// }
// //取出第一个实体的所有Propertie
// Type entityType = entitys[0]!.GetType();
// PropertyInfo[] entityProperties = entityType.GetProperties();
//生成DataTable的structure
//生产代码中,应将生成的DataTable结构Cache起来,此处略
DataTable dt = new DataTable();
for (int i = 0; i < entityProperties.Length; i++)
{
dt.Columns.Add(entityProperties[i].Name);
}
//将所有entity添加到DataTable中
foreach (object? entity in entitys)
{
//检查所有的的实体都为同一类型
if (entity?.GetType() != entityType)
{
throw new Exception("要转换的集合元素类型不一致");
}
object[] entityValues = new object[entityProperties.Length];
for (int i = 0; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(entity, null)!;
}
dt.Rows.Add(entityValues);
}
return dt;
}
}
// //生成DataTable的structure
// //生产代码中,应将生成的DataTable结构Cache起来,此处略
// DataTable dt = new DataTable();
// for (int i = 0; i < entityProperties.Length; i++)
// {
// dt.Columns.Add(entityProperties[i].Name);
// }
// //将所有entity添加到DataTable中
// foreach (object? entity in entitys)
// {
// //检查所有的的实体都为同一类型
// if (entity?.GetType() != entityType)
// {
// throw new Exception("要转换的集合元素类型不一致");
// }
// object[] entityValues = new object[entityProperties.Length];
// for (int i = 0; i < entityProperties.Length; i++)
// {
// entityValues[i] = entityProperties[i].GetValue(entity, null)!;
// }
// dt.Rows.Add(entityValues);
// }
// return dt;
// }
//}
}

157
API/Wood.Util/EntityHelper.cs

@ -1,9 +1,11 @@
using Serilog;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
@ -69,6 +71,161 @@ namespace Wood.Util
}
public static class DataTableHelper
{
/// <summary>
/// 将泛型列表转换为DataTable
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="list">泛型列表</param>
/// <param name="config">转换配置(可选)</param>
/// <returns>DataTable</returns>
public static DataTable ToDataTable<T>(this List<T> list, Action<DataTableConfig<T>> config = null)
{
if (list == null || list.Count == 0)
return new DataTable();
var tableConfig = new DataTableConfig<T>();
config?.Invoke(tableConfig);
var dataTable = new DataTable();
var properties = GetProperties(typeof(T), tableConfig);
// 创建列
foreach (var property in properties)
{
var columnType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
var columnName = tableConfig.ColumnMappings.TryGetValue(property.Name, out var mappedName)
? mappedName
: property.Name;
var column = new DataColumn(columnName, columnType);
dataTable.Columns.Add(column);
}
// 填充数据
foreach (var item in list)
{
var row = dataTable.NewRow();
foreach (var property in properties)
{
var columnName = tableConfig.ColumnMappings.TryGetValue(property.Name, out var mappedName)
? mappedName
: property.Name;
var value = property.GetValue(item);
row[columnName] = value ?? DBNull.Value;
}
dataTable.Rows.Add(row);
}
return dataTable;
}
/// <summary>
/// 获取需要转换的属性列表
/// </summary>
private static PropertyInfo[] GetProperties(Type type, DataTableConfig config)
{
var bindingFlags = BindingFlags.Public | BindingFlags.Instance;
if (config.IgnoreNonPublicProperties)
bindingFlags &= ~BindingFlags.NonPublic;
var properties = type.GetProperties(bindingFlags);
if (config.IgnoreProperties?.Count > 0)
{
properties = Array.FindAll(properties, p => !config.IgnoreProperties.Contains(p.Name));
}
if (config.OnlyIncludeProperties?.Count > 0)
{
properties = Array.FindAll(properties, p => config.OnlyIncludeProperties.Contains(p.Name));
}
return properties;
}
/// <summary>
/// 数据转换配置类
/// </summary>
public class DataTableConfig<T> : DataTableConfig
{
public new Dictionary<string, string> ColumnMappings { get; } = new Dictionary<string, string>();
/// <summary>
/// 设置列映射(属性名 -> 列名)
/// </summary>
public DataTableConfig<T> MapColumn(string propertyName, string columnName)
{
ColumnMappings[propertyName] = columnName;
return this;
}
/// <summary>
/// 设置忽略的属性
/// </summary>
public new DataTableConfig<T> IgnoreProperty(params string[] propertyNames)
{
base.IgnoreProperty(propertyNames);
return this;
}
/// <summary>
/// 设置只包含的属性
/// </summary>
public new DataTableConfig<T> OnlyIncludeProperty(params string[] propertyNames)
{
base.OnlyIncludeProperty(propertyNames);
return this;
}
/// <summary>
/// 设置是否忽略非公共属性(默认忽略)
/// </summary>
public new DataTableConfig<T> SetIgnoreNonPublicProperties(bool ignore = true)
{
base.SetIgnoreNonPublicProperties(ignore);
return this;
}
}
/// <summary>
/// 数据转换配置基类
/// </summary>
public class DataTableConfig
{
public HashSet<string> IgnoreProperties { get; } = new HashSet<string>();
public HashSet<string> OnlyIncludeProperties { get; } = new HashSet<string>();
public Dictionary<string, string> ColumnMappings { get; } = new Dictionary<string, string>();
public bool IgnoreNonPublicProperties { get; private set; } = true;
public DataTableConfig IgnoreProperty(params string[] propertyNames)
{
foreach (var name in propertyNames)
IgnoreProperties.Add(name);
return this;
}
public DataTableConfig OnlyIncludeProperty(params string[] propertyNames)
{
OnlyIncludeProperties.Clear();
foreach (var name in propertyNames)
OnlyIncludeProperties.Add(name);
return this;
}
public DataTableConfig SetIgnoreNonPublicProperties(bool ignore = true)
{
IgnoreNonPublicProperties = ignore;
return this;
}
}
}

Loading…
Cancel
Save