考试管理新增人工阅卷处理完成状态

master
xiaochanghai 2 weeks ago
parent eeb5ffe4ee
commit fcf53eec8b
  1. BIN
      Lib/Tiobon.Core.Base.dll
  2. BIN
      Lib/Tiobon.Core.dll
  3. 1072
      Lib/Tiobon.Core.xml
  4. 2
      Tiobon.Core.Common/DB/EntityUtility.cs
  5. 22
      Tiobon.Core.Common/Extensions/AssemblysExtensions.cs
  6. 163
      Tiobon.Core.Common/Extensions/Check.cs
  7. 16
      Tiobon.Core.Common/Extensions/DictionaryExtensions.cs
  8. 56
      Tiobon.Core.Common/Extensions/ExpressionCombiner.cs
  9. 211
      Tiobon.Core.Common/Extensions/ExpressionExtensions.cs
  10. 143
      Tiobon.Core.Common/Extensions/ExpressionExtensions_Nacos.cs
  11. 383
      Tiobon.Core.Common/Extensions/Extention.Expression.cs
  12. 373
      Tiobon.Core.Common/Extensions/GenericTypeExtensions.cs
  13. 37
      Tiobon.Core.Common/Extensions/HttpRequestExtension.cs
  14. 423
      Tiobon.Core.Common/Extensions/IQueryableExtensions.cs
  15. 16
      Tiobon.Core.Common/Extensions/MethodInfoExtensions.cs
  16. 92
      Tiobon.Core.Common/Extensions/TypeExtensions.cs
  17. 99
      Tiobon.Core.Common/Helper/Base32Helper.cs
  18. 232
      Tiobon.Core.Common/Helper/Base64Encoder.cs
  19. 515
      Tiobon.Core.Common/Helper/DynamicLinqFactory.cs
  20. 23
      Tiobon.Core.Common/Helper/HtmlHelper.cs
  21. 54
      Tiobon.Core.Common/Helper/HttpHelper.cs
  22. 49
      Tiobon.Core.Common/Helper/IpHelper.cs
  23. 238
      Tiobon.Core.Common/Helper/JsonConfigUtils.cs
  24. 29
      Tiobon.Core.Common/Helper/LinqHelper.cs
  25. 32
      Tiobon.Core.Common/Helper/LoggerHelper.cs
  26. 96
      Tiobon.Core.Common/Helper/MD5Hepler.cs
  27. 967
      Tiobon.Core.Common/Helper/NPOIHelper.cs
  28. 297
      Tiobon.Core.Common/Helper/SM/SM4.cs
  29. 93
      Tiobon.Core.Common/Helper/SM/SM4Helper.cs
  30. 17
      Tiobon.Core.Common/Helper/SM/SM4_Context.cs
  31. 4
      Tiobon.Core.Common/Seed/DBSeed.cs
  32. 7
      Tiobon.Core.DataAccess/ReportHelper.cs
  33. 5
      Tiobon.Core.EventBus/EventBusKafka/EventBusKafka.cs
  34. 5
      Tiobon.Core.EventBus/RabbitMQPersistent/EventBusRabbitMQ.cs
  35. 2
      Tiobon.Core.Extensions/AOP/CacheAOPbase.cs
  36. 2
      Tiobon.Core.Extensions/NacosConfig/NacosListenConfigurationTask.cs
  37. 3
      Tiobon.Core.Extensions/NacosConfig/NacosListenNamingTask.cs
  38. 3
      Tiobon.Core.Extensions/ServiceExtensions/NacosSetup.cs
  39. 7
      Tiobon.Core.Gateway/Helper/CustomJwtTokenAuthMiddleware.cs
  40. 11
      Tiobon.Core.Repository/BASE/BaseRepository.cs
  41. 2
      Tiobon.Core.Repository/UnitOfWorks/UnitOfWorkManage.cs
  42. 2
      Tiobon.Core.Serilog/Utility/SerilogRequestUtility.cs
  43. 4
      Tiobon.Core.Services/TasksLogServices.cs
  44. 2
      Tiobon.Core.Tasks/QuartzNet/Jobs/Job_URL_Quartz.cs
  45. 8
      Tiobon.Core.Tests/Common_Test/DynamicLambdaTest.cs
  46. 2
      Tiobon.Core.Tests/Common_Test/HttpHelper_Should.cs

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

@ -1,7 +1,7 @@
using SqlSugar;
using System.Diagnostics;
using System.Reflection;
using Tiobon.Core.Common.Extensions;
using Tiobon.Core.Extensions;
using Tiobon.Core.DB;
using Tiobon.Core.Model;

@ -1,22 +0,0 @@
using Microsoft.Extensions.DependencyModel;
using System.Reflection;
using System.Runtime.Loader;
namespace Tiobon.Core.Common.Extensions;
public static class AssemblysExtensions
{
public static List<Assembly> GetAllAssemblies()
{
var list = new List<Assembly>();
var deps = DependencyContext.Default;
var libs = deps.CompileLibraries.Where(lib => !lib.Serviceable && lib.Type != "package" );
foreach (var lib in libs)
{
var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(lib.Name));
list.Add(assembly);
}
return list;
}
}

@ -1,163 +0,0 @@
using JetBrains.Annotations;
using System.Diagnostics;
namespace Tiobon.Core.Common;
[DebuggerStepThrough]
public static class Check
{
[ContractAnnotation("value:null => halt")]
public static T NotNull<T>(
T value,
[InvokerParameterName][NotNull] string parameterName)
{
if (value == null)
{
throw new ArgumentNullException(parameterName);
}
return value;
}
[ContractAnnotation("value:null => halt")]
public static T NotNull<T>(
T value,
[InvokerParameterName][NotNull] string parameterName,
string message)
{
if (value == null)
{
throw new ArgumentNullException(parameterName, message);
}
return value;
}
[ContractAnnotation("value:null => halt")]
public static string NotNull(
string value,
[InvokerParameterName][NotNull] string parameterName,
int maxLength = int.MaxValue,
int minLength = 0)
{
if (value == null)
{
throw new ArgumentException($"{parameterName} can not be null!", parameterName);
}
if (value.Length > maxLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or lower than {maxLength}!", parameterName);
}
if (minLength > 0 && value.Length < minLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or bigger than {minLength}!", parameterName);
}
return value;
}
[ContractAnnotation("value:null => halt")]
public static string NotNullOrWhiteSpace(
string value,
[InvokerParameterName][NotNull] string parameterName,
int maxLength = int.MaxValue,
int minLength = 0)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException($"{parameterName} can not be null, empty or white space!", parameterName);
}
if (value.Length > maxLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or lower than {maxLength}!", parameterName);
}
if (minLength > 0 && value.Length < minLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or bigger than {minLength}!", parameterName);
}
return value;
}
[ContractAnnotation("value:null => halt")]
public static string NotNullOrEmpty(
string value,
[InvokerParameterName][NotNull] string parameterName,
int maxLength = int.MaxValue,
int minLength = 0)
{
if (value.IsNullOrEmpty())
{
throw new ArgumentException($"{parameterName} can not be null or empty!", parameterName);
}
if (value.Length > maxLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or lower than {maxLength}!", parameterName);
}
if (minLength > 0 && value.Length < minLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or bigger than {minLength}!", parameterName);
}
return value;
}
[ContractAnnotation("value:null => halt")]
public static ICollection<T> NotNullOrEmpty<T>(ICollection<T> value, [InvokerParameterName][NotNull] string parameterName)
{
if (value == null || value.Count <= 0)
{
throw new ArgumentException(parameterName + " can not be null or empty!", parameterName);
}
return value;
}
[ContractAnnotation("type:null => halt")]
public static Type AssignableTo<TBaseType>(
Type type,
[InvokerParameterName][NotNull] string parameterName)
{
NotNull(type, parameterName);
if (!type.IsAssignableTo<TBaseType>())
{
throw new ArgumentException($"{parameterName} (type of {type.AssemblyQualifiedName}) should be assignable to the {typeof(TBaseType).GetFullNameWithAssemblyName()}!");
}
return type;
}
public static string Length(
[CanBeNull] string value,
[InvokerParameterName][NotNull] string parameterName,
int maxLength,
int minLength = 0)
{
if (minLength > 0)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(parameterName + " can not be null or empty!", parameterName);
}
if (value.Length < minLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or bigger than {minLength}!", parameterName);
}
}
if (value != null && value.Length > maxLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or lower than {maxLength}!", parameterName);
}
return value;
}
}

@ -1,16 +0,0 @@
namespace Tiobon.Core.Common.Extensions;
public static class DictionaryExtensions
{
public static void TryAdd<TKey, TValue>(this IDictionary<TKey, List<TValue>> dic, TKey key, TValue value)
{
if (dic.TryGetValue(key, out var old))
{
old.Add(value);
}
else
{
dic.Add(key, new List<TValue> {value});
}
}
}

@ -1,56 +0,0 @@
using System.Linq.Expressions;
namespace Tiobon.Core.Common.Helper;
public static class ExpressionCombiner
{
public static Expression<Func<T, bool>> Combine<T>(Expression<Func<T, bool>> expression1, Expression<Func<T, bool>> expression2)
{
if (expression1 == null && expression2 == null)
{
return null;
}
if (expression1 == null)
{
return expression2;
}
if (expression2 == null)
{
return expression1;
}
var parameter = Expression.Parameter(typeof(T));
var leftVisitor = new ReplaceExpressionVisitor(expression1.Parameters[0], parameter);
var left = leftVisitor.Visit(expression1.Body);
var rightVisitor = new ReplaceExpressionVisitor(expression2.Parameters[0], parameter);
var right = rightVisitor.Visit(expression2.Body);
return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(left, right), parameter);
}
class ReplaceExpressionVisitor : ExpressionVisitor
{
private readonly Expression _oldValue;
private readonly Expression _newValue;
public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
{
_oldValue = oldValue;
_newValue = newValue;
}
public override Expression Visit(Expression node)
{
if (node == _oldValue)
{
return _newValue;
}
return base.Visit(node);
}
}
}

@ -1,211 +0,0 @@
using Microsoft.AspNetCore.Http;
using System.Linq.Expressions;
using Tiobon.Core.Caches;
namespace Tiobon.Core.Common.Helper;
/// <summary>
/// Linq扩展
/// </summary>
public static class ExpressionExtensions
{
#region HttpContext
/// <summary>
/// 返回请求上下文
/// </summary>
/// <param name="context"></param>
/// <param name="code"></param>
/// <param name="message"></param>
/// <param name="ContentType"></param>
/// <returns></returns>
public static async Task Cof_SendResponse(this HttpContext context, System.Net.HttpStatusCode code, string message,
string ContentType = "text/html;charset=utf-8")
{
context.Response.StatusCode = (int) code;
context.Response.ContentType = ContentType;
await context.Response.WriteAsync(message);
}
#endregion
#region ICaching
/// <summary>
/// 从缓存里取数据,如果不存在则执行查询方法,
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="cache">ICaching </param>
/// <param name="key">键值</param>
/// <param name="GetFun">查询方法</param>
/// <param name="timeSpanMin">有效期 单位分钟/param>
/// <returns></returns>
public static T Cof_GetICaching<T>(this ICaching cache, string key, Func<T> GetFun, int timeSpanMin) where T : class
{
var obj = cache.Get<T>(key);
if (obj == null)
{
obj = GetFun();
cache.Set(key, obj, TimeSpan.FromMinutes(timeSpanMin));
}
return obj;
}
/// <summary>
/// 异步从缓存里取数据,如果不存在则执行查询方法
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="cache">ICaching </param>
/// <param name="key">键值</param>
/// <param name="GetFun">查询方法</param>
/// <param name="timeSpanMin">有效期 单位分钟/param>
/// <returns></returns>
public static async Task<T> Cof_AsyncGetICaching<T>(this ICaching cache, string key, Func<Task<T>> GetFun, int timeSpanMin) where T : class
{
var obj = await cache.GetAsync<T>(key);
if (obj == null)
{
obj = await GetFun();
cache.Set(key, obj, TimeSpan.FromMinutes(timeSpanMin));
}
return obj;
}
#endregion
#region 常用扩展方法
public static bool Cof_CheckAvailable<TSource>(this IEnumerable<TSource> Tlist)
{
return Tlist != null && Tlist.Count() > 0;
}
/// <summary>
/// 调用内部方法
/// </summary>
public static Expression Call(this Expression instance, string methodName, params Expression[] arguments)
{
if (instance.Type == typeof(string))
return Expression.Call(instance, instance.Type.GetMethod(methodName, new Type[] {typeof(string)}),
arguments); //修复string contains 出现的问题 Ambiguous match found.
else
return Expression.Call(instance, instance.Type.GetMethod(methodName), arguments);
}
/// <summary>
/// 获取内部成员
/// </summary>
public static Expression Property(this Expression expression, string propertyName)
{
// Todo:左边条件如果是dynamic,
// 则Expression.Property无法获取子内容
// 报错在这里,由于expression内的对象为Object,所以无法解析到
// var x = (expression as IQueryable).ElementType;
var exp = Expression.Property(expression, propertyName);
if (exp.Type.IsGenericType && exp.Type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return Expression.Convert(exp, exp.Type.GetGenericArguments()[0]);
}
return exp;
}
/// <summary>
/// 转Lambda
/// </summary>
public static Expression<TDelegate> ToLambda<TDelegate>(this Expression body,
params ParameterExpression[] parameters)
{
return Expression.Lambda<TDelegate>(body, parameters);
}
#endregion
#region 常用运算符 [ > , >= , == , < , <= , != , || , && ]
/// <summary>
/// &&
/// </summary>
public static Expression AndAlso(this Expression left, Expression right)
{
return Expression.AndAlso(left, right);
}
/// <summary>
/// ||
/// </summary>
public static Expression OrElse(this Expression left, Expression right)
{
return Expression.OrElse(left, right);
}
/// <summary>
/// Contains
/// </summary>
public static Expression Contains(this Expression left, Expression right)
{
return left.Call("Contains", right);
}
public static Expression StartContains(this Expression left, Expression right)
{
return left.Call("StartsWith", right);
}
public static Expression EndContains(this Expression left, Expression right)
{
return left.Call("EndsWith", right);
}
/// <summary>
/// >
/// </summary>
public static Expression GreaterThan(this Expression left, Expression right)
{
return Expression.GreaterThan(left, right);
}
/// <summary>
/// >=
/// </summary>
public static Expression GreaterThanOrEqual(this Expression left, Expression right)
{
return Expression.GreaterThanOrEqual(left, right);
}
/// <summary>
/// <
/// </summary>
public static Expression LessThan(this Expression left, Expression right)
{
return Expression.LessThan(left, right);
}
/// <summary>
/// <=
/// </summary>
public static Expression LessThanOrEqual(this Expression left, Expression right)
{
return Expression.LessThanOrEqual(left, right);
}
/// <summary>
/// ==
/// </summary>
public static Expression Equal(this Expression left, Expression right)
{
return Expression.Equal(left, right);
}
/// <summary>
/// !=
/// </summary>
public static Expression NotEqual(this Expression left, Expression right)
{
return Expression.NotEqual(left, right);
}
#endregion
}

@ -1,143 +0,0 @@
namespace Tiobon.Core.Common.Helper;
/// <summary>
/// Linq扩展
/// </summary>
public static class ExpressionExtensions_Nacos
{
//#region Nacos NamingService
//private static string GetServiceUrl(Nacos.V2.INacosNamingService serv, string ServiceName, string Group,
// string apiurl)
//{
// try
// {
// var instance = serv.SelectOneHealthyInstance(ServiceName, Group).GetAwaiter().GetResult();
// var host = $"{instance.Ip}:{instance.Port}";
// if (instance.Metadata.ContainsKey("endpoint")) host = instance.Metadata["endpoint"];
// var baseUrl = instance.Metadata.TryGetValue("secure", out _)
// ? $"https://{host}"
// : $"http://{host}";
// if (string.IsNullOrWhiteSpace(baseUrl))
// {
// return "";
// }
// return $"{baseUrl}{apiurl}";
// }
// catch (Exception e)
// {
// Console.WriteLine(e.Message);
// }
// return "";
//}
//public static async Task<string> Cof_NaoceGet(this Nacos.V2.INacosNamingService serv, string ServiceName,
// string Group, string apiurl, Dictionary<string, string> Parameters = null)
//{
// try
// {
// var url = GetServiceUrl(serv, ServiceName, Group, apiurl);
// if (string.IsNullOrEmpty(url)) return "";
// if (Parameters != null && Parameters.Any())
// {
// StringBuilder sb = new StringBuilder();
// foreach (var pitem in Parameters)
// {
// sb.Append($"{pitem.Key}={pitem.Value}&");
// }
// url = $"{url}?{sb.ToString().Trim('&')}";
// }
// HttpHelper.Httpclient.DefaultRequestHeaders.Accept.Add(
// new MediaTypeWithQualityHeaderValue("application/json"));
// var result = await HttpHelper.Httpclient.GetAsync(url);
// return await result.Content.ReadAsStringAsync();
// }
// catch (Exception e)
// {
// Console.WriteLine(e.Message);
// }
// return "";
//}
//public static async Task<string> Cof_NaocePostForm(this Nacos.V2.INacosNamingService serv, string ServiceName,
// string Group, string apiurl, Dictionary<string, string> Parameters)
//{
// try
// {
// var url = GetServiceUrl(serv, ServiceName, Group, apiurl);
// if (string.IsNullOrEmpty(url)) return "";
// var content = (Parameters != null && Parameters.Any()) ? new FormUrlEncodedContent(Parameters) : null;
// HttpHelper.Httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// var result = await HttpHelper.Httpclient.PostAsync(url, content);
// return await result.Content.ReadAsStringAsync(); //.GetAwaiter().GetResult();
// }
// catch (Exception e)
// {
// Console.WriteLine(e.Message);
// }
// return "";
//}
//public static async Task<string> Cof_NaocePostJson(this Nacos.V2.INacosNamingService serv, string ServiceName,
// string Group, string apiurl, string jSonData)
//{
// try
// {
// var url = GetServiceUrl(serv, ServiceName, Group, apiurl);
// if (string.IsNullOrEmpty(url)) return "";
// HttpHelper.Httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// var result =
// await HttpHelper.Httpclient.PostAsync(url, new StringContent(jSonData, Encoding.UTF8, "application/json"));
// return await result.Content.ReadAsStringAsync(); //.GetAwaiter().GetResult();
// //httpClient.BaseAddress = new Uri("https://www.testapi.com");
// //httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
// }
// catch (Exception e)
// {
// Console.WriteLine(e.Message);
// }
// return "";
//}
//public static async Task<string> Cof_NaocePostFile(this Nacos.V2.INacosNamingService serv, string ServiceName,
// string Group, string apiurl, Dictionary<string, byte[]> Parameters)
//{
// try
// {
// var url = GetServiceUrl(serv, ServiceName, Group, apiurl);
// if (string.IsNullOrEmpty(url)) return "";
// var content = new MultipartFormDataContent();
// foreach (var pitem in Parameters)
// {
// content.Add(new ByteArrayContent(pitem.Value), "files", pitem.Key);
// }
// HttpHelper.Httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// var result = await HttpHelper.Httpclient.PostAsync(url, content);
// return await result.Content.ReadAsStringAsync(); //.GetAwaiter().GetResult();
// }
// catch (Exception e)
// {
// //InfluxdbHelper.GetInstance().AddLog("Cof_NaocePostFile.Err", ee);
// Console.WriteLine(e.Message);
// }
// return "";
//}
//#endregion
}

@ -1,383 +0,0 @@
using System.Linq.Expressions;
using System.Reflection;
namespace Tiobon.Core.Common.Extensions;
public static partial class Extention
{
#region 拓展BuildExtendSelectExpre方法
/// <summary>
/// 组合继承属性选择表达式树,无拓展参数
/// TResult将继承TBase的所有属性
/// </summary>
/// <typeparam name="TBase">原数据类型</typeparam>
/// <typeparam name="TResult">返回类型</typeparam>
/// <param name="expression">拓展表达式</param>
/// <returns></returns>
public static Expression<Func<TBase, TResult>> BuildExtendSelectExpre<TBase, TResult>(this Expression<Func<TBase, TResult>> expression) where TResult : TBase
{
return GetExtendSelectExpre<TBase, TResult, Func<TBase, TResult>>(expression);
}
/// <summary>
/// 组合继承属性选择表达式树,1个拓展参数
/// TResult将继承TBase的所有属性
/// </summary>
/// <typeparam name="TBase">原数据类型</typeparam>
/// <typeparam name="T1">拓展类型1</typeparam>
/// <typeparam name="TResult">返回类型</typeparam>
/// <param name="expression">拓展表达式</param>
/// <returns></returns>
public static Expression<Func<TBase, T1, TResult>> BuildExtendSelectExpre<TBase, T1, TResult>(this Expression<Func<TBase, T1, TResult>> expression) where TResult : TBase
{
return GetExtendSelectExpre<TBase, TResult, Func<TBase, T1, TResult>>(expression);
}
/// <summary>
/// 组合继承属性选择表达式树,2个拓展参数
/// TResult将继承TBase的所有属性
/// </summary>
/// <typeparam name="TBase">原数据类型</typeparam>
/// <typeparam name="T1">拓展类型1</typeparam>
/// <typeparam name="T2">拓展类型2</typeparam>
/// <typeparam name="TResult">返回类型</typeparam>
/// <param name="expression">拓展表达式</param>
/// <returns></returns>
public static Expression<Func<TBase, T1, T2, TResult>> BuildExtendSelectExpre<TBase, T1, T2, TResult>(this Expression<Func<TBase, T1, T2, TResult>> expression) where TResult : TBase
{
return GetExtendSelectExpre<TBase, TResult, Func<TBase, T1, T2, TResult>>(expression);
}
/// <summary>
/// 组合继承属性选择表达式树,3个拓展参数
/// TResult将继承TBase的所有属性
/// </summary>
/// <typeparam name="TBase">原数据类型</typeparam>
/// <typeparam name="T1">拓展类型1</typeparam>
/// <typeparam name="T2">拓展类型2</typeparam>
/// <typeparam name="T3">拓展类型3</typeparam>
/// <typeparam name="TResult">返回类型</typeparam>
/// <param name="expression">拓展表达式</param>
/// <returns></returns>
public static Expression<Func<TBase, T1, T2, T3, TResult>> BuildExtendSelectExpre<TBase, T1, T2, T3, TResult>(this Expression<Func<TBase, T1, T2, T3, TResult>> expression) where TResult : TBase
{
return GetExtendSelectExpre<TBase, TResult, Func<TBase, T1, T2, T3, TResult>>(expression);
}
/// <summary>
/// 组合继承属性选择表达式树,4个拓展参数
/// TResult将继承TBase的所有属性
/// </summary>
/// <typeparam name="TBase">原数据类型</typeparam>
/// <typeparam name="T1">拓展类型1</typeparam>
/// <typeparam name="T2">拓展类型2</typeparam>
/// <typeparam name="T3">拓展类型3</typeparam>
/// <typeparam name="T4">拓展类型4</typeparam>
/// <typeparam name="TResult">返回类型</typeparam>
/// <param name="expression">拓展表达式</param>
/// <returns></returns>
public static Expression<Func<TBase, T1, T2, T3, T4, TResult>> BuildExtendSelectExpre<TBase, T1, T2, T3, T4, TResult>(this Expression<Func<TBase, T1, T2, T3, T4, TResult>> expression) where TResult : TBase
{
return GetExtendSelectExpre<TBase, TResult, Func<TBase, T1, T2, T3, T4, TResult>>(expression);
}
/// <summary>
/// 组合继承属性选择表达式树,5个拓展参数
/// TResult将继承TBase的所有属性
/// </summary>
/// <typeparam name="TBase">原数据类型</typeparam>
/// <typeparam name="T1">拓展类型1</typeparam>
/// <typeparam name="T2">拓展类型2</typeparam>
/// <typeparam name="T3">拓展类型3</typeparam>
/// <typeparam name="T4">拓展类型4</typeparam>
/// <typeparam name="T5">拓展类型5</typeparam>
/// <typeparam name="TResult">返回类型</typeparam>
/// <param name="expression">拓展表达式</param>
/// <returns></returns>
public static Expression<Func<TBase, T1, T2, T3, T4, T5, TResult>> BuildExtendSelectExpre<TBase, T1, T2, T3, T4, T5, TResult>(this Expression<Func<TBase, T1, T2, T3, T4, T5, TResult>> expression) where TResult : TBase
{
return GetExtendSelectExpre<TBase, TResult, Func<TBase, T1, T2, T3, T4, T5, TResult>>(expression);
}
/// <summary>
/// 组合继承属性选择表达式树,6个拓展参数
/// TResult将继承TBase的所有属性
/// </summary>
/// <typeparam name="TBase">原数据类型</typeparam>
/// <typeparam name="T1">拓展类型1</typeparam>
/// <typeparam name="T2">拓展类型2</typeparam>
/// <typeparam name="T3">拓展类型3</typeparam>
/// <typeparam name="T4">拓展类型4</typeparam>
/// <typeparam name="T5">拓展类型5</typeparam>
/// <typeparam name="T6">拓展类型6</typeparam>
/// <typeparam name="TResult">返回类型</typeparam>
/// <param name="expression">拓展表达式</param>
/// <returns></returns>
public static Expression<Func<TBase, T1, T2, T3, T4, T5, T6, TResult>> BuildExtendSelectExpre<TBase, T1, T2, T3, T4, T5, T6, TResult>(this Expression<Func<TBase, T1, T2, T3, T4, T5, T6, TResult>> expression) where TResult : TBase
{
return GetExtendSelectExpre<TBase, TResult, Func<TBase, T1, T2, T3, T4, T5, T6, TResult>>(expression);
}
/// <summary>
/// 组合继承属性选择表达式树,7个拓展参数
/// TResult将继承TBase的所有属性
/// </summary>
/// <typeparam name="TBase">原数据类型</typeparam>
/// <typeparam name="T1">拓展类型1</typeparam>
/// <typeparam name="T2">拓展类型2</typeparam>
/// <typeparam name="T3">拓展类型3</typeparam>
/// <typeparam name="T4">拓展类型4</typeparam>
/// <typeparam name="T5">拓展类型5</typeparam>
/// <typeparam name="T6">拓展类型6</typeparam>
/// <typeparam name="T7">拓展类型7</typeparam>
/// <typeparam name="TResult">返回类型</typeparam>
/// <param name="expression">拓展表达式</param>
/// <returns></returns>
public static Expression<Func<TBase, T1, T2, T3, T4, T5, T6, T7, TResult>> BuildExtendSelectExpre<TBase, T1, T2, T3, T4, T5, T6, T7, TResult>(this Expression<Func<TBase, T1, T2, T3, T4, T5, T6, T7, TResult>> expression) where TResult : TBase
{
return GetExtendSelectExpre<TBase, TResult, Func<TBase, T1, T2, T3, T4, T5, T6, T7, TResult>>(expression);
}
/// <summary>
/// 组合继承属性选择表达式树,8个拓展参数
/// TResult将继承TBase的所有属性
/// </summary>
/// <typeparam name="TBase">原数据类型</typeparam>
/// <typeparam name="T1">拓展类型1</typeparam>
/// <typeparam name="T2">拓展类型2</typeparam>
/// <typeparam name="T3">拓展类型3</typeparam>
/// <typeparam name="T4">拓展类型4</typeparam>
/// <typeparam name="T5">拓展类型5</typeparam>
/// <typeparam name="T6">拓展类型6</typeparam>
/// <typeparam name="T7">拓展类型7</typeparam>
/// <typeparam name="T8">拓展类型8</typeparam>
/// <typeparam name="TResult">返回类型</typeparam>
/// <param name="expression">拓展表达式</param>
/// <returns></returns>
public static Expression<Func<TBase, T1, T2, T3, T4, T5, T6, T7, T8, TResult>> BuildExtendSelectExpre<TBase, T1, T2, T3, T4, T5, T6, T7, T8, TResult>(this Expression<Func<TBase, T1, T2, T3, T4, T5, T6, T7, T8, TResult>> expression) where TResult : TBase
{
return GetExtendSelectExpre<TBase, TResult, Func<TBase, T1, T2, T3, T4, T5, T6, T7, T8, TResult>>(expression);
}
/// <summary>
/// 组合继承属性选择表达式树,9个拓展参数
/// TResult将继承TBase的所有属性
/// </summary>
/// <typeparam name="TBase">原数据类型</typeparam>
/// <typeparam name="T1">拓展类型1</typeparam>
/// <typeparam name="T2">拓展类型2</typeparam>
/// <typeparam name="T3">拓展类型3</typeparam>
/// <typeparam name="T4">拓展类型4</typeparam>
/// <typeparam name="T5">拓展类型5</typeparam>
/// <typeparam name="T6">拓展类型6</typeparam>
/// <typeparam name="T7">拓展类型7</typeparam>
/// <typeparam name="T8">拓展类型8</typeparam>
/// <typeparam name="T9">拓展类型9</typeparam>
/// <typeparam name="TResult">返回类型</typeparam>
/// <param name="expression">拓展表达式</param>
/// <returns></returns>
public static Expression<Func<TBase, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>> BuildExtendSelectExpre<TBase, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>(this Expression<Func<TBase, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>> expression) where TResult : TBase
{
return GetExtendSelectExpre<TBase, TResult, Func<TBase, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>>(expression);
}
#endregion
#region 拓展And和Or方法
/// <summary>
/// 连接表达式与运算
/// </summary>
/// <typeparam name="T">参数</typeparam>
/// <param name="one">原表达式</param>
/// <param name="another">新的表达式</param>
/// <returns></returns>
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> one, Expression<Func<T, bool>> another)
{
//创建新参数
var newParameter = Expression.Parameter(typeof(T), "parameter");
var parameterReplacer = new ParameterReplaceVisitor(newParameter);
var left = parameterReplacer.Visit(one.Body);
var right = parameterReplacer.Visit(another.Body);
var body = Expression.AndAlso(left, right);
return Expression.Lambda<Func<T, bool>>(body, newParameter);
}
/// <summary>
/// 连接表达式或运算
/// </summary>
/// <typeparam name="T">参数</typeparam>
/// <param name="one">原表达式</param>
/// <param name="another">新表达式</param>
/// <returns></returns>
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> one, Expression<Func<T, bool>> another)
{
//创建新参数
var newParameter = Expression.Parameter(typeof(T), "parameter");
var parameterReplacer = new ParameterReplaceVisitor(newParameter);
var left = parameterReplacer.Visit(one.Body);
var right = parameterReplacer.Visit(another.Body);
var body = Expression.Or(left, right);
return Expression.Lambda<Func<T, bool>>(body, newParameter);
}
#endregion
#region 拓展Expression的Invoke方法
public static TResult Invoke<TResult>(this Expression<Func<TResult>> expression)
{
return expression.Compile().Invoke();
}
public static TResult Invoke<T1, TResult>(this Expression<Func<T1, TResult>> expression, T1 arg1)
{
return expression.Compile().Invoke(arg1);
}
public static TResult Invoke<T1, T2, TResult>(this Expression<Func<T1, T2, TResult>> expression, T1 arg1, T2 arg2)
{
return expression.Compile().Invoke(arg1, arg2);
}
public static TResult Invoke<T1, T2, T3, TResult>(this Expression<Func<T1, T2, T3, TResult>> expression, T1 arg1, T2 arg2, T3 arg3)
{
return expression.Compile().Invoke(arg1, arg2, arg3);
}
public static TResult Invoke<T1, T2, T3, T4, TResult>(this Expression<Func<T1, T2, T3, T4, TResult>> expression, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
return expression.Compile().Invoke(arg1, arg2, arg3, arg4);
}
public static TResult Invoke<T1, T2, T3, T4, T5, TResult>(this Expression<Func<T1, T2, T3, T4, T5, TResult>> expression, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
{
return expression.Compile().Invoke(arg1, arg2, arg3, arg4, arg5);
}
public static TResult Invoke<T1, T2, T3, T4, T5, T6, TResult>(this Expression<Func<T1, T2, T3, T4, T5, T6, TResult>> expression, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6)
{
return expression.Compile().Invoke(arg1, arg2, arg3, arg4, arg5, arg6);
}
public static TResult Invoke<T1, T2, T3, T4, T5, T6, T7, TResult>(this Expression<Func<T1, T2, T3, T4, T5, T6, T7, TResult>> expression, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7)
{
return expression.Compile().Invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7);
}
public static TResult Invoke<T1, T2, T3, T4, T5, T6, T7, T8, TResult>(this Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult>> expression, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8)
{
return expression.Compile().Invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
}
public static TResult Invoke<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>(this Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>> expression, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9)
{
return expression.Compile().Invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
}
public static TResult Invoke<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>(this Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>> expression, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10)
{
return expression.Compile().Invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
}
#endregion
/// <summary>
/// 获取表达式中的固定值
/// </summary>
/// <param name="expression">表达式</param>
/// <returns></returns>
public static object GetConstantValue(this Expression expression)
{
var visitor = new GetConstantValueVisitor();
visitor.Visit(expression);
return visitor.ConstantValue;
}
public static object GetMemberValue(this Expression expression)
{
var visitor = new GetMemberValueVisitor();
visitor.Visit(expression);
return visitor.Value;
}
#region 私有成员
private static Expression<TDelegate> GetExtendSelectExpre<TBase, TResult, TDelegate>(Expression<TDelegate> expression)
{
NewExpression newBody = Expression.New(typeof(TResult));
MemberInitExpression oldExpression = (MemberInitExpression)expression.Body;
ParameterExpression[] oldParamters = expression.Parameters.ToArray();
List<string> existsProperties = new List<string>();
foreach (var aBinding in oldExpression.Bindings)
{
existsProperties.Add(aBinding.Member.Name);
}
List<MemberBinding> newBindings = new List<MemberBinding>();
var ls = typeof(TResult).GetProperties().Where(x => !existsProperties.Contains(x.Name));
foreach (var aProperty in ls)
{
if (typeof(TBase).GetMembers().Any(x => x.Name == aProperty.Name))
{
MemberInfo newMember = typeof(TBase).GetMember(aProperty.Name)[0];
MemberBinding newMemberBinding = Expression.Bind(newMember, Expression.Property(oldParamters[0], aProperty.Name));
newBindings.Add(newMemberBinding);
}
}
newBindings.AddRange(oldExpression.Bindings);
var body = Expression.MemberInit(newBody, newBindings.ToArray());
var resExpression = Expression.Lambda<TDelegate>(body, oldParamters);
return resExpression;
}
#endregion
}
/// <summary>
/// 继承ExpressionVisitor类,实现参数替换统一
/// </summary>
class ParameterReplaceVisitor : ExpressionVisitor
{
public ParameterReplaceVisitor(ParameterExpression paramExpr)
{
_parameter = paramExpr;
}
//新的表达式参数
private ParameterExpression _parameter { get; set; }
protected override Expression VisitParameter(ParameterExpression p)
{
if (p.Type == _parameter.Type)
return _parameter;
else
return p;
}
}
class GetConstantValueVisitor : ExpressionVisitor
{
public object ConstantValue { get; set; }
protected override Expression VisitConstant(ConstantExpression node)
{
ConstantValue = node.Value;
return base.VisitConstant(node);
}
}
class GetMemberValueVisitor : ExpressionVisitor
{
public object Value { get; set; }
}

@ -1,373 +0,0 @@
using Newtonsoft.Json.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Tiobon.Core.Common.Extensions;
public static class GenericTypeExtensions
{
public static string GetGenericTypeName(this Type type)
{
var typeName = string.Empty;
if (type.IsGenericType)
{
var genericTypes = string.Join(",", type.GetGenericArguments().Select(t => t.Name).ToArray());
typeName = $"{type.Name.Remove(type.Name.IndexOf('`'))}<{genericTypes}>";
}
else
{
typeName = type.Name;
}
return typeName;
}
public static string GetGenericTypeName(this object @object)
{
return @object.GetType().GetGenericTypeName();
}
/// <summary>
/// 判断类型是否实现某个泛型
/// </summary>
/// <param name="type">类型</param>
/// <param name="generic">泛型类型</param>
/// <returns>bool</returns>
public static bool HasImplementedRawGeneric(this Type type, Type generic)
{
// 检查接口类型
var isTheRawGenericType = type.GetInterfaces().Any(IsTheRawGenericType);
if (isTheRawGenericType) return true;
// 检查类型
while (type != null && type != typeof(object))
{
isTheRawGenericType = IsTheRawGenericType(type);
if (isTheRawGenericType) return true;
type = type.BaseType;
}
return false;
// 判断逻辑
bool IsTheRawGenericType(Type t) => generic == (t.IsGenericType ? t.GetGenericTypeDefinition() : t);
}
/// <summary>
/// 复制 <paramref name="source"/> 的副本
/// </summary>
/// <typeparam name="TTarget"></typeparam>
/// <typeparam name="TSource"></typeparam>
/// <param name="target"></param>
/// <param name="source"></param>
/// <returns></returns>
public static T Clone<T>(T source)
where T : class
{
var text = System.Text.Json.JsonSerializer.Serialize(source, typeof(T));
return System.Text.Json.JsonSerializer.Deserialize<T>(text);
}
public static TTarget CloneTo<TTarget>(this object source, params object[] args)
where TTarget : class
{
var target = (TTarget)Activator.CreateInstance(typeof(TTarget), args);
return target.CopyFrom(source);
}
/// <summary>
/// 将 <paramref name="source"/> 的值复制到 <paramref name="target"/>,
/// 仅复制同名的属性或字段
/// </summary>
/// <typeparam name="TTarget"></typeparam>
/// <typeparam name="TSource"></typeparam>
/// <param name="target"></param>
/// <param name="source"></param>
/// <returns></returns>
public static TTarget CopyFrom<TTarget, TSource>(this TTarget target, TSource source)
where TTarget : class
where TSource : class
{
foreach (var member in source.GetType().GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
switch (member)
{
case PropertyInfo property:
target.PrivateSet(member.Name, property.GetValue(source));
break;
case FieldInfo field:
target.PrivateSet(member.Name, field.GetValue(source));
break;
default:
break;
}
}
return target;
}
/// <summary>
/// 为对象的指定属性或字段赋值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">对象</param>
/// <param name="name">属性或字段名称</param>
/// <param name="value">值</param>
/// <returns>当前对象</returns>
public static T PrivateSet<T>(this T source, string name, object value) where T : class
{
if (source != null && !string.IsNullOrEmpty(name))
{
Type t = typeof(T);
var members = t.GetMember(name, MemberTypes.Property | MemberTypes.Field, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var member in members)
{
switch (member)
{
case PropertyInfo property:
property.SetValue(source, value);
break;
case FieldInfo field:
field.SetValue(source, value);
break;
default:
break;
}
}
}
return source;
}
/// <summary>
/// 为对象的指定属性或字段赋值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <param name="source">对象</param>
/// <param name="expression">选择了某个属性或字段的表达式</param>
/// <param name="value">值</param>
/// <returns>当前对象</returns>
public static T PrivateSet<T, TKey>(this T source, Expression<Func<T, TKey>> expression, TKey value) where T : class
{
if (source != null && expression != null)
{
if (expression.Body is MemberExpression m && m.Member != null)
{
switch (m.Member)
{
case PropertyInfo property:
property.SetValue(source, value);
break;
case FieldInfo field:
field.SetValue(source, value);
break;
default:
break;
}
}
}
return source;
}
/// <summary>
/// 是否为NULL
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <returns></returns>
public static bool IsNull<T>(this T entity) where T : class
{
return entity == null;
}
/// <summary>
/// 获取 <typeparamref name="TKey"/> 类型的值
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <param name="entity"></param>
/// <param name="field"></param>
/// <returns></returns>
public static TKey GetValueFromField<T, TKey>(this T entity, string field) where T : class
{
if (!entity.HasField(field))
return default;
return (TKey)entity.GetType().GetProperty(field).GetValue(entity);
}
/// <summary>
/// 获取object类型值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="field"></param>
/// <returns></returns>
public static object GetValueFromField<T>(this T entity, string field) where T : class
{
if (!entity.HasField(field))
return null;
return typeof(T).GetProperties().FirstOrDefault(p => p.Name == field)?.GetValue(entity, null);
}
/// <summary>
/// 获取string类型值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="field"></param>
/// <returns></returns>
public static string GetStringValueFromField<T>(this T entity, string field) where T : class
{
if (!entity.HasField(field))
return null;
var value = entity.GetValueFromField(field);
return value == null ? string.Empty : value.ToString();
}
/// <summary>
/// 获取JObject类型值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="field"></param>
/// <returns></returns>
public static JObject GetJsonValueFromField<T>(this T entity, string field) where T : class
{
if (!entity.HasField(field))
return null;
var value = entity.GetValueFromField(field);
return value == null ? null : Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(value.ToString());
}
/// <summary>
/// 获取int类型值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="field"></param>
/// <returns></returns>
public static int GetIntValueFromField<T>(this T entity, string field) where T : class
{
if (!entity.HasField(field))
return 0;
var value = entity.GetValueFromField(field);
return value == null ? 0 : int.Parse(value.ToString());
}
/// <summary>
/// 获取double类型值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="field"></param>
/// <returns></returns>
public static double GetDoubleValueFromField<T>(this T entity, string field) where T : class
{
if (!entity.HasField(field))
return 0;
var value = entity.GetValueFromField(field);
return value == null ? 0 : double.Parse(value.ToString());
}
/// <summary>
/// 获取DateTime类型值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="field"></param>
/// <returns></returns>
public static DateTime GetDateTimeValueFromFieldNotNull<T>(this T entity, string field) where T : class
{
if (!entity.HasField(field))
return DateTime.MaxValue;
var value = entity.GetValueFromField(field);
if (value == null || string.IsNullOrEmpty(value.ToString()))
return DateTime.MaxValue;
return DateTime.Parse(value.ToString());
}
/// <summary>
/// 获取DateTime?类型值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="field"></param>
/// <returns></returns>
public static DateTime? GetDateTimeValueFromField<T>(this T entity, string field) where T : class
{
if (!entity.HasField(field))
{
return null;
}
var value = entity.GetValueFromField(field);
if (value == null || string.IsNullOrEmpty(value.ToString()))
return null;
return DateTime.Parse(value.ToString());
}
/// <summary>
/// 判断是否为DateTime类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="field"></param>
/// <returns></returns>
public static bool FieldTypeIsDateTime<T>(this T entity, string field) where T : class
{
if (!entity.HasField(field))
{
return false;
}
var t = typeof(T).GetProperties().FirstOrDefault(p => p.Name == field).PropertyType;
return t == typeof(DateTime) || t == typeof(DateTime?);
}
/// <summary>
/// 判断是否为数值类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="field"></param>
/// <returns></returns>
public static bool FieldTypeIsNumber<T>(this T entity, string field) where T : class
{
if (!entity.HasField(field))
{
return false;
}
var t = typeof(T).GetProperties().FirstOrDefault(p => p.Name == field).PropertyType;
return t == typeof(int) || t == typeof(int?)
|| t == typeof(double) || t == typeof(double?)
|| t == typeof(decimal) || t == typeof(decimal?)
|| t == typeof(long) || t == typeof(long?)
|| t == typeof(float) || t == typeof(float?);
}
/// <summary>
/// 赋值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="field"></param>
/// <param name="value"></param>
public static void SetValueForField<T>(this T entity, string field, object value) where T : class
{
if (!entity.HasField(field))
{
return;
}
typeof(T).GetProperties().FirstOrDefault(p => p.Name == field).SetValue(entity, value);
}
/// <summary>
/// 是否包含该字段
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="field"></param>
/// <returns></returns>
public static bool HasField<T>(this T entity, string field) where T : class
{
return typeof(T).GetProperties().Any(p => p.Name == field);
}
}

@ -1,37 +0,0 @@
using Microsoft.AspNetCore.Http;
using System.Text;
namespace Tiobon.Core.Common.Extensions;
public static class HttpRequestExtension
{
public static string GetRequestBody(this HttpRequest request)
{
if (!request.Body.CanRead)
{
return default;
}
if (!request.Body.CanSeek)
{
return default;
}
if (request.Body.Length < 1)
{
return default;
}
var bodyStr = "";
// 启用倒带功能,就可以让 Request.Body 可以再次读取
request.Body.Seek(0, SeekOrigin.Begin);
using (StreamReader reader
= new StreamReader(request.Body, Encoding.UTF8, true, 1024, true))
{
bodyStr = reader.ReadToEnd();
}
request.Body.Position = 0;
return bodyStr;
}
}

@ -1,423 +0,0 @@
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Reflection;
using Tiobon.Core.Common.Helper;
namespace Tiobon.Core.Common.Extensions;
public static class IQueryableExtensions
{
static int EXPORT_FILE_PAGESIZE = 10000;
/// <summary>
/// IQueryable数据写入文件(Excel)
/// </summary>
/// <param name="db"></param>
/// <param name="fname"></param>
/// <param name="splitstr"></param>
/// <param name="ExportFields"></param>
/// <param name="exportFieldsWidth"></param>
/// <param name="headText"></param>
/// <param name="totalText"></param>
/// <param name="isNeedItemNo"></param>
public static void IntoFileFromLinqExcel<T>(this IQueryable<T> db, string fname, string splitstr, List<string> exportFields, Dictionary<string, string> exportDicFields = null, List<int> exportFieldsWidth = null, string headText = "", string totalText = "", bool isNeedItemNo = false) where T : class
{
if (db.IsNull())
return;
//查询文件状态
if (File.Exists(fname))
{
LoggerHelper.SendLog("文件已生成 " + fname);
return;
}
LoggerHelper.SendLog("正在生成文件 " + fname);
DateTime dt_start = DateTime.Now;
if (!File.Exists(fname))
File.Create(fname).Close();
//获取需要导出的字段
Dictionary<string, string> fieldDescs = GetFieldDesc<T>();
fieldDescs = exportDicFields;
int dbCount = db.Count();
ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.Commercial;
//列名排序,返回有序列表
var (fields, colunms) = Sort(fieldDescs, exportFields);
using (FileStream stream = File.Create(fname))
{
using (ExcelPackage package = new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("sheet1");
var colunmsCount = colunms.Count;
var startCol = 0;
var startRow = 1; // 初始行数
if (isNeedItemNo)
startCol = 1;
if (!string.IsNullOrEmpty(headText))
{
worksheet.Cells[startRow, 1].Value = headText;
worksheet.Cells[startRow, 1, 1, colunmsCount + startCol].Merge = true;
worksheet.Cells[startRow, 1, 1, colunmsCount + startCol].Style.Font.Bold = true;
worksheet.Cells[startRow, 1, 1, colunmsCount + startCol].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; // Alignment is center
worksheet.Cells[startRow, 1, 1, colunmsCount + startCol].Style.Font.Size = 14;
startRow++;
}
if (isNeedItemNo)
{
worksheet.Cells[startRow, 1].Value = "序号";
worksheet.Cells[startRow, 1, startRow, 1].Style.Font.Bold = true;
worksheet.Cells[startRow, 1, startRow, 1].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Cells[startRow, 1, startRow, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
}
//写入列名
for (int i = 0; i < fields.Count; ++i)
{
worksheet.Cells[startRow, i + 1 + startCol].Value = fields[i];
worksheet.Cells[startRow, i + 1 + startCol, startRow, i + 1 + startCol].Style.Font.Bold = true;
worksheet.Cells[startRow, i + 1 + startCol, startRow, i + 1 + startCol].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Cells[startRow, i + 1 + startCol, startRow, i + 1 + startCol].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
}
startRow++;
//查看数据是否过大,需要分页
int totalPageNum = (dbCount + EXPORT_FILE_PAGESIZE - 1) / EXPORT_FILE_PAGESIZE;
//遍历每一页
for (int pageNum = 0; pageNum < totalPageNum; ++pageNum)
{
var list = db.Skip(pageNum * EXPORT_FILE_PAGESIZE).Take(EXPORT_FILE_PAGESIZE).ToList();
//遍历每行
for (int row = 0; row < list.Count; ++row)
{
if (isNeedItemNo)
{
worksheet.Cells[row + startRow, 1].Value = row + 1;
worksheet.Cells[row + startRow, 1, row + startRow, 1].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Cells[row + startRow, 1, row + startRow, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
}
//遍历需要写入文件的字段
for (int i = 0; i < colunms.Count; ++i)
{
worksheet.Cells[row + startRow, i + 1 + startCol].Value = ConvertData2String(list[row], colunms[i]);
worksheet.Cells[row + startRow, i + 1 + startCol, row + startRow, i + 1 + startCol].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Cells[row + startRow, i + 1 + startCol, row + startRow, i + 1 + startCol].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
}
}
}
if (!string.IsNullOrEmpty(totalText))
{
worksheet.Cells[dbCount + startRow, 1].Value = "总计:";
worksheet.Cells[dbCount + startRow, 1, dbCount + startRow, 1].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Cells[dbCount + startRow, 1, dbCount + startRow, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
worksheet.Cells[dbCount + startRow, 2, dbCount + startRow, colunms.Count + startCol].Value = totalText;
worksheet.Cells[dbCount + startRow, 2, dbCount + startRow, colunms.Count + startCol].Merge = true;
startRow++;
}
using (ExcelRange r = worksheet.Cells[1, 1, dbCount + startRow - 1, fields.Count + startCol])
{
r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
r.Style.Border.Right.Style = ExcelBorderStyle.Thin;
r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
r.Style.Border.Top.Color.SetColor(Color.Black);
r.Style.Border.Left.Color.SetColor(Color.Black);
r.Style.Border.Right.Color.SetColor(Color.Black);
r.Style.Border.Bottom.Color.SetColor(Color.Black);
}
if (isNeedItemNo)
{
worksheet.Column(1).Width = 20;//设置列宽为默认值
}
//设置列宽
if (exportFieldsWidth == null || exportFieldsWidth.Count < fields.Count)
{
for (int i = 0; i < fields.Count; ++i)
{
worksheet.Column(i + 1 + startCol).Width = 20;//设置列宽为默认值
}
}
else
{
for (int i = 0; i < fields.Count; ++i)
{
worksheet.Column(i + 1 + startCol).Width = exportFieldsWidth[i];//设置列宽为前段配置的值
}
}
package.Workbook.Properties.Title = "数据导出";
package.Workbook.Properties.Author = "SUZHOUEU";
package.Workbook.Properties.Comments = "苏州一优信息技术有限公司提供技术支持!";
package.Workbook.Properties.Company = "苏州一优信息技术有限公司";
package.Workbook.Properties.SetCustomPropertyValue("Checked by", "SimonHsiao");
package.Workbook.Properties.SetCustomPropertyValue("AssemblyName", "SUZHOUEU");
package.Save();
}
}
LoggerHelper.SendLog("生成文件 " + fname + " 完毕 " + dbCount + " 耗时 " + (int)(DateTime.Now - dt_start).TotalSeconds);
}
public static void IntoFileFromLinqExcel(this DataTable db, string fname, string splitstr, Dictionary<string, string> fieldDescs, List<int> exportFieldsWidth, string headText = "", string totalText = "", bool isNeedItemNo = false)
{
if (db.IsNull())
return;
//查询文件状态
if (File.Exists(fname))
{
LoggerHelper.SendLog("文件已生成 " + fname);
return;
}
LoggerHelper.SendLog("正在生成文件 " + fname);
DateTime dt_start = DateTime.Now;
if (!File.Exists(fname))
File.Create(fname).Close();
//获取需要导出的字段
int dbCount = db.Rows.Count;
//列名排序,返回有序列表
var (fields, colunms) = Sort(fieldDescs, null);
using (FileStream stream = File.Create(fname))
{
using (ExcelPackage package = new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("sheet1");
var colunmsCount = colunms.Count;
var startCol = 0;
var startRow = 1; // 初始行数
if (isNeedItemNo)
startCol = 1;
if (!string.IsNullOrEmpty(headText))
{
worksheet.Cells[startRow, 1].Value = headText;
worksheet.Cells[startRow, 1, 1, colunmsCount + startCol].Merge = true;
worksheet.Cells[startRow, 1, 1, colunmsCount + startCol].Style.Font.Bold = true;
worksheet.Cells[startRow, 1, 1, colunmsCount + startCol].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; // Alignment is center
worksheet.Cells[startRow, 1, 1, colunmsCount + startCol].Style.Font.Size = 14;
startRow++;
}
if (isNeedItemNo)
{
worksheet.Cells[startRow, 1].Value = "序号";
worksheet.Cells[startRow, 1, startRow, 1].Style.Font.Bold = true;
worksheet.Cells[startRow, 1, startRow, 1].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Cells[startRow, 1, startRow, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
}
//写入列名
for (int i = 0; i < fields.Count; ++i)
{
worksheet.Cells[startRow, i + 1 + startCol].Value = fields[i];
worksheet.Cells[startRow, i + 1 + startCol, startRow, i + 1 + startCol].Style.Font.Bold = true;
worksheet.Cells[startRow, i + 1 + startCol, startRow, i + 1 + startCol].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Cells[startRow, i + 1 + startCol, startRow, i + 1 + startCol].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
}
startRow++;
for (int row = 0; row < dbCount; ++row)
{
if (isNeedItemNo)
{
worksheet.Cells[row + startRow, 1].Value = row + 1;
worksheet.Cells[row + startRow, 1, row + startRow, 1].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Cells[row + startRow, 1, row + startRow, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
}
//遍历需要写入文件的字段
for (int i = 0; i < colunms.Count; ++i)
{
worksheet.Cells[row + startRow, i + 1 + startCol].Value = db.Rows[row][colunms[i]].ToString();
worksheet.Cells[row + startRow, i + 1 + startCol, row + startRow, i + 1 + startCol].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Cells[row + startRow, i + 1 + startCol, row + startRow, i + 1 + startCol].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
}
}
if (!string.IsNullOrEmpty(totalText))
{
worksheet.Cells[dbCount + startRow, 1].Value = "总计:";
worksheet.Cells[dbCount + startRow, 1, dbCount + startRow, 1].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Cells[dbCount + startRow, 1, dbCount + startRow, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
worksheet.Cells[dbCount + startRow, 2, dbCount + startRow, colunms.Count + startCol].Value = totalText;
worksheet.Cells[dbCount + startRow, 2, dbCount + startRow, colunms.Count + startCol].Merge = true;
startRow++;
}
using (ExcelRange r = worksheet.Cells[1, 1, dbCount + startRow - 1, fields.Count + startCol])
{
r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
r.Style.Border.Right.Style = ExcelBorderStyle.Thin;
r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
r.Style.Border.Top.Color.SetColor(Color.Black);
r.Style.Border.Left.Color.SetColor(Color.Black);
r.Style.Border.Right.Color.SetColor(Color.Black);
r.Style.Border.Bottom.Color.SetColor(Color.Black);
}
if (isNeedItemNo)
{
worksheet.Column(1).Width = 20;//设置列宽为默认值
}
//设置列宽
if (exportFieldsWidth == null || exportFieldsWidth.Count < fields.Count)
{
for (int i = 0; i < fields.Count; ++i)
{
worksheet.Column(i + 1 + startCol).Width = 20;//设置列宽为默认值
}
}
else
{
for (int i = 0; i < fields.Count; ++i)
{
worksheet.Column(i + 1 + startCol).Width = exportFieldsWidth[i];//设置列宽为前段配置的值
}
}
package.Workbook.Properties.Title = "数据导出";
package.Workbook.Properties.Author = "SUZHOUEU";
package.Workbook.Properties.Comments = "苏州一优信息技术有限公司提供技术支持!";
package.Workbook.Properties.Company = "苏州一优信息技术有限公司";
package.Workbook.Properties.SetCustomPropertyValue("Checked by", "SimonHsiao");
package.Workbook.Properties.SetCustomPropertyValue("AssemblyName", "SUZHOUEU");
package.Save();
}
}
LoggerHelper.SendLog("生成文件 " + fname + " 完毕 " + dbCount + " 耗时 " + (int)(DateTime.Now - dt_start).TotalSeconds);
}
private static string ConvertData2String<T>(T t, string field) where T : class
{
if (t.FieldTypeIsDateTime(field))
{
DateTime? time = t.GetDateTimeValueFromField(field);
if (time != null)
{
if (time.Value.ToString("HH:mm:ss") == "00:00:00")
{
return time.Value.ToString("yyyy-MM-dd");
}
else
{
return time.Value.ToString("yyyy-MM-dd HH:mm:ss");
}
}
else
{
return string.Empty;
}
}
else
{
return t.GetStringValueFromField(field);
}
}
/// <summary>
/// 列名按照前端显示顺序导出
/// </summary>
/// <param name="columns"></param>
/// <param name="ExportFields"></param>
/// <returns></returns>
public static (List<string>, List<string>) Sort(Dictionary<string, string> columns, List<string> ExportFields)
{
List<string> fields = new List<string>();
List<string> colunms = new List<string>();
if (ExportFields == null || ExportFields.Count == 0)
{
return (columns.Keys.ToList(), columns.Values.ToList());
}
foreach (var field in ExportFields)
{
foreach (var item in columns)
{
if (item.Key == field)
{
fields.Add(item.Key);
colunms.Add(item.Value);
}
}
}
return (fields, colunms);
}
#region 获取字段描述
/// <summary>
/// 对象字段描述
/// </summary>
private static Dictionary<string, Dictionary<string, string>> m_FieldDesc = new Dictionary<string, Dictionary<string, string>>();
/// <summary>
/// 获取字段的描述(描述 - 列名)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Dictionary<string, string> GetFieldDesc<T>()
{
var type = typeof(T).ToString();
lock (m_FieldDesc)
{
if (m_FieldDesc.ContainsKey(type))
return m_FieldDesc[type];
}
Dictionary<string, string> dic = new Dictionary<string, string>();
try
{
PropertyInfo[] peroperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
if (peroperties != null)
{
foreach (PropertyInfo property in peroperties)
{
object[] objs = property.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (objs.Length > 0)
{
var desc = ((DescriptionAttribute)objs[0]).Description.Trim();
if (!dic.ContainsKey(desc))
{
dic.Add(desc, property.Name);
}
else
{
dic[desc] = property.Name;
}
}
}
}
}
catch //(Exception ex)
{
}
lock (m_FieldDesc)
{
if (!m_FieldDesc.ContainsKey(type))
m_FieldDesc.Add(type, dic);
}
return dic;
}
#endregion
}

@ -1,16 +0,0 @@
using System.Reflection;
namespace Tiobon.Core.Common.Extensions;
public static class MethodInfoExtensions
{
public static string GetFullName(this MethodInfo method)
{
if (method.DeclaringType == null)
{
return $@"{method.Name}";
}
return $"{method.DeclaringType.FullName}.{method.Name}";
}
}

@ -1,92 +0,0 @@
using Tiobon.Core.Common;
using JetBrains.Annotations;
namespace System;
public static class TypeExtensions
{
public static string GetFullNameWithAssemblyName(this Type type)
{
return type.FullName + ", " + type.Assembly.GetName().Name;
}
/// <summary>
/// Determines whether an instance of this type can be assigned to
/// an instance of the <typeparamref name="TTarget"></typeparamref>.
///
/// Internally uses <see cref="Type.IsAssignableFrom"/>.
/// </summary>
/// <typeparam name="TTarget">Target type</typeparam> (as reverse).
public static bool IsAssignableTo<TTarget>([NotNull] this Type type)
{
Check.NotNull(type, nameof(type));
return type.IsAssignableTo(typeof(TTarget));
}
/// <summary>
/// Determines whether an instance of this type can be assigned to
/// an instance of the <paramref name="targetType"></paramref>.
///
/// Internally uses <see cref="Type.IsAssignableFrom"/> (as reverse).
/// </summary>
/// <param name="type">this type</param>
/// <param name="targetType">Target type</param>
public static bool IsAssignableTo([NotNull] this Type type, [NotNull] Type targetType)
{
Check.NotNull(type, nameof(type));
Check.NotNull(targetType, nameof(targetType));
return targetType.IsAssignableFrom(type);
}
/// <summary>
/// Gets all base classes of this type.
/// </summary>
/// <param name="type">The type to get its base classes.</param>
/// <param name="includeObject">True, to include the standard <see cref="object"/> type in the returned array.</param>
public static Type[] GetBaseClasses([NotNull] this Type type, bool includeObject = true)
{
Check.NotNull(type, nameof(type));
var types = new List<Type>();
AddTypeAndBaseTypesRecursively(types, type.BaseType, includeObject);
return types.ToArray();
}
/// <summary>
/// Gets all base classes of this type.
/// </summary>
/// <param name="type">The type to get its base classes.</param>
/// <param name="stoppingType">A type to stop going to the deeper base classes. This type will be be included in the returned array</param>
/// <param name="includeObject">True, to include the standard <see cref="object"/> type in the returned array.</param>
public static Type[] GetBaseClasses([NotNull] this Type type, Type stoppingType, bool includeObject = true)
{
Check.NotNull(type, nameof(type));
var types = new List<Type>();
AddTypeAndBaseTypesRecursively(types, type.BaseType, includeObject, stoppingType);
return types.ToArray();
}
private static void AddTypeAndBaseTypesRecursively(
[NotNull] List<Type> types,
[CanBeNull] Type type,
bool includeObject,
[CanBeNull] Type stoppingType = null)
{
if (type == null || type == stoppingType)
{
return;
}
if (!includeObject && type == typeof(object))
{
return;
}
AddTypeAndBaseTypesRecursively(types, type.BaseType, includeObject, stoppingType);
types.Add(type);
}
}

@ -1,99 +0,0 @@
using System.Text;
namespace DPE.Core.Common.Helper;
public sealed class Base32Helper
{
// the valid chars for the encoding
private static string ValidChars = "QAZ2WSX3" + "EDC4RFV5" + "TGB6YHN7" + "UJM8K9LP";
/// <summary>
/// Converts an array of bytes to a Base32-k string.
/// </summary>
public static string ToString(byte[] bytes)
{
StringBuilder sb = new StringBuilder(); // holds the base32 chars
byte index;
int hi = 5;
int currentByte = 0;
while (currentByte < bytes.Length)
{
// do we need to use the next byte?
if (hi > 8)
{
// get the last piece from the current byte, shift it to the right
// and increment the byte counter
index = (byte)(bytes[currentByte++] >> (hi - 5));
if (currentByte != bytes.Length)
{
// if we are not at the end, get the first piece from
// the next byte, clear it and shift it to the left
index = (byte)(((byte)(bytes[currentByte] << (16 - hi)) >> 3) | index);
}
hi -= 3;
}
else if (hi == 8)
{
index = (byte)(bytes[currentByte++] >> 3);
hi -= 3;
}
else
{
// simply get the stuff from the current byte
index = (byte)((byte)(bytes[currentByte] << (8 - hi)) >> 3);
hi += 5;
}
sb.Append(ValidChars[index]);
}
return sb.ToString();
}
/// <summary>
/// Converts a Base32-k string into an array of bytes.
/// </summary>
/// <exception cref="System.ArgumentException">
/// Input string <paramref name="s">s</paramref> contains invalid Base32-k characters.
/// </exception>
public static byte[] FromBase32String(string str)
{
int numBytes = str.Length * 5 / 8;
byte[] bytes = new Byte[numBytes];
// all UPPERCASE chars
str = str.ToUpper();
int bit_buffer;
int currentCharIndex;
int bits_in_buffer;
if (str.Length < 3)
{
bytes[0] = (byte)(ValidChars.IndexOf(str[0]) | ValidChars.IndexOf(str[1]) << 5);
return bytes;
}
bit_buffer = (ValidChars.IndexOf(str[0]) | ValidChars.IndexOf(str[1]) << 5);
bits_in_buffer = 10;
currentCharIndex = 2;
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] = (byte)bit_buffer;
bit_buffer >>= 8;
bits_in_buffer -= 8;
while (bits_in_buffer < 8 && currentCharIndex < str.Length)
{
bit_buffer |= ValidChars.IndexOf(str[currentCharIndex++]) << bits_in_buffer;
bits_in_buffer += 5;
}
}
return bytes;
}
}

@ -1,232 +0,0 @@
namespace Tiobon.Core.Common.Helper;
/// <summary>
/// Base64编码类。
/// 将byte[]类型转换成Base64编码的string类型。
/// </summary>
public class Base64Encoder
{
byte[] source;
int length, length2;
int blockCount;
int paddingCount;
public static Base64Encoder Encoder = new Base64Encoder();
public Base64Encoder()
{
}
private void init(byte[] input)
{
source = input;
length = input.Length;
if ((length % 3) == 0)
{
paddingCount = 0;
blockCount = length / 3;
}
else
{
paddingCount = 3 - (length % 3);
blockCount = (length + paddingCount) / 3;
}
length2 = length + paddingCount;
}
public string GetEncoded(byte[] input)
{
//初始化
init(input);
byte[] source2;
source2 = new byte[length2];
for (int x = 0; x < length2; x++)
{
if (x < length)
{
source2[x] = source[x];
}
else
{
source2[x] = 0;
}
}
byte b1, b2, b3;
byte temp, temp1, temp2, temp3, temp4;
byte[] buffer = new byte[blockCount * 4];
char[] result = new char[blockCount * 4];
for (int x = 0; x < blockCount; x++)
{
b1 = source2[x * 3];
b2 = source2[x * 3 + 1];
b3 = source2[x * 3 + 2];
temp1 = (byte)((b1 & 252) >> 2);
temp = (byte)((b1 & 3) << 4);
temp2 = (byte)((b2 & 240) >> 4);
temp2 += temp;
temp = (byte)((b2 & 15) << 2);
temp3 = (byte)((b3 & 192) >> 6);
temp3 += temp;
temp4 = (byte)(b3 & 63);
buffer[x * 4] = temp1;
buffer[x * 4 + 1] = temp2;
buffer[x * 4 + 2] = temp3;
buffer[x * 4 + 3] = temp4;
}
for (int x = 0; x < blockCount * 4; x++)
{
result[x] = sixbit2char(buffer[x]);
}
switch (paddingCount)
{
case 0: break;
case 1: result[blockCount * 4 - 1] = '='; break;
case 2:
result[blockCount * 4 - 1] = '=';
result[blockCount * 4 - 2] = '=';
break;
default: break;
}
return new string(result);
}
private char sixbit2char(byte b)
{
char[] lookupTable = new char[64]{
'A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','O','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','o','p','q','r','s','t','u','v','w','x','y','z',
'0','1','2','3','4','5','6','7','8','9','+','/'};
if ((b >= 0) && (b <= 63))
{
return lookupTable[(int)b];
}
else
{
return ' ';
}
}
}
/// <summary>
/// Base64解码类
/// 将Base64编码的string类型转换成byte[]类型
/// </summary>
public class Base64Decoder
{
char[] source;
int length, length2, length3;
int blockCount;
int paddingCount;
public static Base64Decoder Decoder = new Base64Decoder();
public Base64Decoder()
{
}
private void init(char[] input)
{
int temp = 0;
source = input;
length = input.Length;
for (int x = 0; x < 2; x++)
{
if (input[length - x - 1] == '=')
temp++;
}
paddingCount = temp;
blockCount = length / 4;
length2 = blockCount * 3;
}
public byte[] GetDecoded(string strInput)
{
//初始化
init(strInput.ToCharArray());
byte[] buffer = new byte[length];
byte[] buffer2 = new byte[length2];
for (int x = 0; x < length; x++)
{
buffer[x] = char2sixbit(source[x]);
}
byte b, b1, b2, b3;
byte temp1, temp2, temp3, temp4;
for (int x = 0; x < blockCount; x++)
{
temp1 = buffer[x * 4];
temp2 = buffer[x * 4 + 1];
temp3 = buffer[x * 4 + 2];
temp4 = buffer[x * 4 + 3];
b = (byte)(temp1 << 2);
b1 = (byte)((temp2 & 48) >> 4);
b1 += b;
b = (byte)((temp2 & 15) << 4);
b2 = (byte)((temp3 & 60) >> 2);
b2 += b;
b = (byte)((temp3 & 3) << 6);
b3 = temp4;
b3 += b;
buffer2[x * 3] = b1;
buffer2[x * 3 + 1] = b2;
buffer2[x * 3 + 2] = b3;
}
length3 = length2 - paddingCount;
byte[] result = new byte[length3];
for (int x = 0; x < length3; x++)
{
result[x] = buffer2[x];
}
return result;
}
private byte char2sixbit(char c)
{
char[] lookupTable = new char[64]{
'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
'O','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',
'o','p','q','r','s','t','u','v','w','x','y','z',
'0','1','2','3','4','5','6','7','8','9','+','/'};
if (c == '=')
return 0;
else
{
for (int x = 0; x < 64; x++)
{
if (lookupTable[x] == c)
return (byte)x;
}
return 0;
}
}
}

@ -1,515 +0,0 @@
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Mapster;
using Tiobon.Core.Common.Extensions;
namespace Tiobon.Core.Common.Helper;
#region 动态linq帮助类,连接符号,运算符号
/// <summary>
/// 动态linq工厂
/// </summary>
public static class DynamicLinqFactory
{
private static readonly Dictionary<string, OperationSymbol> _operatingSystems = new Dictionary<string, OperationSymbol>();
public static Dictionary<string, OperationSymbol> OperatingSystems => GetOperationSymbol();
private static readonly Dictionary<string, LinkSymbol> _linkSymbols = new Dictionary<string, LinkSymbol>();
public static Dictionary<string, LinkSymbol> LinkSymbols => GetLinkSymbol();
/// <summary>
/// 生成lambd表达式(如:CompanyID != 1 & CompanyID == 1)
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="propertyStr"></param>
/// <returns></returns>
public static Expression<Func<TSource, bool>> CreateLambda<TSource>(string propertyStr)
{
// 设置自定义lanbd
// 定义 lanbd 种子(p=> xxxxxx)中的 p
if (string.IsNullOrWhiteSpace(propertyStr))
return LinqHelper.True<TSource>(); //为空就返回空的表达式
var parameter = Expression.Parameter(typeof(TSource), "p");
var strArr = SplitOperationSymbol(propertyStr);
// 第一个判断条件,固定一个判断条件作为最左边
Expression mainExpressin = ExpressionStudio(null, strArr[0], parameter);
// 将需要放置在最左边的判断条件从列表中去除,因为已经合成到表达式最左边了
strArr.RemoveAt(0);
foreach (var x in strArr)
{
mainExpressin = ExpressionStudio(mainExpressin, x, parameter);
}
return mainExpressin.ToLambda<Func<TSource, bool>>(parameter);
}
/// <summary>
/// 组合条件判断表达式
/// </summary>
/// <param name="left">左边的表达式</param>
/// <param name="dynamicLinq"></param>
/// <param name="key"></param>
/// <returns></returns>
public static Expression ExpressionStudio(Expression left, DynamicLinqHelper dynamicLinq, ParameterExpression key)
{
Expression mainExpression = key;
if (!dynamicLinq.Left.IsNullOrEmpty())
{
var properties = dynamicLinq.Left.Split('.');
int index = 0;
foreach (var t in properties)
{
if (mainExpression.Type.HasImplementedRawGeneric(typeof(IEnumerable<>)))
{
return ExpressionStudioEnumerable(left, mainExpression, dynamicLinq.Adapt<DynamicLinqHelper>(),
properties.Skip(index).ToArray());
}
mainExpression = mainExpression.Property(t);
index++;
}
}
Expression right = null;
if (dynamicLinq.IsMerge && dynamicLinq.Child.Any())
{
right = ExpressionStudio(null, dynamicLinq.Child[0], key);
for (var i = 1; i < dynamicLinq.Child.Count; i++)
{
right = ChangeLinkSymbol(dynamicLinq.Child[i].LinkSymbol, right, ExpressionStudio(null, dynamicLinq.Child[i], key));
}
}
else
{
right = ChangeOperationSymbol(dynamicLinq.OperationSymbol, mainExpression, dynamicLinq.Right);
}
left = left == null
// 如果左边表达式为空,则当前的表达式就为最左边
? right
// 如果不为空,则将当前的表达式连接到左边
: ChangeLinkSymbol(dynamicLinq.LinkSymbol, left, right);
return left;
}
public static Expression ExpressionStudioEnumerable(Expression left, Expression property, DynamicLinqHelper dynamicLinq, string[] properties)
{
var realType = property.Type.GenericTypeArguments[0];
var parameter = Expression.Parameter(realType, "z");
Expression mainExpression = property;
if (!properties.Any())
{
throw new ApplicationException("条件表达式错误,属性为集合时,需要明确具体属性");
}
dynamicLinq.Left = string.Join(".", properties);
mainExpression = ExpressionStudio(null, dynamicLinq, parameter);
var lambda = Expression.Lambda(mainExpression, parameter);
mainExpression = Expression.Call(typeof(Enumerable), "Any", new[] { realType }, property, lambda);
left = left == null
? mainExpression
: ChangeLinkSymbol(dynamicLinq.LinkSymbol, left, mainExpression);
return left;
}
public static List<DynamicLinqHelper> SplitOperationSymbol(string str)
{
var outList = new List<DynamicLinqHelper>();
var tokens = Regex.Matches(FormatString(str), _pattern, RegexOptions.Compiled)
.Select(m => m.Groups[1].Value.Trim())
.ToList();
SplitOperationSymbol(tokens, outList);
return outList;
}
private static void SplitOperationSymbol(List<string> tokens, List<DynamicLinqHelper> outList, int start = 0, int end = 0)
{
var dys = new Stack<DynamicLinqHelper>();
var dynamicLinqHelper = new DynamicLinqHelper();
if (end == 0)
{
end = tokens.Count - 1;
}
for (int i = start; i <= end; i++)
{
var token = tokens[i];
if (LinkSymbols.TryGetValue(token, out var symbol))
{
if (dys.Count > 0)
{
var linqHelper = dys.Peek();
linqHelper.Child.Add(dynamicLinqHelper);
}
else
{
outList.Add(dynamicLinqHelper);
}
dynamicLinqHelper = new DynamicLinqHelper()
{
LinkSymbol = symbol,
};
continue;
}
if (OperatingSystems.TryGetValue(token.ToLower(), out var system))
{
dynamicLinqHelper!.OperationSymbol = system;
continue;
}
if (dynamicLinqHelper!.OperationSymbol != OperationSymbol.In)
{
if (string.Equals(token.Trim(), "("))
{
dynamicLinqHelper!.IsMerge = true;
dynamicLinqHelper.Child = new List<DynamicLinqHelper>();
dys.Push(dynamicLinqHelper);
dynamicLinqHelper = new DynamicLinqHelper();
continue;
}
if (string.Equals(token.Trim(), ")"))
{
if (dys.Count > 1)
{
var dya = dys.Pop();
dya.Child.Add(dynamicLinqHelper);
dynamicLinqHelper = dya;
continue;
}
else
{
var dya = dys.Pop();
dya.Child.Add(dynamicLinqHelper);
outList.Add(dya);
dynamicLinqHelper = null;
continue;
}
}
}
if (dynamicLinqHelper!.OperationSymbol is null)
{
dynamicLinqHelper.Left += token;
}
else
{
dynamicLinqHelper.Right += FormatValue(token);
}
if (i == end)
{
outList.Add(dynamicLinqHelper);
dynamicLinqHelper = null;
}
}
}
public static string FormatValue(string str)
{
return str.TrimStart('"').TrimEnd('"');
// return str.TrimStart('"').TrimEnd('"').Replace(@"\""", @"""");
}
/// <summary>
/// 将运算枚举符号转成具体使用方法
/// </summary>
public static Expression ChangeLinkSymbol(LinkSymbol symbol, Expression left, Expression right)
{
switch (symbol)
{
case LinkSymbol.OrElse:
return left.OrElse(right);
case LinkSymbol.AndAlso:
return left.AndAlso(right);
default:
return left;
}
}
public static Dictionary<string, OperationSymbol> GetOperationSymbol()
{
if (_operatingSystems.Any()) return _operatingSystems;
var fielding = typeof(OperationSymbol).GetFields();
foreach (var item in fielding)
{
if (item.GetCustomAttribute(typeof(DisplayAttribute)) is DisplayAttribute attr && !attr.Name.IsNullOrEmpty())
{
foreach (var name in attr.Name.Split(';'))
{
_operatingSystems.Add(name.ToLower(), (OperationSymbol)item.GetValue(null));
}
}
}
return _operatingSystems;
}
public static Dictionary<string, LinkSymbol> GetLinkSymbol()
{
if (_linkSymbols.Any()) return _linkSymbols;
var fielding = typeof(LinkSymbol).GetFields();
foreach (var item in fielding)
{
if (item.GetCustomAttribute(typeof(DisplayAttribute)) is DisplayAttribute attr && !attr.Name.IsNullOrEmpty())
{
foreach (var name in attr.Name.Split(';'))
{
_linkSymbols.Add(name, (LinkSymbol)item.GetValue(null));
}
}
}
return _linkSymbols;
}
public static string FormatString(string str)
{
var sb = new StringBuilder();
var firstIndex = -1;
var lastIndex = -1;
for (var i = 0; i < str.Length; i++)
{
var character = str[i];
if (firstIndex == -1)
{
if (character.IsNullOrEmpty() && i < str.Length - 2)
if ('"'.Equals(str[i + 1]))
firstIndex = i + 1;
}
else
{
if ('\"'.Equals(character))
{
var andIndex = str.IndexOf("\" &", firstIndex);
var orIndex = str.IndexOf("\" |", firstIndex);
var andOrIndex = Math.Min(andIndex, orIndex);
andOrIndex = andOrIndex == -1 ? Math.Max(andOrIndex, orIndex) : andOrIndex;
if (andOrIndex != -1)
{
lastIndex = andOrIndex;
}
else
{
if (i == firstIndex) continue;
if (i == str.Length - 1 || str[i + 1].IsNullOrEmpty()) lastIndex = i;
}
}
if (lastIndex != -1)
{
var temp = str.Substring(firstIndex + 1, lastIndex - firstIndex - 1).Replace(@"""", @"\""");
sb.Append($" \"{temp}\" ");
i = lastIndex;
firstIndex = -1;
lastIndex = -1;
continue;
}
}
if (firstIndex != -1) continue;
sb.Append(character);
}
return sb.ToString();
}
/// <summary>tokenizer pattern: Optional-SpaceS...Token...Optional-Spaces</summary>
public static readonly string _pattern = @"\s*(" + string.Join("|", new string[]
{
// operators and punctuation that are longer than one char: longest first
string.Join("|", new[]
{
"||", "&&", "==", "!=", "<=", ">=",
"in",
"like", "contains", "%=",
"startslike", "StartsLike", "startscontains", "StartsContains", "%>",
"endlike", "EndLike", "endcontains", "EndContains", "%<",
}.Select(Regex.Escape)),
@"""(?:\\.|[^""])*""", // string
@"\d+(?:\.\d+)?", // number with optional decimal part
@"\w+", // word
@"\S", // other 1-char tokens (or eat up one character in case of an error)
}) + @")\s*";
/// <summary>
/// 将运算枚举符号转成具体使用方法
/// </summary>
public static Expression ChangeOperationSymbol(OperationSymbol? symbol, Expression key, object right)
{
// 将右边数据类型强行转换成左边一样的类型
// 两者如果Type不匹配则无法接下去的运算操作,抛出异常
object newTypeRight;
if (right == null || string.IsNullOrEmpty(right.ToString()) || right.ToString() == "null")
{
newTypeRight = null;
}
else
{
if (symbol == OperationSymbol.In)
{
newTypeRight = right.ChangeTypeList(key.Type);
}
else
{
newTypeRight = right.ChangeType(key.Type);
}
}
// 根据当前枚举类别判断使用那种比较方法
switch (symbol)
{
case OperationSymbol.Equal:
return key.Equal(Expression.Constant(newTypeRight));
case OperationSymbol.GreaterThan:
{
if (key.Type == typeof(string))
return key.Contains(Expression.Constant(newTypeRight)); //对string 特殊处理 由于string
return key.GreaterThan(Expression.Constant((newTypeRight)));
}
case OperationSymbol.GreaterThanOrEqual:
{
if (key.Type == typeof(string))
return key.Contains(Expression.Constant(newTypeRight, typeof(string)));
return key.GreaterThanOrEqual(Expression.Constant(newTypeRight));
}
case OperationSymbol.LessThan:
{
if (key.Type == typeof(string))
return key.Contains(Expression.Constant(newTypeRight, typeof(string)));
return key.LessThan(Expression.Constant((newTypeRight)));
}
case OperationSymbol.LessThanOrEqual:
{
if (key.Type == typeof(string))
return key.Contains(Expression.Constant(newTypeRight, typeof(string)));
return key.LessThanOrEqual(Expression.Constant((newTypeRight)));
}
case OperationSymbol.NotEqual:
return key.NotEqual(Expression.Constant(newTypeRight));
case OperationSymbol.Contains:
return key.Contains(Expression.Constant(newTypeRight));
case OperationSymbol.StartsContains:
return key.StartContains(Expression.Constant(newTypeRight));
case OperationSymbol.EndContains:
return key.EndContains(Expression.Constant(newTypeRight));
case OperationSymbol.In:
return Expression.Constant(newTypeRight).Contains(key);
default:
throw new ArgumentException("OperationSymbol IS NULL");
}
}
}
/// <summary>
/// 动态linq帮助类
/// </summary>
public class DynamicLinqHelper
{
[Display(Name = "左")]
public string Left { get; set; }
[Display(Name = "右")]
public string Right { get; set; }
[Display(Name = "运算符")]
public OperationSymbol? OperationSymbol { get; set; }
[Display(Name = "连接符")]
public LinkSymbol LinkSymbol { get; set; }
/// <summary>
/// 是否是合并 用于括号
/// </summary>
public bool IsMerge { get; set; } = false;
/// <summary>
/// 再有括号时候使用
/// </summary>
public List<DynamicLinqHelper> Child { get; set; }
}
/// <summary>
/// 连接符枚举(将来可能会包含 括号 )
/// </summary>
public enum LinkSymbol
{
[Display(Name = "&&;&")]
AndAlso,
[Display(Name = "||;|")]
OrElse,
Empty
}
/// <summary>
/// 常用比较运算符 > , >= , == , < , <= , != ,Contains
/// </summary>
public enum OperationSymbol
{
[Display(Name = "in")]
In,
[Display(Name = "like;contains;%=")]
Contains,
[Display(Name = "StartsLike;StartsContains;%>")]
StartsContains,
[Display(Name = "EndLike;EndContains;%<")]
EndContains,
[Display(Name = ">")]
GreaterThan,
[Display(Name = ">=")]
GreaterThanOrEqual,
[Display(Name = "<")]
LessThan,
[Display(Name = "<=")]
LessThanOrEqual,
[Display(Name = "==;=")]
Equal,
[Display(Name = "!=")]
NotEqual
}
#endregion

@ -1,23 +0,0 @@
namespace Tiobon.Core.Common.Helper;
public static class HtmlHelper
{
#region 去除富文本中的HTML标签
/// <summary>
/// 去除富文本中的HTML标签
/// </summary>
/// <param name="html"></param>
/// <param name="length"></param>
/// <returns></returns>
public static string ReplaceHtmlTag(string html, int length = 0)
{
string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");
strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");
if (length > 0 && strText.Length > length)
return strText.Substring(0, length);
return strText;
}
#endregion
}

@ -1,54 +0,0 @@
using System.Net.Http.Headers;
namespace Tiobon.Core.Common.Helper;
/// <summary>
/// httpclinet请求方式,请尽量使用IHttpClientFactory方式
/// </summary>
public class HttpHelper
{
public static readonly HttpClient Httpclient = new HttpClient();
public static async Task<string> GetAsync(string serviceAddress)
{
try
{
string result = string.Empty;
Uri getUrl = new Uri(serviceAddress);
//Httpclient.Timeout = new TimeSpan(0, 0, 60);
result = await Httpclient.GetAsync(serviceAddress).Result.Content.ReadAsStringAsync();
return result;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return null;
}
public static async Task<string> PostAsync(string serviceAddress, string requestJson = null)
{
try
{
string result = string.Empty;
Uri postUrl = new Uri(serviceAddress);
using (HttpContent httpContent = new StringContent(requestJson))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
Httpclient.Timeout = new TimeSpan(0, 0, 60);
result = await Httpclient.PostAsync(serviceAddress, httpContent).Result.Content.ReadAsStringAsync();
}
return result;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return null;
}
}

@ -1,49 +0,0 @@
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Tiobon.Core.Common.Helper;
public class IpHelper
{
/// <summary>
/// 获取当前IP地址
/// </summary>
/// <param name="preferredNetworks"></param>
/// <returns></returns>
public static string GetCurrentIp(string preferredNetworks)
{
var instanceIp = "127.0.0.1";
try
{
// 获取可用网卡
var nics = NetworkInterface.GetAllNetworkInterfaces()?.Where(network => network.OperationalStatus == OperationalStatus.Up);
// 获取所有可用网卡IP信息
var ipCollection = nics?.Select(x => x.GetIPProperties())?.SelectMany(x => x.UnicastAddresses);
foreach (var ipadd in ipCollection)
{
if (!IPAddress.IsLoopback(ipadd.Address) && ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
{
if (string.IsNullOrEmpty(preferredNetworks))
{
instanceIp = ipadd.Address.ToString();
break;
}
if (!ipadd.Address.ToString().StartsWith(preferredNetworks)) continue;
instanceIp = ipadd.Address.ToString();
break;
}
}
}
catch
{
// ignored
}
return instanceIp;
}
}

@ -1,238 +0,0 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Tiobon.Core.Common.Helper;
/// <summary>
/// Json 配置文件通用类
/// </summary>
public static class JsonConfigUtils
{
#region 变量
/// <summary>
/// 锁
/// </summary>
private static object __Lock__ = new object();
#endregion
/// <summary>
/// 读取配置文件的信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName">要读取json的名称</param>
/// <param name="key">要读取的json节点名称</param>
/// <returns></returns>
public static T GetAppSettings<T>(IConfiguration config, string AppSettingsFileName, string key) where T : class, new()
{
lock (__Lock__)
{
if (config == null)
{
config = new ConfigurationBuilder()
.Add(new JsonConfigurationSource
{
Path = AppSettingsFileName,
Optional = false,
ReloadOnChange = true
})
.Build();
}
var appconfig = new ServiceCollection()
.AddOptions()
.Configure<T>(config.GetSection(key))
.BuildServiceProvider()
.GetService<IOptions<T>>()
.Value;
return appconfig;
}
}
public static string GetJson(string jsonPath, string key)
{
IConfiguration config = new ConfigurationBuilder().AddJsonFile(jsonPath).Build(); //json文件地址
string s = config.GetSection(key).Value; //json某个对象
return s;
}
}
#region Nacos 配置清单
public class JsonConfigSettings
{
// 从nacos 读取到的系统配置信息
public static IConfiguration Configuration { get; set; }
/// <summary>
/// 配置文件名称常量
/// </summary>
private static string AppSettingsFileName = $"appsettings{ GetAppSettingsConfigName() }json";
/// <summary>
/// 根据环境变量定向配置文件名称
/// </summary>
/// <returns></returns>
private static string GetAppSettingsConfigName()
{
if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != null
&& Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != "")
{
return $".{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.";
}
else
{
return ".";
}
}
/// <summary>
/// 获取Nacos配置
/// </summary>
public static List<string> NacosServerAddresses
{
get
{
return JsonConfigUtils.GetAppSettings<NacosConfigDTO>(Configuration, AppSettingsFileName, "nacos").ServerAddresses;
}
}
/// <summary>
/// 获取Nacos配置
/// </summary>
public static int NacosDefaultTimeOut
{
get
{
return JsonConfigUtils.GetAppSettings<NacosConfigDTO>(Configuration, AppSettingsFileName, "nacos").DefaultTimeOut;
}
}
/// <summary>
/// 获取Nacos配置
/// </summary>
public static string NacosNamespace
{
get
{
return JsonConfigUtils.GetAppSettings<NacosConfigDTO>(Configuration, AppSettingsFileName, "nacos").Namespace;
}
}
/// <summary>
/// 获取Nacos配置
/// </summary>
public static string NacosServiceName
{
get
{
return JsonConfigUtils.GetAppSettings<NacosConfigDTO>(Configuration, AppSettingsFileName, "nacos").ServiceName;
}
}
/// <summary>
/// 获取Nacos配置
/// </summary>
public static int ListenInterval
{
get
{
return JsonConfigUtils.GetAppSettings<NacosConfigDTO>(Configuration, AppSettingsFileName, "nacos").ListenInterval;
}
}
/// <summary>
/// 获取Nacos配置
/// </summary>
public static string NacosIp
{
get
{
return JsonConfigUtils.GetAppSettings<NacosConfigDTO>(Configuration, AppSettingsFileName, "nacos").Ip;
}
}
/// <summary>
/// 获取Nacos配置
/// </summary>
public static int NacosPort
{
get
{
return int.Parse(JsonConfigUtils.GetAppSettings<NacosConfigDTO>(Configuration, AppSettingsFileName, "nacos").Port);
}
}
/// <summary>
/// 获取Nacos配置
/// </summary>
public static bool NacosRegisterEnabled
{
get
{
return JsonConfigUtils.GetAppSettings<NacosConfigDTO>(Configuration, AppSettingsFileName, "nacos").RegisterEnabled;
}
}
/// <summary>
/// 获取Nacos配置
/// </summary>
public static Dictionary<string, string> NacosMetadata
{
get
{
return JsonConfigUtils.GetAppSettings<NacosConfigDTO>(Configuration, AppSettingsFileName, "nacos").Metadata;
}
}
#endregion
#region Nacos配置
/// <summary>
/// Nacos配置实体
/// </summary>
public class NacosConfigDTO
{
/// <summary>
/// 服务IP地址
/// </summary>
public List<string> ServerAddresses { get; set; }
/// <summary>
/// 默认超时时间
/// </summary>
public int DefaultTimeOut { get; set; }
/// <summary>
/// 监听间隔
/// </summary>
public int ListenInterval { get; set; }
/// <summary>
/// 服务命名空间
/// </summary>
public string Namespace { get; set; }
/// <summary>
/// 服务名称
/// </summary>
public string ServiceName { get; set; }
/// <summary>
/// IP地址
/// </summary>
public string Ip { get; set; }
/// <summary>
/// 端口
/// </summary>
public string Port { get; set; }
/// <summary>
/// 服务命名空间
/// </summary>
public bool RegisterEnabled { get; set; }
/// <summary>
/// 其他配置
/// </summary>
public Dictionary<string, string> Metadata { get; set; }
}
#endregion
}

@ -1,29 +0,0 @@
using System.Linq.Expressions;
namespace Tiobon.Core.Common.Helper;
/// <summary>
/// Linq操作帮助类
/// </summary>
public static class LinqHelper
{
/// <summary>
/// 创建初始条件为True的表达式
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Expression<Func<T, bool>> True<T>()
{
return x => true;
}
/// <summary>
/// 创建初始条件为False的表达式
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Expression<Func<T, bool>> False<T>()
{
return x => false;
}
}

@ -1,32 +0,0 @@
namespace Tiobon.Core.Common.Helper;
/// <summary>
/// 日志操作
/// </summary>
public static class LoggerHelper
{
/// <summary>
/// console日志
/// </summary>
/// <param name="msg"></param>
public static void Info(string msg)
{
Console.WriteLine($"{DateTime.Now:HH:mm:ss} {msg}");
}
/// <summary>
/// 正常日志
/// </summary>
/// <param name="msg"></param>
public static void SendLog(string msg)
{
Console.WriteLine($"{DateTime.Now:HH:mm:ss} {msg}");
}
/// <summary>
/// 错误日志
/// </summary>
/// <param name="msg"></param>
public static void SendLogError(string msg)
{
Console.WriteLine($"{DateTime.Now:HH:mm:ss} {msg}");
}
}

@ -1,96 +0,0 @@
using System.Security.Cryptography;
using System.Text;
namespace Tiobon.Core.Common.Helper;
public class MD5Helper
{
/// <summary>
/// 16位MD5加密
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
public static string MD5Encrypt16(string password)
{
var md5 = MD5.Create();
string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password)), 4, 8);
t2 = t2.Replace("-", string.Empty);
return t2;
}
/// <summary>
/// 32位MD5加密
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
public static string MD5Encrypt32(string password = "")
{
string pwd = string.Empty;
try
{
if (!string.IsNullOrEmpty(password) && !string.IsNullOrWhiteSpace(password))
{
MD5 md5 = MD5.Create(); //实例化一个md5对像
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
foreach (var item in s)
{
// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
pwd = string.Concat(pwd, item.ToString("X2"));
}
}
}
catch
{
throw new Exception($"错误的 password 字符串:【{password}】");
}
return pwd;
}
/// <summary>
/// 64位MD5加密
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
public static string MD5Encrypt64(string password)
{
// 实例化一个md5对像
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
MD5 md5 = MD5.Create();
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
return Convert.ToBase64String(s);
}
/// <summary>
/// Sha1加密
/// </summary>
/// <param name="str">要加密的字符串</param>
/// <returns>加密后的十六进制的哈希散列(字符串)</returns>
public static string Sha1(string str, string format = "x2")
{
var buffer = Encoding.UTF8.GetBytes(str);
var data = SHA1.Create().ComputeHash(buffer);
var sb = new StringBuilder();
foreach (var t in data)
{
sb.Append(t.ToString(format));
}
return sb.ToString();
}
/// <summary>
/// Sha256加密
/// </summary>
/// <param name="str">要加密的字符串</param>
/// <returns>加密后的十六进制的哈希散列(字符串)</returns>
public static string Sha256(string str, string format = "x2")
{
var buffer = Encoding.UTF8.GetBytes(str);
var data = SHA256.Create().ComputeHash(buffer);
var sb = new StringBuilder();
foreach (var t in data)
{
sb.Append(t.ToString(format));
}
return sb.ToString();
}
}

@ -1,967 +0,0 @@
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
using System.Text;
namespace Tiobon.Core.Common.Helper;
public class NPOIHelper
{
#region DataTable 导出到 Excel 的 MemoryStream
/// <summary>
/// DataTable 导出到 Excel 的 MemoryStream
/// </summary>
/// <param name="dtSource">源 DataTable</param>
/// <param name="strHeaderText">表头文本 空值未不要表头标题</param>
/// <returns></returns>
public static MemoryStream GenerateExportExcel(DataTable dtSource, string strHeaderText, string sheetName, string strFileName = null)
{
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet;
if (!File.Exists(strFileName))
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
//hssfworkbook = new HSSFWorkbook(file);
//hssfworkbook = new XSSFWorkbook(file);
workbook = WorkbookFactory.Create(file);
}
if (workbook == null) throw new Exception("未能加载excel");
sheet = workbook.CreateSheet(sheetName);
}
#region 文件属性
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "EUCloud";
//workbook.DocumentSummaryInformation = dsi;
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Author = "EUCloud";
si.ApplicationName = "EUCloud";
si.LastAuthor = "EUCloud";
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");
ICellStyle datetimeStyle = workbook.CreateCellStyle();
datetimeStyle.DataFormat = format.GetFormat("yyyy-mm-dd hh:mm");
ICellStyle datetimesStyle = workbook.CreateCellStyle();
datetimesStyle.DataFormat = format.GetFormat("yyyy-mm-dd hh:mm:ss");
int[] arrColWidth = new int[dtSource.Columns.Count];
foreach (DataColumn item in dtSource.Columns)
{
arrColWidth[item.Ordinal] = Encoding.GetEncoding("utf-8").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("utf-8").GetBytes(dtSource.Rows[i][j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
}
int rowIndex = 0;
int intTop = 0;
int HeightInPoints = 40;
foreach (DataRow row in dtSource.Rows)
{
#region 新建表、填充表头、填充列头,样式
if (rowIndex == 655350 || rowIndex == 0)
{
if (rowIndex != 0)
{
sheet = workbook.CreateSheet();
}
intTop = 0;
#region 表头及样式
{
if (!string.IsNullOrWhiteSpace(strHeaderText) && strHeaderText.Length > 0)
{
#region 标题单元格样式
ICellStyle titleStyle = workbook.CreateCellStyle();
titleStyle.Alignment = HorizontalAlignment.Center; //居中
titleStyle.VerticalAlignment = VerticalAlignment.Center;//垂直居中
titleStyle.WrapText = true;//自动换行
// 边框
titleStyle.BorderBottom = BorderStyle.Thin;
titleStyle.BorderLeft = BorderStyle.None;
titleStyle.BorderRight = BorderStyle.None;
titleStyle.BorderTop = BorderStyle.None;
IFont font = workbook.CreateFont();
font.FontHeightInPoints = (short)14;
font.FontName = "宋体";
font.IsBold = true;
titleStyle.SetFont(font);
#endregion
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.IsBold = true;
//headStyle.SetFont(font);
headerRow.GetCell(0).CellStyle = titleStyle;
// 设置行高
headerRow.HeightInPoints = 30;
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
}
}
#endregion
#region 年度人力配置
{
if (sheetName == "年度人力配置")
{
HeightInPoints = 15;
#region 标题单元格样式
ICellStyle titleStyle = workbook.CreateCellStyle();
titleStyle.Alignment = HorizontalAlignment.Center; //居中
titleStyle.VerticalAlignment = VerticalAlignment.Center;//垂直居中
titleStyle.WrapText = true;//自动换行
// 边框
titleStyle.BorderBottom = BorderStyle.Thin;
titleStyle.BorderLeft = BorderStyle.Thin;
titleStyle.BorderRight = BorderStyle.Thin;
titleStyle.BorderTop = BorderStyle.Thin;
IFont font = workbook.CreateFont();
font.FontHeightInPoints = (short)10;
font.FontName = "宋体";
font.IsBold = true;
titleStyle.SetFont(font);
#endregion
IRow headerRow = sheet.CreateRow(intTop);
headerRow.HeightInPoints = HeightInPoints;
for (int i = 0; i < 5; i++)
{
headerRow.CreateCell(i).SetCellValue(dtSource.Columns[i].ColumnName);
headerRow.GetCell(i).CellStyle = titleStyle;
}
for (int i = 5; i < 17; i++)
{
headerRow.CreateCell(i).SetCellValue("预算编制数");
headerRow.GetCell(i).CellStyle = titleStyle;
}
//headerRow.CreateCell(5).SetCellValue("预算编制数");
//headerRow.GetCell(5).CellStyle = titleStyle;
headerRow.CreateCell(17).SetCellValue("备注");
headerRow.GetCell(17).CellStyle = titleStyle;
for (int i = 0; i < 5; i++)
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0 + intTop, 1 + intTop, i, i));
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0 + intTop, 1 + intTop, 17, 17));
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0 + intTop, 0 + intTop, 5, 16));
intTop += 1;
}
}
#endregion
#region 培训计划【牛尾】
if (sheetName == "培训计划【牛尾】")
{
HeightInPoints = 15;
#region 标题单元格样式
ICellStyle titleStyle = workbook.CreateCellStyle();
titleStyle.Alignment = HorizontalAlignment.Center; //居中
titleStyle.VerticalAlignment = VerticalAlignment.Center;//垂直居中
titleStyle.WrapText = true;//自动换行
// 边框
titleStyle.BorderBottom = BorderStyle.Thin;
titleStyle.BorderLeft = BorderStyle.Thin;
titleStyle.BorderRight = BorderStyle.Thin;
titleStyle.BorderTop = BorderStyle.Thin;
IFont font = workbook.CreateFont();
font.FontHeightInPoints = (short)10;
font.FontName = "宋体";
font.IsBold = true;
titleStyle.SetFont(font);
#endregion
IRow headerRow = sheet.CreateRow(intTop);
headerRow.HeightInPoints = HeightInPoints;
for (int i = 0; i < 13; i++)
{
headerRow.CreateCell(i).SetCellValue(dtSource.Columns[i].ColumnName);
headerRow.GetCell(i).CellStyle = titleStyle;
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0 + intTop, 1 + intTop, i, i));
}
for (int i = 13; i < 36; i = i + 2)
{
string month = dtSource.Columns[i].ColumnName.Replace("实际合计人天_M", "") + "月";
//month = month.Replace("进展率_M", "");
headerRow.CreateCell(i).SetCellValue(month);
headerRow.GetCell(i).CellStyle = titleStyle;
headerRow.CreateCell(i + 1).SetCellValue(month);
headerRow.GetCell(i + 1).CellStyle = titleStyle;
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(intTop, intTop, i, i + 1));
}
for (int i = 37; i < 42; i++)
{
headerRow.CreateCell(i).SetCellValue(dtSource.Columns[i].ColumnName);
headerRow.GetCell(i).CellStyle = titleStyle;
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0 + intTop, 1 + intTop, i, i));
}
//for (int i = 5; i < 17; i++)
//{
// headerRow.CreateCell(i).SetCellValue("预算编制数");
// headerRow.GetCell(i).CellStyle = titleStyle;
//}
////headerRow.CreateCell(5).SetCellValue("预算编制数");
////headerRow.GetCell(5).CellStyle = titleStyle;
//headerRow.CreateCell(17).SetCellValue("备注");
//headerRow.GetCell(17).CellStyle = titleStyle;
//for (int i = 36; i < 41; i++)
//sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0 + intTop, 1 + intTop, 17, 17));
//sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0 + intTop, 0 + intTop, 5, 16));
intTop += 1;
}
#endregion
#region 列头及样式
{
IRow headerRow = sheet.CreateRow(intTop);
headerRow.HeightInPoints = HeightInPoints;
intTop += 1;
ICellStyle headStyle = workbook.CreateCellStyle();
headStyle.Alignment = HorizontalAlignment.Center; //居中
headStyle.VerticalAlignment = VerticalAlignment.Center;//垂直居中
headStyle.WrapText = true;//自动换行
// 边框
headStyle.BorderBottom = BorderStyle.Thin;
headStyle.BorderLeft = BorderStyle.Thin;
headStyle.BorderRight = BorderStyle.Thin;
headStyle.BorderTop = BorderStyle.Thin;
// 字体
IFont font = workbook.CreateFont();
font.FontHeightInPoints = (short)10;
font.IsBold = true;
font.FontName = "宋体";
headStyle.SetFont(font);
//ICellStyle headStyle = workbook.CreateCellStyle();
//headStyle.Alignment = HorizontalAlignment.Center;
//headStyle.BorderBottom = BorderStyle.Medium;
//headStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.LightGreen.Index;
//headStyle.FillPattern = FillPattern.NoFill;
//IFont font = workbook.CreateFont();
//font.Boldweight = 700;
//headStyle.SetFont(font);
foreach (DataColumn column in dtSource.Columns)
{
var name = column.ColumnName;
if (name.IndexOf("实际合计人天") > -1)
name = "实际合计人天";
if (name.IndexOf("进展率") > -1)
name = "进展率";
headerRow.CreateCell(column.Ordinal).SetCellValue(name);
headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
//设置列宽
//sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
if (arrColWidth[column.Ordinal] > 255)
{
arrColWidth[column.Ordinal] = 254;
}
else
{
sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
}
}
}
#endregion
rowIndex = intTop;
}
#endregion
#region 填充内容
IRow dataRow = sheet.CreateRow(rowIndex);
dataRow.HeightInPoints = 25;
ICellStyle style = workbook.CreateCellStyle();
style.Alignment = HorizontalAlignment.Center; //居中
style.VerticalAlignment = VerticalAlignment.Center;//垂直居中
style.WrapText = true;//自动换行
// 边框
style.BorderBottom = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
style.BorderTop = BorderStyle.Thin;
// 字体
var font1 = workbook.CreateFont();
font1.FontHeightInPoints = (short)10;
font1.FontName = "宋体";
style.SetFont(font1);
foreach (DataColumn column in dtSource.Columns)
{
ICell newCell = dataRow.CreateCell(column.Ordinal);
newCell.CellStyle = style;
string drValue = row[column].ToString();
switch (column.DataType.ToString())
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
break;
case "System.DateTime"://日期类型
DateTime dateV;
if (!string.IsNullOrEmpty(drValue))
{
DateTime.TryParse(drValue, out dateV);
//dateV = DateTimeHelper.ConvertToSecondString(dateV);
newCell.SetCellValue(ConvertToSecondString(dateV));
//if (column.Caption == "renderDateTime")
//{
// newCell.CellStyle.DataFormat = format.GetFormat("yyyy-mm-dd hh:mm");
//}
//else if (column.Caption == "renderDate")
//{
// newCell.CellStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
//}
//else
//{
//
//}
//try
//{
// Convert.ToDateTime(drValue); newCell.CellStyle.DataFormat = format.GetFormat("yyyy-mm-dd hh:mm:ss");
//}
//catch (Exception)
//{
//}
}
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
foreach (DataColumn column in dtSource.Columns)
{
//设置列宽
//sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
if (arrColWidth[column.Ordinal] > 255)
{
arrColWidth[column.Ordinal] = 254;
}
else
{
sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
}
}
rowIndex++;
}
//获取当前列的宽度,然后对比本列的长度,取最大值
if (true)
for (int columnNum = 0; columnNum <= dtSource.Columns.Count; columnNum++)
{
sheet.AutoSizeColumn(columnNum);//先来个常规自适应
var columnWidth = sheet.GetColumnWidth(columnNum) / 256;
for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
{
IRow currentRow;
//当前行未被使用过
if (sheet.GetRow(rowNum) == null)
{
currentRow = sheet.CreateRow(rowNum);
}
else
{
currentRow = sheet.GetRow(rowNum);
}
if (currentRow.GetCell(columnNum) != null)
{
ICell currentCell = currentRow.GetCell(columnNum);
int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
if (columnWidth < length)
{
columnWidth = length;
if (columnWidth > 30) columnWidth = 30;
}
}
}
try
{
sheet.SetColumnWidth(columnNum, columnWidth * 300); // 256
}
catch (Exception e)
{
}
}
for (int rowNum = 2; rowNum <= sheet.LastRowNum; rowNum++)
{
IRow currentRow = sheet.GetRow(rowNum);
int length = 25;
foreach (var item in currentRow.Cells)
{
if (item != null)
length = Encoding.UTF8.GetBytes(item.ToString()).Length > length ? Encoding.UTF8.GetBytes(item.ToString()).Length : length;
}
currentRow.HeightInPoints = 35 * (length / 150 + 1);
}
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
workbook.Dispose();
//ms.Position = 0;
return ms;
}
}
#endregion
public static string ConvertToSecondString(DateTime? dateTime)
{
if (dateTime is null)
return "";
return dateTime.Value.ToString(@"yyyy\-MM\-dd HH:mm:ss");
}
#region DaataTable 导出到 Excel 文件
/// <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 sheetName = null, string strFileName = null)
{
using (MemoryStream ms = GenerateExportExcel(dtSource, strHeaderText, sheetName, strFileName))
{
using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
}
}
}
#endregion
#region 读取 excel,默认第一行为标头
/// <summary>
/// 读取 excel,默认第一行为标头
/// </summary>
/// <param name="strFileName">excel 文档路径</param>
/// <returns></returns>
public static DataTable ImportExcel(string strFileName, string sheetName = "")
{
DataTable dt = new DataTable();
//HSSFWorkbook hssfworkbook;
IWorkbook hssfworkbook;
ISheet sheet;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
//hssfworkbook = new HSSFWorkbook(file);
//hssfworkbook = new XSSFWorkbook(file);
hssfworkbook = NPOI.SS.UserModel.WorkbookFactory.Create(file);
}
if (hssfworkbook == null) throw new Exception("未能加载excel");
int sheetCount = hssfworkbook.NumberOfSheets;
if (sheetCount == 0) throw new Exception("未能加载excel");
if (string.IsNullOrEmpty(sheetName))
{
sheet = hssfworkbook.GetSheetAt(0);
}
else
{
int sheetIndex = hssfworkbook.GetSheetIndex(sheetName);
if (sheetIndex >= 0)
{
sheet = hssfworkbook.GetSheetAt(sheetIndex);
}
else
{
throw new Exception($"未能找到{sheetName}这个sheet页");
}
}
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);
if (!string.IsNullOrWhiteSpace(cell.ToString()))
dt.Columns.Add(cell.ToString());
}
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row is null)
continue;
//if (row.GetCell(row.FirstCellNum) != null && row.GetCell(row.FirstCellNum).ToString().Length > 0)
//if (row.GetCell(row.FirstCellNum) != null)
{
DataRow dataRow = dt.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (j < 0)
continue;
if (row.GetCell(j) != null)
{
DateTime dateV = DateTime.MinValue;
try
{
dataRow[j] = GetCellValue(row.GetCell(j));
//if (row.GetCell(j).IsDate())
//{
// dateV = row.GetCell(j).DateCellValue;
// dataRow[j] = DateTimeHelper.ConvertToSecondString(dateV);
//}
//else
//{
// dataRow[j] = row.GetCell(j).ToString();
//}
}
catch { }
//if (dateV == DateTime.MinValue)
//{
// dataRow[j] = row.GetCell(j).ToString();
//}
//else
//{
// dataRow[j] = DateTimeHelper.ConvertToSecondString(dateV);
//}
}
}
dt.Rows.Add(dataRow);
}
}
return dt;
}
#endregion
/// <summary>
/// 获取单元格类型
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static string GetCellValue(ICell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return Convert.ToString(cell.BooleanCellValue);
case CellType.Numeric: //NUMERIC:
if (DateUtil.IsCellDateFormatted(cell))
{
return ConvertToSecondString(cell.DateCellValue);
}
else
{
return Convert.ToString(cell);
}
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return Convert.ToString(cell.ErrorCellValue);
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
/// <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("utf-8").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("utf-8").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++;
}
}
}

@ -1,297 +0,0 @@
namespace Tiobon.Core.Common.Helper.SM;
public class SM4
{
public const int SM4_ENCRYPT = 1;
public const int SM4_DECRYPT = 0;
private long GET_ULONG_BE(SByte[] b, int i)
{
#pragma warning disable CS0675 // 对进行了带符号扩展的操作数使用了按位或运算符
long n2 = (b[i] & 0xFF) << 24 | (b[(i + 1)] & 0xFF) << 16 | (b[(i + 2)] & 0xFF) << 8 | b[(i + 3)] & 0xFF & 0xFFFFFFFF;
#pragma warning restore CS0675 // 对进行了带符号扩展的操作数使用了按位或运算符
return n2;
}
private void PUT_ULONG_BE(long n, SByte[] b, int i)
{
b[i] = (SByte)(int)(0xFF & n >> 24);
b[i + 1] = (SByte)(int)(0xFF & n >> 16);
b[i + 2] = (SByte)(int)(0xFF & n >> 8);
b[i + 3] = (SByte)(int)(0xFF & n);
}
private long SHL(long x, int n)
{
return (x & 0xFFFFFFFF) << n;
}
private long ROTL(long x, int n)
{
return SHL(x, n) | x >> (32 - n);
}
private void SWAP(long[] sk, int i)
{
long t = sk[i];
sk[i] = sk[(31 - i)];
sk[(31 - i)] = t;
}
/// <summary>
/// S盒
/// </summary>
//public SByte[] SboxTable = new SByte[] {
// 0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05,
// 0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99,
// 0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62,
// 0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6,
// 0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8,
// 0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35,
// 0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87,
// 0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e,
// 0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1,
// 0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3,
// 0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f,
// 0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51,
// 0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8,
// 0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0,
// 0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84,
// 0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48
//};
public SByte[] SboxTable = { -42, -112, -23, -2, -52, -31, 61, -73, 22, -74, 20, -62, 40, -5, 44, 5, 43, 103, -102, 118, 42, -66, 4, -61, -86, 68, 19, 38, 73, -122, 6, -103, -100, 66, 80, -12, -111, -17, -104, 122, 51, 84, 11, 67, -19, -49, -84, 98, -28, -77, 28, -87, -55, 8, -24, -107, -128, -33, -108, -6, 117, -113, 63, -90, 71, 7, -89, -4, -13, 115, 23, -70, -125, 89, 60, 25, -26, -123, 79, -88, 104, 107, -127, -78, 113, 100, -38, -117, -8, -21, 15, 75, 112, 86, -99, 53, 30, 36, 14, 94, 99, 88, -47, -94, 37, 34, 124, 59, 1, 33, 120, -121, -44, 0, 70, 87, -97, -45, 39, 82, 76, 54, 2, -25, -96, -60, -56, -98, -22, -65, -118, -46, 64, -57, 56, -75, -93, -9, -14, -50, -7, 97, 21, -95, -32, -82, 93, -92, -101, 52, 26, 85, -83, -109, 50, 48, -11, -116, -79, -29, 29, -10, -30, 46, -126, 102, -54, 96, -64, 41, 35, -85, 13, 83, 78, 111, -43, -37, 55, 69, -34, -3, -114, 47, 3, -1, 106, 114, 109, 108, 91, 81, -115, 27, -81, -110, -69, -35, -68, 127, 17, -39, 92, 65, 31, 16, 90, -40, 10, -63, 49, -120, -91, -51, 123, -67, 45, 116, -48, 18, -72, -27, -76, -80, -119, 105, -105, 74, 12, -106, 119, 126, 101, -71, -15, 9, -59, 110, -58, -124, 24, -16, 125, -20, 58, -36, 77, 32, 121, -18, 95, 62, -41, -53, 57, 72 };
public int[] FK = { -1548633402, 1453994832, 1736282519, -1301273892 };
public int[] CK = { 462357, 472066609, 943670861, 1415275113, 1886879365, -1936483679, -1464879427, -993275175, -521670923, -66909679, 404694573, 876298825, 1347903077, 1819507329, -2003855715, -1532251463, -1060647211, -589042959, -117504499, 337322537, 808926789, 1280531041, 1752135293, -2071227751, -1599623499, -1128019247, -656414995, -184876535, 269950501, 741554753, 1213159005, 1684763257 };
private SByte sm4Sbox(SByte inch)
{
int i = inch & 0xFF;
SByte retVal = SboxTable[i];
return retVal;
}
private long sm4Lt(long ka)
{
long bb = 0L;
long c = 0L;
SByte[] a = new SByte[4];
SByte[] b = new SByte[4];
PUT_ULONG_BE(ka, a, 0);
b[0] = sm4Sbox(a[0]);
b[1] = sm4Sbox(a[1]);
b[2] = sm4Sbox(a[2]);
b[3] = sm4Sbox(a[3]);
bb = GET_ULONG_BE(b, 0);
c = bb ^ ROTL(bb, 2) ^ ROTL(bb, 10) ^ ROTL(bb, 18) ^ ROTL(bb, 24);
return c;
}
private long sm4F(long x0, long x1, long x2, long x3, long rk)
{
return x0 ^ sm4Lt(x1 ^ x2 ^ x3 ^ rk);
}
private long sm4CalciRK(long ka)
{
long bb = 0L;
long rk = 0L;
SByte[] a = new SByte[4];
SByte[] b = new SByte[4];
PUT_ULONG_BE(ka, a, 0);
b[0] = sm4Sbox(a[0]);
b[1] = sm4Sbox(a[1]);
b[2] = sm4Sbox(a[2]);
b[3] = sm4Sbox(a[3]);
bb = GET_ULONG_BE(b, 0);
rk = bb ^ ROTL(bb, 13) ^ ROTL(bb, 23);
return rk;
}
private void sm4_setkey(long[] SK, SByte[] key)
{
long[] MK = new long[4];
long[] k = new long[36];
int i = 0;
MK[0] = GET_ULONG_BE(key, 0);
MK[1] = GET_ULONG_BE(key, 4);
MK[2] = GET_ULONG_BE(key, 8);
MK[3] = GET_ULONG_BE(key, 12);
MK[0] ^= FK[0];
MK[1] ^= FK[1];
MK[2] ^= FK[2];
MK[3] ^= FK[3];
for (; i < 32; i++)
{
k[(i + 4)] = (k[i] ^ sm4CalciRK(k[(i + 1)] ^ k[(i + 2)] ^ k[(i + 3)] ^ CK[i]));
SK[i] = k[(i + 4)];
}
}
private void sm4_one_round(long[] sk, SByte[] input, SByte[] output)
{
int i = 0;
long[] ulbuf = new long[36];
ulbuf[0] = GET_ULONG_BE(input, 0);
ulbuf[1] = GET_ULONG_BE(input, 4);
ulbuf[2] = GET_ULONG_BE(input, 8);
ulbuf[3] = GET_ULONG_BE(input, 12);
while (i < 32)
{
ulbuf[(i + 4)] = sm4F(ulbuf[i], ulbuf[(i + 1)], ulbuf[(i + 2)], ulbuf[(i + 3)], sk[i]);
i++;
}
PUT_ULONG_BE(ulbuf[35], output, 0);
PUT_ULONG_BE(ulbuf[34], output, 4);
PUT_ULONG_BE(ulbuf[33], output, 8);
PUT_ULONG_BE(ulbuf[32], output, 12);
}
private SByte[] padding(SByte[] input, int mode)
{
if (input == null)
{
return null;
}
SByte[] ret = (SByte[])null;
if (mode == SM4_ENCRYPT)
{
int p = 16 - input.Length % 16;
ret = new SByte[input.Length + p];
Array.Copy(input, 0, ret, 0, input.Length);
for (int i = 0; i < p; i++)
{
ret[input.Length + i] = (SByte)p;
}
}
else
{
int p = input[input.Length - 1];
ret = new SByte[input.Length - p];
Array.Copy(input, 0, ret, 0, input.Length - p);
}
return ret;
}
public void sm4_setkey_enc(SM4_Context ctx, SByte[] key)
{
ctx.mode = SM4_ENCRYPT;
sm4_setkey(ctx.sk, key);
}
public void sm4_setkey_dec(SM4_Context ctx, SByte[] key)
{
int i = 0;
ctx.mode = SM4_DECRYPT;
sm4_setkey(ctx.sk, key);
for (i = 0; i < 16; i++)
{
SWAP(ctx.sk, i);
}
}
public SByte[] sm4_crypt_ecb(SM4_Context ctx, SByte[] input)
{
if (input == null)
{
throw new Exception("input is null!");
}
if ((ctx.isPadding) && (ctx.mode == SM4_ENCRYPT))
{
input = padding(input, SM4_ENCRYPT);
}
int length = input.Length;
SByte[] bins = new SByte[length];
SByte[] bous = new SByte[length];
Array.Copy(input, 0, bins, 0, length);
for (int i = 0; length > 0; length -= 16, i++)
{
SByte[] inBytes = new SByte[16];
SByte[] outBytes = new SByte[16];
Array.Copy(bins, i * 16, inBytes, 0, length > 16 ? 16 : length);
sm4_one_round(ctx.sk, inBytes, outBytes);
Array.Copy(outBytes, 0, bous, i * 16, length > 16 ? 16 : length);
}
if (ctx.isPadding && ctx.mode == SM4_DECRYPT)
{
bous = padding(bous, SM4_DECRYPT);
}
return bous;
}
public SByte[] sm4_crypt_cbc(SM4_Context ctx, SByte[] iv, SByte[] input)
{
if (ctx.isPadding && ctx.mode == SM4_ENCRYPT)
{
input = padding(input, SM4_ENCRYPT);
}
int i = 0;
int length = input.Length;
SByte[] bins = new SByte[length];
Array.Copy(input, 0, bins, 0, length);
SByte[] bous = null;
List<SByte> bousList = new List<SByte>();
if (ctx.mode == SM4_ENCRYPT)
{
for (int j = 0; length > 0; length -= 16, j++)
{
SByte[] inBytes = new SByte[16];
SByte[] outBytes = new SByte[16];
SByte[] out1 = new SByte[16];
Array.Copy(bins, i * 16, inBytes, 0, length > 16 ? 16 : length);
for (i = 0; i < 16; i++)
{
outBytes[i] = ((SByte)(inBytes[i] ^ iv[i]));
}
sm4_one_round(ctx.sk, outBytes, out1);
Array.Copy(out1, 0, iv, 0, 16);
for (int k = 0; k < 16; k++)
{
bousList.Add(out1[k]);
}
}
}
else
{
SByte[] temp = new SByte[16];
for (int j = 0; length > 0; length -= 16, j++)
{
SByte[] inBytes = new SByte[16];
SByte[] outBytes = new SByte[16];
SByte[] out1 = new SByte[16];
Array.Copy(bins, i * 16, inBytes, 0, length > 16 ? 16 : length);
Array.Copy(inBytes, 0, temp, 0, 16);
sm4_one_round(ctx.sk, inBytes, outBytes);
for (i = 0; i < 16; i++)
{
out1[i] = ((SByte)(outBytes[i] ^ iv[i]));
}
Array.Copy(temp, 0, iv, 0, 16);
for (int k = 0; k < 16; k++)
{
bousList.Add(out1[k]);
}
}
}
if (ctx.isPadding && ctx.mode == SM4_DECRYPT)
{
bous = padding(bousList.ToArray(), SM4_DECRYPT);
return bous;
}
else
{
return bousList.ToArray();
}
}
}

@ -1,93 +0,0 @@
using System.Text;
using System.Text.RegularExpressions;
namespace Tiobon.Core.Common.Helper.SM;
public class SM4Helper
{
public String secretKey = "1234567890123456";// 16位
public String iv = "";
public bool hexString = false;
private SByte[] Byte2SByte(byte[] myByte)
{
sbyte[] mySByte = new sbyte[myByte.Length];
for (int i = 0; i < myByte.Length; i++)
{
if (myByte[i] > 127)
mySByte[i] = (sbyte)(myByte[i] - 256);
else
mySByte[i] = (sbyte)myByte[i];
}
return mySByte;
}
private byte[] SByte2Byte(sbyte[] orig)
{
byte[] arr = new byte[orig.Length];
Buffer.BlockCopy(orig, 0, arr, 0, orig.Length);
return arr;
}
public String Encrypt_ECB(String plainText)
{
SM4_Context ctx = new SM4_Context();
ctx.isPadding = true;
ctx.mode = SM4.SM4_ENCRYPT;
SByte[] keyBytes;
if (hexString)
{
keyBytes = null;// Hex.Decode(secretKey);
}
else
{
keyBytes = Byte2SByte(Encoding.UTF8.GetBytes(secretKey));
}
SM4 sm4 = new SM4();
sm4.sm4_setkey_enc(ctx, keyBytes);
SByte[] bytes = Byte2SByte(Encoding.UTF8.GetBytes(plainText));
SByte[] encrypted = sm4.sm4_crypt_ecb(ctx, bytes);
//String cipherText = Encoding.UTF8.GetString(Hex.Encode(SByte2Byte(encrypted)));
String cipherText = new Base64Encoder().GetEncoded(SByte2Byte(encrypted));
if ((cipherText != null) && (cipherText.Trim().Length > 0))
{
var matchCol = Regex.Matches(cipherText, "\\s*|\t|\r|\n", RegexOptions.Multiline);
for (int i = matchCol.Count - 1; i >= 0; i--)
{
Match item = matchCol[i];
cipherText.Remove(item.Index, item.Length);
}
}
return cipherText;
}
public String Decrypt_ECB(String cipherText)
{
SM4_Context ctx = new SM4_Context();
ctx.isPadding = true;
ctx.mode = SM4.SM4_DECRYPT;
SByte[] keyBytes;
if (hexString)
{
keyBytes = null;// Hex.Decode(secretKey);
}
else
{
keyBytes = Byte2SByte(Encoding.UTF8.GetBytes(secretKey));
}
SM4 sm4 = new SM4();
sm4.sm4_setkey_dec(ctx, keyBytes);
SByte[] decrypted = sm4.sm4_crypt_ecb(ctx, Byte2SByte(new Base64Decoder().GetDecoded(cipherText)));
return Encoding.UTF8.GetString(SByte2Byte(decrypted));
}
}

@ -1,17 +0,0 @@
namespace Tiobon.Core.Common.Helper.SM;
public class SM4_Context
{
public int mode;
public long[] sk;
public bool isPadding;
public SM4_Context()
{
this.mode = 1;
this.isPadding = true;
this.sk = new long[32];
}
}

@ -4,7 +4,7 @@ using System.Diagnostics;
using System.Reflection;
using System.Text;
using Tiobon.Core.Common.DB;
using Tiobon.Core.Common.Extensions;
using Tiobon.Core.Extensions;
using Tiobon.Core.Const;
using Tiobon.Core.DB;
using Tiobon.Core.Helper;
@ -106,7 +106,7 @@ public class DBSeed
ConsoleHelper.WriteSuccessLine($"Tables created successfully!");
Console.WriteLine();
if (AppSettings.app(new string[] {"AppSettings", "SeedDBDataEnabled"}).ObjToBool())
if (AppSettings.app(new string[] { "AppSettings", "SeedDBDataEnabled" }).ObjToBool())
{
JsonSerializerSettings setting = new JsonSerializerSettings();
JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>

@ -2,11 +2,8 @@
using Microsoft.AspNetCore.Http;
using NPOI.HSSF.UserModel;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.POIFS.NIO;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.Util.Collections;
using NPOI.XSSF.UserModel;
using SqlSugar;
using System;
@ -18,9 +15,7 @@ using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tiobon.Core.Common;
using Tiobon.Core.Common.Extensions;
using Tiobon.Core.Common.Helper;
using Tiobon.Core.Extensions;
using Tiobon.Core.Helper;
using Tiobon.Core.Model.Entity;
using Tiobon.Core.Model.Models;

@ -1,9 +1,8 @@
using Tiobon.Core.Common.Extensions;
using Confluent.Kafka;
using Confluent.Kafka;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using Tiobon.Core.Extensions;
namespace Tiobon.Core.EventBus
{

@ -1,6 +1,4 @@
using Autofac;
using Tiobon.Core.Common.Extensions;
using Tiobon.Core.Common;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
@ -9,10 +7,9 @@ using Polly.Retry;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.Exceptions;
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Tiobon.Core.Extensions;
namespace Tiobon.Core.EventBus
{

@ -2,7 +2,7 @@
using Newtonsoft.Json;
using SqlSugar;
using System.Linq.Expressions;
using Tiobon.Core.Common.Helper;
using Tiobon.Core.Helper;
namespace Tiobon.Core.AOP;

@ -1,7 +1,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Nacos.V2;
using Tiobon.Core.Common.Helper;
using Tiobon.Core.Helper;
namespace Tiobon.Core.Extensions.NacosConfig;

@ -1,7 +1,6 @@
using Microsoft.Extensions.Hosting;
using Nacos.V2;
using Tiobon.Core.Common;
using Tiobon.Core.Common.Helper;
using Tiobon.Core.Helper;
namespace Tiobon.Core.Extensions.NacosConfig;

@ -1,9 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Nacos.V2.DependencyInjection;
using Tiobon.Core.Common;
using Tiobon.Core.Common.Helper;
using Tiobon.Core.Extensions.NacosConfig;
using Tiobon.Core.Helper;
namespace Tiobon.Core.Extensions;

@ -1,9 +1,8 @@
using System.Net;
using Microsoft.AspNetCore.Authentication;
using System.Net;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Authentication;
using Tiobon.Core.Common;
using Tiobon.Core.Caches;
using Tiobon.Core.Common.Helper;
using Tiobon.Core.Helper;
namespace Tiobon.Core.AuthHelper
{

@ -1,10 +1,9 @@
using System.Data;
using System.Linq.Expressions;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using Tiobon.Core.Common;
using System.Data;
using System.Linq.Expressions;
using System.Reflection;
using Tiobon.Core.Common.DB;
using Tiobon.Core.IRepository.Base;
using Tiobon.Core.Model;
@ -757,7 +756,7 @@ public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity :
protected Expression<Func<T, bool>> CombineExpressions<T>(
Expression<Func<T, bool>> expression1, Expression<Func<T, bool>> expression2)
{
return Common.Helper.ExpressionCombiner.Combine(expression1, expression2);
return Helper.ExpressionCombiner.Combine(expression1, expression2);
}
#endregion

@ -2,7 +2,7 @@
using SqlSugar;
using System.Collections.Concurrent;
using System.Reflection;
using Tiobon.Core.Common.Extensions;
using Tiobon.Core.Extensions;
namespace Tiobon.Core.Repository.UnitOfWorks;

@ -1,4 +1,4 @@
using Tiobon.Core.Common.Extensions;
using Tiobon.Core.Extensions;
using Tiobon.Core.Common.Https;
using Microsoft.AspNetCore.Http;
using Serilog;

@ -1,4 +1,6 @@
namespace Tiobon.Core.Services;
using Tiobon.Core.Extensions;
namespace Tiobon.Core.Services;
public partial class TasksLogServices : BaseServices<Ghre_TasksLog>, ITasksLogServices
{

@ -1,5 +1,5 @@
using Microsoft.Extensions.Logging;
using Tiobon.Core.Common.Helper;
using Tiobon.Core.Helper;
/// <summary>
/// 这里要注意下,命名空间和程序集是一样的,不然反射不到(任务类要去JobSetup添加注入)

@ -1,10 +1,8 @@
using System;
using System.Threading.Tasks;
using Autofac;
using Tiobon.Core.Common.Helper;
using Autofac;
using SqlSugar;
using Tiobon.Core.Helper;
using Tiobon.Core.IRepository.Base;
using Tiobon.Core.Model.Models;
using SqlSugar;
using Xunit;
using Xunit.Abstractions;

@ -1,4 +1,4 @@
using Tiobon.Core.Common.Helper;
using Tiobon.Core.Helper;
using Xunit;
namespace Tiobon.Core.Tests.Common_Test

Loading…
Cancel
Save