This commit is contained in:
“wanyongkang”
2020-12-28 14:55:48 +08:00
parent c2ec7392cb
commit 40a40b6d36
305 changed files with 20629 additions and 20629 deletions

View File

@@ -1,71 +1,71 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Serialization; using System.Xml.Serialization;
using Hncore.Infrastructure.Common; using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Serializer; using Hncore.Infrastructure.Serializer;
namespace Hncore.Infrastructure.AliYun namespace Hncore.Infrastructure.AliYun
{ {
public class AliDayu public class AliDayu
{ {
const string SignName = ""; const string SignName = "";
private IHttpClientFactory _httpClientFactory; private IHttpClientFactory _httpClientFactory;
public AliDayu(IHttpClientFactory httpClientFactory) public AliDayu(IHttpClientFactory httpClientFactory)
{ {
_httpClientFactory = httpClientFactory; _httpClientFactory = httpClientFactory;
} }
public async Task<bool> SendSms(List<string> PhoneNumbers, string templateCode, object content) public async Task<bool> SendSms(List<string> PhoneNumbers, string templateCode, object content)
{ {
Dictionary<string, string> paramDic = Util.BuildCommonParam(); Dictionary<string, string> paramDic = Util.BuildCommonParam();
paramDic.Add("Action", "SendSms"); paramDic.Add("Action", "SendSms");
paramDic.Add("Version", "2017-05-25"); paramDic.Add("Version", "2017-05-25");
paramDic.Add("RegionId", "cn-hangzhou"); paramDic.Add("RegionId", "cn-hangzhou");
paramDic.Add("PhoneNumbers", ListHelper<string>.ListToStr(PhoneNumbers)); paramDic.Add("PhoneNumbers", ListHelper<string>.ListToStr(PhoneNumbers));
paramDic.Add("SignName", SignName); paramDic.Add("SignName", SignName);
paramDic.Add("TemplateCode", templateCode); paramDic.Add("TemplateCode", templateCode);
paramDic.Add("TemplateParam", content.ToJson()); paramDic.Add("TemplateParam", content.ToJson());
string sign = Util.CreateSign(paramDic); string sign = Util.CreateSign(paramDic);
paramDic.Add("Signature", sign); paramDic.Add("Signature", sign);
var httpClient = _httpClientFactory.CreateClient("AliDayu"); var httpClient = _httpClientFactory.CreateClient("AliDayu");
string url = "http://dysmsapi.aliyuncs.com"; string url = "http://dysmsapi.aliyuncs.com";
foreach (var keyValuePair in paramDic) foreach (var keyValuePair in paramDic)
{ {
url = UrlHelper.SetUrlParam(keyValuePair.Key, keyValuePair.Value); url = UrlHelper.SetUrlParam(keyValuePair.Key, keyValuePair.Value);
} }
var res = await httpClient.GetStringAsync(url); var res = await httpClient.GetStringAsync(url);
SendSmsResponse result = XML.XmlDeserialize<SendSmsResponse>(res); SendSmsResponse result = XML.XmlDeserialize<SendSmsResponse>(res);
if (result.Code == "OK") if (result.Code == "OK")
{ {
return true; return true;
} }
LogHelper.Error("阿里大于短信发送失败", res); LogHelper.Error("阿里大于短信发送失败", res);
return false; return false;
} }
} }
[XmlRoot] [XmlRoot]
public class SendSmsResponse public class SendSmsResponse
{ {
[XmlElement] public string Message { get; set; } [XmlElement] public string Message { get; set; }
[XmlElement] public string RequestId { get; set; } [XmlElement] public string RequestId { get; set; }
[XmlElement] public string BizId { get; set; } [XmlElement] public string BizId { get; set; }
[XmlElement] public string Code { get; set; } [XmlElement] public string Code { get; set; }
} }
} }

View File

@@ -1,82 +1,82 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Web; using System.Web;
using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing;
namespace Hncore.Infrastructure.AliYun namespace Hncore.Infrastructure.AliYun
{ {
public class Util public class Util
{ {
const string QUERY_SEPARATOR = "&"; const string QUERY_SEPARATOR = "&";
const string HEADER_SEPARATOR = "\n"; const string HEADER_SEPARATOR = "\n";
const string AccessSecret = "r8FfRmoeWcCJyZSqqkQP2G3dKPPl2N "; const string AccessSecret = "r8FfRmoeWcCJyZSqqkQP2G3dKPPl2N ";
private const string AccessKeyId = "LTAI4FmSkDSwFuXeLxsDB3jB"; private const string AccessKeyId = "LTAI4FmSkDSwFuXeLxsDB3jB";
public static string CreateSign(Dictionary<string, string> data, string method = "GET") public static string CreateSign(Dictionary<string, string> data, string method = "GET")
{ {
var dic = new RouteValueDictionary(data); var dic = new RouteValueDictionary(data);
string[] array = dic.OrderBy(a => a.Key, StringComparer.Ordinal) string[] array = dic.OrderBy(a => a.Key, StringComparer.Ordinal)
.Select(a => PercentEncode(a.Key) + "=" + PercentEncode(a.Value.ToString())).ToArray(); .Select(a => PercentEncode(a.Key) + "=" + PercentEncode(a.Value.ToString())).ToArray();
string dataStr = string.Join("&", array); string dataStr = string.Join("&", array);
string signStr = method + "&" + PercentEncode("/") + "&" + PercentEncode(dataStr); string signStr = method + "&" + PercentEncode("/") + "&" + PercentEncode(dataStr);
HMACSHA1 myhmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(AccessSecret + "&")); HMACSHA1 myhmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(AccessSecret + "&"));
byte[] byteArray = Encoding.UTF8.GetBytes(signStr); byte[] byteArray = Encoding.UTF8.GetBytes(signStr);
MemoryStream stream = new MemoryStream(byteArray); MemoryStream stream = new MemoryStream(byteArray);
string signature = Convert.ToBase64String(myhmacsha1.ComputeHash(stream)); string signature = Convert.ToBase64String(myhmacsha1.ComputeHash(stream));
return signature; return signature;
} }
private static string PercentEncode(string value) private static string PercentEncode(string value)
{ {
return UpperCaseUrlEncode(value) return UpperCaseUrlEncode(value)
.Replace("+", "%20") .Replace("+", "%20")
.Replace("*", "%2A") .Replace("*", "%2A")
.Replace("%7E", "~"); .Replace("%7E", "~");
} }
private static string UpperCaseUrlEncode(string s) private static string UpperCaseUrlEncode(string s)
{ {
char[] temp = HttpUtility.UrlEncode(s).ToCharArray(); char[] temp = HttpUtility.UrlEncode(s).ToCharArray();
for (int i = 0; i < temp.Length - 2; i++) for (int i = 0; i < temp.Length - 2; i++)
{ {
if (temp[i] == '%') if (temp[i] == '%')
{ {
temp[i + 1] = char.ToUpper(temp[i + 1]); temp[i + 1] = char.ToUpper(temp[i + 1]);
temp[i + 2] = char.ToUpper(temp[i + 2]); temp[i + 2] = char.ToUpper(temp[i + 2]);
} }
} }
return new string(temp); return new string(temp);
} }
public static IDictionary<string, string> SortDictionary(Dictionary<string, string> dic) public static IDictionary<string, string> SortDictionary(Dictionary<string, string> dic)
{ {
IDictionary<string, string> sortedDictionary = IDictionary<string, string> sortedDictionary =
new SortedDictionary<string, string>(dic, StringComparer.Ordinal); new SortedDictionary<string, string>(dic, StringComparer.Ordinal);
return sortedDictionary; return sortedDictionary;
} }
public static Dictionary<string, string> BuildCommonParam() public static Dictionary<string, string> BuildCommonParam()
{ {
Dictionary<string, string> dic = new Dictionary<string, string>(); Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("AccessKeyId", AccessKeyId); dic.Add("AccessKeyId", AccessKeyId);
dic.Add("Timestamp", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")); dic.Add("Timestamp", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"));
dic.Add("SignatureMethod", "HMAC-SHA1"); dic.Add("SignatureMethod", "HMAC-SHA1");
dic.Add("SignatureVersion", "1.0"); dic.Add("SignatureVersion", "1.0");
dic.Add("SignatureNonce", Guid.NewGuid().ToString()); dic.Add("SignatureNonce", Guid.NewGuid().ToString());
return dic; return dic;
} }
} }
} }

View File

@@ -1,61 +1,61 @@
using System; using System;
using System.Linq; using System.Linq;
using Autofac; using Autofac;
using Autofac.Extensions.DependencyInjection; using Autofac.Extensions.DependencyInjection;
using Hncore.Infrastructure.IOC; using Hncore.Infrastructure.IOC;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Hncore.Infrastructure.DDD; using Hncore.Infrastructure.DDD;
using Hncore.Infrastructure.EF; using Hncore.Infrastructure.EF;
namespace Hncore.Infrastructure.Autofac namespace Hncore.Infrastructure.Autofac
{ {
public class MvcAutoRegister public class MvcAutoRegister
{ {
public IServiceProvider Build(IServiceCollection services, IMvcBuilder mvcBuilder, public IServiceProvider Build(IServiceCollection services, IMvcBuilder mvcBuilder,
Action<ContainerBuilder> action = null) Action<ContainerBuilder> action = null)
{ {
mvcBuilder.AddControllersAsServices(); mvcBuilder.AddControllersAsServices();
var builder = new ContainerBuilder(); var builder = new ContainerBuilder();
var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToArray(); var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToArray();
var perRequestType = typeof(IPerRequest); var perRequestType = typeof(IPerRequest);
builder.RegisterAssemblyTypes(assemblys) builder.RegisterAssemblyTypes(assemblys)
.Where(t => perRequestType.IsAssignableFrom(t) && t != perRequestType) .Where(t => perRequestType.IsAssignableFrom(t) && t != perRequestType)
.PropertiesAutowired() .PropertiesAutowired()
.AsImplementedInterfaces() .AsImplementedInterfaces()
.InstancePerLifetimeScope(); .InstancePerLifetimeScope();
var perDependencyType = typeof(IDependency); var perDependencyType = typeof(IDependency);
builder.RegisterAssemblyTypes(assemblys) builder.RegisterAssemblyTypes(assemblys)
.Where(t => perDependencyType.IsAssignableFrom(t) && t != perDependencyType) .Where(t => perDependencyType.IsAssignableFrom(t) && t != perDependencyType)
.PropertiesAutowired() .PropertiesAutowired()
.AsImplementedInterfaces() .AsImplementedInterfaces()
.InstancePerDependency(); .InstancePerDependency();
var singleInstanceType = typeof(ISingleInstance); var singleInstanceType = typeof(ISingleInstance);
builder.RegisterAssemblyTypes(assemblys) builder.RegisterAssemblyTypes(assemblys)
.Where(t => singleInstanceType.IsAssignableFrom(t) && t != singleInstanceType) .Where(t => singleInstanceType.IsAssignableFrom(t) && t != singleInstanceType)
.PropertiesAutowired() .PropertiesAutowired()
.AsImplementedInterfaces() .AsImplementedInterfaces()
.SingleInstance(); .SingleInstance();
builder.RegisterGeneric(typeof(QueryBase<,>)).As(typeof(IQuery<,>)).PropertiesAutowired() builder.RegisterGeneric(typeof(QueryBase<,>)).As(typeof(IQuery<,>)).PropertiesAutowired()
.InstancePerLifetimeScope(); .InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(RepositoryBase<,>)).As(typeof(IRepository<,>)).PropertiesAutowired() builder.RegisterGeneric(typeof(RepositoryBase<,>)).As(typeof(IRepository<,>)).PropertiesAutowired()
.InstancePerLifetimeScope(); .InstancePerLifetimeScope();
action?.Invoke(builder); action?.Invoke(builder);
builder.Populate(services); builder.Populate(services);
var container = builder.Build(); var container = builder.Build();
var servicesProvider = new AutofacServiceProvider(container); var servicesProvider = new AutofacServiceProvider(container);
return servicesProvider; return servicesProvider;
} }
} }
} }

View File

@@ -1,49 +1,49 @@
using System.Text; using System.Text;
namespace Hncore.Infrastructure.CSV namespace Hncore.Infrastructure.CSV
{ {
public class CsvRow public class CsvRow
{ {
private string _content = ""; private string _content = "";
public CsvRow AddCell(string content) public CsvRow AddCell(string content)
{ {
if (_content != "") if (_content != "")
{ {
_content += ","; _content += ",";
} }
_content += StringToCsvCell(content); _content += StringToCsvCell(content);
return this; return this;
} }
public override string ToString() public override string ToString()
{ {
return _content; return _content;
} }
private static string StringToCsvCell(string str) private static string StringToCsvCell(string str)
{ {
bool mustQuote = str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n"); bool mustQuote = str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n");
if (mustQuote) if (mustQuote)
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.Append("\""); sb.Append("\"");
foreach (char nextChar in str) foreach (char nextChar in str)
{ {
sb.Append(nextChar); sb.Append(nextChar);
if (nextChar == '"') if (nextChar == '"')
{ {
sb.Append("\""); sb.Append("\"");
} }
} }
sb.Append("\""); sb.Append("\"");
return sb.ToString(); return sb.ToString();
} }
return str; return str;
} }
} }
} }

View File

@@ -1,84 +1,84 @@
using System; using System;
using System.IO; using System.IO;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Hncore.Infrastructure.Extension; using Hncore.Infrastructure.Extension;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
namespace Hncore.Infrastructure.CSV namespace Hncore.Infrastructure.CSV
{ {
public class CsvTemporaryFile : IDisposable public class CsvTemporaryFile : IDisposable
{ {
private string filePath = ""; private string filePath = "";
private FileStream _fileStream; private FileStream _fileStream;
private StreamWriter _streamWriter; private StreamWriter _streamWriter;
public CsvTemporaryFile() public CsvTemporaryFile()
{ {
var execDir = Path.GetDirectoryName(typeof(CsvTemporaryFile).Assembly.Location); var execDir = Path.GetDirectoryName(typeof(CsvTemporaryFile).Assembly.Location);
string tempDir = Path.Combine(execDir, "temp", DateTime.Now.ToString("yyyyMMdd")); string tempDir = Path.Combine(execDir, "temp", DateTime.Now.ToString("yyyyMMdd"));
if (!Directory.Exists(tempDir)) if (!Directory.Exists(tempDir))
{ {
Directory.CreateDirectory(tempDir); Directory.CreateDirectory(tempDir);
} }
filePath = Path.Combine(tempDir, Guid.NewGuid().ToString()); filePath = Path.Combine(tempDir, Guid.NewGuid().ToString());
_fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write); _fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
_streamWriter = new StreamWriter(_fileStream, Encoding.GetEncoding("GB2312")); _streamWriter = new StreamWriter(_fileStream, Encoding.GetEncoding("GB2312"));
_streamWriter.AutoFlush = true; _streamWriter.AutoFlush = true;
} }
public void WriteLine(CsvRow row) public void WriteLine(CsvRow row)
{ {
_streamWriter.WriteLine(row.ToString()); _streamWriter.WriteLine(row.ToString());
} }
public async Task ResponseAsync(HttpResponse httpResponse, string fileName) public async Task ResponseAsync(HttpResponse httpResponse, string fileName)
{ {
httpResponse.ContentType = "application/octet-stream"; httpResponse.ContentType = "application/octet-stream";
httpResponse.Headers.Add("Content-Disposition", $"attachment; filename={fileName.UrlEncode()}"); httpResponse.Headers.Add("Content-Disposition", $"attachment; filename={fileName.UrlEncode()}");
httpResponse.Headers.Add("X-Suggested-Filename", fileName.UrlEncode()); httpResponse.Headers.Add("X-Suggested-Filename", fileName.UrlEncode());
using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{ {
using (BufferedStream bs = new BufferedStream(fs)) using (BufferedStream bs = new BufferedStream(fs))
{ {
byte[] buffer = new byte[4096]; byte[] buffer = new byte[4096];
int bytesRead; int bytesRead;
long total_read = 0; long total_read = 0;
DateTime begin = DateTime.Now; DateTime begin = DateTime.Now;
TimeSpan ts = new TimeSpan(); TimeSpan ts = new TimeSpan();
while ((bytesRead = bs.Read(buffer, 0, buffer.Length)) > 0) while ((bytesRead = bs.Read(buffer, 0, buffer.Length)) > 0)
{ {
await httpResponse.Body.WriteAsync(buffer, 0, bytesRead); await httpResponse.Body.WriteAsync(buffer, 0, bytesRead);
await httpResponse.Body.FlushAsync(); await httpResponse.Body.FlushAsync();
total_read += bytesRead; total_read += bytesRead;
ts = DateTime.Now - begin; ts = DateTime.Now - begin;
if (total_read / ts.TotalSeconds > 1024 * 1000) if (total_read / ts.TotalSeconds > 1024 * 1000)
{ {
await Task.Delay(1); await Task.Delay(1);
} }
} }
} }
} }
} }
public void Dispose() public void Dispose()
{ {
_streamWriter?.Dispose(); _streamWriter?.Dispose();
_fileStream?.Dispose(); _fileStream?.Dispose();
if (File.Exists(filePath)) if (File.Exists(filePath))
{ {
File.Delete(filePath); File.Delete(filePath);
} }
} }
} }
} }

View File

@@ -1,274 +1,274 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Reflection; using System.Reflection;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Globalization; using System.Globalization;
#if !SILVERLIGHT #if !SILVERLIGHT
using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Binary;
#endif #endif
namespace Hncore.Infrastructure.Utils namespace Hncore.Infrastructure.Utils
{ {
/// <summary> /// <summary>
/// Assembly Util Class /// Assembly Util Class
/// </summary> /// </summary>
public static class AssemblyUtil public static class AssemblyUtil
{ {
/// <summary> /// <summary>
/// Creates the instance from type name. /// Creates the instance from type name.
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="type">The type.</param> /// <param name="type">The type.</param>
/// <returns></returns> /// <returns></returns>
public static T CreateInstance<T>(string type) public static T CreateInstance<T>(string type)
{ {
return CreateInstance<T>(type, new object[0]); return CreateInstance<T>(type, new object[0]);
} }
/// <summary> /// <summary>
/// Creates the instance from type name and parameters. /// Creates the instance from type name and parameters.
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="type">The type.</param> /// <param name="type">The type.</param>
/// <param name="parameters">The parameters.</param> /// <param name="parameters">The parameters.</param>
/// <returns></returns> /// <returns></returns>
public static T CreateInstance<T>(string type, object[] parameters) public static T CreateInstance<T>(string type, object[] parameters)
{ {
Type instanceType = null; Type instanceType = null;
var result = default(T); var result = default(T);
instanceType = Type.GetType(type, true); instanceType = Type.GetType(type, true);
if (instanceType == null) if (instanceType == null)
throw new Exception(string.Format("The type '{0}' was not found!", type)); throw new Exception(string.Format("The type '{0}' was not found!", type));
object instance = Activator.CreateInstance(instanceType, parameters); object instance = Activator.CreateInstance(instanceType, parameters);
result = (T)instance; result = (T)instance;
return result; return result;
} }
/// <summary> /// <summary>
/// Gets the type by the full name, also return matched generic type without checking generic type parameters in the name. /// Gets the type by the full name, also return matched generic type without checking generic type parameters in the name.
/// </summary> /// </summary>
/// <param name="fullTypeName">Full name of the type.</param> /// <param name="fullTypeName">Full name of the type.</param>
/// <param name="throwOnError">if set to <c>true</c> [throw on error].</param> /// <param name="throwOnError">if set to <c>true</c> [throw on error].</param>
/// <param name="ignoreCase">if set to <c>true</c> [ignore case].</param> /// <param name="ignoreCase">if set to <c>true</c> [ignore case].</param>
/// <returns></returns> /// <returns></returns>
#if !NET35 #if !NET35
public static Type GetType(string fullTypeName, bool throwOnError, bool ignoreCase) public static Type GetType(string fullTypeName, bool throwOnError, bool ignoreCase)
{ {
var targetType = Type.GetType(fullTypeName, false, ignoreCase); var targetType = Type.GetType(fullTypeName, false, ignoreCase);
if (targetType != null) if (targetType != null)
return targetType; return targetType;
var names = fullTypeName.Split(','); var names = fullTypeName.Split(',');
var assemblyName = names[1].Trim(); var assemblyName = names[1].Trim();
try try
{ {
var assembly = Assembly.Load(assemblyName); var assembly = Assembly.Load(assemblyName);
var typeNamePrefix = names[0].Trim() + "`"; var typeNamePrefix = names[0].Trim() + "`";
var matchedTypes = assembly.GetExportedTypes().Where(t => t.IsGenericType var matchedTypes = assembly.GetExportedTypes().Where(t => t.IsGenericType
&& t.FullName.StartsWith(typeNamePrefix, ignoreCase, CultureInfo.InvariantCulture)).ToArray(); && t.FullName.StartsWith(typeNamePrefix, ignoreCase, CultureInfo.InvariantCulture)).ToArray();
if (matchedTypes.Length != 1) if (matchedTypes.Length != 1)
return null; return null;
return matchedTypes[0]; return matchedTypes[0];
} }
catch (Exception e) catch (Exception e)
{ {
if (throwOnError) if (throwOnError)
throw e; throw e;
return null; return null;
} }
} }
#else #else
public static Type GetType(string fullTypeName, bool throwOnError, bool ignoreCase) public static Type GetType(string fullTypeName, bool throwOnError, bool ignoreCase)
{ {
return Type.GetType(fullTypeName, null, (a, n, ign) => return Type.GetType(fullTypeName, null, (a, n, ign) =>
{ {
var targetType = a.GetType(n, false, ign); var targetType = a.GetType(n, false, ign);
if (targetType != null) if (targetType != null)
return targetType; return targetType;
var typeNamePrefix = n + "`"; var typeNamePrefix = n + "`";
var matchedTypes = a.GetExportedTypes().Where(t => t.IsGenericType var matchedTypes = a.GetExportedTypes().Where(t => t.IsGenericType
&& t.FullName.StartsWith(typeNamePrefix, ign, CultureInfo.InvariantCulture)).ToArray(); && t.FullName.StartsWith(typeNamePrefix, ign, CultureInfo.InvariantCulture)).ToArray();
if (matchedTypes.Length != 1) if (matchedTypes.Length != 1)
return null; return null;
return matchedTypes[0]; return matchedTypes[0];
}, throwOnError, ignoreCase); }, throwOnError, ignoreCase);
} }
#endif #endif
/// <summary> /// <summary>
/// Gets the implement types from assembly. /// Gets the implement types from assembly.
/// </summary> /// </summary>
/// <typeparam name="TBaseType">The type of the base type.</typeparam> /// <typeparam name="TBaseType">The type of the base type.</typeparam>
/// <param name="assembly">The assembly.</param> /// <param name="assembly">The assembly.</param>
/// <returns></returns> /// <returns></returns>
public static IEnumerable<Type> GetImplementTypes<TBaseType>(this Assembly assembly) public static IEnumerable<Type> GetImplementTypes<TBaseType>(this Assembly assembly)
{ {
return assembly.GetExportedTypes().Where(t => return assembly.GetExportedTypes().Where(t =>
t.IsSubclassOf(typeof(TBaseType)) && t.IsClass && !t.IsAbstract); t.IsSubclassOf(typeof(TBaseType)) && t.IsClass && !t.IsAbstract);
} }
/// <summary> /// <summary>
/// Gets the implemented objects by interface. /// Gets the implemented objects by interface.
/// </summary> /// </summary>
/// <typeparam name="TBaseInterface">The type of the base interface.</typeparam> /// <typeparam name="TBaseInterface">The type of the base interface.</typeparam>
/// <param name="assembly">The assembly.</param> /// <param name="assembly">The assembly.</param>
/// <returns></returns> /// <returns></returns>
public static IEnumerable<TBaseInterface> GetImplementedObjectsByInterface<TBaseInterface>(this Assembly assembly) public static IEnumerable<TBaseInterface> GetImplementedObjectsByInterface<TBaseInterface>(this Assembly assembly)
where TBaseInterface : class where TBaseInterface : class
{ {
return GetImplementedObjectsByInterface<TBaseInterface>(assembly, typeof(TBaseInterface)); return GetImplementedObjectsByInterface<TBaseInterface>(assembly, typeof(TBaseInterface));
} }
/// <summary> /// <summary>
/// Gets the implemented objects by interface. /// Gets the implemented objects by interface.
/// </summary> /// </summary>
/// <typeparam name="TBaseInterface">The type of the base interface.</typeparam> /// <typeparam name="TBaseInterface">The type of the base interface.</typeparam>
/// <param name="assembly">The assembly.</param> /// <param name="assembly">The assembly.</param>
/// <param name="targetType">Type of the target.</param> /// <param name="targetType">Type of the target.</param>
/// <returns></returns> /// <returns></returns>
public static IEnumerable<TBaseInterface> GetImplementedObjectsByInterface<TBaseInterface>(this Assembly assembly, Type targetType) public static IEnumerable<TBaseInterface> GetImplementedObjectsByInterface<TBaseInterface>(this Assembly assembly, Type targetType)
where TBaseInterface : class where TBaseInterface : class
{ {
Type[] arrType = assembly.GetExportedTypes(); Type[] arrType = assembly.GetExportedTypes();
var result = new List<TBaseInterface>(); var result = new List<TBaseInterface>();
for (int i = 0; i < arrType.Length; i++) for (int i = 0; i < arrType.Length; i++)
{ {
var currentImplementType = arrType[i]; var currentImplementType = arrType[i];
if (currentImplementType.IsAbstract) if (currentImplementType.IsAbstract)
continue; continue;
if (!targetType.IsAssignableFrom(currentImplementType)) if (!targetType.IsAssignableFrom(currentImplementType))
continue; continue;
result.Add((TBaseInterface)Activator.CreateInstance(currentImplementType)); result.Add((TBaseInterface)Activator.CreateInstance(currentImplementType));
} }
return result; return result;
} }
#if SILVERLIGHT #if SILVERLIGHT
#else #else
/// <summary> /// <summary>
/// Clone object in binary format. /// Clone object in binary format.
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="target">The target.</param> /// <param name="target">The target.</param>
/// <returns></returns> /// <returns></returns>
public static T BinaryClone<T>(this T target) public static T BinaryClone<T>(this T target)
{ {
BinaryFormatter formatter = new BinaryFormatter(); BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream()) using (MemoryStream ms = new MemoryStream())
{ {
formatter.Serialize(ms, target); formatter.Serialize(ms, target);
ms.Position = 0; ms.Position = 0;
return (T)formatter.Deserialize(ms); return (T)formatter.Deserialize(ms);
} }
} }
#endif #endif
/// <summary> /// <summary>
/// Copies the properties of one object to another object. /// Copies the properties of one object to another object.
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param> /// <param name="source">The source.</param>
/// <param name="target">The target.</param> /// <param name="target">The target.</param>
/// <returns></returns> /// <returns></returns>
public static T CopyPropertiesTo<T>(this T source, T target) public static T CopyPropertiesTo<T>(this T source, T target)
{ {
return source.CopyPropertiesTo(p => true, target); return source.CopyPropertiesTo(p => true, target);
} }
/// <summary> /// <summary>
/// Copies the properties of one object to another object. /// Copies the properties of one object to another object.
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param> /// <param name="source">The source.</param>
/// <param name="predict">The properties predict.</param> /// <param name="predict">The properties predict.</param>
/// <param name="target">The target.</param> /// <param name="target">The target.</param>
/// <returns></returns> /// <returns></returns>
public static T CopyPropertiesTo<T>(this T source, Predicate<PropertyInfo> predict, T target) public static T CopyPropertiesTo<T>(this T source, Predicate<PropertyInfo> predict, T target)
{ {
PropertyInfo[] properties = source.GetType() PropertyInfo[] properties = source.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty); .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty);
Dictionary<string, PropertyInfo> sourcePropertiesDict = properties.ToDictionary(p => p.Name); Dictionary<string, PropertyInfo> sourcePropertiesDict = properties.ToDictionary(p => p.Name);
PropertyInfo[] targetProperties = target.GetType() PropertyInfo[] targetProperties = target.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty) .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty)
.Where(p => predict(p)).ToArray(); .Where(p => predict(p)).ToArray();
for (int i = 0; i < targetProperties.Length; i++) for (int i = 0; i < targetProperties.Length; i++)
{ {
var p = targetProperties[i]; var p = targetProperties[i];
PropertyInfo sourceProperty; PropertyInfo sourceProperty;
if (sourcePropertiesDict.TryGetValue(p.Name, out sourceProperty)) if (sourcePropertiesDict.TryGetValue(p.Name, out sourceProperty))
{ {
if (sourceProperty.PropertyType != p.PropertyType) if (sourceProperty.PropertyType != p.PropertyType)
continue; continue;
if (!sourceProperty.PropertyType.IsSerializable) if (!sourceProperty.PropertyType.IsSerializable)
continue; continue;
p.SetValue(target, sourceProperty.GetValue(source, null), null); p.SetValue(target, sourceProperty.GetValue(source, null), null);
} }
} }
return target; return target;
} }
/// <summary> /// <summary>
/// Gets the assemblies from string. /// Gets the assemblies from string.
/// </summary> /// </summary>
/// <param name="assemblyDef">The assembly def.</param> /// <param name="assemblyDef">The assembly def.</param>
/// <returns></returns> /// <returns></returns>
public static IEnumerable<Assembly> GetAssembliesFromString(string assemblyDef) public static IEnumerable<Assembly> GetAssembliesFromString(string assemblyDef)
{ {
return GetAssembliesFromStrings(assemblyDef.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)); return GetAssembliesFromStrings(assemblyDef.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries));
} }
/// <summary> /// <summary>
/// Gets the assemblies from strings. /// Gets the assemblies from strings.
/// </summary> /// </summary>
/// <param name="assemblies">The assemblies.</param> /// <param name="assemblies">The assemblies.</param>
/// <returns></returns> /// <returns></returns>
public static IEnumerable<Assembly> GetAssembliesFromStrings(string[] assemblies) public static IEnumerable<Assembly> GetAssembliesFromStrings(string[] assemblies)
{ {
List<Assembly> result = new List<Assembly>(assemblies.Length); List<Assembly> result = new List<Assembly>(assemblies.Length);
foreach (var a in assemblies) foreach (var a in assemblies)
{ {
result.Add(Assembly.Load(a)); result.Add(Assembly.Load(a));
} }
return result; return result;
} }
public static bool IsImplementedInterface<T, TInterface>() public static bool IsImplementedInterface<T, TInterface>()
{ {
return typeof(TInterface).IsAssignableFrom(typeof(T)); return typeof(TInterface).IsAssignableFrom(typeof(T));
} }
} }
} }

View File

@@ -1,44 +1,44 @@
using System.IO; using System.IO;
using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Binary;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
/// <summary> /// <summary>
/// 二进制序列化 /// 二进制序列化
/// </summary> /// </summary>
public class BinaryHelper public class BinaryHelper
{ {
/// <summary> /// <summary>
/// 序列化对象(二进制) /// 序列化对象(二进制)
/// </summary> /// </summary>
/// <param name="obj">需要序列化的对象</param> /// <param name="obj">需要序列化的对象</param>
public static byte[] Serialize(object obj) public static byte[] Serialize(object obj)
{ {
using (MemoryStream ms = new MemoryStream()) using (MemoryStream ms = new MemoryStream())
{ {
BinaryFormatter binaryFormatter = new BinaryFormatter(); BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(ms, obj); binaryFormatter.Serialize(ms, obj);
return ms.ToArray(); return ms.ToArray();
} }
} }
/// <summary> /// <summary>
/// 反序列化对象(二进制) /// 反序列化对象(二进制)
/// </summary> /// </summary>
/// <param name="bytes">需要反序列化的字符串</param> /// <param name="bytes">需要反序列化的字符串</param>
public static object Deserialize(byte[] bytes) public static object Deserialize(byte[] bytes)
{ {
if (bytes == null) if (bytes == null)
{ {
return null; return null;
} }
using (MemoryStream ms = new MemoryStream()) using (MemoryStream ms = new MemoryStream())
{ {
ms.Write(bytes, 0, bytes.Length); ms.Write(bytes, 0, bytes.Length);
ms.Seek(0, SeekOrigin.Begin); ms.Seek(0, SeekOrigin.Begin);
BinaryFormatter binaryFormatter = new BinaryFormatter(); BinaryFormatter binaryFormatter = new BinaryFormatter();
return binaryFormatter.Deserialize(ms); return binaryFormatter.Deserialize(ms);
} }
} }
} }
} }

View File

@@ -1,55 +1,55 @@
using System; using System;
using System.Linq; using System.Linq;
using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding;
using Hncore.Infrastructure.Data; using Hncore.Infrastructure.Data;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class CheckHelper public class CheckHelper
{ {
public static void NotNull(object obj, string message = "") public static void NotNull(object obj, string message = "")
{ {
if (ReferenceEquals(obj, null)) if (ReferenceEquals(obj, null))
{ {
if (string.IsNullOrEmpty(message)) if (string.IsNullOrEmpty(message))
{ {
message = nameof(obj) + "空引用"; message = nameof(obj) + "空引用";
} }
throw new BusinessException(message); throw new BusinessException(message);
} }
} }
public static void NotEmpty(string obj, string message = "") public static void NotEmpty(string obj, string message = "")
{ {
NotNull(obj,message); NotNull(obj,message);
if (obj.Trim() == "") if (obj.Trim() == "")
{ {
if (string.IsNullOrEmpty(message)) if (string.IsNullOrEmpty(message))
{ {
message = nameof(obj) + "值不能为空"; message = nameof(obj) + "值不能为空";
} }
throw new BusinessException(message); throw new BusinessException(message);
} }
} }
} }
public static class Ext public static class Ext
{ {
public static void Check(this ModelStateDictionary dic) public static void Check(this ModelStateDictionary dic)
{ {
if (!dic.IsValid) if (!dic.IsValid)
{ {
var errs = dic.Values.SelectMany(x => x.Errors); var errs = dic.Values.SelectMany(x => x.Errors);
string msg = ""; string msg = "";
errs.Select(t => t.Exception.Message).ToList().ForEach((s => { msg += s + "\r\n"; })); errs.Select(t => t.Exception.Message).ToList().ForEach((s => { msg += s + "\r\n"; }));
throw new Exception(msg); throw new Exception(msg);
} }
} }
} }
} }

View File

@@ -1,75 +1,75 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Dapper; using Dapper;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class ConcurrentHelper public class ConcurrentHelper
{ {
private static string _connString = ""; private static string _connString = "";
private static string _tableName = "concurrent_helper"; private static string _tableName = "concurrent_helper";
private List<string> _infos = new List<string>(); private List<string> _infos = new List<string>();
private string _id; private string _id;
public static void Init(string mysqlConn) public static void Init(string mysqlConn)
{ {
_connString = mysqlConn; _connString = mysqlConn;
MySqlHelper.Execute(_connString MySqlHelper.Execute(_connString
, $@"create table if not exists {_tableName} , $@"create table if not exists {_tableName}
( (
Id VARCHAR(32) PRIMARY KEY UNIQUE, Id VARCHAR(32) PRIMARY KEY UNIQUE,
CreateTime datetime DEFAULT now(), CreateTime datetime DEFAULT now(),
Info text Info text
)" )"
); );
} }
public ConcurrentHelper AddInfo(string info) public ConcurrentHelper AddInfo(string info)
{ {
_infos.Add(info); _infos.Add(info);
return this; return this;
} }
private async Task<bool> GetAuthority() private async Task<bool> GetAuthority()
{ {
try try
{ {
string info = ListHelper<string>.ListToStr(_infos, "\n"); string info = ListHelper<string>.ListToStr(_infos, "\n");
_id = SecurityHelper.GetMd5Hash(info); _id = SecurityHelper.GetMd5Hash(info);
string sql = $"insert into {_tableName}(Id,Info) values(@Id,@Info)"; string sql = $"insert into {_tableName}(Id,Info) values(@Id,@Info)";
await MySqlHelper.ExecuteAsync(_connString, sql, new {Id = _id, Info = info}); await MySqlHelper.ExecuteAsync(_connString, sql, new {Id = _id, Info = info});
} }
catch catch
{ {
return false; return false;
} }
return true; return true;
} }
public async Task Execute(Action action) public async Task Execute(Action action)
{ {
try try
{ {
if (await GetAuthority()) if (await GetAuthority())
{ {
action(); action();
} }
} }
catch (Exception e) catch (Exception e)
{ {
await MySqlHelper.ExecuteAsync(_connString, $"DELETE FROM {_tableName} where Id='{_id}'"); await MySqlHelper.ExecuteAsync(_connString, $"DELETE FROM {_tableName} where Id='{_id}'");
throw e; throw e;
} }
} }
} }
} }

View File

@@ -1,102 +1,102 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
/// <summary> /// <summary>
/// 文件类型 /// 文件类型
/// </summary> /// </summary>
public class ContentTypeHelper public class ContentTypeHelper
{ {
/// <summary> /// <summary>
/// 图片格式 /// 图片格式
/// </summary> /// </summary>
public static List<string> ImageList = new List<string>() public static List<string> ImageList = new List<string>()
{ {
"image/jpeg", "image/jpeg",
"application/x-jpe", "application/x-jpe",
"application/x-jpg", "application/x-jpg",
"application/x-bmp", "application/x-bmp",
"image/png", "image/png",
"application/x-png", "application/x-png",
"image/gif" "image/gif"
}; };
/// <summary> /// <summary>
/// 视频格式 /// 视频格式
/// </summary> /// </summary>
public static List<string> VideoList = new List<string>() public static List<string> VideoList = new List<string>()
{ {
"video/mpeg4", "video/mpeg4",
"video/avi", "video/avi",
"video/x-ms-wmv", "video/x-ms-wmv",
"video/x-mpeg", "video/x-mpeg",
"video/mpeg4", "video/mpeg4",
"video/x-sgi-movie", "video/x-sgi-movie",
"application/vnd.rn-realmedia", "application/vnd.rn-realmedia",
"application/x-shockwave-flash", "application/x-shockwave-flash",
"application/vnd.rn-realmedia-vbr", "application/vnd.rn-realmedia-vbr",
"application/octet-stream", "application/octet-stream",
"flv-application/octet-stream", "flv-application/octet-stream",
"video/mpg", "video/mpg",
"video/mpeg", "video/mpeg",
"video/mp4", "video/mp4",
"video/x-msvideo" "video/x-msvideo"
}; };
#region #region
/// <summary> /// <summary>
/// 得到文件类型 /// 得到文件类型
/// </summary> /// </summary>
/// <param name="contentType">文件类型</param> /// <param name="contentType">文件类型</param>
/// <returns></returns> /// <returns></returns>
public static FileTypeEnum GetFileType(string contentType) public static FileTypeEnum GetFileType(string contentType)
{ {
if (ImageList.Contains(contentType)) if (ImageList.Contains(contentType))
{ {
return FileTypeEnum.Img; return FileTypeEnum.Img;
} }
if (VideoList.Contains(contentType)) if (VideoList.Contains(contentType))
{ {
return FileTypeEnum.Video; return FileTypeEnum.Video;
} }
return FileTypeEnum.Unknow; return FileTypeEnum.Unknow;
} }
#endregion #endregion
} }
/// <summary> /// <summary>
/// 文件类型 /// 文件类型
/// </summary> /// </summary>
public enum FileTypeEnum public enum FileTypeEnum
{ {
/// <summary> /// <summary>
/// 未知 /// 未知
/// </summary> /// </summary>
[Description("未知")] Unknow = 0, [Description("未知")] Unknow = 0,
/// <summary> /// <summary>
/// 图片 /// 图片
/// </summary> /// </summary>
[Description("图片")] Img = 1, [Description("图片")] Img = 1,
/// <summary> /// <summary>
/// 音频 /// 音频
/// </summary> /// </summary>
[Description("音频")] Audio = 2, [Description("音频")] Audio = 2,
/// <summary> /// <summary>
/// 视频 /// 视频
/// </summary> /// </summary>
[Description("视频")] Video = 3, [Description("视频")] Video = 3,
/// <summary> /// <summary>
/// 其他 /// 其他
/// </summary> /// </summary>
[Description("其他")] Other = 4 [Description("其他")] Other = 4
} }
} }

View File

@@ -1,80 +1,80 @@
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class DateTimeHelper public class DateTimeHelper
{ {
public static DateTime SqlMinTime => Convert.ToDateTime("1975-01-01 00:00:00"); public static DateTime SqlMinTime => Convert.ToDateTime("1975-01-01 00:00:00");
public static DateTime SqlMaxTime => Convert.ToDateTime("9999-12-31 23:59:59"); public static DateTime SqlMaxTime => Convert.ToDateTime("9999-12-31 23:59:59");
/// <summary> /// <summary>
/// 将10位时间戳转时间 /// 将10位时间戳转时间
/// </summary> /// </summary>
/// <param name="unixTimeStamp"></param> /// <param name="unixTimeStamp"></param>
/// <returns></returns> /// <returns></returns>
public static DateTime UnixTimeStampToDateTime(long unixTimeStamp) public static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
{ {
// Unix timestamp is seconds past epoch // Unix timestamp is seconds past epoch
DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime(); dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
return dtDateTime; return dtDateTime;
} }
public static long ToUnixTimestamp(DateTime target) public static long ToUnixTimestamp(DateTime target)
{ {
return Convert.ToInt64((TimeZoneInfo.ConvertTimeToUtc(target) - return Convert.ToInt64((TimeZoneInfo.ConvertTimeToUtc(target) -
new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds); new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds);
} }
/// <summary> /// <summary>
/// 将13位时间戳转为时间 /// 将13位时间戳转为时间
/// </summary> /// </summary>
/// <param name="javaTimeStamp"></param> /// <param name="javaTimeStamp"></param>
/// <returns></returns> /// <returns></returns>
public static DateTime JsTimeStampToDateTime(double javaTimeStamp) public static DateTime JsTimeStampToDateTime(double javaTimeStamp)
{ {
var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dtDateTime = dtDateTime.AddMilliseconds(javaTimeStamp).ToLocalTime(); dtDateTime = dtDateTime.AddMilliseconds(javaTimeStamp).ToLocalTime();
return dtDateTime; return dtDateTime;
} }
/// <summary> /// <summary>
/// 获取时间戳 /// 获取时间戳
/// </summary> /// </summary>
/// <param name="target"></param> /// <param name="target"></param>
/// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳</param> /// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳</param>
/// <returns></returns> /// <returns></returns>
public static long ToUnixTime(DateTime target, bool bflag = false) public static long ToUnixTime(DateTime target, bool bflag = false)
{ {
TimeSpan ts = target - new DateTime(1970, 1, 1, 0, 0, 0, 0); TimeSpan ts = target - new DateTime(1970, 1, 1, 0, 0, 0, 0);
long timer = 0; long timer = 0;
timer = Convert.ToInt64(!bflag ? ts.TotalSeconds : ts.TotalMilliseconds); timer = Convert.ToInt64(!bflag ? ts.TotalSeconds : ts.TotalMilliseconds);
return timer; return timer;
} }
public static TimeZoneInfo GetCstTimeZoneInfo() public static TimeZoneInfo GetCstTimeZoneInfo()
{ {
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{ {
return TimeZoneInfo.FindSystemTimeZoneById("Asia/Shanghai"); return TimeZoneInfo.FindSystemTimeZoneById("Asia/Shanghai");
} }
return TimeZoneInfo.FindSystemTimeZoneById("China Standard Time"); return TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");
} }
public static bool IsSameDayOrLess(DateTime dt1, DateTime dt2) public static bool IsSameDayOrLess(DateTime dt1, DateTime dt2)
{ {
return dt1.Year == dt2.Year return dt1.Year == dt2.Year
&& dt1.Month == dt2.Month && dt1.Month == dt2.Month
&& dt1.Day == dt2.Day && dt1.Day == dt2.Day
|| dt1 < dt2; || dt1 < dt2;
} }
public static DateTime GetDatePart(DateTime dt) public static DateTime GetDatePart(DateTime dt)
{ {
return new DateTime(dt.Year, dt.Month, dt.Day); return new DateTime(dt.Year, dt.Month, dt.Day);
} }
} }
} }

View File

@@ -1,28 +1,28 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Text; using System.Text;
namespace Hncore.Infrastructure.Utils namespace Hncore.Infrastructure.Utils
{ {
public static class DebugClass public static class DebugClass
{ {
public static string PrintStack(bool isOutToDebugWin) public static string PrintStack(bool isOutToDebugWin)
{ {
StackFrame[] stacks = new StackTrace().GetFrames(); StackFrame[] stacks = new StackTrace().GetFrames();
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
foreach (StackFrame stack in stacks) foreach (StackFrame stack in stacks)
{ {
result.AppendFormat("{0} {1} {2} {3}{4}", result.AppendFormat("{0} {1} {2} {3}{4}",
stack.GetFileName(), stack.GetFileName(),
stack.GetFileLineNumber(), stack.GetFileLineNumber(),
stack.GetFileColumnNumber(), stack.GetFileColumnNumber(),
stack.GetMethod().ToString(), stack.GetMethod().ToString(),
Environment.NewLine Environment.NewLine
); );
} }
if (isOutToDebugWin) if (isOutToDebugWin)
Debug.WriteLine(result); Debug.WriteLine(result);
return result.ToString(); return result.ToString();
} }
} }
} }

View File

@@ -1,151 +1,151 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Hncore.Infrastructure.Serializer; using Hncore.Infrastructure.Serializer;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
namespace Hncore.Infrastructure.Common.DingTalk namespace Hncore.Infrastructure.Common.DingTalk
{ {
public class DingTalkHelper public class DingTalkHelper
{ {
private static HttpClient _httpClient = new HttpClient(new HttpClientHandler() {UseProxy = false}) private static HttpClient _httpClient = new HttpClient(new HttpClientHandler() {UseProxy = false})
{Timeout = TimeSpan.FromMinutes(1)}; {Timeout = TimeSpan.FromMinutes(1)};
static DingTalkHelper() static DingTalkHelper()
{ {
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
} }
public static Task SendMessage(object message) public static Task SendMessage(object message)
{ {
return null; return null;
// return _httpClient.PostAsync("https://oapi.dingtalk.com/robot/send?access_token=33", JsonContent(message)); // return _httpClient.PostAsync("https://oapi.dingtalk.com/robot/send?access_token=33", JsonContent(message));
} }
private static StringContent JsonContent(object obj) private static StringContent JsonContent(object obj)
{ {
return new StringContent(obj.ToJson(), Encoding.UTF8, "application/json"); return new StringContent(obj.ToJson(), Encoding.UTF8, "application/json");
} }
private static async Task<bool> CheckSuccess(HttpResponseMessage res) private static async Task<bool> CheckSuccess(HttpResponseMessage res)
{ {
var content = await res.Content.ReadAsStringAsync(); var content = await res.Content.ReadAsStringAsync();
JObject jObject = JsonConvert.DeserializeObject<JObject>(content); JObject jObject = JsonConvert.DeserializeObject<JObject>(content);
if (jObject["errmsg"].ToString() == "ok" && Convert.ToInt32(jObject["errcode"]) != 0) if (jObject["errmsg"].ToString() == "ok" && Convert.ToInt32(jObject["errcode"]) != 0)
{ {
return false; return false;
} }
return true; return true;
} }
} }
/// <summary> /// <summary>
/// 此消息类型为固定text /// 此消息类型为固定text
/// </summary> /// </summary>
public class TextModel public class TextModel
{ {
/// <summary> /// <summary>
/// 此消息类型为固定text /// 此消息类型为固定text
/// </summary> /// </summary>
public string msgtype => "text"; public string msgtype => "text";
/// <summary> /// <summary>
/// 消息内容 /// 消息内容
/// </summary> /// </summary>
public text text { get; set; } public text text { get; set; }
/// <summary> /// <summary>
/// @人 /// @人
/// </summary> /// </summary>
public atText at { get; set; } public atText at { get; set; }
} }
/// <summary> /// <summary>
/// 消息内容 /// 消息内容
/// </summary> /// </summary>
public class text public class text
{ {
/// <summary> /// <summary>
/// 消息内容 /// 消息内容
/// </summary> /// </summary>
public string content { get; set; } public string content { get; set; }
} }
/// <summary> /// <summary>
/// @人 /// @人
/// </summary> /// </summary>
public class atText public class atText
{ {
/// <summary> /// <summary>
/// 被@人的手机号 /// 被@人的手机号
/// </summary> /// </summary>
public List<string> atMobiles { get; set; } public List<string> atMobiles { get; set; }
/// <summary> /// <summary>
/// @所有人时:true,否则为:false /// @所有人时:true,否则为:false
/// </summary> /// </summary>
public bool isAtAll { get; set; } = false; public bool isAtAll { get; set; } = false;
} }
/// <summary> /// <summary>
/// 此消息类型为固定markdown /// 此消息类型为固定markdown
/// </summary> /// </summary>
public class MarkDownModel public class MarkDownModel
{ {
/// <summary> /// <summary>
/// 此消息类型为固定markdown /// 此消息类型为固定markdown
/// </summary> /// </summary>
public string msgtype => "markdown"; public string msgtype => "markdown";
/// <summary> /// <summary>
/// 消息内容 /// 消息内容
/// </summary> /// </summary>
public markdown markdown { get; set; } public markdown markdown { get; set; }
/// <summary> /// <summary>
/// @人 /// @人
/// </summary> /// </summary>
public atMarkdown at { get; set; } public atMarkdown at { get; set; }
} }
/// <summary> /// <summary>
/// 消息内容 /// 消息内容
/// </summary> /// </summary>
public class markdown public class markdown
{ {
/// <summary> /// <summary>
/// 标题 /// 标题
/// </summary> /// </summary>
public string title { get; set; } public string title { get; set; }
/// <summary> /// <summary>
/// 消息内容 /// 消息内容
/// </summary> /// </summary>
public string text { get; set; } public string text { get; set; }
} }
/// <summary> /// <summary>
/// @人 /// @人
/// </summary> /// </summary>
public class atMarkdown public class atMarkdown
{ {
/// <summary> /// <summary>
/// 被@人的手机号 /// 被@人的手机号
/// </summary> /// </summary>
public List<string> atMobiles { get; set; } public List<string> atMobiles { get; set; }
/// <summary> /// <summary>
/// @所有人时:true,否则为:false /// @所有人时:true,否则为:false
/// </summary> /// </summary>
public bool isAtAll { get; set; } = false; public bool isAtAll { get; set; } = false;
} }
} }

View File

@@ -1,14 +1,14 @@
using System; using System;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class EnvironmentVariableHelper public class EnvironmentVariableHelper
{ {
/// <summary> /// <summary>
/// 当前环境是否为生产模式 /// 当前环境是否为生产模式
/// </summary> /// </summary>
public static bool IsAspNetCoreProduction => Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production"; public static bool IsAspNetCoreProduction => Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production";
public static string HostName => Environment.GetEnvironmentVariable("HOSTNAME"); public static string HostName => Environment.GetEnvironmentVariable("HOSTNAME");
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,69 +1,69 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Text; using System.Text;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public static class HttpHelp public static class HttpHelp
{ {
/// <summary> /// <summary>
/// get请求 /// get请求
/// </summary> /// </summary>
/// <param name="url"></param> /// <param name="url"></param>
/// <returns></returns> /// <returns></returns>
public static string HttpGet(string url) public static string HttpGet(string url)
{ {
string result = string.Empty; string result = string.Empty;
try try
{ {
HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url); HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
wbRequest.Method = "GET"; wbRequest.Method = "GET";
HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse(); HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
using (Stream responseStream = wbResponse.GetResponseStream()) using (Stream responseStream = wbResponse.GetResponseStream())
{ {
using (StreamReader sReader = new StreamReader(responseStream)) using (StreamReader sReader = new StreamReader(responseStream))
{ {
result = sReader.ReadToEnd(); result = sReader.ReadToEnd();
} }
} }
} }
catch/* (Exception ex) 此处暂时屏蔽掉了,要不然编译光弹出变量未使用的警告,谁用得着再打开*/ catch/* (Exception ex) 此处暂时屏蔽掉了,要不然编译光弹出变量未使用的警告,谁用得着再打开*/
{ {
} }
return result; return result;
} }
/// <summary> /// <summary>
/// get 请求带token /// get 请求带token
/// </summary> /// </summary>
/// <param name="token"></param> /// <param name="token"></param>
/// <param name="url"></param> /// <param name="url"></param>
/// <returns></returns> /// <returns></returns>
public static string HttpGet(string token,string url) public static string HttpGet(string token,string url)
{ {
string result = string.Empty; string result = string.Empty;
try try
{ {
HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url); HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
wbRequest.Headers.Add("token", token); wbRequest.Headers.Add("token", token);
wbRequest.Method = "GET"; wbRequest.Method = "GET";
HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse(); HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
using (Stream responseStream = wbResponse.GetResponseStream()) using (Stream responseStream = wbResponse.GetResponseStream())
{ {
using (StreamReader sReader = new StreamReader(responseStream)) using (StreamReader sReader = new StreamReader(responseStream))
{ {
result = sReader.ReadToEnd(); result = sReader.ReadToEnd();
} }
} }
} }
catch/* (Exception ex) 此处暂时屏蔽掉了,要不然编译光弹出变量未使用的警告,谁用得着再打开*/ catch/* (Exception ex) 此处暂时屏蔽掉了,要不然编译光弹出变量未使用的警告,谁用得着再打开*/
{ {
} }
return result; return result;
} }
} }
} }

View File

@@ -1,85 +1,85 @@
using System; using System;
using System.IO; using System.IO;
using Qiniu.Storage; using Qiniu.Storage;
using Qiniu.Util; using Qiniu.Util;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class ImageCloudHelper public class ImageCloudHelper
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="bytes"></param> /// <param name="bytes"></param>
/// <returns>图片地址</returns> /// <returns>图片地址</returns>
public static string UploadImage(Stream stream, string prefix) public static string UploadImage(Stream stream, string prefix)
{ {
//todo //todo
return ""; return "";
Mac mac = new Mac("3bmkJLD-inSGpQnLr_9UlommFT81B5L0ryesJLhS", "X22vza-l53jcZyi_fmaex88R065_Ip2_3j5Im0Se"); Mac mac = new Mac("3bmkJLD-inSGpQnLr_9UlommFT81B5L0ryesJLhS", "X22vza-l53jcZyi_fmaex88R065_Ip2_3j5Im0Se");
string bucket = "property"; string bucket = "property";
// 上传策略,参见 // 上传策略,参见
// https://developer.qiniu.com/kodo/manual/put-policy // https://developer.qiniu.com/kodo/manual/put-policy
PutPolicy putPolicy = new PutPolicy(); PutPolicy putPolicy = new PutPolicy();
// 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY"
// putPolicy.Scope = bucket + ":" + saveKey; // putPolicy.Scope = bucket + ":" + saveKey;
putPolicy.Scope = bucket; putPolicy.Scope = bucket;
// 上传策略有效期(对应于生成的凭证的有效期) // 上传策略有效期(对应于生成的凭证的有效期)
putPolicy.SetExpires(3600); putPolicy.SetExpires(3600);
string jstr = putPolicy.ToJsonString(); string jstr = putPolicy.ToJsonString();
string token = Auth.CreateUploadToken(mac, jstr); string token = Auth.CreateUploadToken(mac, jstr);
FormUploader fu = new FormUploader(new Config() FormUploader fu = new FormUploader(new Config()
{ {
Zone = Zone.ZONE_CN_East Zone = Zone.ZONE_CN_East
}); });
string fileName = prefix + Guid.NewGuid() + ".jpg"; string fileName = prefix + Guid.NewGuid() + ".jpg";
var result = fu.UploadStream(stream, fileName, token, null); var result = fu.UploadStream(stream, fileName, token, null);
if (result.Code == 200) if (result.Code == 200)
{ {
return "http://propertyimages.etor.vip/" + fileName; return "http://propertyimages.etor.vip/" + fileName;
} }
return null; return null;
} }
public static string UploadImage(string imageBase64, string prefix) public static string UploadImage(string imageBase64, string prefix)
{ {
byte[] imageByte = Convert.FromBase64String(imageBase64); byte[] imageByte = Convert.FromBase64String(imageBase64);
var stream = new MemoryStream(imageByte); var stream = new MemoryStream(imageByte);
return UploadImage(stream, prefix); return UploadImage(stream, prefix);
} }
public static string GetToken(int expireInSeconds=3600) public static string GetToken(int expireInSeconds=3600)
{ {
Mac mac = new Mac("3bmkJLD-inSGpQnLr_9UlommFT81B5L0ryesJLhS", "X22vza-l53jcZyi_fmaex88R065_Ip2_3j5Im0Se"); Mac mac = new Mac("3bmkJLD-inSGpQnLr_9UlommFT81B5L0ryesJLhS", "X22vza-l53jcZyi_fmaex88R065_Ip2_3j5Im0Se");
string bucket = "property"; string bucket = "property";
// 上传策略,参见 // 上传策略,参见
// https://developer.qiniu.com/kodo/manual/put-policy // https://developer.qiniu.com/kodo/manual/put-policy
PutPolicy putPolicy = new PutPolicy(); PutPolicy putPolicy = new PutPolicy();
// 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY"
// putPolicy.Scope = bucket + ":" + saveKey; // putPolicy.Scope = bucket + ":" + saveKey;
putPolicy.Scope = bucket; putPolicy.Scope = bucket;
// 上传策略有效期(对应于生成的凭证的有效期) // 上传策略有效期(对应于生成的凭证的有效期)
putPolicy.SetExpires(expireInSeconds); putPolicy.SetExpires(expireInSeconds);
putPolicy.ReturnBody = "{\"key\":$(key),\"hash\":$(etag),\"mimeType\":$(mimeType),\"fname\":$(fname),\"fsize\":$(fsize),\"avinfo\":$(avinfo),\"ext\":$(ext),\"imageInfo\":$(imageInfo)}"; putPolicy.ReturnBody = "{\"key\":$(key),\"hash\":$(etag),\"mimeType\":$(mimeType),\"fname\":$(fname),\"fsize\":$(fsize),\"avinfo\":$(avinfo),\"ext\":$(ext),\"imageInfo\":$(imageInfo)}";
string jstr = putPolicy.ToJsonString(); string jstr = putPolicy.ToJsonString();
string token = Auth.CreateUploadToken(mac, jstr); string token = Auth.CreateUploadToken(mac, jstr);
return token; return token;
} }
} }
} }

View File

@@ -1,40 +1,40 @@
using System.IO; using System.IO;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public static class IoHelper public static class IoHelper
{ {
#region #region
/// <summary> /// <summary>
/// 数据流转字节数组 /// 数据流转字节数组
/// </summary> /// </summary>
/// <param name="stream"></param> /// <param name="stream"></param>
/// <returns></returns> /// <returns></returns>
public static byte[] StreamToBytes(this Stream stream) public static byte[] StreamToBytes(this Stream stream)
{ {
byte[] bytes = new byte[stream.Length]; byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length); stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始 // 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin); stream.Seek(0, SeekOrigin.Begin);
return bytes; return bytes;
} }
#endregion #endregion
#region byte[] Stream #region byte[] Stream
public static Stream BytesToStream(this byte[] bytes) public static Stream BytesToStream(this byte[] bytes)
{ {
Stream stream = new MemoryStream(bytes); Stream stream = new MemoryStream(bytes);
return stream; return stream;
} }
#endregion #endregion
} }
} }

View File

@@ -1,138 +1,138 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public static class ListHelper<T> public static class ListHelper<T>
{ {
#region #region
/// <summary> /// <summary>
/// 字符串转化为泛型集合 /// 字符串转化为泛型集合
/// </summary> /// </summary>
/// <param name="str">字符串</param> /// <param name="str">字符串</param>
/// <param name="splitstr">要分割的字符</param> /// <param name="splitstr">要分割的字符</param>
/// <returns></returns> /// <returns></returns>
public static List<T> StrToList(string str, char splitstr) public static List<T> StrToList(string str, char splitstr)
{ {
List<T> list = new List<T>(); List<T> list = new List<T>();
if (string.IsNullOrEmpty(str)) if (string.IsNullOrEmpty(str))
{ {
return list; return list;
} }
if (!str.Contains(splitstr)) if (!str.Contains(splitstr))
{ {
list.Add((T)Convert.ChangeType(str, typeof(T))); list.Add((T)Convert.ChangeType(str, typeof(T)));
return list; return list;
} }
else else
{ {
string[] strarray = str.Split(splitstr); string[] strarray = str.Split(splitstr);
foreach (string s in strarray) foreach (string s in strarray)
{ {
if (s != "") if (s != "")
list.Add((T)Convert.ChangeType(s, typeof(T))); list.Add((T)Convert.ChangeType(s, typeof(T)));
} }
return list; return list;
} }
} }
/// <summary> /// <summary>
/// 字符串转化为泛型集合 /// 字符串转化为泛型集合
/// </summary> /// </summary>
/// <param name="str">字符串</param> /// <param name="str">字符串</param>
/// <returns></returns> /// <returns></returns>
public static List<T> StrToList(string str) public static List<T> StrToList(string str)
{ {
return StrToList(str, ','); return StrToList(str, ',');
} }
#endregion #endregion
public static string ListToStr(List<T> list, string splitstr=",") public static string ListToStr(List<T> list, string splitstr=",")
{ {
string str = ""; string str = "";
list.ForEach(t => list.ForEach(t =>
{ {
str += t + splitstr; str += t + splitstr;
}); });
if (str.EndsWith(splitstr)) if (str.EndsWith(splitstr))
{ {
str = str.Substring(0, str.Length - splitstr.Length); str = str.Substring(0, str.Length - splitstr.Length);
} }
return str; return str;
} }
#region #region
/// <summary> /// <summary>
/// 转换几个中所有元素的类型 /// 转换几个中所有元素的类型
/// </summary> /// </summary>
/// <typeparam name="To"></typeparam> /// <typeparam name="To"></typeparam>
/// <param name="list"></param> /// <param name="list"></param>
/// <returns></returns> /// <returns></returns>
public static List<To> ConvertListType<To>(List<T> list) public static List<To> ConvertListType<To>(List<T> list)
{ {
if (list == null) if (list == null)
{ {
return null; return null;
} }
List<To> newlist = new List<To>(); List<To> newlist = new List<To>();
foreach (T t in list) foreach (T t in list)
{ {
object to = new object(); object to = new object();
if (typeof(To).Name == "Guid") if (typeof(To).Name == "Guid")
{ {
to = Guid.Parse(t.ToString()); to = Guid.Parse(t.ToString());
} }
else else
{ {
to = Convert.ChangeType(t, typeof(To)); to = Convert.ChangeType(t, typeof(To));
} }
newlist.Add((To)to); newlist.Add((To)to);
} }
return newlist; return newlist;
} }
#endregion #endregion
#region DataTable #region DataTable
/// <summary> /// <summary>
/// 转化一个DataTable /// 转化一个DataTable
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="list"></param> /// <param name="list"></param>
/// <returns></returns> /// <returns></returns>
public static DataTable ToDataTable(IEnumerable<T> list) public static DataTable ToDataTable(IEnumerable<T> list)
{ {
//创建属性的集合 //创建属性的集合
List<PropertyInfo> pList = new List<PropertyInfo>(); List<PropertyInfo> pList = new List<PropertyInfo>();
//获得反射的入口 //获得反射的入口
Type type = typeof(T); Type type = typeof(T);
DataTable dt = new DataTable(); DataTable dt = new DataTable();
//把所有的public属性加入到集合 并添加DataTable的列 //把所有的public属性加入到集合 并添加DataTable的列
Array.ForEach(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); }); Array.ForEach(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
foreach (var item in list) foreach (var item in list)
{ {
//创建一个DataRow实例 //创建一个DataRow实例
DataRow row = dt.NewRow(); DataRow row = dt.NewRow();
//给row 赋值 //给row 赋值
pList.ForEach(p => row[p.Name] = p.GetValue(item, null)); pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
//加入到DataTable //加入到DataTable
dt.Rows.Add(row); dt.Rows.Add(row);
} }
return dt; return dt;
} }
#endregion #endregion
} }
} }

View File

@@ -1,59 +1,59 @@
using System; using System;
using NLog; using NLog;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class LogHelper public class LogHelper
{ {
private static readonly Logger Log = LogManager.GetLogger("UserLog"); private static readonly Logger Log = LogManager.GetLogger("UserLog");
private static string assName = AppDomain.CurrentDomain.FriendlyName; private static string assName = AppDomain.CurrentDomain.FriendlyName;
private static string FormatMsg(string title, object msg) private static string FormatMsg(string title, object msg)
{ {
return "Assembly" + assName + "\r\nTitle : " + title + "\r\nMessage : " + msg + "\r\n"; return "Assembly" + assName + "\r\nTitle : " + title + "\r\nMessage : " + msg + "\r\n";
} }
public static void Error(string title, object msg = null) public static void Error(string title, object msg = null)
{ {
Log?.Error(FormatMsg(title, msg)); Log?.Error(FormatMsg(title, msg));
Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg));
} }
public static void Debug(string title, object msg = null) public static void Debug(string title, object msg = null)
{ {
Log?.Debug(FormatMsg(title, msg)); Log?.Debug(FormatMsg(title, msg));
Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg));
} }
public static void Info(string title, object msg = null) public static void Info(string title, object msg = null)
{ {
Log?.Info(FormatMsg(title, msg)); Log?.Info(FormatMsg(title, msg));
Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg));
} }
public static void Warn(string title, object msg = null) public static void Warn(string title, object msg = null)
{ {
Log?.Warn(FormatMsg(title, msg)); Log?.Warn(FormatMsg(title, msg));
Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg));
} }
public static void Trace(string title, object msg = null) public static void Trace(string title, object msg = null)
{ {
Log?.Trace(FormatMsg(title, msg)); Log?.Trace(FormatMsg(title, msg));
Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg));
} }
public static void Fatal(string title, object msg = null) public static void Fatal(string title, object msg = null)
{ {
Log?.Fatal(FormatMsg(title, msg)); Log?.Fatal(FormatMsg(title, msg));
Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg));
} }
} }
} }

View File

@@ -1,29 +1,29 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Dapper; using Dapper;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class MySqlHelper public class MySqlHelper
{ {
public static int Execute(string connStr, string sql, object param = null) public static int Execute(string connStr, string sql, object param = null)
{ {
using (var conn = new MySqlConnection(connStr)) using (var conn = new MySqlConnection(connStr))
{ {
conn.Open(); conn.Open();
return conn.Execute(sql, param); return conn.Execute(sql, param);
} }
} }
public static async Task<int> ExecuteAsync(string connStr, string sql, object param = null) public static async Task<int> ExecuteAsync(string connStr, string sql, object param = null)
{ {
using (var conn = new MySqlConnection(connStr)) using (var conn = new MySqlConnection(connStr))
{ {
conn.Open(); conn.Open();
return await conn.ExecuteAsync(sql, param); return await conn.ExecuteAsync(sql, param);
} }
} }
} }
} }

View File

@@ -1,21 +1,21 @@
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.NetworkInformation; using System.Net.NetworkInformation;
using System.Net.Sockets; using System.Net.Sockets;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class NetworkHelper public class NetworkHelper
{ {
public static string GetPublicIp() public static string GetPublicIp()
{ {
return NetworkInterface return NetworkInterface
.GetAllNetworkInterfaces() .GetAllNetworkInterfaces()
.Select(p => p.GetIPProperties()) .Select(p => p.GetIPProperties())
.SelectMany(p => p.UnicastAddresses) .SelectMany(p => p.UnicastAddresses)
.FirstOrDefault(p => .FirstOrDefault(p =>
p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address))?.Address p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address))?.Address
.ToString(); .ToString();
} }
} }
} }

View File

@@ -1,119 +1,119 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using Hncore.Infrastructure.Extension; using Hncore.Infrastructure.Extension;
using Qiniu.Http; using Qiniu.Http;
using Qiniu.Storage; using Qiniu.Storage;
using Qiniu.Util; using Qiniu.Util;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class QiNiuCloudHelper public class QiNiuCloudHelper
{ {
static Mac mac = new Mac("3bmkJLD-inSGpQnLr_9UlommFT81B5L0ryesJLhS", static Mac mac = new Mac("3bmkJLD-inSGpQnLr_9UlommFT81B5L0ryesJLhS",
"X22vza-l53jcZyi_fmaex88R065_Ip2_3j5Im0Se"); "X22vza-l53jcZyi_fmaex88R065_Ip2_3j5Im0Se");
static string bucket = "property"; static string bucket = "property";
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="bytes"></param> /// <param name="bytes"></param>
/// <returns>图片地址</returns> /// <returns>图片地址</returns>
public static string UploadImage(Stream stream, string prefix, string persistentOps = "") public static string UploadImage(Stream stream, string prefix, string persistentOps = "")
{ {
string fileName = prefix + Guid.NewGuid() + ".jpg"; string fileName = prefix + Guid.NewGuid() + ".jpg";
// 上传策略,参见 // 上传策略,参见
// https://developer.qiniu.com/kodo/manual/put-policy // https://developer.qiniu.com/kodo/manual/put-policy
PutPolicy putPolicy = new PutPolicy(); PutPolicy putPolicy = new PutPolicy();
// 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY"
// putPolicy.Scope = bucket + ":" + saveKey; // putPolicy.Scope = bucket + ":" + saveKey;
putPolicy.Scope = bucket; putPolicy.Scope = bucket;
// 上传策略有效期(对应于生成的凭证的有效期) // 上传策略有效期(对应于生成的凭证的有效期)
putPolicy.SetExpires(3600); putPolicy.SetExpires(3600);
if (!string.IsNullOrEmpty(persistentOps)) if (!string.IsNullOrEmpty(persistentOps))
{ {
string saveAs = (bucket + ":" + fileName).ToBase64String() string saveAs = (bucket + ":" + fileName).ToBase64String()
.Replace("+", "-") .Replace("+", "-")
.Replace("/", "_"); .Replace("/", "_");
putPolicy.PersistentOps = persistentOps + $"|saveas/{saveAs}"; putPolicy.PersistentOps = persistentOps + $"|saveas/{saveAs}";
putPolicy.PersistentPipeline = "face_image"; putPolicy.PersistentPipeline = "face_image";
} }
string jstr = putPolicy.ToJsonString(); string jstr = putPolicy.ToJsonString();
string token = Auth.CreateUploadToken(mac, jstr); string token = Auth.CreateUploadToken(mac, jstr);
ResumableUploader fu = new ResumableUploader(new Config() ResumableUploader fu = new ResumableUploader(new Config()
{ {
Zone = Zone.ZONE_CN_East Zone = Zone.ZONE_CN_East
}); });
var result = fu.UploadStream(stream, fileName, token, null); var result = fu.UploadStream(stream, fileName, token, null);
if (result.Code == 200) if (result.Code == 200)
{ {
return "http://propertyimages.etor.vip/" + fileName; return "http://propertyimages.etor.vip/" + fileName;
} }
LogHelper.Error("七牛上传图片失败", result.ToString()); LogHelper.Error("七牛上传图片失败", result.ToString());
return null; return null;
} }
public static string UploadImage(string imageBase64, string prefix, string persistentOps = "") public static string UploadImage(string imageBase64, string prefix, string persistentOps = "")
{ {
byte[] imageByte = Convert.FromBase64String(imageBase64); byte[] imageByte = Convert.FromBase64String(imageBase64);
var stream = new MemoryStream(imageByte); var stream = new MemoryStream(imageByte);
return UploadImage(stream, prefix, persistentOps); return UploadImage(stream, prefix, persistentOps);
} }
/// <summary> /// <summary>
/// 删除资源 /// 删除资源
/// </summary> /// </summary>
/// <param name="key"></param> /// <param name="key"></param>
public static void Delete(string key) public static void Delete(string key)
{ {
Config config = new Config(); Config config = new Config();
config.Zone = Zone.ZONE_CN_East; config.Zone = Zone.ZONE_CN_East;
BucketManager bucketManager = new BucketManager(mac, config); BucketManager bucketManager = new BucketManager(mac, config);
var res = bucketManager.Delete(bucket, key); var res = bucketManager.Delete(bucket, key);
} }
public static List<string> Domains(string bucket) public static List<string> Domains(string bucket)
{ {
Config config = new Config(); Config config = new Config();
config.Zone = Zone.ZONE_CN_East; config.Zone = Zone.ZONE_CN_East;
BucketManager bucketManager = new BucketManager(mac, config); BucketManager bucketManager = new BucketManager(mac, config);
return bucketManager.Domains("property").Result; return bucketManager.Domains("property").Result;
} }
public static string GetToken(int expireInSeconds = 3600) public static string GetToken(int expireInSeconds = 3600)
{ {
// 上传策略,参见 // 上传策略,参见
// https://developer.qiniu.com/kodo/manual/put-policy // https://developer.qiniu.com/kodo/manual/put-policy
PutPolicy putPolicy = new PutPolicy(); PutPolicy putPolicy = new PutPolicy();
// 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY"
// putPolicy.Scope = bucket + ":" + saveKey; // putPolicy.Scope = bucket + ":" + saveKey;
putPolicy.Scope = bucket; putPolicy.Scope = bucket;
// 上传策略有效期(对应于生成的凭证的有效期) // 上传策略有效期(对应于生成的凭证的有效期)
putPolicy.SetExpires(expireInSeconds); putPolicy.SetExpires(expireInSeconds);
putPolicy.ReturnBody = putPolicy.ReturnBody =
"{\"key\":$(key),\"hash\":$(etag),\"mimeType\":$(mimeType),\"fname\":$(fname),\"fsize\":$(fsize),\"avinfo\":$(avinfo),\"ext\":$(ext),\"imageInfo\":$(imageInfo)}"; "{\"key\":$(key),\"hash\":$(etag),\"mimeType\":$(mimeType),\"fname\":$(fname),\"fsize\":$(fsize),\"avinfo\":$(avinfo),\"ext\":$(ext),\"imageInfo\":$(imageInfo)}";
string jstr = putPolicy.ToJsonString(); string jstr = putPolicy.ToJsonString();
string token = Auth.CreateUploadToken(mac, jstr); string token = Auth.CreateUploadToken(mac, jstr);
return token; return token;
} }
} }
} }

View File

@@ -1,333 +1,333 @@
using System; using System;
using System.IO; using System.IO;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
/// <summary> /// <summary>
/// RSA加解密 使用OpenSSL的公钥加密/私钥解密 /// RSA加解密 使用OpenSSL的公钥加密/私钥解密
/// ///
/// 公私钥请使用openssl生成 ssh-keygen -t rsa 命令生成的公钥私钥是不行的 /// 公私钥请使用openssl生成 ssh-keygen -t rsa 命令生成的公钥私钥是不行的
/// </summary> /// </summary>
public class RsaHelper public class RsaHelper
{ {
private readonly RSA _privateKeyRsaProvider; private readonly RSA _privateKeyRsaProvider;
private readonly RSA _publicKeyRsaProvider; private readonly RSA _publicKeyRsaProvider;
private readonly HashAlgorithmName _hashAlgorithmName; private readonly HashAlgorithmName _hashAlgorithmName;
private readonly Encoding _encoding; private readonly Encoding _encoding;
/// <summary> /// <summary>
/// 实例化RSAHelper /// 实例化RSAHelper
/// </summary> /// </summary>
/// <param name="rsaType">加密算法类型 RSA SHA1;RSA2 SHA256 密钥长度至少为2048</param> /// <param name="rsaType">加密算法类型 RSA SHA1;RSA2 SHA256 密钥长度至少为2048</param>
/// <param name="encoding">编码类型</param> /// <param name="encoding">编码类型</param>
/// <param name="privateKey">私钥</param> /// <param name="privateKey">私钥</param>
/// <param name="publicKey">公钥</param> /// <param name="publicKey">公钥</param>
public RsaHelper(RsaType rsaType, Encoding encoding, string privateKey, string publicKey = null) public RsaHelper(RsaType rsaType, Encoding encoding, string privateKey, string publicKey = null)
{ {
_encoding = encoding; _encoding = encoding;
if (!string.IsNullOrEmpty(privateKey)) if (!string.IsNullOrEmpty(privateKey))
{ {
_privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey); _privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey);
} }
if (!string.IsNullOrEmpty(publicKey)) if (!string.IsNullOrEmpty(publicKey))
{ {
_publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey); _publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey);
} }
_hashAlgorithmName = rsaType == RsaType.RSA ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256; _hashAlgorithmName = rsaType == RsaType.RSA ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256;
} }
#region 使 #region 使
/// <summary> /// <summary>
/// 使用私钥签名 /// 使用私钥签名
/// </summary> /// </summary>
/// <param name="data">原始数据</param> /// <param name="data">原始数据</param>
/// <returns></returns> /// <returns></returns>
public string Sign(string data) public string Sign(string data)
{ {
byte[] dataBytes = _encoding.GetBytes(data); byte[] dataBytes = _encoding.GetBytes(data);
var signatureBytes = var signatureBytes =
_privateKeyRsaProvider.SignData(dataBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1); _privateKeyRsaProvider.SignData(dataBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1);
return Convert.ToBase64String(signatureBytes); return Convert.ToBase64String(signatureBytes);
} }
#endregion #endregion
#region 使 #region 使
/// <summary> /// <summary>
/// 使用公钥验证签名 /// 使用公钥验证签名
/// </summary> /// </summary>
/// <param name="data">原始数据</param> /// <param name="data">原始数据</param>
/// <param name="sign">签名</param> /// <param name="sign">签名</param>
/// <returns></returns> /// <returns></returns>
public bool Verify(string data, string sign) public bool Verify(string data, string sign)
{ {
byte[] dataBytes = _encoding.GetBytes(data); byte[] dataBytes = _encoding.GetBytes(data);
byte[] signBytes = Convert.FromBase64String(sign); byte[] signBytes = Convert.FromBase64String(sign);
var verify = _publicKeyRsaProvider.VerifyData(dataBytes, signBytes, _hashAlgorithmName, var verify = _publicKeyRsaProvider.VerifyData(dataBytes, signBytes, _hashAlgorithmName,
RSASignaturePadding.Pkcs1); RSASignaturePadding.Pkcs1);
return verify; return verify;
} }
#endregion #endregion
#region #region
public string Decrypt(string cipherText) public string Decrypt(string cipherText)
{ {
if (_privateKeyRsaProvider == null) if (_privateKeyRsaProvider == null)
{ {
throw new Exception("_privateKeyRsaProvider is null"); throw new Exception("_privateKeyRsaProvider is null");
} }
return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText),
RSAEncryptionPadding.Pkcs1)); RSAEncryptionPadding.Pkcs1));
} }
#endregion #endregion
#region #region
public string Encrypt(string text) public string Encrypt(string text)
{ {
if (_publicKeyRsaProvider == null) if (_publicKeyRsaProvider == null)
{ {
throw new Exception("_publicKeyRsaProvider is null"); throw new Exception("_publicKeyRsaProvider is null");
} }
return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text),
RSAEncryptionPadding.Pkcs1)); RSAEncryptionPadding.Pkcs1));
} }
#endregion #endregion
#region 使RSA实例 #region 使RSA实例
public RSA CreateRsaProviderFromPrivateKey(string privateKey) public RSA CreateRsaProviderFromPrivateKey(string privateKey)
{ {
var privateKeyBits = Convert.FromBase64String(privateKey); var privateKeyBits = Convert.FromBase64String(privateKey);
var rsa = RSA.Create(); var rsa = RSA.Create();
var rsaParameters = new RSAParameters(); var rsaParameters = new RSAParameters();
using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits))) using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits)))
{ {
byte bt = 0; byte bt = 0;
ushort twobytes = 0; ushort twobytes = 0;
twobytes = binr.ReadUInt16(); twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) if (twobytes == 0x8130)
binr.ReadByte(); binr.ReadByte();
else if (twobytes == 0x8230) else if (twobytes == 0x8230)
binr.ReadInt16(); binr.ReadInt16();
else else
throw new Exception("Unexpected value read binr.ReadUInt16()"); throw new Exception("Unexpected value read binr.ReadUInt16()");
twobytes = binr.ReadUInt16(); twobytes = binr.ReadUInt16();
if (twobytes != 0x0102) if (twobytes != 0x0102)
throw new Exception("Unexpected version"); throw new Exception("Unexpected version");
bt = binr.ReadByte(); bt = binr.ReadByte();
if (bt != 0x00) if (bt != 0x00)
throw new Exception("Unexpected value read binr.ReadByte()"); throw new Exception("Unexpected value read binr.ReadByte()");
rsaParameters.Modulus = binr.ReadBytes(GetIntegerSize(binr)); rsaParameters.Modulus = binr.ReadBytes(GetIntegerSize(binr));
rsaParameters.Exponent = binr.ReadBytes(GetIntegerSize(binr)); rsaParameters.Exponent = binr.ReadBytes(GetIntegerSize(binr));
rsaParameters.D = binr.ReadBytes(GetIntegerSize(binr)); rsaParameters.D = binr.ReadBytes(GetIntegerSize(binr));
rsaParameters.P = binr.ReadBytes(GetIntegerSize(binr)); rsaParameters.P = binr.ReadBytes(GetIntegerSize(binr));
rsaParameters.Q = binr.ReadBytes(GetIntegerSize(binr)); rsaParameters.Q = binr.ReadBytes(GetIntegerSize(binr));
rsaParameters.DP = binr.ReadBytes(GetIntegerSize(binr)); rsaParameters.DP = binr.ReadBytes(GetIntegerSize(binr));
rsaParameters.DQ = binr.ReadBytes(GetIntegerSize(binr)); rsaParameters.DQ = binr.ReadBytes(GetIntegerSize(binr));
rsaParameters.InverseQ = binr.ReadBytes(GetIntegerSize(binr)); rsaParameters.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
} }
rsa.ImportParameters(rsaParameters); rsa.ImportParameters(rsaParameters);
return rsa; return rsa;
} }
#endregion #endregion
#region 使RSA实例 #region 使RSA实例
public RSA CreateRsaProviderFromPublicKey(string publicKeyString) public RSA CreateRsaProviderFromPublicKey(string publicKeyString)
{ {
// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
byte[] seqOid = byte[] seqOid =
{0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00}; {0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00};
byte[] seq = new byte[15]; byte[] seq = new byte[15];
var x509Key = Convert.FromBase64String(publicKeyString); var x509Key = Convert.FromBase64String(publicKeyString);
// --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------ // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------
using (MemoryStream mem = new MemoryStream(x509Key)) using (MemoryStream mem = new MemoryStream(x509Key))
{ {
using (BinaryReader binr = new BinaryReader(mem) using (BinaryReader binr = new BinaryReader(mem)
) //wrap Memory Stream with BinaryReader for easy reading ) //wrap Memory Stream with BinaryReader for easy reading
{ {
byte bt = 0; byte bt = 0;
ushort twobytes = 0; ushort twobytes = 0;
twobytes = binr.ReadUInt16(); twobytes = binr.ReadUInt16();
if (twobytes == 0x8130 if (twobytes == 0x8130
) //data read as little endian order (actual data order for Sequence is 30 81) ) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230) else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes binr.ReadInt16(); //advance 2 bytes
else else
return null; return null;
seq = binr.ReadBytes(15); //read the Sequence OID seq = binr.ReadBytes(15); //read the Sequence OID
if (!CompareBytearrays(seq, seqOid)) //make sure Sequence for OID is correct if (!CompareBytearrays(seq, seqOid)) //make sure Sequence for OID is correct
return null; return null;
twobytes = binr.ReadUInt16(); twobytes = binr.ReadUInt16();
if (twobytes == 0x8103 if (twobytes == 0x8103
) //data read as little endian order (actual data order for Bit String is 03 81) ) //data read as little endian order (actual data order for Bit String is 03 81)
binr.ReadByte(); //advance 1 byte binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8203) else if (twobytes == 0x8203)
binr.ReadInt16(); //advance 2 bytes binr.ReadInt16(); //advance 2 bytes
else else
return null; return null;
bt = binr.ReadByte(); bt = binr.ReadByte();
if (bt != 0x00) //expect null byte next if (bt != 0x00) //expect null byte next
return null; return null;
twobytes = binr.ReadUInt16(); twobytes = binr.ReadUInt16();
if (twobytes == 0x8130 if (twobytes == 0x8130
) //data read as little endian order (actual data order for Sequence is 30 81) ) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230) else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes binr.ReadInt16(); //advance 2 bytes
else else
return null; return null;
twobytes = binr.ReadUInt16(); twobytes = binr.ReadUInt16();
byte lowbyte = 0x00; byte lowbyte = 0x00;
byte highbyte = 0x00; byte highbyte = 0x00;
if (twobytes == 0x8102 if (twobytes == 0x8102
) //data read as little endian order (actual data order for Integer is 02 81) ) //data read as little endian order (actual data order for Integer is 02 81)
lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus
else if (twobytes == 0x8202) else if (twobytes == 0x8202)
{ {
highbyte = binr.ReadByte(); //advance 2 bytes highbyte = binr.ReadByte(); //advance 2 bytes
lowbyte = binr.ReadByte(); lowbyte = binr.ReadByte();
} }
else else
return null; return null;
byte[] modint = byte[] modint =
{lowbyte, highbyte, 0x00, 0x00}; //reverse byte order since asn.1 key uses big endian order {lowbyte, highbyte, 0x00, 0x00}; //reverse byte order since asn.1 key uses big endian order
int modsize = BitConverter.ToInt32(modint, 0); int modsize = BitConverter.ToInt32(modint, 0);
int firstbyte = binr.PeekChar(); int firstbyte = binr.PeekChar();
if (firstbyte == 0x00) if (firstbyte == 0x00)
{ {
//if first byte (highest order) of modulus is zero, don't include it //if first byte (highest order) of modulus is zero, don't include it
binr.ReadByte(); //skip this null byte binr.ReadByte(); //skip this null byte
modsize -= 1; //reduce modulus buffer size by 1 modsize -= 1; //reduce modulus buffer size by 1
} }
byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes
if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data
return null; return null;
int expbytes = int expbytes =
binr binr
.ReadByte(); // should only need one byte for actual exponent data (for all useful values) .ReadByte(); // should only need one byte for actual exponent data (for all useful values)
byte[] exponent = binr.ReadBytes(expbytes); byte[] exponent = binr.ReadBytes(expbytes);
// ------- create RSACryptoServiceProvider instance and initialize with public key ----- // ------- create RSACryptoServiceProvider instance and initialize with public key -----
var rsa = RSA.Create(); var rsa = RSA.Create();
RSAParameters rsaKeyInfo = new RSAParameters RSAParameters rsaKeyInfo = new RSAParameters
{ {
Modulus = modulus, Modulus = modulus,
Exponent = exponent Exponent = exponent
}; };
rsa.ImportParameters(rsaKeyInfo); rsa.ImportParameters(rsaKeyInfo);
return rsa; return rsa;
} }
} }
} }
#endregion #endregion
#region #region
private int GetIntegerSize(BinaryReader binr) private int GetIntegerSize(BinaryReader binr)
{ {
byte bt = 0; byte bt = 0;
int count = 0; int count = 0;
bt = binr.ReadByte(); bt = binr.ReadByte();
if (bt != 0x02) if (bt != 0x02)
return 0; return 0;
bt = binr.ReadByte(); bt = binr.ReadByte();
if (bt == 0x81) if (bt == 0x81)
count = binr.ReadByte(); count = binr.ReadByte();
else if (bt == 0x82) else if (bt == 0x82)
{ {
var highbyte = binr.ReadByte(); var highbyte = binr.ReadByte();
var lowbyte = binr.ReadByte(); var lowbyte = binr.ReadByte();
byte[] modint = {lowbyte, highbyte, 0x00, 0x00}; byte[] modint = {lowbyte, highbyte, 0x00, 0x00};
count = BitConverter.ToInt32(modint, 0); count = BitConverter.ToInt32(modint, 0);
} }
else else
{ {
count = bt; count = bt;
} }
while (binr.ReadByte() == 0x00) while (binr.ReadByte() == 0x00)
{ {
count -= 1; count -= 1;
} }
binr.BaseStream.Seek(-1, SeekOrigin.Current); binr.BaseStream.Seek(-1, SeekOrigin.Current);
return count; return count;
} }
private bool CompareBytearrays(byte[] a, byte[] b) private bool CompareBytearrays(byte[] a, byte[] b)
{ {
if (a.Length != b.Length) if (a.Length != b.Length)
return false; return false;
int i = 0; int i = 0;
foreach (byte c in a) foreach (byte c in a)
{ {
if (c != b[i]) if (c != b[i])
return false; return false;
i++; i++;
} }
return true; return true;
} }
#endregion #endregion
} }
/// <summary> /// <summary>
/// RSA算法类型 /// RSA算法类型
/// </summary> /// </summary>
public enum RsaType public enum RsaType
{ {
/// <summary> /// <summary>
/// SHA1 /// SHA1
/// </summary> /// </summary>
RSA = 0, RSA = 0,
/// <summary> /// <summary>
/// RSA2 密钥长度至少为2048 /// RSA2 密钥长度至少为2048
/// SHA256 /// SHA256
/// </summary> /// </summary>
RSA2 RSA2
} }
} }

View File

@@ -1,143 +1,143 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class RandomHelper public class RandomHelper
{ {
#region #region
/// <summary> /// <summary>
/// 随机数最小值 /// 随机数最小值
/// </summary> /// </summary>
private static int MiniNum => int.MinValue; private static int MiniNum => int.MinValue;
/// <summary> /// <summary>
/// 随机数最大值 /// 随机数最大值
/// </summary> /// </summary>
private static int MaxNum => int.MaxValue; private static int MaxNum => int.MaxValue;
/// <summary> /// <summary>
/// 随机数长度 /// 随机数长度
/// </summary> /// </summary>
private static int RandomLength => 4; private static int RandomLength => 4;
/// <summary> /// <summary>
/// 随机数来源 /// 随机数来源
/// </summary> /// </summary>
private static string RandomString => "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz"; private static string RandomString => "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz";
/// <summary> /// <summary>
/// 系统默认生成随机数长度 /// 系统默认生成随机数长度
/// </summary> /// </summary>
private const int RandomLengthPresent = 6; private const int RandomLengthPresent = 6;
/// <summary> /// <summary>
/// 系统默认随机数来源 /// 系统默认随机数来源
/// </summary> /// </summary>
private const string RandomStringPresent = "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz"; private const string RandomStringPresent = "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz";
private static readonly Random Random = new Random(DateTime.Now.Millisecond); private static readonly Random Random = new Random(DateTime.Now.Millisecond);
#endregion #endregion
#region #region
/// <summary> /// <summary>
/// 产生随机字符 /// 产生随机字符
/// </summary> /// </summary>
/// <param name="randomLength">产生随机数长度,默认为-1</param> /// <param name="randomLength">产生随机数长度,默认为-1</param>
/// <param name="randomString">随机数来源</param> /// <param name="randomString">随机数来源</param>
/// <returns></returns> /// <returns></returns>
public static string GetRandomString(int randomLength = -1, string randomString = "") public static string GetRandomString(int randomLength = -1, string randomString = "")
{ {
int randomLengthTemp;//随机数长度 int randomLengthTemp;//随机数长度
if (randomLength > 0) if (randomLength > 0)
randomLengthTemp = randomLength; randomLengthTemp = randomLength;
else if (RandomLength > 0) else if (RandomLength > 0)
randomLengthTemp = RandomLength; randomLengthTemp = RandomLength;
else else
randomLengthTemp = RandomLengthPresent; randomLengthTemp = RandomLengthPresent;
string randomStringTemp;//随机数来源 string randomStringTemp;//随机数来源
if (!string.IsNullOrEmpty(randomString)) if (!string.IsNullOrEmpty(randomString))
randomStringTemp = randomString; randomStringTemp = randomString;
else if (!string.IsNullOrEmpty(RandomString)) else if (!string.IsNullOrEmpty(RandomString))
randomStringTemp = RandomString; randomStringTemp = RandomString;
else else
randomStringTemp = RandomStringPresent; randomStringTemp = RandomStringPresent;
string returnValue = string.Empty; string returnValue = string.Empty;
for (int i = 0; i < randomLengthTemp; i++) for (int i = 0; i < randomLengthTemp; i++)
{ {
int r = Random.Next(0, randomStringTemp.Length - 1); int r = Random.Next(0, randomStringTemp.Length - 1);
returnValue += randomStringTemp[r]; returnValue += randomStringTemp[r];
} }
return returnValue; return returnValue;
} }
#endregion #endregion
#region #region
/// <summary> /// <summary>
/// 产生随机数 /// 产生随机数
/// </summary> /// </summary>
/// <param name="minNum">最小随机数</param> /// <param name="minNum">最小随机数</param>
/// <param name="maxNum">最大随机数</param> /// <param name="maxNum">最大随机数</param>
/// <returns></returns> /// <returns></returns>
public static int GetRandom(int minNum = -1, int maxNum = -1) public static int GetRandom(int minNum = -1, int maxNum = -1)
{ {
int minNumTemp = minNum == -1 ? MiniNum : minNum;//最小随机数 int minNumTemp = minNum == -1 ? MiniNum : minNum;//最小随机数
int maxNumTemp = maxNum == -1 ? MaxNum : maxNum;//最大随机数 int maxNumTemp = maxNum == -1 ? MaxNum : maxNum;//最大随机数
return Random.Next(minNumTemp, maxNumTemp); return Random.Next(minNumTemp, maxNumTemp);
} }
#endregion #endregion
#region 0.01.0 #region 0.01.0
/// <summary> /// <summary>
/// 生成一个0.0到1.0的随机小数 /// 生成一个0.0到1.0的随机小数
/// </summary> /// </summary>
public double GetRandomDouble() public double GetRandomDouble()
{ {
return Random.NextDouble(); return Random.NextDouble();
} }
#endregion #endregion
#region #region
/// <summary> /// <summary>
/// 对一个数组进行随机排序 /// 对一个数组进行随机排序
/// </summary> /// </summary>
/// <typeparam name="T">数组的类型</typeparam> /// <typeparam name="T">数组的类型</typeparam>
/// <param name="arr">需要随机排序的数组</param> /// <param name="arr">需要随机排序的数组</param>
public void GetRandomArray<T>(T[] arr) public void GetRandomArray<T>(T[] arr)
{ {
//对数组进行随机排序的算法:随机选择两个位置,将两个位置上的值交换 //对数组进行随机排序的算法:随机选择两个位置,将两个位置上的值交换
//交换的次数,这里使用数组的长度作为交换次数 //交换的次数,这里使用数组的长度作为交换次数
int count = arr.Length; int count = arr.Length;
//开始交换 //开始交换
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
{ {
//生成两个随机数位置 //生成两个随机数位置
int randomNum1 = GetRandom(0, arr.Length); int randomNum1 = GetRandom(0, arr.Length);
int randomNum2 = GetRandom(0, arr.Length); int randomNum2 = GetRandom(0, arr.Length);
//定义临时变量 //定义临时变量
//交换两个随机数位置的值 //交换两个随机数位置的值
var temp = arr[randomNum1]; var temp = arr[randomNum1];
arr[randomNum1] = arr[randomNum2]; arr[randomNum1] = arr[randomNum2];
arr[randomNum2] = temp; arr[randomNum2] = temp;
} }
} }
public static string Uuid(int len) public static string Uuid(int len)
{ {
len = len > 32 ? 32 : len; len = len > 32 ? 32 : len;
var str = Guid.NewGuid().ToString("N"); var str = Guid.NewGuid().ToString("N");
var list = new List<string>(); var list = new List<string>();
while (true) while (true)
{ {
var index = GetRandom(0, 32); var index = GetRandom(0, 32);
list.Add(str[index].ToString()); list.Add(str[index].ToString());
if (list.Count >= len) if (list.Count >= len)
break; break;
} }
return string.Join("", list); return string.Join("", list);
} }
#endregion #endregion
} }
} }

View File

@@ -1,72 +1,72 @@
using Hncore.Infrastructure.Extension; using Hncore.Infrastructure.Extension;
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class RedisLocker public class RedisLocker
{ {
private string _key; private string _key;
private long _lockTime; private long _lockTime;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="key">锁的键</param> /// <param name="key">锁的键</param>
/// <param name="outTime">锁超时时间 单位毫秒</param> /// <param name="outTime">锁超时时间 单位毫秒</param>
public RedisLocker(string key,long outTime) public RedisLocker(string key,long outTime)
{ {
_key =$"Lock:{Assembly.GetCallingAssembly().GetFriendName()}:{key}" ; _key =$"Lock:{Assembly.GetCallingAssembly().GetFriendName()}:{key}" ;
_lockTime = outTime; _lockTime = outTime;
} }
public void Exec(Action action) public void Exec(Action action)
{ {
if (GetLock()) if (GetLock())
{ {
action(); action();
ReleaseLock(); ReleaseLock();
} }
} }
protected bool GetLock() protected bool GetLock()
{ {
try try
{ {
var currentTime = DateTime.Now.GetUnixTimeStamp(); var currentTime = DateTime.Now.GetUnixTimeStamp();
if (RedisHelper.SetNx(this._key, currentTime + _lockTime)) if (RedisHelper.SetNx(this._key, currentTime + _lockTime))
{ {
Console.WriteLine("获取到Redis锁了"); Console.WriteLine("获取到Redis锁了");
RedisHelper.Expire(_key, TimeSpan.FromMilliseconds(_lockTime)); //设置过期时间 RedisHelper.Expire(_key, TimeSpan.FromMilliseconds(_lockTime)); //设置过期时间
return true; return true;
} }
//防止SetNx成功但是设置过期时间Expire失败造成死锁 //防止SetNx成功但是设置过期时间Expire失败造成死锁
var lockValue = Convert.ToInt64(RedisHelper.Get(_key)); var lockValue = Convert.ToInt64(RedisHelper.Get(_key));
currentTime = DateTime.Now.GetUnixTimeStamp(); currentTime = DateTime.Now.GetUnixTimeStamp();
if (lockValue > 0 && currentTime > lockValue) if (lockValue > 0 && currentTime > lockValue)
{ {
var getsetResult = Convert.ToInt64(RedisHelper.GetSet(_key, currentTime)); var getsetResult = Convert.ToInt64(RedisHelper.GetSet(_key, currentTime));
if (getsetResult == 0 || getsetResult == lockValue) if (getsetResult == 0 || getsetResult == lockValue)
{ {
Console.WriteLine("获取到Redis锁了"); Console.WriteLine("获取到Redis锁了");
RedisHelper.Expire(_key, TimeSpan.FromMilliseconds(_lockTime)); RedisHelper.Expire(_key, TimeSpan.FromMilliseconds(_lockTime));
return true; return true;
} }
} }
Console.WriteLine("没有获取到锁"); Console.WriteLine("没有获取到锁");
return false; return false;
} }
catch catch
{ {
ReleaseLock(); ReleaseLock();
return false; return false;
} }
} }
protected bool ReleaseLock() protected bool ReleaseLock()
{ {
return RedisHelper.Del(_key) > 0; return RedisHelper.Del(_key) > 0;
} }
} }
} }

View File

@@ -1,35 +1,35 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public static class RegexPattern public static class RegexPattern
{ {
public const string Mobile = @"^1[123456789]\d{9}$";//宽松的手机验证。包含运营商可能的新增号段。 public const string Mobile = @"^1[123456789]\d{9}$";//宽松的手机验证。包含运营商可能的新增号段。
public const string Email = @"^[\w-]+@[\w-]+\.(com|net|org|edu|mil|tv|biz|info)$";// 邮箱验证 public const string Email = @"^[\w-]+@[\w-]+\.(com|net|org|edu|mil|tv|biz|info)$";// 邮箱验证
public const string IdCard = @"^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$";//18位身份证 public const string IdCard = @"^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$";//18位身份证
public const string CarNumber = @"^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1})$"; public const string CarNumber = @"^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1})$";
public static bool IsMatch(string str,string pattern) public static bool IsMatch(string str,string pattern)
{ {
return Regex.IsMatch(str, pattern); return Regex.IsMatch(str, pattern);
} }
public static bool IsMobile(string str) public static bool IsMobile(string str)
{ {
return IsMatch(str, Mobile); return IsMatch(str, Mobile);
} }
public static bool IsEmail(string str) public static bool IsEmail(string str)
{ {
return IsMatch(str, Email); return IsMatch(str, Email);
} }
public static bool IsIdCard(string str) public static bool IsIdCard(string str)
{ {
return IsMatch(str, IdCard); return IsMatch(str, IdCard);
} }
public static bool IsCarNumber(string str) public static bool IsCarNumber(string str)
{ {
return IsMatch(str, CarNumber); return IsMatch(str, CarNumber);
} }
} }
} }

View File

@@ -1,388 +1,388 @@
using System; using System;
using System.IO; using System.IO;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class SecurityHelper public class SecurityHelper
{ {
#region AES加密 #region AES加密
/// <summary> /// <summary>
/// AES加密 /// AES加密
/// </summary> /// </summary>
/// <param name="toEncrypt"></param> /// <param name="toEncrypt"></param>
/// <returns></returns> /// <returns></returns>
public static string AESEncrypt(string toEncrypt, string key) public static string AESEncrypt(string toEncrypt, string key)
{ {
if (string.IsNullOrWhiteSpace(toEncrypt)) if (string.IsNullOrWhiteSpace(toEncrypt))
return string.Empty; return string.Empty;
// 256-AES key // 256-AES key
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
RijndaelManaged rDel = new RijndaelManaged(); RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray; rDel.Key = keyArray;
rDel.Mode = CipherMode.ECB; rDel.Mode = CipherMode.ECB;
rDel.Padding = PaddingMode.PKCS7; rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateEncryptor(); ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length);
} }
#endregion #endregion
#region AES解密 #region AES解密
/// <summary> /// <summary>
/// AES解密 /// AES解密
/// </summary> /// </summary>
/// <param name="toDecrypt"></param> /// <param name="toDecrypt"></param>
/// <returns></returns> /// <returns></returns>
public static string Decrypt(string toDecrypt, string key) public static string Decrypt(string toDecrypt, string key)
{ {
if (string.IsNullOrWhiteSpace(toDecrypt)) if (string.IsNullOrWhiteSpace(toDecrypt))
return string.Empty; return string.Empty;
try try
{ {
// 256-AES key // 256-AES key
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
RijndaelManaged rDel = new RijndaelManaged(); RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray; rDel.Key = keyArray;
rDel.Mode = CipherMode.ECB; rDel.Mode = CipherMode.ECB;
rDel.Padding = PaddingMode.PKCS7; rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateDecryptor(); ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return UTF8Encoding.UTF8.GetString(resultArray); return UTF8Encoding.UTF8.GetString(resultArray);
} }
catch(Exception ex) catch(Exception ex)
{ {
LogHelper.Error("aes Decrypt", ex.Message); LogHelper.Error("aes Decrypt", ex.Message);
return toDecrypt; return toDecrypt;
} }
} }
#endregion #endregion
#region MD5加密 #region MD5加密
/// <summary> /// <summary>
/// MD5加密 /// MD5加密
/// </summary> /// </summary>
/// <param name="input"></param> /// <param name="input"></param>
/// <returns></returns> /// <returns></returns>
public static string GetMd5Hash(string input, Encoding encoding = null) public static string GetMd5Hash(string input, Encoding encoding = null)
{ {
if (encoding == null) if (encoding == null)
{ {
encoding = Encoding.UTF8; encoding = Encoding.UTF8;
} }
MD5 myMD5 = new MD5CryptoServiceProvider(); MD5 myMD5 = new MD5CryptoServiceProvider();
byte[] signed = myMD5.ComputeHash(encoding.GetBytes(input)); byte[] signed = myMD5.ComputeHash(encoding.GetBytes(input));
string signResult = byte2mac(signed); string signResult = byte2mac(signed);
return signResult.ToUpper(); return signResult.ToUpper();
} }
//MD5加密方法 //MD5加密方法
private static string byte2mac(byte[] signed) private static string byte2mac(byte[] signed)
{ {
StringBuilder EnText = new StringBuilder(); StringBuilder EnText = new StringBuilder();
foreach (byte Byte in signed) foreach (byte Byte in signed)
{ {
EnText.AppendFormat("{0:x2}", Byte); EnText.AppendFormat("{0:x2}", Byte);
} }
return EnText.ToString(); return EnText.ToString();
} }
#endregion #endregion
#region DES加密 #region DES加密
/// <summary> /// <summary>
/// 对字符串进行DES加密 /// 对字符串进行DES加密
/// </summary> /// </summary>
/// <param name="sourceString">待加密的字符串</param> /// <param name="sourceString">待加密的字符串</param>
/// <returns>加密后的BASE64编码的字符串</returns> /// <returns>加密后的BASE64编码的字符串</returns>
public static string DesEncrypt(string sourceString, string key, string iv) public static string DesEncrypt(string sourceString, string key, string iv)
{ {
byte[] btKey = Encoding.Default.GetBytes(key); byte[] btKey = Encoding.Default.GetBytes(key);
byte[] btIV = Encoding.Default.GetBytes(iv); byte[] btIV = Encoding.Default.GetBytes(iv);
DESCryptoServiceProvider des = new DESCryptoServiceProvider(); DESCryptoServiceProvider des = new DESCryptoServiceProvider();
using (MemoryStream ms = new MemoryStream()) using (MemoryStream ms = new MemoryStream())
{ {
byte[] inData = Encoding.Default.GetBytes(sourceString); byte[] inData = Encoding.Default.GetBytes(sourceString);
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write)) using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
{ {
cs.Write(inData, 0, inData.Length); cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock(); cs.FlushFinalBlock();
} }
return Convert.ToBase64String(ms.ToArray()); return Convert.ToBase64String(ms.ToArray());
} }
} }
#endregion #endregion
#region DES加密后的字符串进行解密 #region DES加密后的字符串进行解密
/// <summary> /// <summary>
/// 对DES加密后的字符串进行解密 /// 对DES加密后的字符串进行解密
/// </summary> /// </summary>
/// <param name="encryptedString">待解密的字符串</param> /// <param name="encryptedString">待解密的字符串</param>
/// <returns>解密后的字符串</returns> /// <returns>解密后的字符串</returns>
public static string DesDecrypt(string encryptedString, string key, string iv) public static string DesDecrypt(string encryptedString, string key, string iv)
{ {
byte[] btKey = Encoding.Default.GetBytes(key); byte[] btKey = Encoding.Default.GetBytes(key);
byte[] btIV = Encoding.Default.GetBytes(iv); byte[] btIV = Encoding.Default.GetBytes(iv);
DESCryptoServiceProvider des = new DESCryptoServiceProvider(); DESCryptoServiceProvider des = new DESCryptoServiceProvider();
using (MemoryStream ms = new MemoryStream()) using (MemoryStream ms = new MemoryStream())
{ {
byte[] inData = Convert.FromBase64String(encryptedString); byte[] inData = Convert.FromBase64String(encryptedString);
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write)) using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
{ {
cs.Write(inData, 0, inData.Length); cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock(); cs.FlushFinalBlock();
} }
return Encoding.Default.GetString(ms.ToArray()); return Encoding.Default.GetString(ms.ToArray());
} }
} }
#endregion #endregion
public static string Sha1(string str) public static string Sha1(string str)
{ {
SHA1 sha1 = new SHA1CryptoServiceProvider(); SHA1 sha1 = new SHA1CryptoServiceProvider();
byte[] bytes_in = Encoding.UTF8.GetBytes(str); byte[] bytes_in = Encoding.UTF8.GetBytes(str);
byte[] bytes_out = sha1.ComputeHash(bytes_in); byte[] bytes_out = sha1.ComputeHash(bytes_in);
sha1.Dispose(); sha1.Dispose();
var sb = new StringBuilder(); var sb = new StringBuilder();
foreach (byte b in bytes_out) foreach (byte b in bytes_out)
{ {
sb.Append(b.ToString("x2")); sb.Append(b.ToString("x2"));
} }
return sb.ToString(); return sb.ToString();
} }
public static string HMACSHA1(string text, string key) public static string HMACSHA1(string text, string key)
{ {
HMACSHA1 myhmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(key)); HMACSHA1 myhmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(key));
byte[] byteArray = Encoding.UTF8.GetBytes(text); byte[] byteArray = Encoding.UTF8.GetBytes(text);
MemoryStream stream = new MemoryStream(byteArray); MemoryStream stream = new MemoryStream(byteArray);
string signature = Convert.ToBase64String(myhmacsha1.ComputeHash(stream)); string signature = Convert.ToBase64String(myhmacsha1.ComputeHash(stream));
return signature; return signature;
} }
#region JS Aes解密 #region JS Aes解密
/// <summary> /// <summary>
/// JS Aes解密 /// JS Aes解密
/// </summary> /// </summary>
/// <param name="toDecrypt"></param> /// <param name="toDecrypt"></param>
/// <param name="key"></param> /// <param name="key"></param>
/// <param name="iv"></param> /// <param name="iv"></param>
/// <returns></returns> /// <returns></returns>
public static string JsAesDecrypt(string toDecrypt, string key, string iv) public static string JsAesDecrypt(string toDecrypt, string key, string iv)
{ {
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv); byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);
byte[] cipherText = HexToByteArray(toDecrypt); byte[] cipherText = HexToByteArray(toDecrypt);
// Check arguments. // Check arguments.
if (cipherText == null || cipherText.Length <= 0) if (cipherText == null || cipherText.Length <= 0)
{ {
throw new ArgumentNullException("cipherText"); throw new ArgumentNullException("cipherText");
} }
if (key == null || key.Length <= 0) if (key == null || key.Length <= 0)
{ {
throw new ArgumentNullException("key"); throw new ArgumentNullException("key");
} }
if (iv == null || iv.Length <= 0) if (iv == null || iv.Length <= 0)
{ {
throw new ArgumentNullException("key"); throw new ArgumentNullException("key");
} }
string plaintext = null; string plaintext = null;
using (var rijAlg = new RijndaelManaged()) using (var rijAlg = new RijndaelManaged())
{ {
//Settings //Settings
rijAlg.Mode = CipherMode.CBC; rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.PKCS7; rijAlg.Padding = PaddingMode.PKCS7;
rijAlg.FeedbackSize = 128; rijAlg.FeedbackSize = 128;
rijAlg.Key = keyArray; rijAlg.Key = keyArray;
rijAlg.IV = ivArray; rijAlg.IV = ivArray;
var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
using (var msDecrypt = new MemoryStream(cipherText)) using (var msDecrypt = new MemoryStream(cipherText))
{ {
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{ {
using (var srDecrypt = new StreamReader(csDecrypt)) using (var srDecrypt = new StreamReader(csDecrypt))
{ {
plaintext = srDecrypt.ReadToEnd(); plaintext = srDecrypt.ReadToEnd();
} }
} }
} }
} }
return plaintext; return plaintext;
} }
private static byte[] HexToByteArray(string hex) private static byte[] HexToByteArray(string hex)
{ {
int NumberChars = hex.Length; int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2]; byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2) for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes; return bytes;
} }
#endregion #endregion
#region JS Aes #region JS Aes
/// <summary> /// <summary>
/// JsAesEncrypt /// JsAesEncrypt
/// </summary> /// </summary>
/// <param name="plainText"></param> /// <param name="plainText"></param>
/// <param name="key"></param> /// <param name="key"></param>
/// <param name="iv"></param> /// <param name="iv"></param>
/// <returns></returns> /// <returns></returns>
public static string JsAesEncrypt(string plainText, string key, string iv) public static string JsAesEncrypt(string plainText, string key, string iv)
{ {
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv); byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);
// Check arguments. // Check arguments.
if (plainText == null || plainText.Length <= 0) if (plainText == null || plainText.Length <= 0)
{ {
throw new ArgumentNullException("plainText"); throw new ArgumentNullException("plainText");
} }
if (key == null || key.Length <= 0) if (key == null || key.Length <= 0)
{ {
throw new ArgumentNullException("key"); throw new ArgumentNullException("key");
} }
if (iv == null || iv.Length <= 0) if (iv == null || iv.Length <= 0)
{ {
throw new ArgumentNullException("key"); throw new ArgumentNullException("key");
} }
byte[] encrypted; byte[] encrypted;
using (var rijAlg = new RijndaelManaged()) using (var rijAlg = new RijndaelManaged())
{ {
rijAlg.Mode = CipherMode.CBC; rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.PKCS7; rijAlg.Padding = PaddingMode.PKCS7;
rijAlg.FeedbackSize = 128; rijAlg.FeedbackSize = 128;
rijAlg.Key = keyArray; rijAlg.Key = keyArray;
rijAlg.IV = ivArray; rijAlg.IV = ivArray;
var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV); var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
using (var msEncrypt = new MemoryStream()) using (var msEncrypt = new MemoryStream())
{ {
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{ {
using (var swEncrypt = new StreamWriter(csEncrypt)) using (var swEncrypt = new StreamWriter(csEncrypt))
{ {
swEncrypt.Write(plainText); swEncrypt.Write(plainText);
} }
encrypted = msEncrypt.ToArray(); encrypted = msEncrypt.ToArray();
} }
} }
} }
// Return the encrypted bytes from the memory stream. // Return the encrypted bytes from the memory stream.
return ByteArrayToHex(encrypted); return ByteArrayToHex(encrypted);
} }
private static string ByteArrayToHex(byte[] ba) private static string ByteArrayToHex(byte[] ba)
{ {
string hex = BitConverter.ToString(ba); string hex = BitConverter.ToString(ba);
return hex.Replace("-", ""); return hex.Replace("-", "");
} }
#endregion #endregion
#region #region
/// <summary> /// <summary>
/// 加密隐藏信息(将原信息其中一部分数据替换为特殊字符) /// 加密隐藏信息(将原信息其中一部分数据替换为特殊字符)
/// </summary> /// </summary>
/// <param name="param">原参数信息</param> /// <param name="param">原参数信息</param>
/// <param name="key">更换后的特殊字符</param> /// <param name="key">更换后的特殊字符</param>
/// <param name="index">下标</param> /// <param name="index">下标</param>
/// <param name="length">位数,-1代表到队尾</param> /// <param name="length">位数,-1代表到队尾</param>
/// <returns></returns> /// <returns></returns>
public static string Encrypt(string param, string key, int index, int length = -1) public static string Encrypt(string param, string key, int index, int length = -1)
{ {
if (string.IsNullOrEmpty(param)) if (string.IsNullOrEmpty(param))
{ {
return ""; return "";
} }
string str = ""; string str = "";
if (index > param.Length - 1) if (index > param.Length - 1)
{ {
return param; return param;
} }
str = param.Substring(0, index); str = param.Substring(0, index);
if (length == -1) if (length == -1)
{ {
length = param.Length - index; length = param.Length - index;
} }
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
str += key; str += key;
} }
if (index + length < param.Length) if (index + length < param.Length)
{ {
str += param.Substring(index + length); str += param.Substring(index + length);
} }
return str; return str;
} }
#endregion #endregion
/// <summary> /// <summary>
/// 将密码使用MD5算法求哈希值 /// 将密码使用MD5算法求哈希值
/// </summary> /// </summary>
/// <param name="password"></param> /// <param name="password"></param>
/// <returns></returns> /// <returns></returns>
public static string HashPassword(string password) public static string HashPassword(string password)
{ {
using (MD5 md5 = MD5.Create()) using (MD5 md5 = MD5.Create())
{ {
byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(password)); byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
return Convert.ToBase64String(bytes); return Convert.ToBase64String(bytes);
} }
} }
} }
} }

View File

@@ -1,63 +1,63 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class ShellHelper public class ShellHelper
{ {
public static string Bash(string cmd) public static string Bash(string cmd)
{ {
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{ {
var escapedArgs = cmd.Replace("\"", "\\\""); var escapedArgs = cmd.Replace("\"", "\\\"");
var process = new Process() var process = new Process()
{ {
StartInfo = new ProcessStartInfo StartInfo = new ProcessStartInfo
{ {
FileName = "/bin/bash", FileName = "/bin/bash",
Arguments = $"-c \"{escapedArgs}\"", Arguments = $"-c \"{escapedArgs}\"",
RedirectStandardOutput = true, RedirectStandardOutput = true,
UseShellExecute = false, UseShellExecute = false,
CreateNoWindow = true CreateNoWindow = true
} }
}; };
process.Start(); process.Start();
string result = process.StandardOutput.ReadToEnd(); string result = process.StandardOutput.ReadToEnd();
process.WaitForExit(); process.WaitForExit();
return result; return result;
} }
return ""; return "";
} }
public static void RedirectOutputBash(string cmd) public static void RedirectOutputBash(string cmd)
{ {
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{ {
cmd = cmd.Replace("\"", "\\\""); cmd = cmd.Replace("\"", "\\\"");
Console.WriteLine("执行命令"); Console.WriteLine("执行命令");
Console.WriteLine(cmd); Console.WriteLine(cmd);
var process = new Process() var process = new Process()
{ {
StartInfo = new ProcessStartInfo StartInfo = new ProcessStartInfo
{ {
FileName = "/bin/bash", FileName = "/bin/bash",
Arguments = $"-c \"{cmd}\"", Arguments = $"-c \"{cmd}\"",
RedirectStandardOutput = true, RedirectStandardOutput = true,
UseShellExecute = false, UseShellExecute = false,
CreateNoWindow = true, CreateNoWindow = true,
} }
}; };
process.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data); process.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data);
process.Start(); process.Start();
process.BeginOutputReadLine(); process.BeginOutputReadLine();
process.WaitForExit(); process.WaitForExit();
} }
} }
} }
} }

View File

@@ -1,88 +1,88 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Web; using System.Web;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class UrlHelper public class UrlHelper
{ {
#region url参数 #region url参数
/// <summary> /// <summary>
/// 设置url参数 /// 设置url参数
/// </summary> /// </summary>
/// <param name="paramName"></param> /// <param name="paramName"></param>
/// <param name="paramValue"></param> /// <param name="paramValue"></param>
/// <param name="url"></param> /// <param name="url"></param>
/// <returns></returns> /// <returns></returns>
public static string SetUrlParam(string url, string paramName, string paramValue) public static string SetUrlParam(string url, string paramName, string paramValue)
{ {
paramName = paramName.ToLower(); paramName = paramName.ToLower();
string currentUrl = url; string currentUrl = url;
if (!string.IsNullOrEmpty(paramValue)) if (!string.IsNullOrEmpty(paramValue))
{ {
paramValue = HttpUtility.UrlEncode(paramValue); paramValue = HttpUtility.UrlEncode(paramValue);
} }
if (!currentUrl.Contains("?")) if (!currentUrl.Contains("?"))
{ {
return currentUrl += "?" + paramName + "=" + paramValue; return currentUrl += "?" + paramName + "=" + paramValue;
} }
List<string> paramItems = currentUrl.Split('?')[1].Split('&').ToList(); List<string> paramItems = currentUrl.Split('?')[1].Split('&').ToList();
string paramItem = paramItems.SingleOrDefault(t => t.ToLower().Split('=')[0] == paramName); string paramItem = paramItems.SingleOrDefault(t => t.ToLower().Split('=')[0] == paramName);
if (!string.IsNullOrEmpty(paramItem)) if (!string.IsNullOrEmpty(paramItem))
{ {
return currentUrl.Replace(paramItem, paramName + "=" + paramValue); return currentUrl.Replace(paramItem, paramName + "=" + paramValue);
} }
else else
{ {
if (currentUrl.Contains("?")) if (currentUrl.Contains("?"))
{ {
currentUrl += "&"; currentUrl += "&";
} }
else else
{ {
currentUrl += "?"; currentUrl += "?";
} }
return currentUrl + paramName + "=" + paramValue; return currentUrl + paramName + "=" + paramValue;
} }
} }
public static string SetUrlParam(string url, object paramObj) public static string SetUrlParam(string url, object paramObj)
{ {
var type = paramObj.GetType(); var type = paramObj.GetType();
var properties = type.GetProperties(); var properties = type.GetProperties();
foreach (var property in properties) foreach (var property in properties)
{ {
string name = property.Name; string name = property.Name;
object valueObj = property.GetValue(paramObj, null); object valueObj = property.GetValue(paramObj, null);
if (valueObj == null) if (valueObj == null)
{ {
continue; continue;
} }
string value = valueObj.ToString(); string value = valueObj.ToString();
url = SetUrlParam(url, name, value); url = SetUrlParam(url, name, value);
} }
return url; return url;
} }
public static string ToUrlParam(IDictionary<string, string> kvs) public static string ToUrlParam(IDictionary<string, string> kvs)
{ {
return string.Join("&", kvs.Select(m => $"{m.Key}={m.Value}")); return string.Join("&", kvs.Select(m => $"{m.Key}={m.Value}"));
} }
#endregion #endregion
} }
} }

View File

@@ -1,110 +1,110 @@
using System; using System;
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
namespace Hncore.Infrastructure.Common namespace Hncore.Infrastructure.Common
{ {
public class ValidateCodeHelper public class ValidateCodeHelper
{ {
public static string MakeCode(int length = 4) public static string MakeCode(int length = 4)
{ {
char[] allCharArray = new char[] { '2', '3', '4', '5', '6', '7', '8', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'W', 'X', 'Y', 'Z' }; char[] allCharArray = new char[] { '2', '3', '4', '5', '6', '7', '8', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'W', 'X', 'Y', 'Z' };
string randomCode = ""; string randomCode = "";
int temp = -1; int temp = -1;
Random rand = new Random(); Random rand = new Random();
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
if (temp != -1) if (temp != -1)
{ {
rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
} }
int t = rand.Next(allCharArray.Length); int t = rand.Next(allCharArray.Length);
if (temp == t) if (temp == t)
{ {
return MakeCode(length); return MakeCode(length);
} }
temp = t; temp = t;
randomCode += allCharArray[t]; randomCode += allCharArray[t];
} }
return randomCode; return randomCode;
} }
public static string MakeNumCode(int length = 4) public static string MakeNumCode(int length = 4)
{ {
char[] allCharArray = new char[] { '1','2', '3', '4', '5', '6', '7', '8','9'}; char[] allCharArray = new char[] { '1','2', '3', '4', '5', '6', '7', '8','9'};
string randomCode = ""; string randomCode = "";
int temp = -1; int temp = -1;
Random rand = new Random(); Random rand = new Random();
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
if (temp != -1) if (temp != -1)
{ {
rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
} }
int t = rand.Next(allCharArray.Length); int t = rand.Next(allCharArray.Length);
if (temp == t) if (temp == t)
{ {
return MakeNumCode(length); return MakeNumCode(length);
} }
temp = t; temp = t;
randomCode += allCharArray[t]; randomCode += allCharArray[t];
} }
return randomCode; return randomCode;
} }
public static string MakeCharCode(int length = 4) public static string MakeCharCode(int length = 4)
{ {
char[] allCharArray = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'W', 'X', 'Y', 'Z' }; char[] allCharArray = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'W', 'X', 'Y', 'Z' };
string randomCode = ""; string randomCode = "";
int temp = -1; int temp = -1;
Random rand = new Random(); Random rand = new Random();
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
if (temp != -1) if (temp != -1)
{ {
rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
} }
int t = rand.Next(allCharArray.Length); int t = rand.Next(allCharArray.Length);
if (temp == t) if (temp == t)
{ {
return MakeCharCode(length); return MakeCharCode(length);
} }
temp = t; temp = t;
randomCode += allCharArray[t]; randomCode += allCharArray[t];
} }
return randomCode; return randomCode;
} }
public static byte[] GenerateCodeImg(string code) public static byte[] GenerateCodeImg(string code)
{ {
int Gheight = (int)(code.Length * 15) + 10; int Gheight = (int)(code.Length * 15) + 10;
//gheight为图片宽度,根据字符长度自动更改图片宽度 //gheight为图片宽度,根据字符长度自动更改图片宽度
using (var img = new Bitmap(Gheight, 22)) using (var img = new Bitmap(Gheight, 22))
{ {
using (var g = Graphics.FromImage(img)) using (var g = Graphics.FromImage(img))
{ {
SolidBrush whiteBrush = new SolidBrush(Color.White); SolidBrush whiteBrush = new SolidBrush(Color.White);
g.FillRectangle(whiteBrush, 0, 0, Gheight, 22); g.FillRectangle(whiteBrush, 0, 0, Gheight, 22);
int i = 0; int i = 0;
foreach (char ch in code.ToCharArray()) foreach (char ch in code.ToCharArray())
{ {
g.DrawString(ch.ToString(), g.DrawString(ch.ToString(),
new Font("Arial", 13, FontStyle.Italic), new Font("Arial", 13, FontStyle.Italic),
new SolidBrush(Color.FromArgb(0, 0, 0)), new SolidBrush(Color.FromArgb(0, 0, 0)),
i * 15, i * 15,
0); 0);
i++; i++;
} }
//在矩形内绘制字串字串字体画笔颜色左上x.左上y //在矩形内绘制字串字串字体画笔颜色左上x.左上y
System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.MemoryStream ms = new System.IO.MemoryStream();
img.Save(ms, ImageFormat.Jpeg); img.Save(ms, ImageFormat.Jpeg);
return ms.ToArray(); return ms.ToArray();
} }
} }
} }
} }
} }

View File

@@ -1,9 +1,9 @@
namespace Hncore.Infrastructure.DDD namespace Hncore.Infrastructure.DDD
{ {
public abstract class AggregateRoot<TId> : Entity<TId>, IAggregateRoot<TId> public abstract class AggregateRoot<TId> : Entity<TId>, IAggregateRoot<TId>
{ {
public AggregateRoot() public AggregateRoot()
{ {
} }
} }
} }

View File

@@ -1,48 +1,48 @@
using System; using System;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
namespace Hncore.Infrastructure.DDD namespace Hncore.Infrastructure.DDD
{ {
/// <summary> /// <summary>
/// 实现模型抽象基类 /// 实现模型抽象基类
/// </summary> /// </summary>
/// <typeparam name="TId">主键数据类型</typeparam> /// <typeparam name="TId">主键数据类型</typeparam>
public abstract class Entity<TId> : IEntity<TId> public abstract class Entity<TId> : IEntity<TId>
{ {
/// <summary> /// <summary>
/// 记录数据库主键ID /// 记录数据库主键ID
/// </summary> /// </summary>
[JsonProperty("Id")] [JsonProperty("Id")]
public virtual TId Id { get; set; } public virtual TId Id { get; set; }
} }
public abstract class EntityWithTime<TId> : Entity<TId> public abstract class EntityWithTime<TId> : Entity<TId>
{ {
/// <summary> /// <summary>
/// 记录添加(创建)时间 /// 记录添加(创建)时间
/// </summary> /// </summary>
public virtual DateTime CreateTime { get; set; } = DateTime.Now; public virtual DateTime CreateTime { get; set; } = DateTime.Now;
/// <summary> /// <summary>
/// 记录最后更新时间 /// 记录最后更新时间
/// </summary> /// </summary>
public virtual DateTime UpdateTime { get; set; } = DateTime.Now; public virtual DateTime UpdateTime { get; set; } = DateTime.Now;
/// <summary> /// <summary>
/// 记录软删除标记0.代表正常1.代表已删除 /// 记录软删除标记0.代表正常1.代表已删除
/// </summary> /// </summary>
public virtual int DeleteTag { get; set; } public virtual int DeleteTag { get; set; }
} }
public abstract class EntityWithDelete<TId> : Entity<TId>,ISoftDelete public abstract class EntityWithDelete<TId> : Entity<TId>,ISoftDelete
{ {
/// <summary> /// <summary>
/// 记录软删除标记0.代表正常1.代表已删除 /// 记录软删除标记0.代表正常1.代表已删除
/// </summary> /// </summary>
public virtual int DeleteTag { get; set; } = 0; public virtual int DeleteTag { get; set; } = 0;
} }
} }

View File

@@ -1,6 +1,6 @@
namespace Hncore.Infrastructure.DDD namespace Hncore.Infrastructure.DDD
{ {
public interface IAggregateRoot<TId> : IEntity<TId> public interface IAggregateRoot<TId> : IEntity<TId>
{ {
} }
} }

View File

@@ -1,16 +1,16 @@
using System; using System;
namespace Hncore.Infrastructure.DDD namespace Hncore.Infrastructure.DDD
{ {
public interface IEntity public interface IEntity
{ {
} }
public interface IEntity<TId>: IEntity public interface IEntity<TId>: IEntity
{ {
TId Id TId Id
{ {
get; get;
} }
} }
} }

View File

@@ -1,40 +1,40 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using Hncore.Infrastructure.Data; using Hncore.Infrastructure.Data;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace Hncore.Infrastructure.DDD namespace Hncore.Infrastructure.DDD
{ {
public interface IQuery<TEntity,TId> where TEntity : IEntity<TId> public interface IQuery<TEntity,TId> where TEntity : IEntity<TId>
{ {
TEntity GetOne(Expression<Func<TEntity, bool>> condition); TEntity GetOne(Expression<Func<TEntity, bool>> condition);
Task<TEntity> GetOneAsync(Expression<Func<TEntity, bool>> condition); Task<TEntity> GetOneAsync(Expression<Func<TEntity, bool>> condition);
PageData<TEntity> GetList(Expression<Func<TEntity, bool>> condition, int pagesize, int pageindex, bool istotal); PageData<TEntity> GetList(Expression<Func<TEntity, bool>> condition, int pagesize, int pageindex, bool istotal);
Task<PageData<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> condition, int pagesize, int pageindex, bool istotal); Task<PageData<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> condition, int pagesize, int pageindex, bool istotal);
List<TEntity> GetList(Expression<Func<TEntity, bool>> condition); List<TEntity> GetList(Expression<Func<TEntity, bool>> condition);
Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> condition); Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> condition);
bool Exists(Expression<Func<TEntity, bool>> condition); bool Exists(Expression<Func<TEntity, bool>> condition);
Task<bool> ExistsAsync(Expression<Func<TEntity, bool>> condition); Task<bool> ExistsAsync(Expression<Func<TEntity, bool>> condition);
List<TEntity> TopN(Expression<Func<TEntity, bool>> condition, int topN); List<TEntity> TopN(Expression<Func<TEntity, bool>> condition, int topN);
Task<List<TEntity>> TopNAsync(Expression<Func<TEntity, bool>> condition, int topN); Task<List<TEntity>> TopNAsync(Expression<Func<TEntity, bool>> condition, int topN);
IQueryable<TEntity> GetListQueryable(Expression<Func<TEntity, bool>> condition); IQueryable<TEntity> GetListQueryable(Expression<Func<TEntity, bool>> condition);
IQueryable<TEntity> GetQueryable(); IQueryable<TEntity> GetQueryable();
DbContext DbContext(); DbContext DbContext();
} }
} }

View File

@@ -1,43 +1,43 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Hncore.Infrastructure.DDD namespace Hncore.Infrastructure.DDD
{ {
public interface IRepository<TEntity, TId> where TEntity : IEntity<TId> public interface IRepository<TEntity, TId> where TEntity : IEntity<TId>
{ {
TEntity FindById(TId id); TEntity FindById(TId id);
Task<TEntity> FindByIdAsync(TId id); Task<TEntity> FindByIdAsync(TId id);
void Add(TEntity entity); void Add(TEntity entity);
Task AddAsync(TEntity entity); Task AddAsync(TEntity entity);
/// <summary> /// <summary>
/// 批量添加 /// 批量添加
/// </summary> /// </summary>
/// <param name="entity"></param> /// <param name="entity"></param>
void AddRange(List<TEntity> entity); void AddRange(List<TEntity> entity);
/// <summary> /// <summary>
/// 批量添加 /// 批量添加
/// </summary> /// </summary>
/// <param name="entity"></param> /// <param name="entity"></param>
Task AddRangeAsync(List<TEntity> entity); Task AddRangeAsync(List<TEntity> entity);
/// <summary> /// <summary>
/// 批量修改 /// 批量修改
/// </summary> /// </summary>
/// <param name="entity"></param> /// <param name="entity"></param>
void UpdateRange(List<TEntity> entity); void UpdateRange(List<TEntity> entity);
/// <summary> /// <summary>
/// 批量删除 /// 批量删除
/// </summary> /// </summary>
/// <param name="entity"></param> /// <param name="entity"></param>
void RemoveRange(List<TEntity> entity); void RemoveRange(List<TEntity> entity);
void Remove(TEntity entity); void Remove(TEntity entity);
void Update(TEntity entity); void Update(TEntity entity);
IQueryable<TEntity> GetQueryable(); IQueryable<TEntity> GetQueryable();
} }
} }

View File

@@ -1,7 +1,7 @@
namespace Hncore.Infrastructure.DDD namespace Hncore.Infrastructure.DDD
{ {
public interface ISoftDelete public interface ISoftDelete
{ {
int DeleteTag { get; set; } int DeleteTag { get; set; }
} }
} }

View File

@@ -1,7 +1,7 @@
namespace Hncore.Infrastructure.DDD namespace Hncore.Infrastructure.DDD
{ {
public interface ITenant public interface ITenant
{ {
int TenantId { get; set; } int TenantId { get; set; }
} }
} }

View File

@@ -1,7 +1,7 @@
namespace Hncore.Infrastructure.DDD namespace Hncore.Infrastructure.DDD
{ {
public interface ITenantStore public interface ITenantStore
{ {
int StoreId { get; set; } int StoreId { get; set; }
} }
} }

View File

@@ -1,29 +1,29 @@
using System; using System;
using Hncore.Infrastructure.WebApi; using Hncore.Infrastructure.WebApi;
namespace Hncore.Infrastructure.Data namespace Hncore.Infrastructure.Data
{ {
public class BusinessException : Exception public class BusinessException : Exception
{ {
public ResultCode Code { get; } = ResultCode.C_UNKNOWN_ERROR; public ResultCode Code { get; } = ResultCode.C_UNKNOWN_ERROR;
public BusinessException(string message) : base(message) public BusinessException(string message) : base(message)
{ {
} }
public BusinessException(ResultCode code, string message = "") : base(message) public BusinessException(ResultCode code, string message = "") : base(message)
{ {
Code = code; Code = code;
} }
public static void Throw(string message = "") public static void Throw(string message = "")
{ {
throw new BusinessException(message); throw new BusinessException(message);
} }
public static void Throw(ResultCode code, string message = "") public static void Throw(ResultCode code, string message = "")
{ {
throw new BusinessException(code, message); throw new BusinessException(code, message);
} }
} }
} }

View File

@@ -1,17 +1,17 @@
using System; using System;
using System.Net; using System.Net;
namespace Hncore.Infrastructure.Data namespace Hncore.Infrastructure.Data
{ {
public class HttpException: Exception public class HttpException: Exception
{ {
public HttpStatusCode HttpStatusCode { get; set; } public HttpStatusCode HttpStatusCode { get; set; }
public string Content { get; set; } public string Content { get; set; }
public HttpException(HttpStatusCode httpStatusCode) public HttpException(HttpStatusCode httpStatusCode)
{ {
HttpStatusCode = httpStatusCode; HttpStatusCode = httpStatusCode;
} }
} }
} }

View File

@@ -1,40 +1,40 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using System.Collections.Generic; using System.Collections.Generic;
namespace Hncore.Infrastructure.Data namespace Hncore.Infrastructure.Data
{ {
public interface IPageData public interface IPageData
{ {
/// <summary> /// <summary>
/// 总行数 /// 总行数
/// </summary> /// </summary>
int RowCount { get; set; } int RowCount { get; set; }
} }
/// <summary> /// <summary>
/// 分页数据集合 /// 分页数据集合
/// </summary> /// </summary>
public class PageData<T> public class PageData<T>
{ {
public PageData() public PageData()
{ {
List = new List<T>(); List = new List<T>();
} }
public PageData(int rowCount, List<T> data) public PageData(int rowCount, List<T> data)
{ {
this.RowCount = rowCount; this.RowCount = rowCount;
this.List = data; this.List = data;
} }
/// <summary> /// <summary>
/// 总行数 /// 总行数
/// </summary> /// </summary>
public int RowCount { get; set; } public int RowCount { get; set; }
/// <summary> /// <summary>
/// 当前页数据集合 /// 当前页数据集合
/// </summary> /// </summary>
public List<T> List { get; set; } public List<T> List { get; set; }
} }
} }

View File

@@ -1,25 +1,25 @@
using System.Linq; using System.Linq;
namespace Hncore.Infrastructure.Data namespace Hncore.Infrastructure.Data
{ {
/// <summary> /// <summary>
/// 分页数据源 /// 分页数据源
/// </summary> /// </summary>
public class PageQueryable<T> public class PageQueryable<T>
{ {
/// <summary> /// <summary>
/// 总页数 /// 总页数
/// </summary> /// </summary>
public int RowCount { get; set; } public int RowCount { get; set; }
/// <summary> /// <summary>
/// 当前页数据集合 /// 当前页数据集合
/// </summary> /// </summary>
public IQueryable<T> Data { get; set; } public IQueryable<T> Data { get; set; }
public PageData<T> ToList() public PageData<T> ToList()
{ {
return new PageData<T>(){List=Data.ToList(),RowCount=RowCount}; return new PageData<T>(){List=Data.ToList(),RowCount=RowCount};
} }
} }
} }

View File

@@ -1,48 +1,48 @@
using System; using System;
namespace Hncore.Infrastructure.Data namespace Hncore.Infrastructure.Data
{ {
public class ResultMessage public class ResultMessage
{ {
public ResultMessage() public ResultMessage()
{ {
Success = true; Success = true;
} }
public string Message { get; set; } = ""; public string Message { get; set; } = "";
public bool Success { get; set; } public bool Success { get; set; }
public string Code { get; set; } = ""; public string Code { get; set; } = "";
public Action CallBack { get; set; } = null; public Action CallBack { get; set; } = null;
public object Data { get; set; } = null; public object Data { get; set; } = null;
public ResultMessage(bool success, string message) public ResultMessage(bool success, string message)
{ {
this.Success = success; this.Success = success;
this.Message = message; this.Message = message;
} }
public ResultMessage(bool success, string message,object data) public ResultMessage(bool success, string message,object data)
{ {
this.Success = success; this.Success = success;
this.Message = message; this.Message = message;
this.Data = data; this.Data = data;
} }
public ResultMessage(bool success) public ResultMessage(bool success)
{ {
this.Success = success; this.Success = success;
} }
public ResultMessage(string message) public ResultMessage(string message)
{ {
Success = true; Success = true;
this.Message = message; this.Message = message;
} }
} }
} }

View File

@@ -1,24 +1,24 @@
using System; using System;
namespace Hncore.Infrastructure.Data namespace Hncore.Infrastructure.Data
{ {
public class TransactionsHelper public class TransactionsHelper
{ {
public static void NoLockInvokeDB(Action action) public static void NoLockInvokeDB(Action action)
{ {
var transactionOptions = new System.Transactions.TransactionOptions(); var transactionOptions = new System.Transactions.TransactionOptions();
transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
using (var transactionScope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOptions)) using (var transactionScope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOptions))
{ {
try try
{ {
action(); action();
} }
finally finally
{ {
transactionScope.Complete(); transactionScope.Complete();
} }
} }
} }
} }
} }

View File

@@ -1,119 +1,119 @@
using Hncore.Infrastructure.Common; using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.DDD; using Hncore.Infrastructure.DDD;
using Hncore.Infrastructure.Extension; using Hncore.Infrastructure.Extension;
using Hncore.Infrastructure.Serializer; using Hncore.Infrastructure.Serializer;
using Hncore.Infrastructure.WebApi; using Hncore.Infrastructure.WebApi;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Linq; using System.Linq;
namespace Hncore.Infrastructure.EF namespace Hncore.Infrastructure.EF
{ {
/// <summary> /// <summary>
/// 上下文构造器的基类 /// 上下文构造器的基类
/// </summary> /// </summary>
public class DbContextBase : DbContext public class DbContextBase : DbContext
{ {
private IHttpContextAccessor _httpContextAccessor; private IHttpContextAccessor _httpContextAccessor;
private bool _enabledLog = false; private bool _enabledLog = false;
private int _tenantid = 0; private int _tenantid = 0;
private int _storeId = 0; private int _storeId = 0;
private bool _root = false; private bool _root = false;
private bool _allow = false; private bool _allow = false;
public DbContextBase(DbContextOptions options, IHttpContextAccessor httpContextAccessor) : base(options) public DbContextBase(DbContextOptions options, IHttpContextAccessor httpContextAccessor) : base(options)
{ {
_httpContextAccessor = httpContextAccessor; _httpContextAccessor = httpContextAccessor;
if (UseTenantFilter()) if (UseTenantFilter())
{ {
ManageUserInfo manageUserInfo = _httpContextAccessor.HttpContext.Request.GetManageUserInfo(); ManageUserInfo manageUserInfo = _httpContextAccessor.HttpContext.Request.GetManageUserInfo();
if (manageUserInfo != null) if (manageUserInfo != null)
{ {
_tenantid = manageUserInfo.TenantId; _tenantid = manageUserInfo.TenantId;
_storeId = manageUserInfo.StoreId; _storeId = manageUserInfo.StoreId;
} }
} }
else else
{ {
_allow = true; _allow = true;
} }
} }
private bool UseTenantFilter() private bool UseTenantFilter()
{ {
if (_httpContextAccessor == null || _httpContextAccessor.HttpContext == null) if (_httpContextAccessor == null || _httpContextAccessor.HttpContext == null)
{ {
return false; return false;
} }
return _httpContextAccessor.HttpContext.Items.ContainsKey("AuthPassedFilterName") return _httpContextAccessor.HttpContext.Items.ContainsKey("AuthPassedFilterName")
&& _httpContextAccessor.HttpContext.Items["AuthPassedFilterName"].ToString() == "ManageAuth"; && _httpContextAccessor.HttpContext.Items["AuthPassedFilterName"].ToString() == "ManageAuth";
} }
/// <summary> /// <summary>
/// model构造器 创建实体映射 /// model构造器 创建实体映射
/// </summary> /// </summary>
/// <param name="modelBuilder"></param> /// <param name="modelBuilder"></param>
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
base.OnModelCreating(modelBuilder); base.OnModelCreating(modelBuilder);
if (!EnvironmentVariableHelper.IsAspNetCoreProduction) if (!EnvironmentVariableHelper.IsAspNetCoreProduction)
{ {
LogHelper.Debug("进入DbContextBase的OnModelCreating函数", LogHelper.Debug("进入DbContextBase的OnModelCreating函数",
$"UseGlobalManageAuthFilter:{GlobalData.UseGlobalManageAuthFilter}\ntoken:{_httpContextAccessor?.HttpContext?.Request?.GetManageUserInfo()?.ToJson(true)}"); $"UseGlobalManageAuthFilter:{GlobalData.UseGlobalManageAuthFilter}\ntoken:{_httpContextAccessor?.HttpContext?.Request?.GetManageUserInfo()?.ToJson(true)}");
} }
foreach (var type in modelBuilder.Model.GetEntityTypes()) foreach (var type in modelBuilder.Model.GetEntityTypes())
{ {
if (typeof(ISoftDelete).IsAssignableFrom(type.ClrType)) if (typeof(ISoftDelete).IsAssignableFrom(type.ClrType))
{ {
modelBuilder.Entity(type.ClrType).AddQueryFilter<ISoftDelete>(t => t.DeleteTag == 0); modelBuilder.Entity(type.ClrType).AddQueryFilter<ISoftDelete>(t => t.DeleteTag == 0);
} }
//if (typeof(ITenant).IsAssignableFrom(type.ClrType)) //if (typeof(ITenant).IsAssignableFrom(type.ClrType))
//{ //{
// modelBuilder.Entity(type.ClrType).AddQueryFilter<ITenant>(t => _allow || t.TenantId == _tenantid); // modelBuilder.Entity(type.ClrType).AddQueryFilter<ITenant>(t => _allow || t.TenantId == _tenantid);
//} //}
//if (typeof(ITenantStore).IsAssignableFrom(type.ClrType)) //if (typeof(ITenantStore).IsAssignableFrom(type.ClrType))
//{ //{
// modelBuilder.Entity(type.ClrType) // modelBuilder.Entity(type.ClrType)
// .AddQueryFilter<ITenantStore>(t => _storeId == 0|| t.StoreId==_storeId); // .AddQueryFilter<ITenantStore>(t => _storeId == 0|| t.StoreId==_storeId);
//} //}
} }
} }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{ {
if (_httpContextAccessor?.HttpContext?.Request?.Headers != null) if (_httpContextAccessor?.HttpContext?.Request?.Headers != null)
{ {
if (_httpContextAccessor.HttpContext.Request.Headers.ContainsKey("enable-ef-log")) if (_httpContextAccessor.HttpContext.Request.Headers.ContainsKey("enable-ef-log"))
{ {
if (_httpContextAccessor.HttpContext.Request.Headers.ContainsKey("enable-ef-log").ToBool()) if (_httpContextAccessor.HttpContext.Request.Headers.ContainsKey("enable-ef-log").ToBool())
{ {
if (_enabledLog == false) if (_enabledLog == false)
{ {
optionsBuilder.EnableDebugTrace(_httpContextAccessor); optionsBuilder.EnableDebugTrace(_httpContextAccessor);
_enabledLog = true; _enabledLog = true;
} }
} }
} }
} }
#if DEBUG #if DEBUG
Console.WriteLine("当前为debug模式开启EF DebugTrace"); Console.WriteLine("当前为debug模式开启EF DebugTrace");
optionsBuilder.EnableDebugTrace(null); optionsBuilder.EnableDebugTrace(null);
#endif #endif
} }
} }
} }

View File

@@ -1,228 +1,228 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
using System.Data.Common; using System.Data.Common;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
/// <summary> /// <summary>
/// EF上下文对象扩展类 /// EF上下文对象扩展类
/// </summary> /// </summary>
/// ///
public static class DbContextExtension public static class DbContextExtension
{ {
/// <summary> /// <summary>
/// 执行SQL返回受影响的行数 /// 执行SQL返回受影响的行数
/// </summary> /// </summary>
public static int ExecSqlNoQuery(this DbContext db, string sql, DbParameter[] sqlParams = null) public static int ExecSqlNoQuery(this DbContext db, string sql, DbParameter[] sqlParams = null)
{ {
return ExecuteNoQuery(db, sql, sqlParams); return ExecuteNoQuery(db, sql, sqlParams);
} }
/// <summary> /// <summary>
/// 执行存储过程返回IEnumerable数据集 /// 执行存储过程返回IEnumerable数据集
/// </summary> /// </summary>
public static IEnumerable<T> ExecProcQuery<T>(this DbContext db, string sql, DbParameter[] sqlParams = null) where T : new() public static IEnumerable<T> ExecProcQuery<T>(this DbContext db, string sql, DbParameter[] sqlParams = null) where T : new()
{ {
return Execute<T>(db, sql, CommandType.StoredProcedure, sqlParams); return Execute<T>(db, sql, CommandType.StoredProcedure, sqlParams);
} }
/// <summary> /// <summary>
/// 执行存储过程返回IEnumerable数据集 /// 执行存储过程返回IEnumerable数据集
/// </summary> /// </summary>
public static DataSet ExecProcDataSet(this DbContext db, string sql, DbParameter[] sqlParams = null) public static DataSet ExecProcDataSet(this DbContext db, string sql, DbParameter[] sqlParams = null)
{ {
return ExecuteDataSet(db, sql, CommandType.StoredProcedure, sqlParams); return ExecuteDataSet(db, sql, CommandType.StoredProcedure, sqlParams);
} }
/// <summary> /// <summary>
/// 执行sql返回IEnumerable数据集 /// 执行sql返回IEnumerable数据集
/// </summary> /// </summary>
public static IEnumerable<T> ExecSqlQuery<T>(this DbContext db, string sql, DbParameter[] sqlParams = null) where T : new() public static IEnumerable<T> ExecSqlQuery<T>(this DbContext db, string sql, DbParameter[] sqlParams = null) where T : new()
{ {
return Execute<T>(db, sql, CommandType.Text, sqlParams); return Execute<T>(db, sql, CommandType.Text, sqlParams);
} }
/// <summary> /// <summary>
/// 执行SQL并返回受影响的行数 /// 执行SQL并返回受影响的行数
/// </summary> /// </summary>
/// <param name="db"></param> /// <param name="db"></param>
/// <param name="sql"></param> /// <param name="sql"></param>
/// <param name="sqlParams"></param> /// <param name="sqlParams"></param>
/// <returns></returns> /// <returns></returns>
private static int ExecuteNoQuery(this DbContext db, string sql, DbParameter[] sqlParams) private static int ExecuteNoQuery(this DbContext db, string sql, DbParameter[] sqlParams)
{ {
DbConnection connection = db.Database.GetDbConnection(); DbConnection connection = db.Database.GetDbConnection();
DbCommand cmd = connection.CreateCommand(); DbCommand cmd = connection.CreateCommand();
int result = 0; int result = 0;
db.Database.OpenConnection(); db.Database.OpenConnection();
cmd.CommandText = sql; cmd.CommandText = sql;
cmd.CommandType = CommandType.Text; cmd.CommandType = CommandType.Text;
if (sqlParams != null) if (sqlParams != null)
{ {
cmd.Parameters.AddRange(sqlParams); cmd.Parameters.AddRange(sqlParams);
} }
result = cmd.ExecuteNonQuery(); result = cmd.ExecuteNonQuery();
db.Database.CloseConnection(); db.Database.CloseConnection();
return result; return result;
} }
/// <summary> /// <summary>
/// 执行SQL返回查询结果 /// 执行SQL返回查询结果
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="db"></param> /// <param name="db"></param>
/// <param name="sql"></param> /// <param name="sql"></param>
/// <param name="type"></param> /// <param name="type"></param>
/// <param name="sqlParams"></param> /// <param name="sqlParams"></param>
/// <returns></returns> /// <returns></returns>
private static IEnumerable<T> Execute<T>(this DbContext db, string sql, CommandType type, DbParameter[] sqlParams) where T : new() private static IEnumerable<T> Execute<T>(this DbContext db, string sql, CommandType type, DbParameter[] sqlParams) where T : new()
{ {
DbConnection connection = db.Database.GetDbConnection(); DbConnection connection = db.Database.GetDbConnection();
DbCommand cmd = connection.CreateCommand(); DbCommand cmd = connection.CreateCommand();
DataTable dt = new DataTable(); DataTable dt = new DataTable();
try try
{ {
db.Database.OpenConnection(); db.Database.OpenConnection();
cmd.CommandText = sql; cmd.CommandText = sql;
cmd.CommandType = type; cmd.CommandType = type;
if (sqlParams != null) if (sqlParams != null)
{ {
cmd.Parameters.AddRange(sqlParams); cmd.Parameters.AddRange(sqlParams);
} }
using (DbDataReader reader = cmd.ExecuteReader()) using (DbDataReader reader = cmd.ExecuteReader())
{ {
dt.Load(reader); dt.Load(reader);
} }
} }
finally finally
{ {
db.Database.CloseConnection(); db.Database.CloseConnection();
} }
return dt.ToCollection<T>(); return dt.ToCollection<T>();
} }
/// <summary> /// <summary>
/// 执行SQL返回查询结果 /// 执行SQL返回查询结果
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="db"></param> /// <param name="db"></param>
/// <param name="sql"></param> /// <param name="sql"></param>
/// <param name="type"></param> /// <param name="type"></param>
/// <param name="sqlParams"></param> /// <param name="sqlParams"></param>
/// <returns></returns> /// <returns></returns>
private static DataSet ExecuteDataSet(this DbContext db, string sql, CommandType type, DbParameter[] sqlParams) private static DataSet ExecuteDataSet(this DbContext db, string sql, CommandType type, DbParameter[] sqlParams)
{ {
DbConnection connection = db.Database.GetDbConnection(); DbConnection connection = db.Database.GetDbConnection();
DbCommand cmd = connection.CreateCommand(); DbCommand cmd = connection.CreateCommand();
db.Database.OpenConnection(); db.Database.OpenConnection();
cmd.CommandText = sql; cmd.CommandText = sql;
cmd.CommandType = type; cmd.CommandType = type;
if (sqlParams != null) if (sqlParams != null)
{ {
cmd.Parameters.AddRange(sqlParams); cmd.Parameters.AddRange(sqlParams);
} }
DataSet ds = new DataSet(); DataSet ds = new DataSet();
using (DbDataReader reader = cmd.ExecuteReader()) using (DbDataReader reader = cmd.ExecuteReader())
{ {
ds.Load(reader,LoadOption.PreserveChanges,"data","info"); ds.Load(reader,LoadOption.PreserveChanges,"data","info");
} }
db.Database.CloseConnection(); db.Database.CloseConnection();
return ds; return ds;
} }
} }
/// <summary> /// <summary>
/// DataTable扩展类 /// DataTable扩展类
/// </summary> /// </summary>
/// ///
public static class ExtendDataTable public static class ExtendDataTable
{ {
/// <summary> /// <summary>
/// 将对象转换成DataTable /// 将对象转换成DataTable
/// </summary> /// </summary>
/// <typeparam name="T">源对象类型</typeparam> /// <typeparam name="T">源对象类型</typeparam>
/// <param name="data">源对象列表</param> /// <param name="data">源对象列表</param>
/// <returns>转换后的DataTable</returns> /// <returns>转换后的DataTable</returns>
/// ///
public static DataTable ToDataTable<T>(this IEnumerable<T> data) public static DataTable ToDataTable<T>(this IEnumerable<T> data)
{ {
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
var table = new DataTable(); var table = new DataTable();
foreach (PropertyDescriptor prop in properties) foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data) foreach (T item in data)
{ {
DataRow row = table.NewRow(); DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties) foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value; row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row); table.Rows.Add(row);
} }
return table; return table;
} }
/// <summary> /// <summary>
/// 将DataTable首行转换成目标对象 /// 将DataTable首行转换成目标对象
/// </summary> /// </summary>
/// <typeparam name="T">目标对象类型</typeparam> /// <typeparam name="T">目标对象类型</typeparam>
/// <param name="dt">源DataTable对象</param> /// <param name="dt">源DataTable对象</param>
/// <returns>转换后的目标对象</returns> /// <returns>转换后的目标对象</returns>
/// ///
public static T ToEntity<T>(this DataTable dt) where T : new() public static T ToEntity<T>(this DataTable dt) where T : new()
{ {
IEnumerable<T> entities = dt.ToCollection<T>(); IEnumerable<T> entities = dt.ToCollection<T>();
return entities.FirstOrDefault(); return entities.FirstOrDefault();
} }
/// <summary> /// <summary>
/// 将DataTable转换成目标对象列表 /// 将DataTable转换成目标对象列表
/// </summary> /// </summary>
/// <typeparam name="T">目标对象类型</typeparam> /// <typeparam name="T">目标对象类型</typeparam>
/// <param name="dt">源DataTable对象</param> /// <param name="dt">源DataTable对象</param>
/// <returns>转换后的目标对象列表</returns> /// <returns>转换后的目标对象列表</returns>
/// ///
public static IEnumerable<T> ToCollection<T>(this DataTable dt) where T : new() public static IEnumerable<T> ToCollection<T>(this DataTable dt) where T : new()
{ {
if (dt == null || dt.Rows.Count == 0) if (dt == null || dt.Rows.Count == 0)
{ {
return Enumerable.Empty<T>(); return Enumerable.Empty<T>();
} }
IList<T> ts = new List<T>(); IList<T> ts = new List<T>();
// 获得此模型的类型 // 获得此模型的类型
Type type = typeof(T); Type type = typeof(T);
string tempName = string.Empty; string tempName = string.Empty;
foreach (DataRow dr in dt.Rows) foreach (DataRow dr in dt.Rows)
{ {
T t = new T(); T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties(); PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys) foreach (PropertyInfo pi in propertys)
{ {
tempName = pi.Name; tempName = pi.Name;
//检查DataTable是否包含此列列名==对象的属性名) //检查DataTable是否包含此列列名==对象的属性名)
if (dt.Columns.Contains(tempName)) if (dt.Columns.Contains(tempName))
{ {
// 判断此属性是否有Setter // 判断此属性是否有Setter
if (!pi.CanWrite) continue;//该属性不可写,直接跳出 if (!pi.CanWrite) continue;//该属性不可写,直接跳出
object value = dr[tempName]; object value = dr[tempName];
if (value != DBNull.Value) if (value != DBNull.Value)
{ {
if (!pi.PropertyType.IsGenericType) if (!pi.PropertyType.IsGenericType)
{ {
value = Convert.ChangeType(value, pi.PropertyType); value = Convert.ChangeType(value, pi.PropertyType);
pi.SetValue(t, value); pi.SetValue(t, value);
} }
else { else {
Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition(); Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>)) if (genericTypeDefinition == typeof(Nullable<>))
{ {
value = Convert.ChangeType(value, Nullable.GetUnderlyingType(pi.PropertyType)); value = Convert.ChangeType(value, Nullable.GetUnderlyingType(pi.PropertyType));
pi.SetValue(t, value); pi.SetValue(t, value);
} }
} }
} }
} }
} }
ts.Add(t); ts.Add(t);
} }
return ts; return ts;
} }
} }
} }

View File

@@ -1,122 +1,122 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Hncore.Infrastructure.Data; using Hncore.Infrastructure.Data;
using Hncore.Infrastructure.DDD; using Hncore.Infrastructure.DDD;
using Hncore.Infrastructure.EntitiesExtension; using Hncore.Infrastructure.EntitiesExtension;
namespace Hncore.Infrastructure.EF namespace Hncore.Infrastructure.EF
{ {
public static class DbSetExtension public static class DbSetExtension
{ {
public static TEntity GetOne<TEntity>(this DbSet<TEntity> dbSet, Expression<Func<TEntity, bool>> exp) public static TEntity GetOne<TEntity>(this DbSet<TEntity> dbSet, Expression<Func<TEntity, bool>> exp)
where TEntity : class where TEntity : class
{ {
return dbSet.AsNoTracking().FirstOrDefault(exp); return dbSet.AsNoTracking().FirstOrDefault(exp);
} }
public static Task<TEntity> GetOneAsync<TEntity>(this DbSet<TEntity> dbSet, public static Task<TEntity> GetOneAsync<TEntity>(this DbSet<TEntity> dbSet,
Expression<Func<TEntity, bool>> exp) where TEntity : class Expression<Func<TEntity, bool>> exp) where TEntity : class
{ {
return dbSet.AsNoTracking().FirstOrDefaultAsync(exp); return dbSet.AsNoTracking().FirstOrDefaultAsync(exp);
} }
public static PageData<TEntity> GetList<TEntity, TId>(this DbSet<TEntity> dbSet, public static PageData<TEntity> GetList<TEntity, TId>(this DbSet<TEntity> dbSet,
Expression<Func<TEntity, bool>> exp, int pagesize, int pageindex, bool istotal) Expression<Func<TEntity, bool>> exp, int pagesize, int pageindex, bool istotal)
where TEntity : class, IEntity<TId> where TEntity : class, IEntity<TId>
{ {
return dbSet.AsNoTracking() return dbSet.AsNoTracking()
.Where(exp) .Where(exp)
.OrderByDescending(t => t.Id) .OrderByDescending(t => t.Id)
.ListPager(pagesize, pageindex, istotal); .ListPager(pagesize, pageindex, istotal);
} }
public static Task<PageData<TEntity>> GetListAsync<TEntity>(this DbSet<TEntity> dbSet, public static Task<PageData<TEntity>> GetListAsync<TEntity>(this DbSet<TEntity> dbSet,
Expression<Func<TEntity, bool>> exp, int pagesize, int pageindex, bool istotal) Expression<Func<TEntity, bool>> exp, int pagesize, int pageindex, bool istotal)
where TEntity : class where TEntity : class
{ {
return dbSet.AsNoTracking() return dbSet.AsNoTracking()
.Where(exp) .Where(exp)
.ListPagerAsync(pagesize, pageindex, istotal); .ListPagerAsync(pagesize, pageindex, istotal);
} }
public static List<TEntity> GetList<TEntity>(this DbSet<TEntity> dbSet, Expression<Func<TEntity, bool>> exp) public static List<TEntity> GetList<TEntity>(this DbSet<TEntity> dbSet, Expression<Func<TEntity, bool>> exp)
where TEntity : class, IEntity where TEntity : class, IEntity
{ {
return dbSet.AsNoTracking() return dbSet.AsNoTracking()
.Where(exp) .Where(exp)
.ToList(); .ToList();
} }
public static Task<List<TEntity>> GetListAsync<TEntity>(this DbSet<TEntity> dbSet, public static Task<List<TEntity>> GetListAsync<TEntity>(this DbSet<TEntity> dbSet,
Expression<Func<TEntity, bool>> exp) Expression<Func<TEntity, bool>> exp)
where TEntity : class, IEntity where TEntity : class, IEntity
{ {
return dbSet.AsNoTracking() return dbSet.AsNoTracking()
.Where(exp) .Where(exp)
.ToListAsync(); .ToListAsync();
} }
public static IQueryable<TEntity> GetListQueryable<TEntity>(this DbSet<TEntity> dbSet, public static IQueryable<TEntity> GetListQueryable<TEntity>(this DbSet<TEntity> dbSet,
Expression<Func<TEntity, bool>> exp) Expression<Func<TEntity, bool>> exp)
where TEntity : class, IEntity where TEntity : class, IEntity
{ {
return dbSet.AsNoTracking() return dbSet.AsNoTracking()
.Where(exp); .Where(exp);
} }
public static bool Exists<TEntity>(this DbSet<TEntity> dbSet, Expression<Func<TEntity, bool>> exp) public static bool Exists<TEntity>(this DbSet<TEntity> dbSet, Expression<Func<TEntity, bool>> exp)
where TEntity : class, IEntity where TEntity : class, IEntity
{ {
return dbSet.AsNoTracking() return dbSet.AsNoTracking()
.Any(exp); .Any(exp);
} }
public static Task<bool> ExistsAsync<TEntity>(this DbSet<TEntity> dbSet, public static Task<bool> ExistsAsync<TEntity>(this DbSet<TEntity> dbSet,
Expression<Func<TEntity, bool>> exp) Expression<Func<TEntity, bool>> exp)
where TEntity : class, IEntity where TEntity : class, IEntity
{ {
return dbSet.AsNoTracking() return dbSet.AsNoTracking()
.AnyAsync(exp); .AnyAsync(exp);
} }
public static List<TEntity> TopN<TEntity>(this DbSet<TEntity> dbSet, public static List<TEntity> TopN<TEntity>(this DbSet<TEntity> dbSet,
Expression<Func<TEntity, bool>> condition, int topN) Expression<Func<TEntity, bool>> condition, int topN)
where TEntity : class, IEntity where TEntity : class, IEntity
{ {
return dbSet.AsNoTracking() return dbSet.AsNoTracking()
.Where(condition) .Where(condition)
.TopN(topN) .TopN(topN)
.ToList(); .ToList();
} }
public static Task<List<TEntity>> TopNAsync<TEntity>(this DbSet<TEntity> dbSet, public static Task<List<TEntity>> TopNAsync<TEntity>(this DbSet<TEntity> dbSet,
Expression<Func<TEntity, bool>> condition, int topN) Expression<Func<TEntity, bool>> condition, int topN)
where TEntity : class, IEntity where TEntity : class, IEntity
{ {
return dbSet.AsNoTracking() return dbSet.AsNoTracking()
.Where(condition) .Where(condition)
.TopN(topN) .TopN(topN)
.ToListAsync(); .ToListAsync();
} }
public static IQueryable<TEntity> GetQueryable<TEntity>(this DbSet<TEntity> dbSet) where TEntity : class public static IQueryable<TEntity> GetQueryable<TEntity>(this DbSet<TEntity> dbSet) where TEntity : class
{ {
return dbSet.AsNoTracking(); return dbSet.AsNoTracking();
} }
public static TEntity FindById<TEntity>(this DbSet<TEntity> dbSet,object id) where TEntity : class public static TEntity FindById<TEntity>(this DbSet<TEntity> dbSet,object id) where TEntity : class
{ {
return dbSet.Find(id); return dbSet.Find(id);
} }
public static Task<TEntity> FindByIdAsync<TEntity>(this DbSet<TEntity> dbSet, object id) where TEntity : class public static Task<TEntity> FindByIdAsync<TEntity>(this DbSet<TEntity> dbSet, object id) where TEntity : class
{ {
return dbSet.FindAsync(id); return dbSet.FindAsync(id);
} }
} }
} }

View File

@@ -1,25 +1,25 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Hncore.Infrastructure.EF namespace Hncore.Infrastructure.EF
{ {
public interface IEntityMap public interface IEntityMap
{ {
void Map(ModelBuilder builder); void Map(ModelBuilder builder);
} }
public interface IEntityMap<TEntityType> : IEntityMap where TEntityType : class public interface IEntityMap<TEntityType> : IEntityMap where TEntityType : class
{ {
void Map(EntityTypeBuilder<TEntityType> builder); void Map(EntityTypeBuilder<TEntityType> builder);
} }
public abstract class EntityMapBase<T> : IEntityMap<T> where T : class public abstract class EntityMapBase<T> : IEntityMap<T> where T : class
{ {
public abstract void Map(EntityTypeBuilder<T> builder); public abstract void Map(EntityTypeBuilder<T> builder);
public void Map(ModelBuilder builder) public void Map(ModelBuilder builder)
{ {
Map(builder.Entity<T>()); Map(builder.Entity<T>());
} }
} }
} }

View File

@@ -1,47 +1,47 @@
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace Hncore.Infrastructure.EF namespace Hncore.Infrastructure.EF
{ {
public static class AutoMapExtensions public static class AutoMapExtensions
{ {
private static object syncRoot = new object(); private static object syncRoot = new object();
private static ConcurrentDictionary<IEntityMap, object> maps; private static ConcurrentDictionary<IEntityMap, object> maps;
public static void AutoMap(this ModelBuilder modelBuilder, Type assType) public static void AutoMap(this ModelBuilder modelBuilder, Type assType)
{ {
if (maps == null) if (maps == null)
{ {
lock (syncRoot) lock (syncRoot)
{ {
if (maps == null) if (maps == null)
{ {
maps = new ConcurrentDictionary<IEntityMap, object>(); maps = new ConcurrentDictionary<IEntityMap, object>();
Type mappingInterface = typeof(IEntityMap<>); Type mappingInterface = typeof(IEntityMap<>);
var mappingTypes = assType.GetTypeInfo().Assembly.GetTypes() var mappingTypes = assType.GetTypeInfo().Assembly.GetTypes()
.Where(x => !x.IsAbstract .Where(x => !x.IsAbstract
&& x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType
&& y.GetGenericTypeDefinition() == && y.GetGenericTypeDefinition() ==
mappingInterface)); mappingInterface));
foreach (var map in mappingTypes.Select(Activator.CreateInstance).Cast<IEntityMap>()) foreach (var map in mappingTypes.Select(Activator.CreateInstance).Cast<IEntityMap>())
{ {
maps.TryAdd(map, null); maps.TryAdd(map, null);
} }
} }
} }
} }
foreach (var map in maps.Keys) foreach (var map in maps.Keys)
{ {
map.Map(modelBuilder); map.Map(modelBuilder);
} }
} }
} }
} }

View File

@@ -1,121 +1,121 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Hncore.Infrastructure.Common; using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Extension; using Hncore.Infrastructure.Extension;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Hncore.Infrastructure.Core.Web; using Hncore.Infrastructure.Core.Web;
namespace Hncore.Infrastructure.EF namespace Hncore.Infrastructure.EF
{ {
public class TraceLogger : ILogger public class TraceLogger : ILogger
{ {
private readonly string categoryName; private readonly string categoryName;
private IHttpContextAccessor _httpContextAccessor; private IHttpContextAccessor _httpContextAccessor;
public TraceLogger(string categoryName, IHttpContextAccessor httpContextAccessor) public TraceLogger(string categoryName, IHttpContextAccessor httpContextAccessor)
{ {
this.categoryName = categoryName; this.categoryName = categoryName;
this._httpContextAccessor = httpContextAccessor; this._httpContextAccessor = httpContextAccessor;
} }
public bool IsEnabled(LogLevel logLevel) => true; public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>( public void Log<TState>(
LogLevel logLevel, LogLevel logLevel,
EventId eventId, EventId eventId,
TState state, TState state,
Exception exception, Exception exception,
Func<TState, Exception, string> formatter) Func<TState, Exception, string> formatter)
{ {
if (logLevel == LogLevel.Information && categoryName == "Microsoft.EntityFrameworkCore.Database.Command") if (logLevel == LogLevel.Information && categoryName == "Microsoft.EntityFrameworkCore.Database.Command")
{ {
Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 执行sql"); Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 执行sql");
if (exception != null) if (exception != null)
{ {
Console.WriteLine("发生异常:\n" + exception); Console.WriteLine("发生异常:\n" + exception);
} }
else else
{ {
if (state.GetType().Name == "LogValues`6") if (state.GetType().Name == "LogValues`6")
{ {
var paramText = state.GetType().GetField("_value1").GetValue(state).ToString(); var paramText = state.GetType().GetField("_value1").GetValue(state).ToString();
var sql = state.GetType().GetField("_value5").GetValue(state).ToString(); var sql = state.GetType().GetField("_value5").GetValue(state).ToString();
var paramList = paramText.RegexMatches("@__.*?='.*?'"); var paramList = paramText.RegexMatches("@__.*?='.*?'");
paramList.ForEach(param => paramList.ForEach(param =>
{ {
var arr = param.Split('='); var arr = param.Split('=');
sql = sql.Replace(arr[0], arr[1]); sql = sql.Replace(arr[0], arr[1]);
}); });
Console.WriteLine(sql); Console.WriteLine(sql);
if (_httpContextAccessor?.HttpContext?.Request?.Headers != null if (_httpContextAccessor?.HttpContext?.Request?.Headers != null
&& _httpContextAccessor.HttpContext.Request.Headers && _httpContextAccessor.HttpContext.Request.Headers
.ContainsKey("enable-ef-log").ToBool()) .ContainsKey("enable-ef-log").ToBool())
{ {
StringBuilder log = new StringBuilder(); StringBuilder log = new StringBuilder();
log.Append("请求URL" + _httpContextAccessor.HttpContext.Request.GetAbsoluteUri() + ""); log.Append("请求URL" + _httpContextAccessor.HttpContext.Request.GetAbsoluteUri() + "");
log.Append("\nMethod" + _httpContextAccessor.HttpContext.Request.Method + "\n"); log.Append("\nMethod" + _httpContextAccessor.HttpContext.Request.Method + "\n");
if (_httpContextAccessor.HttpContext.Request.Method.ToLower() != "get") if (_httpContextAccessor.HttpContext.Request.Method.ToLower() != "get")
{ {
log.Append("Body\n" + _httpContextAccessor.HttpContext.Items["___requestbody"] + log.Append("Body\n" + _httpContextAccessor.HttpContext.Items["___requestbody"] +
"\n------------------------\n"); "\n------------------------\n");
} }
else else
{ {
log.Append("\n------------------------\n"); log.Append("\n------------------------\n");
} }
log.Append(sql); log.Append(sql);
LogHelper.Debug("efcore日志", log.ToString()); LogHelper.Debug("efcore日志", log.ToString());
} }
} }
} }
//Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} {logLevel} {eventId.Id} {this.categoryName}"); //Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} {logLevel} {eventId.Id} {this.categoryName}");
//Console.WriteLine(formatter(state, exception)); //Console.WriteLine(formatter(state, exception));
} }
} }
public IDisposable BeginScope<TState>(TState state) => null; public IDisposable BeginScope<TState>(TState state) => null;
} }
public class TraceLoggerProvider : ILoggerProvider public class TraceLoggerProvider : ILoggerProvider
{ {
private IHttpContextAccessor _httpContextAccessor; private IHttpContextAccessor _httpContextAccessor;
public TraceLoggerProvider(IHttpContextAccessor httpContextAccessor) public TraceLoggerProvider(IHttpContextAccessor httpContextAccessor)
{ {
_httpContextAccessor = httpContextAccessor; _httpContextAccessor = httpContextAccessor;
} }
public ILogger CreateLogger(string categoryName) => new TraceLogger(categoryName, _httpContextAccessor); public ILogger CreateLogger(string categoryName) => new TraceLogger(categoryName, _httpContextAccessor);
public void Dispose() public void Dispose()
{ {
} }
} }
public static class DebugLog public static class DebugLog
{ {
public static void EnableDebugTrace(this DbContextOptionsBuilder optionsBuilder, public static void EnableDebugTrace(this DbContextOptionsBuilder optionsBuilder,
IHttpContextAccessor httpContextAccessor) IHttpContextAccessor httpContextAccessor)
{ {
LoggerFactory loggerFactory = new LoggerFactory(); LoggerFactory loggerFactory = new LoggerFactory();
loggerFactory.AddProvider(new TraceLoggerProvider(httpContextAccessor)); loggerFactory.AddProvider(new TraceLoggerProvider(httpContextAccessor));
optionsBuilder.UseLoggerFactory(loggerFactory); optionsBuilder.UseLoggerFactory(loggerFactory);
optionsBuilder.EnableSensitiveDataLogging(); optionsBuilder.EnableSensitiveDataLogging();
} }
} }
} }

View File

@@ -1,50 +1,50 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Reflection; using System.Reflection;
using Hncore.Infrastructure.Common; using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Data; using Hncore.Infrastructure.Data;
using Hncore.Infrastructure.DDD; using Hncore.Infrastructure.DDD;
using Hncore.Infrastructure.Serializer; using Hncore.Infrastructure.Serializer;
using Hncore.Infrastructure.WebApi; using Hncore.Infrastructure.WebApi;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Remotion.Linq.Parsing.ExpressionVisitors; using Remotion.Linq.Parsing.ExpressionVisitors;
using Hncore.Infrastructure.Core.Web; using Hncore.Infrastructure.Core.Web;
namespace Hncore.Infrastructure.EF namespace Hncore.Infrastructure.EF
{ {
public static class QueryFilterExtensions public static class QueryFilterExtensions
{ {
public static void AddQueryFilter<T>(this EntityTypeBuilder entityTypeBuilder, public static void AddQueryFilter<T>(this EntityTypeBuilder entityTypeBuilder,
Expression<Func<T, bool>> expression) Expression<Func<T, bool>> expression)
{ {
var parameterType = Expression.Parameter(entityTypeBuilder.Metadata.ClrType); var parameterType = Expression.Parameter(entityTypeBuilder.Metadata.ClrType);
var expressionFilter = ReplacingExpressionVisitor.Replace( var expressionFilter = ReplacingExpressionVisitor.Replace(
expression.Parameters.Single(), parameterType, expression.Body); expression.Parameters.Single(), parameterType, expression.Body);
var internalEntityTypeBuilder = entityTypeBuilder.GetInternalEntityTypeBuilder(); var internalEntityTypeBuilder = entityTypeBuilder.GetInternalEntityTypeBuilder();
if (internalEntityTypeBuilder.Metadata.QueryFilter != null) if (internalEntityTypeBuilder.Metadata.QueryFilter != null)
{ {
var currentQueryFilter = internalEntityTypeBuilder.Metadata.QueryFilter; var currentQueryFilter = internalEntityTypeBuilder.Metadata.QueryFilter;
var currentExpressionFilter = ReplacingExpressionVisitor.Replace( var currentExpressionFilter = ReplacingExpressionVisitor.Replace(
currentQueryFilter.Parameters.Single(), parameterType, currentQueryFilter.Body); currentQueryFilter.Parameters.Single(), parameterType, currentQueryFilter.Body);
expressionFilter = Expression.AndAlso(currentExpressionFilter, expressionFilter); expressionFilter = Expression.AndAlso(currentExpressionFilter, expressionFilter);
} }
var lambdaExpression = Expression.Lambda(expressionFilter, parameterType); var lambdaExpression = Expression.Lambda(expressionFilter, parameterType);
entityTypeBuilder.HasQueryFilter(lambdaExpression); entityTypeBuilder.HasQueryFilter(lambdaExpression);
} }
internal static InternalEntityTypeBuilder GetInternalEntityTypeBuilder(this EntityTypeBuilder entityTypeBuilder) internal static InternalEntityTypeBuilder GetInternalEntityTypeBuilder(this EntityTypeBuilder entityTypeBuilder)
{ {
var internalEntityTypeBuilder = typeof(EntityTypeBuilder) var internalEntityTypeBuilder = typeof(EntityTypeBuilder)
.GetProperty("Builder", BindingFlags.NonPublic | BindingFlags.Instance)? .GetProperty("Builder", BindingFlags.NonPublic | BindingFlags.Instance)?
.GetValue(entityTypeBuilder) as InternalEntityTypeBuilder; .GetValue(entityTypeBuilder) as InternalEntityTypeBuilder;
return internalEntityTypeBuilder; return internalEntityTypeBuilder;
} }
} }
} }

View File

@@ -1,196 +1,196 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data.Common; using System.Data.Common;
using System.Reflection; using System.Reflection;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace Hncore.Infrastructure.EF namespace Hncore.Infrastructure.EF
{ {
public static class Sql public static class Sql
{ {
/// <summary> /// <summary>
/// 执行Reader /// 执行Reader
/// </summary> /// </summary>
/// <param name="dbContext"></param> /// <param name="dbContext"></param>
/// <param name="sql"></param> /// <param name="sql"></param>
/// <param name="action"></param> /// <param name="action"></param>
public static void Reader(this DbContext dbContext, string sql, Action<DbDataReader> action) public static void Reader(this DbContext dbContext, string sql, Action<DbDataReader> action)
{ {
var conn = dbContext.Database.GetDbConnection(); var conn = dbContext.Database.GetDbConnection();
try try
{ {
conn.Open(); conn.Open();
using (var command = conn.CreateCommand()) using (var command = conn.CreateCommand())
{ {
string query = sql; string query = sql;
command.CommandText = query; command.CommandText = query;
using (DbDataReader reader = command.ExecuteReader()) using (DbDataReader reader = command.ExecuteReader())
{ {
if (reader.HasRows) if (reader.HasRows)
{ {
while (reader.Read()) while (reader.Read())
{ {
action(reader); action(reader);
} }
} }
} }
} }
} }
finally finally
{ {
conn.Close(); conn.Close();
} }
} }
/// <summary> /// <summary>
/// 执行Query /// 执行Query
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="dbContext"></param> /// <param name="dbContext"></param>
/// <param name="sql"></param> /// <param name="sql"></param>
/// <returns></returns> /// <returns></returns>
public static List<T> SqlQuery<T>(this DbContext dbContext, string sql) public static List<T> SqlQuery<T>(this DbContext dbContext, string sql)
{ {
List<T> list = new List<T>(); List<T> list = new List<T>();
var conn = dbContext.Database.GetDbConnection(); var conn = dbContext.Database.GetDbConnection();
try try
{ {
conn.Open(); conn.Open();
using (var command = conn.CreateCommand()) using (var command = conn.CreateCommand())
{ {
string query = sql; string query = sql;
command.CommandText = query; command.CommandText = query;
using (DbDataReader reader = command.ExecuteReader()) using (DbDataReader reader = command.ExecuteReader())
{ {
if (reader.HasRows) if (reader.HasRows)
{ {
list = reader.ReaderToList<T>(); list = reader.ReaderToList<T>();
} }
} }
} }
} }
finally finally
{ {
conn.Close(); conn.Close();
} }
return list; return list;
} }
/// <summary> /// <summary>
/// 执行Sql命令 /// 执行Sql命令
/// </summary> /// </summary>
/// <param name="dbContext"></param> /// <param name="dbContext"></param>
/// <param name="sql"></param> /// <param name="sql"></param>
/// <returns></returns> /// <returns></returns>
public static int ExecuteSql(this DbContext dbContext, string sql) public static int ExecuteSql(this DbContext dbContext, string sql)
{ {
var conn = dbContext.Database.GetDbConnection(); var conn = dbContext.Database.GetDbConnection();
int rowAffected = 0; int rowAffected = 0;
try try
{ {
conn.Open(); conn.Open();
using (var command = conn.CreateCommand()) using (var command = conn.CreateCommand())
{ {
command.CommandText = sql; command.CommandText = sql;
rowAffected = command.ExecuteNonQuery(); rowAffected = command.ExecuteNonQuery();
} }
} }
finally finally
{ {
conn.Close(); conn.Close();
} }
return rowAffected; return rowAffected;
} }
/// <summary> /// <summary>
/// DataReader转泛型 /// DataReader转泛型
/// </summary> /// </summary>
/// <typeparam name="T">传入的实体类</typeparam> /// <typeparam name="T">传入的实体类</typeparam>
/// <param name="objReader">DataReader对象</param> /// <param name="objReader">DataReader对象</param>
/// <returns></returns> /// <returns></returns>
public static List<T> ReaderToList<T>(this DbDataReader objReader) public static List<T> ReaderToList<T>(this DbDataReader objReader)
{ {
using (objReader) using (objReader)
{ {
List<T> list = new List<T>(); List<T> list = new List<T>();
//获取传入的数据类型 //获取传入的数据类型
Type modelType = typeof(T); Type modelType = typeof(T);
//遍历DataReader对象 //遍历DataReader对象
while (objReader.Read()) while (objReader.Read())
{ {
//使用与指定参数匹配最高的构造函数,来创建指定类型的实例 //使用与指定参数匹配最高的构造函数,来创建指定类型的实例
T model = Activator.CreateInstance<T>(); T model = Activator.CreateInstance<T>();
for (int i = 0; i < objReader.FieldCount; i++) for (int i = 0; i < objReader.FieldCount; i++)
{ {
//判断字段值是否为空或不存在的值 //判断字段值是否为空或不存在的值
if (!IsNullOrDBNull(objReader[i])) if (!IsNullOrDBNull(objReader[i]))
{ {
//匹配字段名 //匹配字段名
PropertyInfo pi = modelType.GetProperty(objReader.GetName(i), PropertyInfo pi = modelType.GetProperty(objReader.GetName(i),
BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance |
BindingFlags.IgnoreCase); BindingFlags.IgnoreCase);
if (pi != null) if (pi != null)
{ {
//绑定实体对象中同名的字段 //绑定实体对象中同名的字段
pi.SetValue(model, CheckType(objReader[i], pi.PropertyType), null); pi.SetValue(model, CheckType(objReader[i], pi.PropertyType), null);
} }
} }
} }
list.Add(model); list.Add(model);
} }
return list; return list;
} }
} }
/// <summary> /// <summary>
/// 判断指定对象是否是有效值 /// 判断指定对象是否是有效值
/// </summary> /// </summary>
/// <param name="obj"></param> /// <param name="obj"></param>
/// <returns></returns> /// <returns></returns>
private static bool IsNullOrDBNull(object obj) private static bool IsNullOrDBNull(object obj)
{ {
return (obj == null || (obj is DBNull)) ? true : false; return (obj == null || (obj is DBNull)) ? true : false;
} }
/// <summary> /// <summary>
/// 对可空类型进行判断转换 /// 对可空类型进行判断转换
/// </summary> /// </summary>
/// <param name="value">DataReader字段的值</param> /// <param name="value">DataReader字段的值</param>
/// <param name="conversionType">该字段的类型</param> /// <param name="conversionType">该字段的类型</param>
/// <returns></returns> /// <returns></returns>
private static object CheckType(object value, Type conversionType) private static object CheckType(object value, Type conversionType)
{ {
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{ {
if (value == null) if (value == null)
return null; return null;
System.ComponentModel.NullableConverter nullableConverter = System.ComponentModel.NullableConverter nullableConverter =
new System.ComponentModel.NullableConverter(conversionType); new System.ComponentModel.NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType; conversionType = nullableConverter.UnderlyingType;
} }
if (typeof(System.Enum).IsAssignableFrom(conversionType)) if (typeof(System.Enum).IsAssignableFrom(conversionType))
{ {
return Enum.Parse(conversionType, value.ToString()); return Enum.Parse(conversionType, value.ToString());
} }
return Convert.ChangeType(value, conversionType); return Convert.ChangeType(value, conversionType);
} }
} }
} }

View File

@@ -1,9 +1,9 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace Hncore.Infrastructure.EF namespace Hncore.Infrastructure.EF
{ {
public interface IQueryDbContext public interface IQueryDbContext
{ {
DbContext DbContext { get; } DbContext DbContext { get; }
} }
} }

View File

@@ -1,9 +1,9 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace Hncore.Infrastructure.EF namespace Hncore.Infrastructure.EF
{ {
public interface IRepositoryDbContext public interface IRepositoryDbContext
{ {
DbContext DbContext { get; } DbContext DbContext { get; }
} }
} }

View File

@@ -1,90 +1,90 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Hncore.Infrastructure.Data; using Hncore.Infrastructure.Data;
using Hncore.Infrastructure.DDD; using Hncore.Infrastructure.DDD;
namespace Hncore.Infrastructure.EF namespace Hncore.Infrastructure.EF
{ {
public class QueryBase<TEntity, TId> : IQuery<TEntity, TId> where TEntity : class, IEntity<TId> public class QueryBase<TEntity, TId> : IQuery<TEntity, TId> where TEntity : class, IEntity<TId>
{ {
protected DbContext Dbcontext; protected DbContext Dbcontext;
public QueryBase(IQueryDbContext dbContext) public QueryBase(IQueryDbContext dbContext)
{ {
Dbcontext = dbContext.DbContext; Dbcontext = dbContext.DbContext;
} }
public TEntity GetOne(Expression<Func<TEntity, bool>> condition) public TEntity GetOne(Expression<Func<TEntity, bool>> condition)
{ {
return Dbcontext.GetOne<TEntity, TId>(condition); return Dbcontext.GetOne<TEntity, TId>(condition);
} }
public Task<TEntity> GetOneAsync(Expression<Func<TEntity, bool>> condition) public Task<TEntity> GetOneAsync(Expression<Func<TEntity, bool>> condition)
{ {
return Dbcontext.GetOneAsync<TEntity, TId>(condition); return Dbcontext.GetOneAsync<TEntity, TId>(condition);
} }
public PageData<TEntity> GetList(Expression<Func<TEntity, bool>> condition, int pagesize, int pageindex, public PageData<TEntity> GetList(Expression<Func<TEntity, bool>> condition, int pagesize, int pageindex,
bool istotal) bool istotal)
{ {
return Dbcontext.GetList<TEntity, TId>(condition, pagesize, pageindex, istotal); return Dbcontext.GetList<TEntity, TId>(condition, pagesize, pageindex, istotal);
} }
public Task<PageData<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> condition, int pagesize, public Task<PageData<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> condition, int pagesize,
int pageindex, bool istotal) int pageindex, bool istotal)
{ {
return Dbcontext.GetListAsync<TEntity, TId>(condition, pagesize, pageindex, istotal); return Dbcontext.GetListAsync<TEntity, TId>(condition, pagesize, pageindex, istotal);
} }
public List<TEntity> GetList(Expression<Func<TEntity, bool>> condition) public List<TEntity> GetList(Expression<Func<TEntity, bool>> condition)
{ {
return Dbcontext.GetList<TEntity, TId>(condition); return Dbcontext.GetList<TEntity, TId>(condition);
} }
public Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> condition) public Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> condition)
{ {
return Dbcontext.GetListAsync<TEntity, TId>(condition); return Dbcontext.GetListAsync<TEntity, TId>(condition);
} }
public List<TEntity> TopN(Expression<Func<TEntity, bool>> condition, int topN) public List<TEntity> TopN(Expression<Func<TEntity, bool>> condition, int topN)
{ {
return Dbcontext.TopN<TEntity, TId>(condition, topN); return Dbcontext.TopN<TEntity, TId>(condition, topN);
} }
public Task<List<TEntity>> TopNAsync(Expression<Func<TEntity, bool>> condition, int topN) public Task<List<TEntity>> TopNAsync(Expression<Func<TEntity, bool>> condition, int topN)
{ {
return Dbcontext.TopNAsync<TEntity, TId>(condition, topN); return Dbcontext.TopNAsync<TEntity, TId>(condition, topN);
} }
public IQueryable<TEntity> GetListQueryable(Expression<Func<TEntity, bool>> exp) public IQueryable<TEntity> GetListQueryable(Expression<Func<TEntity, bool>> exp)
{ {
return Dbcontext.GetListQueryable<TEntity, TId>(exp); return Dbcontext.GetListQueryable<TEntity, TId>(exp);
} }
public bool Exists(Expression<Func<TEntity, bool>> exp) public bool Exists(Expression<Func<TEntity, bool>> exp)
{ {
return Dbcontext.Exists<TEntity, TId>(exp); return Dbcontext.Exists<TEntity, TId>(exp);
} }
public Task<bool> ExistsAsync(Expression<Func<TEntity, bool>> condition) public Task<bool> ExistsAsync(Expression<Func<TEntity, bool>> condition)
{ {
return Dbcontext.ExistsAsync<TEntity, TId>(condition); return Dbcontext.ExistsAsync<TEntity, TId>(condition);
} }
public IQueryable<TEntity> GetQueryable() public IQueryable<TEntity> GetQueryable()
{ {
return Dbcontext.Set<TEntity>().AsNoTracking(); return Dbcontext.Set<TEntity>().AsNoTracking();
} }
public DbContext DbContext() public DbContext DbContext()
{ {
return Dbcontext; return Dbcontext;
} }
} }
} }

View File

@@ -1,110 +1,110 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Hncore.Infrastructure.Data; using Hncore.Infrastructure.Data;
using Hncore.Infrastructure.DDD; using Hncore.Infrastructure.DDD;
using Hncore.Infrastructure.EntitiesExtension; using Hncore.Infrastructure.EntitiesExtension;
namespace Hncore.Infrastructure.EF namespace Hncore.Infrastructure.EF
{ {
public static class QueryExtension public static class QueryExtension
{ {
public static TEntity GetOne<TEntity, TId>(this DbContext dbcontext, Expression<Func<TEntity, bool>> exp) public static TEntity GetOne<TEntity, TId>(this DbContext dbcontext, Expression<Func<TEntity, bool>> exp)
where TEntity : class, IEntity<TId> where TEntity : class, IEntity<TId>
{ {
return dbcontext.Set<TEntity>().AsNoTracking() return dbcontext.Set<TEntity>().AsNoTracking()
.FirstOrDefault(exp); .FirstOrDefault(exp);
} }
public static Task<TEntity> GetOneAsync<TEntity, TId>(this DbContext dbcontext, public static Task<TEntity> GetOneAsync<TEntity, TId>(this DbContext dbcontext,
Expression<Func<TEntity, bool>> exp) where TEntity : class, IEntity<TId> Expression<Func<TEntity, bool>> exp) where TEntity : class, IEntity<TId>
{ {
return dbcontext.Set<TEntity>().AsNoTracking() return dbcontext.Set<TEntity>().AsNoTracking()
.FirstOrDefaultAsync(exp); .FirstOrDefaultAsync(exp);
} }
public static PageData<TEntity> GetList<TEntity, TId>(this DbContext dbcontext, public static PageData<TEntity> GetList<TEntity, TId>(this DbContext dbcontext,
Expression<Func<TEntity, bool>> exp, int pagesize, int pageindex, bool istotal) Expression<Func<TEntity, bool>> exp, int pagesize, int pageindex, bool istotal)
where TEntity : class, IEntity<TId> where TEntity : class, IEntity<TId>
{ {
return dbcontext.Set<TEntity>().AsNoTracking() return dbcontext.Set<TEntity>().AsNoTracking()
.Where(exp) .Where(exp)
.OrderByDescending(t => t.Id) .OrderByDescending(t => t.Id)
.ListPager(pagesize, pageindex, istotal); .ListPager(pagesize, pageindex, istotal);
} }
public static Task<PageData<TEntity>> GetListAsync<TEntity, TId>(this DbContext dbcontext, public static Task<PageData<TEntity>> GetListAsync<TEntity, TId>(this DbContext dbcontext,
Expression<Func<TEntity, bool>> exp, int pagesize, int pageindex, bool istotal) Expression<Func<TEntity, bool>> exp, int pagesize, int pageindex, bool istotal)
where TEntity : class, IEntity<TId> where TEntity : class, IEntity<TId>
{ {
return dbcontext.Set<TEntity>().AsNoTracking() return dbcontext.Set<TEntity>().AsNoTracking()
.Where(exp) .Where(exp)
.OrderByDescending(t => t.Id) .OrderByDescending(t => t.Id)
.ListPagerAsync(pagesize, pageindex, istotal); .ListPagerAsync(pagesize, pageindex, istotal);
} }
public static List<TEntity> GetList<TEntity, TId>(this DbContext dbcontext, Expression<Func<TEntity, bool>> exp) public static List<TEntity> GetList<TEntity, TId>(this DbContext dbcontext, Expression<Func<TEntity, bool>> exp)
where TEntity : class, IEntity<TId> where TEntity : class, IEntity<TId>
{ {
return dbcontext.Set<TEntity>().AsNoTracking() return dbcontext.Set<TEntity>().AsNoTracking()
.Where(exp) .Where(exp)
.ToList(); .ToList();
} }
public static Task<List<TEntity>> GetListAsync<TEntity, TId>(this DbContext dbcontext, public static Task<List<TEntity>> GetListAsync<TEntity, TId>(this DbContext dbcontext,
Expression<Func<TEntity, bool>> exp) Expression<Func<TEntity, bool>> exp)
where TEntity : class, IEntity<TId> where TEntity : class, IEntity<TId>
{ {
return dbcontext.Set<TEntity>().AsNoTracking() return dbcontext.Set<TEntity>().AsNoTracking()
.Where(exp) .Where(exp)
.ToListAsync(); .ToListAsync();
} }
public static IQueryable<TEntity> GetListQueryable<TEntity, TId>(this DbContext dbcontext, public static IQueryable<TEntity> GetListQueryable<TEntity, TId>(this DbContext dbcontext,
Expression<Func<TEntity, bool>> exp) Expression<Func<TEntity, bool>> exp)
where TEntity : class, IEntity<TId> where TEntity : class, IEntity<TId>
{ {
return dbcontext.Set<TEntity>().AsNoTracking() return dbcontext.Set<TEntity>().AsNoTracking()
.Where(exp); .Where(exp);
} }
public static bool Exists<TEntity, TId>(this DbContext dbcontext, Expression<Func<TEntity, bool>> exp) public static bool Exists<TEntity, TId>(this DbContext dbcontext, Expression<Func<TEntity, bool>> exp)
where TEntity : class, IEntity<TId> where TEntity : class, IEntity<TId>
{ {
return dbcontext.Set<TEntity>().AsNoTracking() return dbcontext.Set<TEntity>().AsNoTracking()
.Any(exp); .Any(exp);
} }
public static Task<bool> ExistsAsync<TEntity, TId>(this DbContext dbcontext, public static Task<bool> ExistsAsync<TEntity, TId>(this DbContext dbcontext,
Expression<Func<TEntity, bool>> exp) Expression<Func<TEntity, bool>> exp)
where TEntity : class, IEntity<TId> where TEntity : class, IEntity<TId>
{ {
return dbcontext.Set<TEntity>().AsNoTracking() return dbcontext.Set<TEntity>().AsNoTracking()
.AnyAsync(exp); .AnyAsync(exp);
} }
public static List<TEntity> TopN<TEntity, TId>(this DbContext dbcontext, public static List<TEntity> TopN<TEntity, TId>(this DbContext dbcontext,
Expression<Func<TEntity, bool>> condition, int topN) Expression<Func<TEntity, bool>> condition, int topN)
where TEntity : class, IEntity<TId> where TEntity : class, IEntity<TId>
{ {
return dbcontext.Set<TEntity>().AsNoTracking() return dbcontext.Set<TEntity>().AsNoTracking()
.Where(condition) .Where(condition)
.TopN(topN) .TopN(topN)
.ToList(); .ToList();
} }
public static Task<List<TEntity>> TopNAsync<TEntity, TId>(this DbContext dbcontext, public static Task<List<TEntity>> TopNAsync<TEntity, TId>(this DbContext dbcontext,
Expression<Func<TEntity, bool>> condition, int topN) Expression<Func<TEntity, bool>> condition, int topN)
where TEntity : class, IEntity<TId> where TEntity : class, IEntity<TId>
{ {
return dbcontext.Set<TEntity>().AsNoTracking() return dbcontext.Set<TEntity>().AsNoTracking()
.Where(condition) .Where(condition)
.TopN(topN) .TopN(topN)
.ToListAsync(); .ToListAsync();
} }
} }
} }

View File

@@ -1,90 +1,90 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Hncore.Infrastructure.DDD; using Hncore.Infrastructure.DDD;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace Hncore.Infrastructure.EF namespace Hncore.Infrastructure.EF
{ {
public class RepositoryBase<TEntity, TId> : IRepository<TEntity, TId> public class RepositoryBase<TEntity, TId> : IRepository<TEntity, TId>
where TEntity : Entity<TId> where TEntity : Entity<TId>
{ {
protected DbContext Dbcontext; protected DbContext Dbcontext;
public RepositoryBase(IRepositoryDbContext dbContext) public RepositoryBase(IRepositoryDbContext dbContext)
{ {
Dbcontext = dbContext.DbContext; Dbcontext = dbContext.DbContext;
} }
public TEntity FindById(TId id) public TEntity FindById(TId id)
{ {
return Dbcontext.Set<TEntity>().Find(id); return Dbcontext.Set<TEntity>().Find(id);
} }
public Task<TEntity> FindByIdAsync(TId id) public Task<TEntity> FindByIdAsync(TId id)
{ {
return Dbcontext.Set<TEntity>().FindAsync(id); return Dbcontext.Set<TEntity>().FindAsync(id);
} }
public void Add(TEntity entity) public void Add(TEntity entity)
{ {
Dbcontext.Set<TEntity>().Add(entity); Dbcontext.Set<TEntity>().Add(entity);
} }
public Task AddAsync(TEntity entity) public Task AddAsync(TEntity entity)
{ {
return Dbcontext.Set<TEntity>().AddAsync(entity); return Dbcontext.Set<TEntity>().AddAsync(entity);
} }
/// <summary> /// <summary>
/// 批量添加 /// 批量添加
/// </summary> /// </summary>
/// <param name="entity"></param> /// <param name="entity"></param>
public void AddRange(List<TEntity> entity) public void AddRange(List<TEntity> entity)
{ {
Dbcontext.Set<TEntity>().AddRange(entity); Dbcontext.Set<TEntity>().AddRange(entity);
} }
/// <summary> /// <summary>
/// 批量添加 /// 批量添加
/// </summary> /// </summary>
/// <param name="entity"></param> /// <param name="entity"></param>
public Task AddRangeAsync(List<TEntity> entity) public Task AddRangeAsync(List<TEntity> entity)
{ {
return Dbcontext.Set<TEntity>().AddRangeAsync(entity); return Dbcontext.Set<TEntity>().AddRangeAsync(entity);
} }
/// <summary> /// <summary>
/// 批量修改 /// 批量修改
/// </summary> /// </summary>
/// <param name="entity"></param> /// <param name="entity"></param>
public void UpdateRange(List<TEntity> entity) public void UpdateRange(List<TEntity> entity)
{ {
Dbcontext.Set<TEntity>().UpdateRange(entity); Dbcontext.Set<TEntity>().UpdateRange(entity);
} }
/// <summary> /// <summary>
/// 批量删除 /// 批量删除
/// </summary> /// </summary>
/// <param name="entity"></param> /// <param name="entity"></param>
public void RemoveRange(List<TEntity> entity) public void RemoveRange(List<TEntity> entity)
{ {
Dbcontext.Set<TEntity>().RemoveRange(entity); Dbcontext.Set<TEntity>().RemoveRange(entity);
} }
public void Remove(TEntity entity) public void Remove(TEntity entity)
{ {
Dbcontext.Set<TEntity>().Remove(entity); Dbcontext.Set<TEntity>().Remove(entity);
} }
public void Update(TEntity entity) public void Update(TEntity entity)
{ {
Dbcontext.Set<TEntity>().Update(entity); Dbcontext.Set<TEntity>().Update(entity);
} }
public IQueryable<TEntity> GetQueryable() public IQueryable<TEntity> GetQueryable()
{ {
return Dbcontext.Set<TEntity>(); return Dbcontext.Set<TEntity>();
} }
} }
} }

View File

@@ -1,13 +1,13 @@
vs vs
Add-Migration Add-Migration
Update-Database Update-Database
cli cli
dotnet ef migrations add init dotnet ef migrations add init
dotnet ef database update dotnet ef database update
输出脚本 输出脚本
dotnet ef migrations script dotnet ef migrations script

View File

@@ -1,48 +1,48 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
namespace Hncore.Infrastructure.EntitiesExtension namespace Hncore.Infrastructure.EntitiesExtension
{ {
public class CommonEqualityComparer<T, V> : IEqualityComparer<T> public class CommonEqualityComparer<T, V> : IEqualityComparer<T>
{ {
private Func<T, V> keySelector; private Func<T, V> keySelector;
private IEqualityComparer<V> comparer; private IEqualityComparer<V> comparer;
public CommonEqualityComparer(Func<T, V> keySelector, IEqualityComparer<V> comparer) public CommonEqualityComparer(Func<T, V> keySelector, IEqualityComparer<V> comparer)
{ {
this.keySelector = keySelector; this.keySelector = keySelector;
this.comparer = comparer; this.comparer = comparer;
} }
public CommonEqualityComparer(Func<T, V> keySelector) public CommonEqualityComparer(Func<T, V> keySelector)
: this(keySelector, EqualityComparer<V>.Default) : this(keySelector, EqualityComparer<V>.Default)
{ } { }
public bool Equals(T x, T y) public bool Equals(T x, T y)
{ {
return comparer.Equals(keySelector(x), keySelector(y)); return comparer.Equals(keySelector(x), keySelector(y));
} }
public int GetHashCode(T obj) public int GetHashCode(T obj)
{ {
return comparer.GetHashCode(keySelector(obj)); return comparer.GetHashCode(keySelector(obj));
} }
} }
/// <summary> /// <summary>
/// 扩展类 /// 扩展类
/// </summary> /// </summary>
public static class DistinctExtensions public static class DistinctExtensions
{ {
public static IEnumerable<T> Distinctx<T, V>(this IEnumerable<T> source, Func<T, V> keySelector) public static IEnumerable<T> Distinctx<T, V>(this IEnumerable<T> source, Func<T, V> keySelector)
{ {
return source.Distinct(new CommonEqualityComparer<T, V>(keySelector)); return source.Distinct(new CommonEqualityComparer<T, V>(keySelector));
} }
public static IEnumerable<T> Distinctx<T, V>(this IEnumerable<T> source, Func<T, V> keySelector, IEqualityComparer<V> comparer) public static IEnumerable<T> Distinctx<T, V>(this IEnumerable<T> source, Func<T, V> keySelector, IEqualityComparer<V> comparer)
{ {
return source.Distinct(new CommonEqualityComparer<T, V>(keySelector, comparer)); return source.Distinct(new CommonEqualityComparer<T, V>(keySelector, comparer));
} }
} }
} }

View File

@@ -1,144 +1,144 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Reflection; using System.Reflection;
namespace Hncore.Infrastructure.EntitiesExtension namespace Hncore.Infrastructure.EntitiesExtension
{ {
internal class ConditionBuilder : ExpressionVisitor internal class ConditionBuilder : ExpressionVisitor
{ {
private List<object> m_arguments; private List<object> m_arguments;
private Stack<string> m_conditionParts; private Stack<string> m_conditionParts;
public string Condition { get; private set; } public string Condition { get; private set; }
public object[] Arguments { get; private set; } public object[] Arguments { get; private set; }
public void Build(Expression expression) public void Build(Expression expression)
{ {
PartialEvaluator evaluator = new PartialEvaluator(); PartialEvaluator evaluator = new PartialEvaluator();
Expression evaluatedExpression = evaluator.Eval(expression); Expression evaluatedExpression = evaluator.Eval(expression);
this.m_arguments = new List<object>(); this.m_arguments = new List<object>();
this.m_conditionParts = new Stack<string>(); this.m_conditionParts = new Stack<string>();
this.Visit(evaluatedExpression); this.Visit(evaluatedExpression);
this.Arguments = this.m_arguments.ToArray(); this.Arguments = this.m_arguments.ToArray();
this.Condition = this.m_conditionParts.Count > 0 ? this.m_conditionParts.Pop() : null; this.Condition = this.m_conditionParts.Count > 0 ? this.m_conditionParts.Pop() : null;
} }
protected override Expression VisitBinary(BinaryExpression b) protected override Expression VisitBinary(BinaryExpression b)
{ {
if (b == null) return b; if (b == null) return b;
string opr; string opr;
switch (b.NodeType) switch (b.NodeType)
{ {
case ExpressionType.Equal: case ExpressionType.Equal:
opr = "="; opr = "=";
break; break;
case ExpressionType.NotEqual: case ExpressionType.NotEqual:
opr = "<>"; opr = "<>";
break; break;
case ExpressionType.GreaterThan: case ExpressionType.GreaterThan:
opr = ">"; opr = ">";
break; break;
case ExpressionType.GreaterThanOrEqual: case ExpressionType.GreaterThanOrEqual:
opr = ">="; opr = ">=";
break; break;
case ExpressionType.LessThan: case ExpressionType.LessThan:
opr = "<"; opr = "<";
break; break;
case ExpressionType.LessThanOrEqual: case ExpressionType.LessThanOrEqual:
opr = "<="; opr = "<=";
break; break;
case ExpressionType.AndAlso: case ExpressionType.AndAlso:
opr = "AND"; opr = "AND";
break; break;
case ExpressionType.OrElse: case ExpressionType.OrElse:
opr = "OR"; opr = "OR";
break; break;
case ExpressionType.Add: case ExpressionType.Add:
opr = "+"; opr = "+";
break; break;
case ExpressionType.Subtract: case ExpressionType.Subtract:
opr = "-"; opr = "-";
break; break;
case ExpressionType.Multiply: case ExpressionType.Multiply:
opr = "*"; opr = "*";
break; break;
case ExpressionType.Divide: case ExpressionType.Divide:
opr = "/"; opr = "/";
break; break;
default: default:
throw new NotSupportedException(b.NodeType + "is not supported."); throw new NotSupportedException(b.NodeType + "is not supported.");
} }
this.Visit(b.Left); this.Visit(b.Left);
this.Visit(b.Right); this.Visit(b.Right);
string right = this.m_conditionParts.Pop(); string right = this.m_conditionParts.Pop();
string left = this.m_conditionParts.Pop(); string left = this.m_conditionParts.Pop();
string condition = String.Format("({0} {1} {2})", left, opr, right); string condition = String.Format("({0} {1} {2})", left, opr, right);
this.m_conditionParts.Push(condition); this.m_conditionParts.Push(condition);
return b; return b;
} }
protected override Expression VisitConstant(ConstantExpression c) protected override Expression VisitConstant(ConstantExpression c)
{ {
if (c == null) return c; if (c == null) return c;
this.m_arguments.Add(c.Value); this.m_arguments.Add(c.Value);
this.m_conditionParts.Push(String.Format("{{{0}}}", this.m_arguments.Count - 1)); this.m_conditionParts.Push(String.Format("{{{0}}}", this.m_arguments.Count - 1));
return c; return c;
} }
protected override Expression VisitMemberAccess(MemberExpression m) protected override Expression VisitMemberAccess(MemberExpression m)
{ {
if (m == null) return m; if (m == null) return m;
PropertyInfo propertyInfo = m.Member as PropertyInfo; PropertyInfo propertyInfo = m.Member as PropertyInfo;
if (propertyInfo == null) return m; if (propertyInfo == null) return m;
this.m_conditionParts.Push(String.Format("[{0}]", propertyInfo.Name)); this.m_conditionParts.Push(String.Format("[{0}]", propertyInfo.Name));
return m; return m;
} }
protected override Expression VisitMethodCall(MethodCallExpression m) protected override Expression VisitMethodCall(MethodCallExpression m)
{ {
if (m == null) return m; if (m == null) return m;
string format; string format;
switch (m.Method.Name) switch (m.Method.Name)
{ {
case "StartsWith": case "StartsWith":
format = "({0} LIKE {1}+'%')"; format = "({0} LIKE {1}+'%')";
break; break;
case "Contains": case "Contains":
format = "({0} LIKE '%'+{1}+'%')"; format = "({0} LIKE '%'+{1}+'%')";
break; break;
case "EndsWith": case "EndsWith":
format = "({0} LIKE '%'+{1})"; format = "({0} LIKE '%'+{1})";
break; break;
default: default:
throw new NotSupportedException(m.NodeType + " is not supported!"); throw new NotSupportedException(m.NodeType + " is not supported!");
} }
this.Visit(m.Object); this.Visit(m.Object);
this.Visit(m.Arguments[0]); this.Visit(m.Arguments[0]);
string right = this.m_conditionParts.Pop(); string right = this.m_conditionParts.Pop();
string left = this.m_conditionParts.Pop(); string left = this.m_conditionParts.Pop();
this.m_conditionParts.Push(String.Format(format, left, right)); this.m_conditionParts.Push(String.Format(format, left, right));
return m; return m;
} }
} }
} }

View File

@@ -1,53 +1,53 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
namespace Hncore.Infrastructure.EntitiesExtension namespace Hncore.Infrastructure.EntitiesExtension
{ {
/// <summary> /// <summary>
/// Extension methods for add And and Or with parameters rebinder /// Extension methods for add And and Or with parameters rebinder
/// </summary> /// </summary>
public static class ExpressionBuilder public static class ExpressionBuilder
{ {
/// <summary> /// <summary>
/// Compose two expression and merge all in a new expression /// Compose two expression and merge all in a new expression
/// </summary> /// </summary>
/// <typeparam name="T">Type of params in expression</typeparam> /// <typeparam name="T">Type of params in expression</typeparam>
/// <param name="first">Expression instance</param> /// <param name="first">Expression instance</param>
/// <param name="second">Expression to merge</param> /// <param name="second">Expression to merge</param>
/// <param name="merge">Function to merge</param> /// <param name="merge">Function to merge</param>
/// <returns>New merged expressions</returns> /// <returns>New merged expressions</returns>
public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge) public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
{ {
// build parameter map (from parameters of second to parameters of first) // build parameter map (from parameters of second to parameters of first)
var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f); var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
// replace parameters in the second lambda expression with parameters from the first // replace parameters in the second lambda expression with parameters from the first
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
// apply composition of lambda expression bodies to parameters from the first expression // apply composition of lambda expression bodies to parameters from the first expression
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters); return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
} }
/// <summary> /// <summary>
/// And operator /// And operator
/// </summary> /// </summary>
/// <typeparam name="T">Type of params in expression</typeparam> /// <typeparam name="T">Type of params in expression</typeparam>
/// <param name="first">Right Expression in AND operation</param> /// <param name="first">Right Expression in AND operation</param>
/// <param name="second">Left Expression in And operation</param> /// <param name="second">Left Expression in And operation</param>
/// <returns>New AND expression</returns> /// <returns>New AND expression</returns>
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{ {
return first.Compose(second, Expression.AndAlso); return first.Compose(second, Expression.AndAlso);
} }
/// <summary> /// <summary>
/// Or operator /// Or operator
/// </summary> /// </summary>
/// <typeparam name="T">Type of param in expression</typeparam> /// <typeparam name="T">Type of param in expression</typeparam>
/// <param name="first">Right expression in OR operation</param> /// <param name="first">Right expression in OR operation</param>
/// <param name="second">Left expression in OR operation</param> /// <param name="second">Left expression in OR operation</param>
/// <returns>New Or expressions</returns> /// <returns>New Or expressions</returns>
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{ {
return first.Compose(second, Expression.Or); return first.Compose(second, Expression.Or);
} }
} }
} }

View File

@@ -1,364 +1,364 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Linq.Expressions; using System.Linq.Expressions;
namespace Hncore.Infrastructure.EntitiesExtension namespace Hncore.Infrastructure.EntitiesExtension
{ {
public abstract class ExpressionVisitor public abstract class ExpressionVisitor
{ {
protected ExpressionVisitor() { } protected ExpressionVisitor() { }
protected virtual Expression Visit(Expression exp) protected virtual Expression Visit(Expression exp)
{ {
if (exp == null) if (exp == null)
return exp; return exp;
switch (exp.NodeType) switch (exp.NodeType)
{ {
case ExpressionType.Negate: case ExpressionType.Negate:
case ExpressionType.NegateChecked: case ExpressionType.NegateChecked:
case ExpressionType.Not: case ExpressionType.Not:
case ExpressionType.Convert: case ExpressionType.Convert:
case ExpressionType.ConvertChecked: case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength: case ExpressionType.ArrayLength:
case ExpressionType.Quote: case ExpressionType.Quote:
case ExpressionType.TypeAs: case ExpressionType.TypeAs:
return this.VisitUnary((UnaryExpression)exp); return this.VisitUnary((UnaryExpression)exp);
case ExpressionType.Add: case ExpressionType.Add:
case ExpressionType.AddChecked: case ExpressionType.AddChecked:
case ExpressionType.Subtract: case ExpressionType.Subtract:
case ExpressionType.SubtractChecked: case ExpressionType.SubtractChecked:
case ExpressionType.Multiply: case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked: case ExpressionType.MultiplyChecked:
case ExpressionType.Divide: case ExpressionType.Divide:
case ExpressionType.Modulo: case ExpressionType.Modulo:
case ExpressionType.And: case ExpressionType.And:
case ExpressionType.AndAlso: case ExpressionType.AndAlso:
case ExpressionType.Or: case ExpressionType.Or:
case ExpressionType.OrElse: case ExpressionType.OrElse:
case ExpressionType.LessThan: case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual: case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan: case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual: case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal: case ExpressionType.Equal:
case ExpressionType.NotEqual: case ExpressionType.NotEqual:
case ExpressionType.Coalesce: case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex: case ExpressionType.ArrayIndex:
case ExpressionType.RightShift: case ExpressionType.RightShift:
case ExpressionType.LeftShift: case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr: case ExpressionType.ExclusiveOr:
return this.VisitBinary((BinaryExpression)exp); return this.VisitBinary((BinaryExpression)exp);
case ExpressionType.TypeIs: case ExpressionType.TypeIs:
return this.VisitTypeIs((TypeBinaryExpression)exp); return this.VisitTypeIs((TypeBinaryExpression)exp);
case ExpressionType.Conditional: case ExpressionType.Conditional:
return this.VisitConditional((ConditionalExpression)exp); return this.VisitConditional((ConditionalExpression)exp);
case ExpressionType.Constant: case ExpressionType.Constant:
return this.VisitConstant((ConstantExpression)exp); return this.VisitConstant((ConstantExpression)exp);
case ExpressionType.Parameter: case ExpressionType.Parameter:
return this.VisitParameter((ParameterExpression)exp); return this.VisitParameter((ParameterExpression)exp);
case ExpressionType.MemberAccess: case ExpressionType.MemberAccess:
return this.VisitMemberAccess((MemberExpression)exp); return this.VisitMemberAccess((MemberExpression)exp);
case ExpressionType.Call: case ExpressionType.Call:
return this.VisitMethodCall((MethodCallExpression)exp); return this.VisitMethodCall((MethodCallExpression)exp);
case ExpressionType.Lambda: case ExpressionType.Lambda:
return this.VisitLambda((LambdaExpression)exp); return this.VisitLambda((LambdaExpression)exp);
case ExpressionType.New: case ExpressionType.New:
return this.VisitNew((NewExpression)exp); return this.VisitNew((NewExpression)exp);
case ExpressionType.NewArrayInit: case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds: case ExpressionType.NewArrayBounds:
return this.VisitNewArray((NewArrayExpression)exp); return this.VisitNewArray((NewArrayExpression)exp);
case ExpressionType.Invoke: case ExpressionType.Invoke:
return this.VisitInvocation((InvocationExpression)exp); return this.VisitInvocation((InvocationExpression)exp);
case ExpressionType.MemberInit: case ExpressionType.MemberInit:
return this.VisitMemberInit((MemberInitExpression)exp); return this.VisitMemberInit((MemberInitExpression)exp);
case ExpressionType.ListInit: case ExpressionType.ListInit:
return this.VisitListInit((ListInitExpression)exp); return this.VisitListInit((ListInitExpression)exp);
default: default:
throw new Exception(string.Format("Unhandled expression type: '{0}'", exp.NodeType)); throw new Exception(string.Format("Unhandled expression type: '{0}'", exp.NodeType));
} }
} }
protected virtual MemberBinding VisitBinding(MemberBinding binding) protected virtual MemberBinding VisitBinding(MemberBinding binding)
{ {
switch (binding.BindingType) switch (binding.BindingType)
{ {
case MemberBindingType.Assignment: case MemberBindingType.Assignment:
return this.VisitMemberAssignment((MemberAssignment)binding); return this.VisitMemberAssignment((MemberAssignment)binding);
case MemberBindingType.MemberBinding: case MemberBindingType.MemberBinding:
return this.VisitMemberMemberBinding((MemberMemberBinding)binding); return this.VisitMemberMemberBinding((MemberMemberBinding)binding);
case MemberBindingType.ListBinding: case MemberBindingType.ListBinding:
return this.VisitMemberListBinding((MemberListBinding)binding); return this.VisitMemberListBinding((MemberListBinding)binding);
default: default:
throw new Exception(string.Format("Unhandled binding type '{0}'", binding.BindingType)); throw new Exception(string.Format("Unhandled binding type '{0}'", binding.BindingType));
} }
} }
protected virtual ElementInit VisitElementInitializer(ElementInit initializer) protected virtual ElementInit VisitElementInitializer(ElementInit initializer)
{ {
ReadOnlyCollection<Expression> arguments = this.VisitExpressionList(initializer.Arguments); ReadOnlyCollection<Expression> arguments = this.VisitExpressionList(initializer.Arguments);
if (arguments != initializer.Arguments) if (arguments != initializer.Arguments)
{ {
return Expression.ElementInit(initializer.AddMethod, arguments); return Expression.ElementInit(initializer.AddMethod, arguments);
} }
return initializer; return initializer;
} }
protected virtual Expression VisitUnary(UnaryExpression u) protected virtual Expression VisitUnary(UnaryExpression u)
{ {
Expression operand = this.Visit(u.Operand); Expression operand = this.Visit(u.Operand);
if (operand != u.Operand) if (operand != u.Operand)
{ {
return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method); return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method);
} }
return u; return u;
} }
protected virtual Expression VisitBinary(BinaryExpression b) protected virtual Expression VisitBinary(BinaryExpression b)
{ {
Expression left = this.Visit(b.Left); Expression left = this.Visit(b.Left);
Expression right = this.Visit(b.Right); Expression right = this.Visit(b.Right);
Expression conversion = this.Visit(b.Conversion); Expression conversion = this.Visit(b.Conversion);
if (left != b.Left || right != b.Right || conversion != b.Conversion) if (left != b.Left || right != b.Right || conversion != b.Conversion)
{ {
if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null) if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null)
return Expression.Coalesce(left, right, conversion as LambdaExpression); return Expression.Coalesce(left, right, conversion as LambdaExpression);
else else
return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method); return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method);
} }
return b; return b;
} }
protected virtual Expression VisitTypeIs(TypeBinaryExpression b) protected virtual Expression VisitTypeIs(TypeBinaryExpression b)
{ {
Expression expr = this.Visit(b.Expression); Expression expr = this.Visit(b.Expression);
if (expr != b.Expression) if (expr != b.Expression)
{ {
return Expression.TypeIs(expr, b.TypeOperand); return Expression.TypeIs(expr, b.TypeOperand);
} }
return b; return b;
} }
protected virtual Expression VisitConstant(ConstantExpression c) protected virtual Expression VisitConstant(ConstantExpression c)
{ {
return c; return c;
} }
protected virtual Expression VisitConditional(ConditionalExpression c) protected virtual Expression VisitConditional(ConditionalExpression c)
{ {
Expression test = this.Visit(c.Test); Expression test = this.Visit(c.Test);
Expression ifTrue = this.Visit(c.IfTrue); Expression ifTrue = this.Visit(c.IfTrue);
Expression ifFalse = this.Visit(c.IfFalse); Expression ifFalse = this.Visit(c.IfFalse);
if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse) if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse)
{ {
return Expression.Condition(test, ifTrue, ifFalse); return Expression.Condition(test, ifTrue, ifFalse);
} }
return c; return c;
} }
protected virtual Expression VisitParameter(ParameterExpression p) protected virtual Expression VisitParameter(ParameterExpression p)
{ {
return p; return p;
} }
protected virtual Expression VisitMemberAccess(MemberExpression m) protected virtual Expression VisitMemberAccess(MemberExpression m)
{ {
Expression exp = this.Visit(m.Expression); Expression exp = this.Visit(m.Expression);
if (exp != m.Expression) if (exp != m.Expression)
{ {
return Expression.MakeMemberAccess(exp, m.Member); return Expression.MakeMemberAccess(exp, m.Member);
} }
return m; return m;
} }
protected virtual Expression VisitMethodCall(MethodCallExpression m) protected virtual Expression VisitMethodCall(MethodCallExpression m)
{ {
Expression obj = this.Visit(m.Object); Expression obj = this.Visit(m.Object);
IEnumerable<Expression> args = this.VisitExpressionList(m.Arguments); IEnumerable<Expression> args = this.VisitExpressionList(m.Arguments);
if (obj != m.Object || args != m.Arguments) if (obj != m.Object || args != m.Arguments)
{ {
return Expression.Call(obj, m.Method, args); return Expression.Call(obj, m.Method, args);
} }
return m; return m;
} }
protected virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original) protected virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original)
{ {
List<Expression> list = null; List<Expression> list = null;
for (int i = 0, n = original.Count; i < n; i++) for (int i = 0, n = original.Count; i < n; i++)
{ {
Expression p = this.Visit(original[i]); Expression p = this.Visit(original[i]);
if (list != null) if (list != null)
{ {
list.Add(p); list.Add(p);
} }
else if (p != original[i]) else if (p != original[i])
{ {
list = new List<Expression>(n); list = new List<Expression>(n);
for (int j = 0; j < i; j++) for (int j = 0; j < i; j++)
{ {
list.Add(original[j]); list.Add(original[j]);
} }
list.Add(p); list.Add(p);
} }
} }
if (list != null) if (list != null)
{ {
return list.AsReadOnly(); return list.AsReadOnly();
} }
return original; return original;
} }
protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment) protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment)
{ {
Expression e = this.Visit(assignment.Expression); Expression e = this.Visit(assignment.Expression);
if (e != assignment.Expression) if (e != assignment.Expression)
{ {
return Expression.Bind(assignment.Member, e); return Expression.Bind(assignment.Member, e);
} }
return assignment; return assignment;
} }
protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding)
{ {
IEnumerable<MemberBinding> bindings = this.VisitBindingList(binding.Bindings); IEnumerable<MemberBinding> bindings = this.VisitBindingList(binding.Bindings);
if (bindings != binding.Bindings) if (bindings != binding.Bindings)
{ {
return Expression.MemberBind(binding.Member, bindings); return Expression.MemberBind(binding.Member, bindings);
} }
return binding; return binding;
} }
protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding) protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding)
{ {
IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(binding.Initializers); IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(binding.Initializers);
if (initializers != binding.Initializers) if (initializers != binding.Initializers)
{ {
return Expression.ListBind(binding.Member, initializers); return Expression.ListBind(binding.Member, initializers);
} }
return binding; return binding;
} }
protected virtual IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original) protected virtual IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original)
{ {
List<MemberBinding> list = null; List<MemberBinding> list = null;
for (int i = 0, n = original.Count; i < n; i++) for (int i = 0, n = original.Count; i < n; i++)
{ {
MemberBinding b = this.VisitBinding(original[i]); MemberBinding b = this.VisitBinding(original[i]);
if (list != null) if (list != null)
{ {
list.Add(b); list.Add(b);
} }
else if (b != original[i]) else if (b != original[i])
{ {
list = new List<MemberBinding>(n); list = new List<MemberBinding>(n);
for (int j = 0; j < i; j++) for (int j = 0; j < i; j++)
{ {
list.Add(original[j]); list.Add(original[j]);
} }
list.Add(b); list.Add(b);
} }
} }
if (list != null) if (list != null)
return list; return list;
return original; return original;
} }
protected virtual IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original) protected virtual IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original)
{ {
List<ElementInit> list = null; List<ElementInit> list = null;
for (int i = 0, n = original.Count; i < n; i++) for (int i = 0, n = original.Count; i < n; i++)
{ {
ElementInit init = this.VisitElementInitializer(original[i]); ElementInit init = this.VisitElementInitializer(original[i]);
if (list != null) if (list != null)
{ {
list.Add(init); list.Add(init);
} }
else if (init != original[i]) else if (init != original[i])
{ {
list = new List<ElementInit>(n); list = new List<ElementInit>(n);
for (int j = 0; j < i; j++) for (int j = 0; j < i; j++)
{ {
list.Add(original[j]); list.Add(original[j]);
} }
list.Add(init); list.Add(init);
} }
} }
if (list != null) if (list != null)
return list; return list;
return original; return original;
} }
protected virtual Expression VisitLambda(LambdaExpression lambda) protected virtual Expression VisitLambda(LambdaExpression lambda)
{ {
Expression body = this.Visit(lambda.Body); Expression body = this.Visit(lambda.Body);
if (body != lambda.Body) if (body != lambda.Body)
{ {
return Expression.Lambda(lambda.Type, body, lambda.Parameters); return Expression.Lambda(lambda.Type, body, lambda.Parameters);
} }
return lambda; return lambda;
} }
protected virtual NewExpression VisitNew(NewExpression nex) protected virtual NewExpression VisitNew(NewExpression nex)
{ {
IEnumerable<Expression> args = this.VisitExpressionList(nex.Arguments); IEnumerable<Expression> args = this.VisitExpressionList(nex.Arguments);
if (args != nex.Arguments) if (args != nex.Arguments)
{ {
if (nex.Members != null) if (nex.Members != null)
return Expression.New(nex.Constructor, args, nex.Members); return Expression.New(nex.Constructor, args, nex.Members);
else else
return Expression.New(nex.Constructor, args); return Expression.New(nex.Constructor, args);
} }
return nex; return nex;
} }
protected virtual Expression VisitMemberInit(MemberInitExpression init) protected virtual Expression VisitMemberInit(MemberInitExpression init)
{ {
NewExpression n = this.VisitNew(init.NewExpression); NewExpression n = this.VisitNew(init.NewExpression);
IEnumerable<MemberBinding> bindings = this.VisitBindingList(init.Bindings); IEnumerable<MemberBinding> bindings = this.VisitBindingList(init.Bindings);
if (n != init.NewExpression || bindings != init.Bindings) if (n != init.NewExpression || bindings != init.Bindings)
{ {
return Expression.MemberInit(n, bindings); return Expression.MemberInit(n, bindings);
} }
return init; return init;
} }
protected virtual Expression VisitListInit(ListInitExpression init) protected virtual Expression VisitListInit(ListInitExpression init)
{ {
NewExpression n = this.VisitNew(init.NewExpression); NewExpression n = this.VisitNew(init.NewExpression);
IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(init.Initializers); IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(init.Initializers);
if (n != init.NewExpression || initializers != init.Initializers) if (n != init.NewExpression || initializers != init.Initializers)
{ {
return Expression.ListInit(n, initializers); return Expression.ListInit(n, initializers);
} }
return init; return init;
} }
protected virtual Expression VisitNewArray(NewArrayExpression na) protected virtual Expression VisitNewArray(NewArrayExpression na)
{ {
IEnumerable<Expression> exprs = this.VisitExpressionList(na.Expressions); IEnumerable<Expression> exprs = this.VisitExpressionList(na.Expressions);
if (exprs != na.Expressions) if (exprs != na.Expressions)
{ {
if (na.NodeType == ExpressionType.NewArrayInit) if (na.NodeType == ExpressionType.NewArrayInit)
{ {
return Expression.NewArrayInit(na.Type.GetElementType(), exprs); return Expression.NewArrayInit(na.Type.GetElementType(), exprs);
} }
else else
{ {
return Expression.NewArrayBounds(na.Type.GetElementType(), exprs); return Expression.NewArrayBounds(na.Type.GetElementType(), exprs);
} }
} }
return na; return na;
} }
protected virtual Expression VisitInvocation(InvocationExpression iv) protected virtual Expression VisitInvocation(InvocationExpression iv)
{ {
IEnumerable<Expression> args = this.VisitExpressionList(iv.Arguments); IEnumerable<Expression> args = this.VisitExpressionList(iv.Arguments);
Expression expr = this.Visit(iv.Expression); Expression expr = this.Visit(iv.Expression);
if (args != iv.Arguments || expr != iv.Expression) if (args != iv.Arguments || expr != iv.Expression)
{ {
return Expression.Invoke(expr, args); return Expression.Invoke(expr, args);
} }
return iv; return iv;
} }
} }
} }

View File

@@ -1,107 +1,107 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Hncore.Infrastructure.Data; using Hncore.Infrastructure.Data;
using Hncore.Infrastructure.Extension; using Hncore.Infrastructure.Extension;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace Hncore.Infrastructure.EntitiesExtension namespace Hncore.Infrastructure.EntitiesExtension
{ {
public static class IQueryableExtend public static class IQueryableExtend
{ {
#region IQueryable<T> #region IQueryable<T>
/// <summary> /// <summary>
/// 返回IQueryable前几条数据 /// 返回IQueryable前几条数据
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="query"></param> /// <param name="query"></param>
/// <param name="TopN"></param> /// <param name="TopN"></param>
/// <returns></returns> /// <returns></returns>
public static IQueryable<T> TopN<T>(this IQueryable<T> query, int TopN) public static IQueryable<T> TopN<T>(this IQueryable<T> query, int TopN)
{ {
return query.Take(TopN); return query.Take(TopN);
} }
#endregion #endregion
#region IQueryable<T> #region IQueryable<T>
/// <summary> /// <summary>
/// 对IQueryable进行分页 /// 对IQueryable进行分页
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="query"></param> /// <param name="query"></param>
/// <param name="PageSize">每页多少条数据</param> /// <param name="PageSize">每页多少条数据</param>
/// <param name="PageIndex">当前页</param> /// <param name="PageIndex">当前页</param>
/// <returns></returns> /// <returns></returns>
public static IQueryable<T> QueryPager<T>(this IQueryable<T> query, int PageSize, int PageIndex) public static IQueryable<T> QueryPager<T>(this IQueryable<T> query, int PageSize, int PageIndex)
{ {
if (PageIndex <= 0) if (PageIndex <= 0)
{ {
PageIndex = 1; PageIndex = 1;
} }
if (PageSize <= 0) if (PageSize <= 0)
{ {
PageSize = 1; PageSize = 1;
} }
if (PageSize > 0) if (PageSize > 0)
return query.Skip((PageIndex - 1) * PageSize).Take(PageSize); return query.Skip((PageIndex - 1) * PageSize).Take(PageSize);
return query; return query;
} }
#endregion #endregion
#region IQueryable<T> #region IQueryable<T>
/// <summary> /// <summary>
/// 得到IQueryable的分页后实体集合 /// 得到IQueryable的分页后实体集合
/// </summary> /// </summary>
/// <param name="query"></param> /// <param name="query"></param>
/// <param name="pageSize">每页多少条数据</param> /// <param name="pageSize">每页多少条数据</param>
/// <param name="pageIndex">当前页</param> /// <param name="pageIndex">当前页</param>
/// <param name="isTotal">是否统计总行数</param> /// <param name="isTotal">是否统计总行数</param>
/// <returns></returns> /// <returns></returns>
public static PageData<T> ListPager<T>(this IQueryable<T> query, int pageSize, int pageIndex, bool isTotal) public static PageData<T> ListPager<T>(this IQueryable<T> query, int pageSize, int pageIndex, bool isTotal)
{ {
PageData<T> list = new PageData<T>(); PageData<T> list = new PageData<T>();
if (isTotal) if (isTotal)
{ {
list.RowCount = query.Count(); list.RowCount = query.Count();
} }
list.List = query.QueryPager<T>(pageSize, pageIndex).ToList(); list.List = query.QueryPager<T>(pageSize, pageIndex).ToList();
return list; return list;
} }
/// <summary> /// <summary>
/// 得到IQueryable的分页后实体集合 /// 得到IQueryable的分页后实体集合
/// </summary> /// </summary>
/// <param name="query"></param> /// <param name="query"></param>
/// <param name="pageSize">每页多少条数据</param> /// <param name="pageSize">每页多少条数据</param>
/// <param name="pageIndex">当前页</param> /// <param name="pageIndex">当前页</param>
/// <param name="isTotal">是否统计总行数</param> /// <param name="isTotal">是否统计总行数</param>
/// <returns></returns> /// <returns></returns>
public static async Task<PageData<T>> ListPagerAsync<T>(this IQueryable<T> query, int pageSize, int pageIndex, public static async Task<PageData<T>> ListPagerAsync<T>(this IQueryable<T> query, int pageSize, int pageIndex,
bool isTotal) bool isTotal)
{ {
PageData<T> list = new PageData<T>(); PageData<T> list = new PageData<T>();
if (isTotal) if (isTotal)
{ {
list.RowCount = await query.CountAsync(); list.RowCount = await query.CountAsync();
} }
list.List = await query.QueryPager<T>(pageSize, pageIndex).ToListAsync(); list.List = await query.QueryPager<T>(pageSize, pageIndex).ToListAsync();
return list; return list;
} }
#endregion #endregion
} }
} }

View File

@@ -1,44 +1,44 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq.Expressions; using System.Linq.Expressions;
namespace Hncore.Infrastructure.EntitiesExtension namespace Hncore.Infrastructure.EntitiesExtension
{ {
public class ParameterRebinder : ExpressionVisitor public class ParameterRebinder : ExpressionVisitor
{ {
private readonly Dictionary<ParameterExpression, ParameterExpression> map; private readonly Dictionary<ParameterExpression, ParameterExpression> map;
/// <summary> /// <summary>
/// Default construcotr /// Default construcotr
/// </summary> /// </summary>
/// <param name="map">Map specification</param> /// <param name="map">Map specification</param>
public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map) public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{ {
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>(); this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
} }
/// <summary> /// <summary>
/// Replate parameters in expression with a Map information /// Replate parameters in expression with a Map information
/// </summary> /// </summary>
/// <param name="map">Map information</param> /// <param name="map">Map information</param>
/// <param name="exp">Expression to replace parameters</param> /// <param name="exp">Expression to replace parameters</param>
/// <returns>Expression with parameters replaced</returns> /// <returns>Expression with parameters replaced</returns>
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp) public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{ {
return new ParameterRebinder(map).Visit(exp); return new ParameterRebinder(map).Visit(exp);
} }
/// <summary> /// <summary>
/// Visit pattern method /// Visit pattern method
/// </summary> /// </summary>
/// <param name="p">A Parameter expression</param> /// <param name="p">A Parameter expression</param>
/// <returns>New visited expression</returns> /// <returns>New visited expression</returns>
protected override Expression VisitParameter(ParameterExpression p) protected override Expression VisitParameter(ParameterExpression p)
{ {
ParameterExpression replacement; ParameterExpression replacement;
if (map.TryGetValue(p, out replacement)) if (map.TryGetValue(p, out replacement))
{ {
p = replacement; p = replacement;
} }
return base.VisitParameter(p); return base.VisitParameter(p);
} }
} }
} }

View File

@@ -1,115 +1,115 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq.Expressions; using System.Linq.Expressions;
namespace Hncore.Infrastructure.EntitiesExtension namespace Hncore.Infrastructure.EntitiesExtension
{ {
public class PartialEvaluator : ExpressionVisitor public class PartialEvaluator : ExpressionVisitor
{ {
private Func<Expression, bool> m_fnCanBeEvaluated; private Func<Expression, bool> m_fnCanBeEvaluated;
private HashSet<Expression> m_candidates; private HashSet<Expression> m_candidates;
public PartialEvaluator() public PartialEvaluator()
: this(CanBeEvaluatedLocally) : this(CanBeEvaluatedLocally)
{ } { }
public PartialEvaluator(Func<Expression, bool> fnCanBeEvaluated) public PartialEvaluator(Func<Expression, bool> fnCanBeEvaluated)
{ {
this.m_fnCanBeEvaluated = fnCanBeEvaluated; this.m_fnCanBeEvaluated = fnCanBeEvaluated;
} }
public Expression Eval(Expression exp) public Expression Eval(Expression exp)
{ {
this.m_candidates = new Nominator(this.m_fnCanBeEvaluated).Nominate(exp); this.m_candidates = new Nominator(this.m_fnCanBeEvaluated).Nominate(exp);
return this.Visit(exp); return this.Visit(exp);
} }
protected override Expression Visit(Expression exp) protected override Expression Visit(Expression exp)
{ {
if (exp == null) if (exp == null)
{ {
return null; return null;
} }
if (this.m_candidates.Contains(exp)) if (this.m_candidates.Contains(exp))
{ {
return this.Evaluate(exp); return this.Evaluate(exp);
} }
return base.Visit(exp); return base.Visit(exp);
} }
private Expression Evaluate(Expression e) private Expression Evaluate(Expression e)
{ {
if (e.NodeType == ExpressionType.Constant) if (e.NodeType == ExpressionType.Constant)
{ {
return e; return e;
} }
LambdaExpression lambda = Expression.Lambda(e); LambdaExpression lambda = Expression.Lambda(e);
Delegate fn = lambda.Compile(); Delegate fn = lambda.Compile();
return Expression.Constant(fn.DynamicInvoke(null), e.Type); return Expression.Constant(fn.DynamicInvoke(null), e.Type);
} }
private static bool CanBeEvaluatedLocally(Expression exp) private static bool CanBeEvaluatedLocally(Expression exp)
{ {
return exp.NodeType != ExpressionType.Parameter; return exp.NodeType != ExpressionType.Parameter;
} }
#region Nominator #region Nominator
/// <summary> /// <summary>
/// Performs bottom-up analysis to determine which nodes can possibly /// Performs bottom-up analysis to determine which nodes can possibly
/// be part of an evaluated sub-tree. /// be part of an evaluated sub-tree.
/// </summary> /// </summary>
private class Nominator : ExpressionVisitor private class Nominator : ExpressionVisitor
{ {
private Func<Expression, bool> m_fnCanBeEvaluated; private Func<Expression, bool> m_fnCanBeEvaluated;
private HashSet<Expression> m_candidates; private HashSet<Expression> m_candidates;
private bool m_cannotBeEvaluated; private bool m_cannotBeEvaluated;
internal Nominator(Func<Expression, bool> fnCanBeEvaluated) internal Nominator(Func<Expression, bool> fnCanBeEvaluated)
{ {
this.m_fnCanBeEvaluated = fnCanBeEvaluated; this.m_fnCanBeEvaluated = fnCanBeEvaluated;
} }
internal HashSet<Expression> Nominate(Expression expression) internal HashSet<Expression> Nominate(Expression expression)
{ {
this.m_candidates = new HashSet<Expression>(); this.m_candidates = new HashSet<Expression>();
this.Visit(expression); this.Visit(expression);
return this.m_candidates; return this.m_candidates;
} }
protected override Expression Visit(Expression expression) protected override Expression Visit(Expression expression)
{ {
if (expression != null) if (expression != null)
{ {
bool saveCannotBeEvaluated = this.m_cannotBeEvaluated; bool saveCannotBeEvaluated = this.m_cannotBeEvaluated;
this.m_cannotBeEvaluated = false; this.m_cannotBeEvaluated = false;
base.Visit(expression); base.Visit(expression);
if (!this.m_cannotBeEvaluated) if (!this.m_cannotBeEvaluated)
{ {
if (this.m_fnCanBeEvaluated(expression)) if (this.m_fnCanBeEvaluated(expression))
{ {
this.m_candidates.Add(expression); this.m_candidates.Add(expression);
} }
else else
{ {
this.m_cannotBeEvaluated = true; this.m_cannotBeEvaluated = true;
} }
} }
this.m_cannotBeEvaluated |= saveCannotBeEvaluated; this.m_cannotBeEvaluated |= saveCannotBeEvaluated;
} }
return expression; return expression;
} }
} }
#endregion #endregion
} }
} }

View File

@@ -1,24 +1,24 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Hncore.Infrastructure.Events namespace Hncore.Infrastructure.Events
{ {
internal class ActionEventHandler<TEventData> : IEventHandler<TEventData> where TEventData : IEventData internal class ActionEventHandler<TEventData> : IEventHandler<TEventData> where TEventData : IEventData
{ {
public Action<TEventData> Action { get; private set; } public Action<TEventData> Action { get; private set; }
public virtual bool Ansyc { get; set; } public virtual bool Ansyc { get; set; }
public ActionEventHandler(Action<TEventData> handler) public ActionEventHandler(Action<TEventData> handler)
{ {
Action = handler; Action = handler;
} }
public void HandleEvent(TEventData eventData) public void HandleEvent(TEventData eventData)
{ {
Action(eventData); Action(eventData);
} }
} }
} }

View File

@@ -1,150 +1,150 @@
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Hncore.Infrastructure.Events namespace Hncore.Infrastructure.Events
{ {
/// <summary> /// <summary>
/// 事件总线 /// 事件总线
/// </summary> /// </summary>
public class EventBus public class EventBus
{ {
private static EventBus _eventBus = null; private static EventBus _eventBus = null;
public static EventBus Default public static EventBus Default
{ {
get { return _eventBus ?? (_eventBus = new EventBus()); } get { return _eventBus ?? (_eventBus = new EventBus()); }
} }
/// <summary> /// <summary>
/// 定义线程安全集合 /// 定义线程安全集合
/// </summary> /// </summary>
private readonly ConcurrentDictionary<Type, List<IEventHandler>> _eventAndHandlerMapping; private readonly ConcurrentDictionary<Type, List<IEventHandler>> _eventAndHandlerMapping;
public EventBus() public EventBus()
{ {
_eventAndHandlerMapping = new ConcurrentDictionary<Type, List<IEventHandler>>(); _eventAndHandlerMapping = new ConcurrentDictionary<Type, List<IEventHandler>>();
MapEventToHandler(); MapEventToHandler();
} }
/// <summary> /// <summary>
///通过反射,将事件源与事件处理绑定 ///通过反射,将事件源与事件处理绑定
/// </summary> /// </summary>
private void MapEventToHandler() private void MapEventToHandler()
{ {
// Assembly assembly = Assembly.GetEntryAssembly(); // Assembly assembly = Assembly.GetEntryAssembly();
var allAssembly = AppDomain.CurrentDomain.GetAssemblies().Where(item => item.FullName.Contains("Microkj.")); var allAssembly = AppDomain.CurrentDomain.GetAssemblies().Where(item => item.FullName.Contains("Microkj."));
if (!allAssembly.Any()) if (!allAssembly.Any())
{ {
return; return;
} }
foreach (var assembly in allAssembly) foreach (var assembly in allAssembly)
{ {
foreach (var type in assembly.GetTypes()) foreach (var type in assembly.GetTypes())
{ {
if (!type.IsGenericType && typeof(IEventHandler).IsAssignableFrom(type)) //判断当前类型是否实现了IEventHandler接口 if (!type.IsGenericType && typeof(IEventHandler).IsAssignableFrom(type)) //判断当前类型是否实现了IEventHandler接口
{ {
Type handlerInterface = type.GetInterface("IEventHandler`1"); //获取该类实现的泛型接口 Type handlerInterface = type.GetInterface("IEventHandler`1"); //获取该类实现的泛型接口
if (handlerInterface != null) if (handlerInterface != null)
{ {
Type eventDataType = handlerInterface.GetGenericArguments()[0]; // 获取泛型接口指定的参数类型 Type eventDataType = handlerInterface.GetGenericArguments()[0]; // 获取泛型接口指定的参数类型
if (_eventAndHandlerMapping.ContainsKey(eventDataType)) if (_eventAndHandlerMapping.ContainsKey(eventDataType))
{ {
List<IEventHandler> handlerTypes = _eventAndHandlerMapping[eventDataType]; List<IEventHandler> handlerTypes = _eventAndHandlerMapping[eventDataType];
handlerTypes.Add(Activator.CreateInstance(type) as IEventHandler); handlerTypes.Add(Activator.CreateInstance(type) as IEventHandler);
_eventAndHandlerMapping[eventDataType] = handlerTypes; _eventAndHandlerMapping[eventDataType] = handlerTypes;
} }
else else
{ {
var handlerTypes = new List<IEventHandler> var handlerTypes = new List<IEventHandler>
{ {
Activator.CreateInstance(type) as IEventHandler Activator.CreateInstance(type) as IEventHandler
}; };
_eventAndHandlerMapping[eventDataType] = handlerTypes; _eventAndHandlerMapping[eventDataType] = handlerTypes;
} }
} }
} }
} }
} }
} }
/// <summary> /// <summary>
/// 手动绑定事件源与事件处理 /// 手动绑定事件源与事件处理
/// </summary> /// </summary>
/// <typeparam name="TEventData"></typeparam> /// <typeparam name="TEventData"></typeparam>
/// <param name="eventHandler"></param> /// <param name="eventHandler"></param>
public void Register<TEventData>(IEventHandler eventHandler) public void Register<TEventData>(IEventHandler eventHandler)
{ {
if (_eventAndHandlerMapping.Keys.Contains(typeof (TEventData))) if (_eventAndHandlerMapping.Keys.Contains(typeof (TEventData)))
{ {
List<IEventHandler> handlerTypes = _eventAndHandlerMapping[typeof (TEventData)]; List<IEventHandler> handlerTypes = _eventAndHandlerMapping[typeof (TEventData)];
if (!handlerTypes.Contains(eventHandler)) if (!handlerTypes.Contains(eventHandler))
{ {
handlerTypes.Add(eventHandler); handlerTypes.Add(eventHandler);
_eventAndHandlerMapping[typeof (TEventData)] = handlerTypes; _eventAndHandlerMapping[typeof (TEventData)] = handlerTypes;
} }
} }
else else
{ {
_eventAndHandlerMapping.GetOrAdd(typeof (TEventData), (type) => new List<IEventHandler>()) _eventAndHandlerMapping.GetOrAdd(typeof (TEventData), (type) => new List<IEventHandler>())
.Add(eventHandler); .Add(eventHandler);
} }
} }
public void Register<TEventData>(Action<TEventData> action) where TEventData : IEventData public void Register<TEventData>(Action<TEventData> action) where TEventData : IEventData
{ {
var actionHandler = new ActionEventHandler<TEventData>(action); var actionHandler = new ActionEventHandler<TEventData>(action);
Register<TEventData>(actionHandler); Register<TEventData>(actionHandler);
} }
/// <summary> /// <summary>
/// 手动解除事件源与事件处理的绑定 /// 手动解除事件源与事件处理的绑定
/// </summary> /// </summary>
/// <typeparam name="TEventData"></typeparam> /// <typeparam name="TEventData"></typeparam>
/// <param name="eventHandler"></param> /// <param name="eventHandler"></param>
public void UnRegister<TEventData>(Type eventHandler) public void UnRegister<TEventData>(Type eventHandler)
{ {
List<IEventHandler> handlerTypes = _eventAndHandlerMapping[typeof (TEventData)]; List<IEventHandler> handlerTypes = _eventAndHandlerMapping[typeof (TEventData)];
_eventAndHandlerMapping.GetOrAdd(typeof (TEventData), (type) => new List<IEventHandler>()) _eventAndHandlerMapping.GetOrAdd(typeof (TEventData), (type) => new List<IEventHandler>())
.RemoveAll(t => t.GetType() == eventHandler); .RemoveAll(t => t.GetType() == eventHandler);
} }
/// <summary> /// <summary>
/// 根据事件源触发绑定的事件处理 /// 根据事件源触发绑定的事件处理
/// </summary> /// </summary>
/// <typeparam name="TEventData"></typeparam> /// <typeparam name="TEventData"></typeparam>
/// <param name="eventData"></param> /// <param name="eventData"></param>
public static void Publish<TEventData>(TEventData eventData) where TEventData : IEventData public static void Publish<TEventData>(TEventData eventData) where TEventData : IEventData
{ {
List<IEventHandler> handlers = Default._eventAndHandlerMapping[typeof (TEventData)]; List<IEventHandler> handlers = Default._eventAndHandlerMapping[typeof (TEventData)];
if (handlers != null && handlers.Count > 0) if (handlers != null && handlers.Count > 0)
{ {
foreach (var handler in handlers) foreach (var handler in handlers)
{ {
var eventHandler = handler as IEventHandler<TEventData>; var eventHandler = handler as IEventHandler<TEventData>;
if (eventHandler.Ansyc) if (eventHandler.Ansyc)
{ {
Task.Run(() => Task.Run(() =>
{ {
eventHandler.HandleEvent(eventData); eventHandler.HandleEvent(eventData);
}); });
} }
else else
{ {
eventHandler.HandleEvent(eventData); eventHandler.HandleEvent(eventData);
} }
} }
} }
} }
} }
} }

View File

@@ -1,39 +1,39 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Hncore.Infrastructure.Events namespace Hncore.Infrastructure.Events
{ {
/// <summary> /// <summary>
/// 事件源:描述事件信息,用于参数传递 /// 事件源:描述事件信息,用于参数传递
/// </summary> /// </summary>
public class EventData<TData> : IEventData where TData:class public class EventData<TData> : IEventData where TData:class
{ {
/// <summary> /// <summary>
/// 事件发生的时间 /// 事件发生的时间
/// </summary> /// </summary>
public DateTime EventTime { get; set; } public DateTime EventTime { get; set; }
/// <summary> /// <summary>
/// 触发事件的对象 /// 触发事件的对象
/// </summary> /// </summary>
public TData EventSource { get; set; } public TData EventSource { get; set; }
object IEventData.EventSource object IEventData.EventSource
{ {
get get
{ {
return this.EventSource as TData; return this.EventSource as TData;
} }
set { this.EventSource =(TData) value; } set { this.EventSource =(TData) value; }
} }
public EventData() public EventData()
{ {
EventTime = DateTime.Now; EventTime = DateTime.Now;
} }
} }
} }

View File

@@ -1,19 +1,19 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Hncore.Infrastructure.Events namespace Hncore.Infrastructure.Events
{ {
public interface IEventBus public interface IEventBus
{ {
void Register<TEventData>(IEventHandler eventHandler); void Register<TEventData>(IEventHandler eventHandler);
void Register<TEventData>(Action<TEventData> action) where TEventData : IEventData; void Register<TEventData>(Action<TEventData> action) where TEventData : IEventData;
void UnRegister<TEventData>(Type eventHandler); void UnRegister<TEventData>(Type eventHandler);
// void Trigger<TEventData>(TEventData eventData) where TEventData : IEventData; // void Trigger<TEventData>(TEventData eventData) where TEventData : IEventData;
} }
} }

View File

@@ -1,24 +1,24 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Hncore.Infrastructure.Events namespace Hncore.Infrastructure.Events
{ {
/// <summary> /// <summary>
/// 定义事件源接口,所有的事件源都要实现该接口 /// 定义事件源接口,所有的事件源都要实现该接口
/// </summary> /// </summary>
public interface IEventData public interface IEventData
{ {
/// <summary> /// <summary>
/// 事件发生的时间 /// 事件发生的时间
/// </summary> /// </summary>
DateTime EventTime { get; set; } DateTime EventTime { get; set; }
/// <summary> /// <summary>
/// 触发事件的对象 /// 触发事件的对象
/// </summary> /// </summary>
Object EventSource { get; set; } Object EventSource { get; set; }
} }
} }

View File

@@ -1,29 +1,29 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Hncore.Infrastructure.Events namespace Hncore.Infrastructure.Events
{ {
/// <summary> /// <summary>
/// 定义事件处理器公共接口,所有的事件处理都要实现该接口 /// 定义事件处理器公共接口,所有的事件处理都要实现该接口
/// </summary> /// </summary>
public interface IEventHandler public interface IEventHandler
{ {
} }
/// <summary> /// <summary>
/// 泛型事件处理器接口 /// 泛型事件处理器接口
/// </summary> /// </summary>
/// <typeparam name="TEventData"></typeparam> /// <typeparam name="TEventData"></typeparam>
public interface IEventHandler<TEventData> : IEventHandler where TEventData : IEventData public interface IEventHandler<TEventData> : IEventHandler where TEventData : IEventData
{ {
bool Ansyc { get; set; } bool Ansyc { get; set; }
/// <summary> /// <summary>
/// 事件处理器实现该方法来处理事件 /// 事件处理器实现该方法来处理事件
/// </summary> /// </summary>
/// <param name="eventData"></param> /// <param name="eventData"></param>
void HandleEvent(TEventData eventData); void HandleEvent(TEventData eventData);
} }
} }

View File

@@ -1,21 +1,21 @@
using System; using System;
using System.Reflection; using System.Reflection;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
/// <summary> /// <summary>
/// 程序集扩展类 /// 程序集扩展类
/// </summary> /// </summary>
public static class AssemblyExtension public static class AssemblyExtension
{ {
/// <summary> /// <summary>
///得到程序集友好名字 ///得到程序集友好名字
/// </summary> /// </summary>
/// <param name="para"></param> /// <param name="para"></param>
/// <returns></returns> /// <returns></returns>
public static string GetFriendName(this Assembly asm) public static string GetFriendName(this Assembly asm)
{ {
return asm.ManifestModule?.Name?.TrimEnd(".dll".ToCharArray()); return asm.ManifestModule?.Name?.TrimEnd(".dll".ToCharArray());
} }
} }
} }

View File

@@ -1,60 +1,60 @@
using System; using System;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
/// <summary> /// <summary>
/// bool类型扩展 /// bool类型扩展
/// </summary> /// </summary>
public static class BoolExtension public static class BoolExtension
{ {
/// <summary> /// <summary>
/// 转为bool /// 转为bool
/// </summary> /// </summary>
/// <param name="para"></param> /// <param name="para"></param>
/// <returns></returns> /// <returns></returns>
public static bool ToBool(this bool? para) public static bool ToBool(this bool? para)
{ {
if (para == null) if (para == null)
{ {
return false; return false;
} }
return Convert.ToBoolean(para); return Convert.ToBoolean(para);
} }
/// <summary> /// <summary>
/// 转为bool /// 转为bool
/// </summary> /// </summary>
/// <param name="obj"></param> /// <param name="obj"></param>
/// <returns></returns> /// <returns></returns>
public static bool ToBool(this object obj) public static bool ToBool(this object obj)
{ {
if (obj == null) if (obj == null)
{ {
return false; return false;
} }
bool.TryParse(obj.ToString(), out var para); bool.TryParse(obj.ToString(), out var para);
return para; return para;
} }
public static bool ToBool(this sbyte? obj) public static bool ToBool(this sbyte? obj)
{ {
if (obj == null) if (obj == null)
{ {
return false; return false;
} }
sbyte num = (sbyte) obj; sbyte num = (sbyte) obj;
if (num == 1) if (num == 1)
{ {
return true; return true;
} }
return false; return false;
} }
} }
} }

View File

@@ -1,177 +1,177 @@
using System; using System;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
public static class DateTimeExtension public static class DateTimeExtension
{ {
public static string Format(this DateTime time, string format = "yyyy-MM-dd") public static string Format(this DateTime time, string format = "yyyy-MM-dd")
{ {
return time.ToString(format); return time.ToString(format);
} }
private static DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); private static DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long CurrentTimeMillis() public static long CurrentTimeMillis()
{ {
return (long) ((DateTime.UtcNow - Jan1st1970).TotalMilliseconds); return (long) ((DateTime.UtcNow - Jan1st1970).TotalMilliseconds);
} }
public static long CurrentTimeMillis(DateTime time) public static long CurrentTimeMillis(DateTime time)
{ {
return (long) ((time.ToUniversalTime() - Jan1st1970).TotalMilliseconds); return (long) ((time.ToUniversalTime() - Jan1st1970).TotalMilliseconds);
} }
public static string Format(this DateTime? dateTime, string format = "yyyy-MM-dd") public static string Format(this DateTime? dateTime, string format = "yyyy-MM-dd")
{ {
return Convert.ToDateTime(dateTime).ToString(format); return Convert.ToDateTime(dateTime).ToString(format);
} }
public static DateTime ToDateTime(this DateTime? dateTime, DateTime defaultTime) public static DateTime ToDateTime(this DateTime? dateTime, DateTime defaultTime)
{ {
if (dateTime != null) if (dateTime != null)
{ {
return Convert.ToDateTime(dateTime); return Convert.ToDateTime(dateTime);
} }
return defaultTime; return defaultTime;
} }
public static bool Between(this DateTime time, DateTime beginTime, DateTime endTime) public static bool Between(this DateTime time, DateTime beginTime, DateTime endTime)
{ {
return time >= beginTime && time <= endTime; return time >= beginTime && time <= endTime;
} }
/// <summary> /// <summary>
/// 取得某月的第一天 /// 取得某月的第一天
/// </summary> /// </summary>
/// <param name="datetime">要取得月份第一天的时间</param> /// <param name="datetime">要取得月份第一天的时间</param>
/// <returns></returns> /// <returns></returns>
public static DateTime FirstDayOfMonth(this DateTime datetime) public static DateTime FirstDayOfMonth(this DateTime datetime)
{ {
return datetime.AddDays(1 - datetime.Day); return datetime.AddDays(1 - datetime.Day);
} }
/**/ /**/
/// <summary> /// <summary>
/// 取得某月的最后一天 /// 取得某月的最后一天
/// </summary> /// </summary>
/// <param name="datetime">要取得月份最后一天的时间</param> /// <param name="datetime">要取得月份最后一天的时间</param>
/// <returns></returns> /// <returns></returns>
public static DateTime LastDayOfMonth(this DateTime datetime) public static DateTime LastDayOfMonth(this DateTime datetime)
{ {
return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1); return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
} }
/**/ /**/
/// <summary> /// <summary>
/// 取得上个月第一天 /// 取得上个月第一天
/// </summary> /// </summary>
/// <param name="datetime">要取得上个月第一天的当前时间</param> /// <param name="datetime">要取得上个月第一天的当前时间</param>
/// <returns></returns> /// <returns></returns>
public static DateTime FirstDayOfPreviousMonth(this DateTime datetime) public static DateTime FirstDayOfPreviousMonth(this DateTime datetime)
{ {
return datetime.AddDays(1 - datetime.Day).AddMonths(-1); return datetime.AddDays(1 - datetime.Day).AddMonths(-1);
} }
/**/ /**/
/// <summary> /// <summary>
/// 取得上个月的最后一天 /// 取得上个月的最后一天
/// </summary> /// </summary>
/// <param name="datetime">要取得上个月最后一天的当前时间</param> /// <param name="datetime">要取得上个月最后一天的当前时间</param>
/// <returns></returns> /// <returns></returns>
public static DateTime LastDayOfPrdviousMonth(this DateTime datetime) public static DateTime LastDayOfPrdviousMonth(this DateTime datetime)
{ {
return datetime.AddDays(1 - datetime.Day).AddDays(-1); return datetime.AddDays(1 - datetime.Day).AddDays(-1);
} }
/// <summary> /// <summary>
/// 获取时间的Unix时间戳 /// 获取时间的Unix时间戳
/// </summary> /// </summary>
/// <param name="tm">时间对象</param> /// <param name="tm">时间对象</param>
/// <returns>Unix时间戳</returns> /// <returns>Unix时间戳</returns>
/// ///
public static long GetUnixTimeStamp(this DateTime tm) public static long GetUnixTimeStamp(this DateTime tm)
{ {
long result = (tm.ToUniversalTime().Ticks - 621355968000000000) / 10000000; long result = (tm.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
return result; return result;
} }
/// <summary> /// <summary>
/// 从Uninx转换时间 /// 从Uninx转换时间
/// </summary> /// </summary>
/// <param name="tm">时间对象</param> /// <param name="tm">时间对象</param>
/// <param name="timeStamp">时间戳</param> /// <param name="timeStamp">时间戳</param>
/// <returns>新时间对象</returns> /// <returns>新时间对象</returns>
/// ///
public static DateTime LoadFromUnixTimeStamp(this DateTime tm,double timeStamp) public static DateTime LoadFromUnixTimeStamp(this DateTime tm,double timeStamp)
{ {
DateTime startTime=TimeZoneInfo.ConvertTime(new System.DateTime(1970, 1, 1),TimeZoneInfo.Local); DateTime startTime=TimeZoneInfo.ConvertTime(new System.DateTime(1970, 1, 1),TimeZoneInfo.Local);
DateTime result=startTime.AddSeconds(timeStamp); DateTime result=startTime.AddSeconds(timeStamp);
return result; return result;
} }
public static DateTime LoadFromUnixTimeStamp(this long timeStamp) public static DateTime LoadFromUnixTimeStamp(this long timeStamp)
{ {
DateTime startTime = TimeZoneInfo.ConvertTime(new System.DateTime(1970, 1, 1), TimeZoneInfo.Local); DateTime startTime = TimeZoneInfo.ConvertTime(new System.DateTime(1970, 1, 1), TimeZoneInfo.Local);
DateTime result = startTime.AddSeconds(timeStamp); DateTime result = startTime.AddSeconds(timeStamp);
return result; return result;
} }
/// <summary> /// <summary>
/// 时间戳转换成时间 /// 时间戳转换成时间
/// </summary> /// </summary>
/// <param name="timestamp">时间戳</param> /// <param name="timestamp">时间戳</param>
/// <param name="millisecond">是否毫秒级,true毫秒级(默认值)</param> /// <param name="millisecond">是否毫秒级,true毫秒级(默认值)</param>
/// <param name="localTime">是否输出本地时间,true本地时间(默认值)</param> /// <param name="localTime">是否输出本地时间,true本地时间(默认值)</param>
/// <returns></returns> /// <returns></returns>
public static DateTime? LoadFromUnixTimeStamp(this string timestamp) public static DateTime? LoadFromUnixTimeStamp(this string timestamp)
{ {
if (long.TryParse(timestamp, out long ts)) if (long.TryParse(timestamp, out long ts))
{ {
return ts.LoadFromUnixTimeStamp(); return ts.LoadFromUnixTimeStamp();
} }
return null; return null;
} }
/// <summary> /// <summary>
/// 1970 到现在的秒数 /// 1970 到现在的秒数
/// </summary> /// </summary>
/// <param name="time"></param> /// <param name="time"></param>
/// <returns></returns> /// <returns></returns>
public static int TimestampFrom19700101(this DateTime time) public static int TimestampFrom19700101(this DateTime time)
{ {
return (int)(time - new DateTime(1970, 01, 01)).TotalSeconds; return (int)(time - new DateTime(1970, 01, 01)).TotalSeconds;
} }
#region #region
public static DateTime Date(this DateTime? time) public static DateTime Date(this DateTime? time)
{ {
return Convert.ToDateTime(time).Date; return Convert.ToDateTime(time).Date;
} }
public static DateTime NextDate(this DateTime? time) public static DateTime NextDate(this DateTime? time)
{ {
return Convert.ToDateTime(time).Date.AddDays(1); return Convert.ToDateTime(time).Date.AddDays(1);
} }
public static DateTime Date(this DateTime time) public static DateTime Date(this DateTime time)
{ {
return time.Date; return time.Date;
} }
public static DateTime NextDate(this DateTime time) public static DateTime NextDate(this DateTime time)
{ {
return time.Date.AddDays(1); return time.Date.AddDays(1);
} }
#endregion #endregion
public static DateTime Begin(this DateTime time) public static DateTime Begin(this DateTime time)
{ {
return new DateTime(time.Year, time.Month, time.Day); return new DateTime(time.Year, time.Month, time.Day);
} }
public static DateTime End(this DateTime time) public static DateTime End(this DateTime time)
{ {
return new DateTime(time.Year, time.Month, time.Day,23,59,59); return new DateTime(time.Year, time.Month, time.Day,23,59,59);
} }
} }
} }

View File

@@ -1,24 +1,24 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Data.Common; using System.Data.Common;
using System.Dynamic; using System.Dynamic;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
public static class DbDataReaderExtension public static class DbDataReaderExtension
{ {
public static IDictionary<string, object> GetDataRow(this DbDataReader dataReader) public static IDictionary<string, object> GetDataRow(this DbDataReader dataReader)
{ {
var dataRow = new ExpandoObject() as IDictionary<string, object>; var dataRow = new ExpandoObject() as IDictionary<string, object>;
for (var iFiled = 0; iFiled < dataReader.FieldCount; iFiled++) for (var iFiled = 0; iFiled < dataReader.FieldCount; iFiled++)
{ {
dataRow.Add( dataRow.Add(
dataReader.GetName(iFiled), dataReader.GetName(iFiled),
dataReader.IsDBNull(iFiled) ? "" : dataReader[iFiled] dataReader.IsDBNull(iFiled) ? "" : dataReader[iFiled]
); );
} }
return dataRow; return dataRow;
} }
} }
} }

View File

@@ -1,149 +1,149 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
public static class EnumExtension public static class EnumExtension
{ {
public static Dictionary<int, string> ToDictionary<T>() public static Dictionary<int, string> ToDictionary<T>()
{ {
Dictionary<int, string> dic = new Dictionary<int, string>(); Dictionary<int, string> dic = new Dictionary<int, string>();
string namestr = ""; string namestr = "";
foreach (var e in Enum.GetValues(typeof(T))) foreach (var e in Enum.GetValues(typeof(T)))
{ {
namestr = ""; namestr = "";
object[] objArrDisplay = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DisplayAttribute), true);//Display object[] objArrDisplay = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DisplayAttribute), true);//Display
if (objArrDisplay.Any()) if (objArrDisplay.Any())
{ {
var da = objArrDisplay[0] as DisplayAttribute; var da = objArrDisplay[0] as DisplayAttribute;
namestr = da.Name; namestr = da.Name;
} }
else else
{ {
object[] objArrDescription = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);//Description object[] objArrDescription = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);//Description
namestr = objArrDescription.Any() ? (objArrDescription[0] as DescriptionAttribute).Description : e.ToString(); namestr = objArrDescription.Any() ? (objArrDescription[0] as DescriptionAttribute).Description : e.ToString();
} }
int value = Convert.ToInt32(e); int value = Convert.ToInt32(e);
// string str = item.GetDescription(); // string str = item.GetDescription();
// int value = (int) item; // int value = (int) item;
dic.Add(value, namestr); dic.Add(value, namestr);
} }
return dic; return dic;
} }
#region #region
/// <summary> /// <summary>
/// 获取枚举的相关信息的集合 /// 获取枚举的相关信息的集合
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <returns></returns> /// <returns></returns>
public static List<EnumInfo> EnumToList<T>() public static List<EnumInfo> EnumToList<T>()
{ {
var list = new List<EnumInfo>(); var list = new List<EnumInfo>();
foreach (var e in Enum.GetValues(typeof(T))) foreach (var e in Enum.GetValues(typeof(T)))
{ {
var m = new EnumInfo(); var m = new EnumInfo();
object[] objArrDisplay = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DisplayAttribute), true);//Display object[] objArrDisplay = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DisplayAttribute), true);//Display
if (objArrDisplay.Any()) if (objArrDisplay.Any())
{ {
var da = objArrDisplay[0] as DisplayAttribute; var da = objArrDisplay[0] as DisplayAttribute;
m.Name = da.Name; m.Name = da.Name;
} }
else else
{ {
object[] objArrDescription = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);//Description object[] objArrDescription = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);//Description
m.Name = objArrDescription.Any() ? (objArrDescription[0] as DescriptionAttribute).Description : e.ToString(); m.Name = objArrDescription.Any() ? (objArrDescription[0] as DescriptionAttribute).Description : e.ToString();
} }
m.Value = Convert.ToInt32(e); m.Value = Convert.ToInt32(e);
list.Add(m); list.Add(m);
} }
return list; return list;
} }
public class EnumInfo public class EnumInfo
{ {
public string Name { set; get; } public string Name { set; get; }
public int Value { set; get; } public int Value { set; get; }
} }
#endregion #endregion
public static string GetDisplayName<T>(T enumValue) public static string GetDisplayName<T>(T enumValue)
{ {
object[] objArrDisplay = enumValue.GetType().GetField(enumValue.ToString()) object[] objArrDisplay = enumValue.GetType().GetField(enumValue.ToString())
?.GetCustomAttributes(typeof(DisplayAttribute), true);//Display ?.GetCustomAttributes(typeof(DisplayAttribute), true);//Display
if (objArrDisplay!=null&&objArrDisplay.Any()) if (objArrDisplay!=null&&objArrDisplay.Any())
{ {
var da = objArrDisplay[0] as DisplayAttribute; var da = objArrDisplay[0] as DisplayAttribute;
return da?.Name; return da?.Name;
} }
return ""; return "";
} }
/// <summary> /// <summary>
/// 获取枚举上通过DisplayName、Description或Display柱注的名称 /// 获取枚举上通过DisplayName、Description或Display柱注的名称
/// 优先级为DisplayName>Description>Display /// 优先级为DisplayName>Description>Display
/// </summary> /// </summary>
/// <param name="e">枚举值</param> /// <param name="e">枚举值</param>
/// <returns>枚举名称</returns> /// <returns>枚举名称</returns>
/// ///
public static string GetEnumDisplayName(this Enum e) public static string GetEnumDisplayName(this Enum e)
{ {
try try
{ {
Type t = e.GetType(); Type t = e.GetType();
FieldInfo fi = t.GetField(Enum.GetName(t, e)); FieldInfo fi = t.GetField(Enum.GetName(t, e));
var dna = fi.GetCustomAttribute<DisplayNameAttribute>(); var dna = fi.GetCustomAttribute<DisplayNameAttribute>();
if (dna != null) if (dna != null)
return dna.DisplayName; return dna.DisplayName;
var da = fi.GetCustomAttribute<DescriptionAttribute>(); var da = fi.GetCustomAttribute<DescriptionAttribute>();
if (da != null) if (da != null)
return da.Description; return da.Description;
var d = fi.GetCustomAttribute<DisplayAttribute>(); var d = fi.GetCustomAttribute<DisplayAttribute>();
if (d != null) if (d != null)
return d.Name; return d.Name;
} }
catch (Exception ex) catch (Exception ex)
{ {
return "获取枚举"+e.GetType().FullName+"名称错误:"+ex.Message; return "获取枚举"+e.GetType().FullName+"名称错误:"+ex.Message;
} }
return ""; return "";
} }
public static string ToHtmlSelectOptions<T>() public static string ToHtmlSelectOptions<T>()
{ {
var dic = ToDictionary<T>(); var dic = ToDictionary<T>();
string str = ""; string str = "";
foreach (var key in dic.Keys) foreach (var key in dic.Keys)
{ {
str += "<option value=\"" + key + "\">" + dic[key] + "</option>"; str += "<option value=\"" + key + "\">" + dic[key] + "</option>";
} }
return str; return str;
} }
#region #region
/// <summary> /// <summary>
/// 判断值是否在枚举中存在 /// 判断值是否在枚举中存在
/// </summary> /// </summary>
/// <param name="enumValue">需要判断的参数</param> /// <param name="enumValue">需要判断的参数</param>
/// <param name="enumType">枚举类型</param> /// <param name="enumType">枚举类型</param>
/// <returns></returns> /// <returns></returns>
public static bool IsExist(this int enumValue, Type enumType) public static bool IsExist(this int enumValue, Type enumType)
{ {
return Enum.IsDefined(enumType, enumValue); return Enum.IsDefined(enumType, enumValue);
} }
#endregion #endregion
} }
} }

View File

@@ -1,25 +1,25 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Globalization; using System.Globalization;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Web; using System.Web;
using TinyPinyin.Core; using TinyPinyin.Core;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
public static class ExceptionExtension public static class ExceptionExtension
{ {
public static string GetInfo(this Exception ex) public static string GetInfo(this Exception ex)
{ {
var info = $"S:{ex.Source},M:{ex.Message},ST:{ex.StackTrace}-----"; var info = $"S:{ex.Source},M:{ex.Message},ST:{ex.StackTrace}-----";
if (ex.InnerException != null) if (ex.InnerException != null)
{ {
info += ex.InnerException.GetInfo(); info += ex.InnerException.GetInfo();
} }
return info; return info;
} }
} }
} }

View File

@@ -1,94 +1,94 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Hncore.Infrastructure.Serializer; using Hncore.Infrastructure.Serializer;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
public static class HttpClientFactoryExtension public static class HttpClientFactoryExtension
{ {
public static HttpClient CreateClient(this IHttpClientFactory factory, TimeSpan timeOut) public static HttpClient CreateClient(this IHttpClientFactory factory, TimeSpan timeOut)
{ {
var client = factory.CreateClient(); var client = factory.CreateClient();
client.Timeout = timeOut; client.Timeout = timeOut;
return client; return client;
} }
} }
public static class HttpClientExtension public static class HttpClientExtension
{ {
/// <summary> /// <summary>
/// post请求ContentTypeapplication/json /// post请求ContentTypeapplication/json
/// </summary> /// </summary>
/// <param name="httpClient"></param> /// <param name="httpClient"></param>
/// <param name="path"></param> /// <param name="path"></param>
/// <param name="data"></param> /// <param name="data"></param>
/// <returns></returns> /// <returns></returns>
public static async Task<HttpResponseMessage> PostAsJson(this HttpClient httpClient, string path, object data, public static async Task<HttpResponseMessage> PostAsJson(this HttpClient httpClient, string path, object data,
Encoding encoding = null) Encoding encoding = null)
{ {
if (encoding == null) if (encoding == null)
{ {
encoding = Encoding.UTF8; encoding = Encoding.UTF8;
} }
string content = ""; string content = "";
if (data is string s) if (data is string s)
{ {
content = s; content = s;
} }
else else
{ {
content = data.ToJson(); content = data.ToJson();
} }
HttpContent httpContent = new StringContent(content, encoding); HttpContent httpContent = new StringContent(content, encoding);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return await httpClient.PostAsync(path, httpContent); return await httpClient.PostAsync(path, httpContent);
} }
/// <summary> /// <summary>
/// post请求ContentTypeapplication/json /// post请求ContentTypeapplication/json
/// </summary> /// </summary>
/// <param name="httpClient"></param> /// <param name="httpClient"></param>
/// <param name="path"></param> /// <param name="path"></param>
/// <param name="data"></param> /// <param name="data"></param>
/// <returns></returns> /// <returns></returns>
public static async Task<string> PostAsJsonGetString(this HttpClient httpClient, string path, object data, public static async Task<string> PostAsJsonGetString(this HttpClient httpClient, string path, object data,
Encoding encoding = null) Encoding encoding = null)
{ {
var res = await httpClient.PostAsJson(path, data, encoding); var res = await httpClient.PostAsJson(path, data, encoding);
return await res.Content.ReadAsStringAsync(); return await res.Content.ReadAsStringAsync();
} }
public static async Task<HttpResponseMessage> PostAsForm(this HttpClient httpClient, string path, IEnumerable<KeyValuePair<string, string>> data, public static async Task<HttpResponseMessage> PostAsForm(this HttpClient httpClient, string path, IEnumerable<KeyValuePair<string, string>> data,
Encoding encoding = null) Encoding encoding = null)
{ {
if (encoding == null) if (encoding == null)
{ {
encoding = Encoding.UTF8; encoding = Encoding.UTF8;
} }
HttpContent httpContent = new FormUrlEncodedContent(data); HttpContent httpContent = new FormUrlEncodedContent(data);
return await httpClient.PostAsync(path, httpContent); return await httpClient.PostAsync(path, httpContent);
} }
public static async Task<string> PostAsFormGetString(this HttpClient httpClient, string path, IEnumerable<KeyValuePair<string, string>> data, public static async Task<string> PostAsFormGetString(this HttpClient httpClient, string path, IEnumerable<KeyValuePair<string, string>> data,
Encoding encoding = null) Encoding encoding = null)
{ {
var resp=await httpClient.PostAsForm(path, data, encoding); var resp=await httpClient.PostAsForm(path, data, encoding);
return await resp.Content.ReadAsStringAsync(); return await resp.Content.ReadAsStringAsync();
} }
} }
} }

View File

@@ -1,126 +1,126 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
public static class ListExtension public static class ListExtension
{ {
public static bool NullOrEmpty<T>(this IList<T> list) public static bool NullOrEmpty<T>(this IList<T> list)
{ {
if (list == null) if (list == null)
{ {
return true; return true;
} }
if (!list.Any()) if (!list.Any())
{ {
return true; return true;
} }
return false; return false;
} }
#region #region
/// <summary> /// <summary>
/// 转换几个中所有元素的类型 /// 转换几个中所有元素的类型
/// </summary> /// </summary>
/// <typeparam name="TO"></typeparam> /// <typeparam name="TO"></typeparam>
/// <param name="list"></param> /// <param name="list"></param>
/// <returns></returns> /// <returns></returns>
public static List<TO> ConvertListType<TO, T>(this List<T> list) public static List<TO> ConvertListType<TO, T>(this List<T> list)
{ {
if (list == null) if (list == null)
{ {
return null; return null;
} }
List<TO> newlist = new List<TO>(); List<TO> newlist = new List<TO>();
foreach (T t in list) foreach (T t in list)
{ {
newlist.Add((TO)Convert.ChangeType(t, typeof(TO))); newlist.Add((TO)Convert.ChangeType(t, typeof(TO)));
} }
return newlist; return newlist;
} }
#endregion #endregion
/// <summary> /// <summary>
/// 添加 /// 添加
/// </summary> /// </summary>
/// <param name="list"></param> /// <param name="list"></param>
/// <param name="item"></param> /// <param name="item"></param>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <returns></returns> /// <returns></returns>
public static List<T> AddNew<T>(this List<T> list, T item) public static List<T> AddNew<T>(this List<T> list, T item)
{ {
list.Add(item); list.Add(item);
return list; return list;
} }
/// <summary> /// <summary>
/// 添加多个集合 /// 添加多个集合
/// </summary> /// </summary>
/// <param name="list"></param> /// <param name="list"></param>
/// <param name="item"></param> /// <param name="item"></param>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <returns></returns> /// <returns></returns>
public static List<T> AddNewMult<T>(this List<T> list, List<T> item) public static List<T> AddNewMult<T>(this List<T> list, List<T> item)
{ {
list.AddRange(item); list.AddRange(item);
return list; return list;
} }
/// <summary> /// <summary>
/// 移除 /// 移除
/// </summary> /// </summary>
/// <param name="list"></param> /// <param name="list"></param>
/// <param name="item"></param> /// <param name="item"></param>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <returns></returns> /// <returns></returns>
public static List<T> RemoveNew<T>(this List<T> list, T item) public static List<T> RemoveNew<T>(this List<T> list, T item)
{ {
list.Remove(item); list.Remove(item);
return list; return list;
} }
#region #region
/// <summary> /// <summary>
/// 移除单条符合条件的数据 /// 移除单条符合条件的数据
/// </summary> /// </summary>
/// <param name="list"></param> /// <param name="list"></param>
/// <param name="condtion">条件</param> /// <param name="condtion">条件</param>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <returns></returns> /// <returns></returns>
public static List<T> RemoveNew<T>(this List<T> list, Func<T, bool> condtion) public static List<T> RemoveNew<T>(this List<T> list, Func<T, bool> condtion)
{ {
List<T> listTemp = list; List<T> listTemp = list;
var item = listTemp.FirstOrDefault(condtion); var item = listTemp.FirstOrDefault(condtion);
if (item != null) if (item != null)
{ {
listTemp.Remove(item); listTemp.Remove(item);
} }
return list; return list;
} }
/// <summary> /// <summary>
/// 移除多条满足条件 /// 移除多条满足条件
/// </summary> /// </summary>
/// <param name="list"></param> /// <param name="list"></param>
/// <param name="condtion">条件</param> /// <param name="condtion">条件</param>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <returns></returns> /// <returns></returns>
public static List<T> RemoveMultNew<T>(this List<T> list, Func<T, bool> condtion) public static List<T> RemoveMultNew<T>(this List<T> list, Func<T, bool> condtion)
{ {
List<T> listTemp = list; List<T> listTemp = list;
var items = listTemp.Where(condtion).ToList() ?? new List<T>(); var items = listTemp.Where(condtion).ToList() ?? new List<T>();
foreach (var item in items) foreach (var item in items)
{ {
listTemp.Remove(item); listTemp.Remove(item);
} }
return list; return list;
} }
#endregion #endregion
} }
} }

View File

@@ -1,19 +1,19 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
public static class ListForEachExtension public static class ListForEachExtension
{ {
public static async Task ForEachAsync<T>(this IEnumerable<T> list, Func<T, Task> func) public static async Task ForEachAsync<T>(this IEnumerable<T> list, Func<T, Task> func)
{ {
foreach (T value in list) foreach (T value in list)
{ {
await func(value); await func(value);
} }
} }
} }
} }

View File

@@ -1,63 +1,63 @@
using System; using System;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
public static class NumberExtension public static class NumberExtension
{ {
public static int ToInt(this int? num) public static int ToInt(this int? num)
{ {
if (num == null) if (num == null)
{ {
return 0; return 0;
} }
return Convert.ToInt32(num); return Convert.ToInt32(num);
} }
public static int ToInt(this JToken obj) public static int ToInt(this JToken obj)
{ {
if (obj == null) if (obj == null)
{ {
return 0; return 0;
} }
int.TryParse(obj.ToString(), out var num); int.TryParse(obj.ToString(), out var num);
return num; return num;
} }
public static decimal ToDecimal(this decimal? num) public static decimal ToDecimal(this decimal? num)
{ {
if (num == null) if (num == null)
{ {
return 0; return 0;
} }
return Convert.ToDecimal(num); return Convert.ToDecimal(num);
} }
public static long ToLong(this long? num) public static long ToLong(this long? num)
{ {
if (num == null) if (num == null)
{ {
return 0; return 0;
} }
return (long) num; return (long) num;
} }
public static int ToInt(this bool flag) public static int ToInt(this bool flag)
{ {
if (flag) if (flag)
{ {
return 1; return 1;
} }
else else
{ {
return 0; return 0;
} }
} }
} }
} }

View File

@@ -1,144 +1,144 @@
using Nelibur.ObjectMapper; using Nelibur.ObjectMapper;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Dynamic; using System.Dynamic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
public static class ObjectExtension public static class ObjectExtension
{ {
/// <summary> /// <summary>
/// 将对象[主要是匿名对象]转换为dynamic /// 将对象[主要是匿名对象]转换为dynamic
/// </summary> /// </summary>
public static dynamic ToDynamic(this object obj, decimal defaultVal) public static dynamic ToDynamic(this object obj, decimal defaultVal)
{ {
decimal result; decimal result;
if (obj != null) if (obj != null)
if (decimal.TryParse(obj.ToString(), out result)) if (decimal.TryParse(obj.ToString(), out result))
return result; return result;
else else
return defaultVal; return defaultVal;
return defaultVal; return defaultVal;
} }
// This extension method is broken out so you can use a similar pattern with // This extension method is broken out so you can use a similar pattern with
// other MetaData elements in the future. This is your base method for each. // other MetaData elements in the future. This is your base method for each.
public static T GetAttribute<T>(this object value) where T : Attribute public static T GetAttribute<T>(this object value) where T : Attribute
{ {
var type = value.GetType(); var type = value.GetType();
var memberInfo = type.GetMember(value.ToString()); var memberInfo = type.GetMember(value.ToString());
if (!memberInfo.Any()) if (!memberInfo.Any())
{ {
return null; return null;
} }
var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false); var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
return (T) attributes[0]; return (T) attributes[0];
} }
// This method creates a specific call to the above method, requesting the // This method creates a specific call to the above method, requesting the
// Description MetaData attribute. // Description MetaData attribute.
public static string GetDescription(this object value) public static string GetDescription(this object value)
{ {
var desAttribute = value.GetAttribute<DescriptionAttribute>(); var desAttribute = value.GetAttribute<DescriptionAttribute>();
if (desAttribute != null) if (desAttribute != null)
{ {
return desAttribute.Description; return desAttribute.Description;
} }
var displayAttribute = value.GetAttribute<DisplayAttribute>(); var displayAttribute = value.GetAttribute<DisplayAttribute>();
if (displayAttribute != null) if (displayAttribute != null)
{ {
return displayAttribute.Name ?? displayAttribute.Description; return displayAttribute.Name ?? displayAttribute.Description;
} }
return ""; return "";
} }
#region key对应枚举的值value对应枚举的注释 #region key对应枚举的值value对应枚举的注释
/// <summary> /// <summary>
/// 得到枚举字典key对应枚举的值value对应枚举的注释 /// 得到枚举字典key对应枚举的值value对应枚举的注释
/// </summary> /// </summary>
/// <typeparam name="TEnum"></typeparam> /// <typeparam name="TEnum"></typeparam>
/// <returns></returns> /// <returns></returns>
public static Dictionary<Enum, string> ToDescriptionDictionary<TEnum>() public static Dictionary<Enum, string> ToDescriptionDictionary<TEnum>()
{ {
Array values = Enum.GetValues(typeof(TEnum)); Array values = Enum.GetValues(typeof(TEnum));
Dictionary<Enum, string> nums = new Dictionary<Enum, string>(); Dictionary<Enum, string> nums = new Dictionary<Enum, string>();
foreach (Enum value in values) foreach (Enum value in values)
{ {
nums.Add(value, GetDescription(value)); nums.Add(value, GetDescription(value));
} }
return nums; return nums;
} }
#endregion #endregion
#region string属性执行Trim() #region string属性执行Trim()
/// <summary> /// <summary>
/// 对象string属性执行Trim() /// 对象string属性执行Trim()
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="t"></param> /// <param name="t"></param>
/// <returns></returns> /// <returns></returns>
public static T ObjectStrTrim<T>(this T t) where T:new () public static T ObjectStrTrim<T>(this T t) where T:new ()
{ {
if (t != null) if (t != null)
{ {
foreach (var pi in t.GetType().GetProperties()) foreach (var pi in t.GetType().GetProperties())
{ {
if (pi.PropertyType.Equals(typeof(string)) && pi.GetValue(t, null) != null)//判断属性的类型是不是String if (pi.PropertyType.Equals(typeof(string)) && pi.GetValue(t, null) != null)//判断属性的类型是不是String
{ {
pi.SetValue(t, pi.GetValue(t, null).ToString().Trim(), null);//给泛型的属性赋值 pi.SetValue(t, pi.GetValue(t, null).ToString().Trim(), null);//给泛型的属性赋值
} }
} }
} }
return t; return t;
} }
#endregion #endregion
#region #region
public static T save<T>(this T obj,string key) where T:class,new() public static T save<T>(this T obj,string key) where T:class,new()
{ {
Dictionary<string, object> dic = c.Value ?? new Dictionary<string, object>(); Dictionary<string, object> dic = c.Value ?? new Dictionary<string, object>();
dic.Add(key,obj); dic.Add(key,obj);
c.Value = dic; c.Value = dic;
return obj; return obj;
} }
public static AsyncLocal<Dictionary<string,Object>> c=new AsyncLocal<Dictionary<string, Object>>(); public static AsyncLocal<Dictionary<string,Object>> c=new AsyncLocal<Dictionary<string, Object>>();
#endregion #endregion
#region #region
public static T MapTo<T>(this Object model) public static T MapTo<T>(this Object model)
{ {
var productDto = TinyMapper.Map<T>(model); var productDto = TinyMapper.Map<T>(model);
return productDto; return productDto;
} }
public static IEnumerable<T> MapsTo<T>(this Object model) public static IEnumerable<T> MapsTo<T>(this Object model)
{ {
var generic = model.GetType().GetGenericTypeDefinition(); var generic = model.GetType().GetGenericTypeDefinition();
if (generic == typeof(List<>)) if (generic == typeof(List<>))
{ {
return TinyMapper.Map<List<T>>(model); return TinyMapper.Map<List<T>>(model);
} }
if (generic == typeof(Collection<>)) if (generic == typeof(Collection<>))
{ {
return TinyMapper.Map<Collection<T>>(model); return TinyMapper.Map<Collection<T>>(model);
} }
throw new Exception("不合法的转换"); throw new Exception("不合法的转换");
} }
#endregion #endregion
} }
} }

View File

@@ -1,46 +1,46 @@
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using System; using System;
using System.Linq; using System.Linq;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
public static class RequestExtension public static class RequestExtension
{ {
public static string Get(this HttpRequest request, string key) public static string Get(this HttpRequest request, string key)
{ {
if (request.Query.ContainsKey(key)) if (request.Query.ContainsKey(key))
{ {
return request.Query[key]; return request.Query[key];
} }
return ""; return "";
} }
public static int GetInt(this HttpRequest request, string key) public static int GetInt(this HttpRequest request, string key)
{ {
if (request.Query.ContainsKey(key)) if (request.Query.ContainsKey(key))
{ {
return Convert.ToInt32(request.Query[key]); return Convert.ToInt32(request.Query[key]);
} }
return 0; return 0;
} }
public static string GetUrl(this HttpRequest request, bool full=true) public static string GetUrl(this HttpRequest request, bool full=true)
{ {
if (full) if (full)
{ {
return $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}"; return $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}";
} }
return $"{request.Path}{request.QueryString}"; return $"{request.Path}{request.QueryString}";
} }
public static string Remove(this HttpRequest request, string key) public static string Remove(this HttpRequest request, string key)
{ {
var q = request.Query.Where(m => !m.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)); var q = request.Query.Where(m => !m.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase));
var kvs = q.Select(m => $"{m.Key}={m.Value}"); var kvs = q.Select(m => $"{m.Key}={m.Value}");
return string.Join("&", kvs); return string.Join("&", kvs);
} }
} }
} }

View File

@@ -1,21 +1,21 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Web; using System.Web;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
public static class StreamExtension public static class StreamExtension
{ {
public async static Task<string> ReadAsStringAsync(this Stream stream) public async static Task<string> ReadAsStringAsync(this Stream stream)
{ {
var reader = new StreamReader(stream); var reader = new StreamReader(stream);
return await reader.ReadToEndAsync(); return await reader.ReadToEndAsync();
} }
} }
} }

View File

@@ -1,17 +1,17 @@
using Nelibur.ObjectMapper; using Nelibur.ObjectMapper;
using System.Collections.Generic; using System.Collections.Generic;
namespace Hncore.Infrastructure.Extension namespace Hncore.Infrastructure.Extension
{ {
public static class TinyMapperExtension public static class TinyMapperExtension
{ {
public static void Binds<T1, T2>() public static void Binds<T1, T2>()
{ {
TinyMapper.Bind<T1, T2>(); TinyMapper.Bind<T1, T2>();
TinyMapper.Bind<T2, T1>(); TinyMapper.Bind<T2, T1>();
TinyMapper.Bind<List<T1>, List<T2>>(); TinyMapper.Bind<List<T1>, List<T2>>();
TinyMapper.Bind<List<T2>, List<T1>>(); TinyMapper.Bind<List<T2>, List<T1>>();
} }
} }
} }

View File

@@ -1,46 +1,46 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<!--<TargetFramework>netcoreapp2.2</TargetFramework>--> <!--<TargetFramework>netcoreapp2.2</TargetFramework>-->
<TargetFramework>netstandard2.0</TargetFramework> <TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="aliyun-net-sdk-core" Version="1.5.3" /> <PackageReference Include="aliyun-net-sdk-core" Version="1.5.3" />
<PackageReference Include="AngleSharp" Version="0.12.1" /> <PackageReference Include="AngleSharp" Version="0.12.1" />
<PackageReference Include="Autofac" Version="4.9.1" /> <PackageReference Include="Autofac" Version="4.9.1" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.4.0" /> <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.4.0" />
<PackageReference Include="Bogus" Version="26.0.1" /> <PackageReference Include="Bogus" Version="26.0.1" />
<PackageReference Include="CSRedisCore" Version="3.0.60" /> <PackageReference Include="CSRedisCore" Version="3.0.60" />
<PackageReference Include="Dapper" Version="1.60.6" /> <PackageReference Include="Dapper" Version="1.60.6" />
<PackageReference Include="DotNetCore.NPOI" Version="1.2.1" /> <PackageReference Include="DotNetCore.NPOI" Version="1.2.1" />
<PackageReference Include="JWT" Version="5.0.1" /> <PackageReference Include="JWT" Version="5.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="3.1.2" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="3.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="3.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="3.2.0" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="2.2.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.2.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="2.2.0" /> <PackageReference Include="Microsoft.Extensions.Http" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.2.0" /> <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.2.0" />
<PackageReference Include="MQiniu.Core" Version="1.0.1" /> <PackageReference Include="MQiniu.Core" Version="1.0.1" />
<PackageReference Include="MySqlConnector" Version="0.56.0" /> <PackageReference Include="MySqlConnector" Version="0.56.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="1.4.0" /> <PackageReference Include="NLog.Extensions.Logging" Version="1.4.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" />
<PackageReference Include="System.Drawing.Common" Version="4.5.1" /> <PackageReference Include="System.Drawing.Common" Version="4.5.1" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.5.1" /> <PackageReference Include="System.Text.Encoding.CodePages" Version="4.5.1" />
<PackageReference Include="TinyMapper" Version="3.0.2-beta" /> <PackageReference Include="TinyMapper" Version="3.0.2-beta" />
<PackageReference Include="TinyPinyin.Core.Standard" Version="1.0.0" /> <PackageReference Include="TinyPinyin.Core.Standard" Version="1.0.0" />
<PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="MQTTnet" Version="2.8.5" /> <PackageReference Include="MQTTnet" Version="2.8.5" />
<PackageReference Include="Polly" Version="7.1.0" /> <PackageReference Include="Polly" Version="7.1.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Update="nlog.config"> <None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -1,7 +1,7 @@
namespace Hncore.Infrastructure.IOC namespace Hncore.Infrastructure.IOC
{ {
public interface IDependency public interface IDependency
{ {
} }
} }

View File

@@ -1,7 +1,7 @@
namespace Hncore.Infrastructure.IOC namespace Hncore.Infrastructure.IOC
{ {
public interface IPerRequest public interface IPerRequest
{ {
} }
} }

View File

@@ -1,7 +1,7 @@
namespace Hncore.Infrastructure.IOC namespace Hncore.Infrastructure.IOC
{ {
public interface ISingleInstance public interface ISingleInstance
{ {
} }
} }

View File

@@ -1,151 +1,151 @@
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Hncore.Infrastructure.Common; using Hncore.Infrastructure.Common;
using MQTTnet; using MQTTnet;
using MQTTnet.Client; using MQTTnet.Client;
using Polly; using Polly;
namespace Hncore.Infrastructure.Mqtt namespace Hncore.Infrastructure.Mqtt
{ {
public class MQTTClient : IDisposable public class MQTTClient : IDisposable
{ {
//实例 ID购买后从控制台获取 //实例 ID购买后从控制台获取
string _instanceId = "post-cn-v0h12xbue09"; string _instanceId = "post-cn-v0h12xbue09";
//此处填写购买得到的 MQTT 接入点域名 //此处填写购买得到的 MQTT 接入点域名
string _brokerUrl = "post-cn-v0h12xbue09.mqtt.aliyuncs.com"; string _brokerUrl = "post-cn-v0h12xbue09.mqtt.aliyuncs.com";
//此处填写阿里云帐号 AccessKey //此处填写阿里云帐号 AccessKey
string _accessKey = "LTAIaJpHI68JfX2c"; string _accessKey = "LTAIaJpHI68JfX2c";
//此处填写阿里云帐号 SecretKey //此处填写阿里云帐号 SecretKey
string _secretKey = "f17za6FRggVzwlSqzFHl8GndQ59SGV"; string _secretKey = "f17za6FRggVzwlSqzFHl8GndQ59SGV";
//此处填写客户端 ClientId需要保证全局唯一其中前缀部分即 GroupId 需要先在 MQ 控制台创建 //此处填写客户端 ClientId需要保证全局唯一其中前缀部分即 GroupId 需要先在 MQ 控制台创建
string _clientId = "GID_DOOR@@@MA_" + Guid.NewGuid(); string _clientId = "GID_DOOR@@@MA_" + Guid.NewGuid();
private IMqttClient _mqttClient; private IMqttClient _mqttClient;
private SemaphoreSlim _lock = new SemaphoreSlim(1, 1); private SemaphoreSlim _lock = new SemaphoreSlim(1, 1);
private ConcurrentDictionary<string, Action<string>> cmdMap = new ConcurrentDictionary<string, Action<string>>(); private ConcurrentDictionary<string, Action<string>> cmdMap = new ConcurrentDictionary<string, Action<string>>();
public MQTTClient() public MQTTClient()
{ {
_mqttClient = new MqttFactory().CreateMqttClient(); _mqttClient = new MqttFactory().CreateMqttClient();
_mqttClient.Disconnected += async (s, e) => _mqttClient.Disconnected += async (s, e) =>
{ {
await Task.Delay(TimeSpan.FromSeconds(2)); await Task.Delay(TimeSpan.FromSeconds(2));
await Conn(); await Conn();
}; };
_mqttClient.ApplicationMessageReceived += (s, e) => _mqttClient.ApplicationMessageReceived += (s, e) =>
{ {
var topic = e.ApplicationMessage.Topic.TrimEnd('/'); var topic = e.ApplicationMessage.Topic.TrimEnd('/');
var data = Encoding.UTF8.GetString(e.ApplicationMessage.Payload??new byte[0]); var data = Encoding.UTF8.GetString(e.ApplicationMessage.Payload??new byte[0]);
Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###"); Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
Console.WriteLine($"+ Topic = {topic}"); Console.WriteLine($"+ Topic = {topic}");
Console.WriteLine($"+ Payload = {data}"); Console.WriteLine($"+ Payload = {data}");
Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}"); Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
Console.WriteLine(); Console.WriteLine();
if (cmdMap.ContainsKey(topic)) if (cmdMap.ContainsKey(topic))
{ {
try try
{ {
cmdMap[topic](data); cmdMap[topic](data);
} }
catch (Exception ex) catch (Exception ex)
{ {
LogHelper.Error($"Mqtt:{topic}", ex.Message); LogHelper.Error($"Mqtt:{topic}", ex.Message);
} }
} }
}; };
} }
private async Task Conn() private async Task Conn()
{ {
if (!_mqttClient.IsConnected) if (!_mqttClient.IsConnected)
{ {
await _lock.WaitAsync(); await _lock.WaitAsync();
try try
{ {
int i = 0; int i = 0;
await Policy.Handle<Exception>() await Policy.Handle<Exception>()
.OrResult<MqttClientConnectResult>(res => !res.IsSessionPresent) .OrResult<MqttClientConnectResult>(res => !res.IsSessionPresent)
.RetryAsync(10) .RetryAsync(10)
.ExecuteAsync(async () => .ExecuteAsync(async () =>
{ {
if (!_mqttClient.IsConnected) if (!_mqttClient.IsConnected)
{ {
i++; i++;
try try
{ {
string userName = "Signature|" + _accessKey + "|" + _instanceId; string userName = "Signature|" + _accessKey + "|" + _instanceId;
string passWord = HMACSHA1(_secretKey, _clientId); string passWord = HMACSHA1(_secretKey, _clientId);
var options = new MqttClientOptionsBuilder() var options = new MqttClientOptionsBuilder()
.WithClientId(_clientId) .WithClientId(_clientId)
.WithTcpServer(_brokerUrl) .WithTcpServer(_brokerUrl)
.WithCredentials(userName, passWord) .WithCredentials(userName, passWord)
.WithCleanSession() .WithCleanSession()
.Build(); .Build();
return await _mqttClient.ConnectAsync(options); return await _mqttClient.ConnectAsync(options);
} }
catch (Exception e) catch (Exception e)
{ {
LogHelper.Error($"mqtt连接失败第{i}次连接", e); LogHelper.Error($"mqtt连接失败第{i}次连接", e);
throw; throw;
} }
} }
return new MqttClientConnectResult(true); return new MqttClientConnectResult(true);
}); });
} }
finally finally
{ {
_lock.Release(); _lock.Release();
} }
} }
} }
public async Task PublishAsync(string topic, string payload) public async Task PublishAsync(string topic, string payload)
{ {
await Conn(); await Conn();
await _mqttClient.PublishAsync(topic, payload); await _mqttClient.PublishAsync(topic, payload);
} }
public async Task SubscribeAsync(string topic, Action<string> action) public async Task SubscribeAsync(string topic, Action<string> action)
{ {
await Conn(); await Conn();
var option = new TopicFilterBuilder().WithTopic(topic).Build(); var option = new TopicFilterBuilder().WithTopic(topic).Build();
await _mqttClient.SubscribeAsync(option); await _mqttClient.SubscribeAsync(option);
cmdMap[topic] = action; cmdMap[topic] = action;
} }
public static string HMACSHA1(string key, string dataToSign) public static string HMACSHA1(string key, string dataToSign)
{ {
Byte[] secretBytes = UTF8Encoding.UTF8.GetBytes(key); Byte[] secretBytes = UTF8Encoding.UTF8.GetBytes(key);
HMACSHA1 hmac = new HMACSHA1(secretBytes); HMACSHA1 hmac = new HMACSHA1(secretBytes);
Byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(dataToSign); Byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(dataToSign);
Byte[] calcHash = hmac.ComputeHash(dataBytes); Byte[] calcHash = hmac.ComputeHash(dataBytes);
String calcHashString = Convert.ToBase64String(calcHash); String calcHashString = Convert.ToBase64String(calcHash);
return calcHashString; return calcHashString;
} }
public async void Dispose() public async void Dispose()
{ {
await _mqttClient.DisconnectAsync(); await _mqttClient.DisconnectAsync();
_mqttClient?.Dispose(); _mqttClient?.Dispose();
} }
} }
} }

View File

@@ -1,26 +1,26 @@
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Hncore.Infrastructure.OpenApi namespace Hncore.Infrastructure.OpenApi
{ {
/// <summary> /// <summary>
/// 接入的应用 /// 接入的应用
/// </summary> /// </summary>
public class Application public class Application
{ {
/// <summary> /// <summary>
/// 应用唯一标识 /// 应用唯一标识
/// </summary> /// </summary>
public string AppId { get; set; } = ""; public string AppId { get; set; } = "";
/// <summary> /// <summary>
/// 应用密钥 /// 应用密钥
/// </summary> /// </summary>
public string AppKey { get; set; } = ""; public string AppKey { get; set; } = "";
/// <summary> /// <summary>
/// 是否启用 /// 是否启用
/// </summary> /// </summary>
public bool Enable { get; set; } = true; public bool Enable { get; set; } = true;
} }
} }

View File

@@ -1,71 +1,71 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Hncore.Infrastructure.Common; using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Extension; using Hncore.Infrastructure.Extension;
using Hncore.Infrastructure.Serializer; using Hncore.Infrastructure.Serializer;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Filters;
using Hncore.Infrastructure.Core.Web; using Hncore.Infrastructure.Core.Web;
namespace Hncore.Infrastructure.OpenApi namespace Hncore.Infrastructure.OpenApi
{ {
public class OpenApiAuthAttribute : TypeFilterAttribute public class OpenApiAuthAttribute : TypeFilterAttribute
{ {
public OpenApiAuthAttribute() : base(typeof(OpenApiAuthFilter)) public OpenApiAuthAttribute() : base(typeof(OpenApiAuthFilter))
{ {
Order = -9997; Order = -9997;
} }
} }
public class OpenApiAuthFilter : IAsyncAuthorizationFilter public class OpenApiAuthFilter : IAsyncAuthorizationFilter
{ {
public async Task OnAuthorizationAsync(AuthorizationFilterContext context) public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{ {
if (context.Filters.Any(item => item is IAllowAnonymousFilter)) if (context.Filters.Any(item => item is IAllowAnonymousFilter))
{ {
context.HttpContext.Items["AllowAnonymous"] = true; context.HttpContext.Items["AllowAnonymous"] = true;
return; return;
} }
context.HttpContext.Items["OpenApi"] = true; context.HttpContext.Items["OpenApi"] = true;
var body = await context.HttpContext.Request.ReadBodyAsStringAsync(); var body = await context.HttpContext.Request.ReadBodyAsStringAsync();
var requestBase = body.FromJsonTo<OpenApiRequestBase>(); var requestBase = body.FromJsonTo<OpenApiRequestBase>();
if (requestBase.Timestamp==null) if (requestBase.Timestamp==null)
{ {
OpenApiException.Throw(OpenApiReturnCode.Error,"缺少timestamp参数"); OpenApiException.Throw(OpenApiReturnCode.Error,"缺少timestamp参数");
} }
if (!requestBase.Sign.Has()) if (!requestBase.Sign.Has())
{ {
OpenApiException.Throw(OpenApiReturnCode.Error,"缺少sign参数"); OpenApiException.Throw(OpenApiReturnCode.Error,"缺少sign参数");
} }
if (!requestBase.AppId.Has()) if (!requestBase.AppId.Has())
{ {
OpenApiException.Throw(OpenApiReturnCode.Error,"缺少appid参数"); OpenApiException.Throw(OpenApiReturnCode.Error,"缺少appid参数");
} }
var application = await RedisHelper.HGetAsync<Application>("OpenApi:Application", requestBase.AppId); var application = await RedisHelper.HGetAsync<Application>("OpenApi:Application", requestBase.AppId);
context.HttpContext.Items["OpenApiAppKey"] = application.AppKey; context.HttpContext.Items["OpenApiAppKey"] = application.AppKey;
if (!application.Enable) if (!application.Enable)
{ {
OpenApiException.Throw(OpenApiReturnCode.Unauthorized); OpenApiException.Throw(OpenApiReturnCode.Unauthorized);
} }
if (DateTimeHelper.ToUnixTimestamp(DateTime.Now) - requestBase.Timestamp > 60) if (DateTimeHelper.ToUnixTimestamp(DateTime.Now) - requestBase.Timestamp > 60)
{ {
OpenApiException.Throw(OpenApiReturnCode.TimeStampExpired); OpenApiException.Throw(OpenApiReturnCode.TimeStampExpired);
} }
requestBase.CheckSign(application.AppKey); requestBase.CheckSign(application.AppKey);
} }
} }
} }

View File

@@ -1,28 +1,28 @@
using System; using System;
namespace Hncore.Infrastructure.OpenApi namespace Hncore.Infrastructure.OpenApi
{ {
public class OpenApiException: Exception public class OpenApiException: Exception
{ {
public OpenApiReturnCode Code { get; } = OpenApiReturnCode.InternalError; public OpenApiReturnCode Code { get; } = OpenApiReturnCode.InternalError;
public OpenApiException(string message) : base(message) public OpenApiException(string message) : base(message)
{ {
} }
public OpenApiException(OpenApiReturnCode code, string message = "") : base(message) public OpenApiException(OpenApiReturnCode code, string message = "") : base(message)
{ {
Code = code; Code = code;
} }
public static void Throw(string message = "") public static void Throw(string message = "")
{ {
throw new OpenApiException(message); throw new OpenApiException(message);
} }
public static void Throw(OpenApiReturnCode code, string message = "") public static void Throw(OpenApiReturnCode code, string message = "")
{ {
throw new OpenApiException(code, message); throw new OpenApiException(code, message);
} }
} }
} }

View File

@@ -1,30 +1,30 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Hncore.Infrastructure.Extension; using Hncore.Infrastructure.Extension;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
namespace Hncore.Infrastructure.OpenApi namespace Hncore.Infrastructure.OpenApi
{ {
public class OpenApiRequestBase public class OpenApiRequestBase
{ {
[JsonProperty("appid")] [JsonProperty("appid")]
public string AppId { get; set; } public string AppId { get; set; }
[JsonProperty("timestamp")] [JsonProperty("timestamp")]
public long? Timestamp { get; set; } public long? Timestamp { get; set; }
[JsonProperty("sign")] [JsonProperty("sign")]
public string Sign { get; set; } public string Sign { get; set; }
public void CheckSign(string key) public void CheckSign(string key)
{ {
var sign = OpenApiSignUtil.CreateSign(this.Timestamp.ToLong(), key); var sign = OpenApiSignUtil.CreateSign(this.Timestamp.ToLong(), key);
if (!String.Equals(sign, Sign, StringComparison.CurrentCultureIgnoreCase)) if (!String.Equals(sign, Sign, StringComparison.CurrentCultureIgnoreCase))
{ {
OpenApiException.Throw(OpenApiReturnCode.SignError); OpenApiException.Throw(OpenApiReturnCode.SignError);
} }
} }
} }
} }

View File

@@ -1,111 +1,111 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using Hncore.Infrastructure.Common; using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Extension; using Hncore.Infrastructure.Extension;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Hncore.Infrastructure.OpenApi namespace Hncore.Infrastructure.OpenApi
{ {
public class OpenApiResult<T> where T : class, new() public class OpenApiResult<T> where T : class, new()
{ {
[JsonProperty("code")] public OpenApiReturnCode Code { get; private set; } [JsonProperty("code")] public OpenApiReturnCode Code { get; private set; }
[JsonProperty("message")] public string Message { get; private set; } = ""; [JsonProperty("message")] public string Message { get; private set; } = "";
[JsonProperty("timestamp")] public long Timestamp { get; set; } [JsonProperty("timestamp")] public long Timestamp { get; set; }
[JsonProperty("sign")] public string Sign { get; set; } [JsonProperty("sign")] public string Sign { get; set; }
[JsonProperty("data")] public T Data { get; set; } = new T(); [JsonProperty("data")] public T Data { get; set; } = new T();
private static readonly Dictionary<Enum, string> Dic; private static readonly Dictionary<Enum, string> Dic;
static OpenApiResult() static OpenApiResult()
{ {
Dic = ObjectExtension.ToDescriptionDictionary<OpenApiReturnCode>(); Dic = ObjectExtension.ToDescriptionDictionary<OpenApiReturnCode>();
} }
public OpenApiResult(OpenApiReturnCode code = OpenApiReturnCode.Success, string message = "") public OpenApiResult(OpenApiReturnCode code = OpenApiReturnCode.Success, string message = "")
{ {
Code = code; Code = code;
if (string.IsNullOrEmpty(message) && Dic.ContainsKey(Code)) if (string.IsNullOrEmpty(message) && Dic.ContainsKey(Code))
{ {
Message = Dic[Code]; Message = Dic[Code];
} }
else else
{ {
Message = message; Message = message;
} }
this.Timestamp = DateTimeHelper.ToUnixTimestamp(DateTime.Now); this.Timestamp = DateTimeHelper.ToUnixTimestamp(DateTime.Now);
} }
public void CreateSign(string key) public void CreateSign(string key)
{ {
this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key); this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key);
} }
public OpenApiResult<T> CreateSign(HttpContext httpContext) public OpenApiResult<T> CreateSign(HttpContext httpContext)
{ {
var key = httpContext.Items["OpenApiAppKey"].ToString(); var key = httpContext.Items["OpenApiAppKey"].ToString();
this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key); this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key);
return this; return this;
} }
} }
public class OpenApiResult : OpenApiResult<object> public class OpenApiResult : OpenApiResult<object>
{ {
public OpenApiResult(OpenApiReturnCode code = OpenApiReturnCode.Success, string message = "") : base(code, public OpenApiResult(OpenApiReturnCode code = OpenApiReturnCode.Success, string message = "") : base(code,
message) message)
{ {
} }
public new OpenApiResult CreateSign(HttpContext httpContext) public new OpenApiResult CreateSign(HttpContext httpContext)
{ {
var key = httpContext.Items["OpenApiAppKey"].ToString(); var key = httpContext.Items["OpenApiAppKey"].ToString();
this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key); this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key);
return this; return this;
} }
} }
public enum OpenApiReturnCode public enum OpenApiReturnCode
{ {
/// <summary> /// <summary>
/// 成功 /// 成功
/// </summary> /// </summary>
[Description("成功")] Success = 10000, [Description("成功")] Success = 10000,
/// <summary> /// <summary>
/// 验签失败 /// 验签失败
/// </summary> /// </summary>
[Description("未授权")] Unauthorized = 40001, [Description("未授权")] Unauthorized = 40001,
/// <summary> /// <summary>
/// 验签失败 /// 验签失败
/// </summary> /// </summary>
[Description("验签失败")] SignError = 40002, [Description("验签失败")] SignError = 40002,
/// <summary> /// <summary>
/// 时间戳过期 /// 时间戳过期
/// </summary> /// </summary>
[Description("时间戳过期")] TimeStampExpired = 40003, [Description("时间戳过期")] TimeStampExpired = 40003,
/// <summary> /// <summary>
/// 内部错误 /// 内部错误
/// </summary> /// </summary>
[Description("内部错误")] InternalError = 50000, [Description("内部错误")] InternalError = 50000,
/// <summary> /// <summary>
/// 处理失败 /// 处理失败
/// </summary> /// </summary>
[Description("处理失败")] Error = 500001 [Description("处理失败")] Error = 500001
} }
} }

View File

@@ -1,15 +1,15 @@
using System.Collections.Generic; using System.Collections.Generic;
using Hncore.Infrastructure.Common; using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Data; using Hncore.Infrastructure.Data;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
namespace Hncore.Infrastructure.OpenApi namespace Hncore.Infrastructure.OpenApi
{ {
public static class OpenApiSignUtil public static class OpenApiSignUtil
{ {
public static string CreateSign(long timestamp, string key) public static string CreateSign(long timestamp, string key)
{ {
return SecurityHelper.GetMd5Hash(timestamp.ToString() + key); return SecurityHelper.GetMd5Hash(timestamp.ToString() + key);
} }
} }
} }

View File

@@ -1,156 +1,156 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Dapper; using Dapper;
using Hncore.Infrastructure.Common; using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Serializer; using Hncore.Infrastructure.Serializer;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Hncore.Infrastructure.OperationLog namespace Hncore.Infrastructure.OperationLog
{ {
public class OperationLog public class OperationLog
{ {
/// <summary> /// <summary>
/// 物业id /// 物业id
/// </summary> /// </summary>
[JsonProperty("owner_id")] [JsonProperty("owner_id")]
public int OwnerId { get; set; } public int OwnerId { get; set; }
/// <summary> /// <summary>
/// 创建时间 /// 创建时间
/// </summary> /// </summary>
[JsonProperty("createtime")] [JsonProperty("createtime")]
public DateTime CreateTime { get; set; } = DateTime.Now; public DateTime CreateTime { get; set; } = DateTime.Now;
/// <summary> /// <summary>
/// 更新时间 /// 更新时间
/// </summary> /// </summary>
[JsonProperty("updatetime")] [JsonProperty("updatetime")]
public DateTime UpdateTime { get; set; } = DateTime.Now; public DateTime UpdateTime { get; set; } = DateTime.Now;
/// <summary> /// <summary>
/// 删除标记 /// 删除标记
/// </summary> /// </summary>
[JsonProperty("deletetag")] [JsonProperty("deletetag")]
public int DeleteTag { get; set; } = 0; public int DeleteTag { get; set; } = 0;
/// <summary> /// <summary>
/// 创建人id /// 创建人id
/// </summary> /// </summary>
[JsonProperty("creatorid")] [JsonProperty("creatorid")]
public int CreatorId { get; set; } public int CreatorId { get; set; }
/// <summary> /// <summary>
/// 更新人id /// 更新人id
/// </summary> /// </summary>
[JsonProperty("updatorid")] [JsonProperty("updatorid")]
public int UpdatorId { get; set; } public int UpdatorId { get; set; }
/// <summary> /// <summary>
/// 操作目标id /// 操作目标id
/// </summary> /// </summary>
[JsonProperty("targetid")] [JsonProperty("targetid")]
public int TargetId { get; set; } public int TargetId { get; set; }
/// <summary> /// <summary>
/// 操作人名 /// 操作人名
/// </summary> /// </summary>
[JsonProperty("operator")] [JsonProperty("operator")]
public string Operator { get; set; } public string Operator { get; set; }
/// <summary> /// <summary>
/// 操作说明 /// 操作说明
/// </summary> /// </summary>
[JsonProperty("opdesc")] [JsonProperty("opdesc")]
public string OpDesc { get; set; } public string OpDesc { get; set; }
/// <summary> /// <summary>
/// 操作前 /// 操作前
/// </summary> /// </summary>
[JsonProperty("beforeop")] [JsonProperty("beforeop")]
public string BeforeOp { get; set; } public string BeforeOp { get; set; }
/// <summary> /// <summary>
/// 操作后 /// 操作后
/// </summary> /// </summary>
[JsonProperty("afterop")] [JsonProperty("afterop")]
public string AfterOp { get; set; } public string AfterOp { get; set; }
/// <summary> /// <summary>
/// 操作对象所在小区编码 /// 操作对象所在小区编码
/// </summary> /// </summary>
[JsonProperty("projectcode")] [JsonProperty("projectcode")]
public int ProjectCode { get; set; } public int ProjectCode { get; set; }
/// <summary> /// <summary>
/// 小区名称 /// 小区名称
/// </summary> /// </summary>
[JsonProperty("estatename")] [JsonProperty("estatename")]
public string EstateName { get; set; } public string EstateName { get; set; }
/// <summary> /// <summary>
/// 操作权限编码 /// 操作权限编码
/// </summary> /// </summary>
[JsonProperty("permissioncode")] [JsonProperty("permissioncode")]
public string PermissionCode { get; set; } public string PermissionCode { get; set; }
/// <summary> /// <summary>
/// 操作权限标签 /// 操作权限标签
/// </summary> /// </summary>
[JsonProperty("permissionlabel")] [JsonProperty("permissionlabel")]
public string PermissionLabel { get; set; } public string PermissionLabel { get; set; }
/// <summary> /// <summary>
/// 操作菜单编码 /// 操作菜单编码
/// </summary> /// </summary>
[JsonProperty("optype")] [JsonProperty("optype")]
public int OpType { get; set; } public int OpType { get; set; }
/// <summary> /// <summary>
/// 操作菜单名称 /// 操作菜单名称
/// </summary> /// </summary>
[JsonProperty("optypename")] [JsonProperty("optypename")]
public string OpTypeName { get; set; } public string OpTypeName { get; set; }
public void Write() public void Write()
{ {
try try
{ {
OperationLogStorage.WriteLog(this); OperationLogStorage.WriteLog(this);
} }
catch (Exception e) catch (Exception e)
{ {
LogHelper.Error("写操作日志失败", e); LogHelper.Error("写操作日志失败", e);
} }
} }
public void WriteAsync() public void WriteAsync()
{ {
Task.Run(()=> Write()); Task.Run(()=> Write());
} }
} }
internal class OperationLogStorage internal class OperationLogStorage
{ {
private static string _devConn = private static string _devConn =
"Server=rm-bp12e1533udh1827azo.mysql.rds.aliyuncs.com;Database=etor_property_test;User=etor_test;Password=etor_test!QAZ2wsx;Convert Zero Datetime=True;"; "Server=rm-bp12e1533udh1827azo.mysql.rds.aliyuncs.com;Database=etor_property_test;User=etor_test;Password=etor_test!QAZ2wsx;Convert Zero Datetime=True;";
private static string _proConn = private static string _proConn =
"Server=rm-bp1z48e1qz15k7q9qo.mysql.rds.aliyuncs.com;Database=etor_property_pro;User=sadmin;Password=!QAZ2wsx;Convert Zero Datetime=True;"; "Server=rm-bp1z48e1qz15k7q9qo.mysql.rds.aliyuncs.com;Database=etor_property_pro;User=sadmin;Password=!QAZ2wsx;Convert Zero Datetime=True;";
private static string _insertSql = @"INSERT INTO etor_property_operationlog private static string _insertSql = @"INSERT INTO etor_property_operationlog
( (
owner_id, createtime, updatetime, deletetag, creatorid, updatorid, targetid, operator, opdesc, beforeop, afterop, projectcode, estatename, permissioncode, permissionlabel, optype, optypename owner_id, createtime, updatetime, deletetag, creatorid, updatorid, targetid, operator, opdesc, beforeop, afterop, projectcode, estatename, permissioncode, permissionlabel, optype, optypename
) )
VALUES (@OwnerId,@CreateTime,@UpdateTime,@DeleteTag,@CreatorId,@UpdatorId,@TargetId,@Operator,@OpDesc,@BeforeOp,@AfterOp,@ProjectCode,@EstateName,@PermissionCode,@PermissionLabel,@OpType,@OpTypeName);"; VALUES (@OwnerId,@CreateTime,@UpdateTime,@DeleteTag,@CreatorId,@UpdatorId,@TargetId,@Operator,@OpDesc,@BeforeOp,@AfterOp,@ProjectCode,@EstateName,@PermissionCode,@PermissionLabel,@OpType,@OpTypeName);";
public static void WriteLog(OperationLog log) public static void WriteLog(OperationLog log)
{ {
string connString = EnvironmentVariableHelper.IsAspNetCoreProduction ? _proConn : _devConn; string connString = EnvironmentVariableHelper.IsAspNetCoreProduction ? _proConn : _devConn;
using (var conn = new MySqlConnection(connString)) using (var conn = new MySqlConnection(connString))
{ {
conn.Execute(_insertSql, log); conn.Execute(_insertSql, log);
} }
} }
} }
} }

Some files were not shown because too many files have changed in this diff Show More