diff --git a/Infrastructure/Hncore.Infrastructure/AliYun/AliDayu.cs b/Infrastructure/Hncore.Infrastructure/AliYun/AliDayu.cs index 3f196ba..a0d582b 100644 --- a/Infrastructure/Hncore.Infrastructure/AliYun/AliDayu.cs +++ b/Infrastructure/Hncore.Infrastructure/AliYun/AliDayu.cs @@ -1,71 +1,71 @@ -using System.Collections.Generic; -using System.Net.Http; -using System.Text; -using System.Threading.Tasks; -using System.Xml.Serialization; -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Serializer; - -namespace Hncore.Infrastructure.AliYun -{ - public class AliDayu - { - const string SignName = ""; - private IHttpClientFactory _httpClientFactory; - - public AliDayu(IHttpClientFactory httpClientFactory) - { - _httpClientFactory = httpClientFactory; - } - - public async Task SendSms(List PhoneNumbers, string templateCode, object content) - { - Dictionary paramDic = Util.BuildCommonParam(); - - paramDic.Add("Action", "SendSms"); - paramDic.Add("Version", "2017-05-25"); - paramDic.Add("RegionId", "cn-hangzhou"); - paramDic.Add("PhoneNumbers", ListHelper.ListToStr(PhoneNumbers)); - paramDic.Add("SignName", SignName); - paramDic.Add("TemplateCode", templateCode); - paramDic.Add("TemplateParam", content.ToJson()); - - string sign = Util.CreateSign(paramDic); - - paramDic.Add("Signature", sign); - - var httpClient = _httpClientFactory.CreateClient("AliDayu"); - - string url = "http://dysmsapi.aliyuncs.com"; - - foreach (var keyValuePair in paramDic) - { - url = UrlHelper.SetUrlParam(keyValuePair.Key, keyValuePair.Value); - } - - var res = await httpClient.GetStringAsync(url); - - SendSmsResponse result = XML.XmlDeserialize(res); - - if (result.Code == "OK") - { - return true; - } - - LogHelper.Error("阿里大于短信发送失败", res); - return false; - } - } - - [XmlRoot] - public class SendSmsResponse - { - [XmlElement] public string Message { get; set; } - - [XmlElement] public string RequestId { get; set; } - - [XmlElement] public string BizId { get; set; } - - [XmlElement] public string Code { get; set; } - } +using System.Collections.Generic; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Serialization; +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Serializer; + +namespace Hncore.Infrastructure.AliYun +{ + public class AliDayu + { + const string SignName = ""; + private IHttpClientFactory _httpClientFactory; + + public AliDayu(IHttpClientFactory httpClientFactory) + { + _httpClientFactory = httpClientFactory; + } + + public async Task SendSms(List PhoneNumbers, string templateCode, object content) + { + Dictionary paramDic = Util.BuildCommonParam(); + + paramDic.Add("Action", "SendSms"); + paramDic.Add("Version", "2017-05-25"); + paramDic.Add("RegionId", "cn-hangzhou"); + paramDic.Add("PhoneNumbers", ListHelper.ListToStr(PhoneNumbers)); + paramDic.Add("SignName", SignName); + paramDic.Add("TemplateCode", templateCode); + paramDic.Add("TemplateParam", content.ToJson()); + + string sign = Util.CreateSign(paramDic); + + paramDic.Add("Signature", sign); + + var httpClient = _httpClientFactory.CreateClient("AliDayu"); + + string url = "http://dysmsapi.aliyuncs.com"; + + foreach (var keyValuePair in paramDic) + { + url = UrlHelper.SetUrlParam(keyValuePair.Key, keyValuePair.Value); + } + + var res = await httpClient.GetStringAsync(url); + + SendSmsResponse result = XML.XmlDeserialize(res); + + if (result.Code == "OK") + { + return true; + } + + LogHelper.Error("阿里大于短信发送失败", res); + return false; + } + } + + [XmlRoot] + public class SendSmsResponse + { + [XmlElement] public string Message { get; set; } + + [XmlElement] public string RequestId { get; set; } + + [XmlElement] public string BizId { get; set; } + + [XmlElement] public string Code { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/AliYun/Util.cs b/Infrastructure/Hncore.Infrastructure/AliYun/Util.cs index 66abd56..e4ce937 100644 --- a/Infrastructure/Hncore.Infrastructure/AliYun/Util.cs +++ b/Infrastructure/Hncore.Infrastructure/AliYun/Util.cs @@ -1,82 +1,82 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Web; -using Microsoft.AspNetCore.Routing; - -namespace Hncore.Infrastructure.AliYun -{ - public class Util - { - const string QUERY_SEPARATOR = "&"; - const string HEADER_SEPARATOR = "\n"; - - const string AccessSecret = "r8FfRmoeWcCJyZSqqkQP2G3dKPPl2N "; - private const string AccessKeyId = "LTAI4FmSkDSwFuXeLxsDB3jB"; - - public static string CreateSign(Dictionary data, string method = "GET") - { - var dic = new RouteValueDictionary(data); - - - string[] array = dic.OrderBy(a => a.Key, StringComparer.Ordinal) - .Select(a => PercentEncode(a.Key) + "=" + PercentEncode(a.Value.ToString())).ToArray(); - string dataStr = string.Join("&", array); - string signStr = method + "&" + PercentEncode("/") + "&" + PercentEncode(dataStr); - - HMACSHA1 myhmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(AccessSecret + "&")); - byte[] byteArray = Encoding.UTF8.GetBytes(signStr); - MemoryStream stream = new MemoryStream(byteArray); - string signature = Convert.ToBase64String(myhmacsha1.ComputeHash(stream)); - - return signature; - } - - private static string PercentEncode(string value) - { - return UpperCaseUrlEncode(value) - .Replace("+", "%20") - .Replace("*", "%2A") - .Replace("%7E", "~"); - } - - private static string UpperCaseUrlEncode(string s) - { - char[] temp = HttpUtility.UrlEncode(s).ToCharArray(); - for (int i = 0; i < temp.Length - 2; i++) - { - if (temp[i] == '%') - { - temp[i + 1] = char.ToUpper(temp[i + 1]); - temp[i + 2] = char.ToUpper(temp[i + 2]); - } - } - - return new string(temp); - } - - public static IDictionary SortDictionary(Dictionary dic) - { - IDictionary sortedDictionary = - new SortedDictionary(dic, StringComparer.Ordinal); - return sortedDictionary; - } - - - public static Dictionary BuildCommonParam() - { - Dictionary dic = new Dictionary(); - - dic.Add("AccessKeyId", AccessKeyId); - dic.Add("Timestamp", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")); - dic.Add("SignatureMethod", "HMAC-SHA1"); - dic.Add("SignatureVersion", "1.0"); - dic.Add("SignatureNonce", Guid.NewGuid().ToString()); - - return dic; - } - } +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Web; +using Microsoft.AspNetCore.Routing; + +namespace Hncore.Infrastructure.AliYun +{ + public class Util + { + const string QUERY_SEPARATOR = "&"; + const string HEADER_SEPARATOR = "\n"; + + const string AccessSecret = "r8FfRmoeWcCJyZSqqkQP2G3dKPPl2N "; + private const string AccessKeyId = "LTAI4FmSkDSwFuXeLxsDB3jB"; + + public static string CreateSign(Dictionary data, string method = "GET") + { + var dic = new RouteValueDictionary(data); + + + string[] array = dic.OrderBy(a => a.Key, StringComparer.Ordinal) + .Select(a => PercentEncode(a.Key) + "=" + PercentEncode(a.Value.ToString())).ToArray(); + string dataStr = string.Join("&", array); + string signStr = method + "&" + PercentEncode("/") + "&" + PercentEncode(dataStr); + + HMACSHA1 myhmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(AccessSecret + "&")); + byte[] byteArray = Encoding.UTF8.GetBytes(signStr); + MemoryStream stream = new MemoryStream(byteArray); + string signature = Convert.ToBase64String(myhmacsha1.ComputeHash(stream)); + + return signature; + } + + private static string PercentEncode(string value) + { + return UpperCaseUrlEncode(value) + .Replace("+", "%20") + .Replace("*", "%2A") + .Replace("%7E", "~"); + } + + private static string UpperCaseUrlEncode(string s) + { + char[] temp = HttpUtility.UrlEncode(s).ToCharArray(); + for (int i = 0; i < temp.Length - 2; i++) + { + if (temp[i] == '%') + { + temp[i + 1] = char.ToUpper(temp[i + 1]); + temp[i + 2] = char.ToUpper(temp[i + 2]); + } + } + + return new string(temp); + } + + public static IDictionary SortDictionary(Dictionary dic) + { + IDictionary sortedDictionary = + new SortedDictionary(dic, StringComparer.Ordinal); + return sortedDictionary; + } + + + public static Dictionary BuildCommonParam() + { + Dictionary dic = new Dictionary(); + + dic.Add("AccessKeyId", AccessKeyId); + dic.Add("Timestamp", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")); + dic.Add("SignatureMethod", "HMAC-SHA1"); + dic.Add("SignatureVersion", "1.0"); + dic.Add("SignatureNonce", Guid.NewGuid().ToString()); + + return dic; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Autofac/MvcAutoRegister.cs b/Infrastructure/Hncore.Infrastructure/Autofac/MvcAutoRegister.cs index 58661a2..92a454c 100644 --- a/Infrastructure/Hncore.Infrastructure/Autofac/MvcAutoRegister.cs +++ b/Infrastructure/Hncore.Infrastructure/Autofac/MvcAutoRegister.cs @@ -1,61 +1,61 @@ -using System; -using System.Linq; -using Autofac; -using Autofac.Extensions.DependencyInjection; -using Hncore.Infrastructure.IOC; -using Microsoft.Extensions.DependencyInjection; -using Hncore.Infrastructure.DDD; -using Hncore.Infrastructure.EF; - -namespace Hncore.Infrastructure.Autofac -{ - public class MvcAutoRegister - { - public IServiceProvider Build(IServiceCollection services, IMvcBuilder mvcBuilder, - Action action = null) - { - mvcBuilder.AddControllersAsServices(); - - var builder = new ContainerBuilder(); - - var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToArray(); - - var perRequestType = typeof(IPerRequest); - builder.RegisterAssemblyTypes(assemblys) - .Where(t => perRequestType.IsAssignableFrom(t) && t != perRequestType) - .PropertiesAutowired() - .AsImplementedInterfaces() - .InstancePerLifetimeScope(); - - var perDependencyType = typeof(IDependency); - builder.RegisterAssemblyTypes(assemblys) - .Where(t => perDependencyType.IsAssignableFrom(t) && t != perDependencyType) - .PropertiesAutowired() - .AsImplementedInterfaces() - .InstancePerDependency(); - - var singleInstanceType = typeof(ISingleInstance); - builder.RegisterAssemblyTypes(assemblys) - .Where(t => singleInstanceType.IsAssignableFrom(t) && t != singleInstanceType) - .PropertiesAutowired() - .AsImplementedInterfaces() - .SingleInstance(); - - builder.RegisterGeneric(typeof(QueryBase<,>)).As(typeof(IQuery<,>)).PropertiesAutowired() - .InstancePerLifetimeScope(); - - builder.RegisterGeneric(typeof(RepositoryBase<,>)).As(typeof(IRepository<,>)).PropertiesAutowired() - .InstancePerLifetimeScope(); - - action?.Invoke(builder); - - builder.Populate(services); - - var container = builder.Build(); - - var servicesProvider = new AutofacServiceProvider(container); - - return servicesProvider; - } - } +using System; +using System.Linq; +using Autofac; +using Autofac.Extensions.DependencyInjection; +using Hncore.Infrastructure.IOC; +using Microsoft.Extensions.DependencyInjection; +using Hncore.Infrastructure.DDD; +using Hncore.Infrastructure.EF; + +namespace Hncore.Infrastructure.Autofac +{ + public class MvcAutoRegister + { + public IServiceProvider Build(IServiceCollection services, IMvcBuilder mvcBuilder, + Action action = null) + { + mvcBuilder.AddControllersAsServices(); + + var builder = new ContainerBuilder(); + + var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToArray(); + + var perRequestType = typeof(IPerRequest); + builder.RegisterAssemblyTypes(assemblys) + .Where(t => perRequestType.IsAssignableFrom(t) && t != perRequestType) + .PropertiesAutowired() + .AsImplementedInterfaces() + .InstancePerLifetimeScope(); + + var perDependencyType = typeof(IDependency); + builder.RegisterAssemblyTypes(assemblys) + .Where(t => perDependencyType.IsAssignableFrom(t) && t != perDependencyType) + .PropertiesAutowired() + .AsImplementedInterfaces() + .InstancePerDependency(); + + var singleInstanceType = typeof(ISingleInstance); + builder.RegisterAssemblyTypes(assemblys) + .Where(t => singleInstanceType.IsAssignableFrom(t) && t != singleInstanceType) + .PropertiesAutowired() + .AsImplementedInterfaces() + .SingleInstance(); + + builder.RegisterGeneric(typeof(QueryBase<,>)).As(typeof(IQuery<,>)).PropertiesAutowired() + .InstancePerLifetimeScope(); + + builder.RegisterGeneric(typeof(RepositoryBase<,>)).As(typeof(IRepository<,>)).PropertiesAutowired() + .InstancePerLifetimeScope(); + + action?.Invoke(builder); + + builder.Populate(services); + + var container = builder.Build(); + + var servicesProvider = new AutofacServiceProvider(container); + + return servicesProvider; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/CSV/CsvRow.cs b/Infrastructure/Hncore.Infrastructure/CSV/CsvRow.cs index 15e6ad7..a8822a4 100644 --- a/Infrastructure/Hncore.Infrastructure/CSV/CsvRow.cs +++ b/Infrastructure/Hncore.Infrastructure/CSV/CsvRow.cs @@ -1,49 +1,49 @@ -using System.Text; - -namespace Hncore.Infrastructure.CSV -{ - public class CsvRow - { - private string _content = ""; - - public CsvRow AddCell(string content) - { - if (_content != "") - { - _content += ","; - } - - _content += StringToCsvCell(content); - - return this; - } - - public override string ToString() - { - return _content; - } - - private static string StringToCsvCell(string str) - { - bool mustQuote = str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n"); - if (mustQuote) - { - StringBuilder sb = new StringBuilder(); - sb.Append("\""); - foreach (char nextChar in str) - { - sb.Append(nextChar); - if (nextChar == '"') - { - sb.Append("\""); - } - } - - sb.Append("\""); - return sb.ToString(); - } - - return str; - } - } +using System.Text; + +namespace Hncore.Infrastructure.CSV +{ + public class CsvRow + { + private string _content = ""; + + public CsvRow AddCell(string content) + { + if (_content != "") + { + _content += ","; + } + + _content += StringToCsvCell(content); + + return this; + } + + public override string ToString() + { + return _content; + } + + private static string StringToCsvCell(string str) + { + bool mustQuote = str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n"); + if (mustQuote) + { + StringBuilder sb = new StringBuilder(); + sb.Append("\""); + foreach (char nextChar in str) + { + sb.Append(nextChar); + if (nextChar == '"') + { + sb.Append("\""); + } + } + + sb.Append("\""); + return sb.ToString(); + } + + return str; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/CSV/CsvTemporaryFile.cs b/Infrastructure/Hncore.Infrastructure/CSV/CsvTemporaryFile.cs index 15f47a9..262e8d4 100644 --- a/Infrastructure/Hncore.Infrastructure/CSV/CsvTemporaryFile.cs +++ b/Infrastructure/Hncore.Infrastructure/CSV/CsvTemporaryFile.cs @@ -1,84 +1,84 @@ -using System; -using System.IO; -using System.Text; -using System.Threading.Tasks; -using Hncore.Infrastructure.Extension; -using Microsoft.AspNetCore.Http; - -namespace Hncore.Infrastructure.CSV -{ - public class CsvTemporaryFile : IDisposable - { - private string filePath = ""; - private FileStream _fileStream; - private StreamWriter _streamWriter; - - public CsvTemporaryFile() - { - var execDir = Path.GetDirectoryName(typeof(CsvTemporaryFile).Assembly.Location); - - string tempDir = Path.Combine(execDir, "temp", DateTime.Now.ToString("yyyyMMdd")); - - if (!Directory.Exists(tempDir)) - { - Directory.CreateDirectory(tempDir); - } - - filePath = Path.Combine(tempDir, Guid.NewGuid().ToString()); - - _fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write); - _streamWriter = new StreamWriter(_fileStream, Encoding.GetEncoding("GB2312")); - _streamWriter.AutoFlush = true; - } - - public void WriteLine(CsvRow row) - { - _streamWriter.WriteLine(row.ToString()); - } - - public async Task ResponseAsync(HttpResponse httpResponse, string fileName) - { - httpResponse.ContentType = "application/octet-stream"; - httpResponse.Headers.Add("Content-Disposition", $"attachment; filename={fileName.UrlEncode()}"); - httpResponse.Headers.Add("X-Suggested-Filename", fileName.UrlEncode()); - - using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - { - using (BufferedStream bs = new BufferedStream(fs)) - { - byte[] buffer = new byte[4096]; - int bytesRead; - - long total_read = 0; - DateTime begin = DateTime.Now; - TimeSpan ts = new TimeSpan(); - - while ((bytesRead = bs.Read(buffer, 0, buffer.Length)) > 0) - { - await httpResponse.Body.WriteAsync(buffer, 0, bytesRead); - await httpResponse.Body.FlushAsync(); - - total_read += bytesRead; - ts = DateTime.Now - begin; - if (total_read / ts.TotalSeconds > 1024 * 1000) - { - await Task.Delay(1); - } - } - } - } - } - - public void Dispose() - { - _streamWriter?.Dispose(); - _fileStream?.Dispose(); - - - if (File.Exists(filePath)) - { - File.Delete(filePath); - } - } - } +using System; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using Hncore.Infrastructure.Extension; +using Microsoft.AspNetCore.Http; + +namespace Hncore.Infrastructure.CSV +{ + public class CsvTemporaryFile : IDisposable + { + private string filePath = ""; + private FileStream _fileStream; + private StreamWriter _streamWriter; + + public CsvTemporaryFile() + { + var execDir = Path.GetDirectoryName(typeof(CsvTemporaryFile).Assembly.Location); + + string tempDir = Path.Combine(execDir, "temp", DateTime.Now.ToString("yyyyMMdd")); + + if (!Directory.Exists(tempDir)) + { + Directory.CreateDirectory(tempDir); + } + + filePath = Path.Combine(tempDir, Guid.NewGuid().ToString()); + + _fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write); + _streamWriter = new StreamWriter(_fileStream, Encoding.GetEncoding("GB2312")); + _streamWriter.AutoFlush = true; + } + + public void WriteLine(CsvRow row) + { + _streamWriter.WriteLine(row.ToString()); + } + + public async Task ResponseAsync(HttpResponse httpResponse, string fileName) + { + httpResponse.ContentType = "application/octet-stream"; + httpResponse.Headers.Add("Content-Disposition", $"attachment; filename={fileName.UrlEncode()}"); + httpResponse.Headers.Add("X-Suggested-Filename", fileName.UrlEncode()); + + using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + { + using (BufferedStream bs = new BufferedStream(fs)) + { + byte[] buffer = new byte[4096]; + int bytesRead; + + long total_read = 0; + DateTime begin = DateTime.Now; + TimeSpan ts = new TimeSpan(); + + while ((bytesRead = bs.Read(buffer, 0, buffer.Length)) > 0) + { + await httpResponse.Body.WriteAsync(buffer, 0, bytesRead); + await httpResponse.Body.FlushAsync(); + + total_read += bytesRead; + ts = DateTime.Now - begin; + if (total_read / ts.TotalSeconds > 1024 * 1000) + { + await Task.Delay(1); + } + } + } + } + } + + public void Dispose() + { + _streamWriter?.Dispose(); + _fileStream?.Dispose(); + + + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/AssemblyUtil.cs b/Infrastructure/Hncore.Infrastructure/Common/AssemblyUtil.cs index b776dd3..c561798 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/AssemblyUtil.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/AssemblyUtil.cs @@ -1,274 +1,274 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Reflection; -using System.IO; -using System.Linq; -using System.Globalization; - -#if !SILVERLIGHT -using System.Runtime.Serialization.Formatters.Binary; -#endif - -namespace Hncore.Infrastructure.Utils -{ - /// - /// Assembly Util Class - /// - public static class AssemblyUtil - { - /// - /// Creates the instance from type name. - /// - /// - /// The type. - /// - public static T CreateInstance(string type) - { - return CreateInstance(type, new object[0]); - } - - /// - /// Creates the instance from type name and parameters. - /// - /// - /// The type. - /// The parameters. - /// - public static T CreateInstance(string type, object[] parameters) - { - Type instanceType = null; - var result = default(T); - - instanceType = Type.GetType(type, true); - - if (instanceType == null) - throw new Exception(string.Format("The type '{0}' was not found!", type)); - - object instance = Activator.CreateInstance(instanceType, parameters); - result = (T)instance; - return result; - } - - /// - /// Gets the type by the full name, also return matched generic type without checking generic type parameters in the name. - /// - /// Full name of the type. - /// if set to true [throw on error]. - /// if set to true [ignore case]. - /// -#if !NET35 - public static Type GetType(string fullTypeName, bool throwOnError, bool ignoreCase) - { - var targetType = Type.GetType(fullTypeName, false, ignoreCase); - - if (targetType != null) - return targetType; - - var names = fullTypeName.Split(','); - var assemblyName = names[1].Trim(); - - try - { - var assembly = Assembly.Load(assemblyName); - - var typeNamePrefix = names[0].Trim() + "`"; - - var matchedTypes = assembly.GetExportedTypes().Where(t => t.IsGenericType - && t.FullName.StartsWith(typeNamePrefix, ignoreCase, CultureInfo.InvariantCulture)).ToArray(); - - if (matchedTypes.Length != 1) - return null; - - return matchedTypes[0]; - } - catch (Exception e) - { - if (throwOnError) - throw e; - - return null; - } - } -#else - public static Type GetType(string fullTypeName, bool throwOnError, bool ignoreCase) - { - return Type.GetType(fullTypeName, null, (a, n, ign) => - { - var targetType = a.GetType(n, false, ign); - - if (targetType != null) - return targetType; - - var typeNamePrefix = n + "`"; - - var matchedTypes = a.GetExportedTypes().Where(t => t.IsGenericType - && t.FullName.StartsWith(typeNamePrefix, ign, CultureInfo.InvariantCulture)).ToArray(); - - if (matchedTypes.Length != 1) - return null; - - return matchedTypes[0]; - }, throwOnError, ignoreCase); - } -#endif - - /// - /// Gets the implement types from assembly. - /// - /// The type of the base type. - /// The assembly. - /// - public static IEnumerable GetImplementTypes(this Assembly assembly) - { - return assembly.GetExportedTypes().Where(t => - t.IsSubclassOf(typeof(TBaseType)) && t.IsClass && !t.IsAbstract); - } - - /// - /// Gets the implemented objects by interface. - /// - /// The type of the base interface. - /// The assembly. - /// - public static IEnumerable GetImplementedObjectsByInterface(this Assembly assembly) - where TBaseInterface : class - { - return GetImplementedObjectsByInterface(assembly, typeof(TBaseInterface)); - } - - /// - /// Gets the implemented objects by interface. - /// - /// The type of the base interface. - /// The assembly. - /// Type of the target. - /// - public static IEnumerable GetImplementedObjectsByInterface(this Assembly assembly, Type targetType) - where TBaseInterface : class - { - Type[] arrType = assembly.GetExportedTypes(); - - var result = new List(); - - for (int i = 0; i < arrType.Length; i++) - { - var currentImplementType = arrType[i]; - - if (currentImplementType.IsAbstract) - continue; - - if (!targetType.IsAssignableFrom(currentImplementType)) - continue; - - result.Add((TBaseInterface)Activator.CreateInstance(currentImplementType)); - } - - return result; - } - -#if SILVERLIGHT -#else - /// - /// Clone object in binary format. - /// - /// - /// The target. - /// - public static T BinaryClone(this T target) - { - BinaryFormatter formatter = new BinaryFormatter(); - using (MemoryStream ms = new MemoryStream()) - { - formatter.Serialize(ms, target); - ms.Position = 0; - return (T)formatter.Deserialize(ms); - } - } -#endif - - - /// - /// Copies the properties of one object to another object. - /// - /// - /// The source. - /// The target. - /// - public static T CopyPropertiesTo(this T source, T target) - { - return source.CopyPropertiesTo(p => true, target); - } - - /// - /// Copies the properties of one object to another object. - /// - /// - /// The source. - /// The properties predict. - /// The target. - /// - public static T CopyPropertiesTo(this T source, Predicate predict, T target) - { - PropertyInfo[] properties = source.GetType() - .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty); - - Dictionary sourcePropertiesDict = properties.ToDictionary(p => p.Name); - - PropertyInfo[] targetProperties = target.GetType() - .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty) - .Where(p => predict(p)).ToArray(); - - for (int i = 0; i < targetProperties.Length; i++) - { - var p = targetProperties[i]; - PropertyInfo sourceProperty; - - if (sourcePropertiesDict.TryGetValue(p.Name, out sourceProperty)) - { - if (sourceProperty.PropertyType != p.PropertyType) - continue; - - if (!sourceProperty.PropertyType.IsSerializable) - continue; - - p.SetValue(target, sourceProperty.GetValue(source, null), null); - } - } - - return target; - } - - /// - /// Gets the assemblies from string. - /// - /// The assembly def. - /// - public static IEnumerable GetAssembliesFromString(string assemblyDef) - { - return GetAssembliesFromStrings(assemblyDef.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)); - } - - /// - /// Gets the assemblies from strings. - /// - /// The assemblies. - /// - public static IEnumerable GetAssembliesFromStrings(string[] assemblies) - { - List result = new List(assemblies.Length); - - foreach (var a in assemblies) - { - result.Add(Assembly.Load(a)); - } - - return result; - } - - public static bool IsImplementedInterface() - { - return typeof(TInterface).IsAssignableFrom(typeof(T)); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Reflection; +using System.IO; +using System.Linq; +using System.Globalization; + +#if !SILVERLIGHT +using System.Runtime.Serialization.Formatters.Binary; +#endif + +namespace Hncore.Infrastructure.Utils +{ + /// + /// Assembly Util Class + /// + public static class AssemblyUtil + { + /// + /// Creates the instance from type name. + /// + /// + /// The type. + /// + public static T CreateInstance(string type) + { + return CreateInstance(type, new object[0]); + } + + /// + /// Creates the instance from type name and parameters. + /// + /// + /// The type. + /// The parameters. + /// + public static T CreateInstance(string type, object[] parameters) + { + Type instanceType = null; + var result = default(T); + + instanceType = Type.GetType(type, true); + + if (instanceType == null) + throw new Exception(string.Format("The type '{0}' was not found!", type)); + + object instance = Activator.CreateInstance(instanceType, parameters); + result = (T)instance; + return result; + } + + /// + /// Gets the type by the full name, also return matched generic type without checking generic type parameters in the name. + /// + /// Full name of the type. + /// if set to true [throw on error]. + /// if set to true [ignore case]. + /// +#if !NET35 + public static Type GetType(string fullTypeName, bool throwOnError, bool ignoreCase) + { + var targetType = Type.GetType(fullTypeName, false, ignoreCase); + + if (targetType != null) + return targetType; + + var names = fullTypeName.Split(','); + var assemblyName = names[1].Trim(); + + try + { + var assembly = Assembly.Load(assemblyName); + + var typeNamePrefix = names[0].Trim() + "`"; + + var matchedTypes = assembly.GetExportedTypes().Where(t => t.IsGenericType + && t.FullName.StartsWith(typeNamePrefix, ignoreCase, CultureInfo.InvariantCulture)).ToArray(); + + if (matchedTypes.Length != 1) + return null; + + return matchedTypes[0]; + } + catch (Exception e) + { + if (throwOnError) + throw e; + + return null; + } + } +#else + public static Type GetType(string fullTypeName, bool throwOnError, bool ignoreCase) + { + return Type.GetType(fullTypeName, null, (a, n, ign) => + { + var targetType = a.GetType(n, false, ign); + + if (targetType != null) + return targetType; + + var typeNamePrefix = n + "`"; + + var matchedTypes = a.GetExportedTypes().Where(t => t.IsGenericType + && t.FullName.StartsWith(typeNamePrefix, ign, CultureInfo.InvariantCulture)).ToArray(); + + if (matchedTypes.Length != 1) + return null; + + return matchedTypes[0]; + }, throwOnError, ignoreCase); + } +#endif + + /// + /// Gets the implement types from assembly. + /// + /// The type of the base type. + /// The assembly. + /// + public static IEnumerable GetImplementTypes(this Assembly assembly) + { + return assembly.GetExportedTypes().Where(t => + t.IsSubclassOf(typeof(TBaseType)) && t.IsClass && !t.IsAbstract); + } + + /// + /// Gets the implemented objects by interface. + /// + /// The type of the base interface. + /// The assembly. + /// + public static IEnumerable GetImplementedObjectsByInterface(this Assembly assembly) + where TBaseInterface : class + { + return GetImplementedObjectsByInterface(assembly, typeof(TBaseInterface)); + } + + /// + /// Gets the implemented objects by interface. + /// + /// The type of the base interface. + /// The assembly. + /// Type of the target. + /// + public static IEnumerable GetImplementedObjectsByInterface(this Assembly assembly, Type targetType) + where TBaseInterface : class + { + Type[] arrType = assembly.GetExportedTypes(); + + var result = new List(); + + for (int i = 0; i < arrType.Length; i++) + { + var currentImplementType = arrType[i]; + + if (currentImplementType.IsAbstract) + continue; + + if (!targetType.IsAssignableFrom(currentImplementType)) + continue; + + result.Add((TBaseInterface)Activator.CreateInstance(currentImplementType)); + } + + return result; + } + +#if SILVERLIGHT +#else + /// + /// Clone object in binary format. + /// + /// + /// The target. + /// + public static T BinaryClone(this T target) + { + BinaryFormatter formatter = new BinaryFormatter(); + using (MemoryStream ms = new MemoryStream()) + { + formatter.Serialize(ms, target); + ms.Position = 0; + return (T)formatter.Deserialize(ms); + } + } +#endif + + + /// + /// Copies the properties of one object to another object. + /// + /// + /// The source. + /// The target. + /// + public static T CopyPropertiesTo(this T source, T target) + { + return source.CopyPropertiesTo(p => true, target); + } + + /// + /// Copies the properties of one object to another object. + /// + /// + /// The source. + /// The properties predict. + /// The target. + /// + public static T CopyPropertiesTo(this T source, Predicate predict, T target) + { + PropertyInfo[] properties = source.GetType() + .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty); + + Dictionary sourcePropertiesDict = properties.ToDictionary(p => p.Name); + + PropertyInfo[] targetProperties = target.GetType() + .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty) + .Where(p => predict(p)).ToArray(); + + for (int i = 0; i < targetProperties.Length; i++) + { + var p = targetProperties[i]; + PropertyInfo sourceProperty; + + if (sourcePropertiesDict.TryGetValue(p.Name, out sourceProperty)) + { + if (sourceProperty.PropertyType != p.PropertyType) + continue; + + if (!sourceProperty.PropertyType.IsSerializable) + continue; + + p.SetValue(target, sourceProperty.GetValue(source, null), null); + } + } + + return target; + } + + /// + /// Gets the assemblies from string. + /// + /// The assembly def. + /// + public static IEnumerable GetAssembliesFromString(string assemblyDef) + { + return GetAssembliesFromStrings(assemblyDef.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)); + } + + /// + /// Gets the assemblies from strings. + /// + /// The assemblies. + /// + public static IEnumerable GetAssembliesFromStrings(string[] assemblies) + { + List result = new List(assemblies.Length); + + foreach (var a in assemblies) + { + result.Add(Assembly.Load(a)); + } + + return result; + } + + public static bool IsImplementedInterface() + { + return typeof(TInterface).IsAssignableFrom(typeof(T)); + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Common/BinaryHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/BinaryHelper.cs index ca09ede..da2b5dd 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/BinaryHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/BinaryHelper.cs @@ -1,44 +1,44 @@ -using System.IO; -using System.Runtime.Serialization.Formatters.Binary; - -namespace Hncore.Infrastructure.Common -{ - /// - /// 二进制序列化 - /// - public class BinaryHelper - { - /// - /// 序列化对象(二进制) - /// - /// 需要序列化的对象 - public static byte[] Serialize(object obj) - { - using (MemoryStream ms = new MemoryStream()) - { - BinaryFormatter binaryFormatter = new BinaryFormatter(); - binaryFormatter.Serialize(ms, obj); - return ms.ToArray(); - } - } - - /// - /// 反序列化对象(二进制) - /// - /// 需要反序列化的字符串 - public static object Deserialize(byte[] bytes) - { - if (bytes == null) - { - return null; - } - using (MemoryStream ms = new MemoryStream()) - { - ms.Write(bytes, 0, bytes.Length); - ms.Seek(0, SeekOrigin.Begin); - BinaryFormatter binaryFormatter = new BinaryFormatter(); - return binaryFormatter.Deserialize(ms); - } - } - } -} +using System.IO; +using System.Runtime.Serialization.Formatters.Binary; + +namespace Hncore.Infrastructure.Common +{ + /// + /// 二进制序列化 + /// + public class BinaryHelper + { + /// + /// 序列化对象(二进制) + /// + /// 需要序列化的对象 + public static byte[] Serialize(object obj) + { + using (MemoryStream ms = new MemoryStream()) + { + BinaryFormatter binaryFormatter = new BinaryFormatter(); + binaryFormatter.Serialize(ms, obj); + return ms.ToArray(); + } + } + + /// + /// 反序列化对象(二进制) + /// + /// 需要反序列化的字符串 + public static object Deserialize(byte[] bytes) + { + if (bytes == null) + { + return null; + } + using (MemoryStream ms = new MemoryStream()) + { + ms.Write(bytes, 0, bytes.Length); + ms.Seek(0, SeekOrigin.Begin); + BinaryFormatter binaryFormatter = new BinaryFormatter(); + return binaryFormatter.Deserialize(ms); + } + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Common/CheckHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/CheckHelper.cs index 468a659..5459be4 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/CheckHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/CheckHelper.cs @@ -1,55 +1,55 @@ -using System; -using System.Linq; -using Microsoft.AspNetCore.Mvc.ModelBinding; -using Hncore.Infrastructure.Data; - -namespace Hncore.Infrastructure.Common -{ - public class CheckHelper - { - public static void NotNull(object obj, string message = "") - { - if (ReferenceEquals(obj, null)) - { - if (string.IsNullOrEmpty(message)) - { - message = nameof(obj) + "空引用"; - } - - throw new BusinessException(message); - } - } - - public static void NotEmpty(string obj, string message = "") - { - NotNull(obj,message); - - if (obj.Trim() == "") - { - if (string.IsNullOrEmpty(message)) - { - message = nameof(obj) + "值不能为空"; - } - - throw new BusinessException(message); - } - } - } - - public static class Ext - { - public static void Check(this ModelStateDictionary dic) - { - if (!dic.IsValid) - { - var errs = dic.Values.SelectMany(x => x.Errors); - - string msg = ""; - - errs.Select(t => t.Exception.Message).ToList().ForEach((s => { msg += s + "\r\n"; })); - - throw new Exception(msg); - } - } - } +using System; +using System.Linq; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Hncore.Infrastructure.Data; + +namespace Hncore.Infrastructure.Common +{ + public class CheckHelper + { + public static void NotNull(object obj, string message = "") + { + if (ReferenceEquals(obj, null)) + { + if (string.IsNullOrEmpty(message)) + { + message = nameof(obj) + "空引用"; + } + + throw new BusinessException(message); + } + } + + public static void NotEmpty(string obj, string message = "") + { + NotNull(obj,message); + + if (obj.Trim() == "") + { + if (string.IsNullOrEmpty(message)) + { + message = nameof(obj) + "值不能为空"; + } + + throw new BusinessException(message); + } + } + } + + public static class Ext + { + public static void Check(this ModelStateDictionary dic) + { + if (!dic.IsValid) + { + var errs = dic.Values.SelectMany(x => x.Errors); + + string msg = ""; + + errs.Select(t => t.Exception.Message).ToList().ForEach((s => { msg += s + "\r\n"; })); + + throw new Exception(msg); + } + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/ConcurrentHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/ConcurrentHelper.cs index c85991f..36a5177 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/ConcurrentHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/ConcurrentHelper.cs @@ -1,75 +1,75 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Dapper; -using MySql.Data.MySqlClient; - -namespace Hncore.Infrastructure.Common -{ - public class ConcurrentHelper - { - private static string _connString = ""; - private static string _tableName = "concurrent_helper"; - - private List _infos = new List(); - - private string _id; - - public static void Init(string mysqlConn) - { - _connString = mysqlConn; - - MySqlHelper.Execute(_connString - , $@"create table if not exists {_tableName} - ( - Id VARCHAR(32) PRIMARY KEY UNIQUE, - CreateTime datetime DEFAULT now(), - Info text - )" - ); - } - - public ConcurrentHelper AddInfo(string info) - { - _infos.Add(info); - - return this; - } - - private async Task GetAuthority() - { - try - { - string info = ListHelper.ListToStr(_infos, "\n"); - _id = SecurityHelper.GetMd5Hash(info); - - string sql = $"insert into {_tableName}(Id,Info) values(@Id,@Info)"; - - await MySqlHelper.ExecuteAsync(_connString, sql, new {Id = _id, Info = info}); - } - catch - { - return false; - } - - return true; - } - - public async Task Execute(Action action) - { - try - { - if (await GetAuthority()) - { - action(); - } - } - catch (Exception e) - { - await MySqlHelper.ExecuteAsync(_connString, $"DELETE FROM {_tableName} where Id='{_id}'"); - - throw e; - } - } - } +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Dapper; +using MySql.Data.MySqlClient; + +namespace Hncore.Infrastructure.Common +{ + public class ConcurrentHelper + { + private static string _connString = ""; + private static string _tableName = "concurrent_helper"; + + private List _infos = new List(); + + private string _id; + + public static void Init(string mysqlConn) + { + _connString = mysqlConn; + + MySqlHelper.Execute(_connString + , $@"create table if not exists {_tableName} + ( + Id VARCHAR(32) PRIMARY KEY UNIQUE, + CreateTime datetime DEFAULT now(), + Info text + )" + ); + } + + public ConcurrentHelper AddInfo(string info) + { + _infos.Add(info); + + return this; + } + + private async Task GetAuthority() + { + try + { + string info = ListHelper.ListToStr(_infos, "\n"); + _id = SecurityHelper.GetMd5Hash(info); + + string sql = $"insert into {_tableName}(Id,Info) values(@Id,@Info)"; + + await MySqlHelper.ExecuteAsync(_connString, sql, new {Id = _id, Info = info}); + } + catch + { + return false; + } + + return true; + } + + public async Task Execute(Action action) + { + try + { + if (await GetAuthority()) + { + action(); + } + } + catch (Exception e) + { + await MySqlHelper.ExecuteAsync(_connString, $"DELETE FROM {_tableName} where Id='{_id}'"); + + throw e; + } + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/ContentTypeHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/ContentTypeHelper.cs index 80884bb..6bb2132 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/ContentTypeHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/ContentTypeHelper.cs @@ -1,102 +1,102 @@ -using System.Collections.Generic; -using System.ComponentModel; - -namespace Hncore.Infrastructure.Common -{ - /// - /// 文件类型 - /// - public class ContentTypeHelper - { - /// - /// 图片格式 - /// - public static List ImageList = new List() - { - "image/jpeg", - "application/x-jpe", - "application/x-jpg", - "application/x-bmp", - "image/png", - "application/x-png", - "image/gif" - }; - - /// - /// 视频格式 - /// - public static List VideoList = new List() - { - "video/mpeg4", - "video/avi", - "video/x-ms-wmv", - "video/x-mpeg", - "video/mpeg4", - "video/x-sgi-movie", - "application/vnd.rn-realmedia", - "application/x-shockwave-flash", - "application/vnd.rn-realmedia-vbr", - "application/octet-stream", - "flv-application/octet-stream", - "video/mpg", - "video/mpeg", - "video/mp4", - "video/x-msvideo" - }; - - #region 得到文件类型 - - /// - /// 得到文件类型 - /// - /// 文件类型 - /// - public static FileTypeEnum GetFileType(string contentType) - { - if (ImageList.Contains(contentType)) - { - return FileTypeEnum.Img; - } - - if (VideoList.Contains(contentType)) - { - return FileTypeEnum.Video; - } - - return FileTypeEnum.Unknow; - } - - #endregion - } - - /// - /// 文件类型 - /// - public enum FileTypeEnum - { - /// - /// 未知 - /// - [Description("未知")] Unknow = 0, - - /// - /// 图片 - /// - [Description("图片")] Img = 1, - - /// - /// 音频 - /// - [Description("音频")] Audio = 2, - - /// - /// 视频 - /// - [Description("视频")] Video = 3, - - /// - /// 其他 - /// - [Description("其他")] Other = 4 - } +using System.Collections.Generic; +using System.ComponentModel; + +namespace Hncore.Infrastructure.Common +{ + /// + /// 文件类型 + /// + public class ContentTypeHelper + { + /// + /// 图片格式 + /// + public static List ImageList = new List() + { + "image/jpeg", + "application/x-jpe", + "application/x-jpg", + "application/x-bmp", + "image/png", + "application/x-png", + "image/gif" + }; + + /// + /// 视频格式 + /// + public static List VideoList = new List() + { + "video/mpeg4", + "video/avi", + "video/x-ms-wmv", + "video/x-mpeg", + "video/mpeg4", + "video/x-sgi-movie", + "application/vnd.rn-realmedia", + "application/x-shockwave-flash", + "application/vnd.rn-realmedia-vbr", + "application/octet-stream", + "flv-application/octet-stream", + "video/mpg", + "video/mpeg", + "video/mp4", + "video/x-msvideo" + }; + + #region 得到文件类型 + + /// + /// 得到文件类型 + /// + /// 文件类型 + /// + public static FileTypeEnum GetFileType(string contentType) + { + if (ImageList.Contains(contentType)) + { + return FileTypeEnum.Img; + } + + if (VideoList.Contains(contentType)) + { + return FileTypeEnum.Video; + } + + return FileTypeEnum.Unknow; + } + + #endregion + } + + /// + /// 文件类型 + /// + public enum FileTypeEnum + { + /// + /// 未知 + /// + [Description("未知")] Unknow = 0, + + /// + /// 图片 + /// + [Description("图片")] Img = 1, + + /// + /// 音频 + /// + [Description("音频")] Audio = 2, + + /// + /// 视频 + /// + [Description("视频")] Video = 3, + + /// + /// 其他 + /// + [Description("其他")] Other = 4 + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/DateTimeHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/DateTimeHelper.cs index f0c53da..91b2dc6 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/DateTimeHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/DateTimeHelper.cs @@ -1,80 +1,80 @@ -using System; -using System.Runtime.InteropServices; - -namespace Hncore.Infrastructure.Common -{ - public class DateTimeHelper - { - public static DateTime SqlMinTime => Convert.ToDateTime("1975-01-01 00:00:00"); - - public static DateTime SqlMaxTime => Convert.ToDateTime("9999-12-31 23:59:59"); - - /// - /// 将10位时间戳转时间 - /// - /// - /// - public static DateTime UnixTimeStampToDateTime(long unixTimeStamp) - { - // Unix timestamp is seconds past epoch - DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); - dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime(); - return dtDateTime; - } - - public static long ToUnixTimestamp(DateTime target) - { - return Convert.ToInt64((TimeZoneInfo.ConvertTimeToUtc(target) - - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds); - } - - /// - /// 将13位时间戳转为时间 - /// - /// - /// - public static DateTime JsTimeStampToDateTime(double javaTimeStamp) - { - var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); - dtDateTime = dtDateTime.AddMilliseconds(javaTimeStamp).ToLocalTime(); - return dtDateTime; - } - - /// - /// 获取时间戳 - /// - /// - /// 为真时获取10位时间戳,为假时获取13位时间戳 - /// - public static long ToUnixTime(DateTime target, bool bflag = false) - { - TimeSpan ts = target - new DateTime(1970, 1, 1, 0, 0, 0, 0); - long timer = 0; - timer = Convert.ToInt64(!bflag ? ts.TotalSeconds : ts.TotalMilliseconds); - return timer; - } - - public static TimeZoneInfo GetCstTimeZoneInfo() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return TimeZoneInfo.FindSystemTimeZoneById("Asia/Shanghai"); - } - - return TimeZoneInfo.FindSystemTimeZoneById("China Standard Time"); - } - - public static bool IsSameDayOrLess(DateTime dt1, DateTime dt2) - { - return dt1.Year == dt2.Year - && dt1.Month == dt2.Month - && dt1.Day == dt2.Day - || dt1 < dt2; - } - - public static DateTime GetDatePart(DateTime dt) - { - return new DateTime(dt.Year, dt.Month, dt.Day); - } - } +using System; +using System.Runtime.InteropServices; + +namespace Hncore.Infrastructure.Common +{ + public class DateTimeHelper + { + public static DateTime SqlMinTime => Convert.ToDateTime("1975-01-01 00:00:00"); + + public static DateTime SqlMaxTime => Convert.ToDateTime("9999-12-31 23:59:59"); + + /// + /// 将10位时间戳转时间 + /// + /// + /// + public static DateTime UnixTimeStampToDateTime(long unixTimeStamp) + { + // Unix timestamp is seconds past epoch + DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime(); + return dtDateTime; + } + + public static long ToUnixTimestamp(DateTime target) + { + return Convert.ToInt64((TimeZoneInfo.ConvertTimeToUtc(target) - + new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds); + } + + /// + /// 将13位时间戳转为时间 + /// + /// + /// + public static DateTime JsTimeStampToDateTime(double javaTimeStamp) + { + var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + dtDateTime = dtDateTime.AddMilliseconds(javaTimeStamp).ToLocalTime(); + return dtDateTime; + } + + /// + /// 获取时间戳 + /// + /// + /// 为真时获取10位时间戳,为假时获取13位时间戳 + /// + public static long ToUnixTime(DateTime target, bool bflag = false) + { + TimeSpan ts = target - new DateTime(1970, 1, 1, 0, 0, 0, 0); + long timer = 0; + timer = Convert.ToInt64(!bflag ? ts.TotalSeconds : ts.TotalMilliseconds); + return timer; + } + + public static TimeZoneInfo GetCstTimeZoneInfo() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + return TimeZoneInfo.FindSystemTimeZoneById("Asia/Shanghai"); + } + + return TimeZoneInfo.FindSystemTimeZoneById("China Standard Time"); + } + + public static bool IsSameDayOrLess(DateTime dt1, DateTime dt2) + { + return dt1.Year == dt2.Year + && dt1.Month == dt2.Month + && dt1.Day == dt2.Day + || dt1 < dt2; + } + + public static DateTime GetDatePart(DateTime dt) + { + return new DateTime(dt.Year, dt.Month, dt.Day); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/DebugClass.cs b/Infrastructure/Hncore.Infrastructure/Common/DebugClass.cs index e40af52..7ee3fa6 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/DebugClass.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/DebugClass.cs @@ -1,28 +1,28 @@ -using System; -using System.Diagnostics; -using System.Text; - -namespace Hncore.Infrastructure.Utils -{ - public static class DebugClass - { - public static string PrintStack(bool isOutToDebugWin) - { - StackFrame[] stacks = new StackTrace().GetFrames(); - StringBuilder result = new StringBuilder(); - foreach (StackFrame stack in stacks) - { - result.AppendFormat("{0} {1} {2} {3}{4}", - stack.GetFileName(), - stack.GetFileLineNumber(), - stack.GetFileColumnNumber(), - stack.GetMethod().ToString(), - Environment.NewLine - ); - } - if (isOutToDebugWin) - Debug.WriteLine(result); - return result.ToString(); - } - } -} +using System; +using System.Diagnostics; +using System.Text; + +namespace Hncore.Infrastructure.Utils +{ + public static class DebugClass + { + public static string PrintStack(bool isOutToDebugWin) + { + StackFrame[] stacks = new StackTrace().GetFrames(); + StringBuilder result = new StringBuilder(); + foreach (StackFrame stack in stacks) + { + result.AppendFormat("{0} {1} {2} {3}{4}", + stack.GetFileName(), + stack.GetFileLineNumber(), + stack.GetFileColumnNumber(), + stack.GetMethod().ToString(), + Environment.NewLine + ); + } + if (isOutToDebugWin) + Debug.WriteLine(result); + return result.ToString(); + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Common/DingTalkHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/DingTalkHelper.cs index 005fc70..e6fbadb 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/DingTalkHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/DingTalkHelper.cs @@ -1,151 +1,151 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Threading.Tasks; -using Hncore.Infrastructure.Serializer; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Hncore.Infrastructure.Common.DingTalk -{ - public class DingTalkHelper - { - private static HttpClient _httpClient = new HttpClient(new HttpClientHandler() {UseProxy = false}) - {Timeout = TimeSpan.FromMinutes(1)}; - - static DingTalkHelper() - { - _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - } - - public static Task SendMessage(object message) - { - return null; - // return _httpClient.PostAsync("https://oapi.dingtalk.com/robot/send?access_token=33", JsonContent(message)); - } - - private static StringContent JsonContent(object obj) - { - return new StringContent(obj.ToJson(), Encoding.UTF8, "application/json"); - } - - - private static async Task CheckSuccess(HttpResponseMessage res) - { - var content = await res.Content.ReadAsStringAsync(); - - JObject jObject = JsonConvert.DeserializeObject(content); - - if (jObject["errmsg"].ToString() == "ok" && Convert.ToInt32(jObject["errcode"]) != 0) - { - return false; - } - - return true; - } - } - - - /// - /// 此消息类型为固定text - /// - public class TextModel - { - /// - /// 此消息类型为固定text - /// - public string msgtype => "text"; - - /// - /// 消息内容 - /// - public text text { get; set; } - - /// - /// @人 - /// - public atText at { get; set; } - } - - /// - /// 消息内容 - /// - public class text - { - /// - /// 消息内容 - /// - public string content { get; set; } - } - - /// - /// @人 - /// - public class atText - { - /// - /// 被@人的手机号 - /// - public List atMobiles { get; set; } - - /// - /// @所有人时:true,否则为:false - /// - public bool isAtAll { get; set; } = false; - } - - /// - /// 此消息类型为固定markdown - /// - public class MarkDownModel - { - /// - /// 此消息类型为固定markdown - /// - public string msgtype => "markdown"; - - /// - /// 消息内容 - /// - public markdown markdown { get; set; } - - /// - /// @人 - /// - public atMarkdown at { get; set; } - } - - /// - /// 消息内容 - /// - public class markdown - { - /// - /// 标题 - /// - public string title { get; set; } - - /// - /// 消息内容 - /// - public string text { get; set; } - } - - /// - /// @人 - /// - public class atMarkdown - { - /// - /// 被@人的手机号 - /// - public List atMobiles { get; set; } - - /// - /// @所有人时:true,否则为:false - /// - public bool isAtAll { get; set; } = false; - } +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +using Hncore.Infrastructure.Serializer; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Hncore.Infrastructure.Common.DingTalk +{ + public class DingTalkHelper + { + private static HttpClient _httpClient = new HttpClient(new HttpClientHandler() {UseProxy = false}) + {Timeout = TimeSpan.FromMinutes(1)}; + + static DingTalkHelper() + { + _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + } + + public static Task SendMessage(object message) + { + return null; + // return _httpClient.PostAsync("https://oapi.dingtalk.com/robot/send?access_token=33", JsonContent(message)); + } + + private static StringContent JsonContent(object obj) + { + return new StringContent(obj.ToJson(), Encoding.UTF8, "application/json"); + } + + + private static async Task CheckSuccess(HttpResponseMessage res) + { + var content = await res.Content.ReadAsStringAsync(); + + JObject jObject = JsonConvert.DeserializeObject(content); + + if (jObject["errmsg"].ToString() == "ok" && Convert.ToInt32(jObject["errcode"]) != 0) + { + return false; + } + + return true; + } + } + + + /// + /// 此消息类型为固定text + /// + public class TextModel + { + /// + /// 此消息类型为固定text + /// + public string msgtype => "text"; + + /// + /// 消息内容 + /// + public text text { get; set; } + + /// + /// @人 + /// + public atText at { get; set; } + } + + /// + /// 消息内容 + /// + public class text + { + /// + /// 消息内容 + /// + public string content { get; set; } + } + + /// + /// @人 + /// + public class atText + { + /// + /// 被@人的手机号 + /// + public List atMobiles { get; set; } + + /// + /// @所有人时:true,否则为:false + /// + public bool isAtAll { get; set; } = false; + } + + /// + /// 此消息类型为固定markdown + /// + public class MarkDownModel + { + /// + /// 此消息类型为固定markdown + /// + public string msgtype => "markdown"; + + /// + /// 消息内容 + /// + public markdown markdown { get; set; } + + /// + /// @人 + /// + public atMarkdown at { get; set; } + } + + /// + /// 消息内容 + /// + public class markdown + { + /// + /// 标题 + /// + public string title { get; set; } + + /// + /// 消息内容 + /// + public string text { get; set; } + } + + /// + /// @人 + /// + public class atMarkdown + { + /// + /// 被@人的手机号 + /// + public List atMobiles { get; set; } + + /// + /// @所有人时:true,否则为:false + /// + public bool isAtAll { get; set; } = false; + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/EnvironmentVariableHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/EnvironmentVariableHelper.cs index d02b92c..4c108d5 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/EnvironmentVariableHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/EnvironmentVariableHelper.cs @@ -1,14 +1,14 @@ -using System; - -namespace Hncore.Infrastructure.Common -{ - public class EnvironmentVariableHelper - { - /// - /// 当前环境是否为生产模式 - /// - public static bool IsAspNetCoreProduction => Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production"; - - public static string HostName => Environment.GetEnvironmentVariable("HOSTNAME"); - } +using System; + +namespace Hncore.Infrastructure.Common +{ + public class EnvironmentVariableHelper + { + /// + /// 当前环境是否为生产模式 + /// + public static bool IsAspNetCoreProduction => Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production"; + + public static string HostName => Environment.GetEnvironmentVariable("HOSTNAME"); + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/ExcelHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/ExcelHelper.cs index 7678340..fc9c923 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/ExcelHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/ExcelHelper.cs @@ -1,644 +1,644 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using System.Web; -using AngleSharp; -using AngleSharp.Dom; -using Hncore.Infrastructure.Data; -using Hncore.Infrastructure.Extension; -using Microsoft.AspNetCore.Mvc; -using NPOI.HSSF.UserModel; - -namespace Hncore.Infrastructure.Common -{ - public static class ExcelHelper - { - public static async Task GetStreamFromHtml(string html) - { - MemoryStream ms = new MemoryStream(); - - HSSFWorkbook book = new HSSFWorkbook(); - - var context = BrowsingContext.New(Configuration.Default); - - var document = await context.OpenAsync(req => req.Content(html)); - - try - { - var tables = document.GetElementsByTagName("table"); - - foreach (var table in tables) - { - var sheetName = table.GetAttribute("sheetname"); - - var sheet = book.CreateSheet(sheetName); - - var trs = table.GetElementsByTagName("tr"); - - var rowIndex = 0; - - foreach (var tr in trs) - { - var row = sheet.CreateRow(rowIndex); - - var tds = tr.GetElementsByTagName("td"); - - var columnIndex = 0; - - foreach (var td in tds) - { - row.CreateCell(columnIndex).SetCellValue(td.InnerHtml.Trim()); - - columnIndex++; - } - - rowIndex++; - - } - } - - book.Write(ms); - ms.Position = 0; - } - finally - { - document.Close(); - document.Dispose(); - - context.Active.Close(); - context.Active.Dispose(); - - document = null; - context = null; - - book.Clear(); - book.Close(); - book = null; - } - - - return ms; - } - - public static async Task ResponseExcelFromHtml(this ControllerBase controllerBase, string fileName, string html) - { - using (var ms = await GetStreamFromHtml(html)) - { - var bytes = ms.StreamToBytes(); - - var response = controllerBase.HttpContext.Response; - - response.ContentType = "application/octet-stream"; - response.Headers.Add("Content-Disposition", $"attachment; filename={fileName.UrlEncode()}"); - response.Headers.Add("X-Suggested-Filename", fileName.UrlEncode()); - response.Headers.Add("Content-Length", bytes.Length.ToString()); - - await response.Body.WriteAsync(bytes, 0, bytes.Length); - await response.Body.FlushAsync(); - } - } - /// - /// excel二进制文件转二维string结合 - /// - /// - /// - /// - public static List> ReadFromStream(Stream stream, int st = 0) - { - //根据路径通过已存在的excel来创建HSSFWorkbook,即整个excel文档 - HSSFWorkbook workbook; - try - { - workbook = new HSSFWorkbook(stream); - } - catch (Exception ex) - { - LogHelper.Error("ReadFromStream",ex); - throw new BusinessException("文件读取错误!"); - } - List> lis1 = new List>(); - { - //获取excel的第一个sheet - var sheet = workbook.GetSheetAt(st); - if (sheet == null) - throw new BusinessException("该文件内没有包含任何工作簿"); - //获取sheet的首行 - var headerRow = sheet.GetRow(0); - //一行最后一个方格的编号 即总的列数 - int cellCount = headerRow.LastCellNum; - - try - { - for (int i = 0; i <= sheet.LastRowNum; i++) - { - List lis = new List(); - var row = sheet.GetRow(i); - if (row == null) - continue; - for (int j = 0; j < cellCount; j++) - { - var cell = row.GetCell(j); - if (cell == null) - { - lis.Add(""); - continue; - } - try - { - switch (cell.CellType) - { - case NPOI.SS.UserModel.CellType.Unknown: - lis.Add("Unknown"); - break; - case NPOI.SS.UserModel.CellType.Numeric: - if (HSSFDateUtil.IsCellDateFormatted(cell))//对日期格式进行特殊对待 - lis.Add(HSSFDateUtil.GetJavaDate(cell.NumericCellValue).ToString()); - else - lis.Add(cell.NumericCellValue.ToString()); - break; - case NPOI.SS.UserModel.CellType.String: - lis.Add(cell.StringCellValue.ToString()); - break; - case NPOI.SS.UserModel.CellType.Formula: - lis.Add(cell.CellFormula.ToString()); - break; - case NPOI.SS.UserModel.CellType.Blank: - lis.Add(""); - break; - case NPOI.SS.UserModel.CellType.Boolean: - lis.Add(cell.BooleanCellValue.ToString()); - break; - case NPOI.SS.UserModel.CellType.Error: - lis.Add(cell.ErrorCellValue.ToString()); - break; - default: - break; - } - } - catch - { - lis.Add(""); - } - } - - //如果本行所有单元格都是空,就跳过本行 - if (lis.All(item => string.IsNullOrEmpty(item))) - continue; - - lis1.Add(lis); - } - } - catch(Exception ex) - { - LogHelper.Error("ReadFromStream", ex); - throw new BusinessException("文件格式错误!"); - } - } - #region 细节化处理 - lis1 = lis1.Where(s => !s.TrueForAll(f => string.IsNullOrWhiteSpace(f))).ToList();//去除全是空格的空行。 - lis1 = lis1.Select(s => s = s.Select(y => y = y.Trim()).ToList()).ToList();//去除空格 - if (lis1.Count == 1) throw new Exception("Excel中无有效数据!"); - #endregion - return lis1; - } - /// - /// 导出列表到excel - /// 导出到sheet的数据一致 - /// - /// - /// 每一个sheet的数据 - /// 列表的属性和名称值 - /// - public static byte[] ExportListToExcel(List> excelData, List excelTitle) - { - var workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(); - - var entityType = typeof(T); - PropertyInfo[] entityProperties = entityType.GetProperties(); - - if (excelData == null || excelData.Count == 0) - { - return null; - } - try - { - foreach (var item in excelData) - { - #region MyRegion - //var sheet = workbook.CreateSheet(item.SheetName.Replace('/','-')); - //var titleRow = sheet.CreateRow(0); - //for (int i = 0; i < excelTitle.Count; i++) - //{ - // titleRow.CreateCell(i).SetCellValue(excelTitle[i].Title); - //} - //var sheetData = item.Data; - //for (int j = 0; j < sheetData.Count; j++) - //{ - // var dataRow = sheet.CreateRow(j + 1); - // for (int i = 0; i < excelTitle.Count; i++) - // { - // if (excelTitle[i].Property.ToUpper().Equals("ID")) - // { - // var num = j + 1; - // dataRow.CreateCell(i).SetCellValue(num); - // continue; - // } - // var entityProperty = entityProperties.FirstOrDefault(m => m.Name == excelTitle[i].Property); - - // var cellVal = entityProperty?.GetValue(sheetData[j]); - // if (cellVal?.GetType().Name == "DateTime") - // { - // dataRow.CreateCell(i).SetCellValue(((DateTime?)cellVal)?.ToString("yyyy/MM/dd HH:mm:ss")); - // } - // else - // { - // dataRow.CreateCell(i).SetCellValue(cellVal?.ToString()); - // } - // //dataRow.CreateCell(i).SetCellValue(cellVal?.ToString()); - // } - //} - #endregion - CreateSheetData(workbook, item, excelTitle, entityProperties); - } - using (var ms = new MemoryStream()) - { - workbook.Write(ms); - var bytes = ms.ToArray(); - return bytes; - } - } - catch(Exception ex) - { - LogHelper.Error("ExportListToExcel=>" + ex); - - throw ex; - } - finally - { - workbook.Clear(); - workbook.Close(); - workbook = null; - } - } - public static byte[] ExportListToExcel(ExcelData excelData, List excelTitle) - { - var workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(); - - var entityType = typeof(T); - PropertyInfo[] entityProperties = entityType.GetProperties(); - - try - { - #region MyRegion - //var sheet = workbook.CreateSheet(excelData.SheetName.Replace('/', '-')); - //var titleRow = sheet.CreateRow(0); - //for (int i = 0; i < excelTitle.Count; i++) - //{ - // titleRow.CreateCell(i).SetCellValue(excelTitle[i].Title); - //} - //var sheetData = excelData.Data; - //for (int j = 0; j < sheetData.Count; j++) - //{ - // var dataRow = sheet.CreateRow(j + 1); - // for (int i = 0; i < excelTitle.Count; i++) - // { - // var cellVal = entityProperties.FirstOrDefault(m => m.Name == excelTitle[i].Property)?.GetValue(sheetData[j]); - - // if (cellVal?.GetType().Name == "DateTime") - // { - // dataRow.CreateCell(i).SetCellValue(((DateTime?)cellVal)?.ToString("yyyy/MM/dd HH:mm:ss")); - // } - // else - // { - // dataRow.CreateCell(i).SetCellValue(cellVal?.ToString()); - // } - // } - //} - #endregion - CreateSheetData(workbook, excelData, excelTitle, entityProperties); - using (var ms = new MemoryStream()) - { - workbook.Write(ms); - var bytes = ms.ToArray(); - return bytes; - } - } - catch (Exception ex) - { - LogHelper.Error("ExportListToExcel=>" + ex); - - throw ex; - } - finally - { - workbook.Clear(); - workbook.Close(); - workbook = null; - } - } - /// - /// 创建excel表单数据 - /// - /// - /// - /// - /// - /// - private static void CreateSheetData(NPOI.XSSF.UserModel.XSSFWorkbook workbook, - ExcelData excelData, List excelTitle,PropertyInfo[] entityProperties) - { - var sheet = workbook.CreateSheet(excelData.SheetName.Replace('/', '-')); - var titleRow = sheet.CreateRow(0); - for (int i = 0; i < excelTitle.Count; i++) - { - titleRow.CreateCell(i).SetCellValue(excelTitle[i].Title); - } - var sheetData = excelData.Data; - for (int j = 0; j < sheetData.Count; j++) - { - var dataRow = sheet.CreateRow(j + 1); - for (int i = 0; i < excelTitle.Count; i++) - { - var currentTitle = excelTitle[i]; - if (currentTitle.Property.Equals("序号")) - { - var num = j + 1; - dataRow.CreateCell(i).SetCellValue(num); - continue; - } - var cellVal = entityProperties.FirstOrDefault(m => m.Name == currentTitle.Property)?.GetValue(sheetData[j]); - if (currentTitle.Format != null) - { - cellVal = currentTitle.Format(cellVal); - } - if (currentTitle.Expr != null) - { - cellVal = currentTitle.Expr(sheetData[j]); - } - else if (cellVal?.GetType().Name == "DateTime") - { - dataRow.CreateCell(i).SetCellValue(((DateTime?)cellVal)?.ToString("yyyy/MM/dd HH:mm:ss")); - } - dataRow.CreateCell(i).SetCellValue(cellVal?.ToString()); - } - } - } - #region DownloadAsync(下载) - - - /// - /// 下载 - /// - /// 流 - /// 文件名,包含扩展名 - public static async Task DownloadAsync(this ControllerBase controllerBase, Stream stream, string fileName) - { - await DownloadAsync(controllerBase,stream, fileName, Encoding.UTF8); - } - /// - /// 下载 - /// - /// 流 - /// 文件名,包含扩展名 - /// 字符编码 - public static async Task DownloadAsync(this ControllerBase controllerBase, Stream stream, string fileName, Encoding encoding) - { - stream.Seek(0, SeekOrigin.Begin); - var buffer = new byte[stream.Length]; - stream.Read(buffer, 0, buffer.Length); - - await DownloadAsync(controllerBase, buffer, fileName, encoding); - } - /// - /// 下载 - /// - /// 字节流 - /// 文件名,包含扩展名 - public static async Task DownloadAsync(this ControllerBase controllerBase, byte[] bytes, string fileName) - { - await DownloadAsync(controllerBase,bytes, fileName, Encoding.UTF8); - } - - /// - /// 下载 - /// - /// 字节流 - /// 文件名,包含扩展名 - /// 字符编码 - public static async Task DownloadAsync(this ControllerBase controllerBase,byte[] bytes, string fileName, Encoding encoding) - { - var response = controllerBase.HttpContext.Response; - if (bytes == null || bytes.Length == 0) - return; - fileName = fileName.Replace(" ", ""); - fileName = HttpUtility.UrlEncode(fileName, encoding); - response.ContentType = "application/octet-stream"; - response.Headers.Add("Content-Disposition", $"attachment; filename={fileName}"); - response.Headers.Add("Content-Length", bytes.Length.ToString()); - response.Headers.Add("X-Suggested-Filename", fileName); - await response.Body.WriteAsync(bytes, 0, bytes.Length); - await response.Body.FlushAsync(); - } - - #endregion - } - - public class ExcelTitle - { - /// - /// 导出数据对应的 属性字段名 - /// - public string Property { get; set; } - /// - /// excel 的title - /// - public string Title { get; set; } - - public Func Format { get; set; } - public Func Expr { get; set; } - } - public class ExcelData - { - /// - /// 导出数据对应的 属性字段名 - /// - public string SheetName { get; set; } - /// - /// excel 的title - /// - public List Data { get; set; } - } - #region Excel导入验证 - /// - /// Excel导入验证 - /// - public static class ValidForExcel - { - - /// - /// 解析字符串到int32、double、datetime... - /// - /// - /// - /// - /// - /// - /// 自然数0,1,2,3... - /// - public static T ValidParseStr(string str,string message = "数据", bool isCanNullOrEmpty = true, bool isPositiveOrZero = true) - { - var val = default(T); - if (string.IsNullOrEmpty(str)) - { - if (isCanNullOrEmpty) - { - return default(T); - } - else - { - throw new Exception($"{message}不能为空"); - } - } - else - { - if (typeof(T).Name == typeof(int).Name || typeof(T).FullName == typeof(int?).FullName) - { - if (int.TryParse(str, out var valueInt)) - { - if (isPositiveOrZero && valueInt < 0) - { - goto error; - } - return (T)Convert.ChangeType(valueInt, TypeCode.Int32); - } - else - { - goto error; - } - } - if (typeof(T).Name == typeof(Decimal).Name || typeof(T).FullName == typeof(Decimal?).FullName) - { - if (Decimal.TryParse(str, out var valueInt)) - { - if (isPositiveOrZero && valueInt < 0) - { - goto error; - } - return (T)Convert.ChangeType(valueInt, TypeCode.Decimal); - } - else - { - goto error; - } - } - if (typeof(T).Name == typeof(Double).Name || typeof(T).FullName == typeof(Double?).FullName) - { - if (Double.TryParse(str, out var valueInt)) - { - if (isPositiveOrZero && valueInt < 0) - { - goto error; - } - return (T)Convert.ChangeType(valueInt, TypeCode.Double); - } - else - { - goto error; - } - } - if (typeof(T).Name == typeof(Single).Name || typeof(T).FullName == typeof(Single?).FullName) - { - if (Single.TryParse(str, out var valueInt)) - { - if (isPositiveOrZero && valueInt < 0) - { - goto error; - } - return (T)Convert.ChangeType(valueInt, TypeCode.Single); - } - else - { - goto error; - } - } - if (typeof(T).Name == typeof(DateTime).Name || typeof(T).FullName == typeof(DateTime?).FullName) - { - if (DateTime.TryParse(str, out var valueInt)) - { - return (T)Convert.ChangeType(valueInt, TypeCode.DateTime); - } - else - { - goto error; - } - } - } - return val; - error: throw new Exception($"{message}的值有误"); - } - - /// - /// 提供正则、提示信息,返回验证结果 - /// - /// - /// - /// - /// - /// - /// - public static string ValidByPattern(string str,string pattern, string message = "数据", bool isCanNullOrEmpty = true) - { - if (string.IsNullOrEmpty(str)) - { - if (isCanNullOrEmpty) - { - return str; - } - else - { - throw new BusinessException($"{message}不能为空"); - } - } - else - { - if (!Regex.IsMatch(str, pattern)) throw new BusinessException($"{message}输入有误"); - return str; - } - } - /// - /// 根据枚举判断 - /// - /// - /// - /// - /// - /// - public static int? ValidByEnum(string str, string message, bool isCanNullOrEmpty = true) //where T:Enum - { - - if (string.IsNullOrEmpty(str)) - { - if (isCanNullOrEmpty) - { - return null; - } - else - { - throw new BusinessException($"{message}不能为空"); - } - } - else - { - var value = EnumExtension.EnumToList().Find(s => s.Name == str)?.Value; - if (value == null) throw new BusinessException($"未知的数据:{str}"); - return Convert.ToInt32(value); - } - } - } - #endregion +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Web; +using AngleSharp; +using AngleSharp.Dom; +using Hncore.Infrastructure.Data; +using Hncore.Infrastructure.Extension; +using Microsoft.AspNetCore.Mvc; +using NPOI.HSSF.UserModel; + +namespace Hncore.Infrastructure.Common +{ + public static class ExcelHelper + { + public static async Task GetStreamFromHtml(string html) + { + MemoryStream ms = new MemoryStream(); + + HSSFWorkbook book = new HSSFWorkbook(); + + var context = BrowsingContext.New(Configuration.Default); + + var document = await context.OpenAsync(req => req.Content(html)); + + try + { + var tables = document.GetElementsByTagName("table"); + + foreach (var table in tables) + { + var sheetName = table.GetAttribute("sheetname"); + + var sheet = book.CreateSheet(sheetName); + + var trs = table.GetElementsByTagName("tr"); + + var rowIndex = 0; + + foreach (var tr in trs) + { + var row = sheet.CreateRow(rowIndex); + + var tds = tr.GetElementsByTagName("td"); + + var columnIndex = 0; + + foreach (var td in tds) + { + row.CreateCell(columnIndex).SetCellValue(td.InnerHtml.Trim()); + + columnIndex++; + } + + rowIndex++; + + } + } + + book.Write(ms); + ms.Position = 0; + } + finally + { + document.Close(); + document.Dispose(); + + context.Active.Close(); + context.Active.Dispose(); + + document = null; + context = null; + + book.Clear(); + book.Close(); + book = null; + } + + + return ms; + } + + public static async Task ResponseExcelFromHtml(this ControllerBase controllerBase, string fileName, string html) + { + using (var ms = await GetStreamFromHtml(html)) + { + var bytes = ms.StreamToBytes(); + + var response = controllerBase.HttpContext.Response; + + response.ContentType = "application/octet-stream"; + response.Headers.Add("Content-Disposition", $"attachment; filename={fileName.UrlEncode()}"); + response.Headers.Add("X-Suggested-Filename", fileName.UrlEncode()); + response.Headers.Add("Content-Length", bytes.Length.ToString()); + + await response.Body.WriteAsync(bytes, 0, bytes.Length); + await response.Body.FlushAsync(); + } + } + /// + /// excel二进制文件转二维string结合 + /// + /// + /// + /// + public static List> ReadFromStream(Stream stream, int st = 0) + { + //根据路径通过已存在的excel来创建HSSFWorkbook,即整个excel文档 + HSSFWorkbook workbook; + try + { + workbook = new HSSFWorkbook(stream); + } + catch (Exception ex) + { + LogHelper.Error("ReadFromStream",ex); + throw new BusinessException("文件读取错误!"); + } + List> lis1 = new List>(); + { + //获取excel的第一个sheet + var sheet = workbook.GetSheetAt(st); + if (sheet == null) + throw new BusinessException("该文件内没有包含任何工作簿"); + //获取sheet的首行 + var headerRow = sheet.GetRow(0); + //一行最后一个方格的编号 即总的列数 + int cellCount = headerRow.LastCellNum; + + try + { + for (int i = 0; i <= sheet.LastRowNum; i++) + { + List lis = new List(); + var row = sheet.GetRow(i); + if (row == null) + continue; + for (int j = 0; j < cellCount; j++) + { + var cell = row.GetCell(j); + if (cell == null) + { + lis.Add(""); + continue; + } + try + { + switch (cell.CellType) + { + case NPOI.SS.UserModel.CellType.Unknown: + lis.Add("Unknown"); + break; + case NPOI.SS.UserModel.CellType.Numeric: + if (HSSFDateUtil.IsCellDateFormatted(cell))//对日期格式进行特殊对待 + lis.Add(HSSFDateUtil.GetJavaDate(cell.NumericCellValue).ToString()); + else + lis.Add(cell.NumericCellValue.ToString()); + break; + case NPOI.SS.UserModel.CellType.String: + lis.Add(cell.StringCellValue.ToString()); + break; + case NPOI.SS.UserModel.CellType.Formula: + lis.Add(cell.CellFormula.ToString()); + break; + case NPOI.SS.UserModel.CellType.Blank: + lis.Add(""); + break; + case NPOI.SS.UserModel.CellType.Boolean: + lis.Add(cell.BooleanCellValue.ToString()); + break; + case NPOI.SS.UserModel.CellType.Error: + lis.Add(cell.ErrorCellValue.ToString()); + break; + default: + break; + } + } + catch + { + lis.Add(""); + } + } + + //如果本行所有单元格都是空,就跳过本行 + if (lis.All(item => string.IsNullOrEmpty(item))) + continue; + + lis1.Add(lis); + } + } + catch(Exception ex) + { + LogHelper.Error("ReadFromStream", ex); + throw new BusinessException("文件格式错误!"); + } + } + #region 细节化处理 + lis1 = lis1.Where(s => !s.TrueForAll(f => string.IsNullOrWhiteSpace(f))).ToList();//去除全是空格的空行。 + lis1 = lis1.Select(s => s = s.Select(y => y = y.Trim()).ToList()).ToList();//去除空格 + if (lis1.Count == 1) throw new Exception("Excel中无有效数据!"); + #endregion + return lis1; + } + /// + /// 导出列表到excel + /// 导出到sheet的数据一致 + /// + /// + /// 每一个sheet的数据 + /// 列表的属性和名称值 + /// + public static byte[] ExportListToExcel(List> excelData, List excelTitle) + { + var workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(); + + var entityType = typeof(T); + PropertyInfo[] entityProperties = entityType.GetProperties(); + + if (excelData == null || excelData.Count == 0) + { + return null; + } + try + { + foreach (var item in excelData) + { + #region MyRegion + //var sheet = workbook.CreateSheet(item.SheetName.Replace('/','-')); + //var titleRow = sheet.CreateRow(0); + //for (int i = 0; i < excelTitle.Count; i++) + //{ + // titleRow.CreateCell(i).SetCellValue(excelTitle[i].Title); + //} + //var sheetData = item.Data; + //for (int j = 0; j < sheetData.Count; j++) + //{ + // var dataRow = sheet.CreateRow(j + 1); + // for (int i = 0; i < excelTitle.Count; i++) + // { + // if (excelTitle[i].Property.ToUpper().Equals("ID")) + // { + // var num = j + 1; + // dataRow.CreateCell(i).SetCellValue(num); + // continue; + // } + // var entityProperty = entityProperties.FirstOrDefault(m => m.Name == excelTitle[i].Property); + + // var cellVal = entityProperty?.GetValue(sheetData[j]); + // if (cellVal?.GetType().Name == "DateTime") + // { + // dataRow.CreateCell(i).SetCellValue(((DateTime?)cellVal)?.ToString("yyyy/MM/dd HH:mm:ss")); + // } + // else + // { + // dataRow.CreateCell(i).SetCellValue(cellVal?.ToString()); + // } + // //dataRow.CreateCell(i).SetCellValue(cellVal?.ToString()); + // } + //} + #endregion + CreateSheetData(workbook, item, excelTitle, entityProperties); + } + using (var ms = new MemoryStream()) + { + workbook.Write(ms); + var bytes = ms.ToArray(); + return bytes; + } + } + catch(Exception ex) + { + LogHelper.Error("ExportListToExcel=>" + ex); + + throw ex; + } + finally + { + workbook.Clear(); + workbook.Close(); + workbook = null; + } + } + public static byte[] ExportListToExcel(ExcelData excelData, List excelTitle) + { + var workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(); + + var entityType = typeof(T); + PropertyInfo[] entityProperties = entityType.GetProperties(); + + try + { + #region MyRegion + //var sheet = workbook.CreateSheet(excelData.SheetName.Replace('/', '-')); + //var titleRow = sheet.CreateRow(0); + //for (int i = 0; i < excelTitle.Count; i++) + //{ + // titleRow.CreateCell(i).SetCellValue(excelTitle[i].Title); + //} + //var sheetData = excelData.Data; + //for (int j = 0; j < sheetData.Count; j++) + //{ + // var dataRow = sheet.CreateRow(j + 1); + // for (int i = 0; i < excelTitle.Count; i++) + // { + // var cellVal = entityProperties.FirstOrDefault(m => m.Name == excelTitle[i].Property)?.GetValue(sheetData[j]); + + // if (cellVal?.GetType().Name == "DateTime") + // { + // dataRow.CreateCell(i).SetCellValue(((DateTime?)cellVal)?.ToString("yyyy/MM/dd HH:mm:ss")); + // } + // else + // { + // dataRow.CreateCell(i).SetCellValue(cellVal?.ToString()); + // } + // } + //} + #endregion + CreateSheetData(workbook, excelData, excelTitle, entityProperties); + using (var ms = new MemoryStream()) + { + workbook.Write(ms); + var bytes = ms.ToArray(); + return bytes; + } + } + catch (Exception ex) + { + LogHelper.Error("ExportListToExcel=>" + ex); + + throw ex; + } + finally + { + workbook.Clear(); + workbook.Close(); + workbook = null; + } + } + /// + /// 创建excel表单数据 + /// + /// + /// + /// + /// + /// + private static void CreateSheetData(NPOI.XSSF.UserModel.XSSFWorkbook workbook, + ExcelData excelData, List excelTitle,PropertyInfo[] entityProperties) + { + var sheet = workbook.CreateSheet(excelData.SheetName.Replace('/', '-')); + var titleRow = sheet.CreateRow(0); + for (int i = 0; i < excelTitle.Count; i++) + { + titleRow.CreateCell(i).SetCellValue(excelTitle[i].Title); + } + var sheetData = excelData.Data; + for (int j = 0; j < sheetData.Count; j++) + { + var dataRow = sheet.CreateRow(j + 1); + for (int i = 0; i < excelTitle.Count; i++) + { + var currentTitle = excelTitle[i]; + if (currentTitle.Property.Equals("序号")) + { + var num = j + 1; + dataRow.CreateCell(i).SetCellValue(num); + continue; + } + var cellVal = entityProperties.FirstOrDefault(m => m.Name == currentTitle.Property)?.GetValue(sheetData[j]); + if (currentTitle.Format != null) + { + cellVal = currentTitle.Format(cellVal); + } + if (currentTitle.Expr != null) + { + cellVal = currentTitle.Expr(sheetData[j]); + } + else if (cellVal?.GetType().Name == "DateTime") + { + dataRow.CreateCell(i).SetCellValue(((DateTime?)cellVal)?.ToString("yyyy/MM/dd HH:mm:ss")); + } + dataRow.CreateCell(i).SetCellValue(cellVal?.ToString()); + } + } + } + #region DownloadAsync(下载) + + + /// + /// 下载 + /// + /// 流 + /// 文件名,包含扩展名 + public static async Task DownloadAsync(this ControllerBase controllerBase, Stream stream, string fileName) + { + await DownloadAsync(controllerBase,stream, fileName, Encoding.UTF8); + } + /// + /// 下载 + /// + /// 流 + /// 文件名,包含扩展名 + /// 字符编码 + public static async Task DownloadAsync(this ControllerBase controllerBase, Stream stream, string fileName, Encoding encoding) + { + stream.Seek(0, SeekOrigin.Begin); + var buffer = new byte[stream.Length]; + stream.Read(buffer, 0, buffer.Length); + + await DownloadAsync(controllerBase, buffer, fileName, encoding); + } + /// + /// 下载 + /// + /// 字节流 + /// 文件名,包含扩展名 + public static async Task DownloadAsync(this ControllerBase controllerBase, byte[] bytes, string fileName) + { + await DownloadAsync(controllerBase,bytes, fileName, Encoding.UTF8); + } + + /// + /// 下载 + /// + /// 字节流 + /// 文件名,包含扩展名 + /// 字符编码 + public static async Task DownloadAsync(this ControllerBase controllerBase,byte[] bytes, string fileName, Encoding encoding) + { + var response = controllerBase.HttpContext.Response; + if (bytes == null || bytes.Length == 0) + return; + fileName = fileName.Replace(" ", ""); + fileName = HttpUtility.UrlEncode(fileName, encoding); + response.ContentType = "application/octet-stream"; + response.Headers.Add("Content-Disposition", $"attachment; filename={fileName}"); + response.Headers.Add("Content-Length", bytes.Length.ToString()); + response.Headers.Add("X-Suggested-Filename", fileName); + await response.Body.WriteAsync(bytes, 0, bytes.Length); + await response.Body.FlushAsync(); + } + + #endregion + } + + public class ExcelTitle + { + /// + /// 导出数据对应的 属性字段名 + /// + public string Property { get; set; } + /// + /// excel 的title + /// + public string Title { get; set; } + + public Func Format { get; set; } + public Func Expr { get; set; } + } + public class ExcelData + { + /// + /// 导出数据对应的 属性字段名 + /// + public string SheetName { get; set; } + /// + /// excel 的title + /// + public List Data { get; set; } + } + #region Excel导入验证 + /// + /// Excel导入验证 + /// + public static class ValidForExcel + { + + /// + /// 解析字符串到int32、double、datetime... + /// + /// + /// + /// + /// + /// + /// 自然数0,1,2,3... + /// + public static T ValidParseStr(string str,string message = "数据", bool isCanNullOrEmpty = true, bool isPositiveOrZero = true) + { + var val = default(T); + if (string.IsNullOrEmpty(str)) + { + if (isCanNullOrEmpty) + { + return default(T); + } + else + { + throw new Exception($"{message}不能为空"); + } + } + else + { + if (typeof(T).Name == typeof(int).Name || typeof(T).FullName == typeof(int?).FullName) + { + if (int.TryParse(str, out var valueInt)) + { + if (isPositiveOrZero && valueInt < 0) + { + goto error; + } + return (T)Convert.ChangeType(valueInt, TypeCode.Int32); + } + else + { + goto error; + } + } + if (typeof(T).Name == typeof(Decimal).Name || typeof(T).FullName == typeof(Decimal?).FullName) + { + if (Decimal.TryParse(str, out var valueInt)) + { + if (isPositiveOrZero && valueInt < 0) + { + goto error; + } + return (T)Convert.ChangeType(valueInt, TypeCode.Decimal); + } + else + { + goto error; + } + } + if (typeof(T).Name == typeof(Double).Name || typeof(T).FullName == typeof(Double?).FullName) + { + if (Double.TryParse(str, out var valueInt)) + { + if (isPositiveOrZero && valueInt < 0) + { + goto error; + } + return (T)Convert.ChangeType(valueInt, TypeCode.Double); + } + else + { + goto error; + } + } + if (typeof(T).Name == typeof(Single).Name || typeof(T).FullName == typeof(Single?).FullName) + { + if (Single.TryParse(str, out var valueInt)) + { + if (isPositiveOrZero && valueInt < 0) + { + goto error; + } + return (T)Convert.ChangeType(valueInt, TypeCode.Single); + } + else + { + goto error; + } + } + if (typeof(T).Name == typeof(DateTime).Name || typeof(T).FullName == typeof(DateTime?).FullName) + { + if (DateTime.TryParse(str, out var valueInt)) + { + return (T)Convert.ChangeType(valueInt, TypeCode.DateTime); + } + else + { + goto error; + } + } + } + return val; + error: throw new Exception($"{message}的值有误"); + } + + /// + /// 提供正则、提示信息,返回验证结果 + /// + /// + /// + /// + /// + /// + /// + public static string ValidByPattern(string str,string pattern, string message = "数据", bool isCanNullOrEmpty = true) + { + if (string.IsNullOrEmpty(str)) + { + if (isCanNullOrEmpty) + { + return str; + } + else + { + throw new BusinessException($"{message}不能为空"); + } + } + else + { + if (!Regex.IsMatch(str, pattern)) throw new BusinessException($"{message}输入有误"); + return str; + } + } + /// + /// 根据枚举判断 + /// + /// + /// + /// + /// + /// + public static int? ValidByEnum(string str, string message, bool isCanNullOrEmpty = true) //where T:Enum + { + + if (string.IsNullOrEmpty(str)) + { + if (isCanNullOrEmpty) + { + return null; + } + else + { + throw new BusinessException($"{message}不能为空"); + } + } + else + { + var value = EnumExtension.EnumToList().Find(s => s.Name == str)?.Value; + if (value == null) throw new BusinessException($"未知的数据:{str}"); + return Convert.ToInt32(value); + } + } + } + #endregion } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/HttpHelp.cs b/Infrastructure/Hncore.Infrastructure/Common/HttpHelp.cs index 1aae178..2bf7a81 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/HttpHelp.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/HttpHelp.cs @@ -1,69 +1,69 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Text; - -namespace Hncore.Infrastructure.Common -{ - public static class HttpHelp - { - /// - /// get请求 - /// - /// - /// - public static string HttpGet(string url) - { - string result = string.Empty; - try - { - HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url); - wbRequest.Method = "GET"; - HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse(); - using (Stream responseStream = wbResponse.GetResponseStream()) - { - using (StreamReader sReader = new StreamReader(responseStream)) - { - result = sReader.ReadToEnd(); - } - } - } - catch/* (Exception ex) 此处暂时屏蔽掉了,要不然编译光弹出变量未使用的警告,谁用得着再打开*/ - { - - } - return result; - } - /// - /// get 请求,带token - /// - /// - /// - /// - public static string HttpGet(string token,string url) - { - string result = string.Empty; - try - { - HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url); - wbRequest.Headers.Add("token", token); - wbRequest.Method = "GET"; - HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse(); - using (Stream responseStream = wbResponse.GetResponseStream()) - { - using (StreamReader sReader = new StreamReader(responseStream)) - { - result = sReader.ReadToEnd(); - } - } - } - catch/* (Exception ex) 此处暂时屏蔽掉了,要不然编译光弹出变量未使用的警告,谁用得着再打开*/ - { - - } - return result; - } - - } -} +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Text; + +namespace Hncore.Infrastructure.Common +{ + public static class HttpHelp + { + /// + /// get请求 + /// + /// + /// + public static string HttpGet(string url) + { + string result = string.Empty; + try + { + HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url); + wbRequest.Method = "GET"; + HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse(); + using (Stream responseStream = wbResponse.GetResponseStream()) + { + using (StreamReader sReader = new StreamReader(responseStream)) + { + result = sReader.ReadToEnd(); + } + } + } + catch/* (Exception ex) 此处暂时屏蔽掉了,要不然编译光弹出变量未使用的警告,谁用得着再打开*/ + { + + } + return result; + } + /// + /// get 请求,带token + /// + /// + /// + /// + public static string HttpGet(string token,string url) + { + string result = string.Empty; + try + { + HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url); + wbRequest.Headers.Add("token", token); + wbRequest.Method = "GET"; + HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse(); + using (Stream responseStream = wbResponse.GetResponseStream()) + { + using (StreamReader sReader = new StreamReader(responseStream)) + { + result = sReader.ReadToEnd(); + } + } + } + catch/* (Exception ex) 此处暂时屏蔽掉了,要不然编译光弹出变量未使用的警告,谁用得着再打开*/ + { + + } + return result; + } + + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Common/ImageCloudHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/ImageCloudHelper.cs index f205c28..a4d62af 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/ImageCloudHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/ImageCloudHelper.cs @@ -1,85 +1,85 @@ -using System; -using System.IO; -using Qiniu.Storage; -using Qiniu.Util; - -namespace Hncore.Infrastructure.Common -{ - public class ImageCloudHelper - { - /// - /// - /// - /// - /// 图片地址 - public static string UploadImage(Stream stream, string prefix) - { - //todo - return ""; - Mac mac = new Mac("3bmkJLD-inSGpQnLr_9UlommFT81B5L0ryesJLhS", "X22vza-l53jcZyi_fmaex88R065_Ip2_3j5Im0Se"); - - string bucket = "property"; - - // 上传策略,参见 - // https://developer.qiniu.com/kodo/manual/put-policy - PutPolicy putPolicy = new PutPolicy(); - // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" - // putPolicy.Scope = bucket + ":" + saveKey; - putPolicy.Scope = bucket; - // 上传策略有效期(对应于生成的凭证的有效期) - putPolicy.SetExpires(3600); - - string jstr = putPolicy.ToJsonString(); - string token = Auth.CreateUploadToken(mac, jstr); - - FormUploader fu = new FormUploader(new Config() - { - Zone = Zone.ZONE_CN_East - }); - - - string fileName = prefix + Guid.NewGuid() + ".jpg"; - - var result = fu.UploadStream(stream, fileName, token, null); - - if (result.Code == 200) - { - return "http://propertyimages.etor.vip/" + fileName; - } - - - return null; - } - - public static string UploadImage(string imageBase64, string prefix) - { - byte[] imageByte = Convert.FromBase64String(imageBase64); - - var stream = new MemoryStream(imageByte); - - return UploadImage(stream, prefix); - } - - public static string GetToken(int expireInSeconds=3600) - { - Mac mac = new Mac("3bmkJLD-inSGpQnLr_9UlommFT81B5L0ryesJLhS", "X22vza-l53jcZyi_fmaex88R065_Ip2_3j5Im0Se"); - - string bucket = "property"; - - // 上传策略,参见 - // https://developer.qiniu.com/kodo/manual/put-policy - PutPolicy putPolicy = new PutPolicy(); - // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" - // putPolicy.Scope = bucket + ":" + saveKey; - putPolicy.Scope = bucket; - // 上传策略有效期(对应于生成的凭证的有效期) - putPolicy.SetExpires(expireInSeconds); - putPolicy.ReturnBody = "{\"key\":$(key),\"hash\":$(etag),\"mimeType\":$(mimeType),\"fname\":$(fname),\"fsize\":$(fsize),\"avinfo\":$(avinfo),\"ext\":$(ext),\"imageInfo\":$(imageInfo)}"; - - string jstr = putPolicy.ToJsonString(); - string token = Auth.CreateUploadToken(mac, jstr); - - return token; - } - } +using System; +using System.IO; +using Qiniu.Storage; +using Qiniu.Util; + +namespace Hncore.Infrastructure.Common +{ + public class ImageCloudHelper + { + /// + /// + /// + /// + /// 图片地址 + public static string UploadImage(Stream stream, string prefix) + { + //todo + return ""; + Mac mac = new Mac("3bmkJLD-inSGpQnLr_9UlommFT81B5L0ryesJLhS", "X22vza-l53jcZyi_fmaex88R065_Ip2_3j5Im0Se"); + + string bucket = "property"; + + // 上传策略,参见 + // https://developer.qiniu.com/kodo/manual/put-policy + PutPolicy putPolicy = new PutPolicy(); + // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" + // putPolicy.Scope = bucket + ":" + saveKey; + putPolicy.Scope = bucket; + // 上传策略有效期(对应于生成的凭证的有效期) + putPolicy.SetExpires(3600); + + string jstr = putPolicy.ToJsonString(); + string token = Auth.CreateUploadToken(mac, jstr); + + FormUploader fu = new FormUploader(new Config() + { + Zone = Zone.ZONE_CN_East + }); + + + string fileName = prefix + Guid.NewGuid() + ".jpg"; + + var result = fu.UploadStream(stream, fileName, token, null); + + if (result.Code == 200) + { + return "http://propertyimages.etor.vip/" + fileName; + } + + + return null; + } + + public static string UploadImage(string imageBase64, string prefix) + { + byte[] imageByte = Convert.FromBase64String(imageBase64); + + var stream = new MemoryStream(imageByte); + + return UploadImage(stream, prefix); + } + + public static string GetToken(int expireInSeconds=3600) + { + Mac mac = new Mac("3bmkJLD-inSGpQnLr_9UlommFT81B5L0ryesJLhS", "X22vza-l53jcZyi_fmaex88R065_Ip2_3j5Im0Se"); + + string bucket = "property"; + + // 上传策略,参见 + // https://developer.qiniu.com/kodo/manual/put-policy + PutPolicy putPolicy = new PutPolicy(); + // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" + // putPolicy.Scope = bucket + ":" + saveKey; + putPolicy.Scope = bucket; + // 上传策略有效期(对应于生成的凭证的有效期) + putPolicy.SetExpires(expireInSeconds); + putPolicy.ReturnBody = "{\"key\":$(key),\"hash\":$(etag),\"mimeType\":$(mimeType),\"fname\":$(fname),\"fsize\":$(fsize),\"avinfo\":$(avinfo),\"ext\":$(ext),\"imageInfo\":$(imageInfo)}"; + + string jstr = putPolicy.ToJsonString(); + string token = Auth.CreateUploadToken(mac, jstr); + + return token; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/IoHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/IoHelper.cs index 4042085..a1a6014 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/IoHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/IoHelper.cs @@ -1,40 +1,40 @@ -using System.IO; - -namespace Hncore.Infrastructure.Common -{ - /// - /// - /// - public static class IoHelper - { - #region 数据流转字节数组 - - /// - /// 数据流转字节数组 - /// - /// - /// - public static byte[] StreamToBytes(this Stream stream) - { - byte[] bytes = new byte[stream.Length]; - stream.Read(bytes, 0, bytes.Length); - // 设置当前流的位置为流的开始 - stream.Seek(0, SeekOrigin.Begin); - - return bytes; - } - - #endregion - - #region 将 byte[] 转成 Stream - - public static Stream BytesToStream(this byte[] bytes) - - { - Stream stream = new MemoryStream(bytes); - return stream; - } - - #endregion - } +using System.IO; + +namespace Hncore.Infrastructure.Common +{ + /// + /// + /// + public static class IoHelper + { + #region 数据流转字节数组 + + /// + /// 数据流转字节数组 + /// + /// + /// + public static byte[] StreamToBytes(this Stream stream) + { + byte[] bytes = new byte[stream.Length]; + stream.Read(bytes, 0, bytes.Length); + // 设置当前流的位置为流的开始 + stream.Seek(0, SeekOrigin.Begin); + + return bytes; + } + + #endregion + + #region 将 byte[] 转成 Stream + + public static Stream BytesToStream(this byte[] bytes) + + { + Stream stream = new MemoryStream(bytes); + return stream; + } + + #endregion + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/ListHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/ListHelper.cs index f6d2fd6..27c7f42 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/ListHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/ListHelper.cs @@ -1,138 +1,138 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Reflection; - -namespace Hncore.Infrastructure.Common -{ - public static class ListHelper - { - #region 字符串转化为泛型集合 - - /// - /// 字符串转化为泛型集合 - /// - /// 字符串 - /// 要分割的字符 - /// - public static List StrToList(string str, char splitstr) - { - List list = new List(); - if (string.IsNullOrEmpty(str)) - { - return list; - } - if (!str.Contains(splitstr)) - { - list.Add((T)Convert.ChangeType(str, typeof(T))); - return list; - } - else - { - string[] strarray = str.Split(splitstr); - - foreach (string s in strarray) - { - if (s != "") - list.Add((T)Convert.ChangeType(s, typeof(T))); - } - return list; - } - } - - /// - /// 字符串转化为泛型集合 - /// - /// 字符串 - /// - public static List StrToList(string str) - { - return StrToList(str, ','); - } - - #endregion - - public static string ListToStr(List list, string splitstr=",") - { - string str = ""; - - list.ForEach(t => - { - str += t + splitstr; - }); - - if (str.EndsWith(splitstr)) - { - str = str.Substring(0, str.Length - splitstr.Length); - } - - return str; - } - - #region 转换几个中所有元素的类型 - - /// - /// 转换几个中所有元素的类型 - /// - /// - /// - /// - public static List ConvertListType(List list) - { - if (list == null) - { - return null; - } - List newlist = new List(); - foreach (T t in list) - { - object to = new object(); - if (typeof(To).Name == "Guid") - { - to = Guid.Parse(t.ToString()); - } - else - { - to = Convert.ChangeType(t, typeof(To)); - } - newlist.Add((To)to); - } - return newlist; - } - - #endregion - - #region 转化一个DataTable - - /// - /// 转化一个DataTable - /// - /// - /// - /// - public static DataTable ToDataTable(IEnumerable list) - { - //创建属性的集合 - List pList = new List(); - //获得反射的入口 - Type type = typeof(T); - DataTable dt = new DataTable(); - //把所有的public属性加入到集合 并添加DataTable的列 - Array.ForEach(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); }); - foreach (var item in list) - { - //创建一个DataRow实例 - DataRow row = dt.NewRow(); - //给row 赋值 - pList.ForEach(p => row[p.Name] = p.GetValue(item, null)); - //加入到DataTable - dt.Rows.Add(row); - } - return dt; - } - - #endregion - - } -} +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Reflection; + +namespace Hncore.Infrastructure.Common +{ + public static class ListHelper + { + #region 字符串转化为泛型集合 + + /// + /// 字符串转化为泛型集合 + /// + /// 字符串 + /// 要分割的字符 + /// + public static List StrToList(string str, char splitstr) + { + List list = new List(); + if (string.IsNullOrEmpty(str)) + { + return list; + } + if (!str.Contains(splitstr)) + { + list.Add((T)Convert.ChangeType(str, typeof(T))); + return list; + } + else + { + string[] strarray = str.Split(splitstr); + + foreach (string s in strarray) + { + if (s != "") + list.Add((T)Convert.ChangeType(s, typeof(T))); + } + return list; + } + } + + /// + /// 字符串转化为泛型集合 + /// + /// 字符串 + /// + public static List StrToList(string str) + { + return StrToList(str, ','); + } + + #endregion + + public static string ListToStr(List list, string splitstr=",") + { + string str = ""; + + list.ForEach(t => + { + str += t + splitstr; + }); + + if (str.EndsWith(splitstr)) + { + str = str.Substring(0, str.Length - splitstr.Length); + } + + return str; + } + + #region 转换几个中所有元素的类型 + + /// + /// 转换几个中所有元素的类型 + /// + /// + /// + /// + public static List ConvertListType(List list) + { + if (list == null) + { + return null; + } + List newlist = new List(); + foreach (T t in list) + { + object to = new object(); + if (typeof(To).Name == "Guid") + { + to = Guid.Parse(t.ToString()); + } + else + { + to = Convert.ChangeType(t, typeof(To)); + } + newlist.Add((To)to); + } + return newlist; + } + + #endregion + + #region 转化一个DataTable + + /// + /// 转化一个DataTable + /// + /// + /// + /// + public static DataTable ToDataTable(IEnumerable list) + { + //创建属性的集合 + List pList = new List(); + //获得反射的入口 + Type type = typeof(T); + DataTable dt = new DataTable(); + //把所有的public属性加入到集合 并添加DataTable的列 + Array.ForEach(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); }); + foreach (var item in list) + { + //创建一个DataRow实例 + DataRow row = dt.NewRow(); + //给row 赋值 + pList.ForEach(p => row[p.Name] = p.GetValue(item, null)); + //加入到DataTable + dt.Rows.Add(row); + } + return dt; + } + + #endregion + + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Common/LogHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/LogHelper.cs index d1f098e..0870dcb 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/LogHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/LogHelper.cs @@ -1,59 +1,59 @@ -using System; -using NLog; - -namespace Hncore.Infrastructure.Common -{ - public class LogHelper - { - private static readonly Logger Log = LogManager.GetLogger("UserLog"); - private static string assName = AppDomain.CurrentDomain.FriendlyName; - - private static string FormatMsg(string title, object msg) - { - return "Assembly:" + assName + "\r\nTitle : " + title + "\r\nMessage : " + msg + "\r\n"; - } - - public static void Error(string title, object msg = null) - { - Log?.Error(FormatMsg(title, msg)); - - Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); - } - - public static void Debug(string title, object msg = null) - { - Log?.Debug(FormatMsg(title, msg)); - - Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); - } - - public static void Info(string title, object msg = null) - { - Log?.Info(FormatMsg(title, msg)); - - Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); - } - - public static void Warn(string title, object msg = null) - { - Log?.Warn(FormatMsg(title, msg)); - - Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); - } - - public static void Trace(string title, object msg = null) - { - Log?.Trace(FormatMsg(title, msg)); - - Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); - } - - public static void Fatal(string title, object msg = null) - { - Log?.Fatal(FormatMsg(title, msg)); - - Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); - } - } - +using System; +using NLog; + +namespace Hncore.Infrastructure.Common +{ + public class LogHelper + { + private static readonly Logger Log = LogManager.GetLogger("UserLog"); + private static string assName = AppDomain.CurrentDomain.FriendlyName; + + private static string FormatMsg(string title, object msg) + { + return "Assembly:" + assName + "\r\nTitle : " + title + "\r\nMessage : " + msg + "\r\n"; + } + + public static void Error(string title, object msg = null) + { + Log?.Error(FormatMsg(title, msg)); + + Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); + } + + public static void Debug(string title, object msg = null) + { + Log?.Debug(FormatMsg(title, msg)); + + Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); + } + + public static void Info(string title, object msg = null) + { + Log?.Info(FormatMsg(title, msg)); + + Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); + } + + public static void Warn(string title, object msg = null) + { + Log?.Warn(FormatMsg(title, msg)); + + Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); + } + + public static void Trace(string title, object msg = null) + { + Log?.Trace(FormatMsg(title, msg)); + + Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); + } + + public static void Fatal(string title, object msg = null) + { + Log?.Fatal(FormatMsg(title, msg)); + + Console.WriteLine(DateTime.Now+"\r\n"+FormatMsg(title, msg)); + } + } + } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/MySqlHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/MySqlHelper.cs index 10091c9..43c268f 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/MySqlHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/MySqlHelper.cs @@ -1,29 +1,29 @@ -using System.Threading.Tasks; -using Dapper; -using MySql.Data.MySqlClient; - -namespace Hncore.Infrastructure.Common -{ - public class MySqlHelper - { - public static int Execute(string connStr, string sql, object param = null) - { - using (var conn = new MySqlConnection(connStr)) - { - conn.Open(); - - return conn.Execute(sql, param); - } - } - - public static async Task ExecuteAsync(string connStr, string sql, object param = null) - { - using (var conn = new MySqlConnection(connStr)) - { - conn.Open(); - - return await conn.ExecuteAsync(sql, param); - } - } - } +using System.Threading.Tasks; +using Dapper; +using MySql.Data.MySqlClient; + +namespace Hncore.Infrastructure.Common +{ + public class MySqlHelper + { + public static int Execute(string connStr, string sql, object param = null) + { + using (var conn = new MySqlConnection(connStr)) + { + conn.Open(); + + return conn.Execute(sql, param); + } + } + + public static async Task ExecuteAsync(string connStr, string sql, object param = null) + { + using (var conn = new MySqlConnection(connStr)) + { + conn.Open(); + + return await conn.ExecuteAsync(sql, param); + } + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/NetworkHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/NetworkHelper.cs index 30c3af8..b3d3f05 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/NetworkHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/NetworkHelper.cs @@ -1,21 +1,21 @@ -using System.Linq; -using System.Net; -using System.Net.NetworkInformation; -using System.Net.Sockets; - -namespace Hncore.Infrastructure.Common -{ - public class NetworkHelper - { - public static string GetPublicIp() - { - return NetworkInterface - .GetAllNetworkInterfaces() - .Select(p => p.GetIPProperties()) - .SelectMany(p => p.UnicastAddresses) - .FirstOrDefault(p => - p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address))?.Address - .ToString(); - } - } +using System.Linq; +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; + +namespace Hncore.Infrastructure.Common +{ + public class NetworkHelper + { + public static string GetPublicIp() + { + return NetworkInterface + .GetAllNetworkInterfaces() + .Select(p => p.GetIPProperties()) + .SelectMany(p => p.UnicastAddresses) + .FirstOrDefault(p => + p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address))?.Address + .ToString(); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/QiNiuCloudHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/QiNiuCloudHelper.cs index 8a74556..710835a 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/QiNiuCloudHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/QiNiuCloudHelper.cs @@ -1,119 +1,119 @@ -using System; -using System.Collections.Generic; -using System.IO; -using Hncore.Infrastructure.Extension; -using Qiniu.Http; -using Qiniu.Storage; -using Qiniu.Util; - -namespace Hncore.Infrastructure.Common -{ - public class QiNiuCloudHelper - { - static Mac mac = new Mac("3bmkJLD-inSGpQnLr_9UlommFT81B5L0ryesJLhS", - "X22vza-l53jcZyi_fmaex88R065_Ip2_3j5Im0Se"); - - static string bucket = "property"; - - /// - /// - /// - /// - /// 图片地址 - public static string UploadImage(Stream stream, string prefix, string persistentOps = "") - { - string fileName = prefix + Guid.NewGuid() + ".jpg"; - - // 上传策略,参见 - // https://developer.qiniu.com/kodo/manual/put-policy - PutPolicy putPolicy = new PutPolicy(); - // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" - // putPolicy.Scope = bucket + ":" + saveKey; - putPolicy.Scope = bucket; - // 上传策略有效期(对应于生成的凭证的有效期) - putPolicy.SetExpires(3600); - - if (!string.IsNullOrEmpty(persistentOps)) - { - string saveAs = (bucket + ":" + fileName).ToBase64String() - .Replace("+", "-") - .Replace("/", "_"); - putPolicy.PersistentOps = persistentOps + $"|saveas/{saveAs}"; - putPolicy.PersistentPipeline = "face_image"; - } - - - string jstr = putPolicy.ToJsonString(); - string token = Auth.CreateUploadToken(mac, jstr); - - ResumableUploader fu = new ResumableUploader(new Config() - { - Zone = Zone.ZONE_CN_East - }); - - - var result = fu.UploadStream(stream, fileName, token, null); - - if (result.Code == 200) - { - return "http://propertyimages.etor.vip/" + fileName; - } - - LogHelper.Error("七牛上传图片失败", result.ToString()); - - return null; - } - - public static string UploadImage(string imageBase64, string prefix, string persistentOps = "") - { - byte[] imageByte = Convert.FromBase64String(imageBase64); - - var stream = new MemoryStream(imageByte); - - return UploadImage(stream, prefix, persistentOps); - } - - /// - /// 删除资源 - /// - /// - public static void Delete(string key) - { - Config config = new Config(); - config.Zone = Zone.ZONE_CN_East; - - BucketManager bucketManager = new BucketManager(mac, config); - - var res = bucketManager.Delete(bucket, key); - } - - public static List Domains(string bucket) - { - Config config = new Config(); - config.Zone = Zone.ZONE_CN_East; - - BucketManager bucketManager = new BucketManager(mac, config); - - return bucketManager.Domains("property").Result; - } - - public static string GetToken(int expireInSeconds = 3600) - { - // 上传策略,参见 - // https://developer.qiniu.com/kodo/manual/put-policy - PutPolicy putPolicy = new PutPolicy(); - // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" - // putPolicy.Scope = bucket + ":" + saveKey; - putPolicy.Scope = bucket; - // 上传策略有效期(对应于生成的凭证的有效期) - putPolicy.SetExpires(expireInSeconds); - putPolicy.ReturnBody = - "{\"key\":$(key),\"hash\":$(etag),\"mimeType\":$(mimeType),\"fname\":$(fname),\"fsize\":$(fsize),\"avinfo\":$(avinfo),\"ext\":$(ext),\"imageInfo\":$(imageInfo)}"; - - string jstr = putPolicy.ToJsonString(); - string token = Auth.CreateUploadToken(mac, jstr); - - return token; - } - } +using System; +using System.Collections.Generic; +using System.IO; +using Hncore.Infrastructure.Extension; +using Qiniu.Http; +using Qiniu.Storage; +using Qiniu.Util; + +namespace Hncore.Infrastructure.Common +{ + public class QiNiuCloudHelper + { + static Mac mac = new Mac("3bmkJLD-inSGpQnLr_9UlommFT81B5L0ryesJLhS", + "X22vza-l53jcZyi_fmaex88R065_Ip2_3j5Im0Se"); + + static string bucket = "property"; + + /// + /// + /// + /// + /// 图片地址 + public static string UploadImage(Stream stream, string prefix, string persistentOps = "") + { + string fileName = prefix + Guid.NewGuid() + ".jpg"; + + // 上传策略,参见 + // https://developer.qiniu.com/kodo/manual/put-policy + PutPolicy putPolicy = new PutPolicy(); + // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" + // putPolicy.Scope = bucket + ":" + saveKey; + putPolicy.Scope = bucket; + // 上传策略有效期(对应于生成的凭证的有效期) + putPolicy.SetExpires(3600); + + if (!string.IsNullOrEmpty(persistentOps)) + { + string saveAs = (bucket + ":" + fileName).ToBase64String() + .Replace("+", "-") + .Replace("/", "_"); + putPolicy.PersistentOps = persistentOps + $"|saveas/{saveAs}"; + putPolicy.PersistentPipeline = "face_image"; + } + + + string jstr = putPolicy.ToJsonString(); + string token = Auth.CreateUploadToken(mac, jstr); + + ResumableUploader fu = new ResumableUploader(new Config() + { + Zone = Zone.ZONE_CN_East + }); + + + var result = fu.UploadStream(stream, fileName, token, null); + + if (result.Code == 200) + { + return "http://propertyimages.etor.vip/" + fileName; + } + + LogHelper.Error("七牛上传图片失败", result.ToString()); + + return null; + } + + public static string UploadImage(string imageBase64, string prefix, string persistentOps = "") + { + byte[] imageByte = Convert.FromBase64String(imageBase64); + + var stream = new MemoryStream(imageByte); + + return UploadImage(stream, prefix, persistentOps); + } + + /// + /// 删除资源 + /// + /// + public static void Delete(string key) + { + Config config = new Config(); + config.Zone = Zone.ZONE_CN_East; + + BucketManager bucketManager = new BucketManager(mac, config); + + var res = bucketManager.Delete(bucket, key); + } + + public static List Domains(string bucket) + { + Config config = new Config(); + config.Zone = Zone.ZONE_CN_East; + + BucketManager bucketManager = new BucketManager(mac, config); + + return bucketManager.Domains("property").Result; + } + + public static string GetToken(int expireInSeconds = 3600) + { + // 上传策略,参见 + // https://developer.qiniu.com/kodo/manual/put-policy + PutPolicy putPolicy = new PutPolicy(); + // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" + // putPolicy.Scope = bucket + ":" + saveKey; + putPolicy.Scope = bucket; + // 上传策略有效期(对应于生成的凭证的有效期) + putPolicy.SetExpires(expireInSeconds); + putPolicy.ReturnBody = + "{\"key\":$(key),\"hash\":$(etag),\"mimeType\":$(mimeType),\"fname\":$(fname),\"fsize\":$(fsize),\"avinfo\":$(avinfo),\"ext\":$(ext),\"imageInfo\":$(imageInfo)}"; + + string jstr = putPolicy.ToJsonString(); + string token = Auth.CreateUploadToken(mac, jstr); + + return token; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/RSAHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/RSAHelper.cs index ed2e840..2b5a584 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/RSAHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/RSAHelper.cs @@ -1,333 +1,333 @@ -using System; -using System.IO; -using System.Security.Cryptography; -using System.Text; - -namespace Hncore.Infrastructure.Common -{ - /// - /// RSA加解密 使用OpenSSL的公钥加密/私钥解密 - /// - /// 公私钥请使用openssl生成 ssh-keygen -t rsa 命令生成的公钥私钥是不行的 - /// - public class RsaHelper - { - private readonly RSA _privateKeyRsaProvider; - private readonly RSA _publicKeyRsaProvider; - private readonly HashAlgorithmName _hashAlgorithmName; - private readonly Encoding _encoding; - - /// - /// 实例化RSAHelper - /// - /// 加密算法类型 RSA SHA1;RSA2 SHA256 密钥长度至少为2048 - /// 编码类型 - /// 私钥 - /// 公钥 - public RsaHelper(RsaType rsaType, Encoding encoding, string privateKey, string publicKey = null) - { - _encoding = encoding; - if (!string.IsNullOrEmpty(privateKey)) - { - _privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey); - } - - if (!string.IsNullOrEmpty(publicKey)) - { - _publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey); - } - - _hashAlgorithmName = rsaType == RsaType.RSA ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256; - } - - #region 使用私钥签名 - - /// - /// 使用私钥签名 - /// - /// 原始数据 - /// - public string Sign(string data) - { - byte[] dataBytes = _encoding.GetBytes(data); - - var signatureBytes = - _privateKeyRsaProvider.SignData(dataBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1); - - return Convert.ToBase64String(signatureBytes); - } - - #endregion - - #region 使用公钥验证签名 - - /// - /// 使用公钥验证签名 - /// - /// 原始数据 - /// 签名 - /// - public bool Verify(string data, string sign) - { - byte[] dataBytes = _encoding.GetBytes(data); - byte[] signBytes = Convert.FromBase64String(sign); - - var verify = _publicKeyRsaProvider.VerifyData(dataBytes, signBytes, _hashAlgorithmName, - RSASignaturePadding.Pkcs1); - - return verify; - } - - #endregion - - #region 解密 - - public string Decrypt(string cipherText) - { - if (_privateKeyRsaProvider == null) - { - throw new Exception("_privateKeyRsaProvider is null"); - } - - return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), - RSAEncryptionPadding.Pkcs1)); - } - - #endregion - - #region 加密 - - public string Encrypt(string text) - { - if (_publicKeyRsaProvider == null) - { - throw new Exception("_publicKeyRsaProvider is null"); - } - - return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), - RSAEncryptionPadding.Pkcs1)); - } - - #endregion - - #region 使用私钥创建RSA实例 - - public RSA CreateRsaProviderFromPrivateKey(string privateKey) - { - var privateKeyBits = Convert.FromBase64String(privateKey); - - var rsa = RSA.Create(); - var rsaParameters = new RSAParameters(); - - using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits))) - { - byte bt = 0; - ushort twobytes = 0; - twobytes = binr.ReadUInt16(); - if (twobytes == 0x8130) - binr.ReadByte(); - else if (twobytes == 0x8230) - binr.ReadInt16(); - else - throw new Exception("Unexpected value read binr.ReadUInt16()"); - - twobytes = binr.ReadUInt16(); - if (twobytes != 0x0102) - throw new Exception("Unexpected version"); - - bt = binr.ReadByte(); - if (bt != 0x00) - throw new Exception("Unexpected value read binr.ReadByte()"); - - rsaParameters.Modulus = binr.ReadBytes(GetIntegerSize(binr)); - rsaParameters.Exponent = binr.ReadBytes(GetIntegerSize(binr)); - rsaParameters.D = binr.ReadBytes(GetIntegerSize(binr)); - rsaParameters.P = binr.ReadBytes(GetIntegerSize(binr)); - rsaParameters.Q = binr.ReadBytes(GetIntegerSize(binr)); - rsaParameters.DP = binr.ReadBytes(GetIntegerSize(binr)); - rsaParameters.DQ = binr.ReadBytes(GetIntegerSize(binr)); - rsaParameters.InverseQ = binr.ReadBytes(GetIntegerSize(binr)); - } - - rsa.ImportParameters(rsaParameters); - return rsa; - } - - #endregion - - #region 使用公钥创建RSA实例 - - public RSA CreateRsaProviderFromPublicKey(string publicKeyString) - { - // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" - byte[] seqOid = - {0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00}; - byte[] seq = new byte[15]; - - var x509Key = Convert.FromBase64String(publicKeyString); - - // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------ - using (MemoryStream mem = new MemoryStream(x509Key)) - { - using (BinaryReader binr = new BinaryReader(mem) - ) //wrap Memory Stream with BinaryReader for easy reading - { - byte bt = 0; - ushort twobytes = 0; - - twobytes = binr.ReadUInt16(); - if (twobytes == 0x8130 - ) //data read as little endian order (actual data order for Sequence is 30 81) - binr.ReadByte(); //advance 1 byte - else if (twobytes == 0x8230) - binr.ReadInt16(); //advance 2 bytes - else - return null; - - seq = binr.ReadBytes(15); //read the Sequence OID - if (!CompareBytearrays(seq, seqOid)) //make sure Sequence for OID is correct - return null; - - twobytes = binr.ReadUInt16(); - if (twobytes == 0x8103 - ) //data read as little endian order (actual data order for Bit String is 03 81) - binr.ReadByte(); //advance 1 byte - else if (twobytes == 0x8203) - binr.ReadInt16(); //advance 2 bytes - else - return null; - - bt = binr.ReadByte(); - if (bt != 0x00) //expect null byte next - return null; - - twobytes = binr.ReadUInt16(); - if (twobytes == 0x8130 - ) //data read as little endian order (actual data order for Sequence is 30 81) - binr.ReadByte(); //advance 1 byte - else if (twobytes == 0x8230) - binr.ReadInt16(); //advance 2 bytes - else - return null; - - twobytes = binr.ReadUInt16(); - byte lowbyte = 0x00; - byte highbyte = 0x00; - - if (twobytes == 0x8102 - ) //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 - else if (twobytes == 0x8202) - { - highbyte = binr.ReadByte(); //advance 2 bytes - lowbyte = binr.ReadByte(); - } - else - return null; - - byte[] modint = - {lowbyte, highbyte, 0x00, 0x00}; //reverse byte order since asn.1 key uses big endian order - int modsize = BitConverter.ToInt32(modint, 0); - - int firstbyte = binr.PeekChar(); - if (firstbyte == 0x00) - { - //if first byte (highest order) of modulus is zero, don't include it - binr.ReadByte(); //skip this null byte - modsize -= 1; //reduce modulus buffer size by 1 - } - - byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes - - if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data - return null; - int expbytes = - binr - .ReadByte(); // should only need one byte for actual exponent data (for all useful values) - byte[] exponent = binr.ReadBytes(expbytes); - - // ------- create RSACryptoServiceProvider instance and initialize with public key ----- - var rsa = RSA.Create(); - RSAParameters rsaKeyInfo = new RSAParameters - { - Modulus = modulus, - Exponent = exponent - }; - rsa.ImportParameters(rsaKeyInfo); - - return rsa; - } - } - } - - #endregion - - #region 导入密钥算法 - - private int GetIntegerSize(BinaryReader binr) - { - byte bt = 0; - int count = 0; - bt = binr.ReadByte(); - if (bt != 0x02) - return 0; - bt = binr.ReadByte(); - - if (bt == 0x81) - count = binr.ReadByte(); - else if (bt == 0x82) - { - var highbyte = binr.ReadByte(); - var lowbyte = binr.ReadByte(); - byte[] modint = {lowbyte, highbyte, 0x00, 0x00}; - count = BitConverter.ToInt32(modint, 0); - } - else - { - count = bt; - } - - while (binr.ReadByte() == 0x00) - { - count -= 1; - } - - binr.BaseStream.Seek(-1, SeekOrigin.Current); - return count; - } - - private bool CompareBytearrays(byte[] a, byte[] b) - { - if (a.Length != b.Length) - return false; - int i = 0; - foreach (byte c in a) - { - if (c != b[i]) - return false; - i++; - } - - return true; - } - - #endregion - } - - /// - /// RSA算法类型 - /// - public enum RsaType - { - /// - /// SHA1 - /// - RSA = 0, - - /// - /// RSA2 密钥长度至少为2048 - /// SHA256 - /// - RSA2 - } +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Hncore.Infrastructure.Common +{ + /// + /// RSA加解密 使用OpenSSL的公钥加密/私钥解密 + /// + /// 公私钥请使用openssl生成 ssh-keygen -t rsa 命令生成的公钥私钥是不行的 + /// + public class RsaHelper + { + private readonly RSA _privateKeyRsaProvider; + private readonly RSA _publicKeyRsaProvider; + private readonly HashAlgorithmName _hashAlgorithmName; + private readonly Encoding _encoding; + + /// + /// 实例化RSAHelper + /// + /// 加密算法类型 RSA SHA1;RSA2 SHA256 密钥长度至少为2048 + /// 编码类型 + /// 私钥 + /// 公钥 + public RsaHelper(RsaType rsaType, Encoding encoding, string privateKey, string publicKey = null) + { + _encoding = encoding; + if (!string.IsNullOrEmpty(privateKey)) + { + _privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey); + } + + if (!string.IsNullOrEmpty(publicKey)) + { + _publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey); + } + + _hashAlgorithmName = rsaType == RsaType.RSA ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256; + } + + #region 使用私钥签名 + + /// + /// 使用私钥签名 + /// + /// 原始数据 + /// + public string Sign(string data) + { + byte[] dataBytes = _encoding.GetBytes(data); + + var signatureBytes = + _privateKeyRsaProvider.SignData(dataBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1); + + return Convert.ToBase64String(signatureBytes); + } + + #endregion + + #region 使用公钥验证签名 + + /// + /// 使用公钥验证签名 + /// + /// 原始数据 + /// 签名 + /// + public bool Verify(string data, string sign) + { + byte[] dataBytes = _encoding.GetBytes(data); + byte[] signBytes = Convert.FromBase64String(sign); + + var verify = _publicKeyRsaProvider.VerifyData(dataBytes, signBytes, _hashAlgorithmName, + RSASignaturePadding.Pkcs1); + + return verify; + } + + #endregion + + #region 解密 + + public string Decrypt(string cipherText) + { + if (_privateKeyRsaProvider == null) + { + throw new Exception("_privateKeyRsaProvider is null"); + } + + return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), + RSAEncryptionPadding.Pkcs1)); + } + + #endregion + + #region 加密 + + public string Encrypt(string text) + { + if (_publicKeyRsaProvider == null) + { + throw new Exception("_publicKeyRsaProvider is null"); + } + + return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), + RSAEncryptionPadding.Pkcs1)); + } + + #endregion + + #region 使用私钥创建RSA实例 + + public RSA CreateRsaProviderFromPrivateKey(string privateKey) + { + var privateKeyBits = Convert.FromBase64String(privateKey); + + var rsa = RSA.Create(); + var rsaParameters = new RSAParameters(); + + using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits))) + { + byte bt = 0; + ushort twobytes = 0; + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) + binr.ReadByte(); + else if (twobytes == 0x8230) + binr.ReadInt16(); + else + throw new Exception("Unexpected value read binr.ReadUInt16()"); + + twobytes = binr.ReadUInt16(); + if (twobytes != 0x0102) + throw new Exception("Unexpected version"); + + bt = binr.ReadByte(); + if (bt != 0x00) + throw new Exception("Unexpected value read binr.ReadByte()"); + + rsaParameters.Modulus = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.Exponent = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.D = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.P = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.Q = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.DP = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.DQ = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.InverseQ = binr.ReadBytes(GetIntegerSize(binr)); + } + + rsa.ImportParameters(rsaParameters); + return rsa; + } + + #endregion + + #region 使用公钥创建RSA实例 + + public RSA CreateRsaProviderFromPublicKey(string publicKeyString) + { + // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" + byte[] seqOid = + {0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00}; + byte[] seq = new byte[15]; + + var x509Key = Convert.FromBase64String(publicKeyString); + + // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------ + using (MemoryStream mem = new MemoryStream(x509Key)) + { + using (BinaryReader binr = new BinaryReader(mem) + ) //wrap Memory Stream with BinaryReader for easy reading + { + byte bt = 0; + ushort twobytes = 0; + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130 + ) //data read as little endian order (actual data order for Sequence is 30 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8230) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + seq = binr.ReadBytes(15); //read the Sequence OID + if (!CompareBytearrays(seq, seqOid)) //make sure Sequence for OID is correct + return null; + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8103 + ) //data read as little endian order (actual data order for Bit String is 03 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8203) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + bt = binr.ReadByte(); + if (bt != 0x00) //expect null byte next + return null; + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130 + ) //data read as little endian order (actual data order for Sequence is 30 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8230) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + twobytes = binr.ReadUInt16(); + byte lowbyte = 0x00; + byte highbyte = 0x00; + + if (twobytes == 0x8102 + ) //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 + else if (twobytes == 0x8202) + { + highbyte = binr.ReadByte(); //advance 2 bytes + lowbyte = binr.ReadByte(); + } + else + return null; + + byte[] modint = + {lowbyte, highbyte, 0x00, 0x00}; //reverse byte order since asn.1 key uses big endian order + int modsize = BitConverter.ToInt32(modint, 0); + + int firstbyte = binr.PeekChar(); + if (firstbyte == 0x00) + { + //if first byte (highest order) of modulus is zero, don't include it + binr.ReadByte(); //skip this null byte + modsize -= 1; //reduce modulus buffer size by 1 + } + + byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes + + if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data + return null; + int expbytes = + binr + .ReadByte(); // should only need one byte for actual exponent data (for all useful values) + byte[] exponent = binr.ReadBytes(expbytes); + + // ------- create RSACryptoServiceProvider instance and initialize with public key ----- + var rsa = RSA.Create(); + RSAParameters rsaKeyInfo = new RSAParameters + { + Modulus = modulus, + Exponent = exponent + }; + rsa.ImportParameters(rsaKeyInfo); + + return rsa; + } + } + } + + #endregion + + #region 导入密钥算法 + + private int GetIntegerSize(BinaryReader binr) + { + byte bt = 0; + int count = 0; + bt = binr.ReadByte(); + if (bt != 0x02) + return 0; + bt = binr.ReadByte(); + + if (bt == 0x81) + count = binr.ReadByte(); + else if (bt == 0x82) + { + var highbyte = binr.ReadByte(); + var lowbyte = binr.ReadByte(); + byte[] modint = {lowbyte, highbyte, 0x00, 0x00}; + count = BitConverter.ToInt32(modint, 0); + } + else + { + count = bt; + } + + while (binr.ReadByte() == 0x00) + { + count -= 1; + } + + binr.BaseStream.Seek(-1, SeekOrigin.Current); + return count; + } + + private bool CompareBytearrays(byte[] a, byte[] b) + { + if (a.Length != b.Length) + return false; + int i = 0; + foreach (byte c in a) + { + if (c != b[i]) + return false; + i++; + } + + return true; + } + + #endregion + } + + /// + /// RSA算法类型 + /// + public enum RsaType + { + /// + /// SHA1 + /// + RSA = 0, + + /// + /// RSA2 密钥长度至少为2048 + /// SHA256 + /// + RSA2 + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/RandomHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/RandomHelper.cs index c5788b0..9c64bb7 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/RandomHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/RandomHelper.cs @@ -1,143 +1,143 @@ -using System; -using System.Collections.Generic; - -namespace Hncore.Infrastructure.Common -{ - public class RandomHelper - { - #region 私有属性 - - /// - /// 随机数最小值 - /// - private static int MiniNum => int.MinValue; - - /// - /// 随机数最大值 - /// - private static int MaxNum => int.MaxValue; - - /// - /// 随机数长度 - /// - private static int RandomLength => 4; - - /// - /// 随机数来源 - /// - private static string RandomString => "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz"; - - /// - /// 系统默认生成随机数长度 - /// - private const int RandomLengthPresent = 6; - - /// - /// 系统默认随机数来源 - /// - private const string RandomStringPresent = "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz"; - - private static readonly Random Random = new Random(DateTime.Now.Millisecond); - #endregion - - #region 产生随机字符 - - /// - /// 产生随机字符 - /// - /// 产生随机数长度,默认为-1 - /// 随机数来源 - /// - public static string GetRandomString(int randomLength = -1, string randomString = "") - { - int randomLengthTemp;//随机数长度 - if (randomLength > 0) - randomLengthTemp = randomLength; - else if (RandomLength > 0) - randomLengthTemp = RandomLength; - else - randomLengthTemp = RandomLengthPresent; - string randomStringTemp;//随机数来源 - if (!string.IsNullOrEmpty(randomString)) - randomStringTemp = randomString; - else if (!string.IsNullOrEmpty(RandomString)) - randomStringTemp = RandomString; - else - randomStringTemp = RandomStringPresent; - string returnValue = string.Empty; - for (int i = 0; i < randomLengthTemp; i++) - { - int r = Random.Next(0, randomStringTemp.Length - 1); - returnValue += randomStringTemp[r]; - } - return returnValue; - } - #endregion - - #region 产生随机数 - /// - /// 产生随机数 - /// - /// 最小随机数 - /// 最大随机数 - /// - public static int GetRandom(int minNum = -1, int maxNum = -1) - { - int minNumTemp = minNum == -1 ? MiniNum : minNum;//最小随机数 - int maxNumTemp = maxNum == -1 ? MaxNum : maxNum;//最大随机数 - return Random.Next(minNumTemp, maxNumTemp); - } - #endregion - - #region 生成一个0.0到1.0的随机小数 - /// - /// 生成一个0.0到1.0的随机小数 - /// - public double GetRandomDouble() - { - return Random.NextDouble(); - } - #endregion - - #region 对一个数组进行随机排序 - /// - /// 对一个数组进行随机排序 - /// - /// 数组的类型 - /// 需要随机排序的数组 - public void GetRandomArray(T[] arr) - { - //对数组进行随机排序的算法:随机选择两个位置,将两个位置上的值交换 - //交换的次数,这里使用数组的长度作为交换次数 - int count = arr.Length; - //开始交换 - for (int i = 0; i < count; i++) - { - //生成两个随机数位置 - int randomNum1 = GetRandom(0, arr.Length); - int randomNum2 = GetRandom(0, arr.Length); - //定义临时变量 - //交换两个随机数位置的值 - var temp = arr[randomNum1]; - arr[randomNum1] = arr[randomNum2]; - arr[randomNum2] = temp; - } - } - - public static string Uuid(int len) - { - len = len > 32 ? 32 : len; - var str = Guid.NewGuid().ToString("N"); - var list = new List(); - while (true) - { - var index = GetRandom(0, 32); - list.Add(str[index].ToString()); - if (list.Count >= len) - break; - } - return string.Join("", list); - } - #endregion - } -} +using System; +using System.Collections.Generic; + +namespace Hncore.Infrastructure.Common +{ + public class RandomHelper + { + #region 私有属性 + + /// + /// 随机数最小值 + /// + private static int MiniNum => int.MinValue; + + /// + /// 随机数最大值 + /// + private static int MaxNum => int.MaxValue; + + /// + /// 随机数长度 + /// + private static int RandomLength => 4; + + /// + /// 随机数来源 + /// + private static string RandomString => "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz"; + + /// + /// 系统默认生成随机数长度 + /// + private const int RandomLengthPresent = 6; + + /// + /// 系统默认随机数来源 + /// + private const string RandomStringPresent = "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz"; + + private static readonly Random Random = new Random(DateTime.Now.Millisecond); + #endregion + + #region 产生随机字符 + + /// + /// 产生随机字符 + /// + /// 产生随机数长度,默认为-1 + /// 随机数来源 + /// + public static string GetRandomString(int randomLength = -1, string randomString = "") + { + int randomLengthTemp;//随机数长度 + if (randomLength > 0) + randomLengthTemp = randomLength; + else if (RandomLength > 0) + randomLengthTemp = RandomLength; + else + randomLengthTemp = RandomLengthPresent; + string randomStringTemp;//随机数来源 + if (!string.IsNullOrEmpty(randomString)) + randomStringTemp = randomString; + else if (!string.IsNullOrEmpty(RandomString)) + randomStringTemp = RandomString; + else + randomStringTemp = RandomStringPresent; + string returnValue = string.Empty; + for (int i = 0; i < randomLengthTemp; i++) + { + int r = Random.Next(0, randomStringTemp.Length - 1); + returnValue += randomStringTemp[r]; + } + return returnValue; + } + #endregion + + #region 产生随机数 + /// + /// 产生随机数 + /// + /// 最小随机数 + /// 最大随机数 + /// + public static int GetRandom(int minNum = -1, int maxNum = -1) + { + int minNumTemp = minNum == -1 ? MiniNum : minNum;//最小随机数 + int maxNumTemp = maxNum == -1 ? MaxNum : maxNum;//最大随机数 + return Random.Next(minNumTemp, maxNumTemp); + } + #endregion + + #region 生成一个0.0到1.0的随机小数 + /// + /// 生成一个0.0到1.0的随机小数 + /// + public double GetRandomDouble() + { + return Random.NextDouble(); + } + #endregion + + #region 对一个数组进行随机排序 + /// + /// 对一个数组进行随机排序 + /// + /// 数组的类型 + /// 需要随机排序的数组 + public void GetRandomArray(T[] arr) + { + //对数组进行随机排序的算法:随机选择两个位置,将两个位置上的值交换 + //交换的次数,这里使用数组的长度作为交换次数 + int count = arr.Length; + //开始交换 + for (int i = 0; i < count; i++) + { + //生成两个随机数位置 + int randomNum1 = GetRandom(0, arr.Length); + int randomNum2 = GetRandom(0, arr.Length); + //定义临时变量 + //交换两个随机数位置的值 + var temp = arr[randomNum1]; + arr[randomNum1] = arr[randomNum2]; + arr[randomNum2] = temp; + } + } + + public static string Uuid(int len) + { + len = len > 32 ? 32 : len; + var str = Guid.NewGuid().ToString("N"); + var list = new List(); + while (true) + { + var index = GetRandom(0, 32); + list.Add(str[index].ToString()); + if (list.Count >= len) + break; + } + return string.Join("", list); + } + #endregion + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Common/RedisLocklHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/RedisLocklHelper.cs index eb92261..1a6eb47 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/RedisLocklHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/RedisLocklHelper.cs @@ -1,72 +1,72 @@ -using Hncore.Infrastructure.Extension; -using System; -using System.Diagnostics; -using System.Reflection; -using System.Runtime.InteropServices; - -namespace Hncore.Infrastructure.Common -{ - public class RedisLocker - { - private string _key; - private long _lockTime; - /// - /// - /// - /// 锁的键 - /// 锁超时时间 单位毫秒 - public RedisLocker(string key,long outTime) - { - _key =$"Lock:{Assembly.GetCallingAssembly().GetFriendName()}:{key}" ; - _lockTime = outTime; - } - public void Exec(Action action) - { - if (GetLock()) - { - action(); - ReleaseLock(); - } - } - - protected bool GetLock() - { - try - { - var currentTime = DateTime.Now.GetUnixTimeStamp(); - if (RedisHelper.SetNx(this._key, currentTime + _lockTime)) - { - Console.WriteLine("获取到Redis锁了"); - RedisHelper.Expire(_key, TimeSpan.FromMilliseconds(_lockTime)); //设置过期时间 - return true; - } - - //防止SetNx成功但是设置过期时间(Expire)失败造成死锁 - var lockValue = Convert.ToInt64(RedisHelper.Get(_key)); - currentTime = DateTime.Now.GetUnixTimeStamp(); - if (lockValue > 0 && currentTime > lockValue) - { - var getsetResult = Convert.ToInt64(RedisHelper.GetSet(_key, currentTime)); - if (getsetResult == 0 || getsetResult == lockValue) - { - Console.WriteLine("获取到Redis锁了"); - RedisHelper.Expire(_key, TimeSpan.FromMilliseconds(_lockTime)); - return true; - } - } - Console.WriteLine("没有获取到锁"); - return false; - } - catch - { - ReleaseLock(); - return false; - } - } - - protected bool ReleaseLock() - { - return RedisHelper.Del(_key) > 0; - } - } +using Hncore.Infrastructure.Extension; +using System; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Hncore.Infrastructure.Common +{ + public class RedisLocker + { + private string _key; + private long _lockTime; + /// + /// + /// + /// 锁的键 + /// 锁超时时间 单位毫秒 + public RedisLocker(string key,long outTime) + { + _key =$"Lock:{Assembly.GetCallingAssembly().GetFriendName()}:{key}" ; + _lockTime = outTime; + } + public void Exec(Action action) + { + if (GetLock()) + { + action(); + ReleaseLock(); + } + } + + protected bool GetLock() + { + try + { + var currentTime = DateTime.Now.GetUnixTimeStamp(); + if (RedisHelper.SetNx(this._key, currentTime + _lockTime)) + { + Console.WriteLine("获取到Redis锁了"); + RedisHelper.Expire(_key, TimeSpan.FromMilliseconds(_lockTime)); //设置过期时间 + return true; + } + + //防止SetNx成功但是设置过期时间(Expire)失败造成死锁 + var lockValue = Convert.ToInt64(RedisHelper.Get(_key)); + currentTime = DateTime.Now.GetUnixTimeStamp(); + if (lockValue > 0 && currentTime > lockValue) + { + var getsetResult = Convert.ToInt64(RedisHelper.GetSet(_key, currentTime)); + if (getsetResult == 0 || getsetResult == lockValue) + { + Console.WriteLine("获取到Redis锁了"); + RedisHelper.Expire(_key, TimeSpan.FromMilliseconds(_lockTime)); + return true; + } + } + Console.WriteLine("没有获取到锁"); + return false; + } + catch + { + ReleaseLock(); + return false; + } + } + + protected bool ReleaseLock() + { + return RedisHelper.Del(_key) > 0; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/RegexPattern.cs b/Infrastructure/Hncore.Infrastructure/Common/RegexPattern.cs index a93d6e8..8d03404 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/RegexPattern.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/RegexPattern.cs @@ -1,35 +1,35 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Text.RegularExpressions; - -namespace Hncore.Infrastructure.Common -{ - public static class RegexPattern - { - 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 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 static bool IsMatch(string str,string pattern) - { - return Regex.IsMatch(str, pattern); - } - public static bool IsMobile(string str) - { - return IsMatch(str, Mobile); - } - public static bool IsEmail(string str) - { - return IsMatch(str, Email); - } - public static bool IsIdCard(string str) - { - return IsMatch(str, IdCard); - } - public static bool IsCarNumber(string str) - { - return IsMatch(str, CarNumber); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; + +namespace Hncore.Infrastructure.Common +{ + public static class RegexPattern + { + 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 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 static bool IsMatch(string str,string pattern) + { + return Regex.IsMatch(str, pattern); + } + public static bool IsMobile(string str) + { + return IsMatch(str, Mobile); + } + public static bool IsEmail(string str) + { + return IsMatch(str, Email); + } + public static bool IsIdCard(string str) + { + return IsMatch(str, IdCard); + } + public static bool IsCarNumber(string str) + { + return IsMatch(str, CarNumber); + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Common/SecurityHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/SecurityHelper.cs index 4a80d1b..04f4787 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/SecurityHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/SecurityHelper.cs @@ -1,388 +1,388 @@ -using System; -using System.IO; -using System.Security.Cryptography; -using System.Text; - -namespace Hncore.Infrastructure.Common -{ - public class SecurityHelper - { - #region AES加密 - - /// - /// AES加密 - /// - /// - /// - public static string AESEncrypt(string toEncrypt, string key) - { - if (string.IsNullOrWhiteSpace(toEncrypt)) - return string.Empty; - // 256-AES key - byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); - byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); - - RijndaelManaged rDel = new RijndaelManaged(); - rDel.Key = keyArray; - rDel.Mode = CipherMode.ECB; - rDel.Padding = PaddingMode.PKCS7; - - ICryptoTransform cTransform = rDel.CreateEncryptor(); - byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); - - - return Convert.ToBase64String(resultArray, 0, resultArray.Length); - } - - #endregion - - #region AES解密 - - /// - /// AES解密 - /// - /// - /// - public static string Decrypt(string toDecrypt, string key) - { - if (string.IsNullOrWhiteSpace(toDecrypt)) - return string.Empty; - try - { - // 256-AES key - byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); - byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); - - RijndaelManaged rDel = new RijndaelManaged(); - rDel.Key = keyArray; - rDel.Mode = CipherMode.ECB; - rDel.Padding = PaddingMode.PKCS7; - - ICryptoTransform cTransform = rDel.CreateDecryptor(); - - - byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); - return UTF8Encoding.UTF8.GetString(resultArray); - } - catch(Exception ex) - { - LogHelper.Error("aes Decrypt", ex.Message); - return toDecrypt; - } - } - - #endregion - - #region MD5加密 - - /// - /// MD5加密 - /// - /// - /// - public static string GetMd5Hash(string input, Encoding encoding = null) - { - if (encoding == null) - { - encoding = Encoding.UTF8; - } - - - MD5 myMD5 = new MD5CryptoServiceProvider(); - byte[] signed = myMD5.ComputeHash(encoding.GetBytes(input)); - string signResult = byte2mac(signed); - return signResult.ToUpper(); - } - - //MD5加密方法 - private static string byte2mac(byte[] signed) - { - StringBuilder EnText = new StringBuilder(); - foreach (byte Byte in signed) - { - EnText.AppendFormat("{0:x2}", Byte); - } - - return EnText.ToString(); - } - - #endregion - - #region 对字符串进行DES加密 - - /// - /// 对字符串进行DES加密 - /// - /// 待加密的字符串 - /// 加密后的BASE64编码的字符串 - public static string DesEncrypt(string sourceString, string key, string iv) - { - byte[] btKey = Encoding.Default.GetBytes(key); - byte[] btIV = Encoding.Default.GetBytes(iv); - DESCryptoServiceProvider des = new DESCryptoServiceProvider(); - using (MemoryStream ms = new MemoryStream()) - { - byte[] inData = Encoding.Default.GetBytes(sourceString); - using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write)) - { - cs.Write(inData, 0, inData.Length); - cs.FlushFinalBlock(); - } - - return Convert.ToBase64String(ms.ToArray()); - } - } - - #endregion - - #region 对DES加密后的字符串进行解密 - - /// - /// 对DES加密后的字符串进行解密 - /// - /// 待解密的字符串 - /// 解密后的字符串 - public static string DesDecrypt(string encryptedString, string key, string iv) - { - byte[] btKey = Encoding.Default.GetBytes(key); - byte[] btIV = Encoding.Default.GetBytes(iv); - DESCryptoServiceProvider des = new DESCryptoServiceProvider(); - using (MemoryStream ms = new MemoryStream()) - { - byte[] inData = Convert.FromBase64String(encryptedString); - using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write)) - { - cs.Write(inData, 0, inData.Length); - cs.FlushFinalBlock(); - } - - return Encoding.Default.GetString(ms.ToArray()); - } - } - - #endregion - - - public static string Sha1(string str) - { - SHA1 sha1 = new SHA1CryptoServiceProvider(); - - byte[] bytes_in = Encoding.UTF8.GetBytes(str); - byte[] bytes_out = sha1.ComputeHash(bytes_in); - sha1.Dispose(); - - var sb = new StringBuilder(); - foreach (byte b in bytes_out) - { - sb.Append(b.ToString("x2")); - } - - return sb.ToString(); - } - - public static string HMACSHA1(string text, string key) - { - HMACSHA1 myhmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(key)); - byte[] byteArray = Encoding.UTF8.GetBytes(text); - MemoryStream stream = new MemoryStream(byteArray); - string signature = Convert.ToBase64String(myhmacsha1.ComputeHash(stream)); - - return signature; - } - - #region JS Aes解密 - - /// - /// JS Aes解密 - /// - /// - /// - /// - /// - public static string JsAesDecrypt(string toDecrypt, string key, string iv) - { - byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); - byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv); - byte[] cipherText = HexToByteArray(toDecrypt); - // Check arguments. - if (cipherText == null || cipherText.Length <= 0) - { - throw new ArgumentNullException("cipherText"); - } - - if (key == null || key.Length <= 0) - { - throw new ArgumentNullException("key"); - } - - if (iv == null || iv.Length <= 0) - { - throw new ArgumentNullException("key"); - } - - string plaintext = null; - using (var rijAlg = new RijndaelManaged()) - { - //Settings - rijAlg.Mode = CipherMode.CBC; - rijAlg.Padding = PaddingMode.PKCS7; - rijAlg.FeedbackSize = 128; - - rijAlg.Key = keyArray; - rijAlg.IV = ivArray; - - var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); - - using (var msDecrypt = new MemoryStream(cipherText)) - { - using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) - { - using (var srDecrypt = new StreamReader(csDecrypt)) - { - plaintext = srDecrypt.ReadToEnd(); - } - } - } - } - - return plaintext; - } - - private static byte[] HexToByteArray(string hex) - { - int NumberChars = hex.Length; - byte[] bytes = new byte[NumberChars / 2]; - for (int i = 0; i < NumberChars; i += 2) - bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); - return bytes; - } - - #endregion - - #region JS Aes 加密 - - /// - /// JsAesEncrypt - /// - /// - /// - /// - /// - public static string JsAesEncrypt(string plainText, string key, string iv) - { - byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); - byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv); - - // Check arguments. - if (plainText == null || plainText.Length <= 0) - { - throw new ArgumentNullException("plainText"); - } - - if (key == null || key.Length <= 0) - { - throw new ArgumentNullException("key"); - } - - if (iv == null || iv.Length <= 0) - { - throw new ArgumentNullException("key"); - } - - byte[] encrypted; - using (var rijAlg = new RijndaelManaged()) - { - rijAlg.Mode = CipherMode.CBC; - rijAlg.Padding = PaddingMode.PKCS7; - rijAlg.FeedbackSize = 128; - - rijAlg.Key = keyArray; - rijAlg.IV = ivArray; - - var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV); - using (var msEncrypt = new MemoryStream()) - { - using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) - { - using (var swEncrypt = new StreamWriter(csEncrypt)) - { - swEncrypt.Write(plainText); - } - - encrypted = msEncrypt.ToArray(); - } - } - } - - // Return the encrypted bytes from the memory stream. - return ByteArrayToHex(encrypted); - } - - private static string ByteArrayToHex(byte[] ba) - { - string hex = BitConverter.ToString(ba); - return hex.Replace("-", ""); - } - - #endregion - - #region 加密隐藏信息(将原信息其中一部分数据替换为特殊字符) - - /// - /// 加密隐藏信息(将原信息其中一部分数据替换为特殊字符) - /// - /// 原参数信息 - /// 更换后的特殊字符 - /// 下标 - /// 位数,-1代表到队尾 - /// - public static string Encrypt(string param, string key, int index, int length = -1) - { - if (string.IsNullOrEmpty(param)) - { - return ""; - } - - string str = ""; - if (index > param.Length - 1) - { - return param; - } - - str = param.Substring(0, index); - if (length == -1) - { - length = param.Length - index; - } - - for (int i = 0; i < length; i++) - { - str += key; - } - - if (index + length < param.Length) - { - str += param.Substring(index + length); - } - - return str; - } - - #endregion - - - /// - /// 将密码使用MD5算法求哈希值 - /// - /// - /// - public static string HashPassword(string password) - { - using (MD5 md5 = MD5.Create()) - { - byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(password)); - return Convert.ToBase64String(bytes); - } - } - } +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Hncore.Infrastructure.Common +{ + public class SecurityHelper + { + #region AES加密 + + /// + /// AES加密 + /// + /// + /// + public static string AESEncrypt(string toEncrypt, string key) + { + if (string.IsNullOrWhiteSpace(toEncrypt)) + return string.Empty; + // 256-AES key + byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); + byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); + + RijndaelManaged rDel = new RijndaelManaged(); + rDel.Key = keyArray; + rDel.Mode = CipherMode.ECB; + rDel.Padding = PaddingMode.PKCS7; + + ICryptoTransform cTransform = rDel.CreateEncryptor(); + byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); + + + return Convert.ToBase64String(resultArray, 0, resultArray.Length); + } + + #endregion + + #region AES解密 + + /// + /// AES解密 + /// + /// + /// + public static string Decrypt(string toDecrypt, string key) + { + if (string.IsNullOrWhiteSpace(toDecrypt)) + return string.Empty; + try + { + // 256-AES key + byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); + byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); + + RijndaelManaged rDel = new RijndaelManaged(); + rDel.Key = keyArray; + rDel.Mode = CipherMode.ECB; + rDel.Padding = PaddingMode.PKCS7; + + ICryptoTransform cTransform = rDel.CreateDecryptor(); + + + byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); + return UTF8Encoding.UTF8.GetString(resultArray); + } + catch(Exception ex) + { + LogHelper.Error("aes Decrypt", ex.Message); + return toDecrypt; + } + } + + #endregion + + #region MD5加密 + + /// + /// MD5加密 + /// + /// + /// + public static string GetMd5Hash(string input, Encoding encoding = null) + { + if (encoding == null) + { + encoding = Encoding.UTF8; + } + + + MD5 myMD5 = new MD5CryptoServiceProvider(); + byte[] signed = myMD5.ComputeHash(encoding.GetBytes(input)); + string signResult = byte2mac(signed); + return signResult.ToUpper(); + } + + //MD5加密方法 + private static string byte2mac(byte[] signed) + { + StringBuilder EnText = new StringBuilder(); + foreach (byte Byte in signed) + { + EnText.AppendFormat("{0:x2}", Byte); + } + + return EnText.ToString(); + } + + #endregion + + #region 对字符串进行DES加密 + + /// + /// 对字符串进行DES加密 + /// + /// 待加密的字符串 + /// 加密后的BASE64编码的字符串 + public static string DesEncrypt(string sourceString, string key, string iv) + { + byte[] btKey = Encoding.Default.GetBytes(key); + byte[] btIV = Encoding.Default.GetBytes(iv); + DESCryptoServiceProvider des = new DESCryptoServiceProvider(); + using (MemoryStream ms = new MemoryStream()) + { + byte[] inData = Encoding.Default.GetBytes(sourceString); + using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write)) + { + cs.Write(inData, 0, inData.Length); + cs.FlushFinalBlock(); + } + + return Convert.ToBase64String(ms.ToArray()); + } + } + + #endregion + + #region 对DES加密后的字符串进行解密 + + /// + /// 对DES加密后的字符串进行解密 + /// + /// 待解密的字符串 + /// 解密后的字符串 + public static string DesDecrypt(string encryptedString, string key, string iv) + { + byte[] btKey = Encoding.Default.GetBytes(key); + byte[] btIV = Encoding.Default.GetBytes(iv); + DESCryptoServiceProvider des = new DESCryptoServiceProvider(); + using (MemoryStream ms = new MemoryStream()) + { + byte[] inData = Convert.FromBase64String(encryptedString); + using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write)) + { + cs.Write(inData, 0, inData.Length); + cs.FlushFinalBlock(); + } + + return Encoding.Default.GetString(ms.ToArray()); + } + } + + #endregion + + + public static string Sha1(string str) + { + SHA1 sha1 = new SHA1CryptoServiceProvider(); + + byte[] bytes_in = Encoding.UTF8.GetBytes(str); + byte[] bytes_out = sha1.ComputeHash(bytes_in); + sha1.Dispose(); + + var sb = new StringBuilder(); + foreach (byte b in bytes_out) + { + sb.Append(b.ToString("x2")); + } + + return sb.ToString(); + } + + public static string HMACSHA1(string text, string key) + { + HMACSHA1 myhmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(key)); + byte[] byteArray = Encoding.UTF8.GetBytes(text); + MemoryStream stream = new MemoryStream(byteArray); + string signature = Convert.ToBase64String(myhmacsha1.ComputeHash(stream)); + + return signature; + } + + #region JS Aes解密 + + /// + /// JS Aes解密 + /// + /// + /// + /// + /// + public static string JsAesDecrypt(string toDecrypt, string key, string iv) + { + byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); + byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv); + byte[] cipherText = HexToByteArray(toDecrypt); + // Check arguments. + if (cipherText == null || cipherText.Length <= 0) + { + throw new ArgumentNullException("cipherText"); + } + + if (key == null || key.Length <= 0) + { + throw new ArgumentNullException("key"); + } + + if (iv == null || iv.Length <= 0) + { + throw new ArgumentNullException("key"); + } + + string plaintext = null; + using (var rijAlg = new RijndaelManaged()) + { + //Settings + rijAlg.Mode = CipherMode.CBC; + rijAlg.Padding = PaddingMode.PKCS7; + rijAlg.FeedbackSize = 128; + + rijAlg.Key = keyArray; + rijAlg.IV = ivArray; + + var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); + + using (var msDecrypt = new MemoryStream(cipherText)) + { + using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) + { + using (var srDecrypt = new StreamReader(csDecrypt)) + { + plaintext = srDecrypt.ReadToEnd(); + } + } + } + } + + return plaintext; + } + + private static byte[] HexToByteArray(string hex) + { + int NumberChars = hex.Length; + byte[] bytes = new byte[NumberChars / 2]; + for (int i = 0; i < NumberChars; i += 2) + bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); + return bytes; + } + + #endregion + + #region JS Aes 加密 + + /// + /// JsAesEncrypt + /// + /// + /// + /// + /// + public static string JsAesEncrypt(string plainText, string key, string iv) + { + byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); + byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv); + + // Check arguments. + if (plainText == null || plainText.Length <= 0) + { + throw new ArgumentNullException("plainText"); + } + + if (key == null || key.Length <= 0) + { + throw new ArgumentNullException("key"); + } + + if (iv == null || iv.Length <= 0) + { + throw new ArgumentNullException("key"); + } + + byte[] encrypted; + using (var rijAlg = new RijndaelManaged()) + { + rijAlg.Mode = CipherMode.CBC; + rijAlg.Padding = PaddingMode.PKCS7; + rijAlg.FeedbackSize = 128; + + rijAlg.Key = keyArray; + rijAlg.IV = ivArray; + + var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV); + using (var msEncrypt = new MemoryStream()) + { + using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) + { + using (var swEncrypt = new StreamWriter(csEncrypt)) + { + swEncrypt.Write(plainText); + } + + encrypted = msEncrypt.ToArray(); + } + } + } + + // Return the encrypted bytes from the memory stream. + return ByteArrayToHex(encrypted); + } + + private static string ByteArrayToHex(byte[] ba) + { + string hex = BitConverter.ToString(ba); + return hex.Replace("-", ""); + } + + #endregion + + #region 加密隐藏信息(将原信息其中一部分数据替换为特殊字符) + + /// + /// 加密隐藏信息(将原信息其中一部分数据替换为特殊字符) + /// + /// 原参数信息 + /// 更换后的特殊字符 + /// 下标 + /// 位数,-1代表到队尾 + /// + public static string Encrypt(string param, string key, int index, int length = -1) + { + if (string.IsNullOrEmpty(param)) + { + return ""; + } + + string str = ""; + if (index > param.Length - 1) + { + return param; + } + + str = param.Substring(0, index); + if (length == -1) + { + length = param.Length - index; + } + + for (int i = 0; i < length; i++) + { + str += key; + } + + if (index + length < param.Length) + { + str += param.Substring(index + length); + } + + return str; + } + + #endregion + + + /// + /// 将密码使用MD5算法求哈希值 + /// + /// + /// + public static string HashPassword(string password) + { + using (MD5 md5 = MD5.Create()) + { + byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(password)); + return Convert.ToBase64String(bytes); + } + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/ShellHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/ShellHelper.cs index cc01e0a..86b6102 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/ShellHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/ShellHelper.cs @@ -1,63 +1,63 @@ -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; - -namespace Hncore.Infrastructure.Common -{ - public class ShellHelper - { - public static string Bash(string cmd) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - var escapedArgs = cmd.Replace("\"", "\\\""); - - var process = new Process() - { - StartInfo = new ProcessStartInfo - { - FileName = "/bin/bash", - Arguments = $"-c \"{escapedArgs}\"", - RedirectStandardOutput = true, - UseShellExecute = false, - CreateNoWindow = true - } - }; - process.Start(); - string result = process.StandardOutput.ReadToEnd(); - process.WaitForExit(); - return result; - } - - return ""; - } - - public static void RedirectOutputBash(string cmd) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - cmd = cmd.Replace("\"", "\\\""); - - Console.WriteLine("执行命令"); - Console.WriteLine(cmd); - - var process = new Process() - { - StartInfo = new ProcessStartInfo - { - FileName = "/bin/bash", - Arguments = $"-c \"{cmd}\"", - RedirectStandardOutput = true, - UseShellExecute = false, - CreateNoWindow = true, - } - }; - - process.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data); - process.Start(); - process.BeginOutputReadLine(); - process.WaitForExit(); - } - } - } +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace Hncore.Infrastructure.Common +{ + public class ShellHelper + { + public static string Bash(string cmd) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + var escapedArgs = cmd.Replace("\"", "\\\""); + + var process = new Process() + { + StartInfo = new ProcessStartInfo + { + FileName = "/bin/bash", + Arguments = $"-c \"{escapedArgs}\"", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + } + }; + process.Start(); + string result = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + return result; + } + + return ""; + } + + public static void RedirectOutputBash(string cmd) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + cmd = cmd.Replace("\"", "\\\""); + + Console.WriteLine("执行命令"); + Console.WriteLine(cmd); + + var process = new Process() + { + StartInfo = new ProcessStartInfo + { + FileName = "/bin/bash", + Arguments = $"-c \"{cmd}\"", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true, + } + }; + + process.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data); + process.Start(); + process.BeginOutputReadLine(); + process.WaitForExit(); + } + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/UrlHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/UrlHelper.cs index 0fef710..7ffc5fa 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/UrlHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/UrlHelper.cs @@ -1,88 +1,88 @@ -using System.Collections.Generic; -using System.Linq; -using System.Web; - -namespace Hncore.Infrastructure.Common -{ - public class UrlHelper - { - #region 设置url参数 - - /// - /// 设置url参数 - /// - /// - /// - /// - /// - public static string SetUrlParam(string url, string paramName, string paramValue) - { - paramName = paramName.ToLower(); - - string currentUrl = url; - - if (!string.IsNullOrEmpty(paramValue)) - { - paramValue = HttpUtility.UrlEncode(paramValue); - } - - if (!currentUrl.Contains("?")) - { - return currentUrl += "?" + paramName + "=" + paramValue; - } - - List paramItems = currentUrl.Split('?')[1].Split('&').ToList(); - - string paramItem = paramItems.SingleOrDefault(t => t.ToLower().Split('=')[0] == paramName); - - if (!string.IsNullOrEmpty(paramItem)) - { - return currentUrl.Replace(paramItem, paramName + "=" + paramValue); - } - else - { - if (currentUrl.Contains("?")) - { - currentUrl += "&"; - } - else - { - currentUrl += "?"; - } - return currentUrl + paramName + "=" + paramValue; - } - } - - public static string SetUrlParam(string url, object paramObj) - { - var type = paramObj.GetType(); - var properties = type.GetProperties(); - - foreach (var property in properties) - { - string name = property.Name; - - object valueObj = property.GetValue(paramObj, null); - - if (valueObj == null) - { - continue; - } - - string value = valueObj.ToString(); - - url = SetUrlParam(url, name, value); - } - - return url; - } - - - public static string ToUrlParam(IDictionary kvs) - { - return string.Join("&", kvs.Select(m => $"{m.Key}={m.Value}")); - } - - #endregion - } +using System.Collections.Generic; +using System.Linq; +using System.Web; + +namespace Hncore.Infrastructure.Common +{ + public class UrlHelper + { + #region 设置url参数 + + /// + /// 设置url参数 + /// + /// + /// + /// + /// + public static string SetUrlParam(string url, string paramName, string paramValue) + { + paramName = paramName.ToLower(); + + string currentUrl = url; + + if (!string.IsNullOrEmpty(paramValue)) + { + paramValue = HttpUtility.UrlEncode(paramValue); + } + + if (!currentUrl.Contains("?")) + { + return currentUrl += "?" + paramName + "=" + paramValue; + } + + List paramItems = currentUrl.Split('?')[1].Split('&').ToList(); + + string paramItem = paramItems.SingleOrDefault(t => t.ToLower().Split('=')[0] == paramName); + + if (!string.IsNullOrEmpty(paramItem)) + { + return currentUrl.Replace(paramItem, paramName + "=" + paramValue); + } + else + { + if (currentUrl.Contains("?")) + { + currentUrl += "&"; + } + else + { + currentUrl += "?"; + } + return currentUrl + paramName + "=" + paramValue; + } + } + + public static string SetUrlParam(string url, object paramObj) + { + var type = paramObj.GetType(); + var properties = type.GetProperties(); + + foreach (var property in properties) + { + string name = property.Name; + + object valueObj = property.GetValue(paramObj, null); + + if (valueObj == null) + { + continue; + } + + string value = valueObj.ToString(); + + url = SetUrlParam(url, name, value); + } + + return url; + } + + + public static string ToUrlParam(IDictionary kvs) + { + return string.Join("&", kvs.Select(m => $"{m.Key}={m.Value}")); + } + + #endregion + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Common/ValidateCodeHelper.cs b/Infrastructure/Hncore.Infrastructure/Common/ValidateCodeHelper.cs index e50d33c..9427e34 100644 --- a/Infrastructure/Hncore.Infrastructure/Common/ValidateCodeHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Common/ValidateCodeHelper.cs @@ -1,110 +1,110 @@ -using System; -using System.Drawing; -using System.Drawing.Imaging; - -namespace Hncore.Infrastructure.Common -{ - public class ValidateCodeHelper - { - 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' }; - string randomCode = ""; - int temp = -1; - - Random rand = new Random(); - for (int i = 0; i < length; i++) - { - if (temp != -1) - { - rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); - } - int t = rand.Next(allCharArray.Length); - if (temp == t) - { - return MakeCode(length); - } - temp = t; - randomCode += allCharArray[t]; - } - return randomCode; - } - public static string MakeNumCode(int length = 4) - { - char[] allCharArray = new char[] { '1','2', '3', '4', '5', '6', '7', '8','9'}; - string randomCode = ""; - int temp = -1; - - Random rand = new Random(); - for (int i = 0; i < length; i++) - { - if (temp != -1) - { - rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); - } - int t = rand.Next(allCharArray.Length); - if (temp == t) - { - return MakeNumCode(length); - } - temp = t; - randomCode += allCharArray[t]; - } - return randomCode; - } - - 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' }; - string randomCode = ""; - int temp = -1; - - Random rand = new Random(); - for (int i = 0; i < length; i++) - { - if (temp != -1) - { - rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); - } - int t = rand.Next(allCharArray.Length); - if (temp == t) - { - return MakeCharCode(length); - } - temp = t; - randomCode += allCharArray[t]; - } - return randomCode; - } - - public static byte[] GenerateCodeImg(string code) - { - int Gheight = (int)(code.Length * 15) + 10; - - //gheight为图片宽度,根据字符长度自动更改图片宽度 - using (var img = new Bitmap(Gheight, 22)) - { - using (var g = Graphics.FromImage(img)) - { - SolidBrush whiteBrush = new SolidBrush(Color.White); - g.FillRectangle(whiteBrush, 0, 0, Gheight, 22); - int i = 0; - foreach (char ch in code.ToCharArray()) - { - g.DrawString(ch.ToString(), - new Font("Arial", 13, FontStyle.Italic), - new SolidBrush(Color.FromArgb(0, 0, 0)), - i * 15, - 0); - i++; - } - - //在矩形内绘制字串(字串,字体,画笔颜色,左上x.左上y) - System.IO.MemoryStream ms = new System.IO.MemoryStream(); - img.Save(ms, ImageFormat.Jpeg); - return ms.ToArray(); - } - } - } - } +using System; +using System.Drawing; +using System.Drawing.Imaging; + +namespace Hncore.Infrastructure.Common +{ + public class ValidateCodeHelper + { + 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' }; + string randomCode = ""; + int temp = -1; + + Random rand = new Random(); + for (int i = 0; i < length; i++) + { + if (temp != -1) + { + rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); + } + int t = rand.Next(allCharArray.Length); + if (temp == t) + { + return MakeCode(length); + } + temp = t; + randomCode += allCharArray[t]; + } + return randomCode; + } + public static string MakeNumCode(int length = 4) + { + char[] allCharArray = new char[] { '1','2', '3', '4', '5', '6', '7', '8','9'}; + string randomCode = ""; + int temp = -1; + + Random rand = new Random(); + for (int i = 0; i < length; i++) + { + if (temp != -1) + { + rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); + } + int t = rand.Next(allCharArray.Length); + if (temp == t) + { + return MakeNumCode(length); + } + temp = t; + randomCode += allCharArray[t]; + } + return randomCode; + } + + 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' }; + string randomCode = ""; + int temp = -1; + + Random rand = new Random(); + for (int i = 0; i < length; i++) + { + if (temp != -1) + { + rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); + } + int t = rand.Next(allCharArray.Length); + if (temp == t) + { + return MakeCharCode(length); + } + temp = t; + randomCode += allCharArray[t]; + } + return randomCode; + } + + public static byte[] GenerateCodeImg(string code) + { + int Gheight = (int)(code.Length * 15) + 10; + + //gheight为图片宽度,根据字符长度自动更改图片宽度 + using (var img = new Bitmap(Gheight, 22)) + { + using (var g = Graphics.FromImage(img)) + { + SolidBrush whiteBrush = new SolidBrush(Color.White); + g.FillRectangle(whiteBrush, 0, 0, Gheight, 22); + int i = 0; + foreach (char ch in code.ToCharArray()) + { + g.DrawString(ch.ToString(), + new Font("Arial", 13, FontStyle.Italic), + new SolidBrush(Color.FromArgb(0, 0, 0)), + i * 15, + 0); + i++; + } + + //在矩形内绘制字串(字串,字体,画笔颜色,左上x.左上y) + System.IO.MemoryStream ms = new System.IO.MemoryStream(); + img.Save(ms, ImageFormat.Jpeg); + return ms.ToArray(); + } + } + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/DDD/AggregateRoot.cs b/Infrastructure/Hncore.Infrastructure/DDD/AggregateRoot.cs index b527574..3436361 100644 --- a/Infrastructure/Hncore.Infrastructure/DDD/AggregateRoot.cs +++ b/Infrastructure/Hncore.Infrastructure/DDD/AggregateRoot.cs @@ -1,9 +1,9 @@ -namespace Hncore.Infrastructure.DDD -{ - public abstract class AggregateRoot : Entity, IAggregateRoot - { - public AggregateRoot() - { - } - } +namespace Hncore.Infrastructure.DDD +{ + public abstract class AggregateRoot : Entity, IAggregateRoot + { + public AggregateRoot() + { + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/DDD/Entity.cs b/Infrastructure/Hncore.Infrastructure/DDD/Entity.cs index 6c78ef6..6c2ef93 100644 --- a/Infrastructure/Hncore.Infrastructure/DDD/Entity.cs +++ b/Infrastructure/Hncore.Infrastructure/DDD/Entity.cs @@ -1,48 +1,48 @@ -using System; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace Hncore.Infrastructure.DDD -{ - /// - /// 实现模型抽象基类 - /// - /// 主键数据类型 - public abstract class Entity : IEntity - { - /// - /// 记录数据库主键ID - /// - [JsonProperty("Id")] - public virtual TId Id { get; set; } - } - - public abstract class EntityWithTime : Entity - { - /// - /// 记录添加(创建)时间 - /// - public virtual DateTime CreateTime { get; set; } = DateTime.Now; - - /// - /// 记录最后更新时间 - /// - public virtual DateTime UpdateTime { get; set; } = DateTime.Now; - - /// - /// 记录软删除标记,0.代表正常,1.代表已删除 - /// - public virtual int DeleteTag { get; set; } - - } - - public abstract class EntityWithDelete : Entity,ISoftDelete - { - /// - /// 记录软删除标记,0.代表正常,1.代表已删除 - /// - public virtual int DeleteTag { get; set; } = 0; - - } - +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Hncore.Infrastructure.DDD +{ + /// + /// 实现模型抽象基类 + /// + /// 主键数据类型 + public abstract class Entity : IEntity + { + /// + /// 记录数据库主键ID + /// + [JsonProperty("Id")] + public virtual TId Id { get; set; } + } + + public abstract class EntityWithTime : Entity + { + /// + /// 记录添加(创建)时间 + /// + public virtual DateTime CreateTime { get; set; } = DateTime.Now; + + /// + /// 记录最后更新时间 + /// + public virtual DateTime UpdateTime { get; set; } = DateTime.Now; + + /// + /// 记录软删除标记,0.代表正常,1.代表已删除 + /// + public virtual int DeleteTag { get; set; } + + } + + public abstract class EntityWithDelete : Entity,ISoftDelete + { + /// + /// 记录软删除标记,0.代表正常,1.代表已删除 + /// + public virtual int DeleteTag { get; set; } = 0; + + } + } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/DDD/IAggregateRoot.cs b/Infrastructure/Hncore.Infrastructure/DDD/IAggregateRoot.cs index b10c5bd..a4bd488 100644 --- a/Infrastructure/Hncore.Infrastructure/DDD/IAggregateRoot.cs +++ b/Infrastructure/Hncore.Infrastructure/DDD/IAggregateRoot.cs @@ -1,6 +1,6 @@ -namespace Hncore.Infrastructure.DDD -{ - public interface IAggregateRoot : IEntity - { - } +namespace Hncore.Infrastructure.DDD +{ + public interface IAggregateRoot : IEntity + { + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/DDD/IEntity.cs b/Infrastructure/Hncore.Infrastructure/DDD/IEntity.cs index 01dac88..43ae0c9 100644 --- a/Infrastructure/Hncore.Infrastructure/DDD/IEntity.cs +++ b/Infrastructure/Hncore.Infrastructure/DDD/IEntity.cs @@ -1,16 +1,16 @@ -using System; - -namespace Hncore.Infrastructure.DDD -{ - public interface IEntity - { - - } - public interface IEntity: IEntity - { - TId Id - { - get; - } - } -} +using System; + +namespace Hncore.Infrastructure.DDD +{ + public interface IEntity + { + + } + public interface IEntity: IEntity + { + TId Id + { + get; + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/DDD/IQuery.cs b/Infrastructure/Hncore.Infrastructure/DDD/IQuery.cs index aee99c0..3aeb4f6 100644 --- a/Infrastructure/Hncore.Infrastructure/DDD/IQuery.cs +++ b/Infrastructure/Hncore.Infrastructure/DDD/IQuery.cs @@ -1,40 +1,40 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Threading.Tasks; -using Hncore.Infrastructure.Data; -using Microsoft.EntityFrameworkCore; - -namespace Hncore.Infrastructure.DDD -{ - public interface IQuery where TEntity : IEntity - { - TEntity GetOne(Expression> condition); - - Task GetOneAsync(Expression> condition); - - PageData GetList(Expression> condition, int pagesize, int pageindex, bool istotal); - - Task> GetListAsync(Expression> condition, int pagesize, int pageindex, bool istotal); - - List GetList(Expression> condition); - - Task> GetListAsync(Expression> condition); - - bool Exists(Expression> condition); - - Task ExistsAsync(Expression> condition); - - List TopN(Expression> condition, int topN); - - Task> TopNAsync(Expression> condition, int topN); - - IQueryable GetListQueryable(Expression> condition); - - IQueryable GetQueryable(); - - DbContext DbContext(); - - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; +using Hncore.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace Hncore.Infrastructure.DDD +{ + public interface IQuery where TEntity : IEntity + { + TEntity GetOne(Expression> condition); + + Task GetOneAsync(Expression> condition); + + PageData GetList(Expression> condition, int pagesize, int pageindex, bool istotal); + + Task> GetListAsync(Expression> condition, int pagesize, int pageindex, bool istotal); + + List GetList(Expression> condition); + + Task> GetListAsync(Expression> condition); + + bool Exists(Expression> condition); + + Task ExistsAsync(Expression> condition); + + List TopN(Expression> condition, int topN); + + Task> TopNAsync(Expression> condition, int topN); + + IQueryable GetListQueryable(Expression> condition); + + IQueryable GetQueryable(); + + DbContext DbContext(); + + } +} diff --git a/Infrastructure/Hncore.Infrastructure/DDD/IRepository.cs b/Infrastructure/Hncore.Infrastructure/DDD/IRepository.cs index 72f24c7..758bb19 100644 --- a/Infrastructure/Hncore.Infrastructure/DDD/IRepository.cs +++ b/Infrastructure/Hncore.Infrastructure/DDD/IRepository.cs @@ -1,43 +1,43 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Hncore.Infrastructure.DDD -{ - public interface IRepository where TEntity : IEntity - { - TEntity FindById(TId id); - - Task FindByIdAsync(TId id); - - void Add(TEntity entity); - - Task AddAsync(TEntity entity); - /// - /// 批量添加 - /// - /// - void AddRange(List entity); - /// - /// 批量添加 - /// - /// - Task AddRangeAsync(List entity); - /// - /// 批量修改 - /// - /// - void UpdateRange(List entity); - /// - /// 批量删除 - /// - /// - void RemoveRange(List entity); - - void Remove(TEntity entity); - void Update(TEntity entity); - - - IQueryable GetQueryable(); - } +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Hncore.Infrastructure.DDD +{ + public interface IRepository where TEntity : IEntity + { + TEntity FindById(TId id); + + Task FindByIdAsync(TId id); + + void Add(TEntity entity); + + Task AddAsync(TEntity entity); + /// + /// 批量添加 + /// + /// + void AddRange(List entity); + /// + /// 批量添加 + /// + /// + Task AddRangeAsync(List entity); + /// + /// 批量修改 + /// + /// + void UpdateRange(List entity); + /// + /// 批量删除 + /// + /// + void RemoveRange(List entity); + + void Remove(TEntity entity); + void Update(TEntity entity); + + + IQueryable GetQueryable(); + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/DDD/ISoftDelete.cs b/Infrastructure/Hncore.Infrastructure/DDD/ISoftDelete.cs index 55f49f2..1c2b80d 100644 --- a/Infrastructure/Hncore.Infrastructure/DDD/ISoftDelete.cs +++ b/Infrastructure/Hncore.Infrastructure/DDD/ISoftDelete.cs @@ -1,7 +1,7 @@ -namespace Hncore.Infrastructure.DDD -{ - public interface ISoftDelete - { - int DeleteTag { get; set; } - } +namespace Hncore.Infrastructure.DDD +{ + public interface ISoftDelete + { + int DeleteTag { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/DDD/ITenant.cs b/Infrastructure/Hncore.Infrastructure/DDD/ITenant.cs index 21e4e64..5cd971b 100644 --- a/Infrastructure/Hncore.Infrastructure/DDD/ITenant.cs +++ b/Infrastructure/Hncore.Infrastructure/DDD/ITenant.cs @@ -1,7 +1,7 @@ -namespace Hncore.Infrastructure.DDD -{ - public interface ITenant - { - int TenantId { get; set; } - } +namespace Hncore.Infrastructure.DDD +{ + public interface ITenant + { + int TenantId { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/DDD/ITenantStore.cs b/Infrastructure/Hncore.Infrastructure/DDD/ITenantStore.cs index a173b68..0c3cd68 100644 --- a/Infrastructure/Hncore.Infrastructure/DDD/ITenantStore.cs +++ b/Infrastructure/Hncore.Infrastructure/DDD/ITenantStore.cs @@ -1,7 +1,7 @@ -namespace Hncore.Infrastructure.DDD -{ - public interface ITenantStore - { - int StoreId { get; set; } - } +namespace Hncore.Infrastructure.DDD +{ + public interface ITenantStore + { + int StoreId { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Data/BusinessException.cs b/Infrastructure/Hncore.Infrastructure/Data/BusinessException.cs index f41880c..9472674 100644 --- a/Infrastructure/Hncore.Infrastructure/Data/BusinessException.cs +++ b/Infrastructure/Hncore.Infrastructure/Data/BusinessException.cs @@ -1,29 +1,29 @@ -using System; -using Hncore.Infrastructure.WebApi; - -namespace Hncore.Infrastructure.Data -{ - public class BusinessException : Exception - { - public ResultCode Code { get; } = ResultCode.C_UNKNOWN_ERROR; - - public BusinessException(string message) : base(message) - { - } - - public BusinessException(ResultCode code, string message = "") : base(message) - { - Code = code; - } - - public static void Throw(string message = "") - { - throw new BusinessException(message); - } - - public static void Throw(ResultCode code, string message = "") - { - throw new BusinessException(code, message); - } - } +using System; +using Hncore.Infrastructure.WebApi; + +namespace Hncore.Infrastructure.Data +{ + public class BusinessException : Exception + { + public ResultCode Code { get; } = ResultCode.C_UNKNOWN_ERROR; + + public BusinessException(string message) : base(message) + { + } + + public BusinessException(ResultCode code, string message = "") : base(message) + { + Code = code; + } + + public static void Throw(string message = "") + { + throw new BusinessException(message); + } + + public static void Throw(ResultCode code, string message = "") + { + throw new BusinessException(code, message); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Data/HttpException.cs b/Infrastructure/Hncore.Infrastructure/Data/HttpException.cs index b9bf6a8..fc633ee 100644 --- a/Infrastructure/Hncore.Infrastructure/Data/HttpException.cs +++ b/Infrastructure/Hncore.Infrastructure/Data/HttpException.cs @@ -1,17 +1,17 @@ -using System; -using System.Net; - -namespace Hncore.Infrastructure.Data -{ - public class HttpException: Exception - { - public HttpStatusCode HttpStatusCode { get; set; } - - public string Content { get; set; } - - public HttpException(HttpStatusCode httpStatusCode) - { - HttpStatusCode = httpStatusCode; - } - } +using System; +using System.Net; + +namespace Hncore.Infrastructure.Data +{ + public class HttpException: Exception + { + public HttpStatusCode HttpStatusCode { get; set; } + + public string Content { get; set; } + + public HttpException(HttpStatusCode httpStatusCode) + { + HttpStatusCode = httpStatusCode; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Data/PageData.cs b/Infrastructure/Hncore.Infrastructure/Data/PageData.cs index ed50c4f..af9c74b 100644 --- a/Infrastructure/Hncore.Infrastructure/Data/PageData.cs +++ b/Infrastructure/Hncore.Infrastructure/Data/PageData.cs @@ -1,40 +1,40 @@ -using Newtonsoft.Json; -using System.Collections.Generic; - -namespace Hncore.Infrastructure.Data -{ - public interface IPageData - { - /// - /// 总行数 - /// - int RowCount { get; set; } - - } - /// - /// 分页数据集合 - /// - public class PageData - { - public PageData() - { - List = new List(); - } - - public PageData(int rowCount, List data) - { - this.RowCount = rowCount; - this.List = data; - } - - /// - /// 总行数 - /// - public int RowCount { get; set; } - - /// - /// 当前页数据集合 - /// - public List List { get; set; } - } -} +using Newtonsoft.Json; +using System.Collections.Generic; + +namespace Hncore.Infrastructure.Data +{ + public interface IPageData + { + /// + /// 总行数 + /// + int RowCount { get; set; } + + } + /// + /// 分页数据集合 + /// + public class PageData + { + public PageData() + { + List = new List(); + } + + public PageData(int rowCount, List data) + { + this.RowCount = rowCount; + this.List = data; + } + + /// + /// 总行数 + /// + public int RowCount { get; set; } + + /// + /// 当前页数据集合 + /// + public List List { get; set; } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Data/PageQueryable.cs b/Infrastructure/Hncore.Infrastructure/Data/PageQueryable.cs index 5162b5f..c28fb07 100644 --- a/Infrastructure/Hncore.Infrastructure/Data/PageQueryable.cs +++ b/Infrastructure/Hncore.Infrastructure/Data/PageQueryable.cs @@ -1,25 +1,25 @@ -using System.Linq; - -namespace Hncore.Infrastructure.Data -{ - /// - /// 分页数据源 - /// - public class PageQueryable - { - /// - /// 总页数 - /// - public int RowCount { get; set; } - - /// - /// 当前页数据集合 - /// - public IQueryable Data { get; set; } - - public PageData ToList() - { - return new PageData(){List=Data.ToList(),RowCount=RowCount}; - } - } -} +using System.Linq; + +namespace Hncore.Infrastructure.Data +{ + /// + /// 分页数据源 + /// + public class PageQueryable + { + /// + /// 总页数 + /// + public int RowCount { get; set; } + + /// + /// 当前页数据集合 + /// + public IQueryable Data { get; set; } + + public PageData ToList() + { + return new PageData(){List=Data.ToList(),RowCount=RowCount}; + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Data/ResultMessage.cs b/Infrastructure/Hncore.Infrastructure/Data/ResultMessage.cs index 8716a62..5a41963 100644 --- a/Infrastructure/Hncore.Infrastructure/Data/ResultMessage.cs +++ b/Infrastructure/Hncore.Infrastructure/Data/ResultMessage.cs @@ -1,48 +1,48 @@ - - -using System; - -namespace Hncore.Infrastructure.Data -{ - public class ResultMessage - { - public ResultMessage() - { - Success = true; - } - - public string Message { get; set; } = ""; - - public bool Success { get; set; } - - public string Code { get; set; } = ""; - - public Action CallBack { get; set; } = null; - - public object Data { get; set; } = null; - - public ResultMessage(bool success, string message) - { - this.Success = success; - this.Message = message; - } - - public ResultMessage(bool success, string message,object data) - { - this.Success = success; - this.Message = message; - this.Data = data; - } - - public ResultMessage(bool success) - { - this.Success = success; - } - - public ResultMessage(string message) - { - Success = true; - this.Message = message; - } - } -} + + +using System; + +namespace Hncore.Infrastructure.Data +{ + public class ResultMessage + { + public ResultMessage() + { + Success = true; + } + + public string Message { get; set; } = ""; + + public bool Success { get; set; } + + public string Code { get; set; } = ""; + + public Action CallBack { get; set; } = null; + + public object Data { get; set; } = null; + + public ResultMessage(bool success, string message) + { + this.Success = success; + this.Message = message; + } + + public ResultMessage(bool success, string message,object data) + { + this.Success = success; + this.Message = message; + this.Data = data; + } + + public ResultMessage(bool success) + { + this.Success = success; + } + + public ResultMessage(string message) + { + Success = true; + this.Message = message; + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Data/TransactionsHelper.cs b/Infrastructure/Hncore.Infrastructure/Data/TransactionsHelper.cs index d17c96d..f1ad18d 100644 --- a/Infrastructure/Hncore.Infrastructure/Data/TransactionsHelper.cs +++ b/Infrastructure/Hncore.Infrastructure/Data/TransactionsHelper.cs @@ -1,24 +1,24 @@ -using System; - -namespace Hncore.Infrastructure.Data -{ - public class TransactionsHelper - { - public static void NoLockInvokeDB(Action action) - { - var transactionOptions = new System.Transactions.TransactionOptions(); - transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; - using (var transactionScope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOptions)) - { - try - { - action(); - } - finally - { - transactionScope.Complete(); - } - } - } - } +using System; + +namespace Hncore.Infrastructure.Data +{ + public class TransactionsHelper + { + public static void NoLockInvokeDB(Action action) + { + var transactionOptions = new System.Transactions.TransactionOptions(); + transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; + using (var transactionScope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOptions)) + { + try + { + action(); + } + finally + { + transactionScope.Complete(); + } + } + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EF/DbContextBase.cs b/Infrastructure/Hncore.Infrastructure/EF/DbContextBase.cs index 4b44e9b..eec0568 100644 --- a/Infrastructure/Hncore.Infrastructure/EF/DbContextBase.cs +++ b/Infrastructure/Hncore.Infrastructure/EF/DbContextBase.cs @@ -1,119 +1,119 @@ -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.DDD; -using Hncore.Infrastructure.Extension; -using Hncore.Infrastructure.Serializer; -using Hncore.Infrastructure.WebApi; -using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; -using System; -using System.Linq; - - -namespace Hncore.Infrastructure.EF -{ - /// - /// 上下文构造器的基类 - /// - public class DbContextBase : DbContext - { - private IHttpContextAccessor _httpContextAccessor; - - private bool _enabledLog = false; - - private int _tenantid = 0; - - private int _storeId = 0; - - private bool _root = false; - - private bool _allow = false; - - public DbContextBase(DbContextOptions options, IHttpContextAccessor httpContextAccessor) : base(options) - { - _httpContextAccessor = httpContextAccessor; - - if (UseTenantFilter()) - { - ManageUserInfo manageUserInfo = _httpContextAccessor.HttpContext.Request.GetManageUserInfo(); - - if (manageUserInfo != null) - { - _tenantid = manageUserInfo.TenantId; - _storeId = manageUserInfo.StoreId; - } - } - else - { - _allow = true; - } - } - - private bool UseTenantFilter() - { - if (_httpContextAccessor == null || _httpContextAccessor.HttpContext == null) - { - return false; - } - - return _httpContextAccessor.HttpContext.Items.ContainsKey("AuthPassedFilterName") - && _httpContextAccessor.HttpContext.Items["AuthPassedFilterName"].ToString() == "ManageAuth"; - } - - - /// - /// model构造器 创建实体映射 - /// - /// - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - base.OnModelCreating(modelBuilder); - - if (!EnvironmentVariableHelper.IsAspNetCoreProduction) - { - LogHelper.Debug("进入DbContextBase的OnModelCreating函数", - $"UseGlobalManageAuthFilter:{GlobalData.UseGlobalManageAuthFilter}\ntoken:{_httpContextAccessor?.HttpContext?.Request?.GetManageUserInfo()?.ToJson(true)}"); - } - - foreach (var type in modelBuilder.Model.GetEntityTypes()) - { - if (typeof(ISoftDelete).IsAssignableFrom(type.ClrType)) - { - modelBuilder.Entity(type.ClrType).AddQueryFilter(t => t.DeleteTag == 0); - } - //if (typeof(ITenant).IsAssignableFrom(type.ClrType)) - //{ - // modelBuilder.Entity(type.ClrType).AddQueryFilter(t => _allow || t.TenantId == _tenantid); - //} - - //if (typeof(ITenantStore).IsAssignableFrom(type.ClrType)) - //{ - // modelBuilder.Entity(type.ClrType) - // .AddQueryFilter(t => _storeId == 0|| t.StoreId==_storeId); - //} - } - } - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - if (_httpContextAccessor?.HttpContext?.Request?.Headers != null) - { - if (_httpContextAccessor.HttpContext.Request.Headers.ContainsKey("enable-ef-log")) - { - if (_httpContextAccessor.HttpContext.Request.Headers.ContainsKey("enable-ef-log").ToBool()) - { - if (_enabledLog == false) - { - optionsBuilder.EnableDebugTrace(_httpContextAccessor); - _enabledLog = true; - } - } - } - } -#if DEBUG - Console.WriteLine("当前为debug模式,开启EF DebugTrace"); - optionsBuilder.EnableDebugTrace(null); -#endif - } - - } +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.DDD; +using Hncore.Infrastructure.Extension; +using Hncore.Infrastructure.Serializer; +using Hncore.Infrastructure.WebApi; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using System; +using System.Linq; + + +namespace Hncore.Infrastructure.EF +{ + /// + /// 上下文构造器的基类 + /// + public class DbContextBase : DbContext + { + private IHttpContextAccessor _httpContextAccessor; + + private bool _enabledLog = false; + + private int _tenantid = 0; + + private int _storeId = 0; + + private bool _root = false; + + private bool _allow = false; + + public DbContextBase(DbContextOptions options, IHttpContextAccessor httpContextAccessor) : base(options) + { + _httpContextAccessor = httpContextAccessor; + + if (UseTenantFilter()) + { + ManageUserInfo manageUserInfo = _httpContextAccessor.HttpContext.Request.GetManageUserInfo(); + + if (manageUserInfo != null) + { + _tenantid = manageUserInfo.TenantId; + _storeId = manageUserInfo.StoreId; + } + } + else + { + _allow = true; + } + } + + private bool UseTenantFilter() + { + if (_httpContextAccessor == null || _httpContextAccessor.HttpContext == null) + { + return false; + } + + return _httpContextAccessor.HttpContext.Items.ContainsKey("AuthPassedFilterName") + && _httpContextAccessor.HttpContext.Items["AuthPassedFilterName"].ToString() == "ManageAuth"; + } + + + /// + /// model构造器 创建实体映射 + /// + /// + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + if (!EnvironmentVariableHelper.IsAspNetCoreProduction) + { + LogHelper.Debug("进入DbContextBase的OnModelCreating函数", + $"UseGlobalManageAuthFilter:{GlobalData.UseGlobalManageAuthFilter}\ntoken:{_httpContextAccessor?.HttpContext?.Request?.GetManageUserInfo()?.ToJson(true)}"); + } + + foreach (var type in modelBuilder.Model.GetEntityTypes()) + { + if (typeof(ISoftDelete).IsAssignableFrom(type.ClrType)) + { + modelBuilder.Entity(type.ClrType).AddQueryFilter(t => t.DeleteTag == 0); + } + //if (typeof(ITenant).IsAssignableFrom(type.ClrType)) + //{ + // modelBuilder.Entity(type.ClrType).AddQueryFilter(t => _allow || t.TenantId == _tenantid); + //} + + //if (typeof(ITenantStore).IsAssignableFrom(type.ClrType)) + //{ + // modelBuilder.Entity(type.ClrType) + // .AddQueryFilter(t => _storeId == 0|| t.StoreId==_storeId); + //} + } + } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + if (_httpContextAccessor?.HttpContext?.Request?.Headers != null) + { + if (_httpContextAccessor.HttpContext.Request.Headers.ContainsKey("enable-ef-log")) + { + if (_httpContextAccessor.HttpContext.Request.Headers.ContainsKey("enable-ef-log").ToBool()) + { + if (_enabledLog == false) + { + optionsBuilder.EnableDebugTrace(_httpContextAccessor); + _enabledLog = true; + } + } + } + } +#if DEBUG + Console.WriteLine("当前为debug模式,开启EF DebugTrace"); + optionsBuilder.EnableDebugTrace(null); +#endif + } + + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EF/DbContextExtension.cs b/Infrastructure/Hncore.Infrastructure/EF/DbContextExtension.cs index a1f5692..26cfe37 100644 --- a/Infrastructure/Hncore.Infrastructure/EF/DbContextExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/EF/DbContextExtension.cs @@ -1,228 +1,228 @@ -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Data.Common; -using System.Linq; -using System.Reflection; - -namespace Hncore.Infrastructure.Extension -{ - /// - /// EF上下文对象扩展类 - /// - /// - public static class DbContextExtension - { - /// - /// 执行SQL返回受影响的行数 - /// - public static int ExecSqlNoQuery(this DbContext db, string sql, DbParameter[] sqlParams = null) - { - return ExecuteNoQuery(db, sql, sqlParams); - } - /// - /// 执行存储过程返回IEnumerable数据集 - /// - public static IEnumerable ExecProcQuery(this DbContext db, string sql, DbParameter[] sqlParams = null) where T : new() - { - return Execute(db, sql, CommandType.StoredProcedure, sqlParams); - } - /// - /// 执行存储过程返回IEnumerable数据集 - /// - public static DataSet ExecProcDataSet(this DbContext db, string sql, DbParameter[] sqlParams = null) - { - return ExecuteDataSet(db, sql, CommandType.StoredProcedure, sqlParams); - } - /// - /// 执行sql返回IEnumerable数据集 - /// - public static IEnumerable ExecSqlQuery(this DbContext db, string sql, DbParameter[] sqlParams = null) where T : new() - { - return Execute(db, sql, CommandType.Text, sqlParams); - } - /// - /// 执行SQL并返回受影响的行数 - /// - /// - /// - /// - /// - private static int ExecuteNoQuery(this DbContext db, string sql, DbParameter[] sqlParams) - { - DbConnection connection = db.Database.GetDbConnection(); - DbCommand cmd = connection.CreateCommand(); - int result = 0; - db.Database.OpenConnection(); - cmd.CommandText = sql; - cmd.CommandType = CommandType.Text; - if (sqlParams != null) - { - cmd.Parameters.AddRange(sqlParams); - } - result = cmd.ExecuteNonQuery(); - db.Database.CloseConnection(); - return result; - } - /// - /// 执行SQL,返回查询结果 - /// - /// - /// - /// - /// - /// - /// - private static IEnumerable Execute(this DbContext db, string sql, CommandType type, DbParameter[] sqlParams) where T : new() - { - DbConnection connection = db.Database.GetDbConnection(); - DbCommand cmd = connection.CreateCommand(); - DataTable dt = new DataTable(); - try - { - db.Database.OpenConnection(); - cmd.CommandText = sql; - cmd.CommandType = type; - if (sqlParams != null) - { - cmd.Parameters.AddRange(sqlParams); - } - using (DbDataReader reader = cmd.ExecuteReader()) - { - dt.Load(reader); - } - } - finally - { - db.Database.CloseConnection(); - } - return dt.ToCollection(); - } - /// - /// 执行SQL,返回查询结果 - /// - /// - /// - /// - /// - /// - /// - private static DataSet ExecuteDataSet(this DbContext db, string sql, CommandType type, DbParameter[] sqlParams) - { - DbConnection connection = db.Database.GetDbConnection(); - DbCommand cmd = connection.CreateCommand(); - db.Database.OpenConnection(); - cmd.CommandText = sql; - cmd.CommandType = type; - if (sqlParams != null) - { - cmd.Parameters.AddRange(sqlParams); - } - DataSet ds = new DataSet(); - using (DbDataReader reader = cmd.ExecuteReader()) - { - ds.Load(reader,LoadOption.PreserveChanges,"data","info"); - } - db.Database.CloseConnection(); - return ds; - } - } - - /// - /// DataTable扩展类 - /// - /// - public static class ExtendDataTable - { - /// - /// 将对象转换成DataTable - /// - /// 源对象类型 - /// 源对象列表 - /// 转换后的DataTable - /// - public static DataTable ToDataTable(this IEnumerable data) - { - PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); - var table = new DataTable(); - foreach (PropertyDescriptor prop in properties) - table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); - foreach (T item in data) - { - DataRow row = table.NewRow(); - foreach (PropertyDescriptor prop in properties) - row[prop.Name] = prop.GetValue(item) ?? DBNull.Value; - table.Rows.Add(row); - } - return table; - } - - /// - /// 将DataTable首行转换成目标对象 - /// - /// 目标对象类型 - /// 源DataTable对象 - /// 转换后的目标对象 - /// - public static T ToEntity(this DataTable dt) where T : new() - { - IEnumerable entities = dt.ToCollection(); - return entities.FirstOrDefault(); - } - - /// - /// 将DataTable转换成目标对象列表 - /// - /// 目标对象类型 - /// 源DataTable对象 - /// 转换后的目标对象列表 - /// - public static IEnumerable ToCollection(this DataTable dt) where T : new() - { - if (dt == null || dt.Rows.Count == 0) - { - return Enumerable.Empty(); - } - IList ts = new List(); - // 获得此模型的类型 - Type type = typeof(T); - string tempName = string.Empty; - foreach (DataRow dr in dt.Rows) - { - T t = new T(); - PropertyInfo[] propertys = t.GetType().GetProperties(); - foreach (PropertyInfo pi in propertys) - { - tempName = pi.Name; - //检查DataTable是否包含此列(列名==对象的属性名) - if (dt.Columns.Contains(tempName)) - { - // 判断此属性是否有Setter - if (!pi.CanWrite) continue;//该属性不可写,直接跳出 - object value = dr[tempName]; - if (value != DBNull.Value) - { - if (!pi.PropertyType.IsGenericType) - { - value = Convert.ChangeType(value, pi.PropertyType); - pi.SetValue(t, value); - } - else { - Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition(); - if (genericTypeDefinition == typeof(Nullable<>)) - { - value = Convert.ChangeType(value, Nullable.GetUnderlyingType(pi.PropertyType)); - pi.SetValue(t, value); - } - } - } - } - } - ts.Add(t); - } - return ts; - } - } -} +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Data.Common; +using System.Linq; +using System.Reflection; + +namespace Hncore.Infrastructure.Extension +{ + /// + /// EF上下文对象扩展类 + /// + /// + public static class DbContextExtension + { + /// + /// 执行SQL返回受影响的行数 + /// + public static int ExecSqlNoQuery(this DbContext db, string sql, DbParameter[] sqlParams = null) + { + return ExecuteNoQuery(db, sql, sqlParams); + } + /// + /// 执行存储过程返回IEnumerable数据集 + /// + public static IEnumerable ExecProcQuery(this DbContext db, string sql, DbParameter[] sqlParams = null) where T : new() + { + return Execute(db, sql, CommandType.StoredProcedure, sqlParams); + } + /// + /// 执行存储过程返回IEnumerable数据集 + /// + public static DataSet ExecProcDataSet(this DbContext db, string sql, DbParameter[] sqlParams = null) + { + return ExecuteDataSet(db, sql, CommandType.StoredProcedure, sqlParams); + } + /// + /// 执行sql返回IEnumerable数据集 + /// + public static IEnumerable ExecSqlQuery(this DbContext db, string sql, DbParameter[] sqlParams = null) where T : new() + { + return Execute(db, sql, CommandType.Text, sqlParams); + } + /// + /// 执行SQL并返回受影响的行数 + /// + /// + /// + /// + /// + private static int ExecuteNoQuery(this DbContext db, string sql, DbParameter[] sqlParams) + { + DbConnection connection = db.Database.GetDbConnection(); + DbCommand cmd = connection.CreateCommand(); + int result = 0; + db.Database.OpenConnection(); + cmd.CommandText = sql; + cmd.CommandType = CommandType.Text; + if (sqlParams != null) + { + cmd.Parameters.AddRange(sqlParams); + } + result = cmd.ExecuteNonQuery(); + db.Database.CloseConnection(); + return result; + } + /// + /// 执行SQL,返回查询结果 + /// + /// + /// + /// + /// + /// + /// + private static IEnumerable Execute(this DbContext db, string sql, CommandType type, DbParameter[] sqlParams) where T : new() + { + DbConnection connection = db.Database.GetDbConnection(); + DbCommand cmd = connection.CreateCommand(); + DataTable dt = new DataTable(); + try + { + db.Database.OpenConnection(); + cmd.CommandText = sql; + cmd.CommandType = type; + if (sqlParams != null) + { + cmd.Parameters.AddRange(sqlParams); + } + using (DbDataReader reader = cmd.ExecuteReader()) + { + dt.Load(reader); + } + } + finally + { + db.Database.CloseConnection(); + } + return dt.ToCollection(); + } + /// + /// 执行SQL,返回查询结果 + /// + /// + /// + /// + /// + /// + /// + private static DataSet ExecuteDataSet(this DbContext db, string sql, CommandType type, DbParameter[] sqlParams) + { + DbConnection connection = db.Database.GetDbConnection(); + DbCommand cmd = connection.CreateCommand(); + db.Database.OpenConnection(); + cmd.CommandText = sql; + cmd.CommandType = type; + if (sqlParams != null) + { + cmd.Parameters.AddRange(sqlParams); + } + DataSet ds = new DataSet(); + using (DbDataReader reader = cmd.ExecuteReader()) + { + ds.Load(reader,LoadOption.PreserveChanges,"data","info"); + } + db.Database.CloseConnection(); + return ds; + } + } + + /// + /// DataTable扩展类 + /// + /// + public static class ExtendDataTable + { + /// + /// 将对象转换成DataTable + /// + /// 源对象类型 + /// 源对象列表 + /// 转换后的DataTable + /// + public static DataTable ToDataTable(this IEnumerable data) + { + PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); + var table = new DataTable(); + foreach (PropertyDescriptor prop in properties) + table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); + foreach (T item in data) + { + DataRow row = table.NewRow(); + foreach (PropertyDescriptor prop in properties) + row[prop.Name] = prop.GetValue(item) ?? DBNull.Value; + table.Rows.Add(row); + } + return table; + } + + /// + /// 将DataTable首行转换成目标对象 + /// + /// 目标对象类型 + /// 源DataTable对象 + /// 转换后的目标对象 + /// + public static T ToEntity(this DataTable dt) where T : new() + { + IEnumerable entities = dt.ToCollection(); + return entities.FirstOrDefault(); + } + + /// + /// 将DataTable转换成目标对象列表 + /// + /// 目标对象类型 + /// 源DataTable对象 + /// 转换后的目标对象列表 + /// + public static IEnumerable ToCollection(this DataTable dt) where T : new() + { + if (dt == null || dt.Rows.Count == 0) + { + return Enumerable.Empty(); + } + IList ts = new List(); + // 获得此模型的类型 + Type type = typeof(T); + string tempName = string.Empty; + foreach (DataRow dr in dt.Rows) + { + T t = new T(); + PropertyInfo[] propertys = t.GetType().GetProperties(); + foreach (PropertyInfo pi in propertys) + { + tempName = pi.Name; + //检查DataTable是否包含此列(列名==对象的属性名) + if (dt.Columns.Contains(tempName)) + { + // 判断此属性是否有Setter + if (!pi.CanWrite) continue;//该属性不可写,直接跳出 + object value = dr[tempName]; + if (value != DBNull.Value) + { + if (!pi.PropertyType.IsGenericType) + { + value = Convert.ChangeType(value, pi.PropertyType); + pi.SetValue(t, value); + } + else { + Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition(); + if (genericTypeDefinition == typeof(Nullable<>)) + { + value = Convert.ChangeType(value, Nullable.GetUnderlyingType(pi.PropertyType)); + pi.SetValue(t, value); + } + } + } + } + } + ts.Add(t); + } + return ts; + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/EF/DbSetExtension.cs b/Infrastructure/Hncore.Infrastructure/EF/DbSetExtension.cs index 954a49b..574bb9f 100644 --- a/Infrastructure/Hncore.Infrastructure/EF/DbSetExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/EF/DbSetExtension.cs @@ -1,122 +1,122 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using Hncore.Infrastructure.Data; -using Hncore.Infrastructure.DDD; -using Hncore.Infrastructure.EntitiesExtension; - -namespace Hncore.Infrastructure.EF -{ - public static class DbSetExtension - { - public static TEntity GetOne(this DbSet dbSet, Expression> exp) - where TEntity : class - { - return dbSet.AsNoTracking().FirstOrDefault(exp); - } - - public static Task GetOneAsync(this DbSet dbSet, - Expression> exp) where TEntity : class - { - return dbSet.AsNoTracking().FirstOrDefaultAsync(exp); - } - - public static PageData GetList(this DbSet dbSet, - Expression> exp, int pagesize, int pageindex, bool istotal) - where TEntity : class, IEntity - { - return dbSet.AsNoTracking() - .Where(exp) - .OrderByDescending(t => t.Id) - .ListPager(pagesize, pageindex, istotal); - } - - public static Task> GetListAsync(this DbSet dbSet, - Expression> exp, int pagesize, int pageindex, bool istotal) - where TEntity : class - { - return dbSet.AsNoTracking() - .Where(exp) - .ListPagerAsync(pagesize, pageindex, istotal); - } - - public static List GetList(this DbSet dbSet, Expression> exp) - where TEntity : class, IEntity - { - return dbSet.AsNoTracking() - .Where(exp) - .ToList(); - } - - public static Task> GetListAsync(this DbSet dbSet, - Expression> exp) - where TEntity : class, IEntity - { - return dbSet.AsNoTracking() - .Where(exp) - .ToListAsync(); - } - - public static IQueryable GetListQueryable(this DbSet dbSet, - Expression> exp) - where TEntity : class, IEntity - { - return dbSet.AsNoTracking() - .Where(exp); - } - - public static bool Exists(this DbSet dbSet, Expression> exp) - where TEntity : class, IEntity - { - return dbSet.AsNoTracking() - .Any(exp); - } - - public static Task ExistsAsync(this DbSet dbSet, - Expression> exp) - where TEntity : class, IEntity - { - return dbSet.AsNoTracking() - .AnyAsync(exp); - } - - public static List TopN(this DbSet dbSet, - Expression> condition, int topN) - where TEntity : class, IEntity - { - return dbSet.AsNoTracking() - .Where(condition) - .TopN(topN) - .ToList(); - } - - public static Task> TopNAsync(this DbSet dbSet, - Expression> condition, int topN) - where TEntity : class, IEntity - { - return dbSet.AsNoTracking() - .Where(condition) - .TopN(topN) - .ToListAsync(); - } - - public static IQueryable GetQueryable(this DbSet dbSet) where TEntity : class - { - return dbSet.AsNoTracking(); - } - - public static TEntity FindById(this DbSet dbSet,object id) where TEntity : class - { - return dbSet.Find(id); - } - - public static Task FindByIdAsync(this DbSet dbSet, object id) where TEntity : class - { - return dbSet.FindAsync(id); - } - - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Hncore.Infrastructure.Data; +using Hncore.Infrastructure.DDD; +using Hncore.Infrastructure.EntitiesExtension; + +namespace Hncore.Infrastructure.EF +{ + public static class DbSetExtension + { + public static TEntity GetOne(this DbSet dbSet, Expression> exp) + where TEntity : class + { + return dbSet.AsNoTracking().FirstOrDefault(exp); + } + + public static Task GetOneAsync(this DbSet dbSet, + Expression> exp) where TEntity : class + { + return dbSet.AsNoTracking().FirstOrDefaultAsync(exp); + } + + public static PageData GetList(this DbSet dbSet, + Expression> exp, int pagesize, int pageindex, bool istotal) + where TEntity : class, IEntity + { + return dbSet.AsNoTracking() + .Where(exp) + .OrderByDescending(t => t.Id) + .ListPager(pagesize, pageindex, istotal); + } + + public static Task> GetListAsync(this DbSet dbSet, + Expression> exp, int pagesize, int pageindex, bool istotal) + where TEntity : class + { + return dbSet.AsNoTracking() + .Where(exp) + .ListPagerAsync(pagesize, pageindex, istotal); + } + + public static List GetList(this DbSet dbSet, Expression> exp) + where TEntity : class, IEntity + { + return dbSet.AsNoTracking() + .Where(exp) + .ToList(); + } + + public static Task> GetListAsync(this DbSet dbSet, + Expression> exp) + where TEntity : class, IEntity + { + return dbSet.AsNoTracking() + .Where(exp) + .ToListAsync(); + } + + public static IQueryable GetListQueryable(this DbSet dbSet, + Expression> exp) + where TEntity : class, IEntity + { + return dbSet.AsNoTracking() + .Where(exp); + } + + public static bool Exists(this DbSet dbSet, Expression> exp) + where TEntity : class, IEntity + { + return dbSet.AsNoTracking() + .Any(exp); + } + + public static Task ExistsAsync(this DbSet dbSet, + Expression> exp) + where TEntity : class, IEntity + { + return dbSet.AsNoTracking() + .AnyAsync(exp); + } + + public static List TopN(this DbSet dbSet, + Expression> condition, int topN) + where TEntity : class, IEntity + { + return dbSet.AsNoTracking() + .Where(condition) + .TopN(topN) + .ToList(); + } + + public static Task> TopNAsync(this DbSet dbSet, + Expression> condition, int topN) + where TEntity : class, IEntity + { + return dbSet.AsNoTracking() + .Where(condition) + .TopN(topN) + .ToListAsync(); + } + + public static IQueryable GetQueryable(this DbSet dbSet) where TEntity : class + { + return dbSet.AsNoTracking(); + } + + public static TEntity FindById(this DbSet dbSet,object id) where TEntity : class + { + return dbSet.Find(id); + } + + public static Task FindByIdAsync(this DbSet dbSet, object id) where TEntity : class + { + return dbSet.FindAsync(id); + } + + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EF/EntityMapBase.cs b/Infrastructure/Hncore.Infrastructure/EF/EntityMapBase.cs index 56c8e9c..034d1fd 100644 --- a/Infrastructure/Hncore.Infrastructure/EF/EntityMapBase.cs +++ b/Infrastructure/Hncore.Infrastructure/EF/EntityMapBase.cs @@ -1,25 +1,25 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace Hncore.Infrastructure.EF -{ - public interface IEntityMap - { - void Map(ModelBuilder builder); - } - - public interface IEntityMap : IEntityMap where TEntityType : class - { - void Map(EntityTypeBuilder builder); - } - - public abstract class EntityMapBase : IEntityMap where T : class - { - public abstract void Map(EntityTypeBuilder builder); - - public void Map(ModelBuilder builder) - { - Map(builder.Entity()); - } - } +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Hncore.Infrastructure.EF +{ + public interface IEntityMap + { + void Map(ModelBuilder builder); + } + + public interface IEntityMap : IEntityMap where TEntityType : class + { + void Map(EntityTypeBuilder builder); + } + + public abstract class EntityMapBase : IEntityMap where T : class + { + public abstract void Map(EntityTypeBuilder builder); + + public void Map(ModelBuilder builder) + { + Map(builder.Entity()); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EF/Extensions/AutoMap.cs b/Infrastructure/Hncore.Infrastructure/EF/Extensions/AutoMap.cs index e5cd598..4652d83 100644 --- a/Infrastructure/Hncore.Infrastructure/EF/Extensions/AutoMap.cs +++ b/Infrastructure/Hncore.Infrastructure/EF/Extensions/AutoMap.cs @@ -1,47 +1,47 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Microsoft.EntityFrameworkCore; - -namespace Hncore.Infrastructure.EF -{ - public static class AutoMapExtensions - { - private static object syncRoot = new object(); - private static ConcurrentDictionary maps; - - public static void AutoMap(this ModelBuilder modelBuilder, Type assType) - { - if (maps == null) - { - lock (syncRoot) - { - if (maps == null) - { - maps = new ConcurrentDictionary(); - - Type mappingInterface = typeof(IEntityMap<>); - - var mappingTypes = assType.GetTypeInfo().Assembly.GetTypes() - .Where(x => !x.IsAbstract - && x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType - && y.GetGenericTypeDefinition() == - mappingInterface)); - - foreach (var map in mappingTypes.Select(Activator.CreateInstance).Cast()) - { - maps.TryAdd(map, null); - } - } - } - } - - foreach (var map in maps.Keys) - { - map.Map(modelBuilder); - } - } - } +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Microsoft.EntityFrameworkCore; + +namespace Hncore.Infrastructure.EF +{ + public static class AutoMapExtensions + { + private static object syncRoot = new object(); + private static ConcurrentDictionary maps; + + public static void AutoMap(this ModelBuilder modelBuilder, Type assType) + { + if (maps == null) + { + lock (syncRoot) + { + if (maps == null) + { + maps = new ConcurrentDictionary(); + + Type mappingInterface = typeof(IEntityMap<>); + + var mappingTypes = assType.GetTypeInfo().Assembly.GetTypes() + .Where(x => !x.IsAbstract + && x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType + && y.GetGenericTypeDefinition() == + mappingInterface)); + + foreach (var map in mappingTypes.Select(Activator.CreateInstance).Cast()) + { + maps.TryAdd(map, null); + } + } + } + } + + foreach (var map in maps.Keys) + { + map.Map(modelBuilder); + } + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EF/Extensions/DebugLog.cs b/Infrastructure/Hncore.Infrastructure/EF/Extensions/DebugLog.cs index f525444..3e4e997 100644 --- a/Infrastructure/Hncore.Infrastructure/EF/Extensions/DebugLog.cs +++ b/Infrastructure/Hncore.Infrastructure/EF/Extensions/DebugLog.cs @@ -1,121 +1,121 @@ -using System; -using System.Diagnostics; -using System.Linq; -using System.Text; -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Extension; -using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using Hncore.Infrastructure.Core.Web; - -namespace Hncore.Infrastructure.EF -{ - public class TraceLogger : ILogger - { - private readonly string categoryName; - private IHttpContextAccessor _httpContextAccessor; - - public TraceLogger(string categoryName, IHttpContextAccessor httpContextAccessor) - { - this.categoryName = categoryName; - this._httpContextAccessor = httpContextAccessor; - } - - public bool IsEnabled(LogLevel logLevel) => true; - - public void Log( - LogLevel logLevel, - EventId eventId, - TState state, - Exception exception, - Func formatter) - { - if (logLevel == LogLevel.Information && categoryName == "Microsoft.EntityFrameworkCore.Database.Command") - { - Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 执行sql:"); - - if (exception != null) - { - Console.WriteLine("发生异常:\n" + exception); - } - else - { - if (state.GetType().Name == "LogValues`6") - { - var paramText = state.GetType().GetField("_value1").GetValue(state).ToString(); - var sql = state.GetType().GetField("_value5").GetValue(state).ToString(); - - var paramList = paramText.RegexMatches("@__.*?='.*?'"); - - paramList.ForEach(param => - { - var arr = param.Split('='); - - sql = sql.Replace(arr[0], arr[1]); - }); - - Console.WriteLine(sql); - - if (_httpContextAccessor?.HttpContext?.Request?.Headers != null - && _httpContextAccessor.HttpContext.Request.Headers - .ContainsKey("enable-ef-log").ToBool()) - { - StringBuilder log = new StringBuilder(); - - log.Append("请求URL:" + _httpContextAccessor.HttpContext.Request.GetAbsoluteUri() + ""); - log.Append("\nMethod:" + _httpContextAccessor.HttpContext.Request.Method + "\n"); - if (_httpContextAccessor.HttpContext.Request.Method.ToLower() != "get") - { - log.Append("Body:\n" + _httpContextAccessor.HttpContext.Items["___requestbody"] + - "\n------------------------\n"); - } - else - { - log.Append("\n------------------------\n"); - } - - log.Append(sql); - - LogHelper.Debug("efcore日志", log.ToString()); - } - } - } - - //Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} {logLevel} {eventId.Id} {this.categoryName}"); - //Console.WriteLine(formatter(state, exception)); - } - } - - public IDisposable BeginScope(TState state) => null; - } - - public class TraceLoggerProvider : ILoggerProvider - { - private IHttpContextAccessor _httpContextAccessor; - - public TraceLoggerProvider(IHttpContextAccessor httpContextAccessor) - { - _httpContextAccessor = httpContextAccessor; - } - - public ILogger CreateLogger(string categoryName) => new TraceLogger(categoryName, _httpContextAccessor); - - public void Dispose() - { - } - } - - - public static class DebugLog - { - public static void EnableDebugTrace(this DbContextOptionsBuilder optionsBuilder, - IHttpContextAccessor httpContextAccessor) - { - LoggerFactory loggerFactory = new LoggerFactory(); - loggerFactory.AddProvider(new TraceLoggerProvider(httpContextAccessor)); - optionsBuilder.UseLoggerFactory(loggerFactory); - optionsBuilder.EnableSensitiveDataLogging(); - } - } +using System; +using System.Diagnostics; +using System.Linq; +using System.Text; +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Extension; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Hncore.Infrastructure.Core.Web; + +namespace Hncore.Infrastructure.EF +{ + public class TraceLogger : ILogger + { + private readonly string categoryName; + private IHttpContextAccessor _httpContextAccessor; + + public TraceLogger(string categoryName, IHttpContextAccessor httpContextAccessor) + { + this.categoryName = categoryName; + this._httpContextAccessor = httpContextAccessor; + } + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception exception, + Func formatter) + { + if (logLevel == LogLevel.Information && categoryName == "Microsoft.EntityFrameworkCore.Database.Command") + { + Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 执行sql:"); + + if (exception != null) + { + Console.WriteLine("发生异常:\n" + exception); + } + else + { + if (state.GetType().Name == "LogValues`6") + { + var paramText = state.GetType().GetField("_value1").GetValue(state).ToString(); + var sql = state.GetType().GetField("_value5").GetValue(state).ToString(); + + var paramList = paramText.RegexMatches("@__.*?='.*?'"); + + paramList.ForEach(param => + { + var arr = param.Split('='); + + sql = sql.Replace(arr[0], arr[1]); + }); + + Console.WriteLine(sql); + + if (_httpContextAccessor?.HttpContext?.Request?.Headers != null + && _httpContextAccessor.HttpContext.Request.Headers + .ContainsKey("enable-ef-log").ToBool()) + { + StringBuilder log = new StringBuilder(); + + log.Append("请求URL:" + _httpContextAccessor.HttpContext.Request.GetAbsoluteUri() + ""); + log.Append("\nMethod:" + _httpContextAccessor.HttpContext.Request.Method + "\n"); + if (_httpContextAccessor.HttpContext.Request.Method.ToLower() != "get") + { + log.Append("Body:\n" + _httpContextAccessor.HttpContext.Items["___requestbody"] + + "\n------------------------\n"); + } + else + { + log.Append("\n------------------------\n"); + } + + log.Append(sql); + + LogHelper.Debug("efcore日志", log.ToString()); + } + } + } + + //Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} {logLevel} {eventId.Id} {this.categoryName}"); + //Console.WriteLine(formatter(state, exception)); + } + } + + public IDisposable BeginScope(TState state) => null; + } + + public class TraceLoggerProvider : ILoggerProvider + { + private IHttpContextAccessor _httpContextAccessor; + + public TraceLoggerProvider(IHttpContextAccessor httpContextAccessor) + { + _httpContextAccessor = httpContextAccessor; + } + + public ILogger CreateLogger(string categoryName) => new TraceLogger(categoryName, _httpContextAccessor); + + public void Dispose() + { + } + } + + + public static class DebugLog + { + public static void EnableDebugTrace(this DbContextOptionsBuilder optionsBuilder, + IHttpContextAccessor httpContextAccessor) + { + LoggerFactory loggerFactory = new LoggerFactory(); + loggerFactory.AddProvider(new TraceLoggerProvider(httpContextAccessor)); + optionsBuilder.UseLoggerFactory(loggerFactory); + optionsBuilder.EnableSensitiveDataLogging(); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EF/Extensions/QueryFilter.cs b/Infrastructure/Hncore.Infrastructure/EF/Extensions/QueryFilter.cs index 741ba41..fe4cdcf 100644 --- a/Infrastructure/Hncore.Infrastructure/EF/Extensions/QueryFilter.cs +++ b/Infrastructure/Hncore.Infrastructure/EF/Extensions/QueryFilter.cs @@ -1,50 +1,50 @@ -using System; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Data; -using Hncore.Infrastructure.DDD; -using Hncore.Infrastructure.Serializer; -using Hncore.Infrastructure.WebApi; -using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using Microsoft.EntityFrameworkCore.Metadata.Internal; -using Remotion.Linq.Parsing.ExpressionVisitors; -using Hncore.Infrastructure.Core.Web; - -namespace Hncore.Infrastructure.EF -{ - public static class QueryFilterExtensions - { - public static void AddQueryFilter(this EntityTypeBuilder entityTypeBuilder, - Expression> expression) - { - var parameterType = Expression.Parameter(entityTypeBuilder.Metadata.ClrType); - var expressionFilter = ReplacingExpressionVisitor.Replace( - expression.Parameters.Single(), parameterType, expression.Body); - - var internalEntityTypeBuilder = entityTypeBuilder.GetInternalEntityTypeBuilder(); - if (internalEntityTypeBuilder.Metadata.QueryFilter != null) - { - var currentQueryFilter = internalEntityTypeBuilder.Metadata.QueryFilter; - var currentExpressionFilter = ReplacingExpressionVisitor.Replace( - currentQueryFilter.Parameters.Single(), parameterType, currentQueryFilter.Body); - expressionFilter = Expression.AndAlso(currentExpressionFilter, expressionFilter); - } - - var lambdaExpression = Expression.Lambda(expressionFilter, parameterType); - entityTypeBuilder.HasQueryFilter(lambdaExpression); - } - - internal static InternalEntityTypeBuilder GetInternalEntityTypeBuilder(this EntityTypeBuilder entityTypeBuilder) - { - var internalEntityTypeBuilder = typeof(EntityTypeBuilder) - .GetProperty("Builder", BindingFlags.NonPublic | BindingFlags.Instance)? - .GetValue(entityTypeBuilder) as InternalEntityTypeBuilder; - - return internalEntityTypeBuilder; - } - } +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Data; +using Hncore.Infrastructure.DDD; +using Hncore.Infrastructure.Serializer; +using Hncore.Infrastructure.WebApi; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Microsoft.EntityFrameworkCore.Metadata.Internal; +using Remotion.Linq.Parsing.ExpressionVisitors; +using Hncore.Infrastructure.Core.Web; + +namespace Hncore.Infrastructure.EF +{ + public static class QueryFilterExtensions + { + public static void AddQueryFilter(this EntityTypeBuilder entityTypeBuilder, + Expression> expression) + { + var parameterType = Expression.Parameter(entityTypeBuilder.Metadata.ClrType); + var expressionFilter = ReplacingExpressionVisitor.Replace( + expression.Parameters.Single(), parameterType, expression.Body); + + var internalEntityTypeBuilder = entityTypeBuilder.GetInternalEntityTypeBuilder(); + if (internalEntityTypeBuilder.Metadata.QueryFilter != null) + { + var currentQueryFilter = internalEntityTypeBuilder.Metadata.QueryFilter; + var currentExpressionFilter = ReplacingExpressionVisitor.Replace( + currentQueryFilter.Parameters.Single(), parameterType, currentQueryFilter.Body); + expressionFilter = Expression.AndAlso(currentExpressionFilter, expressionFilter); + } + + var lambdaExpression = Expression.Lambda(expressionFilter, parameterType); + entityTypeBuilder.HasQueryFilter(lambdaExpression); + } + + internal static InternalEntityTypeBuilder GetInternalEntityTypeBuilder(this EntityTypeBuilder entityTypeBuilder) + { + var internalEntityTypeBuilder = typeof(EntityTypeBuilder) + .GetProperty("Builder", BindingFlags.NonPublic | BindingFlags.Instance)? + .GetValue(entityTypeBuilder) as InternalEntityTypeBuilder; + + return internalEntityTypeBuilder; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EF/Extensions/Sql.cs b/Infrastructure/Hncore.Infrastructure/EF/Extensions/Sql.cs index 4663b23..be2a65a 100644 --- a/Infrastructure/Hncore.Infrastructure/EF/Extensions/Sql.cs +++ b/Infrastructure/Hncore.Infrastructure/EF/Extensions/Sql.cs @@ -1,196 +1,196 @@ -using System; -using System.Collections.Generic; -using System.Data.Common; -using System.Reflection; -using Microsoft.EntityFrameworkCore; - -namespace Hncore.Infrastructure.EF -{ - public static class Sql - { - /// - /// 执行Reader - /// - /// - /// - /// - public static void Reader(this DbContext dbContext, string sql, Action action) - { - var conn = dbContext.Database.GetDbConnection(); - - try - { - conn.Open(); - - using (var command = conn.CreateCommand()) - { - string query = sql; - - command.CommandText = query; - - using (DbDataReader reader = command.ExecuteReader()) - { - if (reader.HasRows) - { - while (reader.Read()) - { - action(reader); - } - } - } - } - } - finally - { - conn.Close(); - } - } - - /// - /// 执行Query - /// - /// - /// - /// - /// - public static List SqlQuery(this DbContext dbContext, string sql) - { - List list = new List(); - - var conn = dbContext.Database.GetDbConnection(); - - try - { - conn.Open(); - - using (var command = conn.CreateCommand()) - { - string query = sql; - - command.CommandText = query; - - using (DbDataReader reader = command.ExecuteReader()) - { - if (reader.HasRows) - { - list = reader.ReaderToList(); - } - } - } - } - finally - { - conn.Close(); - } - - - return list; - } - - /// - /// 执行Sql命令 - /// - /// - /// - /// - public static int ExecuteSql(this DbContext dbContext, string sql) - { - var conn = dbContext.Database.GetDbConnection(); - int rowAffected = 0; - try - { - conn.Open(); - - using (var command = conn.CreateCommand()) - { - command.CommandText = sql; - rowAffected = command.ExecuteNonQuery(); - } - } - finally - { - conn.Close(); - } - - return rowAffected; - } - - /// - /// DataReader转泛型 - /// - /// 传入的实体类 - /// DataReader对象 - /// - public static List ReaderToList(this DbDataReader objReader) - { - using (objReader) - { - List list = new List(); - - //获取传入的数据类型 - Type modelType = typeof(T); - - //遍历DataReader对象 - while (objReader.Read()) - { - //使用与指定参数匹配最高的构造函数,来创建指定类型的实例 - T model = Activator.CreateInstance(); - for (int i = 0; i < objReader.FieldCount; i++) - { - //判断字段值是否为空或不存在的值 - if (!IsNullOrDBNull(objReader[i])) - { - //匹配字段名 - PropertyInfo pi = modelType.GetProperty(objReader.GetName(i), - BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | - BindingFlags.IgnoreCase); - if (pi != null) - { - //绑定实体对象中同名的字段 - pi.SetValue(model, CheckType(objReader[i], pi.PropertyType), null); - } - } - } - - list.Add(model); - } - - return list; - } - } - - /// - /// 判断指定对象是否是有效值 - /// - /// - /// - private static bool IsNullOrDBNull(object obj) - { - return (obj == null || (obj is DBNull)) ? true : false; - } - - /// - /// 对可空类型进行判断转换 - /// - /// DataReader字段的值 - /// 该字段的类型 - /// - private static object CheckType(object value, Type conversionType) - { - if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) - { - if (value == null) - return null; - System.ComponentModel.NullableConverter nullableConverter = - new System.ComponentModel.NullableConverter(conversionType); - conversionType = nullableConverter.UnderlyingType; - } - - if (typeof(System.Enum).IsAssignableFrom(conversionType)) - { - return Enum.Parse(conversionType, value.ToString()); - } - return Convert.ChangeType(value, conversionType); - } - } +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Reflection; +using Microsoft.EntityFrameworkCore; + +namespace Hncore.Infrastructure.EF +{ + public static class Sql + { + /// + /// 执行Reader + /// + /// + /// + /// + public static void Reader(this DbContext dbContext, string sql, Action action) + { + var conn = dbContext.Database.GetDbConnection(); + + try + { + conn.Open(); + + using (var command = conn.CreateCommand()) + { + string query = sql; + + command.CommandText = query; + + using (DbDataReader reader = command.ExecuteReader()) + { + if (reader.HasRows) + { + while (reader.Read()) + { + action(reader); + } + } + } + } + } + finally + { + conn.Close(); + } + } + + /// + /// 执行Query + /// + /// + /// + /// + /// + public static List SqlQuery(this DbContext dbContext, string sql) + { + List list = new List(); + + var conn = dbContext.Database.GetDbConnection(); + + try + { + conn.Open(); + + using (var command = conn.CreateCommand()) + { + string query = sql; + + command.CommandText = query; + + using (DbDataReader reader = command.ExecuteReader()) + { + if (reader.HasRows) + { + list = reader.ReaderToList(); + } + } + } + } + finally + { + conn.Close(); + } + + + return list; + } + + /// + /// 执行Sql命令 + /// + /// + /// + /// + public static int ExecuteSql(this DbContext dbContext, string sql) + { + var conn = dbContext.Database.GetDbConnection(); + int rowAffected = 0; + try + { + conn.Open(); + + using (var command = conn.CreateCommand()) + { + command.CommandText = sql; + rowAffected = command.ExecuteNonQuery(); + } + } + finally + { + conn.Close(); + } + + return rowAffected; + } + + /// + /// DataReader转泛型 + /// + /// 传入的实体类 + /// DataReader对象 + /// + public static List ReaderToList(this DbDataReader objReader) + { + using (objReader) + { + List list = new List(); + + //获取传入的数据类型 + Type modelType = typeof(T); + + //遍历DataReader对象 + while (objReader.Read()) + { + //使用与指定参数匹配最高的构造函数,来创建指定类型的实例 + T model = Activator.CreateInstance(); + for (int i = 0; i < objReader.FieldCount; i++) + { + //判断字段值是否为空或不存在的值 + if (!IsNullOrDBNull(objReader[i])) + { + //匹配字段名 + PropertyInfo pi = modelType.GetProperty(objReader.GetName(i), + BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | + BindingFlags.IgnoreCase); + if (pi != null) + { + //绑定实体对象中同名的字段 + pi.SetValue(model, CheckType(objReader[i], pi.PropertyType), null); + } + } + } + + list.Add(model); + } + + return list; + } + } + + /// + /// 判断指定对象是否是有效值 + /// + /// + /// + private static bool IsNullOrDBNull(object obj) + { + return (obj == null || (obj is DBNull)) ? true : false; + } + + /// + /// 对可空类型进行判断转换 + /// + /// DataReader字段的值 + /// 该字段的类型 + /// + private static object CheckType(object value, Type conversionType) + { + if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) + { + if (value == null) + return null; + System.ComponentModel.NullableConverter nullableConverter = + new System.ComponentModel.NullableConverter(conversionType); + conversionType = nullableConverter.UnderlyingType; + } + + if (typeof(System.Enum).IsAssignableFrom(conversionType)) + { + return Enum.Parse(conversionType, value.ToString()); + } + return Convert.ChangeType(value, conversionType); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EF/IQueryDbContext.cs b/Infrastructure/Hncore.Infrastructure/EF/IQueryDbContext.cs index 3ef13a9..1780043 100644 --- a/Infrastructure/Hncore.Infrastructure/EF/IQueryDbContext.cs +++ b/Infrastructure/Hncore.Infrastructure/EF/IQueryDbContext.cs @@ -1,9 +1,9 @@ -using Microsoft.EntityFrameworkCore; - -namespace Hncore.Infrastructure.EF -{ - public interface IQueryDbContext - { - DbContext DbContext { get; } - } +using Microsoft.EntityFrameworkCore; + +namespace Hncore.Infrastructure.EF +{ + public interface IQueryDbContext + { + DbContext DbContext { get; } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EF/IRepositoryDbContext.cs b/Infrastructure/Hncore.Infrastructure/EF/IRepositoryDbContext.cs index 2e86775..6f54ff7 100644 --- a/Infrastructure/Hncore.Infrastructure/EF/IRepositoryDbContext.cs +++ b/Infrastructure/Hncore.Infrastructure/EF/IRepositoryDbContext.cs @@ -1,9 +1,9 @@ -using Microsoft.EntityFrameworkCore; - -namespace Hncore.Infrastructure.EF -{ - public interface IRepositoryDbContext - { - DbContext DbContext { get; } - } +using Microsoft.EntityFrameworkCore; + +namespace Hncore.Infrastructure.EF +{ + public interface IRepositoryDbContext + { + DbContext DbContext { get; } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EF/QueryBase.cs b/Infrastructure/Hncore.Infrastructure/EF/QueryBase.cs index 5e2b9e9..2537b59 100644 --- a/Infrastructure/Hncore.Infrastructure/EF/QueryBase.cs +++ b/Infrastructure/Hncore.Infrastructure/EF/QueryBase.cs @@ -1,90 +1,90 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using Hncore.Infrastructure.Data; -using Hncore.Infrastructure.DDD; - - -namespace Hncore.Infrastructure.EF -{ - public class QueryBase : IQuery where TEntity : class, IEntity - { - protected DbContext Dbcontext; - - public QueryBase(IQueryDbContext dbContext) - { - Dbcontext = dbContext.DbContext; - } - - public TEntity GetOne(Expression> condition) - { - return Dbcontext.GetOne(condition); - } - - public Task GetOneAsync(Expression> condition) - { - return Dbcontext.GetOneAsync(condition); - } - - public PageData GetList(Expression> condition, int pagesize, int pageindex, - bool istotal) - { - return Dbcontext.GetList(condition, pagesize, pageindex, istotal); - } - - public Task> GetListAsync(Expression> condition, int pagesize, - int pageindex, bool istotal) - { - return Dbcontext.GetListAsync(condition, pagesize, pageindex, istotal); - } - - public List GetList(Expression> condition) - { - return Dbcontext.GetList(condition); - } - - public Task> GetListAsync(Expression> condition) - { - return Dbcontext.GetListAsync(condition); - } - - public List TopN(Expression> condition, int topN) - { - return Dbcontext.TopN(condition, topN); - } - - public Task> TopNAsync(Expression> condition, int topN) - { - return Dbcontext.TopNAsync(condition, topN); - } - - public IQueryable GetListQueryable(Expression> exp) - { - return Dbcontext.GetListQueryable(exp); - } - - public bool Exists(Expression> exp) - { - return Dbcontext.Exists(exp); - } - - public Task ExistsAsync(Expression> condition) - { - return Dbcontext.ExistsAsync(condition); - } - - public IQueryable GetQueryable() - { - return Dbcontext.Set().AsNoTracking(); - } - public DbContext DbContext() - { - return Dbcontext; - } - - - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Hncore.Infrastructure.Data; +using Hncore.Infrastructure.DDD; + + +namespace Hncore.Infrastructure.EF +{ + public class QueryBase : IQuery where TEntity : class, IEntity + { + protected DbContext Dbcontext; + + public QueryBase(IQueryDbContext dbContext) + { + Dbcontext = dbContext.DbContext; + } + + public TEntity GetOne(Expression> condition) + { + return Dbcontext.GetOne(condition); + } + + public Task GetOneAsync(Expression> condition) + { + return Dbcontext.GetOneAsync(condition); + } + + public PageData GetList(Expression> condition, int pagesize, int pageindex, + bool istotal) + { + return Dbcontext.GetList(condition, pagesize, pageindex, istotal); + } + + public Task> GetListAsync(Expression> condition, int pagesize, + int pageindex, bool istotal) + { + return Dbcontext.GetListAsync(condition, pagesize, pageindex, istotal); + } + + public List GetList(Expression> condition) + { + return Dbcontext.GetList(condition); + } + + public Task> GetListAsync(Expression> condition) + { + return Dbcontext.GetListAsync(condition); + } + + public List TopN(Expression> condition, int topN) + { + return Dbcontext.TopN(condition, topN); + } + + public Task> TopNAsync(Expression> condition, int topN) + { + return Dbcontext.TopNAsync(condition, topN); + } + + public IQueryable GetListQueryable(Expression> exp) + { + return Dbcontext.GetListQueryable(exp); + } + + public bool Exists(Expression> exp) + { + return Dbcontext.Exists(exp); + } + + public Task ExistsAsync(Expression> condition) + { + return Dbcontext.ExistsAsync(condition); + } + + public IQueryable GetQueryable() + { + return Dbcontext.Set().AsNoTracking(); + } + public DbContext DbContext() + { + return Dbcontext; + } + + + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EF/QueryExtension.cs b/Infrastructure/Hncore.Infrastructure/EF/QueryExtension.cs index ff85a9c..6eb330b 100644 --- a/Infrastructure/Hncore.Infrastructure/EF/QueryExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/EF/QueryExtension.cs @@ -1,110 +1,110 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using Hncore.Infrastructure.Data; -using Hncore.Infrastructure.DDD; -using Hncore.Infrastructure.EntitiesExtension; - -namespace Hncore.Infrastructure.EF -{ - public static class QueryExtension - { - public static TEntity GetOne(this DbContext dbcontext, Expression> exp) - where TEntity : class, IEntity - { - return dbcontext.Set().AsNoTracking() - .FirstOrDefault(exp); - } - - public static Task GetOneAsync(this DbContext dbcontext, - Expression> exp) where TEntity : class, IEntity - { - return dbcontext.Set().AsNoTracking() - .FirstOrDefaultAsync(exp); - } - - public static PageData GetList(this DbContext dbcontext, - Expression> exp, int pagesize, int pageindex, bool istotal) - where TEntity : class, IEntity - { - return dbcontext.Set().AsNoTracking() - .Where(exp) - .OrderByDescending(t => t.Id) - .ListPager(pagesize, pageindex, istotal); - } - - public static Task> GetListAsync(this DbContext dbcontext, - Expression> exp, int pagesize, int pageindex, bool istotal) - where TEntity : class, IEntity - { - return dbcontext.Set().AsNoTracking() - .Where(exp) - .OrderByDescending(t => t.Id) - .ListPagerAsync(pagesize, pageindex, istotal); - } - - public static List GetList(this DbContext dbcontext, Expression> exp) - where TEntity : class, IEntity - { - return dbcontext.Set().AsNoTracking() - .Where(exp) - .ToList(); - } - - public static Task> GetListAsync(this DbContext dbcontext, - Expression> exp) - where TEntity : class, IEntity - { - return dbcontext.Set().AsNoTracking() - .Where(exp) - .ToListAsync(); - } - - public static IQueryable GetListQueryable(this DbContext dbcontext, - Expression> exp) - where TEntity : class, IEntity - { - return dbcontext.Set().AsNoTracking() - .Where(exp); - } - - public static bool Exists(this DbContext dbcontext, Expression> exp) - where TEntity : class, IEntity - { - return dbcontext.Set().AsNoTracking() - .Any(exp); - } - - public static Task ExistsAsync(this DbContext dbcontext, - Expression> exp) - where TEntity : class, IEntity - { - return dbcontext.Set().AsNoTracking() - .AnyAsync(exp); - } - - public static List TopN(this DbContext dbcontext, - Expression> condition, int topN) - where TEntity : class, IEntity - { - return dbcontext.Set().AsNoTracking() - .Where(condition) - .TopN(topN) - .ToList(); - } - - public static Task> TopNAsync(this DbContext dbcontext, - Expression> condition, int topN) - where TEntity : class, IEntity - { - return dbcontext.Set().AsNoTracking() - .Where(condition) - .TopN(topN) - .ToListAsync(); - } - - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Hncore.Infrastructure.Data; +using Hncore.Infrastructure.DDD; +using Hncore.Infrastructure.EntitiesExtension; + +namespace Hncore.Infrastructure.EF +{ + public static class QueryExtension + { + public static TEntity GetOne(this DbContext dbcontext, Expression> exp) + where TEntity : class, IEntity + { + return dbcontext.Set().AsNoTracking() + .FirstOrDefault(exp); + } + + public static Task GetOneAsync(this DbContext dbcontext, + Expression> exp) where TEntity : class, IEntity + { + return dbcontext.Set().AsNoTracking() + .FirstOrDefaultAsync(exp); + } + + public static PageData GetList(this DbContext dbcontext, + Expression> exp, int pagesize, int pageindex, bool istotal) + where TEntity : class, IEntity + { + return dbcontext.Set().AsNoTracking() + .Where(exp) + .OrderByDescending(t => t.Id) + .ListPager(pagesize, pageindex, istotal); + } + + public static Task> GetListAsync(this DbContext dbcontext, + Expression> exp, int pagesize, int pageindex, bool istotal) + where TEntity : class, IEntity + { + return dbcontext.Set().AsNoTracking() + .Where(exp) + .OrderByDescending(t => t.Id) + .ListPagerAsync(pagesize, pageindex, istotal); + } + + public static List GetList(this DbContext dbcontext, Expression> exp) + where TEntity : class, IEntity + { + return dbcontext.Set().AsNoTracking() + .Where(exp) + .ToList(); + } + + public static Task> GetListAsync(this DbContext dbcontext, + Expression> exp) + where TEntity : class, IEntity + { + return dbcontext.Set().AsNoTracking() + .Where(exp) + .ToListAsync(); + } + + public static IQueryable GetListQueryable(this DbContext dbcontext, + Expression> exp) + where TEntity : class, IEntity + { + return dbcontext.Set().AsNoTracking() + .Where(exp); + } + + public static bool Exists(this DbContext dbcontext, Expression> exp) + where TEntity : class, IEntity + { + return dbcontext.Set().AsNoTracking() + .Any(exp); + } + + public static Task ExistsAsync(this DbContext dbcontext, + Expression> exp) + where TEntity : class, IEntity + { + return dbcontext.Set().AsNoTracking() + .AnyAsync(exp); + } + + public static List TopN(this DbContext dbcontext, + Expression> condition, int topN) + where TEntity : class, IEntity + { + return dbcontext.Set().AsNoTracking() + .Where(condition) + .TopN(topN) + .ToList(); + } + + public static Task> TopNAsync(this DbContext dbcontext, + Expression> condition, int topN) + where TEntity : class, IEntity + { + return dbcontext.Set().AsNoTracking() + .Where(condition) + .TopN(topN) + .ToListAsync(); + } + + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EF/RepositoryBase.cs b/Infrastructure/Hncore.Infrastructure/EF/RepositoryBase.cs index 16cb9d7..63e44b5 100644 --- a/Infrastructure/Hncore.Infrastructure/EF/RepositoryBase.cs +++ b/Infrastructure/Hncore.Infrastructure/EF/RepositoryBase.cs @@ -1,90 +1,90 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using Hncore.Infrastructure.DDD; -using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore.ChangeTracking; - -namespace Hncore.Infrastructure.EF -{ - public class RepositoryBase : IRepository - where TEntity : Entity - { - protected DbContext Dbcontext; - - public RepositoryBase(IRepositoryDbContext dbContext) - { - Dbcontext = dbContext.DbContext; - } - - public TEntity FindById(TId id) - { - return Dbcontext.Set().Find(id); - } - - public Task FindByIdAsync(TId id) - { - return Dbcontext.Set().FindAsync(id); - } - - public void Add(TEntity entity) - { - Dbcontext.Set().Add(entity); - } - - - public Task AddAsync(TEntity entity) - { - return Dbcontext.Set().AddAsync(entity); - } - /// - /// 批量添加 - /// - /// - public void AddRange(List entity) - { - Dbcontext.Set().AddRange(entity); - } - /// - /// 批量添加 - /// - /// - public Task AddRangeAsync(List entity) - { - return Dbcontext.Set().AddRangeAsync(entity); - } - /// - /// 批量修改 - /// - /// - public void UpdateRange(List entity) - { - Dbcontext.Set().UpdateRange(entity); - } - /// - /// 批量删除 - /// - /// - public void RemoveRange(List entity) - { - Dbcontext.Set().RemoveRange(entity); - } - - public void Remove(TEntity entity) - { - Dbcontext.Set().Remove(entity); - } - public void Update(TEntity entity) - { - Dbcontext.Set().Update(entity); - } - - public IQueryable GetQueryable() - { - return Dbcontext.Set(); - } - - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Hncore.Infrastructure.DDD; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore.ChangeTracking; + +namespace Hncore.Infrastructure.EF +{ + public class RepositoryBase : IRepository + where TEntity : Entity + { + protected DbContext Dbcontext; + + public RepositoryBase(IRepositoryDbContext dbContext) + { + Dbcontext = dbContext.DbContext; + } + + public TEntity FindById(TId id) + { + return Dbcontext.Set().Find(id); + } + + public Task FindByIdAsync(TId id) + { + return Dbcontext.Set().FindAsync(id); + } + + public void Add(TEntity entity) + { + Dbcontext.Set().Add(entity); + } + + + public Task AddAsync(TEntity entity) + { + return Dbcontext.Set().AddAsync(entity); + } + /// + /// 批量添加 + /// + /// + public void AddRange(List entity) + { + Dbcontext.Set().AddRange(entity); + } + /// + /// 批量添加 + /// + /// + public Task AddRangeAsync(List entity) + { + return Dbcontext.Set().AddRangeAsync(entity); + } + /// + /// 批量修改 + /// + /// + public void UpdateRange(List entity) + { + Dbcontext.Set().UpdateRange(entity); + } + /// + /// 批量删除 + /// + /// + public void RemoveRange(List entity) + { + Dbcontext.Set().RemoveRange(entity); + } + + public void Remove(TEntity entity) + { + Dbcontext.Set().Remove(entity); + } + public void Update(TEntity entity) + { + Dbcontext.Set().Update(entity); + } + + public IQueryable GetQueryable() + { + return Dbcontext.Set(); + } + + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EF/迁移命令.txt b/Infrastructure/Hncore.Infrastructure/EF/迁移命令.txt index f5dacca..ebcba70 100644 --- a/Infrastructure/Hncore.Infrastructure/EF/迁移命令.txt +++ b/Infrastructure/Hncore.Infrastructure/EF/迁移命令.txt @@ -1,13 +1,13 @@ -vs -Add-Migration -Update-Database - - - -cli -dotnet ef migrations add init - -dotnet ef database update - -输出脚本 +vs +Add-Migration +Update-Database + + + +cli +dotnet ef migrations add init + +dotnet ef database update + +输出脚本 dotnet ef migrations script \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EntitiesExtension/CommonEqualityComparer.cs b/Infrastructure/Hncore.Infrastructure/EntitiesExtension/CommonEqualityComparer.cs index 3aca6ff..d50da74 100644 --- a/Infrastructure/Hncore.Infrastructure/EntitiesExtension/CommonEqualityComparer.cs +++ b/Infrastructure/Hncore.Infrastructure/EntitiesExtension/CommonEqualityComparer.cs @@ -1,48 +1,48 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Hncore.Infrastructure.EntitiesExtension -{ - public class CommonEqualityComparer : IEqualityComparer - { - private Func keySelector; - private IEqualityComparer comparer; - - public CommonEqualityComparer(Func keySelector, IEqualityComparer comparer) - { - this.keySelector = keySelector; - this.comparer = comparer; - } - - public CommonEqualityComparer(Func keySelector) - : this(keySelector, EqualityComparer.Default) - { } - - public bool Equals(T x, T y) - { - return comparer.Equals(keySelector(x), keySelector(y)); - } - - public int GetHashCode(T obj) - { - return comparer.GetHashCode(keySelector(obj)); - } - } - /// - /// 扩展类 - /// - public static class DistinctExtensions - { - public static IEnumerable Distinctx(this IEnumerable source, Func keySelector) - { - return source.Distinct(new CommonEqualityComparer(keySelector)); - } - - public static IEnumerable Distinctx(this IEnumerable source, Func keySelector, IEqualityComparer comparer) - { - return source.Distinct(new CommonEqualityComparer(keySelector, comparer)); - } - } - -} +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Hncore.Infrastructure.EntitiesExtension +{ + public class CommonEqualityComparer : IEqualityComparer + { + private Func keySelector; + private IEqualityComparer comparer; + + public CommonEqualityComparer(Func keySelector, IEqualityComparer comparer) + { + this.keySelector = keySelector; + this.comparer = comparer; + } + + public CommonEqualityComparer(Func keySelector) + : this(keySelector, EqualityComparer.Default) + { } + + public bool Equals(T x, T y) + { + return comparer.Equals(keySelector(x), keySelector(y)); + } + + public int GetHashCode(T obj) + { + return comparer.GetHashCode(keySelector(obj)); + } + } + /// + /// 扩展类 + /// + public static class DistinctExtensions + { + public static IEnumerable Distinctx(this IEnumerable source, Func keySelector) + { + return source.Distinct(new CommonEqualityComparer(keySelector)); + } + + public static IEnumerable Distinctx(this IEnumerable source, Func keySelector, IEqualityComparer comparer) + { + return source.Distinct(new CommonEqualityComparer(keySelector, comparer)); + } + } + +} diff --git a/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ConditionBuilder.cs b/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ConditionBuilder.cs index 0d1bdd8..81690a7 100644 --- a/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ConditionBuilder.cs +++ b/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ConditionBuilder.cs @@ -1,144 +1,144 @@ -using System; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Reflection; - -namespace Hncore.Infrastructure.EntitiesExtension -{ - internal class ConditionBuilder : ExpressionVisitor - { - private List m_arguments; - private Stack m_conditionParts; - - public string Condition { get; private set; } - - public object[] Arguments { get; private set; } - - public void Build(Expression expression) - { - PartialEvaluator evaluator = new PartialEvaluator(); - Expression evaluatedExpression = evaluator.Eval(expression); - - this.m_arguments = new List(); - this.m_conditionParts = new Stack(); - - this.Visit(evaluatedExpression); - - this.Arguments = this.m_arguments.ToArray(); - this.Condition = this.m_conditionParts.Count > 0 ? this.m_conditionParts.Pop() : null; - } - - protected override Expression VisitBinary(BinaryExpression b) - { - if (b == null) return b; - - string opr; - switch (b.NodeType) - { - case ExpressionType.Equal: - opr = "="; - break; - case ExpressionType.NotEqual: - opr = "<>"; - break; - case ExpressionType.GreaterThan: - opr = ">"; - break; - case ExpressionType.GreaterThanOrEqual: - opr = ">="; - break; - case ExpressionType.LessThan: - opr = "<"; - break; - case ExpressionType.LessThanOrEqual: - opr = "<="; - break; - case ExpressionType.AndAlso: - opr = "AND"; - break; - case ExpressionType.OrElse: - opr = "OR"; - break; - case ExpressionType.Add: - opr = "+"; - break; - case ExpressionType.Subtract: - opr = "-"; - break; - case ExpressionType.Multiply: - opr = "*"; - break; - case ExpressionType.Divide: - opr = "/"; - break; - default: - throw new NotSupportedException(b.NodeType + "is not supported."); - } - - this.Visit(b.Left); - this.Visit(b.Right); - - string right = this.m_conditionParts.Pop(); - string left = this.m_conditionParts.Pop(); - - string condition = String.Format("({0} {1} {2})", left, opr, right); - this.m_conditionParts.Push(condition); - - return b; - } - - protected override Expression VisitConstant(ConstantExpression c) - { - if (c == null) return c; - - this.m_arguments.Add(c.Value); - this.m_conditionParts.Push(String.Format("{{{0}}}", this.m_arguments.Count - 1)); - - return c; - } - - protected override Expression VisitMemberAccess(MemberExpression m) - { - if (m == null) return m; - - PropertyInfo propertyInfo = m.Member as PropertyInfo; - if (propertyInfo == null) return m; - - this.m_conditionParts.Push(String.Format("[{0}]", propertyInfo.Name)); - - return m; - } - - protected override Expression VisitMethodCall(MethodCallExpression m) - { - if (m == null) return m; - - string format; - switch (m.Method.Name) - { - case "StartsWith": - format = "({0} LIKE {1}+'%')"; - break; - - case "Contains": - format = "({0} LIKE '%'+{1}+'%')"; - break; - - case "EndsWith": - format = "({0} LIKE '%'+{1})"; - break; - - default: - throw new NotSupportedException(m.NodeType + " is not supported!"); - } - - this.Visit(m.Object); - this.Visit(m.Arguments[0]); - string right = this.m_conditionParts.Pop(); - string left = this.m_conditionParts.Pop(); - this.m_conditionParts.Push(String.Format(format, left, right)); - - return m; - } - } -} +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using System.Reflection; + +namespace Hncore.Infrastructure.EntitiesExtension +{ + internal class ConditionBuilder : ExpressionVisitor + { + private List m_arguments; + private Stack m_conditionParts; + + public string Condition { get; private set; } + + public object[] Arguments { get; private set; } + + public void Build(Expression expression) + { + PartialEvaluator evaluator = new PartialEvaluator(); + Expression evaluatedExpression = evaluator.Eval(expression); + + this.m_arguments = new List(); + this.m_conditionParts = new Stack(); + + this.Visit(evaluatedExpression); + + this.Arguments = this.m_arguments.ToArray(); + this.Condition = this.m_conditionParts.Count > 0 ? this.m_conditionParts.Pop() : null; + } + + protected override Expression VisitBinary(BinaryExpression b) + { + if (b == null) return b; + + string opr; + switch (b.NodeType) + { + case ExpressionType.Equal: + opr = "="; + break; + case ExpressionType.NotEqual: + opr = "<>"; + break; + case ExpressionType.GreaterThan: + opr = ">"; + break; + case ExpressionType.GreaterThanOrEqual: + opr = ">="; + break; + case ExpressionType.LessThan: + opr = "<"; + break; + case ExpressionType.LessThanOrEqual: + opr = "<="; + break; + case ExpressionType.AndAlso: + opr = "AND"; + break; + case ExpressionType.OrElse: + opr = "OR"; + break; + case ExpressionType.Add: + opr = "+"; + break; + case ExpressionType.Subtract: + opr = "-"; + break; + case ExpressionType.Multiply: + opr = "*"; + break; + case ExpressionType.Divide: + opr = "/"; + break; + default: + throw new NotSupportedException(b.NodeType + "is not supported."); + } + + this.Visit(b.Left); + this.Visit(b.Right); + + string right = this.m_conditionParts.Pop(); + string left = this.m_conditionParts.Pop(); + + string condition = String.Format("({0} {1} {2})", left, opr, right); + this.m_conditionParts.Push(condition); + + return b; + } + + protected override Expression VisitConstant(ConstantExpression c) + { + if (c == null) return c; + + this.m_arguments.Add(c.Value); + this.m_conditionParts.Push(String.Format("{{{0}}}", this.m_arguments.Count - 1)); + + return c; + } + + protected override Expression VisitMemberAccess(MemberExpression m) + { + if (m == null) return m; + + PropertyInfo propertyInfo = m.Member as PropertyInfo; + if (propertyInfo == null) return m; + + this.m_conditionParts.Push(String.Format("[{0}]", propertyInfo.Name)); + + return m; + } + + protected override Expression VisitMethodCall(MethodCallExpression m) + { + if (m == null) return m; + + string format; + switch (m.Method.Name) + { + case "StartsWith": + format = "({0} LIKE {1}+'%')"; + break; + + case "Contains": + format = "({0} LIKE '%'+{1}+'%')"; + break; + + case "EndsWith": + format = "({0} LIKE '%'+{1})"; + break; + + default: + throw new NotSupportedException(m.NodeType + " is not supported!"); + } + + this.Visit(m.Object); + this.Visit(m.Arguments[0]); + string right = this.m_conditionParts.Pop(); + string left = this.m_conditionParts.Pop(); + this.m_conditionParts.Push(String.Format(format, left, right)); + + return m; + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ExpressionBuilder.cs b/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ExpressionBuilder.cs index f0bd712..b3d6a70 100644 --- a/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ExpressionBuilder.cs +++ b/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ExpressionBuilder.cs @@ -1,53 +1,53 @@ -using System; -using System.Linq; -using System.Linq.Expressions; - -namespace Hncore.Infrastructure.EntitiesExtension -{ - /// - /// Extension methods for add And and Or with parameters rebinder - /// - public static class ExpressionBuilder - { - /// - /// Compose two expression and merge all in a new expression - /// - /// Type of params in expression - /// Expression instance - /// Expression to merge - /// Function to merge - /// New merged expressions - public static Expression Compose(this Expression first, Expression second, Func merge) - { - // 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); - - // replace parameters in the second lambda expression with parameters from the first - var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); - // apply composition of lambda expression bodies to parameters from the first expression - return Expression.Lambda(merge(first.Body, secondBody), first.Parameters); - } - /// - /// And operator - /// - /// Type of params in expression - /// Right Expression in AND operation - /// Left Expression in And operation - /// New AND expression - public static Expression> And(this Expression> first, Expression> second) - { - return first.Compose(second, Expression.AndAlso); - } - /// - /// Or operator - /// - /// Type of param in expression - /// Right expression in OR operation - /// Left expression in OR operation - /// New Or expressions - public static Expression> Or(this Expression> first, Expression> second) - { - return first.Compose(second, Expression.Or); - } - } -} +using System; +using System.Linq; +using System.Linq.Expressions; + +namespace Hncore.Infrastructure.EntitiesExtension +{ + /// + /// Extension methods for add And and Or with parameters rebinder + /// + public static class ExpressionBuilder + { + /// + /// Compose two expression and merge all in a new expression + /// + /// Type of params in expression + /// Expression instance + /// Expression to merge + /// Function to merge + /// New merged expressions + public static Expression Compose(this Expression first, Expression second, Func merge) + { + // 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); + + // replace parameters in the second lambda expression with parameters from the first + var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); + // apply composition of lambda expression bodies to parameters from the first expression + return Expression.Lambda(merge(first.Body, secondBody), first.Parameters); + } + /// + /// And operator + /// + /// Type of params in expression + /// Right Expression in AND operation + /// Left Expression in And operation + /// New AND expression + public static Expression> And(this Expression> first, Expression> second) + { + return first.Compose(second, Expression.AndAlso); + } + /// + /// Or operator + /// + /// Type of param in expression + /// Right expression in OR operation + /// Left expression in OR operation + /// New Or expressions + public static Expression> Or(this Expression> first, Expression> second) + { + return first.Compose(second, Expression.Or); + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ExpressionVisitor.cs b/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ExpressionVisitor.cs index af4436f..dc7914a 100644 --- a/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ExpressionVisitor.cs +++ b/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ExpressionVisitor.cs @@ -1,364 +1,364 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq.Expressions; - -namespace Hncore.Infrastructure.EntitiesExtension -{ - public abstract class ExpressionVisitor - { - protected ExpressionVisitor() { } - - protected virtual Expression Visit(Expression exp) - { - if (exp == null) - return exp; - switch (exp.NodeType) - { - case ExpressionType.Negate: - case ExpressionType.NegateChecked: - case ExpressionType.Not: - case ExpressionType.Convert: - case ExpressionType.ConvertChecked: - case ExpressionType.ArrayLength: - case ExpressionType.Quote: - case ExpressionType.TypeAs: - return this.VisitUnary((UnaryExpression)exp); - case ExpressionType.Add: - case ExpressionType.AddChecked: - case ExpressionType.Subtract: - case ExpressionType.SubtractChecked: - case ExpressionType.Multiply: - case ExpressionType.MultiplyChecked: - case ExpressionType.Divide: - case ExpressionType.Modulo: - case ExpressionType.And: - case ExpressionType.AndAlso: - case ExpressionType.Or: - case ExpressionType.OrElse: - case ExpressionType.LessThan: - case ExpressionType.LessThanOrEqual: - case ExpressionType.GreaterThan: - case ExpressionType.GreaterThanOrEqual: - case ExpressionType.Equal: - case ExpressionType.NotEqual: - case ExpressionType.Coalesce: - case ExpressionType.ArrayIndex: - case ExpressionType.RightShift: - case ExpressionType.LeftShift: - case ExpressionType.ExclusiveOr: - return this.VisitBinary((BinaryExpression)exp); - case ExpressionType.TypeIs: - return this.VisitTypeIs((TypeBinaryExpression)exp); - case ExpressionType.Conditional: - return this.VisitConditional((ConditionalExpression)exp); - case ExpressionType.Constant: - return this.VisitConstant((ConstantExpression)exp); - case ExpressionType.Parameter: - return this.VisitParameter((ParameterExpression)exp); - case ExpressionType.MemberAccess: - return this.VisitMemberAccess((MemberExpression)exp); - case ExpressionType.Call: - return this.VisitMethodCall((MethodCallExpression)exp); - case ExpressionType.Lambda: - return this.VisitLambda((LambdaExpression)exp); - case ExpressionType.New: - return this.VisitNew((NewExpression)exp); - case ExpressionType.NewArrayInit: - case ExpressionType.NewArrayBounds: - return this.VisitNewArray((NewArrayExpression)exp); - case ExpressionType.Invoke: - return this.VisitInvocation((InvocationExpression)exp); - case ExpressionType.MemberInit: - return this.VisitMemberInit((MemberInitExpression)exp); - case ExpressionType.ListInit: - return this.VisitListInit((ListInitExpression)exp); - default: - throw new Exception(string.Format("Unhandled expression type: '{0}'", exp.NodeType)); - } - } - - protected virtual MemberBinding VisitBinding(MemberBinding binding) - { - switch (binding.BindingType) - { - case MemberBindingType.Assignment: - return this.VisitMemberAssignment((MemberAssignment)binding); - case MemberBindingType.MemberBinding: - return this.VisitMemberMemberBinding((MemberMemberBinding)binding); - case MemberBindingType.ListBinding: - return this.VisitMemberListBinding((MemberListBinding)binding); - default: - throw new Exception(string.Format("Unhandled binding type '{0}'", binding.BindingType)); - } - } - - protected virtual ElementInit VisitElementInitializer(ElementInit initializer) - { - ReadOnlyCollection arguments = this.VisitExpressionList(initializer.Arguments); - if (arguments != initializer.Arguments) - { - return Expression.ElementInit(initializer.AddMethod, arguments); - } - return initializer; - } - - protected virtual Expression VisitUnary(UnaryExpression u) - { - Expression operand = this.Visit(u.Operand); - if (operand != u.Operand) - { - return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method); - } - return u; - } - - protected virtual Expression VisitBinary(BinaryExpression b) - { - Expression left = this.Visit(b.Left); - Expression right = this.Visit(b.Right); - Expression conversion = this.Visit(b.Conversion); - if (left != b.Left || right != b.Right || conversion != b.Conversion) - { - if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null) - return Expression.Coalesce(left, right, conversion as LambdaExpression); - else - return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method); - } - return b; - } - - protected virtual Expression VisitTypeIs(TypeBinaryExpression b) - { - Expression expr = this.Visit(b.Expression); - if (expr != b.Expression) - { - return Expression.TypeIs(expr, b.TypeOperand); - } - return b; - } - - protected virtual Expression VisitConstant(ConstantExpression c) - { - return c; - } - - protected virtual Expression VisitConditional(ConditionalExpression c) - { - Expression test = this.Visit(c.Test); - Expression ifTrue = this.Visit(c.IfTrue); - Expression ifFalse = this.Visit(c.IfFalse); - if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse) - { - return Expression.Condition(test, ifTrue, ifFalse); - } - return c; - } - - protected virtual Expression VisitParameter(ParameterExpression p) - { - return p; - } - - protected virtual Expression VisitMemberAccess(MemberExpression m) - { - Expression exp = this.Visit(m.Expression); - if (exp != m.Expression) - { - return Expression.MakeMemberAccess(exp, m.Member); - } - return m; - } - - protected virtual Expression VisitMethodCall(MethodCallExpression m) - { - Expression obj = this.Visit(m.Object); - IEnumerable args = this.VisitExpressionList(m.Arguments); - if (obj != m.Object || args != m.Arguments) - { - return Expression.Call(obj, m.Method, args); - } - return m; - } - - protected virtual ReadOnlyCollection VisitExpressionList(ReadOnlyCollection original) - { - List list = null; - for (int i = 0, n = original.Count; i < n; i++) - { - Expression p = this.Visit(original[i]); - if (list != null) - { - list.Add(p); - } - else if (p != original[i]) - { - list = new List(n); - for (int j = 0; j < i; j++) - { - list.Add(original[j]); - } - list.Add(p); - } - } - if (list != null) - { - return list.AsReadOnly(); - } - return original; - } - - protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment) - { - Expression e = this.Visit(assignment.Expression); - if (e != assignment.Expression) - { - return Expression.Bind(assignment.Member, e); - } - return assignment; - } - - protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) - { - IEnumerable bindings = this.VisitBindingList(binding.Bindings); - if (bindings != binding.Bindings) - { - return Expression.MemberBind(binding.Member, bindings); - } - return binding; - } - - protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding) - { - IEnumerable initializers = this.VisitElementInitializerList(binding.Initializers); - if (initializers != binding.Initializers) - { - return Expression.ListBind(binding.Member, initializers); - } - return binding; - } - - protected virtual IEnumerable VisitBindingList(ReadOnlyCollection original) - { - List list = null; - for (int i = 0, n = original.Count; i < n; i++) - { - MemberBinding b = this.VisitBinding(original[i]); - if (list != null) - { - list.Add(b); - } - else if (b != original[i]) - { - list = new List(n); - for (int j = 0; j < i; j++) - { - list.Add(original[j]); - } - list.Add(b); - } - } - if (list != null) - return list; - return original; - } - - protected virtual IEnumerable VisitElementInitializerList(ReadOnlyCollection original) - { - List list = null; - for (int i = 0, n = original.Count; i < n; i++) - { - ElementInit init = this.VisitElementInitializer(original[i]); - if (list != null) - { - list.Add(init); - } - else if (init != original[i]) - { - list = new List(n); - for (int j = 0; j < i; j++) - { - list.Add(original[j]); - } - list.Add(init); - } - } - if (list != null) - return list; - return original; - } - - protected virtual Expression VisitLambda(LambdaExpression lambda) - { - Expression body = this.Visit(lambda.Body); - if (body != lambda.Body) - { - return Expression.Lambda(lambda.Type, body, lambda.Parameters); - } - return lambda; - } - - protected virtual NewExpression VisitNew(NewExpression nex) - { - IEnumerable args = this.VisitExpressionList(nex.Arguments); - if (args != nex.Arguments) - { - if (nex.Members != null) - return Expression.New(nex.Constructor, args, nex.Members); - else - return Expression.New(nex.Constructor, args); - } - return nex; - } - - protected virtual Expression VisitMemberInit(MemberInitExpression init) - { - NewExpression n = this.VisitNew(init.NewExpression); - IEnumerable bindings = this.VisitBindingList(init.Bindings); - if (n != init.NewExpression || bindings != init.Bindings) - { - return Expression.MemberInit(n, bindings); - } - return init; - } - - protected virtual Expression VisitListInit(ListInitExpression init) - { - NewExpression n = this.VisitNew(init.NewExpression); - IEnumerable initializers = this.VisitElementInitializerList(init.Initializers); - if (n != init.NewExpression || initializers != init.Initializers) - { - return Expression.ListInit(n, initializers); - } - return init; - } - - protected virtual Expression VisitNewArray(NewArrayExpression na) - { - IEnumerable exprs = this.VisitExpressionList(na.Expressions); - if (exprs != na.Expressions) - { - if (na.NodeType == ExpressionType.NewArrayInit) - { - return Expression.NewArrayInit(na.Type.GetElementType(), exprs); - } - else - { - return Expression.NewArrayBounds(na.Type.GetElementType(), exprs); - } - } - return na; - } - - protected virtual Expression VisitInvocation(InvocationExpression iv) - { - IEnumerable args = this.VisitExpressionList(iv.Arguments); - Expression expr = this.Visit(iv.Expression); - if (args != iv.Arguments || expr != iv.Expression) - { - return Expression.Invoke(expr, args); - } - return iv; - } - } -} +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq.Expressions; + +namespace Hncore.Infrastructure.EntitiesExtension +{ + public abstract class ExpressionVisitor + { + protected ExpressionVisitor() { } + + protected virtual Expression Visit(Expression exp) + { + if (exp == null) + return exp; + switch (exp.NodeType) + { + case ExpressionType.Negate: + case ExpressionType.NegateChecked: + case ExpressionType.Not: + case ExpressionType.Convert: + case ExpressionType.ConvertChecked: + case ExpressionType.ArrayLength: + case ExpressionType.Quote: + case ExpressionType.TypeAs: + return this.VisitUnary((UnaryExpression)exp); + case ExpressionType.Add: + case ExpressionType.AddChecked: + case ExpressionType.Subtract: + case ExpressionType.SubtractChecked: + case ExpressionType.Multiply: + case ExpressionType.MultiplyChecked: + case ExpressionType.Divide: + case ExpressionType.Modulo: + case ExpressionType.And: + case ExpressionType.AndAlso: + case ExpressionType.Or: + case ExpressionType.OrElse: + case ExpressionType.LessThan: + case ExpressionType.LessThanOrEqual: + case ExpressionType.GreaterThan: + case ExpressionType.GreaterThanOrEqual: + case ExpressionType.Equal: + case ExpressionType.NotEqual: + case ExpressionType.Coalesce: + case ExpressionType.ArrayIndex: + case ExpressionType.RightShift: + case ExpressionType.LeftShift: + case ExpressionType.ExclusiveOr: + return this.VisitBinary((BinaryExpression)exp); + case ExpressionType.TypeIs: + return this.VisitTypeIs((TypeBinaryExpression)exp); + case ExpressionType.Conditional: + return this.VisitConditional((ConditionalExpression)exp); + case ExpressionType.Constant: + return this.VisitConstant((ConstantExpression)exp); + case ExpressionType.Parameter: + return this.VisitParameter((ParameterExpression)exp); + case ExpressionType.MemberAccess: + return this.VisitMemberAccess((MemberExpression)exp); + case ExpressionType.Call: + return this.VisitMethodCall((MethodCallExpression)exp); + case ExpressionType.Lambda: + return this.VisitLambda((LambdaExpression)exp); + case ExpressionType.New: + return this.VisitNew((NewExpression)exp); + case ExpressionType.NewArrayInit: + case ExpressionType.NewArrayBounds: + return this.VisitNewArray((NewArrayExpression)exp); + case ExpressionType.Invoke: + return this.VisitInvocation((InvocationExpression)exp); + case ExpressionType.MemberInit: + return this.VisitMemberInit((MemberInitExpression)exp); + case ExpressionType.ListInit: + return this.VisitListInit((ListInitExpression)exp); + default: + throw new Exception(string.Format("Unhandled expression type: '{0}'", exp.NodeType)); + } + } + + protected virtual MemberBinding VisitBinding(MemberBinding binding) + { + switch (binding.BindingType) + { + case MemberBindingType.Assignment: + return this.VisitMemberAssignment((MemberAssignment)binding); + case MemberBindingType.MemberBinding: + return this.VisitMemberMemberBinding((MemberMemberBinding)binding); + case MemberBindingType.ListBinding: + return this.VisitMemberListBinding((MemberListBinding)binding); + default: + throw new Exception(string.Format("Unhandled binding type '{0}'", binding.BindingType)); + } + } + + protected virtual ElementInit VisitElementInitializer(ElementInit initializer) + { + ReadOnlyCollection arguments = this.VisitExpressionList(initializer.Arguments); + if (arguments != initializer.Arguments) + { + return Expression.ElementInit(initializer.AddMethod, arguments); + } + return initializer; + } + + protected virtual Expression VisitUnary(UnaryExpression u) + { + Expression operand = this.Visit(u.Operand); + if (operand != u.Operand) + { + return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method); + } + return u; + } + + protected virtual Expression VisitBinary(BinaryExpression b) + { + Expression left = this.Visit(b.Left); + Expression right = this.Visit(b.Right); + Expression conversion = this.Visit(b.Conversion); + if (left != b.Left || right != b.Right || conversion != b.Conversion) + { + if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null) + return Expression.Coalesce(left, right, conversion as LambdaExpression); + else + return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method); + } + return b; + } + + protected virtual Expression VisitTypeIs(TypeBinaryExpression b) + { + Expression expr = this.Visit(b.Expression); + if (expr != b.Expression) + { + return Expression.TypeIs(expr, b.TypeOperand); + } + return b; + } + + protected virtual Expression VisitConstant(ConstantExpression c) + { + return c; + } + + protected virtual Expression VisitConditional(ConditionalExpression c) + { + Expression test = this.Visit(c.Test); + Expression ifTrue = this.Visit(c.IfTrue); + Expression ifFalse = this.Visit(c.IfFalse); + if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse) + { + return Expression.Condition(test, ifTrue, ifFalse); + } + return c; + } + + protected virtual Expression VisitParameter(ParameterExpression p) + { + return p; + } + + protected virtual Expression VisitMemberAccess(MemberExpression m) + { + Expression exp = this.Visit(m.Expression); + if (exp != m.Expression) + { + return Expression.MakeMemberAccess(exp, m.Member); + } + return m; + } + + protected virtual Expression VisitMethodCall(MethodCallExpression m) + { + Expression obj = this.Visit(m.Object); + IEnumerable args = this.VisitExpressionList(m.Arguments); + if (obj != m.Object || args != m.Arguments) + { + return Expression.Call(obj, m.Method, args); + } + return m; + } + + protected virtual ReadOnlyCollection VisitExpressionList(ReadOnlyCollection original) + { + List list = null; + for (int i = 0, n = original.Count; i < n; i++) + { + Expression p = this.Visit(original[i]); + if (list != null) + { + list.Add(p); + } + else if (p != original[i]) + { + list = new List(n); + for (int j = 0; j < i; j++) + { + list.Add(original[j]); + } + list.Add(p); + } + } + if (list != null) + { + return list.AsReadOnly(); + } + return original; + } + + protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment) + { + Expression e = this.Visit(assignment.Expression); + if (e != assignment.Expression) + { + return Expression.Bind(assignment.Member, e); + } + return assignment; + } + + protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) + { + IEnumerable bindings = this.VisitBindingList(binding.Bindings); + if (bindings != binding.Bindings) + { + return Expression.MemberBind(binding.Member, bindings); + } + return binding; + } + + protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding) + { + IEnumerable initializers = this.VisitElementInitializerList(binding.Initializers); + if (initializers != binding.Initializers) + { + return Expression.ListBind(binding.Member, initializers); + } + return binding; + } + + protected virtual IEnumerable VisitBindingList(ReadOnlyCollection original) + { + List list = null; + for (int i = 0, n = original.Count; i < n; i++) + { + MemberBinding b = this.VisitBinding(original[i]); + if (list != null) + { + list.Add(b); + } + else if (b != original[i]) + { + list = new List(n); + for (int j = 0; j < i; j++) + { + list.Add(original[j]); + } + list.Add(b); + } + } + if (list != null) + return list; + return original; + } + + protected virtual IEnumerable VisitElementInitializerList(ReadOnlyCollection original) + { + List list = null; + for (int i = 0, n = original.Count; i < n; i++) + { + ElementInit init = this.VisitElementInitializer(original[i]); + if (list != null) + { + list.Add(init); + } + else if (init != original[i]) + { + list = new List(n); + for (int j = 0; j < i; j++) + { + list.Add(original[j]); + } + list.Add(init); + } + } + if (list != null) + return list; + return original; + } + + protected virtual Expression VisitLambda(LambdaExpression lambda) + { + Expression body = this.Visit(lambda.Body); + if (body != lambda.Body) + { + return Expression.Lambda(lambda.Type, body, lambda.Parameters); + } + return lambda; + } + + protected virtual NewExpression VisitNew(NewExpression nex) + { + IEnumerable args = this.VisitExpressionList(nex.Arguments); + if (args != nex.Arguments) + { + if (nex.Members != null) + return Expression.New(nex.Constructor, args, nex.Members); + else + return Expression.New(nex.Constructor, args); + } + return nex; + } + + protected virtual Expression VisitMemberInit(MemberInitExpression init) + { + NewExpression n = this.VisitNew(init.NewExpression); + IEnumerable bindings = this.VisitBindingList(init.Bindings); + if (n != init.NewExpression || bindings != init.Bindings) + { + return Expression.MemberInit(n, bindings); + } + return init; + } + + protected virtual Expression VisitListInit(ListInitExpression init) + { + NewExpression n = this.VisitNew(init.NewExpression); + IEnumerable initializers = this.VisitElementInitializerList(init.Initializers); + if (n != init.NewExpression || initializers != init.Initializers) + { + return Expression.ListInit(n, initializers); + } + return init; + } + + protected virtual Expression VisitNewArray(NewArrayExpression na) + { + IEnumerable exprs = this.VisitExpressionList(na.Expressions); + if (exprs != na.Expressions) + { + if (na.NodeType == ExpressionType.NewArrayInit) + { + return Expression.NewArrayInit(na.Type.GetElementType(), exprs); + } + else + { + return Expression.NewArrayBounds(na.Type.GetElementType(), exprs); + } + } + return na; + } + + protected virtual Expression VisitInvocation(InvocationExpression iv) + { + IEnumerable args = this.VisitExpressionList(iv.Arguments); + Expression expr = this.Visit(iv.Expression); + if (args != iv.Arguments || expr != iv.Expression) + { + return Expression.Invoke(expr, args); + } + return iv; + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/EntitiesExtension/IQueryableExtend.cs b/Infrastructure/Hncore.Infrastructure/EntitiesExtension/IQueryableExtend.cs index 217207d..4024cb2 100644 --- a/Infrastructure/Hncore.Infrastructure/EntitiesExtension/IQueryableExtend.cs +++ b/Infrastructure/Hncore.Infrastructure/EntitiesExtension/IQueryableExtend.cs @@ -1,107 +1,107 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Hncore.Infrastructure.Data; -using Hncore.Infrastructure.Extension; -using Microsoft.EntityFrameworkCore; - -namespace Hncore.Infrastructure.EntitiesExtension -{ - public static class IQueryableExtend - { - #region 返回IQueryable前几条数据 - - /// - /// 返回IQueryable前几条数据 - /// - /// - /// - /// - /// - public static IQueryable TopN(this IQueryable query, int TopN) - { - return query.Take(TopN); - } - - #endregion - - #region 对IQueryable进行分页 - - /// - /// 对IQueryable进行分页 - /// - /// - /// - /// 每页多少条数据 - /// 当前页 - /// - public static IQueryable QueryPager(this IQueryable query, int PageSize, int PageIndex) - { - if (PageIndex <= 0) - { - PageIndex = 1; - } - - if (PageSize <= 0) - { - PageSize = 1; - } - - if (PageSize > 0) - return query.Skip((PageIndex - 1) * PageSize).Take(PageSize); - return query; - } - - #endregion - - #region 得到IQueryable的分页后实体集合 - - /// - /// 得到IQueryable的分页后实体集合 - /// - /// - /// 每页多少条数据 - /// 当前页 - /// 是否统计总行数 - /// - public static PageData ListPager(this IQueryable query, int pageSize, int pageIndex, bool isTotal) - { - PageData list = new PageData(); - - if (isTotal) - { - list.RowCount = query.Count(); - } - - list.List = query.QueryPager(pageSize, pageIndex).ToList(); - - return list; - } - - /// - /// 得到IQueryable的分页后实体集合 - /// - /// - /// 每页多少条数据 - /// 当前页 - /// 是否统计总行数 - /// - public static async Task> ListPagerAsync(this IQueryable query, int pageSize, int pageIndex, - bool isTotal) - { - PageData list = new PageData(); - - if (isTotal) - { - list.RowCount = await query.CountAsync(); - } - - list.List = await query.QueryPager(pageSize, pageIndex).ToListAsync(); - - return list; - } - - #endregion - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Hncore.Infrastructure.Data; +using Hncore.Infrastructure.Extension; +using Microsoft.EntityFrameworkCore; + +namespace Hncore.Infrastructure.EntitiesExtension +{ + public static class IQueryableExtend + { + #region 返回IQueryable前几条数据 + + /// + /// 返回IQueryable前几条数据 + /// + /// + /// + /// + /// + public static IQueryable TopN(this IQueryable query, int TopN) + { + return query.Take(TopN); + } + + #endregion + + #region 对IQueryable进行分页 + + /// + /// 对IQueryable进行分页 + /// + /// + /// + /// 每页多少条数据 + /// 当前页 + /// + public static IQueryable QueryPager(this IQueryable query, int PageSize, int PageIndex) + { + if (PageIndex <= 0) + { + PageIndex = 1; + } + + if (PageSize <= 0) + { + PageSize = 1; + } + + if (PageSize > 0) + return query.Skip((PageIndex - 1) * PageSize).Take(PageSize); + return query; + } + + #endregion + + #region 得到IQueryable的分页后实体集合 + + /// + /// 得到IQueryable的分页后实体集合 + /// + /// + /// 每页多少条数据 + /// 当前页 + /// 是否统计总行数 + /// + public static PageData ListPager(this IQueryable query, int pageSize, int pageIndex, bool isTotal) + { + PageData list = new PageData(); + + if (isTotal) + { + list.RowCount = query.Count(); + } + + list.List = query.QueryPager(pageSize, pageIndex).ToList(); + + return list; + } + + /// + /// 得到IQueryable的分页后实体集合 + /// + /// + /// 每页多少条数据 + /// 当前页 + /// 是否统计总行数 + /// + public static async Task> ListPagerAsync(this IQueryable query, int pageSize, int pageIndex, + bool isTotal) + { + PageData list = new PageData(); + + if (isTotal) + { + list.RowCount = await query.CountAsync(); + } + + list.List = await query.QueryPager(pageSize, pageIndex).ToListAsync(); + + return list; + } + + #endregion + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ParameterRebinder.cs b/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ParameterRebinder.cs index 305ca0d..040a991 100644 --- a/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ParameterRebinder.cs +++ b/Infrastructure/Hncore.Infrastructure/EntitiesExtension/ParameterRebinder.cs @@ -1,44 +1,44 @@ -using System.Collections.Generic; -using System.Linq.Expressions; - -namespace Hncore.Infrastructure.EntitiesExtension -{ - public class ParameterRebinder : ExpressionVisitor - { - private readonly Dictionary map; - - /// - /// Default construcotr - /// - /// Map specification - public ParameterRebinder(Dictionary map) - { - this.map = map ?? new Dictionary(); - } - /// - /// Replate parameters in expression with a Map information - /// - /// Map information - /// Expression to replace parameters - /// Expression with parameters replaced - public static Expression ReplaceParameters(Dictionary map, Expression exp) - { - return new ParameterRebinder(map).Visit(exp); - } - /// - /// Visit pattern method - /// - /// A Parameter expression - /// New visited expression - protected override Expression VisitParameter(ParameterExpression p) - { - ParameterExpression replacement; - if (map.TryGetValue(p, out replacement)) - { - p = replacement; - } - - return base.VisitParameter(p); - } - } -} +using System.Collections.Generic; +using System.Linq.Expressions; + +namespace Hncore.Infrastructure.EntitiesExtension +{ + public class ParameterRebinder : ExpressionVisitor + { + private readonly Dictionary map; + + /// + /// Default construcotr + /// + /// Map specification + public ParameterRebinder(Dictionary map) + { + this.map = map ?? new Dictionary(); + } + /// + /// Replate parameters in expression with a Map information + /// + /// Map information + /// Expression to replace parameters + /// Expression with parameters replaced + public static Expression ReplaceParameters(Dictionary map, Expression exp) + { + return new ParameterRebinder(map).Visit(exp); + } + /// + /// Visit pattern method + /// + /// A Parameter expression + /// New visited expression + protected override Expression VisitParameter(ParameterExpression p) + { + ParameterExpression replacement; + if (map.TryGetValue(p, out replacement)) + { + p = replacement; + } + + return base.VisitParameter(p); + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/EntitiesExtension/PartialEvaluator.cs b/Infrastructure/Hncore.Infrastructure/EntitiesExtension/PartialEvaluator.cs index 3288771..9503d06 100644 --- a/Infrastructure/Hncore.Infrastructure/EntitiesExtension/PartialEvaluator.cs +++ b/Infrastructure/Hncore.Infrastructure/EntitiesExtension/PartialEvaluator.cs @@ -1,115 +1,115 @@ -using System; -using System.Collections.Generic; -using System.Linq.Expressions; - -namespace Hncore.Infrastructure.EntitiesExtension -{ - public class PartialEvaluator : ExpressionVisitor - { - private Func m_fnCanBeEvaluated; - private HashSet m_candidates; - - public PartialEvaluator() - : this(CanBeEvaluatedLocally) - { } - - public PartialEvaluator(Func fnCanBeEvaluated) - { - this.m_fnCanBeEvaluated = fnCanBeEvaluated; - } - - public Expression Eval(Expression exp) - { - this.m_candidates = new Nominator(this.m_fnCanBeEvaluated).Nominate(exp); - - return this.Visit(exp); - } - - protected override Expression Visit(Expression exp) - { - if (exp == null) - { - return null; - } - - if (this.m_candidates.Contains(exp)) - { - return this.Evaluate(exp); - } - - return base.Visit(exp); - } - - private Expression Evaluate(Expression e) - { - if (e.NodeType == ExpressionType.Constant) - { - return e; - } - - LambdaExpression lambda = Expression.Lambda(e); - Delegate fn = lambda.Compile(); - - return Expression.Constant(fn.DynamicInvoke(null), e.Type); - } - - private static bool CanBeEvaluatedLocally(Expression exp) - { - return exp.NodeType != ExpressionType.Parameter; - } - - #region Nominator - - /// - /// Performs bottom-up analysis to determine which nodes can possibly - /// be part of an evaluated sub-tree. - /// - private class Nominator : ExpressionVisitor - { - private Func m_fnCanBeEvaluated; - private HashSet m_candidates; - private bool m_cannotBeEvaluated; - - internal Nominator(Func fnCanBeEvaluated) - { - this.m_fnCanBeEvaluated = fnCanBeEvaluated; - } - - internal HashSet Nominate(Expression expression) - { - this.m_candidates = new HashSet(); - this.Visit(expression); - return this.m_candidates; - } - - protected override Expression Visit(Expression expression) - { - if (expression != null) - { - bool saveCannotBeEvaluated = this.m_cannotBeEvaluated; - this.m_cannotBeEvaluated = false; - - base.Visit(expression); - - if (!this.m_cannotBeEvaluated) - { - if (this.m_fnCanBeEvaluated(expression)) - { - this.m_candidates.Add(expression); - } - else - { - this.m_cannotBeEvaluated = true; - } - } - - this.m_cannotBeEvaluated |= saveCannotBeEvaluated; - } - - return expression; - } - } - - #endregion - } -} +using System; +using System.Collections.Generic; +using System.Linq.Expressions; + +namespace Hncore.Infrastructure.EntitiesExtension +{ + public class PartialEvaluator : ExpressionVisitor + { + private Func m_fnCanBeEvaluated; + private HashSet m_candidates; + + public PartialEvaluator() + : this(CanBeEvaluatedLocally) + { } + + public PartialEvaluator(Func fnCanBeEvaluated) + { + this.m_fnCanBeEvaluated = fnCanBeEvaluated; + } + + public Expression Eval(Expression exp) + { + this.m_candidates = new Nominator(this.m_fnCanBeEvaluated).Nominate(exp); + + return this.Visit(exp); + } + + protected override Expression Visit(Expression exp) + { + if (exp == null) + { + return null; + } + + if (this.m_candidates.Contains(exp)) + { + return this.Evaluate(exp); + } + + return base.Visit(exp); + } + + private Expression Evaluate(Expression e) + { + if (e.NodeType == ExpressionType.Constant) + { + return e; + } + + LambdaExpression lambda = Expression.Lambda(e); + Delegate fn = lambda.Compile(); + + return Expression.Constant(fn.DynamicInvoke(null), e.Type); + } + + private static bool CanBeEvaluatedLocally(Expression exp) + { + return exp.NodeType != ExpressionType.Parameter; + } + + #region Nominator + + /// + /// Performs bottom-up analysis to determine which nodes can possibly + /// be part of an evaluated sub-tree. + /// + private class Nominator : ExpressionVisitor + { + private Func m_fnCanBeEvaluated; + private HashSet m_candidates; + private bool m_cannotBeEvaluated; + + internal Nominator(Func fnCanBeEvaluated) + { + this.m_fnCanBeEvaluated = fnCanBeEvaluated; + } + + internal HashSet Nominate(Expression expression) + { + this.m_candidates = new HashSet(); + this.Visit(expression); + return this.m_candidates; + } + + protected override Expression Visit(Expression expression) + { + if (expression != null) + { + bool saveCannotBeEvaluated = this.m_cannotBeEvaluated; + this.m_cannotBeEvaluated = false; + + base.Visit(expression); + + if (!this.m_cannotBeEvaluated) + { + if (this.m_fnCanBeEvaluated(expression)) + { + this.m_candidates.Add(expression); + } + else + { + this.m_cannotBeEvaluated = true; + } + } + + this.m_cannotBeEvaluated |= saveCannotBeEvaluated; + } + + return expression; + } + } + + #endregion + } +} diff --git a/Infrastructure/Hncore.Infrastructure/EventBus/ActionEventHandler.cs b/Infrastructure/Hncore.Infrastructure/EventBus/ActionEventHandler.cs index f20722b..fce6539 100644 --- a/Infrastructure/Hncore.Infrastructure/EventBus/ActionEventHandler.cs +++ b/Infrastructure/Hncore.Infrastructure/EventBus/ActionEventHandler.cs @@ -1,24 +1,24 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Hncore.Infrastructure.Events -{ - internal class ActionEventHandler : IEventHandler where TEventData : IEventData - { - public Action Action { get; private set; } - - public virtual bool Ansyc { get; set; } - - public ActionEventHandler(Action handler) - { - Action = handler; - } - public void HandleEvent(TEventData eventData) - { - Action(eventData); - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Hncore.Infrastructure.Events +{ + internal class ActionEventHandler : IEventHandler where TEventData : IEventData + { + public Action Action { get; private set; } + + public virtual bool Ansyc { get; set; } + + public ActionEventHandler(Action handler) + { + Action = handler; + } + public void HandleEvent(TEventData eventData) + { + Action(eventData); + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/EventBus/EventBus.cs b/Infrastructure/Hncore.Infrastructure/EventBus/EventBus.cs index 0c4ef4c..1f66587 100644 --- a/Infrastructure/Hncore.Infrastructure/EventBus/EventBus.cs +++ b/Infrastructure/Hncore.Infrastructure/EventBus/EventBus.cs @@ -1,150 +1,150 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; - -namespace Hncore.Infrastructure.Events -{ - /// - /// 事件总线 - /// - public class EventBus - { - private static EventBus _eventBus = null; - - public static EventBus Default - { - get { return _eventBus ?? (_eventBus = new EventBus()); } - } - - /// - /// 定义线程安全集合 - /// - private readonly ConcurrentDictionary> _eventAndHandlerMapping; - - public EventBus() - { - _eventAndHandlerMapping = new ConcurrentDictionary>(); - MapEventToHandler(); - } - - /// - ///通过反射,将事件源与事件处理绑定 - /// - private void MapEventToHandler() - { - // Assembly assembly = Assembly.GetEntryAssembly(); - - var allAssembly = AppDomain.CurrentDomain.GetAssemblies().Where(item => item.FullName.Contains("Microkj.")); - if (!allAssembly.Any()) - { - return; - } - - foreach (var assembly in allAssembly) - { - foreach (var type in assembly.GetTypes()) - { - if (!type.IsGenericType && typeof(IEventHandler).IsAssignableFrom(type)) //判断当前类型是否实现了IEventHandler接口 - { - Type handlerInterface = type.GetInterface("IEventHandler`1"); //获取该类实现的泛型接口 - if (handlerInterface != null) - { - Type eventDataType = handlerInterface.GetGenericArguments()[0]; // 获取泛型接口指定的参数类型 - - if (_eventAndHandlerMapping.ContainsKey(eventDataType)) - { - List handlerTypes = _eventAndHandlerMapping[eventDataType]; - handlerTypes.Add(Activator.CreateInstance(type) as IEventHandler); - _eventAndHandlerMapping[eventDataType] = handlerTypes; - } - else - { - var handlerTypes = new List - { - Activator.CreateInstance(type) as IEventHandler - }; - _eventAndHandlerMapping[eventDataType] = handlerTypes; - } - } - } - } - } - } - - /// - /// 手动绑定事件源与事件处理 - /// - /// - /// - public void Register(IEventHandler eventHandler) - { - if (_eventAndHandlerMapping.Keys.Contains(typeof (TEventData))) - { - List handlerTypes = _eventAndHandlerMapping[typeof (TEventData)]; - if (!handlerTypes.Contains(eventHandler)) - { - handlerTypes.Add(eventHandler); - _eventAndHandlerMapping[typeof (TEventData)] = handlerTypes; - } - } - else - { - _eventAndHandlerMapping.GetOrAdd(typeof (TEventData), (type) => new List()) - .Add(eventHandler); - } - } - - - public void Register(Action action) where TEventData : IEventData - { - var actionHandler = new ActionEventHandler(action); - Register(actionHandler); - } - - /// - /// 手动解除事件源与事件处理的绑定 - /// - /// - /// - public void UnRegister(Type eventHandler) - { - List handlerTypes = _eventAndHandlerMapping[typeof (TEventData)]; - - _eventAndHandlerMapping.GetOrAdd(typeof (TEventData), (type) => new List()) - .RemoveAll(t => t.GetType() == eventHandler); - } - - /// - /// 根据事件源触发绑定的事件处理 - /// - /// - /// - public static void Publish(TEventData eventData) where TEventData : IEventData - { - List handlers = Default._eventAndHandlerMapping[typeof (TEventData)]; - - if (handlers != null && handlers.Count > 0) - { - foreach (var handler in handlers) - { - var eventHandler = handler as IEventHandler; - if (eventHandler.Ansyc) - { - Task.Run(() => - { - eventHandler.HandleEvent(eventData); - }); - } - else - { - eventHandler.HandleEvent(eventData); - } - } - } - } - } -} +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace Hncore.Infrastructure.Events +{ + /// + /// 事件总线 + /// + public class EventBus + { + private static EventBus _eventBus = null; + + public static EventBus Default + { + get { return _eventBus ?? (_eventBus = new EventBus()); } + } + + /// + /// 定义线程安全集合 + /// + private readonly ConcurrentDictionary> _eventAndHandlerMapping; + + public EventBus() + { + _eventAndHandlerMapping = new ConcurrentDictionary>(); + MapEventToHandler(); + } + + /// + ///通过反射,将事件源与事件处理绑定 + /// + private void MapEventToHandler() + { + // Assembly assembly = Assembly.GetEntryAssembly(); + + var allAssembly = AppDomain.CurrentDomain.GetAssemblies().Where(item => item.FullName.Contains("Microkj.")); + if (!allAssembly.Any()) + { + return; + } + + foreach (var assembly in allAssembly) + { + foreach (var type in assembly.GetTypes()) + { + if (!type.IsGenericType && typeof(IEventHandler).IsAssignableFrom(type)) //判断当前类型是否实现了IEventHandler接口 + { + Type handlerInterface = type.GetInterface("IEventHandler`1"); //获取该类实现的泛型接口 + if (handlerInterface != null) + { + Type eventDataType = handlerInterface.GetGenericArguments()[0]; // 获取泛型接口指定的参数类型 + + if (_eventAndHandlerMapping.ContainsKey(eventDataType)) + { + List handlerTypes = _eventAndHandlerMapping[eventDataType]; + handlerTypes.Add(Activator.CreateInstance(type) as IEventHandler); + _eventAndHandlerMapping[eventDataType] = handlerTypes; + } + else + { + var handlerTypes = new List + { + Activator.CreateInstance(type) as IEventHandler + }; + _eventAndHandlerMapping[eventDataType] = handlerTypes; + } + } + } + } + } + } + + /// + /// 手动绑定事件源与事件处理 + /// + /// + /// + public void Register(IEventHandler eventHandler) + { + if (_eventAndHandlerMapping.Keys.Contains(typeof (TEventData))) + { + List handlerTypes = _eventAndHandlerMapping[typeof (TEventData)]; + if (!handlerTypes.Contains(eventHandler)) + { + handlerTypes.Add(eventHandler); + _eventAndHandlerMapping[typeof (TEventData)] = handlerTypes; + } + } + else + { + _eventAndHandlerMapping.GetOrAdd(typeof (TEventData), (type) => new List()) + .Add(eventHandler); + } + } + + + public void Register(Action action) where TEventData : IEventData + { + var actionHandler = new ActionEventHandler(action); + Register(actionHandler); + } + + /// + /// 手动解除事件源与事件处理的绑定 + /// + /// + /// + public void UnRegister(Type eventHandler) + { + List handlerTypes = _eventAndHandlerMapping[typeof (TEventData)]; + + _eventAndHandlerMapping.GetOrAdd(typeof (TEventData), (type) => new List()) + .RemoveAll(t => t.GetType() == eventHandler); + } + + /// + /// 根据事件源触发绑定的事件处理 + /// + /// + /// + public static void Publish(TEventData eventData) where TEventData : IEventData + { + List handlers = Default._eventAndHandlerMapping[typeof (TEventData)]; + + if (handlers != null && handlers.Count > 0) + { + foreach (var handler in handlers) + { + var eventHandler = handler as IEventHandler; + if (eventHandler.Ansyc) + { + Task.Run(() => + { + eventHandler.HandleEvent(eventData); + }); + } + else + { + eventHandler.HandleEvent(eventData); + } + } + } + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/EventBus/EventData.cs b/Infrastructure/Hncore.Infrastructure/EventBus/EventData.cs index 6141ba5..f86b570 100644 --- a/Infrastructure/Hncore.Infrastructure/EventBus/EventData.cs +++ b/Infrastructure/Hncore.Infrastructure/EventBus/EventData.cs @@ -1,39 +1,39 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Hncore.Infrastructure.Events -{ - /// - /// 事件源:描述事件信息,用于参数传递 - /// - public class EventData : IEventData where TData:class - { - /// - /// 事件发生的时间 - /// - public DateTime EventTime { get; set; } - - /// - /// 触发事件的对象 - /// - public TData EventSource { get; set; } - - object IEventData.EventSource - { - get - { - return this.EventSource as TData; - } - - set { this.EventSource =(TData) value; } - } - - public EventData() - { - EventTime = DateTime.Now; - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Hncore.Infrastructure.Events +{ + /// + /// 事件源:描述事件信息,用于参数传递 + /// + public class EventData : IEventData where TData:class + { + /// + /// 事件发生的时间 + /// + public DateTime EventTime { get; set; } + + /// + /// 触发事件的对象 + /// + public TData EventSource { get; set; } + + object IEventData.EventSource + { + get + { + return this.EventSource as TData; + } + + set { this.EventSource =(TData) value; } + } + + public EventData() + { + EventTime = DateTime.Now; + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/EventBus/IEventBus.cs b/Infrastructure/Hncore.Infrastructure/EventBus/IEventBus.cs index 18cb20c..f0556db 100644 --- a/Infrastructure/Hncore.Infrastructure/EventBus/IEventBus.cs +++ b/Infrastructure/Hncore.Infrastructure/EventBus/IEventBus.cs @@ -1,19 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Hncore.Infrastructure.Events -{ - public interface IEventBus - { - void Register(IEventHandler eventHandler); - - void Register(Action action) where TEventData : IEventData; - - void UnRegister(Type eventHandler); - - // void Trigger(TEventData eventData) where TEventData : IEventData; - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Hncore.Infrastructure.Events +{ + public interface IEventBus + { + void Register(IEventHandler eventHandler); + + void Register(Action action) where TEventData : IEventData; + + void UnRegister(Type eventHandler); + + // void Trigger(TEventData eventData) where TEventData : IEventData; + } +} diff --git a/Infrastructure/Hncore.Infrastructure/EventBus/IEventData.cs b/Infrastructure/Hncore.Infrastructure/EventBus/IEventData.cs index 0e0a12b..5f3a3cf 100644 --- a/Infrastructure/Hncore.Infrastructure/EventBus/IEventData.cs +++ b/Infrastructure/Hncore.Infrastructure/EventBus/IEventData.cs @@ -1,24 +1,24 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Hncore.Infrastructure.Events -{ - /// - /// 定义事件源接口,所有的事件源都要实现该接口 - /// - public interface IEventData - { - /// - /// 事件发生的时间 - /// - DateTime EventTime { get; set; } - - /// - /// 触发事件的对象 - /// - Object EventSource { get; set; } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Hncore.Infrastructure.Events +{ + /// + /// 定义事件源接口,所有的事件源都要实现该接口 + /// + public interface IEventData + { + /// + /// 事件发生的时间 + /// + DateTime EventTime { get; set; } + + /// + /// 触发事件的对象 + /// + Object EventSource { get; set; } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/EventBus/IEventHandler.cs b/Infrastructure/Hncore.Infrastructure/EventBus/IEventHandler.cs index bc296f9..9044bb1 100644 --- a/Infrastructure/Hncore.Infrastructure/EventBus/IEventHandler.cs +++ b/Infrastructure/Hncore.Infrastructure/EventBus/IEventHandler.cs @@ -1,29 +1,29 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Hncore.Infrastructure.Events -{ - /// - /// 定义事件处理器公共接口,所有的事件处理都要实现该接口 - /// - public interface IEventHandler - { - } - - /// - /// 泛型事件处理器接口 - /// - /// - public interface IEventHandler : IEventHandler where TEventData : IEventData - { - bool Ansyc { get; set; } - /// - /// 事件处理器实现该方法来处理事件 - /// - /// - void HandleEvent(TEventData eventData); - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Hncore.Infrastructure.Events +{ + /// + /// 定义事件处理器公共接口,所有的事件处理都要实现该接口 + /// + public interface IEventHandler + { + } + + /// + /// 泛型事件处理器接口 + /// + /// + public interface IEventHandler : IEventHandler where TEventData : IEventData + { + bool Ansyc { get; set; } + /// + /// 事件处理器实现该方法来处理事件 + /// + /// + void HandleEvent(TEventData eventData); + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Extension/AssemblyExtension.cs b/Infrastructure/Hncore.Infrastructure/Extension/AssemblyExtension.cs index 1b36781..c557ae1 100644 --- a/Infrastructure/Hncore.Infrastructure/Extension/AssemblyExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Extension/AssemblyExtension.cs @@ -1,21 +1,21 @@ -using System; -using System.Reflection; - -namespace Hncore.Infrastructure.Extension -{ - /// - /// 程序集扩展类 - /// - public static class AssemblyExtension - { - /// - ///得到程序集友好名字 - /// - /// - /// - public static string GetFriendName(this Assembly asm) - { - return asm.ManifestModule?.Name?.TrimEnd(".dll".ToCharArray()); - } - } +using System; +using System.Reflection; + +namespace Hncore.Infrastructure.Extension +{ + /// + /// 程序集扩展类 + /// + public static class AssemblyExtension + { + /// + ///得到程序集友好名字 + /// + /// + /// + public static string GetFriendName(this Assembly asm) + { + return asm.ManifestModule?.Name?.TrimEnd(".dll".ToCharArray()); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Extension/BoolExtension.cs b/Infrastructure/Hncore.Infrastructure/Extension/BoolExtension.cs index bd7c500..64894a3 100644 --- a/Infrastructure/Hncore.Infrastructure/Extension/BoolExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Extension/BoolExtension.cs @@ -1,60 +1,60 @@ -using System; - -namespace Hncore.Infrastructure.Extension -{ - /// - /// bool类型扩展 - /// - public static class BoolExtension - { - /// - /// 转为bool - /// - /// - /// - public static bool ToBool(this bool? para) - { - if (para == null) - { - return false; - } - - return Convert.ToBoolean(para); - } - - - /// - /// 转为bool - /// - /// - /// - public static bool ToBool(this object obj) - { - if (obj == null) - { - return false; - } - - bool.TryParse(obj.ToString(), out var para); - - return para; - } - - public static bool ToBool(this sbyte? obj) - { - if (obj == null) - { - return false; - } - - sbyte num = (sbyte) obj; - - if (num == 1) - { - return true; - } - - return false; - } - } +using System; + +namespace Hncore.Infrastructure.Extension +{ + /// + /// bool类型扩展 + /// + public static class BoolExtension + { + /// + /// 转为bool + /// + /// + /// + public static bool ToBool(this bool? para) + { + if (para == null) + { + return false; + } + + return Convert.ToBoolean(para); + } + + + /// + /// 转为bool + /// + /// + /// + public static bool ToBool(this object obj) + { + if (obj == null) + { + return false; + } + + bool.TryParse(obj.ToString(), out var para); + + return para; + } + + public static bool ToBool(this sbyte? obj) + { + if (obj == null) + { + return false; + } + + sbyte num = (sbyte) obj; + + if (num == 1) + { + return true; + } + + return false; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Extension/DateTimeExtension.cs b/Infrastructure/Hncore.Infrastructure/Extension/DateTimeExtension.cs index 36bae3b..568d568 100644 --- a/Infrastructure/Hncore.Infrastructure/Extension/DateTimeExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Extension/DateTimeExtension.cs @@ -1,177 +1,177 @@ -using System; - -namespace Hncore.Infrastructure.Extension -{ - public static class DateTimeExtension - { - public static string Format(this DateTime time, string format = "yyyy-MM-dd") - { - return time.ToString(format); - } - - - private static DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - - public static long CurrentTimeMillis() - { - return (long) ((DateTime.UtcNow - Jan1st1970).TotalMilliseconds); - } - - public static long CurrentTimeMillis(DateTime time) - { - return (long) ((time.ToUniversalTime() - Jan1st1970).TotalMilliseconds); - } - - public static string Format(this DateTime? dateTime, string format = "yyyy-MM-dd") - { - return Convert.ToDateTime(dateTime).ToString(format); - } - - public static DateTime ToDateTime(this DateTime? dateTime, DateTime defaultTime) - { - if (dateTime != null) - { - return Convert.ToDateTime(dateTime); - } - - return defaultTime; - } - - public static bool Between(this DateTime time, DateTime beginTime, DateTime endTime) - { - return time >= beginTime && time <= endTime; - } - - /// - /// 取得某月的第一天 - /// - /// 要取得月份第一天的时间 - /// - public static DateTime FirstDayOfMonth(this DateTime datetime) - { - return datetime.AddDays(1 - datetime.Day); - } - - /**/ - /// - /// 取得某月的最后一天 - /// - /// 要取得月份最后一天的时间 - /// - public static DateTime LastDayOfMonth(this DateTime datetime) - { - return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1); - } - - /**/ - /// - /// 取得上个月第一天 - /// - /// 要取得上个月第一天的当前时间 - /// - public static DateTime FirstDayOfPreviousMonth(this DateTime datetime) - { - return datetime.AddDays(1 - datetime.Day).AddMonths(-1); - } - - /**/ - /// - /// 取得上个月的最后一天 - /// - /// 要取得上个月最后一天的当前时间 - /// - public static DateTime LastDayOfPrdviousMonth(this DateTime datetime) - { - return datetime.AddDays(1 - datetime.Day).AddDays(-1); - } - - /// - /// 获取时间的Unix时间戳 - /// - /// 时间对象 - /// Unix时间戳 - /// - public static long GetUnixTimeStamp(this DateTime tm) - { - long result = (tm.ToUniversalTime().Ticks - 621355968000000000) / 10000000; - return result; - } - - /// - /// 从Uninx转换时间 - /// - /// 时间对象 - /// 时间戳 - /// 新时间对象 - /// - public static DateTime LoadFromUnixTimeStamp(this DateTime tm,double timeStamp) - { - DateTime startTime=TimeZoneInfo.ConvertTime(new System.DateTime(1970, 1, 1),TimeZoneInfo.Local); - DateTime result=startTime.AddSeconds(timeStamp); - return result; - } - - public static DateTime LoadFromUnixTimeStamp(this long timeStamp) - { - DateTime startTime = TimeZoneInfo.ConvertTime(new System.DateTime(1970, 1, 1), TimeZoneInfo.Local); - DateTime result = startTime.AddSeconds(timeStamp); - return result; - } - - /// - /// 时间戳转换成时间 - /// - /// 时间戳 - /// 是否毫秒级,true毫秒级(默认值) - /// 是否输出本地时间,true本地时间(默认值) - /// - public static DateTime? LoadFromUnixTimeStamp(this string timestamp) - { - if (long.TryParse(timestamp, out long ts)) - { - return ts.LoadFromUnixTimeStamp(); - } - return null; - } - - /// - /// 1970 到现在的秒数 - /// - /// - /// - public static int TimestampFrom19700101(this DateTime time) - { - return (int)(time - new DateTime(1970, 01, 01)).TotalSeconds; - } - - - #region 获取日期、明天 - public static DateTime Date(this DateTime? time) - { - return Convert.ToDateTime(time).Date; - } - public static DateTime NextDate(this DateTime? time) - { - return Convert.ToDateTime(time).Date.AddDays(1); - } - public static DateTime Date(this DateTime time) - { - return time.Date; - } - public static DateTime NextDate(this DateTime time) - { - return time.Date.AddDays(1); - } - #endregion - - public static DateTime Begin(this DateTime time) - { - return new DateTime(time.Year, time.Month, time.Day); - } - - public static DateTime End(this DateTime time) - { - return new DateTime(time.Year, time.Month, time.Day,23,59,59); - } - } +using System; + +namespace Hncore.Infrastructure.Extension +{ + public static class DateTimeExtension + { + public static string Format(this DateTime time, string format = "yyyy-MM-dd") + { + return time.ToString(format); + } + + + private static DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + public static long CurrentTimeMillis() + { + return (long) ((DateTime.UtcNow - Jan1st1970).TotalMilliseconds); + } + + public static long CurrentTimeMillis(DateTime time) + { + return (long) ((time.ToUniversalTime() - Jan1st1970).TotalMilliseconds); + } + + public static string Format(this DateTime? dateTime, string format = "yyyy-MM-dd") + { + return Convert.ToDateTime(dateTime).ToString(format); + } + + public static DateTime ToDateTime(this DateTime? dateTime, DateTime defaultTime) + { + if (dateTime != null) + { + return Convert.ToDateTime(dateTime); + } + + return defaultTime; + } + + public static bool Between(this DateTime time, DateTime beginTime, DateTime endTime) + { + return time >= beginTime && time <= endTime; + } + + /// + /// 取得某月的第一天 + /// + /// 要取得月份第一天的时间 + /// + public static DateTime FirstDayOfMonth(this DateTime datetime) + { + return datetime.AddDays(1 - datetime.Day); + } + + /**/ + /// + /// 取得某月的最后一天 + /// + /// 要取得月份最后一天的时间 + /// + public static DateTime LastDayOfMonth(this DateTime datetime) + { + return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1); + } + + /**/ + /// + /// 取得上个月第一天 + /// + /// 要取得上个月第一天的当前时间 + /// + public static DateTime FirstDayOfPreviousMonth(this DateTime datetime) + { + return datetime.AddDays(1 - datetime.Day).AddMonths(-1); + } + + /**/ + /// + /// 取得上个月的最后一天 + /// + /// 要取得上个月最后一天的当前时间 + /// + public static DateTime LastDayOfPrdviousMonth(this DateTime datetime) + { + return datetime.AddDays(1 - datetime.Day).AddDays(-1); + } + + /// + /// 获取时间的Unix时间戳 + /// + /// 时间对象 + /// Unix时间戳 + /// + public static long GetUnixTimeStamp(this DateTime tm) + { + long result = (tm.ToUniversalTime().Ticks - 621355968000000000) / 10000000; + return result; + } + + /// + /// 从Uninx转换时间 + /// + /// 时间对象 + /// 时间戳 + /// 新时间对象 + /// + public static DateTime LoadFromUnixTimeStamp(this DateTime tm,double timeStamp) + { + DateTime startTime=TimeZoneInfo.ConvertTime(new System.DateTime(1970, 1, 1),TimeZoneInfo.Local); + DateTime result=startTime.AddSeconds(timeStamp); + return result; + } + + public static DateTime LoadFromUnixTimeStamp(this long timeStamp) + { + DateTime startTime = TimeZoneInfo.ConvertTime(new System.DateTime(1970, 1, 1), TimeZoneInfo.Local); + DateTime result = startTime.AddSeconds(timeStamp); + return result; + } + + /// + /// 时间戳转换成时间 + /// + /// 时间戳 + /// 是否毫秒级,true毫秒级(默认值) + /// 是否输出本地时间,true本地时间(默认值) + /// + public static DateTime? LoadFromUnixTimeStamp(this string timestamp) + { + if (long.TryParse(timestamp, out long ts)) + { + return ts.LoadFromUnixTimeStamp(); + } + return null; + } + + /// + /// 1970 到现在的秒数 + /// + /// + /// + public static int TimestampFrom19700101(this DateTime time) + { + return (int)(time - new DateTime(1970, 01, 01)).TotalSeconds; + } + + + #region 获取日期、明天 + public static DateTime Date(this DateTime? time) + { + return Convert.ToDateTime(time).Date; + } + public static DateTime NextDate(this DateTime? time) + { + return Convert.ToDateTime(time).Date.AddDays(1); + } + public static DateTime Date(this DateTime time) + { + return time.Date; + } + public static DateTime NextDate(this DateTime time) + { + return time.Date.AddDays(1); + } + #endregion + + public static DateTime Begin(this DateTime time) + { + return new DateTime(time.Year, time.Month, time.Day); + } + + public static DateTime End(this DateTime time) + { + return new DateTime(time.Year, time.Month, time.Day,23,59,59); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Extension/DbDataReaderExtension.cs b/Infrastructure/Hncore.Infrastructure/Extension/DbDataReaderExtension.cs index c3d545d..4ffc33d 100644 --- a/Infrastructure/Hncore.Infrastructure/Extension/DbDataReaderExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Extension/DbDataReaderExtension.cs @@ -1,24 +1,24 @@ -using System.Collections.Generic; -using System.Data.Common; -using System.Dynamic; - -namespace Hncore.Infrastructure.Extension -{ - public static class DbDataReaderExtension - { - public static IDictionary GetDataRow(this DbDataReader dataReader) - { - var dataRow = new ExpandoObject() as IDictionary; - - for (var iFiled = 0; iFiled < dataReader.FieldCount; iFiled++) - { - dataRow.Add( - dataReader.GetName(iFiled), - dataReader.IsDBNull(iFiled) ? "" : dataReader[iFiled] - ); - } - - return dataRow; - } - } +using System.Collections.Generic; +using System.Data.Common; +using System.Dynamic; + +namespace Hncore.Infrastructure.Extension +{ + public static class DbDataReaderExtension + { + public static IDictionary GetDataRow(this DbDataReader dataReader) + { + var dataRow = new ExpandoObject() as IDictionary; + + for (var iFiled = 0; iFiled < dataReader.FieldCount; iFiled++) + { + dataRow.Add( + dataReader.GetName(iFiled), + dataReader.IsDBNull(iFiled) ? "" : dataReader[iFiled] + ); + } + + return dataRow; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Extension/EnumExtension.cs b/Infrastructure/Hncore.Infrastructure/Extension/EnumExtension.cs index 428e469..09cff73 100644 --- a/Infrastructure/Hncore.Infrastructure/Extension/EnumExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Extension/EnumExtension.cs @@ -1,149 +1,149 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Reflection; - -namespace Hncore.Infrastructure.Extension -{ - public static class EnumExtension - { - public static Dictionary ToDictionary() - { - Dictionary dic = new Dictionary(); - string namestr = ""; - foreach (var e in Enum.GetValues(typeof(T))) - { - namestr = ""; - - object[] objArrDisplay = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DisplayAttribute), true);//Display - if (objArrDisplay.Any()) - { - var da = objArrDisplay[0] as DisplayAttribute; - namestr = da.Name; - } - else - { - object[] objArrDescription = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);//Description - namestr = objArrDescription.Any() ? (objArrDescription[0] as DescriptionAttribute).Description : e.ToString(); - } - int value = Convert.ToInt32(e); - - - - // string str = item.GetDescription(); - // int value = (int) item; - - dic.Add(value, namestr); - } - - return dic; - } - #region 获取枚举的相关信息的集合 - /// - /// 获取枚举的相关信息的集合 - /// - /// - /// - public static List EnumToList() - { - var list = new List(); - foreach (var e in Enum.GetValues(typeof(T))) - { - var m = new EnumInfo(); - object[] objArrDisplay = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DisplayAttribute), true);//Display - if (objArrDisplay.Any()) - { - var da = objArrDisplay[0] as DisplayAttribute; - m.Name = da.Name; - } - else - { - object[] objArrDescription = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);//Description - m.Name = objArrDescription.Any() ? (objArrDescription[0] as DescriptionAttribute).Description : e.ToString(); - } - m.Value = Convert.ToInt32(e); - list.Add(m); - } - return list; - } - public class EnumInfo - { - public string Name { set; get; } - - public int Value { set; get; } - } - #endregion - public static string GetDisplayName(T enumValue) - { - object[] objArrDisplay = enumValue.GetType().GetField(enumValue.ToString()) - ?.GetCustomAttributes(typeof(DisplayAttribute), true);//Display - if (objArrDisplay!=null&&objArrDisplay.Any()) - { - var da = objArrDisplay[0] as DisplayAttribute; - return da?.Name; - } - return ""; - } - - /// - /// 获取枚举上通过DisplayName、Description或Display柱注的名称 - /// 优先级为DisplayName>Description>Display - /// - /// 枚举值 - /// 枚举名称 - /// - public static string GetEnumDisplayName(this Enum e) - { - try - { - Type t = e.GetType(); - FieldInfo fi = t.GetField(Enum.GetName(t, e)); - var dna = fi.GetCustomAttribute(); - if (dna != null) - return dna.DisplayName; - var da = fi.GetCustomAttribute(); - if (da != null) - return da.Description; - var d = fi.GetCustomAttribute(); - if (d != null) - return d.Name; - } - catch (Exception ex) - { - return "获取枚举"+e.GetType().FullName+"名称错误:"+ex.Message; - } - return ""; - } - - public static string ToHtmlSelectOptions() - { - var dic = ToDictionary(); - - string str = ""; - - foreach (var key in dic.Keys) - { - str += ""; - } - - return str; - } - - #region 判断值是否在枚举类型中存在 - - /// - /// 判断值是否在枚举中存在 - /// - /// 需要判断的参数 - /// 枚举类型 - /// - public static bool IsExist(this int enumValue, Type enumType) - { - return Enum.IsDefined(enumType, enumValue); - } - - #endregion - } +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Reflection; + +namespace Hncore.Infrastructure.Extension +{ + public static class EnumExtension + { + public static Dictionary ToDictionary() + { + Dictionary dic = new Dictionary(); + string namestr = ""; + foreach (var e in Enum.GetValues(typeof(T))) + { + namestr = ""; + + object[] objArrDisplay = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DisplayAttribute), true);//Display + if (objArrDisplay.Any()) + { + var da = objArrDisplay[0] as DisplayAttribute; + namestr = da.Name; + } + else + { + object[] objArrDescription = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);//Description + namestr = objArrDescription.Any() ? (objArrDescription[0] as DescriptionAttribute).Description : e.ToString(); + } + int value = Convert.ToInt32(e); + + + + // string str = item.GetDescription(); + // int value = (int) item; + + dic.Add(value, namestr); + } + + return dic; + } + #region 获取枚举的相关信息的集合 + /// + /// 获取枚举的相关信息的集合 + /// + /// + /// + public static List EnumToList() + { + var list = new List(); + foreach (var e in Enum.GetValues(typeof(T))) + { + var m = new EnumInfo(); + object[] objArrDisplay = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DisplayAttribute), true);//Display + if (objArrDisplay.Any()) + { + var da = objArrDisplay[0] as DisplayAttribute; + m.Name = da.Name; + } + else + { + object[] objArrDescription = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);//Description + m.Name = objArrDescription.Any() ? (objArrDescription[0] as DescriptionAttribute).Description : e.ToString(); + } + m.Value = Convert.ToInt32(e); + list.Add(m); + } + return list; + } + public class EnumInfo + { + public string Name { set; get; } + + public int Value { set; get; } + } + #endregion + public static string GetDisplayName(T enumValue) + { + object[] objArrDisplay = enumValue.GetType().GetField(enumValue.ToString()) + ?.GetCustomAttributes(typeof(DisplayAttribute), true);//Display + if (objArrDisplay!=null&&objArrDisplay.Any()) + { + var da = objArrDisplay[0] as DisplayAttribute; + return da?.Name; + } + return ""; + } + + /// + /// 获取枚举上通过DisplayName、Description或Display柱注的名称 + /// 优先级为DisplayName>Description>Display + /// + /// 枚举值 + /// 枚举名称 + /// + public static string GetEnumDisplayName(this Enum e) + { + try + { + Type t = e.GetType(); + FieldInfo fi = t.GetField(Enum.GetName(t, e)); + var dna = fi.GetCustomAttribute(); + if (dna != null) + return dna.DisplayName; + var da = fi.GetCustomAttribute(); + if (da != null) + return da.Description; + var d = fi.GetCustomAttribute(); + if (d != null) + return d.Name; + } + catch (Exception ex) + { + return "获取枚举"+e.GetType().FullName+"名称错误:"+ex.Message; + } + return ""; + } + + public static string ToHtmlSelectOptions() + { + var dic = ToDictionary(); + + string str = ""; + + foreach (var key in dic.Keys) + { + str += ""; + } + + return str; + } + + #region 判断值是否在枚举类型中存在 + + /// + /// 判断值是否在枚举中存在 + /// + /// 需要判断的参数 + /// 枚举类型 + /// + public static bool IsExist(this int enumValue, Type enumType) + { + return Enum.IsDefined(enumType, enumValue); + } + + #endregion + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Extension/ExceptionExtension.cs b/Infrastructure/Hncore.Infrastructure/Extension/ExceptionExtension.cs index 91579cc..9008fe4 100644 --- a/Infrastructure/Hncore.Infrastructure/Extension/ExceptionExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Extension/ExceptionExtension.cs @@ -1,25 +1,25 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using TinyPinyin.Core; - -namespace Hncore.Infrastructure.Extension -{ - public static class ExceptionExtension - { - public static string GetInfo(this Exception ex) - { - var info = $"S:{ex.Source},M:{ex.Message},ST:{ex.StackTrace}-----"; - if (ex.InnerException != null) - { - info += ex.InnerException.GetInfo(); - } - return info; - } - - } +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; +using System.Web; +using TinyPinyin.Core; + +namespace Hncore.Infrastructure.Extension +{ + public static class ExceptionExtension + { + public static string GetInfo(this Exception ex) + { + var info = $"S:{ex.Source},M:{ex.Message},ST:{ex.StackTrace}-----"; + if (ex.InnerException != null) + { + info += ex.InnerException.GetInfo(); + } + return info; + } + + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Extension/HttpClientExtension.cs b/Infrastructure/Hncore.Infrastructure/Extension/HttpClientExtension.cs index 3e94f7f..81a94a8 100644 --- a/Infrastructure/Hncore.Infrastructure/Extension/HttpClientExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Extension/HttpClientExtension.cs @@ -1,94 +1,94 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Threading.Tasks; -using Hncore.Infrastructure.Serializer; - -namespace Hncore.Infrastructure.Extension -{ - public static class HttpClientFactoryExtension - { - public static HttpClient CreateClient(this IHttpClientFactory factory, TimeSpan timeOut) - { - var client = factory.CreateClient(); - - client.Timeout = timeOut; - - return client; - } - } - - public static class HttpClientExtension - { - /// - /// post请求,ContentType:application/json - /// - /// - /// - /// - /// - public static async Task PostAsJson(this HttpClient httpClient, string path, object data, - Encoding encoding = null) - { - if (encoding == null) - { - encoding = Encoding.UTF8; - } - - string content = ""; - - if (data is string s) - { - content = s; - } - else - { - content = data.ToJson(); - } - - HttpContent httpContent = new StringContent(content, encoding); - - httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - - return await httpClient.PostAsync(path, httpContent); - } - - /// - /// post请求,ContentType:application/json - /// - /// - /// - /// - /// - public static async Task PostAsJsonGetString(this HttpClient httpClient, string path, object data, - Encoding encoding = null) - { - var res = await httpClient.PostAsJson(path, data, encoding); - - return await res.Content.ReadAsStringAsync(); - } - - public static async Task PostAsForm(this HttpClient httpClient, string path, IEnumerable> data, - Encoding encoding = null) - { - if (encoding == null) - { - encoding = Encoding.UTF8; - } - - HttpContent httpContent = new FormUrlEncodedContent(data); - - return await httpClient.PostAsync(path, httpContent); - } - public static async Task PostAsFormGetString(this HttpClient httpClient, string path, IEnumerable> data, -Encoding encoding = null) - { - var resp=await httpClient.PostAsForm(path, data, encoding); - - return await resp.Content.ReadAsStringAsync(); - } - } +using System; +using System.Collections; +using System.Collections.Generic; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +using Hncore.Infrastructure.Serializer; + +namespace Hncore.Infrastructure.Extension +{ + public static class HttpClientFactoryExtension + { + public static HttpClient CreateClient(this IHttpClientFactory factory, TimeSpan timeOut) + { + var client = factory.CreateClient(); + + client.Timeout = timeOut; + + return client; + } + } + + public static class HttpClientExtension + { + /// + /// post请求,ContentType:application/json + /// + /// + /// + /// + /// + public static async Task PostAsJson(this HttpClient httpClient, string path, object data, + Encoding encoding = null) + { + if (encoding == null) + { + encoding = Encoding.UTF8; + } + + string content = ""; + + if (data is string s) + { + content = s; + } + else + { + content = data.ToJson(); + } + + HttpContent httpContent = new StringContent(content, encoding); + + httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + + return await httpClient.PostAsync(path, httpContent); + } + + /// + /// post请求,ContentType:application/json + /// + /// + /// + /// + /// + public static async Task PostAsJsonGetString(this HttpClient httpClient, string path, object data, + Encoding encoding = null) + { + var res = await httpClient.PostAsJson(path, data, encoding); + + return await res.Content.ReadAsStringAsync(); + } + + public static async Task PostAsForm(this HttpClient httpClient, string path, IEnumerable> data, + Encoding encoding = null) + { + if (encoding == null) + { + encoding = Encoding.UTF8; + } + + HttpContent httpContent = new FormUrlEncodedContent(data); + + return await httpClient.PostAsync(path, httpContent); + } + public static async Task PostAsFormGetString(this HttpClient httpClient, string path, IEnumerable> data, +Encoding encoding = null) + { + var resp=await httpClient.PostAsForm(path, data, encoding); + + return await resp.Content.ReadAsStringAsync(); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Extension/ListExtension.cs b/Infrastructure/Hncore.Infrastructure/Extension/ListExtension.cs index bd277f4..ecdf4fc 100644 --- a/Infrastructure/Hncore.Infrastructure/Extension/ListExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Extension/ListExtension.cs @@ -1,126 +1,126 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; - -namespace Hncore.Infrastructure.Extension -{ - public static class ListExtension - { - public static bool NullOrEmpty(this IList list) - { - if (list == null) - { - return true; - } - - if (!list.Any()) - { - return true; - } - return false; - } - - #region 转换几个中所有元素的类型 - /// - /// 转换几个中所有元素的类型 - /// - /// - /// - /// - public static List ConvertListType(this List list) - { - if (list == null) - { - return null; - } - List newlist = new List(); - foreach (T t in list) - { - newlist.Add((TO)Convert.ChangeType(t, typeof(TO))); - } - return newlist; - } - #endregion - - /// - /// 添加 - /// - /// - /// - /// - /// - public static List AddNew(this List list, T item) - { - list.Add(item); - return list; - } - - /// - /// 添加多个集合 - /// - /// - /// - /// - /// - public static List AddNewMult(this List list, List item) - { - list.AddRange(item); - return list; - } - - /// - /// 移除 - /// - /// - /// - /// - /// - public static List RemoveNew(this List list, T item) - { - list.Remove(item); - return list; - } - - #region 按条件移除 - - /// - /// 移除单条符合条件的数据 - /// - /// - /// 条件 - /// - /// - public static List RemoveNew(this List list, Func condtion) - { - List listTemp = list; - var item = listTemp.FirstOrDefault(condtion); - if (item != null) - { - listTemp.Remove(item); - } - return list; - } - - /// - /// 移除多条满足条件 - /// - /// - /// 条件 - /// - /// - public static List RemoveMultNew(this List list, Func condtion) - { - List listTemp = list; - var items = listTemp.Where(condtion).ToList() ?? new List(); - foreach (var item in items) - { - listTemp.Remove(item); - } - return list; - } - - #endregion - - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; + +namespace Hncore.Infrastructure.Extension +{ + public static class ListExtension + { + public static bool NullOrEmpty(this IList list) + { + if (list == null) + { + return true; + } + + if (!list.Any()) + { + return true; + } + return false; + } + + #region 转换几个中所有元素的类型 + /// + /// 转换几个中所有元素的类型 + /// + /// + /// + /// + public static List ConvertListType(this List list) + { + if (list == null) + { + return null; + } + List newlist = new List(); + foreach (T t in list) + { + newlist.Add((TO)Convert.ChangeType(t, typeof(TO))); + } + return newlist; + } + #endregion + + /// + /// 添加 + /// + /// + /// + /// + /// + public static List AddNew(this List list, T item) + { + list.Add(item); + return list; + } + + /// + /// 添加多个集合 + /// + /// + /// + /// + /// + public static List AddNewMult(this List list, List item) + { + list.AddRange(item); + return list; + } + + /// + /// 移除 + /// + /// + /// + /// + /// + public static List RemoveNew(this List list, T item) + { + list.Remove(item); + return list; + } + + #region 按条件移除 + + /// + /// 移除单条符合条件的数据 + /// + /// + /// 条件 + /// + /// + public static List RemoveNew(this List list, Func condtion) + { + List listTemp = list; + var item = listTemp.FirstOrDefault(condtion); + if (item != null) + { + listTemp.Remove(item); + } + return list; + } + + /// + /// 移除多条满足条件 + /// + /// + /// 条件 + /// + /// + public static List RemoveMultNew(this List list, Func condtion) + { + List listTemp = list; + var items = listTemp.Where(condtion).ToList() ?? new List(); + foreach (var item in items) + { + listTemp.Remove(item); + } + return list; + } + + #endregion + + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Extension/ListForEachExtension.cs b/Infrastructure/Hncore.Infrastructure/Extension/ListForEachExtension.cs index 770df28..cbf4278 100644 --- a/Infrastructure/Hncore.Infrastructure/Extension/ListForEachExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Extension/ListForEachExtension.cs @@ -1,19 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Threading.Tasks; - -namespace Hncore.Infrastructure.Extension -{ - public static class ListForEachExtension - { - public static async Task ForEachAsync(this IEnumerable list, Func func) - { - foreach (T value in list) - { - await func(value); - } - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; + +namespace Hncore.Infrastructure.Extension +{ + public static class ListForEachExtension + { + public static async Task ForEachAsync(this IEnumerable list, Func func) + { + foreach (T value in list) + { + await func(value); + } + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Extension/NumberExtension.cs b/Infrastructure/Hncore.Infrastructure/Extension/NumberExtension.cs index 5fe694d..8d13a31 100644 --- a/Infrastructure/Hncore.Infrastructure/Extension/NumberExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Extension/NumberExtension.cs @@ -1,63 +1,63 @@ -using System; -using Newtonsoft.Json.Linq; - -namespace Hncore.Infrastructure.Extension -{ - public static class NumberExtension - { - public static int ToInt(this int? num) - { - if (num == null) - { - return 0; - } - - return Convert.ToInt32(num); - } - - public static int ToInt(this JToken obj) - { - if (obj == null) - { - return 0; - } - - int.TryParse(obj.ToString(), out var num); - - return num; - } - - public static decimal ToDecimal(this decimal? num) - { - if (num == null) - { - - return 0; - } - - return Convert.ToDecimal(num); - } - - public static long ToLong(this long? num) - { - if (num == null) - { - return 0; - } - - return (long) num; - } - - public static int ToInt(this bool flag) - { - if (flag) - { - return 1; - } - else - { - return 0; - } - } - } +using System; +using Newtonsoft.Json.Linq; + +namespace Hncore.Infrastructure.Extension +{ + public static class NumberExtension + { + public static int ToInt(this int? num) + { + if (num == null) + { + return 0; + } + + return Convert.ToInt32(num); + } + + public static int ToInt(this JToken obj) + { + if (obj == null) + { + return 0; + } + + int.TryParse(obj.ToString(), out var num); + + return num; + } + + public static decimal ToDecimal(this decimal? num) + { + if (num == null) + { + + return 0; + } + + return Convert.ToDecimal(num); + } + + public static long ToLong(this long? num) + { + if (num == null) + { + return 0; + } + + return (long) num; + } + + public static int ToInt(this bool flag) + { + if (flag) + { + return 1; + } + else + { + return 0; + } + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Extension/ObjectExtension.cs b/Infrastructure/Hncore.Infrastructure/Extension/ObjectExtension.cs index 17227b4..4a168fc 100644 --- a/Infrastructure/Hncore.Infrastructure/Extension/ObjectExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Extension/ObjectExtension.cs @@ -1,144 +1,144 @@ -using Nelibur.ObjectMapper; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.ComponentModel.DataAnnotations; -using System.Dynamic; -using System.Linq; -using System.Threading; - -namespace Hncore.Infrastructure.Extension -{ - public static class ObjectExtension - { - /// - /// 将对象[主要是匿名对象]转换为dynamic - /// - public static dynamic ToDynamic(this object obj, decimal defaultVal) - { - decimal result; - if (obj != null) - if (decimal.TryParse(obj.ToString(), out result)) - return result; - else - return defaultVal; - return defaultVal; - } - - // 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. - public static T GetAttribute(this object value) where T : Attribute - { - var type = value.GetType(); - var memberInfo = type.GetMember(value.ToString()); - if (!memberInfo.Any()) - { - return null; - } - - var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false); - return (T) attributes[0]; - } - - // This method creates a specific call to the above method, requesting the - // Description MetaData attribute. - public static string GetDescription(this object value) - { - var desAttribute = value.GetAttribute(); - if (desAttribute != null) - { - return desAttribute.Description; - } - - var displayAttribute = value.GetAttribute(); - if (displayAttribute != null) - { - return displayAttribute.Name ?? displayAttribute.Description; - } - - return ""; - } - - #region 得到枚举字典(key对应枚举的值,value对应枚举的注释) - - /// - /// 得到枚举字典(key对应枚举的值,value对应枚举的注释) - /// - /// - /// - public static Dictionary ToDescriptionDictionary() - { - Array values = Enum.GetValues(typeof(TEnum)); - Dictionary nums = new Dictionary(); - foreach (Enum value in values) - { - nums.Add(value, GetDescription(value)); - } - - return nums; - } - - #endregion - - #region 实体中string属性执行Trim() - /// - /// 对象string属性执行Trim() - /// - /// - /// - /// - public static T ObjectStrTrim(this T t) where T:new () - { - if (t != null) - { - foreach (var pi in t.GetType().GetProperties()) - { - if (pi.PropertyType.Equals(typeof(string)) && pi.GetValue(t, null) != null)//判断属性的类型是不是String - { - pi.SetValue(t, pi.GetValue(t, null).ToString().Trim(), null);//给泛型的属性赋值 - } - } - } - return t; - } - #endregion - - #region - public static T save(this T obj,string key) where T:class,new() - { - Dictionary dic = c.Value ?? new Dictionary(); - dic.Add(key,obj); - c.Value = dic; - return obj; - } - public static AsyncLocal> c=new AsyncLocal>(); - #endregion - - #region 对象转换 - - public static T MapTo(this Object model) - { - var productDto = TinyMapper.Map(model); - - return productDto; - } - public static IEnumerable MapsTo(this Object model) - { - var generic = model.GetType().GetGenericTypeDefinition(); - - if (generic == typeof(List<>)) - { - return TinyMapper.Map>(model); - } - if (generic == typeof(Collection<>)) - { - return TinyMapper.Map>(model); - } - - throw new Exception("不合法的转换"); - } - - #endregion - } +using Nelibur.ObjectMapper; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.Dynamic; +using System.Linq; +using System.Threading; + +namespace Hncore.Infrastructure.Extension +{ + public static class ObjectExtension + { + /// + /// 将对象[主要是匿名对象]转换为dynamic + /// + public static dynamic ToDynamic(this object obj, decimal defaultVal) + { + decimal result; + if (obj != null) + if (decimal.TryParse(obj.ToString(), out result)) + return result; + else + return defaultVal; + return defaultVal; + } + + // 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. + public static T GetAttribute(this object value) where T : Attribute + { + var type = value.GetType(); + var memberInfo = type.GetMember(value.ToString()); + if (!memberInfo.Any()) + { + return null; + } + + var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false); + return (T) attributes[0]; + } + + // This method creates a specific call to the above method, requesting the + // Description MetaData attribute. + public static string GetDescription(this object value) + { + var desAttribute = value.GetAttribute(); + if (desAttribute != null) + { + return desAttribute.Description; + } + + var displayAttribute = value.GetAttribute(); + if (displayAttribute != null) + { + return displayAttribute.Name ?? displayAttribute.Description; + } + + return ""; + } + + #region 得到枚举字典(key对应枚举的值,value对应枚举的注释) + + /// + /// 得到枚举字典(key对应枚举的值,value对应枚举的注释) + /// + /// + /// + public static Dictionary ToDescriptionDictionary() + { + Array values = Enum.GetValues(typeof(TEnum)); + Dictionary nums = new Dictionary(); + foreach (Enum value in values) + { + nums.Add(value, GetDescription(value)); + } + + return nums; + } + + #endregion + + #region 实体中string属性执行Trim() + /// + /// 对象string属性执行Trim() + /// + /// + /// + /// + public static T ObjectStrTrim(this T t) where T:new () + { + if (t != null) + { + foreach (var pi in t.GetType().GetProperties()) + { + if (pi.PropertyType.Equals(typeof(string)) && pi.GetValue(t, null) != null)//判断属性的类型是不是String + { + pi.SetValue(t, pi.GetValue(t, null).ToString().Trim(), null);//给泛型的属性赋值 + } + } + } + return t; + } + #endregion + + #region + public static T save(this T obj,string key) where T:class,new() + { + Dictionary dic = c.Value ?? new Dictionary(); + dic.Add(key,obj); + c.Value = dic; + return obj; + } + public static AsyncLocal> c=new AsyncLocal>(); + #endregion + + #region 对象转换 + + public static T MapTo(this Object model) + { + var productDto = TinyMapper.Map(model); + + return productDto; + } + public static IEnumerable MapsTo(this Object model) + { + var generic = model.GetType().GetGenericTypeDefinition(); + + if (generic == typeof(List<>)) + { + return TinyMapper.Map>(model); + } + if (generic == typeof(Collection<>)) + { + return TinyMapper.Map>(model); + } + + throw new Exception("不合法的转换"); + } + + #endregion + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Extension/RequestExtension.cs b/Infrastructure/Hncore.Infrastructure/Extension/RequestExtension.cs index 10c5293..e76de67 100644 --- a/Infrastructure/Hncore.Infrastructure/Extension/RequestExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Extension/RequestExtension.cs @@ -1,46 +1,46 @@ - - -using Microsoft.AspNetCore.Http; -using System; -using System.Linq; - -namespace Hncore.Infrastructure.Extension -{ - - public static class RequestExtension - { - public static string Get(this HttpRequest request, string key) - { - if (request.Query.ContainsKey(key)) - { - return request.Query[key]; - } - return ""; - } - public static int GetInt(this HttpRequest request, string key) - { - if (request.Query.ContainsKey(key)) - { - return Convert.ToInt32(request.Query[key]); - } - return 0; - } - - public static string GetUrl(this HttpRequest request, bool full=true) - { - if (full) - { - return $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}"; - } - return $"{request.Path}{request.QueryString}"; - } - - public static string Remove(this HttpRequest request, string key) - { - var q = request.Query.Where(m => !m.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)); - var kvs = q.Select(m => $"{m.Key}={m.Value}"); - return string.Join("&", kvs); - - } - } + + +using Microsoft.AspNetCore.Http; +using System; +using System.Linq; + +namespace Hncore.Infrastructure.Extension +{ + + public static class RequestExtension + { + public static string Get(this HttpRequest request, string key) + { + if (request.Query.ContainsKey(key)) + { + return request.Query[key]; + } + return ""; + } + public static int GetInt(this HttpRequest request, string key) + { + if (request.Query.ContainsKey(key)) + { + return Convert.ToInt32(request.Query[key]); + } + return 0; + } + + public static string GetUrl(this HttpRequest request, bool full=true) + { + if (full) + { + return $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}"; + } + return $"{request.Path}{request.QueryString}"; + } + + public static string Remove(this HttpRequest request, string key) + { + var q = request.Query.Where(m => !m.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)); + var kvs = q.Select(m => $"{m.Key}={m.Value}"); + return string.Join("&", kvs); + + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Extension/StreamExtension.cs b/Infrastructure/Hncore.Infrastructure/Extension/StreamExtension.cs index d3b16e1..617f45d 100644 --- a/Infrastructure/Hncore.Infrastructure/Extension/StreamExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Extension/StreamExtension.cs @@ -1,21 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using System.Web; - -namespace Hncore.Infrastructure.Extension -{ - public static class StreamExtension - { - public async static Task ReadAsStringAsync(this Stream stream) - { - var reader = new StreamReader(stream); - return await reader.ReadToEndAsync(); - } - } +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Web; + +namespace Hncore.Infrastructure.Extension +{ + public static class StreamExtension + { + public async static Task ReadAsStringAsync(this Stream stream) + { + var reader = new StreamReader(stream); + return await reader.ReadToEndAsync(); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Extension/StringExtension.cs b/Infrastructure/Hncore.Infrastructure/Extension/StringExtension.cs index 7755a0b..610335e 100644 --- a/Infrastructure/Hncore.Infrastructure/Extension/StringExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Extension/StringExtension.cs @@ -1,779 +1,779 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.Text; -using System.Text.RegularExpressions; -using System.Web; -using TinyPinyin.Core; - -namespace Hncore.Infrastructure.Extension -{ - public static class StringExtension - { - #region Url、Html编码 - - [DebuggerStepThrough] - public static string UrlEncode(this string target) - { - return HttpUtility.UrlEncode(target); - } - - [DebuggerStepThrough] - public static string UrlEncode(this string target, Encoding encoding) - { - return HttpUtility.UrlEncode(target, encoding); - } - - [DebuggerStepThrough] - public static string UrlDecode(this string target) - { - return HttpUtility.UrlDecode(target); - } - - [DebuggerStepThrough] - public static string UrlDecode(this string target, Encoding encoding) - { - return HttpUtility.UrlDecode(target, encoding); - } - - [DebuggerStepThrough] - public static string AttributeEncode(this string target) - { - return HttpUtility.HtmlAttributeEncode(target); - } - - [DebuggerStepThrough] - public static string HtmlEncode(this string target) - { - return HttpUtility.HtmlEncode(target); - } - - [DebuggerStepThrough] - public static string HtmlDecode(this string target) - { - return HttpUtility.HtmlDecode(target); - } - - #endregion - - #region Unicode编码 - - /// - /// 汉字转换为Unicode编码 - /// - /// 要编码的汉字字符串 - /// Unicode编码的的字符串 - public static string ToUnicode(this string str) - { - if (string.IsNullOrEmpty(str)) - { - return str; - } - - StringBuilder unicode = new StringBuilder(); - - foreach (char chr in str) - { - // Get the integral value of the character. - int value = Convert.ToInt32(chr); - // Convert the decimal value to a hexadecimal value in string form. - string hexOutput = String.Format("{0:x}", value); - - unicode.Append("\\u" + hexOutput); - } - - return unicode.ToString(); - } - - /// - /// 将Unicode编码转换为汉字字符串 - /// - /// Unicode编码字符串 - /// 汉字字符串 - public static string FromUnicode(this string unicode) - { - if (string.IsNullOrEmpty(unicode)) - { - return unicode; - } - - StringBuilder str = new StringBuilder(); - - unicode = unicode.Replace("\\u", "_"); - - string[] hex = unicode.Split('_'); - - for (int i = 1; i < hex.Length; i++) - { - int data = Convert.ToInt32(hex[i].ToString(), 16); - - str.Append((char) data); - } - - return str.ToString(); - } - - #endregion - - #region 清除脚本 - - /// - /// 清除脚本 - /// - /// - /// - public static string NoHTML(this string Htmlstring) - { - //删除脚本 - Htmlstring = Regex.Replace(Htmlstring, @"]*?>.*?", "", RegexOptions.IgnoreCase); - //删除HTML - Htmlstring = Regex.Replace(Htmlstring, @"<.*?>|&.{4,5}", "", RegexOptions.IgnoreCase); - Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase); - Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase); - Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase); - Htmlstring = Regex.Replace(Htmlstring, @"", "", RegexOptions.IgnoreCase); + Htmlstring = Regex.Replace(Htmlstring, @" - netstandard2.0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Always - - - - + + + + + netstandard2.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Always + + + + diff --git a/Infrastructure/Hncore.Infrastructure/IOC/IDependency.cs b/Infrastructure/Hncore.Infrastructure/IOC/IDependency.cs index c73054c..6ed28d6 100644 --- a/Infrastructure/Hncore.Infrastructure/IOC/IDependency.cs +++ b/Infrastructure/Hncore.Infrastructure/IOC/IDependency.cs @@ -1,7 +1,7 @@ -namespace Hncore.Infrastructure.IOC -{ - public interface IDependency - { - - } +namespace Hncore.Infrastructure.IOC +{ + public interface IDependency + { + + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/IOC/IPerRequest.cs b/Infrastructure/Hncore.Infrastructure/IOC/IPerRequest.cs index a783bef..27e0607 100644 --- a/Infrastructure/Hncore.Infrastructure/IOC/IPerRequest.cs +++ b/Infrastructure/Hncore.Infrastructure/IOC/IPerRequest.cs @@ -1,7 +1,7 @@ -namespace Hncore.Infrastructure.IOC -{ - public interface IPerRequest - { - - } +namespace Hncore.Infrastructure.IOC +{ + public interface IPerRequest + { + + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/IOC/ISingleInstance.cs b/Infrastructure/Hncore.Infrastructure/IOC/ISingleInstance.cs index 60c18ce..3f1bc51 100644 --- a/Infrastructure/Hncore.Infrastructure/IOC/ISingleInstance.cs +++ b/Infrastructure/Hncore.Infrastructure/IOC/ISingleInstance.cs @@ -1,7 +1,7 @@ -namespace Hncore.Infrastructure.IOC -{ - public interface ISingleInstance - { - - } +namespace Hncore.Infrastructure.IOC +{ + public interface ISingleInstance + { + + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Mqtt/MQTTClient.cs b/Infrastructure/Hncore.Infrastructure/Mqtt/MQTTClient.cs index 05ec815..64ddf02 100644 --- a/Infrastructure/Hncore.Infrastructure/Mqtt/MQTTClient.cs +++ b/Infrastructure/Hncore.Infrastructure/Mqtt/MQTTClient.cs @@ -1,151 +1,151 @@ -using System; -using System.Collections.Concurrent; -using System.Security.Cryptography; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Hncore.Infrastructure.Common; -using MQTTnet; -using MQTTnet.Client; -using Polly; - -namespace Hncore.Infrastructure.Mqtt -{ - public class MQTTClient : IDisposable - { - //实例 ID,购买后从控制台获取 - string _instanceId = "post-cn-v0h12xbue09"; - - //此处填写购买得到的 MQTT 接入点域名 - string _brokerUrl = "post-cn-v0h12xbue09.mqtt.aliyuncs.com"; - - //此处填写阿里云帐号 AccessKey - string _accessKey = "LTAIaJpHI68JfX2c"; - - //此处填写阿里云帐号 SecretKey - string _secretKey = "f17za6FRggVzwlSqzFHl8GndQ59SGV"; - - //此处填写客户端 ClientId,需要保证全局唯一,其中前缀部分即 GroupId 需要先在 MQ 控制台创建 - string _clientId = "GID_DOOR@@@MA_" + Guid.NewGuid(); - - private IMqttClient _mqttClient; - - private SemaphoreSlim _lock = new SemaphoreSlim(1, 1); - - private ConcurrentDictionary> cmdMap = new ConcurrentDictionary>(); - - public MQTTClient() - { - _mqttClient = new MqttFactory().CreateMqttClient(); - - _mqttClient.Disconnected += async (s, e) => - { - await Task.Delay(TimeSpan.FromSeconds(2)); - await Conn(); - }; - _mqttClient.ApplicationMessageReceived += (s, e) => - { - var topic = e.ApplicationMessage.Topic.TrimEnd('/'); - var data = Encoding.UTF8.GetString(e.ApplicationMessage.Payload??new byte[0]); - Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###"); - Console.WriteLine($"+ Topic = {topic}"); - Console.WriteLine($"+ Payload = {data}"); - Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); - Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}"); - Console.WriteLine(); - if (cmdMap.ContainsKey(topic)) - { - try - { - cmdMap[topic](data); - } - catch (Exception ex) - { - LogHelper.Error($"Mqtt:{topic}", ex.Message); - } - } - }; - } - - private async Task Conn() - { - if (!_mqttClient.IsConnected) - { - await _lock.WaitAsync(); - - try - { - int i = 0; - - await Policy.Handle() - .OrResult(res => !res.IsSessionPresent) - .RetryAsync(10) - .ExecuteAsync(async () => - { - if (!_mqttClient.IsConnected) - { - i++; - - try - { - string userName = "Signature|" + _accessKey + "|" + _instanceId; - string passWord = HMACSHA1(_secretKey, _clientId); - - var options = new MqttClientOptionsBuilder() - .WithClientId(_clientId) - .WithTcpServer(_brokerUrl) - .WithCredentials(userName, passWord) - .WithCleanSession() - .Build(); - - return await _mqttClient.ConnectAsync(options); - } - catch (Exception e) - { - LogHelper.Error($"mqtt连接失败,第{i}次连接", e); - throw; - } - } - - return new MqttClientConnectResult(true); - }); - } - finally - { - _lock.Release(); - } - } - } - - public async Task PublishAsync(string topic, string payload) - { - await Conn(); - - await _mqttClient.PublishAsync(topic, payload); - } - - public async Task SubscribeAsync(string topic, Action action) - { - await Conn(); - var option = new TopicFilterBuilder().WithTopic(topic).Build(); - await _mqttClient.SubscribeAsync(option); - cmdMap[topic] = action; - } - - public static string HMACSHA1(string key, string dataToSign) - { - Byte[] secretBytes = UTF8Encoding.UTF8.GetBytes(key); - HMACSHA1 hmac = new HMACSHA1(secretBytes); - Byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(dataToSign); - Byte[] calcHash = hmac.ComputeHash(dataBytes); - String calcHashString = Convert.ToBase64String(calcHash); - return calcHashString; - } - - public async void Dispose() - { - await _mqttClient.DisconnectAsync(); - _mqttClient?.Dispose(); - } - } +using System; +using System.Collections.Concurrent; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Hncore.Infrastructure.Common; +using MQTTnet; +using MQTTnet.Client; +using Polly; + +namespace Hncore.Infrastructure.Mqtt +{ + public class MQTTClient : IDisposable + { + //实例 ID,购买后从控制台获取 + string _instanceId = "post-cn-v0h12xbue09"; + + //此处填写购买得到的 MQTT 接入点域名 + string _brokerUrl = "post-cn-v0h12xbue09.mqtt.aliyuncs.com"; + + //此处填写阿里云帐号 AccessKey + string _accessKey = "LTAIaJpHI68JfX2c"; + + //此处填写阿里云帐号 SecretKey + string _secretKey = "f17za6FRggVzwlSqzFHl8GndQ59SGV"; + + //此处填写客户端 ClientId,需要保证全局唯一,其中前缀部分即 GroupId 需要先在 MQ 控制台创建 + string _clientId = "GID_DOOR@@@MA_" + Guid.NewGuid(); + + private IMqttClient _mqttClient; + + private SemaphoreSlim _lock = new SemaphoreSlim(1, 1); + + private ConcurrentDictionary> cmdMap = new ConcurrentDictionary>(); + + public MQTTClient() + { + _mqttClient = new MqttFactory().CreateMqttClient(); + + _mqttClient.Disconnected += async (s, e) => + { + await Task.Delay(TimeSpan.FromSeconds(2)); + await Conn(); + }; + _mqttClient.ApplicationMessageReceived += (s, e) => + { + var topic = e.ApplicationMessage.Topic.TrimEnd('/'); + var data = Encoding.UTF8.GetString(e.ApplicationMessage.Payload??new byte[0]); + Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###"); + Console.WriteLine($"+ Topic = {topic}"); + Console.WriteLine($"+ Payload = {data}"); + Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); + Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}"); + Console.WriteLine(); + if (cmdMap.ContainsKey(topic)) + { + try + { + cmdMap[topic](data); + } + catch (Exception ex) + { + LogHelper.Error($"Mqtt:{topic}", ex.Message); + } + } + }; + } + + private async Task Conn() + { + if (!_mqttClient.IsConnected) + { + await _lock.WaitAsync(); + + try + { + int i = 0; + + await Policy.Handle() + .OrResult(res => !res.IsSessionPresent) + .RetryAsync(10) + .ExecuteAsync(async () => + { + if (!_mqttClient.IsConnected) + { + i++; + + try + { + string userName = "Signature|" + _accessKey + "|" + _instanceId; + string passWord = HMACSHA1(_secretKey, _clientId); + + var options = new MqttClientOptionsBuilder() + .WithClientId(_clientId) + .WithTcpServer(_brokerUrl) + .WithCredentials(userName, passWord) + .WithCleanSession() + .Build(); + + return await _mqttClient.ConnectAsync(options); + } + catch (Exception e) + { + LogHelper.Error($"mqtt连接失败,第{i}次连接", e); + throw; + } + } + + return new MqttClientConnectResult(true); + }); + } + finally + { + _lock.Release(); + } + } + } + + public async Task PublishAsync(string topic, string payload) + { + await Conn(); + + await _mqttClient.PublishAsync(topic, payload); + } + + public async Task SubscribeAsync(string topic, Action action) + { + await Conn(); + var option = new TopicFilterBuilder().WithTopic(topic).Build(); + await _mqttClient.SubscribeAsync(option); + cmdMap[topic] = action; + } + + public static string HMACSHA1(string key, string dataToSign) + { + Byte[] secretBytes = UTF8Encoding.UTF8.GetBytes(key); + HMACSHA1 hmac = new HMACSHA1(secretBytes); + Byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(dataToSign); + Byte[] calcHash = hmac.ComputeHash(dataBytes); + String calcHashString = Convert.ToBase64String(calcHash); + return calcHashString; + } + + public async void Dispose() + { + await _mqttClient.DisconnectAsync(); + _mqttClient?.Dispose(); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/OpenApi/Application.cs b/Infrastructure/Hncore.Infrastructure/OpenApi/Application.cs index 9a5f7da..0022eff 100644 --- a/Infrastructure/Hncore.Infrastructure/OpenApi/Application.cs +++ b/Infrastructure/Hncore.Infrastructure/OpenApi/Application.cs @@ -1,26 +1,26 @@ -using System.Threading.Tasks; - -namespace Hncore.Infrastructure.OpenApi -{ - /// - /// 接入的应用 - /// - public class Application - { - /// - /// 应用唯一标识 - /// - public string AppId { get; set; } = ""; - - /// - /// 应用密钥 - /// - public string AppKey { get; set; } = ""; - - /// - /// 是否启用 - /// - public bool Enable { get; set; } = true; - - } +using System.Threading.Tasks; + +namespace Hncore.Infrastructure.OpenApi +{ + /// + /// 接入的应用 + /// + public class Application + { + /// + /// 应用唯一标识 + /// + public string AppId { get; set; } = ""; + + /// + /// 应用密钥 + /// + public string AppKey { get; set; } = ""; + + /// + /// 是否启用 + /// + public bool Enable { get; set; } = true; + + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiAuthAttribute.cs b/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiAuthAttribute.cs index 6d66448..94bd610 100644 --- a/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiAuthAttribute.cs +++ b/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiAuthAttribute.cs @@ -1,71 +1,71 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Extension; -using Hncore.Infrastructure.Serializer; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Authorization; -using Microsoft.AspNetCore.Mvc.Filters; -using Hncore.Infrastructure.Core.Web; - -namespace Hncore.Infrastructure.OpenApi -{ - public class OpenApiAuthAttribute : TypeFilterAttribute - { - public OpenApiAuthAttribute() : base(typeof(OpenApiAuthFilter)) - { - Order = -9997; - } - } - - public class OpenApiAuthFilter : IAsyncAuthorizationFilter - { - public async Task OnAuthorizationAsync(AuthorizationFilterContext context) - { - if (context.Filters.Any(item => item is IAllowAnonymousFilter)) - { - context.HttpContext.Items["AllowAnonymous"] = true; - return; - } - - context.HttpContext.Items["OpenApi"] = true; - - var body = await context.HttpContext.Request.ReadBodyAsStringAsync(); - - var requestBase = body.FromJsonTo(); - - if (requestBase.Timestamp==null) - { - OpenApiException.Throw(OpenApiReturnCode.Error,"缺少timestamp参数"); - } - - if (!requestBase.Sign.Has()) - { - OpenApiException.Throw(OpenApiReturnCode.Error,"缺少sign参数"); - } - - if (!requestBase.AppId.Has()) - { - OpenApiException.Throw(OpenApiReturnCode.Error,"缺少appid参数"); - } - - var application = await RedisHelper.HGetAsync("OpenApi:Application", requestBase.AppId); - - context.HttpContext.Items["OpenApiAppKey"] = application.AppKey; - - if (!application.Enable) - { - OpenApiException.Throw(OpenApiReturnCode.Unauthorized); - } - - if (DateTimeHelper.ToUnixTimestamp(DateTime.Now) - requestBase.Timestamp > 60) - { - OpenApiException.Throw(OpenApiReturnCode.TimeStampExpired); - } - - requestBase.CheckSign(application.AppKey); - } - - } +using System; +using System.Linq; +using System.Threading.Tasks; +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Extension; +using Hncore.Infrastructure.Serializer; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Authorization; +using Microsoft.AspNetCore.Mvc.Filters; +using Hncore.Infrastructure.Core.Web; + +namespace Hncore.Infrastructure.OpenApi +{ + public class OpenApiAuthAttribute : TypeFilterAttribute + { + public OpenApiAuthAttribute() : base(typeof(OpenApiAuthFilter)) + { + Order = -9997; + } + } + + public class OpenApiAuthFilter : IAsyncAuthorizationFilter + { + public async Task OnAuthorizationAsync(AuthorizationFilterContext context) + { + if (context.Filters.Any(item => item is IAllowAnonymousFilter)) + { + context.HttpContext.Items["AllowAnonymous"] = true; + return; + } + + context.HttpContext.Items["OpenApi"] = true; + + var body = await context.HttpContext.Request.ReadBodyAsStringAsync(); + + var requestBase = body.FromJsonTo(); + + if (requestBase.Timestamp==null) + { + OpenApiException.Throw(OpenApiReturnCode.Error,"缺少timestamp参数"); + } + + if (!requestBase.Sign.Has()) + { + OpenApiException.Throw(OpenApiReturnCode.Error,"缺少sign参数"); + } + + if (!requestBase.AppId.Has()) + { + OpenApiException.Throw(OpenApiReturnCode.Error,"缺少appid参数"); + } + + var application = await RedisHelper.HGetAsync("OpenApi:Application", requestBase.AppId); + + context.HttpContext.Items["OpenApiAppKey"] = application.AppKey; + + if (!application.Enable) + { + OpenApiException.Throw(OpenApiReturnCode.Unauthorized); + } + + if (DateTimeHelper.ToUnixTimestamp(DateTime.Now) - requestBase.Timestamp > 60) + { + OpenApiException.Throw(OpenApiReturnCode.TimeStampExpired); + } + + requestBase.CheckSign(application.AppKey); + } + + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiException.cs b/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiException.cs index 452fd50..b7564a9 100644 --- a/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiException.cs +++ b/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiException.cs @@ -1,28 +1,28 @@ -using System; - -namespace Hncore.Infrastructure.OpenApi -{ - public class OpenApiException: Exception - { - public OpenApiReturnCode Code { get; } = OpenApiReturnCode.InternalError; - - public OpenApiException(string message) : base(message) - { - } - - public OpenApiException(OpenApiReturnCode code, string message = "") : base(message) - { - Code = code; - } - - public static void Throw(string message = "") - { - throw new OpenApiException(message); - } - - public static void Throw(OpenApiReturnCode code, string message = "") - { - throw new OpenApiException(code, message); - } - } +using System; + +namespace Hncore.Infrastructure.OpenApi +{ + public class OpenApiException: Exception + { + public OpenApiReturnCode Code { get; } = OpenApiReturnCode.InternalError; + + public OpenApiException(string message) : base(message) + { + } + + public OpenApiException(OpenApiReturnCode code, string message = "") : base(message) + { + Code = code; + } + + public static void Throw(string message = "") + { + throw new OpenApiException(message); + } + + public static void Throw(OpenApiReturnCode code, string message = "") + { + throw new OpenApiException(code, message); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiRequestBase.cs b/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiRequestBase.cs index 6655a3f..42a0357 100644 --- a/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiRequestBase.cs +++ b/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiRequestBase.cs @@ -1,30 +1,30 @@ -using System; -using System.Threading.Tasks; -using Hncore.Infrastructure.Extension; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace Hncore.Infrastructure.OpenApi -{ - public class OpenApiRequestBase - { - [JsonProperty("appid")] - public string AppId { get; set; } - - [JsonProperty("timestamp")] - public long? Timestamp { get; set; } - - [JsonProperty("sign")] - public string Sign { get; set; } - - public void CheckSign(string key) - { - var sign = OpenApiSignUtil.CreateSign(this.Timestamp.ToLong(), key); - - if (!String.Equals(sign, Sign, StringComparison.CurrentCultureIgnoreCase)) - { - OpenApiException.Throw(OpenApiReturnCode.SignError); - } - } - } +using System; +using System.Threading.Tasks; +using Hncore.Infrastructure.Extension; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Hncore.Infrastructure.OpenApi +{ + public class OpenApiRequestBase + { + [JsonProperty("appid")] + public string AppId { get; set; } + + [JsonProperty("timestamp")] + public long? Timestamp { get; set; } + + [JsonProperty("sign")] + public string Sign { get; set; } + + public void CheckSign(string key) + { + var sign = OpenApiSignUtil.CreateSign(this.Timestamp.ToLong(), key); + + if (!String.Equals(sign, Sign, StringComparison.CurrentCultureIgnoreCase)) + { + OpenApiException.Throw(OpenApiReturnCode.SignError); + } + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiResult.cs b/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiResult.cs index 7538c45..90a6e3a 100644 --- a/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiResult.cs +++ b/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiResult.cs @@ -1,111 +1,111 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Extension; -using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; - -namespace Hncore.Infrastructure.OpenApi -{ - public class OpenApiResult where T : class, new() - { - [JsonProperty("code")] public OpenApiReturnCode Code { get; private set; } - - [JsonProperty("message")] public string Message { get; private set; } = ""; - - [JsonProperty("timestamp")] public long Timestamp { get; set; } - - [JsonProperty("sign")] public string Sign { get; set; } - - [JsonProperty("data")] public T Data { get; set; } = new T(); - - private static readonly Dictionary Dic; - - static OpenApiResult() - { - Dic = ObjectExtension.ToDescriptionDictionary(); - } - - - public OpenApiResult(OpenApiReturnCode code = OpenApiReturnCode.Success, string message = "") - { - Code = code; - - if (string.IsNullOrEmpty(message) && Dic.ContainsKey(Code)) - { - Message = Dic[Code]; - } - else - { - Message = message; - } - - this.Timestamp = DateTimeHelper.ToUnixTimestamp(DateTime.Now); - } - - public void CreateSign(string key) - { - this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key); - } - - public OpenApiResult CreateSign(HttpContext httpContext) - { - var key = httpContext.Items["OpenApiAppKey"].ToString(); - - this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key); - - return this; - } - } - - public class OpenApiResult : OpenApiResult - { - public OpenApiResult(OpenApiReturnCode code = OpenApiReturnCode.Success, string message = "") : base(code, - message) - { - } - - public new OpenApiResult CreateSign(HttpContext httpContext) - { - var key = httpContext.Items["OpenApiAppKey"].ToString(); - - this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key); - - return this; - } - } - - public enum OpenApiReturnCode - { - /// - /// 成功 - /// - [Description("成功")] Success = 10000, - - /// - /// 验签失败 - /// - [Description("未授权")] Unauthorized = 40001, - - /// - /// 验签失败 - /// - [Description("验签失败")] SignError = 40002, - - /// - /// 时间戳过期 - /// - [Description("时间戳过期")] TimeStampExpired = 40003, - - /// - /// 内部错误 - /// - [Description("内部错误")] InternalError = 50000, - - /// - /// 处理失败 - /// - [Description("处理失败")] Error = 500001 - } +using System; +using System.Collections.Generic; +using System.ComponentModel; +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Extension; +using Microsoft.AspNetCore.Http; +using Newtonsoft.Json; + +namespace Hncore.Infrastructure.OpenApi +{ + public class OpenApiResult where T : class, new() + { + [JsonProperty("code")] public OpenApiReturnCode Code { get; private set; } + + [JsonProperty("message")] public string Message { get; private set; } = ""; + + [JsonProperty("timestamp")] public long Timestamp { get; set; } + + [JsonProperty("sign")] public string Sign { get; set; } + + [JsonProperty("data")] public T Data { get; set; } = new T(); + + private static readonly Dictionary Dic; + + static OpenApiResult() + { + Dic = ObjectExtension.ToDescriptionDictionary(); + } + + + public OpenApiResult(OpenApiReturnCode code = OpenApiReturnCode.Success, string message = "") + { + Code = code; + + if (string.IsNullOrEmpty(message) && Dic.ContainsKey(Code)) + { + Message = Dic[Code]; + } + else + { + Message = message; + } + + this.Timestamp = DateTimeHelper.ToUnixTimestamp(DateTime.Now); + } + + public void CreateSign(string key) + { + this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key); + } + + public OpenApiResult CreateSign(HttpContext httpContext) + { + var key = httpContext.Items["OpenApiAppKey"].ToString(); + + this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key); + + return this; + } + } + + public class OpenApiResult : OpenApiResult + { + public OpenApiResult(OpenApiReturnCode code = OpenApiReturnCode.Success, string message = "") : base(code, + message) + { + } + + public new OpenApiResult CreateSign(HttpContext httpContext) + { + var key = httpContext.Items["OpenApiAppKey"].ToString(); + + this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key); + + return this; + } + } + + public enum OpenApiReturnCode + { + /// + /// 成功 + /// + [Description("成功")] Success = 10000, + + /// + /// 验签失败 + /// + [Description("未授权")] Unauthorized = 40001, + + /// + /// 验签失败 + /// + [Description("验签失败")] SignError = 40002, + + /// + /// 时间戳过期 + /// + [Description("时间戳过期")] TimeStampExpired = 40003, + + /// + /// 内部错误 + /// + [Description("内部错误")] InternalError = 50000, + + /// + /// 处理失败 + /// + [Description("处理失败")] Error = 500001 + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiSignUtil.cs b/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiSignUtil.cs index 4b23567..72f7ecc 100644 --- a/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiSignUtil.cs +++ b/Infrastructure/Hncore.Infrastructure/OpenApi/OpenApiSignUtil.cs @@ -1,15 +1,15 @@ -using System.Collections.Generic; -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Data; -using Newtonsoft.Json.Linq; - -namespace Hncore.Infrastructure.OpenApi -{ - public static class OpenApiSignUtil - { - public static string CreateSign(long timestamp, string key) - { - return SecurityHelper.GetMd5Hash(timestamp.ToString() + key); - } - } +using System.Collections.Generic; +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Data; +using Newtonsoft.Json.Linq; + +namespace Hncore.Infrastructure.OpenApi +{ + public static class OpenApiSignUtil + { + public static string CreateSign(long timestamp, string key) + { + return SecurityHelper.GetMd5Hash(timestamp.ToString() + key); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/OperationLog/OperationLog.cs b/Infrastructure/Hncore.Infrastructure/OperationLog/OperationLog.cs index 2a31f57..fbf76b8 100644 --- a/Infrastructure/Hncore.Infrastructure/OperationLog/OperationLog.cs +++ b/Infrastructure/Hncore.Infrastructure/OperationLog/OperationLog.cs @@ -1,156 +1,156 @@ -using System; -using System.Threading.Tasks; -using Dapper; -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Serializer; -using MySql.Data.MySqlClient; -using Newtonsoft.Json; - -namespace Hncore.Infrastructure.OperationLog -{ - public class OperationLog - { - /// - /// 物业id - /// - [JsonProperty("owner_id")] - public int OwnerId { get; set; } - - /// - /// 创建时间 - /// - [JsonProperty("createtime")] - public DateTime CreateTime { get; set; } = DateTime.Now; - - /// - /// 更新时间 - /// - [JsonProperty("updatetime")] - public DateTime UpdateTime { get; set; } = DateTime.Now; - - /// - /// 删除标记 - /// - [JsonProperty("deletetag")] - public int DeleteTag { get; set; } = 0; - - /// - /// 创建人id - /// - [JsonProperty("creatorid")] - public int CreatorId { get; set; } - - /// - /// 更新人id - /// - [JsonProperty("updatorid")] - public int UpdatorId { get; set; } - - /// - /// 操作目标id - /// - [JsonProperty("targetid")] - public int TargetId { get; set; } - - /// - /// 操作人名 - /// - [JsonProperty("operator")] - public string Operator { get; set; } - - /// - /// 操作说明 - /// - [JsonProperty("opdesc")] - public string OpDesc { get; set; } - - /// - /// 操作前 - /// - [JsonProperty("beforeop")] - public string BeforeOp { get; set; } - - /// - /// 操作后 - /// - [JsonProperty("afterop")] - public string AfterOp { get; set; } - - /// - /// 操作对象所在小区编码 - /// - [JsonProperty("projectcode")] - public int ProjectCode { get; set; } - - /// - /// 小区名称 - /// - [JsonProperty("estatename")] - public string EstateName { get; set; } - - /// - /// 操作权限编码 - /// - [JsonProperty("permissioncode")] - public string PermissionCode { get; set; } - - /// - /// 操作权限标签 - /// - [JsonProperty("permissionlabel")] - public string PermissionLabel { get; set; } - - /// - /// 操作菜单编码 - /// - [JsonProperty("optype")] - public int OpType { get; set; } - - /// - /// 操作菜单名称 - /// - [JsonProperty("optypename")] - public string OpTypeName { get; set; } - - public void Write() - { - try - { - OperationLogStorage.WriteLog(this); - } - catch (Exception e) - { - LogHelper.Error("写操作日志失败", e); - } - } - public void WriteAsync() - { - Task.Run(()=> Write()); - } - } - - internal class OperationLogStorage - { - 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;"; - - private static string _proConn = - "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 -( -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);"; - - public static void WriteLog(OperationLog log) - { - string connString = EnvironmentVariableHelper.IsAspNetCoreProduction ? _proConn : _devConn; - - using (var conn = new MySqlConnection(connString)) - { - conn.Execute(_insertSql, log); - } - } - } +using System; +using System.Threading.Tasks; +using Dapper; +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Serializer; +using MySql.Data.MySqlClient; +using Newtonsoft.Json; + +namespace Hncore.Infrastructure.OperationLog +{ + public class OperationLog + { + /// + /// 物业id + /// + [JsonProperty("owner_id")] + public int OwnerId { get; set; } + + /// + /// 创建时间 + /// + [JsonProperty("createtime")] + public DateTime CreateTime { get; set; } = DateTime.Now; + + /// + /// 更新时间 + /// + [JsonProperty("updatetime")] + public DateTime UpdateTime { get; set; } = DateTime.Now; + + /// + /// 删除标记 + /// + [JsonProperty("deletetag")] + public int DeleteTag { get; set; } = 0; + + /// + /// 创建人id + /// + [JsonProperty("creatorid")] + public int CreatorId { get; set; } + + /// + /// 更新人id + /// + [JsonProperty("updatorid")] + public int UpdatorId { get; set; } + + /// + /// 操作目标id + /// + [JsonProperty("targetid")] + public int TargetId { get; set; } + + /// + /// 操作人名 + /// + [JsonProperty("operator")] + public string Operator { get; set; } + + /// + /// 操作说明 + /// + [JsonProperty("opdesc")] + public string OpDesc { get; set; } + + /// + /// 操作前 + /// + [JsonProperty("beforeop")] + public string BeforeOp { get; set; } + + /// + /// 操作后 + /// + [JsonProperty("afterop")] + public string AfterOp { get; set; } + + /// + /// 操作对象所在小区编码 + /// + [JsonProperty("projectcode")] + public int ProjectCode { get; set; } + + /// + /// 小区名称 + /// + [JsonProperty("estatename")] + public string EstateName { get; set; } + + /// + /// 操作权限编码 + /// + [JsonProperty("permissioncode")] + public string PermissionCode { get; set; } + + /// + /// 操作权限标签 + /// + [JsonProperty("permissionlabel")] + public string PermissionLabel { get; set; } + + /// + /// 操作菜单编码 + /// + [JsonProperty("optype")] + public int OpType { get; set; } + + /// + /// 操作菜单名称 + /// + [JsonProperty("optypename")] + public string OpTypeName { get; set; } + + public void Write() + { + try + { + OperationLogStorage.WriteLog(this); + } + catch (Exception e) + { + LogHelper.Error("写操作日志失败", e); + } + } + public void WriteAsync() + { + Task.Run(()=> Write()); + } + } + + internal class OperationLogStorage + { + 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;"; + + private static string _proConn = + "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 +( +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);"; + + public static void WriteLog(OperationLog log) + { + string connString = EnvironmentVariableHelper.IsAspNetCoreProduction ? _proConn : _devConn; + + using (var conn = new MySqlConnection(connString)) + { + conn.Execute(_insertSql, log); + } + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/SMS/AliSmsService.cs b/Infrastructure/Hncore.Infrastructure/SMS/AliSmsService.cs index 74f6452..070b857 100644 --- a/Infrastructure/Hncore.Infrastructure/SMS/AliSmsService.cs +++ b/Infrastructure/Hncore.Infrastructure/SMS/AliSmsService.cs @@ -1,46 +1,46 @@ -using Aliyun.Acs.Core; -using Aliyun.Acs.Core.Exceptions; -using Aliyun.Acs.Core.Http; -using Aliyun.Acs.Core.Profile; -using Hncore.Infrastructure.Serializer; -using System; -using System.Collections.Generic; -namespace Hncore.Infrastructure.SMS -{ - /// - /// 发送短信 - /// - public class AliSmsService - { - public static bool Send(string TemplateCode,object TemplateParam, string SignName="", params string[] PhoneNumbers) - { - IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", "LTAI4FmSkDSwFuXeLxsDB3jB", "r8FfRmoeWcCJyZSqqkQP2G3dKPPl2N"); - DefaultAcsClient client = new DefaultAcsClient(profile); - CommonRequest request = new CommonRequest(); - request.Method = MethodType.POST; - request.Domain = "dysmsapi.aliyuncs.com"; - request.Version = "2017-05-25"; - request.Action = "SendSms"; - // request.Protocol = ProtocolType.HTTP; - request.AddQueryParameters("PhoneNumbers", string.Join(",", PhoneNumbers)); - request.AddQueryParameters("SignName", SignName); - request.AddQueryParameters("TemplateCode", TemplateCode); - request.AddQueryParameters("TemplateParam", TemplateParam.ToJson()); - try - { - CommonResponse response = client.GetCommonResponse(request); - Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content)); - return true; - } - catch (ServerException e) - { - Console.WriteLine(e); - } - catch (ClientException e) - { - Console.WriteLine(e); - } - return false; - } - } -} +using Aliyun.Acs.Core; +using Aliyun.Acs.Core.Exceptions; +using Aliyun.Acs.Core.Http; +using Aliyun.Acs.Core.Profile; +using Hncore.Infrastructure.Serializer; +using System; +using System.Collections.Generic; +namespace Hncore.Infrastructure.SMS +{ + /// + /// 发送短信 + /// + public class AliSmsService + { + public static bool Send(string TemplateCode,object TemplateParam, string SignName="", params string[] PhoneNumbers) + { + IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", "LTAI4FmSkDSwFuXeLxsDB3jB", "r8FfRmoeWcCJyZSqqkQP2G3dKPPl2N"); + DefaultAcsClient client = new DefaultAcsClient(profile); + CommonRequest request = new CommonRequest(); + request.Method = MethodType.POST; + request.Domain = "dysmsapi.aliyuncs.com"; + request.Version = "2017-05-25"; + request.Action = "SendSms"; + // request.Protocol = ProtocolType.HTTP; + request.AddQueryParameters("PhoneNumbers", string.Join(",", PhoneNumbers)); + request.AddQueryParameters("SignName", SignName); + request.AddQueryParameters("TemplateCode", TemplateCode); + request.AddQueryParameters("TemplateParam", TemplateParam.ToJson()); + try + { + CommonResponse response = client.GetCommonResponse(request); + Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content)); + return true; + } + catch (ServerException e) + { + Console.WriteLine(e); + } + catch (ClientException e) + { + Console.WriteLine(e); + } + return false; + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/SMS/SendSMSService.cs b/Infrastructure/Hncore.Infrastructure/SMS/SendSMSService.cs index e864966..e272b0d 100644 --- a/Infrastructure/Hncore.Infrastructure/SMS/SendSMSService.cs +++ b/Infrastructure/Hncore.Infrastructure/SMS/SendSMSService.cs @@ -1,135 +1,135 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Serializer; -using Newtonsoft.Json; - -namespace Hncore.Infrastructure.SMS -{ - /// - /// 发送短信 - /// - public class SendSMSService - { - private static string smsApi = "http://dysmsapi.aliyuncs.com"; - private static string smsAuthorization = "Basic cGJsOjEyMzQ1NmFh"; - private static string smsAppId = smsAppId = "weiyuwuye"; - - - - /// - /// 发送短信 - /// - /// 发送内容 - /// 多个手机号逗号分隔 - /// - public async static Task SendSMS(string Content, string mobile) - { - if (string.IsNullOrEmpty(Content) || string.IsNullOrEmpty(mobile)) - { - throw new ArgumentException("SendSMS参数错误"); - } - mobile = mobile.Replace(';', ','); - var postData = new SMSData() { - Mobile=mobile, - SmsType=4, - Content=Content - }; - Dictionary headers = new Dictionary(); - headers.Add("Authorization", smsAuthorization); - headers.Add("AppId", smsAppId); - var res= await HttpPostAsync(smsApi, JsonConvert.SerializeObject(postData), "application/json", 30, headers); - // return response.Data; {"Code":"100000","Message":"发送成功","Data":null} - return JsonConvert.DeserializeObject(res) ; - - } - - /// - /// post请求 - /// - /// - /// - /// - /// - /// - /// - public static string HttpPost(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary headers = null) - { - postData = postData ?? ""; - using (HttpClient client = new HttpClient()) - { - if (headers != null) - { - foreach (var header in headers) - client.DefaultRequestHeaders.Add(header.Key, header.Value); - } - using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8)) - { - if (contentType != null) - httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); - - HttpResponseMessage response = client.PostAsync(url, httpContent).Result; - return response.Content.ReadAsStringAsync().Result; - } - } - } - - - public static async Task HttpPostAsync(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary headers = null) - { - postData = postData ?? ""; - using (HttpClient client = new HttpClient()) - { - client.Timeout = new TimeSpan(0, 0, timeOut); - if (headers != null) - { - foreach (var header in headers) - client.DefaultRequestHeaders.Add(header.Key, header.Value); - } - using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8)) - { - if (contentType != null) - httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); - - HttpResponseMessage response = await client.PostAsync(url, httpContent); - return await response.Content.ReadAsStringAsync(); - } - } - } - - public class APIResponse - { - /// - /// 业务状态码 - /// - public string Code { get; set; } - - /// - /// 业务消息,如:操作失败消息 - /// - public string Message { get; set; } - - /// - /// 业务实体数据 - /// - public T Data { get; set; } - } - - public class SMSData - { - public string Mobile { get; set; } - public string Content { get; set; } - public int SmsType { get; set; } - } - public class SMSDataResponse - { - public int Code { get; set; } - public string Message { get; set; } - public object Data { get; set; } - } - } -} +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Serializer; +using Newtonsoft.Json; + +namespace Hncore.Infrastructure.SMS +{ + /// + /// 发送短信 + /// + public class SendSMSService + { + private static string smsApi = "http://dysmsapi.aliyuncs.com"; + private static string smsAuthorization = "Basic cGJsOjEyMzQ1NmFh"; + private static string smsAppId = smsAppId = "weiyuwuye"; + + + + /// + /// 发送短信 + /// + /// 发送内容 + /// 多个手机号逗号分隔 + /// + public async static Task SendSMS(string Content, string mobile) + { + if (string.IsNullOrEmpty(Content) || string.IsNullOrEmpty(mobile)) + { + throw new ArgumentException("SendSMS参数错误"); + } + mobile = mobile.Replace(';', ','); + var postData = new SMSData() { + Mobile=mobile, + SmsType=4, + Content=Content + }; + Dictionary headers = new Dictionary(); + headers.Add("Authorization", smsAuthorization); + headers.Add("AppId", smsAppId); + var res= await HttpPostAsync(smsApi, JsonConvert.SerializeObject(postData), "application/json", 30, headers); + // return response.Data; {"Code":"100000","Message":"发送成功","Data":null} + return JsonConvert.DeserializeObject(res) ; + + } + + /// + /// post请求 + /// + /// + /// + /// + /// + /// + /// + public static string HttpPost(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary headers = null) + { + postData = postData ?? ""; + using (HttpClient client = new HttpClient()) + { + if (headers != null) + { + foreach (var header in headers) + client.DefaultRequestHeaders.Add(header.Key, header.Value); + } + using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8)) + { + if (contentType != null) + httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); + + HttpResponseMessage response = client.PostAsync(url, httpContent).Result; + return response.Content.ReadAsStringAsync().Result; + } + } + } + + + public static async Task HttpPostAsync(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary headers = null) + { + postData = postData ?? ""; + using (HttpClient client = new HttpClient()) + { + client.Timeout = new TimeSpan(0, 0, timeOut); + if (headers != null) + { + foreach (var header in headers) + client.DefaultRequestHeaders.Add(header.Key, header.Value); + } + using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8)) + { + if (contentType != null) + httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); + + HttpResponseMessage response = await client.PostAsync(url, httpContent); + return await response.Content.ReadAsStringAsync(); + } + } + } + + public class APIResponse + { + /// + /// 业务状态码 + /// + public string Code { get; set; } + + /// + /// 业务消息,如:操作失败消息 + /// + public string Message { get; set; } + + /// + /// 业务实体数据 + /// + public T Data { get; set; } + } + + public class SMSData + { + public string Mobile { get; set; } + public string Content { get; set; } + public int SmsType { get; set; } + } + public class SMSDataResponse + { + public int Code { get; set; } + public string Message { get; set; } + public object Data { get; set; } + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Serializer/JsonNetSetting.cs b/Infrastructure/Hncore.Infrastructure/Serializer/JsonNetSetting.cs index fc970f5..a817d9f 100644 --- a/Infrastructure/Hncore.Infrastructure/Serializer/JsonNetSetting.cs +++ b/Infrastructure/Hncore.Infrastructure/Serializer/JsonNetSetting.cs @@ -1,74 +1,74 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Hncore.Infrastructure.Common; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace Hncore.Infrastructure.Serializer -{ - public class NullToEmptyStringResolver : DefaultContractResolver - { - protected override IList CreateProperties(Type type, MemberSerialization memberSerialization) - { - return type.GetProperties() - .Select(p => - { - var jp = base.CreateProperty(p, memberSerialization); - jp.ValueProvider = new NullToEmptyStringValueProvider(p); - return jp; - }).ToList(); - } - } - - public class NullToEmptyStringValueProvider : IValueProvider - { - PropertyInfo _MemberInfo; - - public NullToEmptyStringValueProvider(PropertyInfo memberInfo) - { - _MemberInfo = memberInfo; - } - - public object GetValue(object target) - { - object result = _MemberInfo.GetValue(target); - if (_MemberInfo.PropertyType == typeof(string) && result == null) - { - result = ""; - } - else if ((_MemberInfo.PropertyType == typeof(DateTime) || _MemberInfo.PropertyType == typeof(DateTime?)) && - result != null) - { - if (result.ToString() == "0001/1/1 0:00:00" || result.ToString() == "1000/1/1 0:00:00") - { - result = DateTimeHelper.SqlMinTime; - } - - DateTime time = Convert.ToDateTime(result); - - if (time == DateTimeHelper.SqlMaxTime || time == DateTimeHelper.SqlMinTime || time == DateTime.MaxValue || - time == DateTime.MinValue) - { - result = ""; - } - } - else if (_MemberInfo.PropertyType.Name == "List`1" && result == null) - { - result = new List(); - } - else if (_MemberInfo.PropertyType.Name == "Object" && result == null) - { - result = new { }; - } - - return result; - } - - public void SetValue(object target, object value) - { - _MemberInfo.SetValue(target, value); - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Hncore.Infrastructure.Common; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Hncore.Infrastructure.Serializer +{ + public class NullToEmptyStringResolver : DefaultContractResolver + { + protected override IList CreateProperties(Type type, MemberSerialization memberSerialization) + { + return type.GetProperties() + .Select(p => + { + var jp = base.CreateProperty(p, memberSerialization); + jp.ValueProvider = new NullToEmptyStringValueProvider(p); + return jp; + }).ToList(); + } + } + + public class NullToEmptyStringValueProvider : IValueProvider + { + PropertyInfo _MemberInfo; + + public NullToEmptyStringValueProvider(PropertyInfo memberInfo) + { + _MemberInfo = memberInfo; + } + + public object GetValue(object target) + { + object result = _MemberInfo.GetValue(target); + if (_MemberInfo.PropertyType == typeof(string) && result == null) + { + result = ""; + } + else if ((_MemberInfo.PropertyType == typeof(DateTime) || _MemberInfo.PropertyType == typeof(DateTime?)) && + result != null) + { + if (result.ToString() == "0001/1/1 0:00:00" || result.ToString() == "1000/1/1 0:00:00") + { + result = DateTimeHelper.SqlMinTime; + } + + DateTime time = Convert.ToDateTime(result); + + if (time == DateTimeHelper.SqlMaxTime || time == DateTimeHelper.SqlMinTime || time == DateTime.MaxValue || + time == DateTime.MinValue) + { + result = ""; + } + } + else if (_MemberInfo.PropertyType.Name == "List`1" && result == null) + { + result = new List(); + } + else if (_MemberInfo.PropertyType.Name == "Object" && result == null) + { + result = new { }; + } + + return result; + } + + public void SetValue(object target, object value) + { + _MemberInfo.SetValue(target, value); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Serializer/ObjectExtension.cs b/Infrastructure/Hncore.Infrastructure/Serializer/ObjectExtension.cs index 875bd58..8208a73 100644 --- a/Infrastructure/Hncore.Infrastructure/Serializer/ObjectExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Serializer/ObjectExtension.cs @@ -1,185 +1,185 @@ -using System; -using System.ComponentModel; -using System.IO; -using System.Runtime.Serialization.Formatters.Binary; -using Hncore.Infrastructure.Common; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Hncore.Infrastructure.Serializer -{ - public static class ObjectExtension - { - #region 序列化为二进制 - - /// - /// 序列化位二进制 - /// - /// 要序列化的对象 - /// 字节数组 - public static byte[] SerializeBinary(this object request) - { - using (MemoryStream memStream = new MemoryStream()) - { - BinaryFormatter serializer = new BinaryFormatter(); - serializer.Serialize(memStream, request); - return memStream.GetBuffer(); - } - } - - #endregion - - #region 二进制反序列化 - - /// - /// 二进制反序列化 - /// - /// 字节数组 - /// 得到的对象 - public static T DeserializeBinary(this byte[] buf) where T : class, new() - { - if (buf == null) - { - return default(T); - } - - using (MemoryStream memStream = new MemoryStream(buf)) - { - memStream.Position = 0; - BinaryFormatter deserializer = new BinaryFormatter(); - T info = (T) deserializer.Deserialize(memStream); - memStream.Close(); - return info; - } - } - - #endregion - - #region Json序列化 - - /// - /// Json序列化 - /// - public static string ToJson(this object item, bool format = false) - { - using (StringWriter sw = new StringWriter()) - { - JsonSerializer serializer = JsonSerializer.Create( - new JsonSerializerSettings - { - DateFormatHandling = DateFormatHandling.MicrosoftDateFormat, - - ReferenceLoopHandling = ReferenceLoopHandling.Ignore, - - //NullValueHandling = NullValueHandling.Ignore, - - DateFormatString = "yyyy-MM-dd HH:mm:ss" - } - ); - - JsonWriter jsonWriter; - if (format) - { - jsonWriter = new JsonTextWriter(sw) - { - Formatting = Formatting.Indented, - Indentation = 4, - IndentChar = ' ' - }; - } - else - { - jsonWriter = new JsonTextWriter(sw); - } - - using (jsonWriter) - { - serializer.Serialize(jsonWriter, item); - } - - return sw.ToString(); - } - } - - #endregion - - #region Json反序列化 - - /// - /// Json反序列化 - /// - public static T FromJsonTo(this string jsonString) - { - try - { - if (!string.IsNullOrWhiteSpace(jsonString)) - { - T t = JsonConvert.DeserializeObject(jsonString); - return t; - } - else - { - return default(T); - } - } - catch (Exception ex) - { - LogHelper.Error($"Json反序列化出错", $"待反序列化的json字符串为{jsonString},错误信息:{ex}"); - return default(T); - } - } - - public static T FromJsonToOrDefault(this string str) - { - try - { - if (string.IsNullOrEmpty(str) || str == "[]" || str == "{}") - { - return default(T); - } - else - { - return JsonConvert.DeserializeObject(str); - } - } - catch (Exception ex) - { - LogHelper.Error($"Json反序列化出错", $"待反序列化的json字符串为{str},错误信息:{ex}"); - return default(T); - } - } - - #endregion - - #region 获取json字符串中的属性值 - /// - /// 获取json字符串中的属性值 - /// - /// json字符串 - /// "result:data:name" - /// - public static string JsonItemValue(this string str, string key) - { - var defaultValue = ""; - if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(key)) return defaultValue; - var JObject = JsonConvert.DeserializeObject(str) as JToken; - var res = GetJsonItem(JObject, key.Split(':'), 0) ?? defaultValue; - return res.ToString(); - } - - private static JToken GetJsonItem(JToken JToken, string[] arr, int index) - { - if (JToken == null || index == arr.Length) - { - return JToken; - } - else - { - JToken = JToken[arr[index]]; - index++; - } - return GetJsonItem(JToken, arr, index); - } - #endregion - } +using System; +using System.ComponentModel; +using System.IO; +using System.Runtime.Serialization.Formatters.Binary; +using Hncore.Infrastructure.Common; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Hncore.Infrastructure.Serializer +{ + public static class ObjectExtension + { + #region 序列化为二进制 + + /// + /// 序列化位二进制 + /// + /// 要序列化的对象 + /// 字节数组 + public static byte[] SerializeBinary(this object request) + { + using (MemoryStream memStream = new MemoryStream()) + { + BinaryFormatter serializer = new BinaryFormatter(); + serializer.Serialize(memStream, request); + return memStream.GetBuffer(); + } + } + + #endregion + + #region 二进制反序列化 + + /// + /// 二进制反序列化 + /// + /// 字节数组 + /// 得到的对象 + public static T DeserializeBinary(this byte[] buf) where T : class, new() + { + if (buf == null) + { + return default(T); + } + + using (MemoryStream memStream = new MemoryStream(buf)) + { + memStream.Position = 0; + BinaryFormatter deserializer = new BinaryFormatter(); + T info = (T) deserializer.Deserialize(memStream); + memStream.Close(); + return info; + } + } + + #endregion + + #region Json序列化 + + /// + /// Json序列化 + /// + public static string ToJson(this object item, bool format = false) + { + using (StringWriter sw = new StringWriter()) + { + JsonSerializer serializer = JsonSerializer.Create( + new JsonSerializerSettings + { + DateFormatHandling = DateFormatHandling.MicrosoftDateFormat, + + ReferenceLoopHandling = ReferenceLoopHandling.Ignore, + + //NullValueHandling = NullValueHandling.Ignore, + + DateFormatString = "yyyy-MM-dd HH:mm:ss" + } + ); + + JsonWriter jsonWriter; + if (format) + { + jsonWriter = new JsonTextWriter(sw) + { + Formatting = Formatting.Indented, + Indentation = 4, + IndentChar = ' ' + }; + } + else + { + jsonWriter = new JsonTextWriter(sw); + } + + using (jsonWriter) + { + serializer.Serialize(jsonWriter, item); + } + + return sw.ToString(); + } + } + + #endregion + + #region Json反序列化 + + /// + /// Json反序列化 + /// + public static T FromJsonTo(this string jsonString) + { + try + { + if (!string.IsNullOrWhiteSpace(jsonString)) + { + T t = JsonConvert.DeserializeObject(jsonString); + return t; + } + else + { + return default(T); + } + } + catch (Exception ex) + { + LogHelper.Error($"Json反序列化出错", $"待反序列化的json字符串为{jsonString},错误信息:{ex}"); + return default(T); + } + } + + public static T FromJsonToOrDefault(this string str) + { + try + { + if (string.IsNullOrEmpty(str) || str == "[]" || str == "{}") + { + return default(T); + } + else + { + return JsonConvert.DeserializeObject(str); + } + } + catch (Exception ex) + { + LogHelper.Error($"Json反序列化出错", $"待反序列化的json字符串为{str},错误信息:{ex}"); + return default(T); + } + } + + #endregion + + #region 获取json字符串中的属性值 + /// + /// 获取json字符串中的属性值 + /// + /// json字符串 + /// "result:data:name" + /// + public static string JsonItemValue(this string str, string key) + { + var defaultValue = ""; + if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(key)) return defaultValue; + var JObject = JsonConvert.DeserializeObject(str) as JToken; + var res = GetJsonItem(JObject, key.Split(':'), 0) ?? defaultValue; + return res.ToString(); + } + + private static JToken GetJsonItem(JToken JToken, string[] arr, int index) + { + if (JToken == null || index == arr.Length) + { + return JToken; + } + else + { + JToken = JToken[arr[index]]; + index++; + } + return GetJsonItem(JToken, arr, index); + } + #endregion + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Serializer/XML.cs b/Infrastructure/Hncore.Infrastructure/Serializer/XML.cs index e1fcac0..90031d9 100644 --- a/Infrastructure/Hncore.Infrastructure/Serializer/XML.cs +++ b/Infrastructure/Hncore.Infrastructure/Serializer/XML.cs @@ -1,54 +1,54 @@ -using System.IO; -using System.Xml.Serialization; - -namespace Hncore.Infrastructure.Serializer -{ - public class XML - { - #region 将C#数据实体转化为xml数据 - - /// - /// 将C#数据实体转化为xml数据 - /// - /// 要转化的数据实体 - /// xml格式字符串 - public static string XmlSerialize(T obj) - { - using (MemoryStream stream = new MemoryStream()) - { - XmlSerializer xml = new XmlSerializer(typeof(T)); - - //序列化对象 - xml.Serialize(stream, obj); - - stream.Position = 0; - using (StreamReader sr = new StreamReader(stream)) - { - string str = sr.ReadToEnd(); - - return str; - } - } - } - - #endregion - - #region 将xml数据转化为C#数据实体 - - /// - /// 将xml数据转化为C#数据实体 - /// - /// 符合xml格式的字符串 - /// T类型的对象 - public static T XmlDeserialize(string xml) - { - XmlSerializer xmldes = new XmlSerializer(typeof(T)); - using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml.ToCharArray()))) - { - return (T)xmldes.Deserialize(stream); - } - } - - #endregion - } +using System.IO; +using System.Xml.Serialization; + +namespace Hncore.Infrastructure.Serializer +{ + public class XML + { + #region 将C#数据实体转化为xml数据 + + /// + /// 将C#数据实体转化为xml数据 + /// + /// 要转化的数据实体 + /// xml格式字符串 + public static string XmlSerialize(T obj) + { + using (MemoryStream stream = new MemoryStream()) + { + XmlSerializer xml = new XmlSerializer(typeof(T)); + + //序列化对象 + xml.Serialize(stream, obj); + + stream.Position = 0; + using (StreamReader sr = new StreamReader(stream)) + { + string str = sr.ReadToEnd(); + + return str; + } + } + } + + #endregion + + #region 将xml数据转化为C#数据实体 + + /// + /// 将xml数据转化为C#数据实体 + /// + /// 符合xml格式的字符串 + /// T类型的对象 + public static T XmlDeserialize(string xml) + { + XmlSerializer xmldes = new XmlSerializer(typeof(T)); + using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml.ToCharArray()))) + { + return (T)xmldes.Deserialize(stream); + } + } + + #endregion + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Service/IServiceCollectionExtension.cs b/Infrastructure/Hncore.Infrastructure/Service/IServiceCollectionExtension.cs index 3cb4095..fedf0d2 100644 --- a/Infrastructure/Hncore.Infrastructure/Service/IServiceCollectionExtension.cs +++ b/Infrastructure/Hncore.Infrastructure/Service/IServiceCollectionExtension.cs @@ -1,14 +1,14 @@ -using Microsoft.Extensions.DependencyInjection; - -namespace Hncore.Infrastructure.Service -{ - public static class IServiceCollectionExtension - { - public static void AddServiceClient(this IServiceCollection service, string baseUrl) - { - ServiceHttpClient._BaseUrl = baseUrl; - - service.AddSingleton(); - } - } +using Microsoft.Extensions.DependencyInjection; + +namespace Hncore.Infrastructure.Service +{ + public static class IServiceCollectionExtension + { + public static void AddServiceClient(this IServiceCollection service, string baseUrl) + { + ServiceHttpClient._BaseUrl = baseUrl; + + service.AddSingleton(); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Service/ServiceBase.cs b/Infrastructure/Hncore.Infrastructure/Service/ServiceBase.cs index 9620151..3286f31 100644 --- a/Infrastructure/Hncore.Infrastructure/Service/ServiceBase.cs +++ b/Infrastructure/Hncore.Infrastructure/Service/ServiceBase.cs @@ -1,205 +1,205 @@ -using Hncore.Infrastructure.Data; -using Hncore.Infrastructure.DDD; -using Hncore.Infrastructure.EF; -using Hncore.Infrastructure.EntitiesExtension; -using Hncore.Infrastructure.WebApi; -using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Threading.Tasks; - -namespace Hncore.Infrastructure.Service -{ - - public interface IFindService - { - - } - - public class ServiceBase : IFindService where TEntity : class - { - IHttpContextAccessor m_HttpContextAccessor; - - public HttpContext HttpContext - { - get => m_HttpContextAccessor.HttpContext; - } - public ManageUserInfo ManagerInfo - { - get => HttpContext.Request.GetManageUserInfo(); - } - protected DbContextBase m_DbContextBase { get; set; } - public ServiceBase(DbContextBase dbContext, IHttpContextAccessor httpContextAccessor) - { - m_DbContextBase = dbContext; - m_HttpContextAccessor = httpContextAccessor; - } - - - public virtual async Task GetById(object id) - { - return await m_DbContextBase.Set().FindByIdAsync(id); - } - - public virtual async Task Add(TEntity entity, bool autoSave = true) - { - var ret = await m_DbContextBase.Set().AddAsync(entity); - if (autoSave) - await m_DbContextBase.SaveChangesAsync(); - return ret.Entity; - } - public virtual async Task Adds(IEnumerable entitys, bool autoSave = true) - { - await m_DbContextBase.Set().AddRangeAsync(entitys); - if (autoSave) - await m_DbContextBase.SaveChangesAsync(); - } - public virtual async Task DeleteById(object id, bool autoSave = true) - { - var entity = await this.GetById(id); - return await Delete(entity, autoSave); - } - - public virtual async Task Delete(TEntity entity, bool autoSave = true) - { - //if (entity is ITenant) - //{ - // var tenantId = HttpContext.Request.GetManageUserInfo()?.TenantId; - // if (tenantId.HasValue && tenantId > 0 && (entity as ITenant).TenantId != tenantId) - // { - // return false; - // } - //} - - if (entity is ISoftDelete) - { - (entity as ISoftDelete).DeleteTag = 1; - m_DbContextBase.Set().Update(entity); - } - else - { - m_DbContextBase.Set().Remove(entity); - } - if (autoSave) - await m_DbContextBase.SaveChangesAsync(); - return true; - } - - public virtual async Task Deletes(IEnumerable entitys, bool autoSave = true) - { - if (entitys == null || entitys.Count() == 0) - return false; - - var entity = entitys.FirstOrDefault(); - - if (entity is ISoftDelete) - { - foreach(var item in entitys) { (entity as ISoftDelete).DeleteTag = 1; } - m_DbContextBase.Set().UpdateRange(entity); - } - else - { - m_DbContextBase.Set().RemoveRange(entity); - } - if (autoSave) - await m_DbContextBase.SaveChangesAsync(); - return true; - } - - - public virtual async Task Update(TEntity entity, bool autoSave = true) - { - //if (entity is ITenant) - //{ - // var tenantId = HttpContext.Request.GetManageUserInfo()?.TenantId; - // if (tenantId.HasValue && tenantId > 0 && (entity as ITenant).TenantId != tenantId) - // { - // return false; - // } - //} - m_DbContextBase.Set().Update(entity); - if (autoSave) - return (await m_DbContextBase.SaveChangesAsync()) > 0; - return true; - } - - public virtual async Task Update(IEnumerable list, bool autoSave = true) - { - m_DbContextBase.Set().UpdateRange(list); - if (autoSave) - await m_DbContextBase.SaveChangesAsync(); - return true; - } - public virtual IQueryable Query(bool noTracking = false) - { - var ret = m_DbContextBase.Set().AsQueryable(); - if (noTracking) - { - ret = ret.AsNoTracking(); - } - return ret; - } - public async virtual Task> GetAll(bool noTracking = false) - { - var ret = m_DbContextBase.Set().AsQueryable(); - if (noTracking) - { - ret = ret.AsNoTracking(); - } - return await ret.ToListAsync(); - } - public virtual IQueryable Query(Expression> exp=null, bool noTracking = false) - { - var ret = m_DbContextBase.Set().AsQueryable(); - if (exp != null) - { - ret = ret.Where(exp); - } - if (noTracking) - { - ret = ret.AsNoTracking(); - } - return ret; - } - public virtual async Task> Page(int page, int limit, Expression> exp = null, bool noTracking = false) - { - var ret = await Query(exp, noTracking).ListPagerAsync(limit, page, true); - return ret; - } - - public virtual async Task> PageDesc(int page, int limit, Expression> exp = null, bool noTracking = false, Expression> order = null) - { - - var query = Query(exp, noTracking); - if (order != null) - query = query.OrderByDescending(order); - - var ret = await query.ListPagerAsync(limit, page, true); - return ret; - } - - public virtual async Task> PageAsc(int page, int limit, Expression> exp = null, bool noTracking = false, Expression> order = null) - { - - var query = Query(exp, noTracking); - if (order != null) - query = query.OrderBy(order); - - var ret = await query.ListPagerAsync(limit, page, true); - return ret; - } - - public virtual bool Exist(Expression> expr) - { - return this.Query(expr).Count() > 0; - } - - public async Task Save() - { - return (await m_DbContextBase.SaveChangesAsync()) > 0; - } - } -} +using Hncore.Infrastructure.Data; +using Hncore.Infrastructure.DDD; +using Hncore.Infrastructure.EF; +using Hncore.Infrastructure.EntitiesExtension; +using Hncore.Infrastructure.WebApi; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; + +namespace Hncore.Infrastructure.Service +{ + + public interface IFindService + { + + } + + public class ServiceBase : IFindService where TEntity : class + { + IHttpContextAccessor m_HttpContextAccessor; + + public HttpContext HttpContext + { + get => m_HttpContextAccessor.HttpContext; + } + public ManageUserInfo ManagerInfo + { + get => HttpContext.Request.GetManageUserInfo(); + } + protected DbContextBase m_DbContextBase { get; set; } + public ServiceBase(DbContextBase dbContext, IHttpContextAccessor httpContextAccessor) + { + m_DbContextBase = dbContext; + m_HttpContextAccessor = httpContextAccessor; + } + + + public virtual async Task GetById(object id) + { + return await m_DbContextBase.Set().FindByIdAsync(id); + } + + public virtual async Task Add(TEntity entity, bool autoSave = true) + { + var ret = await m_DbContextBase.Set().AddAsync(entity); + if (autoSave) + await m_DbContextBase.SaveChangesAsync(); + return ret.Entity; + } + public virtual async Task Adds(IEnumerable entitys, bool autoSave = true) + { + await m_DbContextBase.Set().AddRangeAsync(entitys); + if (autoSave) + await m_DbContextBase.SaveChangesAsync(); + } + public virtual async Task DeleteById(object id, bool autoSave = true) + { + var entity = await this.GetById(id); + return await Delete(entity, autoSave); + } + + public virtual async Task Delete(TEntity entity, bool autoSave = true) + { + //if (entity is ITenant) + //{ + // var tenantId = HttpContext.Request.GetManageUserInfo()?.TenantId; + // if (tenantId.HasValue && tenantId > 0 && (entity as ITenant).TenantId != tenantId) + // { + // return false; + // } + //} + + if (entity is ISoftDelete) + { + (entity as ISoftDelete).DeleteTag = 1; + m_DbContextBase.Set().Update(entity); + } + else + { + m_DbContextBase.Set().Remove(entity); + } + if (autoSave) + await m_DbContextBase.SaveChangesAsync(); + return true; + } + + public virtual async Task Deletes(IEnumerable entitys, bool autoSave = true) + { + if (entitys == null || entitys.Count() == 0) + return false; + + var entity = entitys.FirstOrDefault(); + + if (entity is ISoftDelete) + { + foreach(var item in entitys) { (entity as ISoftDelete).DeleteTag = 1; } + m_DbContextBase.Set().UpdateRange(entity); + } + else + { + m_DbContextBase.Set().RemoveRange(entity); + } + if (autoSave) + await m_DbContextBase.SaveChangesAsync(); + return true; + } + + + public virtual async Task Update(TEntity entity, bool autoSave = true) + { + //if (entity is ITenant) + //{ + // var tenantId = HttpContext.Request.GetManageUserInfo()?.TenantId; + // if (tenantId.HasValue && tenantId > 0 && (entity as ITenant).TenantId != tenantId) + // { + // return false; + // } + //} + m_DbContextBase.Set().Update(entity); + if (autoSave) + return (await m_DbContextBase.SaveChangesAsync()) > 0; + return true; + } + + public virtual async Task Update(IEnumerable list, bool autoSave = true) + { + m_DbContextBase.Set().UpdateRange(list); + if (autoSave) + await m_DbContextBase.SaveChangesAsync(); + return true; + } + public virtual IQueryable Query(bool noTracking = false) + { + var ret = m_DbContextBase.Set().AsQueryable(); + if (noTracking) + { + ret = ret.AsNoTracking(); + } + return ret; + } + public async virtual Task> GetAll(bool noTracking = false) + { + var ret = m_DbContextBase.Set().AsQueryable(); + if (noTracking) + { + ret = ret.AsNoTracking(); + } + return await ret.ToListAsync(); + } + public virtual IQueryable Query(Expression> exp=null, bool noTracking = false) + { + var ret = m_DbContextBase.Set().AsQueryable(); + if (exp != null) + { + ret = ret.Where(exp); + } + if (noTracking) + { + ret = ret.AsNoTracking(); + } + return ret; + } + public virtual async Task> Page(int page, int limit, Expression> exp = null, bool noTracking = false) + { + var ret = await Query(exp, noTracking).ListPagerAsync(limit, page, true); + return ret; + } + + public virtual async Task> PageDesc(int page, int limit, Expression> exp = null, bool noTracking = false, Expression> order = null) + { + + var query = Query(exp, noTracking); + if (order != null) + query = query.OrderByDescending(order); + + var ret = await query.ListPagerAsync(limit, page, true); + return ret; + } + + public virtual async Task> PageAsc(int page, int limit, Expression> exp = null, bool noTracking = false, Expression> order = null) + { + + var query = Query(exp, noTracking); + if (order != null) + query = query.OrderBy(order); + + var ret = await query.ListPagerAsync(limit, page, true); + return ret; + } + + public virtual bool Exist(Expression> expr) + { + return this.Query(expr).Count() > 0; + } + + public async Task Save() + { + return (await m_DbContextBase.SaveChangesAsync()) > 0; + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Service/ServiceHttpClient.cs b/Infrastructure/Hncore.Infrastructure/Service/ServiceHttpClient.cs index e4d27fc..fa368d9 100644 --- a/Infrastructure/Hncore.Infrastructure/Service/ServiceHttpClient.cs +++ b/Infrastructure/Hncore.Infrastructure/Service/ServiceHttpClient.cs @@ -1,34 +1,34 @@ -using Hncore.Infrastructure.WebApi; -using System.Net.Http; - -namespace Hncore.Infrastructure.Service -{ - public class ServiceHttpClient - { - private IHttpClientFactory _httpClientFactory; - - internal static string _BaseUrl = ""; - - public string BaseUrl => _BaseUrl; - - public ServiceHttpClient(IHttpClientFactory httpClientFactory) - { - _httpClientFactory = httpClientFactory; - } - - public HttpClient CreateHttpClient() - { - var client = _httpClientFactory.CreateClient(); - client.BaseAddress = new System.Uri(_BaseUrl); - return client; - } - - public HttpClient CreateInternalClient() - { - var client = _httpClientFactory.CreateInternalAuthClient(); - client.BaseAddress = new System.Uri(_BaseUrl); - return client; - - } - } +using Hncore.Infrastructure.WebApi; +using System.Net.Http; + +namespace Hncore.Infrastructure.Service +{ + public class ServiceHttpClient + { + private IHttpClientFactory _httpClientFactory; + + internal static string _BaseUrl = ""; + + public string BaseUrl => _BaseUrl; + + public ServiceHttpClient(IHttpClientFactory httpClientFactory) + { + _httpClientFactory = httpClientFactory; + } + + public HttpClient CreateHttpClient() + { + var client = _httpClientFactory.CreateClient(); + client.BaseAddress = new System.Uri(_BaseUrl); + return client; + } + + public HttpClient CreateInternalClient() + { + var client = _httpClientFactory.CreateInternalAuthClient(); + client.BaseAddress = new System.Uri(_BaseUrl); + return client; + + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/Service/ServiceIOCExt.cs b/Infrastructure/Hncore.Infrastructure/Service/ServiceIOCExt.cs index 9694df4..5a476fb 100644 --- a/Infrastructure/Hncore.Infrastructure/Service/ServiceIOCExt.cs +++ b/Infrastructure/Hncore.Infrastructure/Service/ServiceIOCExt.cs @@ -1,26 +1,26 @@ -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Linq; -using System.Reflection; - -namespace Hncore.Infrastructure.Service -{ - public static class ServiceIOCExt - { - public static IServiceCollection AutoAddService(this IServiceCollection service, Type fromType = null) - { - if (fromType == null) - fromType = typeof(IFindService); - - var types = Assembly.GetCallingAssembly().GetTypes(); - - types = types.Where(m => fromType.IsAssignableFrom(m)).ToArray(); - - foreach (var type in types) - { - service.AddScoped(type); - } - return service; - } - } -} +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Linq; +using System.Reflection; + +namespace Hncore.Infrastructure.Service +{ + public static class ServiceIOCExt + { + public static IServiceCollection AutoAddService(this IServiceCollection service, Type fromType = null) + { + if (fromType == null) + fromType = typeof(IFindService); + + var types = Assembly.GetCallingAssembly().GetTypes(); + + types = types.Where(m => fromType.IsAssignableFrom(m)).ToArray(); + + foreach (var type in types) + { + service.AddScoped(type); + } + return service; + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Tree/DataNode.cs b/Infrastructure/Hncore.Infrastructure/Tree/DataNode.cs index 5c44ac9..cb524b9 100644 --- a/Infrastructure/Hncore.Infrastructure/Tree/DataNode.cs +++ b/Infrastructure/Hncore.Infrastructure/Tree/DataNode.cs @@ -1,74 +1,74 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Hncore.Infrastructure.Tree -{ - public class DataNode - { - public DataNode(TData data) - { - this.Data = data; - } - - public DataNode Parent { get; set; } - public TData Data { get; set; } - - public List> Children { get; set; } = new List>(); - - public bool IsLeaf { get { return this.Children.Count()==0; } } - - public void Traverse(Action> act) - { - act(this); - this.Children.ForEach(item => - { - item.Traverse(act); - }); - } - - public string GetFullPath(Func func, string separator = ".") - { - var parent = this.Parent; - var names = new List { func(this.Data) }; - while (parent != null) - { - names.Add(func(parent.Data)); - parent = parent.Parent; - } - names.Reverse(); - return string.Join(separator, names).TrimStart(separator.ToArray()); - } - - public DataNode SortAsc(Func exp) - { - if (this.Children.Count > 0) - { - Func, Tkey> iierExp = m => exp(m.Data); - this.Children.OrderBy(iierExp); - this.Children.ForEach(item => - { - item.SortAsc(exp); - }); - } - return this; - } - - public DataNode SortDesc(Func exp) - { - if (this.Children.Count > 0) - { - Func, Tkey> iierExp = m => exp(m.Data); - this.Children.OrderByDescending(iierExp); - this.Children.ForEach(item => - { - item.SortDesc(exp); - }); - } - - return this; - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Hncore.Infrastructure.Tree +{ + public class DataNode + { + public DataNode(TData data) + { + this.Data = data; + } + + public DataNode Parent { get; set; } + public TData Data { get; set; } + + public List> Children { get; set; } = new List>(); + + public bool IsLeaf { get { return this.Children.Count()==0; } } + + public void Traverse(Action> act) + { + act(this); + this.Children.ForEach(item => + { + item.Traverse(act); + }); + } + + public string GetFullPath(Func func, string separator = ".") + { + var parent = this.Parent; + var names = new List { func(this.Data) }; + while (parent != null) + { + names.Add(func(parent.Data)); + parent = parent.Parent; + } + names.Reverse(); + return string.Join(separator, names).TrimStart(separator.ToArray()); + } + + public DataNode SortAsc(Func exp) + { + if (this.Children.Count > 0) + { + Func, Tkey> iierExp = m => exp(m.Data); + this.Children.OrderBy(iierExp); + this.Children.ForEach(item => + { + item.SortAsc(exp); + }); + } + return this; + } + + public DataNode SortDesc(Func exp) + { + if (this.Children.Count > 0) + { + Func, Tkey> iierExp = m => exp(m.Data); + this.Children.OrderByDescending(iierExp); + this.Children.ForEach(item => + { + item.SortDesc(exp); + }); + } + + return this; + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/Tree/DataTree.cs b/Infrastructure/Hncore.Infrastructure/Tree/DataTree.cs index 8d3bb83..8e41ad4 100644 --- a/Infrastructure/Hncore.Infrastructure/Tree/DataTree.cs +++ b/Infrastructure/Hncore.Infrastructure/Tree/DataTree.cs @@ -1,60 +1,60 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Hncore.Infrastructure.Tree -{ - public class DataTree - { - /// - /// - /// - /// 得到第一级节点条件 - /// 得到孩子得条件 - public static DataNode Load(IEnumerable datas, Func topPredicate, Func childPredicate) where TData : new() - { - var root = new DataNode(new TData() { }); - if (datas == null || datas.Count() == 0) - return root; - var tops = datas.Where(topPredicate); - - foreach (var p in tops) - { - LoadChildren(datas, root, p, childPredicate); - } - return root; - } - private static void LoadChildren(IEnumerable datas,DataNode topNode, TData p, Func childPredicate) - { - var pNode = new DataNode(p); - pNode.Parent = topNode; - topNode.Children.Add(pNode); - - var childDatas = datas.Where(item=>childPredicate(p,item)) ; - - if (childDatas.Count() > 0) - { - foreach (var childData in childDatas) - { - LoadChildren(datas,pNode, childData, childPredicate); - } - } - } - - - public static void Traverse(DataNode rootNode, Action> act, bool root = true) - { - if (root) - { - rootNode.Traverse(act); - } - else - { - rootNode.Children.ForEach(item => - { - item.Traverse(act); - }); - } - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Hncore.Infrastructure.Tree +{ + public class DataTree + { + /// + /// + /// + /// 得到第一级节点条件 + /// 得到孩子得条件 + public static DataNode Load(IEnumerable datas, Func topPredicate, Func childPredicate) where TData : new() + { + var root = new DataNode(new TData() { }); + if (datas == null || datas.Count() == 0) + return root; + var tops = datas.Where(topPredicate); + + foreach (var p in tops) + { + LoadChildren(datas, root, p, childPredicate); + } + return root; + } + private static void LoadChildren(IEnumerable datas,DataNode topNode, TData p, Func childPredicate) + { + var pNode = new DataNode(p); + pNode.Parent = topNode; + topNode.Children.Add(pNode); + + var childDatas = datas.Where(item=>childPredicate(p,item)) ; + + if (childDatas.Count() > 0) + { + foreach (var childData in childDatas) + { + LoadChildren(datas,pNode, childData, childPredicate); + } + } + } + + + public static void Traverse(DataNode rootNode, Action> act, bool root = true) + { + if (root) + { + rootNode.Traverse(act); + } + else + { + rootNode.Children.ForEach(item => + { + item.Traverse(act); + }); + } + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/CommonController/CheckController.cs b/Infrastructure/Hncore.Infrastructure/WebApi/CommonController/CheckController.cs index 9dfa160..8761555 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/CommonController/CheckController.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/CommonController/CheckController.cs @@ -1,16 +1,16 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Hncore.Infrastructure.WebApi -{ - [Route("/check")] - public class CheckController: ControllerBase - { - [HttpGet] - [AllowAnonymous] - public IActionResult Get() - { - return Ok("ok"); - } - } +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Hncore.Infrastructure.WebApi +{ + [Route("/check")] + public class CheckController: ControllerBase + { + [HttpGet] + [AllowAnonymous] + public IActionResult Get() + { + return Ok("ok"); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/CommonController/EtorControllerBase.cs b/Infrastructure/Hncore.Infrastructure/WebApi/CommonController/EtorControllerBase.cs index 0b0c2ac..496d4ee 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/CommonController/EtorControllerBase.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/CommonController/EtorControllerBase.cs @@ -1,124 +1,124 @@ -using System; -using System.IO; -using System.Text; -using System.Threading.Tasks; -using Hncore.Infrastructure.EF; -using Hncore.Infrastructure.Extension; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Abstractions; -using Microsoft.AspNetCore.Mvc.ModelBinding; -using Microsoft.AspNetCore.Mvc.Razor; -using Microsoft.AspNetCore.Mvc.Rendering; -using Microsoft.AspNetCore.Mvc.ViewEngines; -using Microsoft.AspNetCore.Mvc.ViewFeatures; -using Microsoft.AspNetCore.Routing; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Storage; -using Microsoft.Extensions.DependencyInjection; - -namespace Hncore.Infrastructure.WebApi -{ - [ApiController] - public class HncoreControllerBase : ControllerBase - { - protected ApiResult Success() - { - return new ApiResult(ResultCode.C_SUCCESS, ""); - } - - protected ApiResult Success(T data, string message = "") - { - return new ApiResult(ResultCode.C_SUCCESS, message) {Data = data}; - } - - protected ApiResult Error(string message = "") - { - return new ApiResult(ResultCode.C_UNKNOWN_ERROR, message); - } - - protected ApiResult Error(ResultCode code, string message = "") - { - return new ApiResult(code, message); - } - - protected ApiResult UofCommit(string message = "") - { - RepositoryDbContext.SaveChanges(); - - return Success(message); - } - - protected ApiResult UofCommit(Func func, string message = "") - { - RepositoryDbContext.SaveChanges(); - - return Success(func(), message); - } - - protected async Task UofCommitAsync(string message = "") - { - await RepositoryDbContext.SaveChangesAsync(); - - return Success(message); - } - - protected async Task UofCommitAsync(IDbContextTransaction trans, string message = "") - { - await RepositoryDbContext.SaveChangesAsync(); - - trans.Commit(); - - return Success(message); - } - - protected async Task UofCommitAsync(Func func, string message = "") - { - await RepositoryDbContext.SaveChangesAsync(); - - return Success(func(), message); - } - - - protected DbContext RepositoryDbContext => - Request.HttpContext - .RequestServices - .GetService() - .DbContext; - - protected async Task RenderViewToStringAsync(string viewName, object model = null) - { - using (var sw = new StringWriter()) - { - var actionContext = new ActionContext(HttpContext, new RouteData(), new ActionDescriptor()); - - var viewResult = HttpContext.RequestServices.GetService() - .FindView(actionContext, viewName, false); - - if (viewResult.View == null) - { - throw new ArgumentNullException($"未找到视图{viewName}"); - } - - var viewDictionary = - new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) - { - Model = model - }; - - var viewContext = new ViewContext( - actionContext, - viewResult.View, - viewDictionary, - new TempDataDictionary(actionContext.HttpContext, - HttpContext.RequestServices.GetService()), - sw, - new HtmlHelperOptions() - ); - - await viewResult.View.RenderAsync(viewContext); - - return sw.ToString().HtmlDecode(); - } - } - } +using System; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using Hncore.Infrastructure.EF; +using Hncore.Infrastructure.Extension; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.Razor; +using Microsoft.AspNetCore.Mvc.Rendering; +using Microsoft.AspNetCore.Mvc.ViewEngines; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.DependencyInjection; + +namespace Hncore.Infrastructure.WebApi +{ + [ApiController] + public class HncoreControllerBase : ControllerBase + { + protected ApiResult Success() + { + return new ApiResult(ResultCode.C_SUCCESS, ""); + } + + protected ApiResult Success(T data, string message = "") + { + return new ApiResult(ResultCode.C_SUCCESS, message) {Data = data}; + } + + protected ApiResult Error(string message = "") + { + return new ApiResult(ResultCode.C_UNKNOWN_ERROR, message); + } + + protected ApiResult Error(ResultCode code, string message = "") + { + return new ApiResult(code, message); + } + + protected ApiResult UofCommit(string message = "") + { + RepositoryDbContext.SaveChanges(); + + return Success(message); + } + + protected ApiResult UofCommit(Func func, string message = "") + { + RepositoryDbContext.SaveChanges(); + + return Success(func(), message); + } + + protected async Task UofCommitAsync(string message = "") + { + await RepositoryDbContext.SaveChangesAsync(); + + return Success(message); + } + + protected async Task UofCommitAsync(IDbContextTransaction trans, string message = "") + { + await RepositoryDbContext.SaveChangesAsync(); + + trans.Commit(); + + return Success(message); + } + + protected async Task UofCommitAsync(Func func, string message = "") + { + await RepositoryDbContext.SaveChangesAsync(); + + return Success(func(), message); + } + + + protected DbContext RepositoryDbContext => + Request.HttpContext + .RequestServices + .GetService() + .DbContext; + + protected async Task RenderViewToStringAsync(string viewName, object model = null) + { + using (var sw = new StringWriter()) + { + var actionContext = new ActionContext(HttpContext, new RouteData(), new ActionDescriptor()); + + var viewResult = HttpContext.RequestServices.GetService() + .FindView(actionContext, viewName, false); + + if (viewResult.View == null) + { + throw new ArgumentNullException($"未找到视图{viewName}"); + } + + var viewDictionary = + new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) + { + Model = model + }; + + var viewContext = new ViewContext( + actionContext, + viewResult.View, + viewDictionary, + new TempDataDictionary(actionContext.HttpContext, + HttpContext.RequestServices.GetService()), + sw, + new HtmlHelperOptions() + ); + + await viewResult.View.RenderAsync(viewContext); + + return sw.ToString().HtmlDecode(); + } + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/CommonController/PodHookController.cs b/Infrastructure/Hncore.Infrastructure/WebApi/CommonController/PodHookController.cs index 04ce1aa..671cc1a 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/CommonController/PodHookController.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/CommonController/PodHookController.cs @@ -1,35 +1,35 @@ -using System; -using System.Threading.Tasks; -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Common.DingTalk; -using Hncore.Infrastructure.Extension; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Hncore.Infrastructure.WebApi -{ - [Route("/pod/[action]")] - public class PodHookController : ControllerBase - { - [HttpGet, AllowAnonymous] - public async Task PreStop() - { - LogHelper.Warn("应用即将退出"); - - if (EnvironmentVariableHelper.IsAspNetCoreProduction) - { - await DingTalkHelper.SendMessage(new MarkDownModel() - { - markdown = new markdown() - { - title = "应用即将退出", - text = "### 应用即将退出\n\nhostname:" + EnvironmentVariableHelper.HostName + "\n\n" + - DateTime.Now.Format("yyyy-MM-dd HH:mm:ss") - } - }); - } - - return Ok(); - } - } +using System; +using System.Threading.Tasks; +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Common.DingTalk; +using Hncore.Infrastructure.Extension; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Hncore.Infrastructure.WebApi +{ + [Route("/pod/[action]")] + public class PodHookController : ControllerBase + { + [HttpGet, AllowAnonymous] + public async Task PreStop() + { + LogHelper.Warn("应用即将退出"); + + if (EnvironmentVariableHelper.IsAspNetCoreProduction) + { + await DingTalkHelper.SendMessage(new MarkDownModel() + { + markdown = new markdown() + { + title = "应用即将退出", + text = "### 应用即将退出\n\nhostname:" + EnvironmentVariableHelper.HostName + "\n\n" + + DateTime.Now.Format("yyyy-MM-dd HH:mm:ss") + } + }); + } + + return Ok(); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/DTO/ApiResult.cs b/Infrastructure/Hncore.Infrastructure/WebApi/DTO/ApiResult.cs index bb4b2d5..62246b3 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/DTO/ApiResult.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/DTO/ApiResult.cs @@ -1,274 +1,274 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using Hncore.Infrastructure.Data; -using Hncore.Infrastructure.Extension; -using Newtonsoft.Json; - -namespace Hncore.Infrastructure.WebApi -{ - - public class ApiResult - { - public ApiResult() - { - - } - public ApiResult(object data):this(ResultCode.C_SUCCESS,"") - { - Data = data; - } - public ApiResult(ResultCode code = ResultCode.C_SUCCESS, string message = "") - { - Code = code; - Message = message; - } - [JsonProperty("Code")] public ResultCode Code { get; private set; } - - [JsonProperty("Message")] public string Message { get; private set; } = ""; - - [JsonProperty("Data")] public virtual object Data { get; set; } - - } - - public class ApiResult: ApiResult where T : class, new() - { - [JsonProperty("Data")] public new T Data { get; set; } - - - private static readonly Dictionary Dic; - - static ApiResult() - { - Dic = ObjectExtension.ToDescriptionDictionary(); - } - public ApiResult() - { - - } - public ApiResult(T data) : this(ResultCode.C_SUCCESS, "") - { - Data = data; - } - - public ApiResult(ResultCode code = ResultCode.C_SUCCESS, string message = "") : base(code, message) - { - } - - //public ApiResult(ResultCode code = ResultCode.C_SUCCESS, string message = ""):base(code,message) - //{ - // Code = code; - - // if (string.IsNullOrEmpty(message) && Dic.ContainsKey(Code)) - // { - // Message = Dic[Code]; - // } - // else - // { - // Message = message; - // } - //} - } - - //public class ApiResult : ApiResult - //{ - - // public ApiResult(ResultCode code = ResultCode.C_SUCCESS, string message = "") : base(code, message) - // { - // } - //} - - public class ApiResultPaged : ApiResult where T : class, new() - { - [JsonProperty("TotalCount")] public int TotalCount { get; set; } - - public ApiResultPaged(ResultCode code = ResultCode.C_SUCCESS, string message = "") : base(code, message) - { - } - } - - public static class PageDataExt - { - public static ApiResultPaged> ToApiResult(this PageData pageData) where T : class, new() - { - return new ApiResultPaged>() - { - TotalCount = pageData.RowCount, - Data = pageData.List - }; - } - - public static ApiResultPaged> ToApiResult(this PageData pageData) where T2 : class, new() - { - return new ApiResultPaged>() - { - TotalCount = pageData.RowCount, - Data = pageData.List.MapsTo().ToList() - }; - } - } - - public enum ResultCode - { - /// - /// 未知错误 - /// - [Description("服务正在更新中,请稍后再试")] C_UNKNOWN_ERROR = 0, - - /// - /// 成功 - /// - [Description("成功")] C_SUCCESS = 10000, - - /// - /// 验证码 - /// - [Description("验证码错误")] C_VERIFY_CODE_ERROR = 10001, - - /// - /// 参数 - /// - [Description("服务正在更新中,请稍后再试")] C_PARAM_ERROR = 10002, - - /// - /// 登录名 - /// - [Description("登录名错误")] C_LONGIN_NAME_ERROR = 10003, - - /// - /// 密码 - /// - [Description("密码错误")] C_PASSWORD_ERROR = 10004, - - /// - /// 无效操作 - /// - [Description("非法操作")] C_INVALID_ERROR = 10005, - - /// - /// 文件 - /// - [Description("文件错误")] C_FILE_ERROR = 10006, - - /// - /// 已存在错误 - /// - [Description("资源已存在错误")] C_ALREADY_EXISTS_ERROR = 10007, - - /// - /// 资源无法访问:不是资源的拥有者 - /// - [Description("不是资源的拥有者,资源无法访问")] C_OWNER_ERROR = 10008, - - /// - /// 资源不存在 - /// - [Description("资源不存在")] C_NOT_EXISTS_ERROR = 10009, - - /// - /// 新建角色出错 - /// - [Description("创建角色出错")] C_ROLE_CREATE_ERROR = 10010, - - /// - /// 新建权限出错 - /// - [Description("新建权限错误")] C_PERMISSION_CREATE_ERROR = 10011, - - /// - /// 绑定角色和权限出错 - /// - [Description("绑定角色和权限出错")] C_ROLE_PERMISSION_CREATE_ERROR = 10012, - - /// - /// 服务器繁忙,请稍后再试! - /// - [Description("服务器繁忙")] C_Server_Is_Busy = 10013, - - /// - /// 访问被禁止 - /// - [Description("禁止访问")] C_Access_Forbidden = 10014, - - /// - /// 非法操作 - /// - [Description("非法操作")] C_Illegal_Operation = 10015, - - /// - /// 无效的openID - /// - [Description("OpenID无效")] C_OPENID_ERROR = 10016, - - /// - /// 返回错误,但无需理会 - /// - [Description("可忽略的错误")] C_IGNORE_ERROR = 10017, - - /// - /// 用户信息错误 - /// - [Description("用户信息错误")] C_USERINFO_ERROR = 10018, - - /// - /// 用户需要认证 - /// - [Description("用户需要认证")] C_USER_SELECT_ERROR = 10019, - - /// - /// 过期 - /// - [Description("超时错误")] C_TIMEOUT_ERROR = 10020, - - /// - /// 手机和验证码不匹配 - /// - [Description("手机和验证码不匹配")] C_PHONE_CODE_ERROR = 10021, - - /// - /// 微信没有选择楼 - /// - [Description("微信没有选择楼")] C_WX_UNIT_UNSELECT_ERROR = 10022, - - /// - /// 黑名单错误 - /// - [Description("黑名单错误")] C_BLACKLIST_ERROR = 10023, - - /// - /// 支付失败 - /// - [Description("支付失败")] C_PAY_FAIL = 10024, - - /// - /// 重复支付 - /// - [Description("重复支付")] RepeatPay= 10025, - - /// - /// 重定向 - /// - [Description("重定向")] C_REDIRECT_URL = 100302, - - [Description("用户重定向")] C_USER_REDIRECT_URL = 900302, - - - [Description("人脸已经存在")] C_FACEKEY_EXIST_ERROR = 900303, - - [Description("人脸角度不正确")] C_FACE_ANGLE_ERROR = 900304, - - [Description("退款失败")] C_PAY_Refund = 900305, - - /// - /// 用户支付中 - /// - [Description("用户支付中")] C_USERPAYING = 900306, - - - [Description("审核中")] C_VISITOR_CHECKING = 11001, - [Description("已过期")] C_VISITOR_OUTTIME = 11002, - [Description("未到期")] C_VISITOR_NOTYETDUE = 11003, - - } +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using Hncore.Infrastructure.Data; +using Hncore.Infrastructure.Extension; +using Newtonsoft.Json; + +namespace Hncore.Infrastructure.WebApi +{ + + public class ApiResult + { + public ApiResult() + { + + } + public ApiResult(object data):this(ResultCode.C_SUCCESS,"") + { + Data = data; + } + public ApiResult(ResultCode code = ResultCode.C_SUCCESS, string message = "") + { + Code = code; + Message = message; + } + [JsonProperty("Code")] public ResultCode Code { get; private set; } + + [JsonProperty("Message")] public string Message { get; private set; } = ""; + + [JsonProperty("Data")] public virtual object Data { get; set; } + + } + + public class ApiResult: ApiResult where T : class, new() + { + [JsonProperty("Data")] public new T Data { get; set; } + + + private static readonly Dictionary Dic; + + static ApiResult() + { + Dic = ObjectExtension.ToDescriptionDictionary(); + } + public ApiResult() + { + + } + public ApiResult(T data) : this(ResultCode.C_SUCCESS, "") + { + Data = data; + } + + public ApiResult(ResultCode code = ResultCode.C_SUCCESS, string message = "") : base(code, message) + { + } + + //public ApiResult(ResultCode code = ResultCode.C_SUCCESS, string message = ""):base(code,message) + //{ + // Code = code; + + // if (string.IsNullOrEmpty(message) && Dic.ContainsKey(Code)) + // { + // Message = Dic[Code]; + // } + // else + // { + // Message = message; + // } + //} + } + + //public class ApiResult : ApiResult + //{ + + // public ApiResult(ResultCode code = ResultCode.C_SUCCESS, string message = "") : base(code, message) + // { + // } + //} + + public class ApiResultPaged : ApiResult where T : class, new() + { + [JsonProperty("TotalCount")] public int TotalCount { get; set; } + + public ApiResultPaged(ResultCode code = ResultCode.C_SUCCESS, string message = "") : base(code, message) + { + } + } + + public static class PageDataExt + { + public static ApiResultPaged> ToApiResult(this PageData pageData) where T : class, new() + { + return new ApiResultPaged>() + { + TotalCount = pageData.RowCount, + Data = pageData.List + }; + } + + public static ApiResultPaged> ToApiResult(this PageData pageData) where T2 : class, new() + { + return new ApiResultPaged>() + { + TotalCount = pageData.RowCount, + Data = pageData.List.MapsTo().ToList() + }; + } + } + + public enum ResultCode + { + /// + /// 未知错误 + /// + [Description("服务正在更新中,请稍后再试")] C_UNKNOWN_ERROR = 0, + + /// + /// 成功 + /// + [Description("成功")] C_SUCCESS = 10000, + + /// + /// 验证码 + /// + [Description("验证码错误")] C_VERIFY_CODE_ERROR = 10001, + + /// + /// 参数 + /// + [Description("服务正在更新中,请稍后再试")] C_PARAM_ERROR = 10002, + + /// + /// 登录名 + /// + [Description("登录名错误")] C_LONGIN_NAME_ERROR = 10003, + + /// + /// 密码 + /// + [Description("密码错误")] C_PASSWORD_ERROR = 10004, + + /// + /// 无效操作 + /// + [Description("非法操作")] C_INVALID_ERROR = 10005, + + /// + /// 文件 + /// + [Description("文件错误")] C_FILE_ERROR = 10006, + + /// + /// 已存在错误 + /// + [Description("资源已存在错误")] C_ALREADY_EXISTS_ERROR = 10007, + + /// + /// 资源无法访问:不是资源的拥有者 + /// + [Description("不是资源的拥有者,资源无法访问")] C_OWNER_ERROR = 10008, + + /// + /// 资源不存在 + /// + [Description("资源不存在")] C_NOT_EXISTS_ERROR = 10009, + + /// + /// 新建角色出错 + /// + [Description("创建角色出错")] C_ROLE_CREATE_ERROR = 10010, + + /// + /// 新建权限出错 + /// + [Description("新建权限错误")] C_PERMISSION_CREATE_ERROR = 10011, + + /// + /// 绑定角色和权限出错 + /// + [Description("绑定角色和权限出错")] C_ROLE_PERMISSION_CREATE_ERROR = 10012, + + /// + /// 服务器繁忙,请稍后再试! + /// + [Description("服务器繁忙")] C_Server_Is_Busy = 10013, + + /// + /// 访问被禁止 + /// + [Description("禁止访问")] C_Access_Forbidden = 10014, + + /// + /// 非法操作 + /// + [Description("非法操作")] C_Illegal_Operation = 10015, + + /// + /// 无效的openID + /// + [Description("OpenID无效")] C_OPENID_ERROR = 10016, + + /// + /// 返回错误,但无需理会 + /// + [Description("可忽略的错误")] C_IGNORE_ERROR = 10017, + + /// + /// 用户信息错误 + /// + [Description("用户信息错误")] C_USERINFO_ERROR = 10018, + + /// + /// 用户需要认证 + /// + [Description("用户需要认证")] C_USER_SELECT_ERROR = 10019, + + /// + /// 过期 + /// + [Description("超时错误")] C_TIMEOUT_ERROR = 10020, + + /// + /// 手机和验证码不匹配 + /// + [Description("手机和验证码不匹配")] C_PHONE_CODE_ERROR = 10021, + + /// + /// 微信没有选择楼 + /// + [Description("微信没有选择楼")] C_WX_UNIT_UNSELECT_ERROR = 10022, + + /// + /// 黑名单错误 + /// + [Description("黑名单错误")] C_BLACKLIST_ERROR = 10023, + + /// + /// 支付失败 + /// + [Description("支付失败")] C_PAY_FAIL = 10024, + + /// + /// 重复支付 + /// + [Description("重复支付")] RepeatPay= 10025, + + /// + /// 重定向 + /// + [Description("重定向")] C_REDIRECT_URL = 100302, + + [Description("用户重定向")] C_USER_REDIRECT_URL = 900302, + + + [Description("人脸已经存在")] C_FACEKEY_EXIST_ERROR = 900303, + + [Description("人脸角度不正确")] C_FACE_ANGLE_ERROR = 900304, + + [Description("退款失败")] C_PAY_Refund = 900305, + + /// + /// 用户支付中 + /// + [Description("用户支付中")] C_USERPAYING = 900306, + + + [Description("审核中")] C_VISITOR_CHECKING = 11001, + [Description("已过期")] C_VISITOR_OUTTIME = 11002, + [Description("未到期")] C_VISITOR_NOTYETDUE = 11003, + + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/DTO/EtorRequestBase.cs b/Infrastructure/Hncore.Infrastructure/WebApi/DTO/EtorRequestBase.cs index 13677ce..82e1309 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/DTO/EtorRequestBase.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/DTO/EtorRequestBase.cs @@ -1,126 +1,126 @@ -using Hncore.Infrastructure.Extension; -using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; - -namespace Hncore.Infrastructure.WebApi -{ - /// - /// 请求顶级父类 - /// - public class RequestBase - { - [JsonProperty("TenantId")] - [FromQuery(Name = "TenantId")] - public int? __tenantId { get; set; } - - /// - /// 隶属物业数据库ID - /// - [JsonIgnore] - public int TenantId - { - get => __tenantId.ToInt(); - set => __tenantId = value; - } - - [JsonProperty("OperaterId")] - [FromQuery(Name = "OperaterId")] - public int? __operaterId { get; set; } - - /// - /// 当前操作员数据库ID - /// - [JsonIgnore] - public int OperaterId - { - get => __operaterId.ToInt(); - set => __operaterId = value; - } - - [JsonProperty("ProjectCode")] - [FromQuery(Name = "ProjectCode")] - public int? __projectCode { get; set; } - - /// - /// 隶属项目编码 - /// - [JsonIgnore] - public int ProjectCode - { - get => __projectCode.ToInt(); - set => __projectCode = value; - } - } - - /// - /// 泛型请求父类(主要用于在请求时携带数据) - /// - /// 携带的数据类型 - public class RequestBase : RequestBase - { - /// - /// 请求携带的数据对象 - /// - public T Data { get; set; } - } - - /// - /// 分页请求父类(主要用于分页请求操作) - /// - /// - public class PageRequestBase : RequestBase - { - [JsonProperty("PageIndex")] - [FromQuery(Name = "PageIndex")] - public int? __pageIndex { get; set; } = 1; - - /// - /// 当前页码 - /// - [JsonIgnore] - public int PageIndex - { - get => __pageIndex.ToInt(); - set => __pageIndex = value; - } - - [JsonProperty("PageSize")] - [FromQuery(Name = "PageSize")] - public int? __pageSize { get; set; } = 50; - - /// - /// 每页条目数 - /// - [JsonIgnore] - public int PageSize - { - get => __pageSize.ToInt(); - set => __pageSize = value; - } - - public string KeyWord { get; set; } - } - - /// - /// 泛型分页请求父类(在分页请求的基础之上携带数据) - /// - /// 携带的数据类型 - public class PageRequestBase : PageRequestBase - { - /// - /// 请求携带的数据对象 - /// - public T Data { get; set; } - } - - /// - /// 主键ID查询请求类(主要用于根据一个主键ID查询单条数据的情况) - /// - public class QueryByIdRequest : RequestBase - { - /// - /// 记录的数据库主键ID - /// - public int Id { get; set; } - } +using Hncore.Infrastructure.Extension; +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; + +namespace Hncore.Infrastructure.WebApi +{ + /// + /// 请求顶级父类 + /// + public class RequestBase + { + [JsonProperty("TenantId")] + [FromQuery(Name = "TenantId")] + public int? __tenantId { get; set; } + + /// + /// 隶属物业数据库ID + /// + [JsonIgnore] + public int TenantId + { + get => __tenantId.ToInt(); + set => __tenantId = value; + } + + [JsonProperty("OperaterId")] + [FromQuery(Name = "OperaterId")] + public int? __operaterId { get; set; } + + /// + /// 当前操作员数据库ID + /// + [JsonIgnore] + public int OperaterId + { + get => __operaterId.ToInt(); + set => __operaterId = value; + } + + [JsonProperty("ProjectCode")] + [FromQuery(Name = "ProjectCode")] + public int? __projectCode { get; set; } + + /// + /// 隶属项目编码 + /// + [JsonIgnore] + public int ProjectCode + { + get => __projectCode.ToInt(); + set => __projectCode = value; + } + } + + /// + /// 泛型请求父类(主要用于在请求时携带数据) + /// + /// 携带的数据类型 + public class RequestBase : RequestBase + { + /// + /// 请求携带的数据对象 + /// + public T Data { get; set; } + } + + /// + /// 分页请求父类(主要用于分页请求操作) + /// + /// + public class PageRequestBase : RequestBase + { + [JsonProperty("PageIndex")] + [FromQuery(Name = "PageIndex")] + public int? __pageIndex { get; set; } = 1; + + /// + /// 当前页码 + /// + [JsonIgnore] + public int PageIndex + { + get => __pageIndex.ToInt(); + set => __pageIndex = value; + } + + [JsonProperty("PageSize")] + [FromQuery(Name = "PageSize")] + public int? __pageSize { get; set; } = 50; + + /// + /// 每页条目数 + /// + [JsonIgnore] + public int PageSize + { + get => __pageSize.ToInt(); + set => __pageSize = value; + } + + public string KeyWord { get; set; } + } + + /// + /// 泛型分页请求父类(在分页请求的基础之上携带数据) + /// + /// 携带的数据类型 + public class PageRequestBase : PageRequestBase + { + /// + /// 请求携带的数据对象 + /// + public T Data { get; set; } + } + + /// + /// 主键ID查询请求类(主要用于根据一个主键ID查询单条数据的情况) + /// + public class QueryByIdRequest : RequestBase + { + /// + /// 记录的数据库主键ID + /// + public int Id { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/EtorJwtValidator.cs b/Infrastructure/Hncore.Infrastructure/WebApi/EtorJwtValidator.cs index 5365339..79ccc51 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/EtorJwtValidator.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/EtorJwtValidator.cs @@ -1,219 +1,219 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using JWT; - -namespace Hncore.Infrastructure.WebApi -{ - public class ValidatorOption - { - public bool ValidateLifetime = true; - } - - public sealed class EtorJwtValidator : IJwtValidator - { - private readonly IJsonSerializer _jsonSerializer; - private readonly IDateTimeProvider _dateTimeProvider; - - private readonly ValidatorOption _option; - - /// - /// Creates an instance of - /// - /// The Json Serializer - /// The DateTime Provider - public EtorJwtValidator(IJsonSerializer jsonSerializer, IDateTimeProvider dateTimeProvider,ValidatorOption option) - { - _jsonSerializer = jsonSerializer; - _dateTimeProvider = dateTimeProvider; - _option = option; - } - - /// - /// - /// - public void Validate(string payloadJson, string decodedCrypto, string decodedSignature) - { - var ex = GetValidationException(payloadJson, decodedCrypto, decodedSignature); - if (ex != null) - throw ex; - } - - /// - /// - /// - public void Validate(string payloadJson, string decodedCrypto, string[] decodedSignatures) - { - var ex = GetValidationException(payloadJson, decodedCrypto, decodedSignatures); - if (ex != null) - throw ex; - } - - /// - /// Given the JWT, verifies its signature correctness without throwing an exception but returning it instead - /// - /// >An arbitrary payload (already serialized to JSON) - /// Decoded body - /// Decoded signature - /// Validation exception, if any - /// True if exception is JWT is valid and exception is null, otherwise false - public bool TryValidate(string payloadJson, string decodedCrypto, string decodedSignature, out Exception ex) - { - ex = GetValidationException(payloadJson, decodedCrypto, decodedSignature); - return ex is null; - } - - /// - /// Given the JWT, verifies its signatures correctness without throwing an exception but returning it instead - /// - /// >An arbitrary payload (already serialized to JSON) - /// Decoded body - /// Decoded signatures - /// Validation exception, if any - /// True if exception is JWT is valid and exception is null, otherwise false - public bool TryValidate(string payloadJson, string decodedCrypto, string[] decodedSignature, out Exception ex) - { - ex = GetValidationException(payloadJson, decodedCrypto, decodedSignature); - return ex is null; - } - - private Exception GetValidationException(string payloadJson, string decodedCrypto, string decodedSignature) - { - if (String.IsNullOrWhiteSpace(payloadJson)) - return new ArgumentException(nameof(payloadJson)); - - if (String.IsNullOrWhiteSpace(decodedCrypto)) - return new ArgumentException(nameof(decodedCrypto)); - - if (String.IsNullOrWhiteSpace(decodedSignature)) - return new ArgumentException(nameof(decodedSignature)); - - if (!CompareCryptoWithSignature(decodedCrypto, decodedSignature)) - return new SignatureVerificationException(decodedCrypto, decodedSignature); - - return GetValidationException(payloadJson); - } - - private Exception GetValidationException(string payloadJson, string decodedCrypto, string[] decodedSignatures) - { - if (String.IsNullOrWhiteSpace(payloadJson)) - return new ArgumentException(nameof(payloadJson)); - - if (String.IsNullOrWhiteSpace(decodedCrypto)) - return new ArgumentException(nameof(decodedCrypto)); - - if (AreAllDecodedSignaturesNullOrWhiteSpace(decodedSignatures)) - return new ArgumentException(nameof(decodedSignatures)); - - if (!IsAnySignatureValid(decodedCrypto, decodedSignatures)) - return new SignatureVerificationException(decodedCrypto, decodedSignatures); - - return GetValidationException(payloadJson); - } - - private Exception GetValidationException(string payloadJson) - { - if (!_option.ValidateLifetime) - { - return null; - } - - var payloadData = _jsonSerializer.Deserialize>(payloadJson); - - var now = _dateTimeProvider.GetNow(); - var secondsSinceEpoch = UnixEpoch.GetSecondsSince(now); - - return ValidateExpClaim(payloadData, secondsSinceEpoch) ?? ValidateNbfClaim(payloadData, secondsSinceEpoch); - } - - private static bool AreAllDecodedSignaturesNullOrWhiteSpace(string[] decodedSignatures) => - decodedSignatures.All(sgn => String.IsNullOrWhiteSpace(sgn)); - - private static bool IsAnySignatureValid(string decodedCrypto, string[] decodedSignatures) => - decodedSignatures.Any(decodedSignature => CompareCryptoWithSignature(decodedCrypto, decodedSignature)); - - /// In the future this method can be opened for extension so made protected virtual - private static bool CompareCryptoWithSignature(string decodedCrypto, string decodedSignature) - { - if (decodedCrypto.Length != decodedSignature.Length) - return false; - - var decodedCryptoBytes = Encoding.UTF8.GetBytes(decodedCrypto); - var decodedSignatureBytes = Encoding.UTF8.GetBytes(decodedSignature); - - byte result = 0; - for (var i = 0; i < decodedCrypto.Length; i++) - { - result |= (byte) (decodedCryptoBytes[i] ^ decodedSignatureBytes[i]); - } - - return result == 0; - } - - /// - /// Verifies the 'exp' claim. - /// - /// See https://tools.ietf.org/html/rfc7515#section-4.1.4 - /// - /// - private static Exception ValidateExpClaim(IDictionary payloadData, double secondsSinceEpoch) - { - - if (!payloadData.TryGetValue("exp", out var expObj)) - return null; - - if (expObj is null) - return new SignatureVerificationException("Claim 'exp' must be a number."); - - double expValue; - try - { - expValue = Convert.ToDouble(expObj); - } - catch - { - return new SignatureVerificationException("Claim 'exp' must be a number."); - } - - if (secondsSinceEpoch >= expValue) - { - return new TokenExpiredException("Token has expired."); - } - - return null; - } - - /// - /// Verifies the 'nbf' claim. - /// - /// See https://tools.ietf.org/html/rfc7515#section-4.1.5 - /// - private static Exception ValidateNbfClaim(IReadOnlyDictionary payloadData, - double secondsSinceEpoch) - { - if (!payloadData.TryGetValue("nbf", out var nbfObj)) - return null; - - if (nbfObj is null) - return new SignatureVerificationException("Claim 'nbf' must be a number."); - - double nbfValue; - try - { - nbfValue = Convert.ToDouble(nbfObj); - } - catch - { - return new SignatureVerificationException("Claim 'nbf' must be a number."); - } - - if (secondsSinceEpoch < nbfValue) - { - return new SignatureVerificationException("Token is not yet valid."); - } - - return null; - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using JWT; + +namespace Hncore.Infrastructure.WebApi +{ + public class ValidatorOption + { + public bool ValidateLifetime = true; + } + + public sealed class EtorJwtValidator : IJwtValidator + { + private readonly IJsonSerializer _jsonSerializer; + private readonly IDateTimeProvider _dateTimeProvider; + + private readonly ValidatorOption _option; + + /// + /// Creates an instance of + /// + /// The Json Serializer + /// The DateTime Provider + public EtorJwtValidator(IJsonSerializer jsonSerializer, IDateTimeProvider dateTimeProvider,ValidatorOption option) + { + _jsonSerializer = jsonSerializer; + _dateTimeProvider = dateTimeProvider; + _option = option; + } + + /// + /// + /// + public void Validate(string payloadJson, string decodedCrypto, string decodedSignature) + { + var ex = GetValidationException(payloadJson, decodedCrypto, decodedSignature); + if (ex != null) + throw ex; + } + + /// + /// + /// + public void Validate(string payloadJson, string decodedCrypto, string[] decodedSignatures) + { + var ex = GetValidationException(payloadJson, decodedCrypto, decodedSignatures); + if (ex != null) + throw ex; + } + + /// + /// Given the JWT, verifies its signature correctness without throwing an exception but returning it instead + /// + /// >An arbitrary payload (already serialized to JSON) + /// Decoded body + /// Decoded signature + /// Validation exception, if any + /// True if exception is JWT is valid and exception is null, otherwise false + public bool TryValidate(string payloadJson, string decodedCrypto, string decodedSignature, out Exception ex) + { + ex = GetValidationException(payloadJson, decodedCrypto, decodedSignature); + return ex is null; + } + + /// + /// Given the JWT, verifies its signatures correctness without throwing an exception but returning it instead + /// + /// >An arbitrary payload (already serialized to JSON) + /// Decoded body + /// Decoded signatures + /// Validation exception, if any + /// True if exception is JWT is valid and exception is null, otherwise false + public bool TryValidate(string payloadJson, string decodedCrypto, string[] decodedSignature, out Exception ex) + { + ex = GetValidationException(payloadJson, decodedCrypto, decodedSignature); + return ex is null; + } + + private Exception GetValidationException(string payloadJson, string decodedCrypto, string decodedSignature) + { + if (String.IsNullOrWhiteSpace(payloadJson)) + return new ArgumentException(nameof(payloadJson)); + + if (String.IsNullOrWhiteSpace(decodedCrypto)) + return new ArgumentException(nameof(decodedCrypto)); + + if (String.IsNullOrWhiteSpace(decodedSignature)) + return new ArgumentException(nameof(decodedSignature)); + + if (!CompareCryptoWithSignature(decodedCrypto, decodedSignature)) + return new SignatureVerificationException(decodedCrypto, decodedSignature); + + return GetValidationException(payloadJson); + } + + private Exception GetValidationException(string payloadJson, string decodedCrypto, string[] decodedSignatures) + { + if (String.IsNullOrWhiteSpace(payloadJson)) + return new ArgumentException(nameof(payloadJson)); + + if (String.IsNullOrWhiteSpace(decodedCrypto)) + return new ArgumentException(nameof(decodedCrypto)); + + if (AreAllDecodedSignaturesNullOrWhiteSpace(decodedSignatures)) + return new ArgumentException(nameof(decodedSignatures)); + + if (!IsAnySignatureValid(decodedCrypto, decodedSignatures)) + return new SignatureVerificationException(decodedCrypto, decodedSignatures); + + return GetValidationException(payloadJson); + } + + private Exception GetValidationException(string payloadJson) + { + if (!_option.ValidateLifetime) + { + return null; + } + + var payloadData = _jsonSerializer.Deserialize>(payloadJson); + + var now = _dateTimeProvider.GetNow(); + var secondsSinceEpoch = UnixEpoch.GetSecondsSince(now); + + return ValidateExpClaim(payloadData, secondsSinceEpoch) ?? ValidateNbfClaim(payloadData, secondsSinceEpoch); + } + + private static bool AreAllDecodedSignaturesNullOrWhiteSpace(string[] decodedSignatures) => + decodedSignatures.All(sgn => String.IsNullOrWhiteSpace(sgn)); + + private static bool IsAnySignatureValid(string decodedCrypto, string[] decodedSignatures) => + decodedSignatures.Any(decodedSignature => CompareCryptoWithSignature(decodedCrypto, decodedSignature)); + + /// In the future this method can be opened for extension so made protected virtual + private static bool CompareCryptoWithSignature(string decodedCrypto, string decodedSignature) + { + if (decodedCrypto.Length != decodedSignature.Length) + return false; + + var decodedCryptoBytes = Encoding.UTF8.GetBytes(decodedCrypto); + var decodedSignatureBytes = Encoding.UTF8.GetBytes(decodedSignature); + + byte result = 0; + for (var i = 0; i < decodedCrypto.Length; i++) + { + result |= (byte) (decodedCryptoBytes[i] ^ decodedSignatureBytes[i]); + } + + return result == 0; + } + + /// + /// Verifies the 'exp' claim. + /// + /// See https://tools.ietf.org/html/rfc7515#section-4.1.4 + /// + /// + private static Exception ValidateExpClaim(IDictionary payloadData, double secondsSinceEpoch) + { + + if (!payloadData.TryGetValue("exp", out var expObj)) + return null; + + if (expObj is null) + return new SignatureVerificationException("Claim 'exp' must be a number."); + + double expValue; + try + { + expValue = Convert.ToDouble(expObj); + } + catch + { + return new SignatureVerificationException("Claim 'exp' must be a number."); + } + + if (secondsSinceEpoch >= expValue) + { + return new TokenExpiredException("Token has expired."); + } + + return null; + } + + /// + /// Verifies the 'nbf' claim. + /// + /// See https://tools.ietf.org/html/rfc7515#section-4.1.5 + /// + private static Exception ValidateNbfClaim(IReadOnlyDictionary payloadData, + double secondsSinceEpoch) + { + if (!payloadData.TryGetValue("nbf", out var nbfObj)) + return null; + + if (nbfObj is null) + return new SignatureVerificationException("Claim 'nbf' must be a number."); + + double nbfValue; + try + { + nbfValue = Convert.ToDouble(nbfObj); + } + catch + { + return new SignatureVerificationException("Claim 'nbf' must be a number."); + } + + if (secondsSinceEpoch < nbfValue) + { + return new SignatureVerificationException("Token is not yet valid."); + } + + return null; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/AuthBase.cs b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/AuthBase.cs index 04a5b44..b42028c 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/AuthBase.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/AuthBase.cs @@ -1,50 +1,50 @@ -using System; -using Hncore.Infrastructure.Common; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc.Filters; - -namespace Hncore.Infrastructure.WebApi -{ - public abstract class AuthBase : Attribute, IAuthorizationFilter, IResourceFilter - { - public abstract void OnAuthorization(AuthorizationFilterContext context); - - public void OnResourceExecuting(ResourceExecutingContext context) - { - if (!context.HasPassed() && !context.AllowAnonymous()) - { - context.Reject(); - } - } - - public void OnResourceExecuted(ResourceExecutedContext context) - { - } - - /// - /// 内部接口签名 - /// - /// - /// - /// - public static string CreateInternalApiSign(long timestamp, string randomstr) - { - string secret = - "1CD985F202645678FF1CE16BC14BCB9E.74562B91A1E851E9CEC9DA8BCE313DFE.EA6B2EFBDD4255A9F1B3BBC6399B58F4"; - - return SecurityHelper.GetMd5Hash($"{timestamp}{randomstr}{secret}"); - } - - /// - /// 创建第三方开放接口签名 - /// - /// - /// - /// - /// - public static string CreateOpenApiSign(long timestamp, string randomstr, string appKey) - { - return SecurityHelper.GetMd5Hash($"{timestamp}{randomstr}{appKey}"); - } - } +using System; +using Hncore.Infrastructure.Common; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace Hncore.Infrastructure.WebApi +{ + public abstract class AuthBase : Attribute, IAuthorizationFilter, IResourceFilter + { + public abstract void OnAuthorization(AuthorizationFilterContext context); + + public void OnResourceExecuting(ResourceExecutingContext context) + { + if (!context.HasPassed() && !context.AllowAnonymous()) + { + context.Reject(); + } + } + + public void OnResourceExecuted(ResourceExecutedContext context) + { + } + + /// + /// 内部接口签名 + /// + /// + /// + /// + public static string CreateInternalApiSign(long timestamp, string randomstr) + { + string secret = + "1CD985F202645678FF1CE16BC14BCB9E.74562B91A1E851E9CEC9DA8BCE313DFE.EA6B2EFBDD4255A9F1B3BBC6399B58F4"; + + return SecurityHelper.GetMd5Hash($"{timestamp}{randomstr}{secret}"); + } + + /// + /// 创建第三方开放接口签名 + /// + /// + /// + /// + /// + public static string CreateOpenApiSign(long timestamp, string randomstr, string appKey) + { + return SecurityHelper.GetMd5Hash($"{timestamp}{randomstr}{appKey}"); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/HttpContextExt.cs b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/HttpContextExt.cs index 31f4300..daf9e15 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/HttpContextExt.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/HttpContextExt.cs @@ -1,180 +1,180 @@ -using System.Linq; -using Hncore.Infrastructure.Extension; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Authorization; -using Microsoft.AspNetCore.Mvc.Filters; - -namespace Hncore.Infrastructure.WebApi -{ - public static class HttpContextExt - { - /// - /// 是否允许匿名访问 - /// - /// - /// - public static bool AllowAnonymous(this AuthorizationFilterContext context) - { - if (context.HttpContext.Items.ContainsKey("AllowAnonymous") - && context.HttpContext.Items["AllowAnonymous"].ToBool()) - { - return true; - } - - if (context.Filters.Any(item => item is IAllowAnonymousFilter)) - { - context.HttpContext.Items["AllowAnonymous"] = true; - return true; - } - - return false; - } - - /// - /// 是否允许匿名访问 - /// - /// - /// - public static bool AllowAnonymous(this ResourceExecutingContext context) - { - if (context.HttpContext.Items.ContainsKey("AllowAnonymous") - && context.HttpContext.Items["AllowAnonymous"].ToBool()) - { - return true; - } - - if (context.Filters.Any(item => item is IAllowAnonymousFilter)) - { - context.HttpContext.Items["AllowAnonymous"] = true; - return true; - } - - return false; - } - - /// - /// 是否已通过验证 - /// - /// - public static bool HasPassed(this AuthorizationFilterContext context) - { - if (context.HttpContext.Items.ContainsKey("AuthPassed") && context.HttpContext.Items["AuthPassed"].ToBool()) - { - return true; - } - - return false; - } - - /// - /// 是否已通过验证 - /// - /// - public static bool HasPassed(this ResourceExecutingContext context) - { - if (context.HttpContext.Items.ContainsKey("AuthPassed") && context.HttpContext.Items["AuthPassed"].ToBool()) - { - return true; - } - - return false; - } - - /// - /// 通过验证 - /// - /// - /// 过滤器名称 - /// - public static void SetPassed(this AuthorizationFilterContext context, string filterName) - { - context.HttpContext.Items["AuthPassed"] = true; - context.HttpContext.Items["AuthPassedFilterName"] = filterName; - } - - /// - /// 拒绝通过 - /// - /// - /// 拒绝原因 - public static void Reject(this AuthorizationFilterContext context, string reason = "") - { - context.HttpContext.Response.StatusCode = 401; - context.Result = new JsonResult(new ApiResult(ResultCode.C_Access_Forbidden, reason)); - } - - /// - /// 拒绝通过并跳转 - /// - /// - /// - public static void RejectToRedirect(this AuthorizationFilterContext context, string url = "") - { - //context.HttpContext.Response.StatusCode = 401; - context.Result = new RedirectResult(url); - } - - /// - /// 拒绝通过 - /// - /// - /// 拒绝原因 - public static void Reject(this ResourceExecutingContext context, string reason = "") - { - context.HttpContext.Response.StatusCode = 401; - context.Result = new JsonResult(new ApiResult(ResultCode.C_Access_Forbidden, reason)); - } - - - /// - /// 是否包含内部调用验证信息 - /// - /// - /// - public static bool HasInternalApiAuthInfo(this AuthorizationFilterContext context) - { - if (!context.HttpContext.Request.Headers.ContainsKey("timestamp") - || !context.HttpContext.Request.Headers.ContainsKey("randomstr") - || !context.HttpContext.Request.Headers.ContainsKey("internalsign")) - { - return false; - } - - return true; - } - - /// - /// 是否包含第三方开放验证信息 - /// - /// - /// - public static bool HasOpenApiAuthInfo(this AuthorizationFilterContext context) - { - if (!context.HttpContext.Request.Headers.ContainsKey("timestamp") - || !context.HttpContext.Request.Headers.ContainsKey("randomstr") - || !context.HttpContext.Request.Headers.ContainsKey("appid") - || !context.HttpContext.Request.Headers.ContainsKey("sign")) - { - return false; - } - - return true; - } - - /// - /// 是否包含token验证信息 - /// - /// - /// - public static bool HasTokenAuthInfo(this AuthorizationFilterContext context) - { - if (!context.HttpContext.Request.Headers.ContainsKey("token")&&!context.HttpContext.Request.Cookies.ContainsKey("token")) - { - return false; - } - - return true; - } - } +using System.Linq; +using Hncore.Infrastructure.Extension; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Authorization; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace Hncore.Infrastructure.WebApi +{ + public static class HttpContextExt + { + /// + /// 是否允许匿名访问 + /// + /// + /// + public static bool AllowAnonymous(this AuthorizationFilterContext context) + { + if (context.HttpContext.Items.ContainsKey("AllowAnonymous") + && context.HttpContext.Items["AllowAnonymous"].ToBool()) + { + return true; + } + + if (context.Filters.Any(item => item is IAllowAnonymousFilter)) + { + context.HttpContext.Items["AllowAnonymous"] = true; + return true; + } + + return false; + } + + /// + /// 是否允许匿名访问 + /// + /// + /// + public static bool AllowAnonymous(this ResourceExecutingContext context) + { + if (context.HttpContext.Items.ContainsKey("AllowAnonymous") + && context.HttpContext.Items["AllowAnonymous"].ToBool()) + { + return true; + } + + if (context.Filters.Any(item => item is IAllowAnonymousFilter)) + { + context.HttpContext.Items["AllowAnonymous"] = true; + return true; + } + + return false; + } + + /// + /// 是否已通过验证 + /// + /// + public static bool HasPassed(this AuthorizationFilterContext context) + { + if (context.HttpContext.Items.ContainsKey("AuthPassed") && context.HttpContext.Items["AuthPassed"].ToBool()) + { + return true; + } + + return false; + } + + /// + /// 是否已通过验证 + /// + /// + public static bool HasPassed(this ResourceExecutingContext context) + { + if (context.HttpContext.Items.ContainsKey("AuthPassed") && context.HttpContext.Items["AuthPassed"].ToBool()) + { + return true; + } + + return false; + } + + /// + /// 通过验证 + /// + /// + /// 过滤器名称 + /// + public static void SetPassed(this AuthorizationFilterContext context, string filterName) + { + context.HttpContext.Items["AuthPassed"] = true; + context.HttpContext.Items["AuthPassedFilterName"] = filterName; + } + + /// + /// 拒绝通过 + /// + /// + /// 拒绝原因 + public static void Reject(this AuthorizationFilterContext context, string reason = "") + { + context.HttpContext.Response.StatusCode = 401; + context.Result = new JsonResult(new ApiResult(ResultCode.C_Access_Forbidden, reason)); + } + + /// + /// 拒绝通过并跳转 + /// + /// + /// + public static void RejectToRedirect(this AuthorizationFilterContext context, string url = "") + { + //context.HttpContext.Response.StatusCode = 401; + context.Result = new RedirectResult(url); + } + + /// + /// 拒绝通过 + /// + /// + /// 拒绝原因 + public static void Reject(this ResourceExecutingContext context, string reason = "") + { + context.HttpContext.Response.StatusCode = 401; + context.Result = new JsonResult(new ApiResult(ResultCode.C_Access_Forbidden, reason)); + } + + + /// + /// 是否包含内部调用验证信息 + /// + /// + /// + public static bool HasInternalApiAuthInfo(this AuthorizationFilterContext context) + { + if (!context.HttpContext.Request.Headers.ContainsKey("timestamp") + || !context.HttpContext.Request.Headers.ContainsKey("randomstr") + || !context.HttpContext.Request.Headers.ContainsKey("internalsign")) + { + return false; + } + + return true; + } + + /// + /// 是否包含第三方开放验证信息 + /// + /// + /// + public static bool HasOpenApiAuthInfo(this AuthorizationFilterContext context) + { + if (!context.HttpContext.Request.Headers.ContainsKey("timestamp") + || !context.HttpContext.Request.Headers.ContainsKey("randomstr") + || !context.HttpContext.Request.Headers.ContainsKey("appid") + || !context.HttpContext.Request.Headers.ContainsKey("sign")) + { + return false; + } + + return true; + } + + /// + /// 是否包含token验证信息 + /// + /// + /// + public static bool HasTokenAuthInfo(this AuthorizationFilterContext context) + { + if (!context.HttpContext.Request.Headers.ContainsKey("token")&&!context.HttpContext.Request.Cookies.ContainsKey("token")) + { + return false; + } + + return true; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/InternalApiAuthAttribute.cs b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/InternalApiAuthAttribute.cs index 3cabb43..85ffe68 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/InternalApiAuthAttribute.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/InternalApiAuthAttribute.cs @@ -1,70 +1,70 @@ -using System; -using System.Linq; -using System.Net.Http; -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Data; -using Hncore.Infrastructure.Extension; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Authorization; -using Microsoft.AspNetCore.Mvc.Filters; - -namespace Hncore.Infrastructure.WebApi -{ - public class InternalApiAuthAttribute : AuthBase,IOrderedFilter - { - public int Order =>0; - - public override void OnAuthorization(AuthorizationFilterContext context) - { - - if (context.AllowAnonymous() - || context.HasPassed() - || !context.HasInternalApiAuthInfo()) - { - return; - } - - long.TryParse(context.HttpContext.Request.Headers["timestamp"], out long timestamp); - string randomstr = context.HttpContext.Request.Headers["randomstr"]; - string sign = context.HttpContext.Request.Headers["internalsign"]; - - if (EnvironmentVariableHelper.IsAspNetCoreProduction) - { - long secondDiff = DateTimeHelper.ToUnixTimestamp(DateTime.Now) - timestamp; - - if (secondDiff > 600 || secondDiff < -600) - { - context.Reject("时间戳已过期"); - } - } - - - if (!String.Equals(sign, AuthBase.CreateInternalApiSign(timestamp, randomstr) - , StringComparison.CurrentCultureIgnoreCase)) - { - context.Reject("签名错误"); - } - - context.SetPassed("InternalApiAuth"); - } - } - - public static class InternalApiAuthExt - { - public static HttpClient CreateInternalAuthClient(this IHttpClientFactory httpClientFactory) - { - var httpclient = httpClientFactory.CreateClient(TimeSpan.FromSeconds(10)); - - long timestamp = DateTimeHelper.ToUnixTimestamp(DateTime.Now); - string randomstr = Guid.NewGuid().ToString(); - - var sign = AuthBase.CreateInternalApiSign(timestamp, randomstr); - - httpclient.DefaultRequestHeaders.Add("timestamp", timestamp.ToString()); - httpclient.DefaultRequestHeaders.Add("randomstr", randomstr); - httpclient.DefaultRequestHeaders.Add("internalsign", sign); - - return httpclient; - } - } +using System; +using System.Linq; +using System.Net.Http; +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Data; +using Hncore.Infrastructure.Extension; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Authorization; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace Hncore.Infrastructure.WebApi +{ + public class InternalApiAuthAttribute : AuthBase,IOrderedFilter + { + public int Order =>0; + + public override void OnAuthorization(AuthorizationFilterContext context) + { + + if (context.AllowAnonymous() + || context.HasPassed() + || !context.HasInternalApiAuthInfo()) + { + return; + } + + long.TryParse(context.HttpContext.Request.Headers["timestamp"], out long timestamp); + string randomstr = context.HttpContext.Request.Headers["randomstr"]; + string sign = context.HttpContext.Request.Headers["internalsign"]; + + if (EnvironmentVariableHelper.IsAspNetCoreProduction) + { + long secondDiff = DateTimeHelper.ToUnixTimestamp(DateTime.Now) - timestamp; + + if (secondDiff > 600 || secondDiff < -600) + { + context.Reject("时间戳已过期"); + } + } + + + if (!String.Equals(sign, AuthBase.CreateInternalApiSign(timestamp, randomstr) + , StringComparison.CurrentCultureIgnoreCase)) + { + context.Reject("签名错误"); + } + + context.SetPassed("InternalApiAuth"); + } + } + + public static class InternalApiAuthExt + { + public static HttpClient CreateInternalAuthClient(this IHttpClientFactory httpClientFactory) + { + var httpclient = httpClientFactory.CreateClient(TimeSpan.FromSeconds(10)); + + long timestamp = DateTimeHelper.ToUnixTimestamp(DateTime.Now); + string randomstr = Guid.NewGuid().ToString(); + + var sign = AuthBase.CreateInternalApiSign(timestamp, randomstr); + + httpclient.DefaultRequestHeaders.Add("timestamp", timestamp.ToString()); + httpclient.DefaultRequestHeaders.Add("randomstr", randomstr); + httpclient.DefaultRequestHeaders.Add("internalsign", sign); + + return httpclient; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/LimitQosAttribute.cs b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/LimitQosAttribute.cs index da0a5a3..ef07bb3 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/LimitQosAttribute.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/LimitQosAttribute.cs @@ -1,88 +1,88 @@ -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Core.Web; -using Microsoft.AspNetCore.Mvc.Filters; -using System; -using System.Linq; - -namespace Hncore.Infrastructure.WebApi.Filter -{ - public enum LimitDimension - { - Ip, - TenantId, - AppId - } - public class LimitQosAttribute : AuthBase - { - private int _timeWindow; - private int _count; - private LimitDimension[] _dimensions; - - public LimitQosAttribute(int timeWindow, int count, params LimitDimension[] dimensions) - { - _timeWindow = timeWindow; - _count = count; - _dimensions = dimensions; - } - - public override void OnAuthorization(AuthorizationFilterContext context) - { - string url = context.HttpContext.Request.Path.ToString().ToLower(); - - string cacheKey = $"limitqos:{url}"; - - if (_dimensions.Contains(LimitDimension.Ip)) - { - string ip = context.HttpContext.GetUserIp(); - cacheKey += $":{ip}"; - } - - if (_dimensions.Contains(LimitDimension.TenantId)) - { - var mangeInfo = context.HttpContext.Request.GetManageUserInfo(); - - if (mangeInfo == null) - { - return; - } - - cacheKey += $":{mangeInfo.TenantId}"; - } - - if (_dimensions.Contains(LimitDimension.AppId)) - { - if (!context.HttpContext.Items.ContainsKey("OpenAppId")) - { - return; - } - - cacheKey += $":{context.HttpContext.Items["OpenAppId"]}"; - } - - var luaScript = $"return redis.call('CL.THROTTLE','{cacheKey}','{_count}','{_count}','{_timeWindow}','1')"; - - try - { - var res = RedisHelper.Eval(luaScript, cacheKey); - - if (res is Array) - { - var arr = res as Array; - - if (arr.Length == 5) - { - if (Convert.ToInt32(arr.GetValue(0)) != 0) - { - context.Reject($"超出{_timeWindow}秒{_count}次的请求限制"); - } - } - } - } - catch (Exception e) - { - LogHelper.Error("reids异常", e); - } - } - } - +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Core.Web; +using Microsoft.AspNetCore.Mvc.Filters; +using System; +using System.Linq; + +namespace Hncore.Infrastructure.WebApi.Filter +{ + public enum LimitDimension + { + Ip, + TenantId, + AppId + } + public class LimitQosAttribute : AuthBase + { + private int _timeWindow; + private int _count; + private LimitDimension[] _dimensions; + + public LimitQosAttribute(int timeWindow, int count, params LimitDimension[] dimensions) + { + _timeWindow = timeWindow; + _count = count; + _dimensions = dimensions; + } + + public override void OnAuthorization(AuthorizationFilterContext context) + { + string url = context.HttpContext.Request.Path.ToString().ToLower(); + + string cacheKey = $"limitqos:{url}"; + + if (_dimensions.Contains(LimitDimension.Ip)) + { + string ip = context.HttpContext.GetUserIp(); + cacheKey += $":{ip}"; + } + + if (_dimensions.Contains(LimitDimension.TenantId)) + { + var mangeInfo = context.HttpContext.Request.GetManageUserInfo(); + + if (mangeInfo == null) + { + return; + } + + cacheKey += $":{mangeInfo.TenantId}"; + } + + if (_dimensions.Contains(LimitDimension.AppId)) + { + if (!context.HttpContext.Items.ContainsKey("OpenAppId")) + { + return; + } + + cacheKey += $":{context.HttpContext.Items["OpenAppId"]}"; + } + + var luaScript = $"return redis.call('CL.THROTTLE','{cacheKey}','{_count}','{_count}','{_timeWindow}','1')"; + + try + { + var res = RedisHelper.Eval(luaScript, cacheKey); + + if (res is Array) + { + var arr = res as Array; + + if (arr.Length == 5) + { + if (Convert.ToInt32(arr.GetValue(0)) != 0) + { + context.Reject($"超出{_timeWindow}秒{_count}次的请求限制"); + } + } + } + } + catch (Exception e) + { + LogHelper.Error("reids异常", e); + } + } + } + } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/ManageAuthAttribute.cs b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/ManageAuthAttribute.cs index ecb883f..225fded 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/ManageAuthAttribute.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/ManageAuthAttribute.cs @@ -1,148 +1,148 @@ -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Extension; -using Hncore.Infrastructure.Serializer; -using JWT; -using JWT.Serializers; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.Extensions.DependencyInjection; -using Newtonsoft.Json; -using System; -using System.Net.Http; - - -namespace Hncore.Infrastructure.WebApi -{ - public class ManageAuthAttribute : AuthBase, IOrderedFilter - { - public int Order =>1; - - public override void OnAuthorization(AuthorizationFilterContext context) - { - - if (context.AllowAnonymous() - || context.HasPassed() - || !context.HasTokenAuthInfo()) - { - return; - } - - if (context.HttpContext.Request.GetManageUserInfo() == null) - { - context.Reject(); - } - - context.SetPassed("ManageAuth"); - } - } - - public class ManageUserInfo - { - [JsonProperty("LoginName")] public string LoginName { get; set; } - - [JsonProperty("RoleName")] public string RoleName { get; set; } - - [JsonProperty("OperaterID")] public int OperaterId { get; set; } - - [JsonProperty("TenantId")] public int TenantId { get; set; } - - [JsonProperty("DataDomain")] public int StoreId { get; set; } - - [JsonProperty("exp")] public long ExpiredTimestamp { get; set; } - - [JsonProperty("iat")] public long IssueTimestamp { get; set; } - [JsonProperty("OpenId")] public string OpenId { get; set; } - } - - public static class HttpRequestExt - { - private static string _secret = "etor_yh_lzh_20f_2020_YES"; - - public static void SetManageUserInfo(this HttpRequest request, ManageUserInfo manageUserInfo) - { - request.HttpContext.Items["ManageUserInfo"] = manageUserInfo; - } - - public static ManageUserInfo GetManageUserInfo(this HttpRequest request) - { - if (!request.Headers.ContainsKey("token")) - { - return null; - } - - if (request.HttpContext.Items.ContainsKey("ManageUserInfo")) - { - return request.HttpContext.Items["ManageUserInfo"] as ManageUserInfo; - } - - string token = request.Headers["token"]; - - string storeId = request.Headers["sid"]; - - string payload = string.Empty; - - try - { - IJsonSerializer serializer = new JsonNetSerializer(); - IDateTimeProvider provider = new UtcDateTimeProvider(); - IJwtValidator validator = new JwtValidator(serializer, provider); - IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); - IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); - payload = decoder.Decode(token, _secret, verify: true); - - if (string.IsNullOrEmpty(payload)) - { - return null; - } - - try - { - ManageUserInfo manageUserInfo = payload.FromJsonTo(); - - if (manageUserInfo == null || manageUserInfo.TenantId == 0) - { - return null; - } - - if (manageUserInfo.IssueTimestamp == 0 - || DateTimeHelper.UnixTimeStampToDateTime(manageUserInfo.IssueTimestamp) < - DateTime.Now.AddHours(-4)) - { - return null; - } - - if(storeId.Has()) - { - manageUserInfo.StoreId = Convert.ToInt32(storeId); - } - - request.SetManageUserInfo(manageUserInfo); - - return manageUserInfo; - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - return null; - } - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - return null; - } - } - - public static HttpClient CreateManageAuthHttpClient(this HttpRequest request) - { - var httpclient = request.HttpContext.RequestServices - .GetService() - .CreateClient(TimeSpan.FromMinutes(1)); - - httpclient.DefaultRequestHeaders.Add("token", request.Headers["token"].ToString()); - httpclient.DefaultRequestHeaders.Add("sid", request.Headers["sid"].ToString()); - - return httpclient; - } - } +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Extension; +using Hncore.Infrastructure.Serializer; +using JWT; +using JWT.Serializers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.DependencyInjection; +using Newtonsoft.Json; +using System; +using System.Net.Http; + + +namespace Hncore.Infrastructure.WebApi +{ + public class ManageAuthAttribute : AuthBase, IOrderedFilter + { + public int Order =>1; + + public override void OnAuthorization(AuthorizationFilterContext context) + { + + if (context.AllowAnonymous() + || context.HasPassed() + || !context.HasTokenAuthInfo()) + { + return; + } + + if (context.HttpContext.Request.GetManageUserInfo() == null) + { + context.Reject(); + } + + context.SetPassed("ManageAuth"); + } + } + + public class ManageUserInfo + { + [JsonProperty("LoginName")] public string LoginName { get; set; } + + [JsonProperty("RoleName")] public string RoleName { get; set; } + + [JsonProperty("OperaterID")] public int OperaterId { get; set; } + + [JsonProperty("TenantId")] public int TenantId { get; set; } + + [JsonProperty("DataDomain")] public int StoreId { get; set; } + + [JsonProperty("exp")] public long ExpiredTimestamp { get; set; } + + [JsonProperty("iat")] public long IssueTimestamp { get; set; } + [JsonProperty("OpenId")] public string OpenId { get; set; } + } + + public static class HttpRequestExt + { + private static string _secret = "etor_yh_lzh_20f_2020_YES"; + + public static void SetManageUserInfo(this HttpRequest request, ManageUserInfo manageUserInfo) + { + request.HttpContext.Items["ManageUserInfo"] = manageUserInfo; + } + + public static ManageUserInfo GetManageUserInfo(this HttpRequest request) + { + if (!request.Headers.ContainsKey("token")) + { + return null; + } + + if (request.HttpContext.Items.ContainsKey("ManageUserInfo")) + { + return request.HttpContext.Items["ManageUserInfo"] as ManageUserInfo; + } + + string token = request.Headers["token"]; + + string storeId = request.Headers["sid"]; + + string payload = string.Empty; + + try + { + IJsonSerializer serializer = new JsonNetSerializer(); + IDateTimeProvider provider = new UtcDateTimeProvider(); + IJwtValidator validator = new JwtValidator(serializer, provider); + IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); + IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); + payload = decoder.Decode(token, _secret, verify: true); + + if (string.IsNullOrEmpty(payload)) + { + return null; + } + + try + { + ManageUserInfo manageUserInfo = payload.FromJsonTo(); + + if (manageUserInfo == null || manageUserInfo.TenantId == 0) + { + return null; + } + + if (manageUserInfo.IssueTimestamp == 0 + || DateTimeHelper.UnixTimeStampToDateTime(manageUserInfo.IssueTimestamp) < + DateTime.Now.AddHours(-4)) + { + return null; + } + + if(storeId.Has()) + { + manageUserInfo.StoreId = Convert.ToInt32(storeId); + } + + request.SetManageUserInfo(manageUserInfo); + + return manageUserInfo; + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + return null; + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + return null; + } + } + + public static HttpClient CreateManageAuthHttpClient(this HttpRequest request) + { + var httpclient = request.HttpContext.RequestServices + .GetService() + .CreateClient(TimeSpan.FromMinutes(1)); + + httpclient.DefaultRequestHeaders.Add("token", request.Headers["token"].ToString()); + httpclient.DefaultRequestHeaders.Add("sid", request.Headers["sid"].ToString()); + + return httpclient; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/UserAuthAttribute.cs b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/UserAuthAttribute.cs index 157bfaf..4281e3f 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/UserAuthAttribute.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/Auth/UserAuthAttribute.cs @@ -1,166 +1,166 @@ -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Extension; -using Hncore.Infrastructure.Serializer; -using JWT; -using JWT.Serializers; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Net.Http.Headers; -using Newtonsoft.Json; -using System; -using System.Net.Http; - - -namespace Hncore.Infrastructure.WebApi -{ - public class UserAuthAttribute : AuthBase, IOrderedFilter - { - public int Order => 0; - - public override void OnAuthorization(AuthorizationFilterContext context) - { - - if (context.HasPassed())//context.AllowAnonymous()|| - - { - return; - } - - if (context.HttpContext.Request.GetUserInfo() == null) - { - // context.Reject(); - context.HttpContext.Response.Cookies.Delete("token"); - context.HttpContext.Response.Cookies.Delete("userInfo"); - - var userAgent = context.HttpContext.Request.Headers[HeaderNames.UserAgent].ToString().ToLower(); - if (userAgent.IndexOf("micromessenger") == -1) - { - context.RejectToRedirect("/User/WebLogin"); - } - else - { - var url = context.HttpContext.Request.GetUrl().UrlEncode(); - context.RejectToRedirect($"/User/MP_GetUserInfo?appid=wx18e5b4f42773c3ec&callbakUrl={url}"); - } - } - - context.SetPassed("UserAuth"); - } - } - - public class AppUserInfo - { - [JsonProperty("LoginName")] public string LoginName { get; set; } - - [JsonProperty("Name")] public string Name { get; set; } - - [JsonProperty("RoleName")] public string RoleName { get; set; } - - [JsonProperty("UserId")] public int UserId { get; set; } - - [JsonProperty("TenantId")] public int TenantId { get; set; } - - [JsonProperty("DataDomain")] public int[] DataDomain { get; set; } - - [JsonProperty("exp")] public long ExpiredTimestamp { get; set; } - - [JsonProperty("iat")] public long IssueTimestamp { get; set; } - [JsonProperty("OpenId")] public string OpenId { get; set; } - [JsonProperty("AppType")] public string AppType { get; set; } - [JsonProperty("AppId")] public string AppId { get; set; } - [JsonProperty("StoreId")] public int StoreId { get; set; } - } - - public static class HttpRequestExt1 - { - private static string _secret = "hncore_yh_lzh_20f_2020_READY"; - - public static void SetUserInfo(this HttpRequest request, AppUserInfo manageUserInfo) - { - request.HttpContext.Items["UserInfo"] = manageUserInfo; - } - - public static AppUserInfo GetUserInfo(this HttpRequest request) - { - if (!request.Headers.ContainsKey("token")&& !request.Cookies.ContainsKey("token")) - { - return null; - } - - if (request.HttpContext.Items.ContainsKey("UserInfo")) - { - return request.HttpContext.Items["UserInfo"] as AppUserInfo; - } - - if(!request.Cookies.TryGetValue("token",out string token)) - { - token = request.Headers["token"]; - } - string payload = string.Empty; - - try - { - IJsonSerializer serializer = new JsonNetSerializer(); - IDateTimeProvider provider = new UtcDateTimeProvider(); - IJwtValidator validator = new JwtValidator(serializer, provider); - IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); - IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); - payload = decoder.Decode(token, _secret, verify: true); - - if (string.IsNullOrEmpty(payload)) - { - request.HttpContext.Response.Cookies.Delete("token"); - request.HttpContext.Response.Cookies.Delete("userInfo"); - return null; - } - - try - { - AppUserInfo manageUserInfo = payload.FromJsonTo(); - - if (manageUserInfo == null) - { - return null; - } - - if (manageUserInfo.IssueTimestamp == 0 - || DateTimeHelper.UnixTimeStampToDateTime(manageUserInfo.IssueTimestamp) < - DateTime.Now.AddHours(-4)) - { - return null; - } - - request.SetUserInfo(manageUserInfo); - - return manageUserInfo; - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - request.HttpContext.Response.Cookies.Delete("token"); - request.HttpContext.Response.Cookies.Delete("userInfo"); - return null; - } - } - catch(Exception ex) - { - Console.WriteLine(ex.Message); - request.HttpContext.Response.Cookies.Delete("token"); - request.HttpContext.Response.Cookies.Delete("userInfo"); - return null; - } - } - - public static HttpClient CreateManageAuthHttpClient(this HttpRequest request) - { - var httpclient = request.HttpContext.RequestServices - .GetService() - .CreateClient(TimeSpan.FromMinutes(1)); - - httpclient.DefaultRequestHeaders.Add("token", request.Headers["token"].ToString()); - - return httpclient; - } - } +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Extension; +using Hncore.Infrastructure.Serializer; +using JWT; +using JWT.Serializers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Net.Http.Headers; +using Newtonsoft.Json; +using System; +using System.Net.Http; + + +namespace Hncore.Infrastructure.WebApi +{ + public class UserAuthAttribute : AuthBase, IOrderedFilter + { + public int Order => 0; + + public override void OnAuthorization(AuthorizationFilterContext context) + { + + if (context.HasPassed())//context.AllowAnonymous()|| + + { + return; + } + + if (context.HttpContext.Request.GetUserInfo() == null) + { + // context.Reject(); + context.HttpContext.Response.Cookies.Delete("token"); + context.HttpContext.Response.Cookies.Delete("userInfo"); + + var userAgent = context.HttpContext.Request.Headers[HeaderNames.UserAgent].ToString().ToLower(); + if (userAgent.IndexOf("micromessenger") == -1) + { + context.RejectToRedirect("/User/WebLogin"); + } + else + { + var url = context.HttpContext.Request.GetUrl().UrlEncode(); + context.RejectToRedirect($"/User/MP_GetUserInfo?appid=wx18e5b4f42773c3ec&callbakUrl={url}"); + } + } + + context.SetPassed("UserAuth"); + } + } + + public class AppUserInfo + { + [JsonProperty("LoginName")] public string LoginName { get; set; } + + [JsonProperty("Name")] public string Name { get; set; } + + [JsonProperty("RoleName")] public string RoleName { get; set; } + + [JsonProperty("UserId")] public int UserId { get; set; } + + [JsonProperty("TenantId")] public int TenantId { get; set; } + + [JsonProperty("DataDomain")] public int[] DataDomain { get; set; } + + [JsonProperty("exp")] public long ExpiredTimestamp { get; set; } + + [JsonProperty("iat")] public long IssueTimestamp { get; set; } + [JsonProperty("OpenId")] public string OpenId { get; set; } + [JsonProperty("AppType")] public string AppType { get; set; } + [JsonProperty("AppId")] public string AppId { get; set; } + [JsonProperty("StoreId")] public int StoreId { get; set; } + } + + public static class HttpRequestExt1 + { + private static string _secret = "hncore_yh_lzh_20f_2020_READY"; + + public static void SetUserInfo(this HttpRequest request, AppUserInfo manageUserInfo) + { + request.HttpContext.Items["UserInfo"] = manageUserInfo; + } + + public static AppUserInfo GetUserInfo(this HttpRequest request) + { + if (!request.Headers.ContainsKey("token")&& !request.Cookies.ContainsKey("token")) + { + return null; + } + + if (request.HttpContext.Items.ContainsKey("UserInfo")) + { + return request.HttpContext.Items["UserInfo"] as AppUserInfo; + } + + if(!request.Cookies.TryGetValue("token",out string token)) + { + token = request.Headers["token"]; + } + string payload = string.Empty; + + try + { + IJsonSerializer serializer = new JsonNetSerializer(); + IDateTimeProvider provider = new UtcDateTimeProvider(); + IJwtValidator validator = new JwtValidator(serializer, provider); + IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); + IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); + payload = decoder.Decode(token, _secret, verify: true); + + if (string.IsNullOrEmpty(payload)) + { + request.HttpContext.Response.Cookies.Delete("token"); + request.HttpContext.Response.Cookies.Delete("userInfo"); + return null; + } + + try + { + AppUserInfo manageUserInfo = payload.FromJsonTo(); + + if (manageUserInfo == null) + { + return null; + } + + if (manageUserInfo.IssueTimestamp == 0 + || DateTimeHelper.UnixTimeStampToDateTime(manageUserInfo.IssueTimestamp) < + DateTime.Now.AddHours(-4)) + { + return null; + } + + request.SetUserInfo(manageUserInfo); + + return manageUserInfo; + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + request.HttpContext.Response.Cookies.Delete("token"); + request.HttpContext.Response.Cookies.Delete("userInfo"); + return null; + } + } + catch(Exception ex) + { + Console.WriteLine(ex.Message); + request.HttpContext.Response.Cookies.Delete("token"); + request.HttpContext.Response.Cookies.Delete("userInfo"); + return null; + } + } + + public static HttpClient CreateManageAuthHttpClient(this HttpRequest request) + { + var httpclient = request.HttpContext.RequestServices + .GetService() + .CreateClient(TimeSpan.FromMinutes(1)); + + httpclient.DefaultRequestHeaders.Add("token", request.Headers["token"].ToString()); + + return httpclient; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/SwaggerAddEnumDescriptionsDocumentFilter.cs b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/SwaggerAddEnumDescriptionsDocumentFilter.cs index eee11d8..aaba937 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/SwaggerAddEnumDescriptionsDocumentFilter.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/SwaggerAddEnumDescriptionsDocumentFilter.cs @@ -1,106 +1,106 @@ -using Swashbuckle.AspNetCore.Swagger; -using Swashbuckle.AspNetCore.SwaggerGen; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Text; - -namespace Hncore.Infrastructure.WebApi.Filter -{ - public class SwaggerAddEnumDescriptionsDocumentFilter : IDocumentFilter - { - public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) - { - // add enum descriptions to result models - // 将枚举加到返回对象的描述中,json.definitions对象里的枚举 - foreach (KeyValuePair schemaDictionaryItem in swaggerDoc.Definitions) - { - Schema schema = schemaDictionaryItem.Value; - foreach (KeyValuePair propertyDictionaryItem in schema.Properties) - { - Schema property = propertyDictionaryItem.Value; - IList propertyEnums = property.Enum; - if (propertyEnums != null && propertyEnums.Count > 0) - { - property.Description += DescribeEnum(propertyEnums); - } - } - } - - // add enum descriptions to input parameters - if (swaggerDoc.Paths.Count > 0) - { - foreach (PathItem pathItem in swaggerDoc.Paths.Values) - { - DescribeEnumParameters(pathItem.Parameters); - // head, patch, options, delete left out - List possibleParameterisedOperations = new List { pathItem.Get, pathItem.Post, pathItem.Put }; - possibleParameterisedOperations.FindAll(x => x != null).ForEach(x => DescribeEnumParameters(x.Parameters)); - } - } - } - - private void DescribeEnumParameters(IList parameters) - { - if (parameters != null) - { - foreach (var param in parameters) - { - if (param.In == "path") - { - var nonParam = (NonBodyParameter)param; - IList paramEnums = nonParam.Enum; - if (paramEnums != null && paramEnums.Count > 0) - { - param.Description +=":"+ DescribeEnum(paramEnums); - } - } - if (param.In == "body") - { - var bodyParam = (BodyParameter)param; - Schema property = bodyParam.Schema; - IList propertyEnums = property.Enum; - if (propertyEnums != null && propertyEnums.Count > 0) - { - property.Description += ":" + DescribeEnum(propertyEnums); - } - } - if (param.In == "query") - { - var nonParam = (NonBodyParameter)param; - IList paramEnums = nonParam.Enum; - if (paramEnums != null && paramEnums.Count > 0) - { - param.Description += ":" + DescribeEnum(paramEnums); - } - } - } - } - } - /// - /// 枚举转换成值和描述 - /// - /// - /// - private string DescribeEnum(IList enums) - { - List enumDescriptions = new List(); - foreach (object item in enums) - { - var type = item.GetType(); - var objArr = type.GetField(item.ToString()).GetCustomAttributes(typeof(DisplayAttribute), true); - if (objArr != null && objArr.Length > 0) - { - DisplayAttribute da = objArr[0] as DisplayAttribute; - enumDescriptions.Add($"{(int)item} {da.Name}"); - } - else - { - enumDescriptions.Add(string.Format("{0} = {1}", (int)item, Enum.GetName(item.GetType(), item))); - } - } - return string.Join(", ", enumDescriptions.ToArray()); - } - - } -} +using Swashbuckle.AspNetCore.Swagger; +using Swashbuckle.AspNetCore.SwaggerGen; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Text; + +namespace Hncore.Infrastructure.WebApi.Filter +{ + public class SwaggerAddEnumDescriptionsDocumentFilter : IDocumentFilter + { + public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) + { + // add enum descriptions to result models + // 将枚举加到返回对象的描述中,json.definitions对象里的枚举 + foreach (KeyValuePair schemaDictionaryItem in swaggerDoc.Definitions) + { + Schema schema = schemaDictionaryItem.Value; + foreach (KeyValuePair propertyDictionaryItem in schema.Properties) + { + Schema property = propertyDictionaryItem.Value; + IList propertyEnums = property.Enum; + if (propertyEnums != null && propertyEnums.Count > 0) + { + property.Description += DescribeEnum(propertyEnums); + } + } + } + + // add enum descriptions to input parameters + if (swaggerDoc.Paths.Count > 0) + { + foreach (PathItem pathItem in swaggerDoc.Paths.Values) + { + DescribeEnumParameters(pathItem.Parameters); + // head, patch, options, delete left out + List possibleParameterisedOperations = new List { pathItem.Get, pathItem.Post, pathItem.Put }; + possibleParameterisedOperations.FindAll(x => x != null).ForEach(x => DescribeEnumParameters(x.Parameters)); + } + } + } + + private void DescribeEnumParameters(IList parameters) + { + if (parameters != null) + { + foreach (var param in parameters) + { + if (param.In == "path") + { + var nonParam = (NonBodyParameter)param; + IList paramEnums = nonParam.Enum; + if (paramEnums != null && paramEnums.Count > 0) + { + param.Description +=":"+ DescribeEnum(paramEnums); + } + } + if (param.In == "body") + { + var bodyParam = (BodyParameter)param; + Schema property = bodyParam.Schema; + IList propertyEnums = property.Enum; + if (propertyEnums != null && propertyEnums.Count > 0) + { + property.Description += ":" + DescribeEnum(propertyEnums); + } + } + if (param.In == "query") + { + var nonParam = (NonBodyParameter)param; + IList paramEnums = nonParam.Enum; + if (paramEnums != null && paramEnums.Count > 0) + { + param.Description += ":" + DescribeEnum(paramEnums); + } + } + } + } + } + /// + /// 枚举转换成值和描述 + /// + /// + /// + private string DescribeEnum(IList enums) + { + List enumDescriptions = new List(); + foreach (object item in enums) + { + var type = item.GetType(); + var objArr = type.GetField(item.ToString()).GetCustomAttributes(typeof(DisplayAttribute), true); + if (objArr != null && objArr.Length > 0) + { + DisplayAttribute da = objArr[0] as DisplayAttribute; + enumDescriptions.Add($"{(int)item} {da.Name}"); + } + else + { + enumDescriptions.Add(string.Format("{0} = {1}", (int)item, Enum.GetName(item.GetType(), item))); + } + } + return string.Join(", ", enumDescriptions.ToArray()); + } + + } +} diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/SwaggerOperationFilter.cs b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/SwaggerOperationFilter.cs index ce2cddb..48f003a 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/SwaggerOperationFilter.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/SwaggerOperationFilter.cs @@ -1,53 +1,53 @@ -using Microsoft.AspNetCore.JsonPatch.Operations; -using Swashbuckle.AspNetCore.Swagger; -using Swashbuckle.AspNetCore.SwaggerGen; -using System.ComponentModel.DataAnnotations; -using System.Linq; - -namespace Hncore.Infrastructure.WebApi.Filter -{ - public class SwaggerOperationFilter : IOperationFilter - { - /// - /// 应用过滤器 - /// - /// - /// - public void Apply(Swashbuckle.AspNetCore.Swagger.Operation operation, OperationFilterContext context) - { - #region Swagger版本描述处理 - - foreach (var parameter in operation.Parameters.OfType()) - { - //var description = context.ApiDescription.ParameterDescriptions.First(p => p.Name == parameter.Name); - if (parameter.Name == "version") - { - parameter.Description = "填写版本号如:1、2"; - parameter.Default = context.ApiDescription.GroupName.Replace("v", ""); - } - - //if (parameter.Enum!=null&¶meter.Enum.Count > 0) - //{ - // string desc = ""; - // foreach(var item in parameter.Enum) - // { - // var type = item.GetType(); - // var objArr=type.GetField(item.ToString()).GetCustomAttributes(typeof(DisplayAttribute), true); - // if (objArr != null && objArr.Length > 0) - // { - // DisplayAttribute da = objArr[0] as DisplayAttribute; - // desc += $"{item} {da.Name}"; - // } - // } - // parameter.Description = desc; - //} - } - - #endregion - - var auth = context.MethodInfo - .GetCustomAttributes(true) - .OfType(); - } - } +using Microsoft.AspNetCore.JsonPatch.Operations; +using Swashbuckle.AspNetCore.Swagger; +using Swashbuckle.AspNetCore.SwaggerGen; +using System.ComponentModel.DataAnnotations; +using System.Linq; + +namespace Hncore.Infrastructure.WebApi.Filter +{ + public class SwaggerOperationFilter : IOperationFilter + { + /// + /// 应用过滤器 + /// + /// + /// + public void Apply(Swashbuckle.AspNetCore.Swagger.Operation operation, OperationFilterContext context) + { + #region Swagger版本描述处理 + + foreach (var parameter in operation.Parameters.OfType()) + { + //var description = context.ApiDescription.ParameterDescriptions.First(p => p.Name == parameter.Name); + if (parameter.Name == "version") + { + parameter.Description = "填写版本号如:1、2"; + parameter.Default = context.ApiDescription.GroupName.Replace("v", ""); + } + + //if (parameter.Enum!=null&¶meter.Enum.Count > 0) + //{ + // string desc = ""; + // foreach(var item in parameter.Enum) + // { + // var type = item.GetType(); + // var objArr=type.GetField(item.ToString()).GetCustomAttributes(typeof(DisplayAttribute), true); + // if (objArr != null && objArr.Length > 0) + // { + // DisplayAttribute da = objArr[0] as DisplayAttribute; + // desc += $"{item} {da.Name}"; + // } + // } + // parameter.Description = desc; + //} + } + + #endregion + + var auth = context.MethodInfo + .GetCustomAttributes(true) + .OfType(); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/ValidateModelAttribute.cs b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/ValidateModelAttribute.cs index dacd7aa..617708d 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/Filter/ValidateModelAttribute.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/Filter/ValidateModelAttribute.cs @@ -1,46 +1,46 @@ -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using System; -using System.Collections.Generic; -using System.Net; -using System.Text; - -namespace Hncore.Infrastructure.WebApi.Filter -{ - public class ValidateModelAttribute : ActionFilterAttribute - { - /// - /// netcore 会自动判断context.ModelState.IsValid - /// 如果是false,自动返回BadRequestObjectResult - /// 需要在OnResultExecuting重写返回值 - /// - /// - public override void OnActionExecuting(ActionExecutingContext context) - { - //var httpContext = context.HttpContext; - //if (context.ModelState.IsValid == false) - //{ - // context.Result = new JsonResult(context.ModelState); - // //httpContext.Response = httpContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.ModelState); - //} - } - public override void OnResultExecuting(ResultExecutingContext context) - { - var httpContext = context.HttpContext; - if (context.ModelState.IsValid == false) - { - var message = new List(); ; - foreach(var item in context.ModelState.Values) - { - foreach (var error in item.Errors) - { - message.Add( error.ErrorMessage ); - } - } - var apiRes = new ApiResult(ResultCode.C_PARAM_ERROR, string.Join("|", message)); - context.Result = new JsonResult(apiRes); - //httpContext.Response = httpContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.ModelState); - } - } - } -} +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using System; +using System.Collections.Generic; +using System.Net; +using System.Text; + +namespace Hncore.Infrastructure.WebApi.Filter +{ + public class ValidateModelAttribute : ActionFilterAttribute + { + /// + /// netcore 会自动判断context.ModelState.IsValid + /// 如果是false,自动返回BadRequestObjectResult + /// 需要在OnResultExecuting重写返回值 + /// + /// + public override void OnActionExecuting(ActionExecutingContext context) + { + //var httpContext = context.HttpContext; + //if (context.ModelState.IsValid == false) + //{ + // context.Result = new JsonResult(context.ModelState); + // //httpContext.Response = httpContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.ModelState); + //} + } + public override void OnResultExecuting(ResultExecutingContext context) + { + var httpContext = context.HttpContext; + if (context.ModelState.IsValid == false) + { + var message = new List(); ; + foreach(var item in context.ModelState.Values) + { + foreach (var error in item.Errors) + { + message.Add( error.ErrorMessage ); + } + } + var apiRes = new ApiResult(ResultCode.C_PARAM_ERROR, string.Join("|", message)); + context.Result = new JsonResult(apiRes); + //httpContext.Response = httpContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.ModelState); + } + } + } +} diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/GlobalData.cs b/Infrastructure/Hncore.Infrastructure/WebApi/GlobalData.cs index 50e7078..cc8cbb8 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/GlobalData.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/GlobalData.cs @@ -1,7 +1,7 @@ -namespace Hncore.Infrastructure.WebApi -{ - internal class GlobalData - { - public static bool UseGlobalManageAuthFilter { get; set; } - } +namespace Hncore.Infrastructure.WebApi +{ + internal class GlobalData + { + public static bool UseGlobalManageAuthFilter { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/Middleware/ErrorHandlingMiddleware.cs b/Infrastructure/Hncore.Infrastructure/WebApi/Middleware/ErrorHandlingMiddleware.cs index d37f138..92313b5 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/Middleware/ErrorHandlingMiddleware.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/Middleware/ErrorHandlingMiddleware.cs @@ -1,103 +1,103 @@ -using System; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Data; -using Hncore.Infrastructure.Extension; -using Hncore.Infrastructure.OpenApi; -using Hncore.Infrastructure.Serializer; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using Hncore.Infrastructure.Core.Web; - - -namespace Hncore.Infrastructure.WebApi -{ - /// - /// 统一错误异常处理中间件类 - /// - /// - public class ErrorHandlingMiddleware - { - private readonly RequestDelegate next; - - public ErrorHandlingMiddleware(RequestDelegate next) - { - this.next = next; - } - - public async Task Invoke(HttpContext context) - { - try - { - await next(context); - } - catch (Exception ex) - { - string requestMsg = "请求URL:" + context.Request.GetAbsoluteUri() + ""; - - requestMsg += "\nMethod:" + context.Request.Method + "\n"; - - if (context.Request.Method.ToLower() != "get") - { - var requestBody = await context.Request.ReadBodyAsStringAsync(); - requestMsg += "Body:\n" + requestBody + - "\n------------------------\n"; - } - else - { - requestMsg += "\n------------------------\n"; - } - - - await HandleExceptionAsync(context, ex, requestMsg); - } - } - - - private static Task HandleExceptionAsync(HttpContext context, Exception ex, - string requestMsg) - { - ResultCode code = ResultCode.C_UNKNOWN_ERROR; - string msg = ""; - - if (ex is BusinessException bex) - { - code = bex.Code; - msg = bex.Message; - - LogHelper.Error($"业务异常,{msg}", requestMsg + ex); - } - else - { - if (EnvironmentVariableHelper.IsAspNetCoreProduction) - { - msg = "系统繁忙,请稍后再试"; - } - else - { - msg = ex.Message; - } - - LogHelper.Error($"未知异常,{ex.Message}", requestMsg + ex); - } - - var data = new ApiResult(code, msg); - - var result = data.ToJson(); - - context.Response.ContentType = "application/json;charset=utf-8"; - - return context.Response.WriteAsync(result); - } - } - - public static class ErrorHandlingExtensions - { - public static IApplicationBuilder UseErrorHandling(this IApplicationBuilder builder) - { - return builder.UseMiddleware(); - } - } +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Data; +using Hncore.Infrastructure.Extension; +using Hncore.Infrastructure.OpenApi; +using Hncore.Infrastructure.Serializer; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Hncore.Infrastructure.Core.Web; + + +namespace Hncore.Infrastructure.WebApi +{ + /// + /// 统一错误异常处理中间件类 + /// + /// + public class ErrorHandlingMiddleware + { + private readonly RequestDelegate next; + + public ErrorHandlingMiddleware(RequestDelegate next) + { + this.next = next; + } + + public async Task Invoke(HttpContext context) + { + try + { + await next(context); + } + catch (Exception ex) + { + string requestMsg = "请求URL:" + context.Request.GetAbsoluteUri() + ""; + + requestMsg += "\nMethod:" + context.Request.Method + "\n"; + + if (context.Request.Method.ToLower() != "get") + { + var requestBody = await context.Request.ReadBodyAsStringAsync(); + requestMsg += "Body:\n" + requestBody + + "\n------------------------\n"; + } + else + { + requestMsg += "\n------------------------\n"; + } + + + await HandleExceptionAsync(context, ex, requestMsg); + } + } + + + private static Task HandleExceptionAsync(HttpContext context, Exception ex, + string requestMsg) + { + ResultCode code = ResultCode.C_UNKNOWN_ERROR; + string msg = ""; + + if (ex is BusinessException bex) + { + code = bex.Code; + msg = bex.Message; + + LogHelper.Error($"业务异常,{msg}", requestMsg + ex); + } + else + { + if (EnvironmentVariableHelper.IsAspNetCoreProduction) + { + msg = "系统繁忙,请稍后再试"; + } + else + { + msg = ex.Message; + } + + LogHelper.Error($"未知异常,{ex.Message}", requestMsg + ex); + } + + var data = new ApiResult(code, msg); + + var result = data.ToJson(); + + context.Response.ContentType = "application/json;charset=utf-8"; + + return context.Response.WriteAsync(result); + } + } + + public static class ErrorHandlingExtensions + { + public static IApplicationBuilder UseErrorHandling(this IApplicationBuilder builder) + { + return builder.UseMiddleware(); + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/StartupExtensions/ApplicationBuilderExtend.cs b/Infrastructure/Hncore.Infrastructure/WebApi/StartupExtensions/ApplicationBuilderExtend.cs index 092bc59..a4e4c16 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/StartupExtensions/ApplicationBuilderExtend.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/StartupExtensions/ApplicationBuilderExtend.cs @@ -1,76 +1,76 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Common.DingTalk; -using Hncore.Infrastructure.Extension; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Logging; -using NLog.Extensions.Logging; - -namespace Hncore.Infrastructure.WebApi -{ - /// - /// 应用程序构建器扩展类 - /// - /// - public static class ApplicationBuilderExtend - { - /// - /// 初始化应用程序构建器 - /// - /// 当前应用程序构建器对象 - /// 日志工厂对象 - /// 初始化后的应用程序构建器对象 - /// 应用程序生命周期对象 - /// - public static IApplicationBuilder Init(this IApplicationBuilder app, ILoggerFactory loggerFactory, - IApplicationLifetime applicationLifetime) - { - loggerFactory.AddNLog(); //启用Nlog日志插件 - - app.UseErrorHandling(); //添加统一错误异常处理中间件(一个自定义类) - - - - //启用Cors(跨域请求)支持(默认关闭状态) - - app.UseCors(builder => builder - .SetIsOriginAllowed(host => true) //允许所有来源 - .AllowAnyMethod() //允许任何请求方法(GET、POST、PUT、DELETE等) - .AllowAnyHeader() //允许任何请求头信息 - .AllowCredentials() //允许跨域凭据 - // .SetPreflightMaxAge(TimeSpan.FromDays(30)) //指定可以缓存预检请求的响应的时间为30天 - .WithExposedHeaders("X-Suggested-Filename", "set-user-token", "set-user") - ); - app.UseMvc(); //启用MVC - - - //向应用程序生命周期的“应用程序已完全启动”事件注册回调函数 - applicationLifetime.ApplicationStarted.Register(OnAppStarted); - - return app; - } - - /// - /// 应用程序完全启动完成处理回调函数 - /// - /// - private static void OnAppStarted() - { - //if (EnvironmentVariableHelper.IsAspNetCoreProduction) - //{ - // DingTalkHelper.SendMessage(new MarkDownModel() - // { - // markdown = new markdown() - // { - // title = "应用已启动", - // text = "### 应用已启动\n\nhostname:" + EnvironmentVariableHelper.HostName + "\n\n" + - // DateTime.Now.Format("yyyy-MM-dd HH:mm:ss") - // } - // }); - //} - } - } +using System; +using System.Threading; +using System.Threading.Tasks; +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Common.DingTalk; +using Hncore.Infrastructure.Extension; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + +namespace Hncore.Infrastructure.WebApi +{ + /// + /// 应用程序构建器扩展类 + /// + /// + public static class ApplicationBuilderExtend + { + /// + /// 初始化应用程序构建器 + /// + /// 当前应用程序构建器对象 + /// 日志工厂对象 + /// 初始化后的应用程序构建器对象 + /// 应用程序生命周期对象 + /// + public static IApplicationBuilder Init(this IApplicationBuilder app, ILoggerFactory loggerFactory, + IApplicationLifetime applicationLifetime) + { + loggerFactory.AddNLog(); //启用Nlog日志插件 + + app.UseErrorHandling(); //添加统一错误异常处理中间件(一个自定义类) + + + + //启用Cors(跨域请求)支持(默认关闭状态) + + app.UseCors(builder => builder + .SetIsOriginAllowed(host => true) //允许所有来源 + .AllowAnyMethod() //允许任何请求方法(GET、POST、PUT、DELETE等) + .AllowAnyHeader() //允许任何请求头信息 + .AllowCredentials() //允许跨域凭据 + // .SetPreflightMaxAge(TimeSpan.FromDays(30)) //指定可以缓存预检请求的响应的时间为30天 + .WithExposedHeaders("X-Suggested-Filename", "set-user-token", "set-user") + ); + app.UseMvc(); //启用MVC + + + //向应用程序生命周期的“应用程序已完全启动”事件注册回调函数 + applicationLifetime.ApplicationStarted.Register(OnAppStarted); + + return app; + } + + /// + /// 应用程序完全启动完成处理回调函数 + /// + /// + private static void OnAppStarted() + { + //if (EnvironmentVariableHelper.IsAspNetCoreProduction) + //{ + // DingTalkHelper.SendMessage(new MarkDownModel() + // { + // markdown = new markdown() + // { + // title = "应用已启动", + // text = "### 应用已启动\n\nhostname:" + EnvironmentVariableHelper.HostName + "\n\n" + + // DateTime.Now.Format("yyyy-MM-dd HH:mm:ss") + // } + // }); + //} + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/StartupExtensions/HostingEnvironmentExtend.cs b/Infrastructure/Hncore.Infrastructure/WebApi/StartupExtensions/HostingEnvironmentExtend.cs index e2c02c9..bb9136c 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/StartupExtensions/HostingEnvironmentExtend.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/StartupExtensions/HostingEnvironmentExtend.cs @@ -1,42 +1,42 @@ -using System; -using System.Runtime; -using Hncore.Infrastructure.Serializer; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; - -namespace Hncore.Infrastructure.WebApi -{ - public static class HostingEnvironmentExtend - { - public static IConfigurationRoot UseAppsettings(this IHostingEnvironment env) - { - Console.WriteLine("环境:" + Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")); -#if DEBUG - Console.WriteLine("模式:DEBUG"); -#endif - -#if RELEASE - Console.WriteLine("模式:RELEASE"); -#endif - - Console.WriteLine("GC模式:" + new - { - IsServerGC = GCSettings.IsServerGC, - LargeObjectHeapCompactionMode = GCSettings.LargeObjectHeapCompactionMode.ToString(), - LatencyMode = GCSettings.LatencyMode.ToString() - }.ToJson(true)); - - System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); - - var builder = new ConfigurationBuilder() - .SetBasePath(env.ContentRootPath) - .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) - .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: false) - .AddEnvironmentVariables(); - - var config = builder.Build(); - - return config; - } - } +using System; +using System.Runtime; +using Hncore.Infrastructure.Serializer; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; + +namespace Hncore.Infrastructure.WebApi +{ + public static class HostingEnvironmentExtend + { + public static IConfigurationRoot UseAppsettings(this IHostingEnvironment env) + { + Console.WriteLine("环境:" + Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")); +#if DEBUG + Console.WriteLine("模式:DEBUG"); +#endif + +#if RELEASE + Console.WriteLine("模式:RELEASE"); +#endif + + Console.WriteLine("GC模式:" + new + { + IsServerGC = GCSettings.IsServerGC, + LargeObjectHeapCompactionMode = GCSettings.LargeObjectHeapCompactionMode.ToString(), + LatencyMode = GCSettings.LatencyMode.ToString() + }.ToJson(true)); + + System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); + + var builder = new ConfigurationBuilder() + .SetBasePath(env.ContentRootPath) + .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) + .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: false) + .AddEnvironmentVariables(); + + var config = builder.Build(); + + return config; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/StartupExtensions/ServiceCollectionExtend.cs b/Infrastructure/Hncore.Infrastructure/WebApi/StartupExtensions/ServiceCollectionExtend.cs index 5180bb9..98bedcb 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/StartupExtensions/ServiceCollectionExtend.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/StartupExtensions/ServiceCollectionExtend.cs @@ -1,113 +1,113 @@ -using System; -using Hncore.Infrastructure.Autofac; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Newtonsoft.Json; - -namespace Hncore.Infrastructure.WebApi -{ - /// - /// 服务集合对象(可以理解为内置的依赖注入容器)功能扩展类 - /// - /// - public static class ServiceCollectionExtend - { - /// - /// 通用初始化方法(被各个微服务项目所引用) - /// - /// 服务集合对象 - /// 配置信息对象 - /// .net core兼容版本 - /// 服务自定义选项对象 - /// 服务提供者对象 - /// - public static IServiceProvider Init(this IServiceCollection services, IConfiguration configuration, - CompatibilityVersion version, ServiceOption serviceOption = null) - { - //启用选项配置服务 - services.AddOptions(); - - //将配置信息对象以单例模式添加到服务集合中 - services.AddSingleton(configuration); - - // services.AddCors(); - var mvcbuilder = services - .AddMvc(options => - { - options.EnableEndpointRouting = false; //关闭终端点路由 - - if (serviceOption != null && serviceOption.UseGlobalManageAuthFilter) - { - //如果配置并传递了自定义选项中的全局授权过滤器,就将全局授权过滤器添加到MVC全局过滤器链中让其生效 - options.Filters.Add(new ManageAuthAttribute()); - - GlobalData.UseGlobalManageAuthFilter = true; - } - else - { - GlobalData.UseGlobalManageAuthFilter = false; - } - }) - .SetCompatibilityVersion(version) //设置.net core兼容版本号 - .AddJsonOptions(options => - { - //使用NewtonsoftJson插件,替换掉系统默认提供的JSON插件 - options.SerializerSettings.ContractResolver = - new Newtonsoft.Json.Serialization.DefaultContractResolver(); - - //定义日期格式化策略 - options.SerializerSettings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; - - options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; - - //定义循环引用处理策略(就是要序列化的对象类A中引用了B,B引用了C……转了一圈儿之后又直接或间接引用回了A,就称为循环引用) - options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; - - //序列化或反序列化时,可接受的日期时间字符串格式 - options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; - - if (serviceOption != null && serviceOption.IgnoreJsonNullValue) - { - //如果配置并传递了自定义选项中的忽略空值选项,就在操作JSON时忽略掉空值数据 - //忽略掉空值的意思就是如果对象中的某个属性值为null,它将不会出现在最终序列化后的JSON字符串中 - options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; - } - }); - - services.AddApiVersioning(option => - { - //设置API版本信息 - option.ReportApiVersions = true; //在向客户端响应的响应头中显示受支持的API版本信息 - option.AssumeDefaultVersionWhenUnspecified = true; //如果客户端未提供并指定要调用的API版本,就以下方的默认版本为准 - option.DefaultApiVersion = new ApiVersion(1, 0); //默认版本号 - }); - - //启用HTTP请求上下文访问器(用来访问类似传统MVC中的那个HttpContext对象) - services.AddHttpContextAccessor(); - - - - - //构建并返回服务提供对象(在Build方法中主要用Autofac插件替换掉了默认的依赖注入插件,并做一些自动扫描配置) - return new MvcAutoRegister().Build(services, mvcbuilder); - } - } - - /// - /// 服务自定义配置类(承载一些自定义配置) - /// - /// - public class ServiceOption - { - /// - /// 是否启用全局授权过滤器(默认关闭) - /// - public bool UseGlobalManageAuthFilter { get; set; } = false; - - /// - /// 是否在生成的JSON字符串中忽略掉为null的属性或字段(默认为false,意思就是就算字段为null也会出现在最终序列化后的JSON字符串中) - /// - public bool IgnoreJsonNullValue { get; set; } = false; - } +using System; +using Hncore.Infrastructure.Autofac; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Newtonsoft.Json; + +namespace Hncore.Infrastructure.WebApi +{ + /// + /// 服务集合对象(可以理解为内置的依赖注入容器)功能扩展类 + /// + /// + public static class ServiceCollectionExtend + { + /// + /// 通用初始化方法(被各个微服务项目所引用) + /// + /// 服务集合对象 + /// 配置信息对象 + /// .net core兼容版本 + /// 服务自定义选项对象 + /// 服务提供者对象 + /// + public static IServiceProvider Init(this IServiceCollection services, IConfiguration configuration, + CompatibilityVersion version, ServiceOption serviceOption = null) + { + //启用选项配置服务 + services.AddOptions(); + + //将配置信息对象以单例模式添加到服务集合中 + services.AddSingleton(configuration); + + // services.AddCors(); + var mvcbuilder = services + .AddMvc(options => + { + options.EnableEndpointRouting = false; //关闭终端点路由 + + if (serviceOption != null && serviceOption.UseGlobalManageAuthFilter) + { + //如果配置并传递了自定义选项中的全局授权过滤器,就将全局授权过滤器添加到MVC全局过滤器链中让其生效 + options.Filters.Add(new ManageAuthAttribute()); + + GlobalData.UseGlobalManageAuthFilter = true; + } + else + { + GlobalData.UseGlobalManageAuthFilter = false; + } + }) + .SetCompatibilityVersion(version) //设置.net core兼容版本号 + .AddJsonOptions(options => + { + //使用NewtonsoftJson插件,替换掉系统默认提供的JSON插件 + options.SerializerSettings.ContractResolver = + new Newtonsoft.Json.Serialization.DefaultContractResolver(); + + //定义日期格式化策略 + options.SerializerSettings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; + + options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; + + //定义循环引用处理策略(就是要序列化的对象类A中引用了B,B引用了C……转了一圈儿之后又直接或间接引用回了A,就称为循环引用) + options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + + //序列化或反序列化时,可接受的日期时间字符串格式 + options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; + + if (serviceOption != null && serviceOption.IgnoreJsonNullValue) + { + //如果配置并传递了自定义选项中的忽略空值选项,就在操作JSON时忽略掉空值数据 + //忽略掉空值的意思就是如果对象中的某个属性值为null,它将不会出现在最终序列化后的JSON字符串中 + options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; + } + }); + + services.AddApiVersioning(option => + { + //设置API版本信息 + option.ReportApiVersions = true; //在向客户端响应的响应头中显示受支持的API版本信息 + option.AssumeDefaultVersionWhenUnspecified = true; //如果客户端未提供并指定要调用的API版本,就以下方的默认版本为准 + option.DefaultApiVersion = new ApiVersion(1, 0); //默认版本号 + }); + + //启用HTTP请求上下文访问器(用来访问类似传统MVC中的那个HttpContext对象) + services.AddHttpContextAccessor(); + + + + + //构建并返回服务提供对象(在Build方法中主要用Autofac插件替换掉了默认的依赖注入插件,并做一些自动扫描配置) + return new MvcAutoRegister().Build(services, mvcbuilder); + } + } + + /// + /// 服务自定义配置类(承载一些自定义配置) + /// + /// + public class ServiceOption + { + /// + /// 是否启用全局授权过滤器(默认关闭) + /// + public bool UseGlobalManageAuthFilter { get; set; } = false; + + /// + /// 是否在生成的JSON字符串中忽略掉为null的属性或字段(默认为false,意思就是就算字段为null也会出现在最终序列化后的JSON字符串中) + /// + public bool IgnoreJsonNullValue { get; set; } = false; + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/WebApi/WebRequest.cs b/Infrastructure/Hncore.Infrastructure/WebApi/WebRequest.cs index e637bd0..0f4ba61 100644 --- a/Infrastructure/Hncore.Infrastructure/WebApi/WebRequest.cs +++ b/Infrastructure/Hncore.Infrastructure/WebApi/WebRequest.cs @@ -1,71 +1,71 @@ -using Microsoft.AspNetCore.Http; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading.Tasks; - -namespace Hncore.Infrastructure.Core.Web -{ - public static class HttpContextExtension - { - public static string GetUserIp(this HttpContext context) - { - var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault(); - if (string.IsNullOrEmpty(ip)) - { - ip = context.Connection.RemoteIpAddress.ToString(); - } - - return ip; - } - - public static string GetAbsoluteUri(this HttpRequest request) - { - return new StringBuilder() - .Append(request.Scheme) - .Append("://") - .Append(request.Host) - .Append(request.PathBase) - .Append(request.Path) - .Append(request.QueryString) - .ToString(); - } - - public static async Task ReadBodyAsStringAsync(this HttpRequest request) - { - request.EnableBuffering(); - - var requestReader = new StreamReader(request.Body); - - var requestBody = await requestReader.ReadToEndAsync(); - - request.Body.Position = 0; - - return requestBody; - } - } - - public static class IsLocalExtension - { - private const string NullIpAddress = "::1"; - - public static bool IsLocal(this HttpRequest req) - { - var connection = req.HttpContext.Connection; - if (connection.RemoteIpAddress.IsSet()) - { - return connection.LocalIpAddress.IsSet() - ? connection.RemoteIpAddress.Equals(connection.LocalIpAddress) - : IPAddress.IsLoopback(connection.RemoteIpAddress); - } - - return true; - } - - private static bool IsSet(this IPAddress address) - { - return address != null && address.ToString() != NullIpAddress; - } - } +using Microsoft.AspNetCore.Http; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading.Tasks; + +namespace Hncore.Infrastructure.Core.Web +{ + public static class HttpContextExtension + { + public static string GetUserIp(this HttpContext context) + { + var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault(); + if (string.IsNullOrEmpty(ip)) + { + ip = context.Connection.RemoteIpAddress.ToString(); + } + + return ip; + } + + public static string GetAbsoluteUri(this HttpRequest request) + { + return new StringBuilder() + .Append(request.Scheme) + .Append("://") + .Append(request.Host) + .Append(request.PathBase) + .Append(request.Path) + .Append(request.QueryString) + .ToString(); + } + + public static async Task ReadBodyAsStringAsync(this HttpRequest request) + { + request.EnableBuffering(); + + var requestReader = new StreamReader(request.Body); + + var requestBody = await requestReader.ReadToEndAsync(); + + request.Body.Position = 0; + + return requestBody; + } + } + + public static class IsLocalExtension + { + private const string NullIpAddress = "::1"; + + public static bool IsLocal(this HttpRequest req) + { + var connection = req.HttpContext.Connection; + if (connection.RemoteIpAddress.IsSet()) + { + return connection.LocalIpAddress.IsSet() + ? connection.RemoteIpAddress.Equals(connection.LocalIpAddress) + : IPAddress.IsLoopback(connection.RemoteIpAddress); + } + + return true; + } + + private static bool IsSet(this IPAddress address) + { + return address != null && address.ToString() != NullIpAddress; + } + } } \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/nlog.config b/Infrastructure/Hncore.Infrastructure/nlog.config index 08d55a2..8ea310b 100644 --- a/Infrastructure/Hncore.Infrastructure/nlog.config +++ b/Infrastructure/Hncore.Infrastructure/nlog.config @@ -1,25 +1,25 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Infrastructure/Hncore.Infrastructure/xUnit/PriorityOrderer.cs b/Infrastructure/Hncore.Infrastructure/xUnit/PriorityOrderer.cs index 3ec7740..36397be 100644 --- a/Infrastructure/Hncore.Infrastructure/xUnit/PriorityOrderer.cs +++ b/Infrastructure/Hncore.Infrastructure/xUnit/PriorityOrderer.cs @@ -1,56 +1,56 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Xunit.Abstractions; -using Xunit.Sdk; - -namespace Hncore.Infrastructure.xUnit -{ - public class PriorityOrderer : ITestCaseOrderer - { - public IEnumerable OrderTestCases(IEnumerable testCases) where TTestCase : ITestCase - { - var sortedMethods = new SortedDictionary>(); - - foreach (TTestCase testCase in testCases) - { - int priority = 0; - - foreach (IAttributeInfo attr in testCase.TestMethod.Method.GetCustomAttributes((typeof(TestPriorityAttribute).AssemblyQualifiedName))) - priority = attr.GetNamedArgument("Priority"); - - GetOrCreate(sortedMethods, priority).Add(testCase); - } - - foreach (var list in sortedMethods.Keys.Select(priority => sortedMethods[priority])) - { - list.Sort((x, y) => StringComparer.OrdinalIgnoreCase.Compare(x.TestMethod.Method.Name, y.TestMethod.Method.Name)); - foreach (TTestCase testCase in list) - yield return testCase; - } - } - - static TValue GetOrCreate(IDictionary dictionary, TKey key) where TValue : new() - { - TValue result; - - if (dictionary.TryGetValue(key, out result)) return result; - - result = new TValue(); - dictionary[key] = result; - - return result; - } - } - - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] - public class TestPriorityAttribute : Attribute - { - public TestPriorityAttribute(int priority) - { - Priority = priority; - } - - public int Priority { get; private set; } - } +using System; +using System.Collections.Generic; +using System.Linq; +using Xunit.Abstractions; +using Xunit.Sdk; + +namespace Hncore.Infrastructure.xUnit +{ + public class PriorityOrderer : ITestCaseOrderer + { + public IEnumerable OrderTestCases(IEnumerable testCases) where TTestCase : ITestCase + { + var sortedMethods = new SortedDictionary>(); + + foreach (TTestCase testCase in testCases) + { + int priority = 0; + + foreach (IAttributeInfo attr in testCase.TestMethod.Method.GetCustomAttributes((typeof(TestPriorityAttribute).AssemblyQualifiedName))) + priority = attr.GetNamedArgument("Priority"); + + GetOrCreate(sortedMethods, priority).Add(testCase); + } + + foreach (var list in sortedMethods.Keys.Select(priority => sortedMethods[priority])) + { + list.Sort((x, y) => StringComparer.OrdinalIgnoreCase.Compare(x.TestMethod.Method.Name, y.TestMethod.Method.Name)); + foreach (TTestCase testCase in list) + yield return testCase; + } + } + + static TValue GetOrCreate(IDictionary dictionary, TKey key) where TValue : new() + { + TValue result; + + if (dictionary.TryGetValue(key, out result)) return result; + + result = new TValue(); + dictionary[key] = result; + + return result; + } + } + + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + public class TestPriorityAttribute : Attribute + { + public TestPriorityAttribute(int priority) + { + Priority = priority; + } + + public int Priority { get; private set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/Alipay.AopSdk.Core/DefaultAopClient.cs b/Infrastructure/ServiceClient/Alipay.AopSdk.Core/DefaultAopClient.cs index 47ea2cc..76e8bc3 100644 --- a/Infrastructure/ServiceClient/Alipay.AopSdk.Core/DefaultAopClient.cs +++ b/Infrastructure/ServiceClient/Alipay.AopSdk.Core/DefaultAopClient.cs @@ -1,649 +1,649 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Threading.Tasks; -using System.Web; -using Alipay.AopSdk.Core.Parser; -using Alipay.AopSdk.Core.Util; -using Newtonsoft.Json; - -namespace Alipay.AopSdk.Core -{ - /// - /// - /// AOP客户端。 - /// - public class DefaultAopClient : IAopClient - { - public const string APP_ID = "app_id"; - public const string FORMAT = "format"; - public const string METHOD = "method"; - public const string TIMESTAMP = "timestamp"; - public const string VERSION = "version"; - public const string SIGN_TYPE = "sign_type"; - public const string ACCESS_TOKEN = "auth_token"; - public const string SIGN = "sign"; - public const string TERMINAL_TYPE = "terminal_type"; - public const string TERMINAL_INFO = "terminal_info"; - public const string PROD_CODE = "prod_code"; - public const string NOTIFY_URL = "notify_url"; - public const string CHARSET = "charset"; - public const string ENCRYPT_TYPE = "encrypt_type"; - public const string BIZ_CONTENT = "biz_content"; - public const string APP_AUTH_TOKEN = "app_auth_token"; - public const string RETURN_URL = "return_url"; - private readonly string alipayPublicKey; - private string charset; - private readonly string encyptKey; - private readonly string encyptType = "AES"; - private string format; - private string httpmethod; - private readonly bool keyFromFile; - - public string notify_url; - private readonly string privateKeyPem; - public string return_url; - private readonly string serverUrl; - private readonly string signType = "RSA2"; - - private string version; - - private readonly WebUtils webUtils; - - public string Version - { - get => version != null ? version : "1.0"; - set => version = value; - } - - public string Format - { - get => format != null ? format : "json"; - set => format = value; - } - - public string AppId { get; set; } - - #region IAopClient Members - - public T PageExecute(IAopRequest request) where T : AopResponse - { - return PageExecute(request, null, "POST"); - } - - public async Task PageExecuteAsync(IAopRequest request) where T : AopResponse - { - return await PageExecuteAsync(request, null, "POST"); - } - #endregion - - #region IAopClient Members - public T PageExecute (IAopRequest request, string accessToken, string reqMethod) where T : AopResponse - { - return AsyncHelper.RunSync(async () => await PageExecuteAsync(request, accessToken, reqMethod)); - } - - public async Task PageExecuteAsync(IAopRequest request, string accessToken, string reqMethod) where T : AopResponse - { - if (string.IsNullOrEmpty(charset)) - charset = "utf-8"; - - string apiVersion = null; - - if (!string.IsNullOrEmpty(request.GetApiVersion())) - apiVersion = request.GetApiVersion(); - else - apiVersion = Version; - - var txtParams = new AopDictionary(request.GetParameters()); - - // 序列化BizModel - txtParams = SerializeBizModel(txtParams, request); - - // 添加协议级请求参数 - //AopDictionary txtParams = new AopDictionary(request.GetParameters()); - txtParams.Add(METHOD, request.GetApiName()); - txtParams.Add(VERSION, apiVersion); - txtParams.Add(APP_ID, AppId); - txtParams.Add(FORMAT, format); - txtParams.Add(TIMESTAMP, DateTime.Now); - txtParams.Add(ACCESS_TOKEN, accessToken); - txtParams.Add(SIGN_TYPE, signType); - txtParams.Add(TERMINAL_TYPE, request.GetTerminalType()); - txtParams.Add(TERMINAL_INFO, request.GetTerminalInfo()); - txtParams.Add(PROD_CODE, request.GetProdCode()); - txtParams.Add(NOTIFY_URL, request.GetNotifyUrl()); - txtParams.Add(CHARSET, charset); - txtParams.Add(RETURN_URL, request.GetReturnUrl()); - //字典排序 - IDictionary sortedTxtParams = new SortedDictionary(txtParams); - txtParams = new AopDictionary(sortedTxtParams); - // 排序返回字典类型添加签名参数 - - var signContent =AlipaySignature.GetSignContent(txtParams); - - var path ="Logs/"+DateTime.Now.ToString("yyyyMMdd"); - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - var file = path + "/alipay.log"; - File.AppendAllText(file, "pay body:" + signContent); - - txtParams.Add(SIGN, AopUtils.SignAopRequest(sortedTxtParams, privateKeyPem, charset, keyFromFile, signType)); - File.AppendAllText(file, "pay SIGN:" + txtParams[SIGN]); - // 是否需要上传文件 - string body; - - if (request is IAopUploadRequest) - { - var uRequest = (IAopUploadRequest) request; - var fileParams = AopUtils.CleanupDictionary(uRequest.GetFileParameters()); - body = await webUtils.DoPostAsync(serverUrl + "?" + CHARSET + "=" + charset, txtParams, fileParams, charset); - } - else - { - if (reqMethod.Equals("GET")) - { - //直接调用DoGet方法请求 - //body=webUtils .DoGet (this.serverUrl ,txtParams ,this.charset); - //拼接get请求的url - var tmpUrl = serverUrl; - if (txtParams != null && txtParams.Count > 0) - if (tmpUrl.Contains("?")) - tmpUrl = tmpUrl + "&" + WebUtils.BuildQuery(txtParams, charset); - else - tmpUrl = tmpUrl + "?" + WebUtils.BuildQuery(txtParams, charset); - body = tmpUrl; - } - else - { - //直接调用DoPost方法请求 - // body = webUtils.DoPost(this.serverUrl, txtParams, this.charset); - //输出post表单 - body = BuildHtmlRequest(txtParams, reqMethod, reqMethod); - } - } - - T rsp = null; - IAopParser parser = null; - if ("xml".Equals(format)) - { - parser = new AopXmlParser(); - rsp = parser.Parse(body, charset); - } - else - { - parser = new AopJsonParser(); - rsp = parser.Parse(body, charset); - } - - //验签 - // CheckResponseSign(request, rsp, parser, this.alipayPublicKey, this.charset); - return rsp; - } - - #endregion - - #region SDK Execute - - public T SdkExecute(IAopRequest request) where T : AopResponse - { - // 构造请求参数 - var requestParams = buildRequestParams(request, null, null); - - // 字典排序 - IDictionary sortedParams = new SortedDictionary(requestParams); - var sortedAopDic = new AopDictionary(sortedParams); - - // 参数签名 - var charset = string.IsNullOrEmpty(this.charset) ? "utf-8" : this.charset; - var signResult = AopUtils.SignAopRequest(sortedAopDic, privateKeyPem, charset, keyFromFile, signType); - - // 添加签名结果参数 - sortedAopDic.Add(SIGN, signResult); - - // 参数拼接 - var signedResult = WebUtils.BuildQuery(sortedAopDic, charset); - - // 构造结果 - var rsp = (T) Activator.CreateInstance(typeof(T)); - rsp.Body = signedResult; - return rsp; - } - - #endregion - - #region IAopClient Members - - public string BuildHtmlRequest(IDictionary sParaTemp, string strMethod, string strButtonValue) - { - //待请求参数数组 - IDictionary dicPara = new Dictionary(); - dicPara = sParaTemp; - - var sbHtml = new StringBuilder(); - //sbHtml.Append(""); - - sbHtml.Append("
"); - ; - foreach (var temp in dicPara) - sbHtml.Append(""); - - //submit按钮控件请不要含有name属性 - sbHtml.Append("
"); - // sbHtml.Append(""); - - //表单实现自动提交 - sbHtml.Append(""); - - return sbHtml.ToString(); - } - - #endregion - - #region Common Method - - private AopDictionary buildRequestParams(IAopRequest request, string accessToken, string appAuthToken) - where T : AopResponse - { - // 默认参数 - var oriParams = new AopDictionary(request.GetParameters()); - - // 序列化BizModel - var result = SerializeBizModel(oriParams, request); - - // 获取参数 - var charset = string.IsNullOrEmpty(this.charset) ? "utf-8" : this.charset; - var apiVersion = string.IsNullOrEmpty(request.GetApiVersion()) ? Version : request.GetApiVersion(); - - // 添加协议级请求参数,为空的参数后面会自动过滤,这里不做处理。 - result.Add(METHOD, request.GetApiName()); - result.Add(VERSION, apiVersion); - result.Add(APP_ID, AppId); - result.Add(FORMAT, format); - result.Add(TIMESTAMP, DateTime.Now); - result.Add(ACCESS_TOKEN, accessToken); - result.Add(SIGN_TYPE, signType); - result.Add(TERMINAL_TYPE, request.GetTerminalType()); - result.Add(TERMINAL_INFO, request.GetTerminalInfo()); - result.Add(PROD_CODE, request.GetProdCode()); - result.Add(NOTIFY_URL, request.GetNotifyUrl()); - result.Add(CHARSET, charset); - result.Add(RETURN_URL, request.GetReturnUrl()); - result.Add(APP_AUTH_TOKEN, appAuthToken); - - if (request.GetNeedEncrypt()) - { - if (string.IsNullOrEmpty(result[BIZ_CONTENT])) - throw new AopException("api request Fail ! The reason: encrypt request is not supported!"); - - if (string.IsNullOrEmpty(encyptKey) || string.IsNullOrEmpty(encyptType)) - throw new AopException("encryptType or encryptKey must not null!"); - - if (!"AES".Equals(encyptType)) - throw new AopException("api only support Aes!"); - - var encryptContent = AopUtils.AesEncrypt(encyptKey, result[BIZ_CONTENT], this.charset); - result.Remove(BIZ_CONTENT); - result.Add(BIZ_CONTENT, encryptContent); - result.Add(ENCRYPT_TYPE, encyptType); - } - - return result; - } - - #endregion - - #region DefaultAopClient Constructors - - public DefaultAopClient(string serverUrl, string appId, string privateKeyPem) - { - AppId = appId; - this.privateKeyPem = privateKeyPem; - this.serverUrl = serverUrl; - webUtils = new WebUtils(serverUrl); - } - - public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, bool keyFromFile) - { - AppId = appId; - this.privateKeyPem = privateKeyPem; - this.serverUrl = serverUrl; - this.keyFromFile = keyFromFile; - webUtils = new WebUtils(serverUrl); - } - - public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, string format) - { - AppId = appId; - this.privateKeyPem = privateKeyPem; - this.serverUrl = serverUrl; - this.format = format; - webUtils = new WebUtils(serverUrl); - } - - public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, string format, string charset) - : this(serverUrl, appId, privateKeyPem, format) - { - this.charset = charset; - } - - public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, string format, string version, - string signType) - : this(serverUrl, appId, privateKeyPem) - { - this.format = format; - this.version = version; - this.signType = signType; - } - - public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, string format, string version, - string signType, string alipayPulicKey) - : this(serverUrl, appId, privateKeyPem, format, version, signType) - { - alipayPublicKey = alipayPulicKey; - } - - public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, string format, string version, - string signType, string alipayPulicKey, string charset) - : this(serverUrl, appId, privateKeyPem, format, version, signType, alipayPulicKey) - { - this.charset = charset; - } - - // - public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, string format, string version, - string signType, string alipayPulicKey, string charset, bool keyFromFile) - : this(serverUrl, appId, privateKeyPem, format, version, signType, alipayPulicKey) - { - this.keyFromFile = keyFromFile; - this.charset = charset; - } - - public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, string format, string version, - string signType, string alipayPulicKey, string charset, string encyptKey) - : this(serverUrl, appId, privateKeyPem, format, version, signType, alipayPulicKey, charset) - { - this.encyptKey = encyptKey; - encyptType = "AES"; - } - - #endregion - - #region IAopClient Members - - public T Execute(IAopRequest request) where T : AopResponse - { - return Execute(request, null); - } - - public T Execute(IAopRequest request, string accessToken) where T : AopResponse - { - return Execute(request, accessToken, null); - } - - public async Task ExecuteAsync(IAopRequest request) where T : AopResponse - { - return await ExecuteAsync(request, null); - } - - public async Task ExecuteAsync(IAopRequest request, string accessToken) where T : AopResponse - { - return await ExecuteAsync(request, accessToken, null); - } - - #endregion - - #region IAopClient Members - - public T Execute(IAopRequest request, string accessToken, string appAuthToken) where T : AopResponse - { - return AsyncHelper.RunSync(async () => await ExecuteAsync(request, accessToken, appAuthToken)); - } - - public async Task ExecuteAsync(IAopRequest request, string accessToken, string appAuthToken) where T : AopResponse - { - if (string.IsNullOrEmpty(charset)) - charset = "utf-8"; - - string apiVersion = null; - - if (!string.IsNullOrEmpty(request.GetApiVersion())) - apiVersion = request.GetApiVersion(); - else - apiVersion = Version; - - // 添加协议级请求参数 - var txtParams = new AopDictionary(request.GetParameters()); - - // 序列化BizModel - txtParams = SerializeBizModel(txtParams, request); - - txtParams.Add(METHOD, request.GetApiName()); - txtParams.Add(VERSION, apiVersion); - txtParams.Add(APP_ID, AppId); - txtParams.Add(FORMAT, format); - txtParams.Add(TIMESTAMP, DateTime.Now); - txtParams.Add(ACCESS_TOKEN, accessToken); - txtParams.Add(SIGN_TYPE, signType); - txtParams.Add(TERMINAL_TYPE, request.GetTerminalType()); - txtParams.Add(TERMINAL_INFO, request.GetTerminalInfo()); - txtParams.Add(PROD_CODE, request.GetProdCode()); - txtParams.Add(CHARSET, charset); - - - if (!string.IsNullOrEmpty(request.GetNotifyUrl())) - txtParams.Add(NOTIFY_URL, request.GetNotifyUrl()); - - if (!string.IsNullOrEmpty(appAuthToken)) - txtParams.Add(APP_AUTH_TOKEN, appAuthToken); - - - if (request.GetNeedEncrypt()) - { - if (string.IsNullOrEmpty(txtParams[BIZ_CONTENT])) - throw new AopException("api request Fail ! The reason: encrypt request is not supported!"); - - if (string.IsNullOrEmpty(encyptKey) || string.IsNullOrEmpty(encyptType)) - throw new AopException("encryptType or encryptKey must not null!"); - - if (!"AES".Equals(encyptType)) - throw new AopException("api only support Aes!"); - - var encryptContent = AopUtils.AesEncrypt(encyptKey, txtParams[BIZ_CONTENT], charset); - txtParams.Remove(BIZ_CONTENT); - txtParams.Add(BIZ_CONTENT, encryptContent); - txtParams.Add(ENCRYPT_TYPE, encyptType); - } - - // 添加签名参数 - txtParams.Add(SIGN, AopUtils.SignAopRequest(txtParams, privateKeyPem, charset, keyFromFile, signType)); - - - // 是否需要上传文件 - string body; - - - if (request is IAopUploadRequest) - { - var uRequest = (IAopUploadRequest)request; - var fileParams = AopUtils.CleanupDictionary(uRequest.GetFileParameters()); - body = await webUtils.DoPostAsync(serverUrl + "?" + CHARSET + "=" + charset, txtParams, fileParams, charset); - } - else - { - body = await webUtils.DoPostAsync(serverUrl + "?" + CHARSET + "=" + charset, txtParams, charset); - } - - T rsp = null; - IAopParser parser = null; - if ("xml".Equals(format)) - { - parser = new AopXmlParser(); - rsp = parser.Parse(body, charset); - } - else - { - parser = new AopJsonParser(); - rsp = parser.Parse(body, charset); - } - - var item = parseRespItem(request, body, parser, encyptKey, encyptType, charset); - rsp = parser.Parse(item.realContent, charset); - - CheckResponseSign(request, item.respContent, rsp.IsError, parser, alipayPublicKey, charset, signType, keyFromFile); - - return rsp; - } - - private static ResponseParseItem parseRespItem(IAopRequest request, string respBody, IAopParser parser, - string encryptKey, string encryptType, string charset) where T : AopResponse - { - string realContent = null; - - if (request.GetNeedEncrypt()) - realContent = parser.EncryptSourceData(request, respBody, encryptType, encryptKey, charset); - else - realContent = respBody; - - var item = new ResponseParseItem(); - item.realContent = realContent; - item.respContent = respBody; - - return item; - } - - public static void CheckResponseSign(IAopRequest request, string responseBody, bool isError, - IAopParser parser, string alipayPublicKey, string charset, string signType) where T : AopResponse - { - if (string.IsNullOrEmpty(alipayPublicKey) || string.IsNullOrEmpty(charset)) - return; - - var signItem = parser.GetSignItem(request, responseBody); - if (signItem == null) - throw new AopException("sign check fail: Body is Empty!"); - - if (!isError || - isError && !string.IsNullOrEmpty(signItem.Sign)) - { - var rsaCheckContent = - AlipaySignature.RSACheckContent(signItem.SignSourceDate, signItem.Sign, alipayPublicKey, charset, signType); - if (!rsaCheckContent) - if (!string.IsNullOrEmpty(signItem.SignSourceDate) && signItem.SignSourceDate.Contains("\\/")) - { - var srouceData = signItem.SignSourceDate.Replace("\\/", "/"); - var jsonCheck = AlipaySignature.RSACheckContent(srouceData, signItem.Sign, alipayPublicKey, charset, signType); - if (!jsonCheck) - throw new AopException( - "sign check fail: check Sign and Data Fail JSON also"); - } - else - { - throw new AopException( - "sign check fail: check Sign and Data Fail!"); - } - } - } - - public static void CheckResponseSign(IAopRequest request, string responseBody, bool isError, - IAopParser parser, string alipayPublicKey, string charset, string signType, bool keyFromFile) - where T : AopResponse - { - if (string.IsNullOrEmpty(alipayPublicKey) || string.IsNullOrEmpty(charset)) - return; - - var signItem = parser.GetSignItem(request, responseBody); - if (signItem == null) - throw new AopException("sign check fail: Body is Empty!"); - - if (!isError || - isError && !string.IsNullOrEmpty(signItem.Sign)) - { - var rsaCheckContent = AlipaySignature.RSACheckContent(signItem.SignSourceDate, signItem.Sign, alipayPublicKey, - charset, signType, keyFromFile); - if (!rsaCheckContent) - if (!string.IsNullOrEmpty(signItem.SignSourceDate) && signItem.SignSourceDate.Contains("\\/")) - { - var srouceData = signItem.SignSourceDate.Replace("\\/", "/"); - var jsonCheck = - AlipaySignature.RSACheckContent(srouceData, signItem.Sign, alipayPublicKey, charset, signType, keyFromFile); - if (!jsonCheck) - throw new AopException( - "sign check fail: check Sign and Data Fail JSON also"); - } - else - { - throw new AopException( - "sign check fail: check Sign and Data Fail!"); - } - } - } - - #endregion - - #region IAopClient Members - - public Dictionary FilterPara(SortedDictionary dicArrayPre) - { - var dicArray = new Dictionary(); - foreach (var temp in dicArrayPre) - if (temp.Key.ToLower() != "sign" && temp.Key.ToLower() != "sign_type" && temp.Value != "" && temp.Value != null) - dicArray.Add(temp.Key, temp.Value); - - return dicArray; - } - - public static string CreateLinkStringUrlencode(Dictionary dicArray, Encoding code) - { - var prestr = new StringBuilder(); - foreach (var temp in dicArray) - prestr.Append(temp.Key + "=" + HttpUtility.UrlEncode(temp.Value, code) + "&"); - - //去掉最後一個&字符 - var nLen = prestr.Length; - prestr.Remove(nLen - 1, 1); - - return prestr.ToString(); - } - - #endregion - - #region Model Serialize - - /// - /// - /// - /// - /// - /// - private AopDictionary SerializeBizModel(AopDictionary requestParams, IAopRequest request) where T : AopResponse - { - var result = requestParams; - var isBizContentEmpty = !requestParams.ContainsKey(BIZ_CONTENT) || string.IsNullOrEmpty(requestParams[BIZ_CONTENT]); - if (isBizContentEmpty && request.GetBizModel() != null) - { - var bizModel = request.GetBizModel(); - var content = Serialize(bizModel); - result.Add(BIZ_CONTENT, content); - } - return result; - } - - /// - /// AopObject序列化 - /// - /// - /// - private string Serialize(AopObject obj) - { - JsonSerializerSettings jsetting = new JsonSerializerSettings(); - jsetting.NullValueHandling = NullValueHandling.Ignore; - return JsonConvert.SerializeObject(obj, Formatting.None, jsetting); - } - - #endregion - } +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using System.Web; +using Alipay.AopSdk.Core.Parser; +using Alipay.AopSdk.Core.Util; +using Newtonsoft.Json; + +namespace Alipay.AopSdk.Core +{ + /// + /// + /// AOP客户端。 + /// + public class DefaultAopClient : IAopClient + { + public const string APP_ID = "app_id"; + public const string FORMAT = "format"; + public const string METHOD = "method"; + public const string TIMESTAMP = "timestamp"; + public const string VERSION = "version"; + public const string SIGN_TYPE = "sign_type"; + public const string ACCESS_TOKEN = "auth_token"; + public const string SIGN = "sign"; + public const string TERMINAL_TYPE = "terminal_type"; + public const string TERMINAL_INFO = "terminal_info"; + public const string PROD_CODE = "prod_code"; + public const string NOTIFY_URL = "notify_url"; + public const string CHARSET = "charset"; + public const string ENCRYPT_TYPE = "encrypt_type"; + public const string BIZ_CONTENT = "biz_content"; + public const string APP_AUTH_TOKEN = "app_auth_token"; + public const string RETURN_URL = "return_url"; + private readonly string alipayPublicKey; + private string charset; + private readonly string encyptKey; + private readonly string encyptType = "AES"; + private string format; + private string httpmethod; + private readonly bool keyFromFile; + + public string notify_url; + private readonly string privateKeyPem; + public string return_url; + private readonly string serverUrl; + private readonly string signType = "RSA2"; + + private string version; + + private readonly WebUtils webUtils; + + public string Version + { + get => version != null ? version : "1.0"; + set => version = value; + } + + public string Format + { + get => format != null ? format : "json"; + set => format = value; + } + + public string AppId { get; set; } + + #region IAopClient Members + + public T PageExecute(IAopRequest request) where T : AopResponse + { + return PageExecute(request, null, "POST"); + } + + public async Task PageExecuteAsync(IAopRequest request) where T : AopResponse + { + return await PageExecuteAsync(request, null, "POST"); + } + #endregion + + #region IAopClient Members + public T PageExecute (IAopRequest request, string accessToken, string reqMethod) where T : AopResponse + { + return AsyncHelper.RunSync(async () => await PageExecuteAsync(request, accessToken, reqMethod)); + } + + public async Task PageExecuteAsync(IAopRequest request, string accessToken, string reqMethod) where T : AopResponse + { + if (string.IsNullOrEmpty(charset)) + charset = "utf-8"; + + string apiVersion = null; + + if (!string.IsNullOrEmpty(request.GetApiVersion())) + apiVersion = request.GetApiVersion(); + else + apiVersion = Version; + + var txtParams = new AopDictionary(request.GetParameters()); + + // 序列化BizModel + txtParams = SerializeBizModel(txtParams, request); + + // 添加协议级请求参数 + //AopDictionary txtParams = new AopDictionary(request.GetParameters()); + txtParams.Add(METHOD, request.GetApiName()); + txtParams.Add(VERSION, apiVersion); + txtParams.Add(APP_ID, AppId); + txtParams.Add(FORMAT, format); + txtParams.Add(TIMESTAMP, DateTime.Now); + txtParams.Add(ACCESS_TOKEN, accessToken); + txtParams.Add(SIGN_TYPE, signType); + txtParams.Add(TERMINAL_TYPE, request.GetTerminalType()); + txtParams.Add(TERMINAL_INFO, request.GetTerminalInfo()); + txtParams.Add(PROD_CODE, request.GetProdCode()); + txtParams.Add(NOTIFY_URL, request.GetNotifyUrl()); + txtParams.Add(CHARSET, charset); + txtParams.Add(RETURN_URL, request.GetReturnUrl()); + //字典排序 + IDictionary sortedTxtParams = new SortedDictionary(txtParams); + txtParams = new AopDictionary(sortedTxtParams); + // 排序返回字典类型添加签名参数 + + var signContent =AlipaySignature.GetSignContent(txtParams); + + var path ="Logs/"+DateTime.Now.ToString("yyyyMMdd"); + if (!Directory.Exists(path)) + { + Directory.CreateDirectory(path); + } + var file = path + "/alipay.log"; + File.AppendAllText(file, "pay body:" + signContent); + + txtParams.Add(SIGN, AopUtils.SignAopRequest(sortedTxtParams, privateKeyPem, charset, keyFromFile, signType)); + File.AppendAllText(file, "pay SIGN:" + txtParams[SIGN]); + // 是否需要上传文件 + string body; + + if (request is IAopUploadRequest) + { + var uRequest = (IAopUploadRequest) request; + var fileParams = AopUtils.CleanupDictionary(uRequest.GetFileParameters()); + body = await webUtils.DoPostAsync(serverUrl + "?" + CHARSET + "=" + charset, txtParams, fileParams, charset); + } + else + { + if (reqMethod.Equals("GET")) + { + //直接调用DoGet方法请求 + //body=webUtils .DoGet (this.serverUrl ,txtParams ,this.charset); + //拼接get请求的url + var tmpUrl = serverUrl; + if (txtParams != null && txtParams.Count > 0) + if (tmpUrl.Contains("?")) + tmpUrl = tmpUrl + "&" + WebUtils.BuildQuery(txtParams, charset); + else + tmpUrl = tmpUrl + "?" + WebUtils.BuildQuery(txtParams, charset); + body = tmpUrl; + } + else + { + //直接调用DoPost方法请求 + // body = webUtils.DoPost(this.serverUrl, txtParams, this.charset); + //输出post表单 + body = BuildHtmlRequest(txtParams, reqMethod, reqMethod); + } + } + + T rsp = null; + IAopParser parser = null; + if ("xml".Equals(format)) + { + parser = new AopXmlParser(); + rsp = parser.Parse(body, charset); + } + else + { + parser = new AopJsonParser(); + rsp = parser.Parse(body, charset); + } + + //验签 + // CheckResponseSign(request, rsp, parser, this.alipayPublicKey, this.charset); + return rsp; + } + + #endregion + + #region SDK Execute + + public T SdkExecute(IAopRequest request) where T : AopResponse + { + // 构造请求参数 + var requestParams = buildRequestParams(request, null, null); + + // 字典排序 + IDictionary sortedParams = new SortedDictionary(requestParams); + var sortedAopDic = new AopDictionary(sortedParams); + + // 参数签名 + var charset = string.IsNullOrEmpty(this.charset) ? "utf-8" : this.charset; + var signResult = AopUtils.SignAopRequest(sortedAopDic, privateKeyPem, charset, keyFromFile, signType); + + // 添加签名结果参数 + sortedAopDic.Add(SIGN, signResult); + + // 参数拼接 + var signedResult = WebUtils.BuildQuery(sortedAopDic, charset); + + // 构造结果 + var rsp = (T) Activator.CreateInstance(typeof(T)); + rsp.Body = signedResult; + return rsp; + } + + #endregion + + #region IAopClient Members + + public string BuildHtmlRequest(IDictionary sParaTemp, string strMethod, string strButtonValue) + { + //待请求参数数组 + IDictionary dicPara = new Dictionary(); + dicPara = sParaTemp; + + var sbHtml = new StringBuilder(); + //sbHtml.Append(""); + + sbHtml.Append("
"); + ; + foreach (var temp in dicPara) + sbHtml.Append(""); + + //submit按钮控件请不要含有name属性 + sbHtml.Append("
"); + // sbHtml.Append(""); + + //表单实现自动提交 + sbHtml.Append(""); + + return sbHtml.ToString(); + } + + #endregion + + #region Common Method + + private AopDictionary buildRequestParams(IAopRequest request, string accessToken, string appAuthToken) + where T : AopResponse + { + // 默认参数 + var oriParams = new AopDictionary(request.GetParameters()); + + // 序列化BizModel + var result = SerializeBizModel(oriParams, request); + + // 获取参数 + var charset = string.IsNullOrEmpty(this.charset) ? "utf-8" : this.charset; + var apiVersion = string.IsNullOrEmpty(request.GetApiVersion()) ? Version : request.GetApiVersion(); + + // 添加协议级请求参数,为空的参数后面会自动过滤,这里不做处理。 + result.Add(METHOD, request.GetApiName()); + result.Add(VERSION, apiVersion); + result.Add(APP_ID, AppId); + result.Add(FORMAT, format); + result.Add(TIMESTAMP, DateTime.Now); + result.Add(ACCESS_TOKEN, accessToken); + result.Add(SIGN_TYPE, signType); + result.Add(TERMINAL_TYPE, request.GetTerminalType()); + result.Add(TERMINAL_INFO, request.GetTerminalInfo()); + result.Add(PROD_CODE, request.GetProdCode()); + result.Add(NOTIFY_URL, request.GetNotifyUrl()); + result.Add(CHARSET, charset); + result.Add(RETURN_URL, request.GetReturnUrl()); + result.Add(APP_AUTH_TOKEN, appAuthToken); + + if (request.GetNeedEncrypt()) + { + if (string.IsNullOrEmpty(result[BIZ_CONTENT])) + throw new AopException("api request Fail ! The reason: encrypt request is not supported!"); + + if (string.IsNullOrEmpty(encyptKey) || string.IsNullOrEmpty(encyptType)) + throw new AopException("encryptType or encryptKey must not null!"); + + if (!"AES".Equals(encyptType)) + throw new AopException("api only support Aes!"); + + var encryptContent = AopUtils.AesEncrypt(encyptKey, result[BIZ_CONTENT], this.charset); + result.Remove(BIZ_CONTENT); + result.Add(BIZ_CONTENT, encryptContent); + result.Add(ENCRYPT_TYPE, encyptType); + } + + return result; + } + + #endregion + + #region DefaultAopClient Constructors + + public DefaultAopClient(string serverUrl, string appId, string privateKeyPem) + { + AppId = appId; + this.privateKeyPem = privateKeyPem; + this.serverUrl = serverUrl; + webUtils = new WebUtils(serverUrl); + } + + public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, bool keyFromFile) + { + AppId = appId; + this.privateKeyPem = privateKeyPem; + this.serverUrl = serverUrl; + this.keyFromFile = keyFromFile; + webUtils = new WebUtils(serverUrl); + } + + public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, string format) + { + AppId = appId; + this.privateKeyPem = privateKeyPem; + this.serverUrl = serverUrl; + this.format = format; + webUtils = new WebUtils(serverUrl); + } + + public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, string format, string charset) + : this(serverUrl, appId, privateKeyPem, format) + { + this.charset = charset; + } + + public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, string format, string version, + string signType) + : this(serverUrl, appId, privateKeyPem) + { + this.format = format; + this.version = version; + this.signType = signType; + } + + public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, string format, string version, + string signType, string alipayPulicKey) + : this(serverUrl, appId, privateKeyPem, format, version, signType) + { + alipayPublicKey = alipayPulicKey; + } + + public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, string format, string version, + string signType, string alipayPulicKey, string charset) + : this(serverUrl, appId, privateKeyPem, format, version, signType, alipayPulicKey) + { + this.charset = charset; + } + + // + public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, string format, string version, + string signType, string alipayPulicKey, string charset, bool keyFromFile) + : this(serverUrl, appId, privateKeyPem, format, version, signType, alipayPulicKey) + { + this.keyFromFile = keyFromFile; + this.charset = charset; + } + + public DefaultAopClient(string serverUrl, string appId, string privateKeyPem, string format, string version, + string signType, string alipayPulicKey, string charset, string encyptKey) + : this(serverUrl, appId, privateKeyPem, format, version, signType, alipayPulicKey, charset) + { + this.encyptKey = encyptKey; + encyptType = "AES"; + } + + #endregion + + #region IAopClient Members + + public T Execute(IAopRequest request) where T : AopResponse + { + return Execute(request, null); + } + + public T Execute(IAopRequest request, string accessToken) where T : AopResponse + { + return Execute(request, accessToken, null); + } + + public async Task ExecuteAsync(IAopRequest request) where T : AopResponse + { + return await ExecuteAsync(request, null); + } + + public async Task ExecuteAsync(IAopRequest request, string accessToken) where T : AopResponse + { + return await ExecuteAsync(request, accessToken, null); + } + + #endregion + + #region IAopClient Members + + public T Execute(IAopRequest request, string accessToken, string appAuthToken) where T : AopResponse + { + return AsyncHelper.RunSync(async () => await ExecuteAsync(request, accessToken, appAuthToken)); + } + + public async Task ExecuteAsync(IAopRequest request, string accessToken, string appAuthToken) where T : AopResponse + { + if (string.IsNullOrEmpty(charset)) + charset = "utf-8"; + + string apiVersion = null; + + if (!string.IsNullOrEmpty(request.GetApiVersion())) + apiVersion = request.GetApiVersion(); + else + apiVersion = Version; + + // 添加协议级请求参数 + var txtParams = new AopDictionary(request.GetParameters()); + + // 序列化BizModel + txtParams = SerializeBizModel(txtParams, request); + + txtParams.Add(METHOD, request.GetApiName()); + txtParams.Add(VERSION, apiVersion); + txtParams.Add(APP_ID, AppId); + txtParams.Add(FORMAT, format); + txtParams.Add(TIMESTAMP, DateTime.Now); + txtParams.Add(ACCESS_TOKEN, accessToken); + txtParams.Add(SIGN_TYPE, signType); + txtParams.Add(TERMINAL_TYPE, request.GetTerminalType()); + txtParams.Add(TERMINAL_INFO, request.GetTerminalInfo()); + txtParams.Add(PROD_CODE, request.GetProdCode()); + txtParams.Add(CHARSET, charset); + + + if (!string.IsNullOrEmpty(request.GetNotifyUrl())) + txtParams.Add(NOTIFY_URL, request.GetNotifyUrl()); + + if (!string.IsNullOrEmpty(appAuthToken)) + txtParams.Add(APP_AUTH_TOKEN, appAuthToken); + + + if (request.GetNeedEncrypt()) + { + if (string.IsNullOrEmpty(txtParams[BIZ_CONTENT])) + throw new AopException("api request Fail ! The reason: encrypt request is not supported!"); + + if (string.IsNullOrEmpty(encyptKey) || string.IsNullOrEmpty(encyptType)) + throw new AopException("encryptType or encryptKey must not null!"); + + if (!"AES".Equals(encyptType)) + throw new AopException("api only support Aes!"); + + var encryptContent = AopUtils.AesEncrypt(encyptKey, txtParams[BIZ_CONTENT], charset); + txtParams.Remove(BIZ_CONTENT); + txtParams.Add(BIZ_CONTENT, encryptContent); + txtParams.Add(ENCRYPT_TYPE, encyptType); + } + + // 添加签名参数 + txtParams.Add(SIGN, AopUtils.SignAopRequest(txtParams, privateKeyPem, charset, keyFromFile, signType)); + + + // 是否需要上传文件 + string body; + + + if (request is IAopUploadRequest) + { + var uRequest = (IAopUploadRequest)request; + var fileParams = AopUtils.CleanupDictionary(uRequest.GetFileParameters()); + body = await webUtils.DoPostAsync(serverUrl + "?" + CHARSET + "=" + charset, txtParams, fileParams, charset); + } + else + { + body = await webUtils.DoPostAsync(serverUrl + "?" + CHARSET + "=" + charset, txtParams, charset); + } + + T rsp = null; + IAopParser parser = null; + if ("xml".Equals(format)) + { + parser = new AopXmlParser(); + rsp = parser.Parse(body, charset); + } + else + { + parser = new AopJsonParser(); + rsp = parser.Parse(body, charset); + } + + var item = parseRespItem(request, body, parser, encyptKey, encyptType, charset); + rsp = parser.Parse(item.realContent, charset); + + CheckResponseSign(request, item.respContent, rsp.IsError, parser, alipayPublicKey, charset, signType, keyFromFile); + + return rsp; + } + + private static ResponseParseItem parseRespItem(IAopRequest request, string respBody, IAopParser parser, + string encryptKey, string encryptType, string charset) where T : AopResponse + { + string realContent = null; + + if (request.GetNeedEncrypt()) + realContent = parser.EncryptSourceData(request, respBody, encryptType, encryptKey, charset); + else + realContent = respBody; + + var item = new ResponseParseItem(); + item.realContent = realContent; + item.respContent = respBody; + + return item; + } + + public static void CheckResponseSign(IAopRequest request, string responseBody, bool isError, + IAopParser parser, string alipayPublicKey, string charset, string signType) where T : AopResponse + { + if (string.IsNullOrEmpty(alipayPublicKey) || string.IsNullOrEmpty(charset)) + return; + + var signItem = parser.GetSignItem(request, responseBody); + if (signItem == null) + throw new AopException("sign check fail: Body is Empty!"); + + if (!isError || + isError && !string.IsNullOrEmpty(signItem.Sign)) + { + var rsaCheckContent = + AlipaySignature.RSACheckContent(signItem.SignSourceDate, signItem.Sign, alipayPublicKey, charset, signType); + if (!rsaCheckContent) + if (!string.IsNullOrEmpty(signItem.SignSourceDate) && signItem.SignSourceDate.Contains("\\/")) + { + var srouceData = signItem.SignSourceDate.Replace("\\/", "/"); + var jsonCheck = AlipaySignature.RSACheckContent(srouceData, signItem.Sign, alipayPublicKey, charset, signType); + if (!jsonCheck) + throw new AopException( + "sign check fail: check Sign and Data Fail JSON also"); + } + else + { + throw new AopException( + "sign check fail: check Sign and Data Fail!"); + } + } + } + + public static void CheckResponseSign(IAopRequest request, string responseBody, bool isError, + IAopParser parser, string alipayPublicKey, string charset, string signType, bool keyFromFile) + where T : AopResponse + { + if (string.IsNullOrEmpty(alipayPublicKey) || string.IsNullOrEmpty(charset)) + return; + + var signItem = parser.GetSignItem(request, responseBody); + if (signItem == null) + throw new AopException("sign check fail: Body is Empty!"); + + if (!isError || + isError && !string.IsNullOrEmpty(signItem.Sign)) + { + var rsaCheckContent = AlipaySignature.RSACheckContent(signItem.SignSourceDate, signItem.Sign, alipayPublicKey, + charset, signType, keyFromFile); + if (!rsaCheckContent) + if (!string.IsNullOrEmpty(signItem.SignSourceDate) && signItem.SignSourceDate.Contains("\\/")) + { + var srouceData = signItem.SignSourceDate.Replace("\\/", "/"); + var jsonCheck = + AlipaySignature.RSACheckContent(srouceData, signItem.Sign, alipayPublicKey, charset, signType, keyFromFile); + if (!jsonCheck) + throw new AopException( + "sign check fail: check Sign and Data Fail JSON also"); + } + else + { + throw new AopException( + "sign check fail: check Sign and Data Fail!"); + } + } + } + + #endregion + + #region IAopClient Members + + public Dictionary FilterPara(SortedDictionary dicArrayPre) + { + var dicArray = new Dictionary(); + foreach (var temp in dicArrayPre) + if (temp.Key.ToLower() != "sign" && temp.Key.ToLower() != "sign_type" && temp.Value != "" && temp.Value != null) + dicArray.Add(temp.Key, temp.Value); + + return dicArray; + } + + public static string CreateLinkStringUrlencode(Dictionary dicArray, Encoding code) + { + var prestr = new StringBuilder(); + foreach (var temp in dicArray) + prestr.Append(temp.Key + "=" + HttpUtility.UrlEncode(temp.Value, code) + "&"); + + //去掉最後一個&字符 + var nLen = prestr.Length; + prestr.Remove(nLen - 1, 1); + + return prestr.ToString(); + } + + #endregion + + #region Model Serialize + + /// + /// + /// + /// + /// + /// + private AopDictionary SerializeBizModel(AopDictionary requestParams, IAopRequest request) where T : AopResponse + { + var result = requestParams; + var isBizContentEmpty = !requestParams.ContainsKey(BIZ_CONTENT) || string.IsNullOrEmpty(requestParams[BIZ_CONTENT]); + if (isBizContentEmpty && request.GetBizModel() != null) + { + var bizModel = request.GetBizModel(); + var content = Serialize(bizModel); + result.Add(BIZ_CONTENT, content); + } + return result; + } + + /// + /// AopObject序列化 + /// + /// + /// + private string Serialize(AopObject obj) + { + JsonSerializerSettings jsetting = new JsonSerializerSettings(); + jsetting.NullValueHandling = NullValueHandling.Ignore; + return JsonConvert.SerializeObject(obj, Formatting.None, jsetting); + } + + #endregion + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/Alipay.AopSdk.Core/Util/AlipaySignature.cs b/Infrastructure/ServiceClient/Alipay.AopSdk.Core/Util/AlipaySignature.cs index 4aac54e..a95d2e4 100644 --- a/Infrastructure/ServiceClient/Alipay.AopSdk.Core/Util/AlipaySignature.cs +++ b/Infrastructure/ServiceClient/Alipay.AopSdk.Core/Util/AlipaySignature.cs @@ -1,807 +1,807 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Security.Cryptography; -using System.Text; - -namespace Alipay.AopSdk.Core.Util -{ - public class AlipaySignature - { - /** 默认编码字符集 */ - private static readonly string DEFAULT_CHARSET = "utf-8"; - - public static string GetSignContent(IDictionary parameters) - { - // 第一步:把字典按Key的字母顺序排序 - IDictionary sortedParams = new SortedDictionary(parameters); - var dem = sortedParams.GetEnumerator(); - - // 第二步:把所有参数名和参数值串在一起 - var query = new StringBuilder(""); - while (dem.MoveNext()) - { - var key = dem.Current.Key; - var value = dem.Current.Value; - if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value)) - query.Append(key).Append("=").Append(value).Append("&"); - } - var content = query.ToString().Substring(0, query.Length - 1); - - return content; - } - - public static string RSASign(IDictionary parameters, string privateKeyPem, string charset, - string signType) - { - var signContent = GetSignContent(parameters); - - return RSASignCharSet(signContent, privateKeyPem, charset, signType); - } - - public static string RSASign(string data, string privateKeyPem, string charset, string signType) - { - return RSASignCharSet(data, privateKeyPem, charset, signType); - } - - ///* - public static string RSASign(IDictionary parameters, string privateKeyPem, string charset, - bool keyFromFile, string signType) - { - var signContent = GetSignContent(parameters); - - return RSASignCharSet(signContent, privateKeyPem, charset, keyFromFile, signType); - } - - public static string RSASign(string data, string privateKeyPem, string charset, string signType, bool keyFromFile) - { - return RSASignCharSet(data, privateKeyPem, charset, keyFromFile, signType); - } - - //*/ - public static string RSASignCharSet(string data, string privateKeyPem, string charset, string signType) - { - RSA rsaCsp = LoadCertificateFile(privateKeyPem, signType); - byte[] dataBytes = null; - if (string.IsNullOrEmpty(charset)) - dataBytes = Encoding.UTF8.GetBytes(data); - else - dataBytes = Encoding.GetEncoding(charset).GetBytes(data); - - var signatureBytes = rsaCsp.SignData(dataBytes, "RSA2".Equals(signType) ? HashAlgorithmName.SHA256 : HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); - - return Convert.ToBase64String(signatureBytes); - } - - - public static string RSASignCharSet(string data, string privateKeyPem, string charset, bool keyFromFile, - string signType) - { - byte[] signatureBytes = null; - try - { - RSA rsaCsp = null; - rsaCsp = keyFromFile ? LoadCertificateFile(privateKeyPem, signType) : LoadCertificateString(privateKeyPem, signType); - - byte[] dataBytes = null; - if (string.IsNullOrEmpty(charset)) - dataBytes = Encoding.UTF8.GetBytes(data); - else - dataBytes = Encoding.GetEncoding(charset).GetBytes(data); - if (null == rsaCsp) - throw new AopException("您使用的私钥格式错误,请检查RSA私钥配置" + ",charset = " + charset); - signatureBytes = rsaCsp.SignData(dataBytes, "RSA2".Equals(signType) ? HashAlgorithmName.SHA256 : HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); - } - catch (Exception ex) - { - throw new AopException($"您使用的私钥格式错误,请检查RSA私钥配置,charset = {charset},异常信息:{ex.Message}", ex); - } - return Convert.ToBase64String(signatureBytes); - } - - - public static bool RSACheckV1(IDictionary parameters, string publicKeyPem, string charset) - { - var sign = parameters["sign"]; - - parameters.Remove("sign"); - parameters.Remove("sign_type"); - var signContent = GetSignContent(parameters); - return RSACheckContent(signContent, sign, publicKeyPem, charset, "RSA"); - } - - public static bool RSACheckV1(IDictionary parameters, string publicKeyPem) - { - var sign = parameters["sign"]; - - parameters.Remove("sign"); - parameters.Remove("sign_type"); - var signContent = GetSignContent(parameters); - - return RSACheckContent(signContent, sign, publicKeyPem, DEFAULT_CHARSET, "RSA"); - } - - public static bool RSA2Check(IDictionary parameters, string publicKeyPem) - { - var sign = parameters["sign"]; - - parameters.Remove("sign"); - parameters.Remove("sign_type"); - var signContent = GetSignContent(parameters); - - return RSACheckContent(signContent, sign, publicKeyPem, DEFAULT_CHARSET, "RSA2"); - } - - public static bool RSACheckV1(IDictionary parameters, string publicKeyPem, string charset, - string signType, bool keyFromFile) - { - var sign = parameters["sign"]; - - parameters.Remove("sign"); - parameters.Remove("sign_type"); - var signContent = GetSignContent(parameters); - return RSACheckContent(signContent, sign, publicKeyPem, charset, signType, keyFromFile); - } - - public static bool RSACheckV2(IDictionary parameters, string publicKeyPem, string charset) - { - var sign = parameters["sign"]; - - parameters.Remove("sign"); - parameters.Remove("sign_type"); - var signContent = GetSignContent(parameters); - - return RSACheckContent(signContent, sign, publicKeyPem, charset, "RSA"); - } - - public static bool RSACheckV2(IDictionary parameters, string publicKeyPem, string charset, - string signType, bool keyFromFile) - { - var sign = parameters["sign"]; - parameters.Remove("sign"); - parameters.Remove("sign_type"); - var signContent = GetSignContent(parameters); - - return RSACheckContent(signContent, sign, publicKeyPem, charset, signType, keyFromFile); - } - - public static RSA CreateRsaProviderFromPublicKey(string publicKeyString,string signType) - { - // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" - byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 }; - byte[] seq = new byte[15]; - - var x509Key = Convert.FromBase64String(publicKeyString); - - // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------ - using (MemoryStream mem = new MemoryStream(x509Key)) - { - using (BinaryReader binr = new BinaryReader(mem)) //wrap Memory Stream with BinaryReader for easy reading - { - byte bt = 0; - ushort twobytes = 0; - - twobytes = binr.ReadUInt16(); - if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) - binr.ReadByte(); //advance 1 byte - else if (twobytes == 0x8230) - binr.ReadInt16(); //advance 2 bytes - else - return null; - - seq = binr.ReadBytes(15); //read the Sequence OID - if (!CompareBytearrays(seq, seqOid)) //make sure Sequence for OID is correct - return null; - - twobytes = binr.ReadUInt16(); - if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81) - binr.ReadByte(); //advance 1 byte - else if (twobytes == 0x8203) - binr.ReadInt16(); //advance 2 bytes - else - return null; - - bt = binr.ReadByte(); - if (bt != 0x00) //expect null byte next - return null; - - twobytes = binr.ReadUInt16(); - if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) - binr.ReadByte(); //advance 1 byte - else if (twobytes == 0x8230) - binr.ReadInt16(); //advance 2 bytes - else - return null; - - twobytes = binr.ReadUInt16(); - byte lowbyte = 0x00; - byte highbyte = 0x00; - - if (twobytes == 0x8102) //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 - else if (twobytes == 0x8202) - { - highbyte = binr.ReadByte(); //advance 2 bytes - lowbyte = binr.ReadByte(); - } - else - return null; - byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order - int modsize = BitConverter.ToInt32(modint, 0); - - int firstbyte = binr.PeekChar(); - if (firstbyte == 0x00) - { //if first byte (highest order) of modulus is zero, don't include it - binr.ReadByte(); //skip this null byte - modsize -= 1; //reduce modulus buffer size by 1 - } - - byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes - - if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data - return null; - int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values) - byte[] exponent = binr.ReadBytes(expbytes); - - // ------- create RSACryptoServiceProvider instance and initialize with public key ----- - var rsa = RSA.Create(); - rsa.KeySize = signType == "RSA" ? 1024 : 2048; - RSAParameters rsaKeyInfo = new RSAParameters(); - rsaKeyInfo.Modulus = modulus; - rsaKeyInfo.Exponent = exponent; - rsa.ImportParameters(rsaKeyInfo); - - return rsa; - } - - } - } - - private static bool CompareBytearrays(byte[] a, byte[] b) - { - if (a.Length != b.Length) - return false; - int i = 0; - foreach (byte c in a) - { - if (c != b[i]) - return false; - i++; - } - return true; - } - - public static bool RSACheckContent(string signContent, string sign, string publicKeyPem, string charset, - string signType) - { - try - { - if (string.IsNullOrEmpty(charset)) - charset = DEFAULT_CHARSET; - - var sPublicKeyPem = File.ReadAllText(publicKeyPem); - - var rsa = CreateRsaProviderFromPublicKey(sPublicKeyPem, signType); - - if ("RSA2".Equals(signType)) - { - - - var bVerifyResultOriginal = rsa.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), - Convert.FromBase64String(sign),HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); - return bVerifyResultOriginal; - } - else - { - - var bVerifyResultOriginal = rsa.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), - Convert.FromBase64String(sign), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); - return bVerifyResultOriginal; - } - } - catch - { - return false; - } - } - - public static bool RSACheckContent(string signContent, string sign, string publicKeyPem, string charset, - string signType, bool keyFromFile) - { - try - { - if (string.IsNullOrEmpty(charset)) - charset = DEFAULT_CHARSET; - - string sPublicKeyPem= publicKeyPem; - - if (keyFromFile) - { - sPublicKeyPem = File.ReadAllText(publicKeyPem); - } - var rsa = CreateRsaProviderFromPublicKey(sPublicKeyPem, signType); - - if ("RSA2".Equals(signType)) - { - - - var bVerifyResultOriginal = rsa.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), - Convert.FromBase64String(sign), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); - return bVerifyResultOriginal; - } - else - { - var bVerifyResultOriginal = rsa.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), - Convert.FromBase64String(sign), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); - return bVerifyResultOriginal; - } - } - catch - { - return false; - } - } - - public static bool RSACheckContent(string signContent, string sign, string publicKeyPem, string charset, - bool keyFromFile) - { - try - { - string sPublicKeyPem= publicKeyPem; - if (keyFromFile) - { - sPublicKeyPem = File.ReadAllText(publicKeyPem); - } - var rsa = CreateRsaProviderFromPublicKey(sPublicKeyPem, "RSA"); - var sha1 = new SHA1CryptoServiceProvider(); - if (string.IsNullOrEmpty(charset)) - charset = DEFAULT_CHARSET; - var bVerifyResultOriginal = rsa.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), - Convert.FromBase64String(sign),HashAlgorithmName.SHA1,RSASignaturePadding.Pkcs1); - return bVerifyResultOriginal; - } - catch (Exception ex) - { - var s = ex.Message; - return false; - } - } - - public static string CheckSignAndDecrypt(IDictionary parameters, string alipayPublicKey, - string cusPrivateKey, bool isCheckSign, - bool isDecrypt) - { - var charset = parameters["charset"]; - var bizContent = parameters["biz_content"]; - if (isCheckSign) - if (!RSACheckV2(parameters, alipayPublicKey, charset)) - throw new AopException("rsaCheck failure:rsaParams=" + parameters); - - if (isDecrypt) - return RSADecrypt(bizContent, cusPrivateKey, charset, "RSA"); - - return bizContent; - } - - public static string CheckSignAndDecrypt(IDictionary parameters, string alipayPublicKey, - string cusPrivateKey, bool isCheckSign, - bool isDecrypt, string signType, bool keyFromFile) - { - var charset = parameters["charset"]; - var bizContent = parameters["biz_content"]; - if (isCheckSign) - if (!RSACheckV2(parameters, alipayPublicKey, charset, signType, keyFromFile)) - throw new AopException("rsaCheck failure:rsaParams=" + parameters); - - if (isDecrypt) - return RSADecrypt(bizContent, cusPrivateKey, charset, signType, keyFromFile); - - return bizContent; - } - - public static string encryptAndSign(string bizContent, string alipayPublicKey, - string cusPrivateKey, string charset, bool isEncrypt, - bool isSign, string signType, bool keyFromFile) - { - var sb = new StringBuilder(); - if (string.IsNullOrEmpty(charset)) - charset = DEFAULT_CHARSET; - sb.Append(""); - if (isEncrypt) - { -// 加密 - sb.Append(""); - var encrypted = RSAEncrypt(bizContent, alipayPublicKey, charset, keyFromFile); - sb.Append("" + encrypted + ""); - sb.Append("" + signType + ""); - if (isSign) - { - var sign = RSASign(encrypted, cusPrivateKey, charset, signType, keyFromFile); - sb.Append("" + sign + ""); - sb.Append("" + signType + ""); - } - sb.Append(""); - } - else if (isSign) - { -// 不加密,但需要签名 - sb.Append(""); - sb.Append("" + bizContent + ""); - var sign = RSASign(bizContent, cusPrivateKey, charset, signType, keyFromFile); - sb.Append("" + sign + ""); - sb.Append("" + signType + ""); - sb.Append(""); - } - else - { -// 不加密,不加签 - sb.Append(bizContent); - } - return sb.ToString(); - } - - public static string encryptAndSign(string bizContent, string alipayPublicKey, - string cusPrivateKey, string charset, bool isEncrypt, - bool isSign) - { - var sb = new StringBuilder(); - if (string.IsNullOrEmpty(charset)) - charset = DEFAULT_CHARSET; - sb.Append(""); - if (isEncrypt) - { -// 加密 - sb.Append(""); - var encrypted = RSAEncrypt(bizContent, alipayPublicKey, charset); - sb.Append("" + encrypted + ""); - sb.Append("RSA"); - if (isSign) - { - var sign = RSASign(encrypted, cusPrivateKey, charset, "RSA"); - sb.Append("" + sign + ""); - sb.Append("RSA"); - } - sb.Append(""); - } - else if (isSign) - { -// 不加密,但需要签名 - sb.Append(""); - sb.Append("" + bizContent + ""); - var sign = RSASign(bizContent, cusPrivateKey, charset, "RSA"); - sb.Append("" + sign + ""); - sb.Append("RSA"); - sb.Append(""); - } - else - { -// 不加密,不加签 - sb.Append(bizContent); - } - return sb.ToString(); - } - - public static string RSAEncrypt(string content, string publicKeyPem, string charset) - { - try - { - var sPublicKeyPEM = File.ReadAllText(publicKeyPem); - var rsa = CreateRsaProviderFromPublicKey(sPublicKeyPEM, "RSA"); - if (string.IsNullOrEmpty(charset)) - charset = DEFAULT_CHARSET; - var data = Encoding.GetEncoding(charset).GetBytes(content); - var maxBlockSize = rsa.KeySize / 8 - 11; //加密块最大长度限制 - if (data.Length <= maxBlockSize) - { - var cipherbytes = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1); - return Convert.ToBase64String(cipherbytes); - } - var plaiStream = new MemoryStream(data); - var crypStream = new MemoryStream(); - var buffer = new byte[maxBlockSize]; - var blockSize = plaiStream.Read(buffer, 0, maxBlockSize); - while (blockSize > 0) - { - var toEncrypt = new byte[blockSize]; - Array.Copy(buffer, 0, toEncrypt, 0, blockSize); - var cryptograph = rsa.Encrypt(toEncrypt, RSAEncryptionPadding.Pkcs1); - crypStream.Write(cryptograph, 0, cryptograph.Length); - blockSize = plaiStream.Read(buffer, 0, maxBlockSize); - } - - return Convert.ToBase64String(crypStream.ToArray(), Base64FormattingOptions.None); - } - catch (Exception ex) - { - throw new AopException("EncryptContent = " + content + ",charset = " + charset, ex); - } - } - - public static string RSAEncrypt(string content, string publicKeyPem, string charset, bool keyFromFile) - { - try - { - string sPublicKeyPEM= publicKeyPem; - if (keyFromFile) - { - sPublicKeyPEM = File.ReadAllText(publicKeyPem); - } - var rsa = CreateRsaProviderFromPublicKey(publicKeyPem, "RSA"); - if (string.IsNullOrEmpty(charset)) - charset = DEFAULT_CHARSET; - var data = Encoding.GetEncoding(charset).GetBytes(content); - var maxBlockSize = rsa.KeySize / 8 - 11; //加密块最大长度限制 - if (data.Length <= maxBlockSize) - { - var cipherbytes = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1); - return Convert.ToBase64String(cipherbytes); - } - var plaiStream = new MemoryStream(data); - var crypStream = new MemoryStream(); - var buffer = new byte[maxBlockSize]; - var blockSize = plaiStream.Read(buffer, 0, maxBlockSize); - while (blockSize > 0) - { - var toEncrypt = new byte[blockSize]; - Array.Copy(buffer, 0, toEncrypt, 0, blockSize); - var cryptograph = rsa.Encrypt(toEncrypt, RSAEncryptionPadding.Pkcs1); - crypStream.Write(cryptograph, 0, cryptograph.Length); - blockSize = plaiStream.Read(buffer, 0, maxBlockSize); - } - - return Convert.ToBase64String(crypStream.ToArray(), Base64FormattingOptions.None); - } - catch (Exception ex) - { - throw new AopException("EncryptContent = " + content + ",charset = " + charset, ex); - } - } - - public static string RSADecrypt(string content, string privateKeyPem, string charset, string signType) - { - try - { - var rsaCsp = LoadCertificateFile(privateKeyPem, signType); - if (string.IsNullOrEmpty(charset)) - charset = DEFAULT_CHARSET; - var data = Convert.FromBase64String(content); - var maxBlockSize = rsaCsp.KeySize / 8; //解密块最大长度限制 - if (data.Length <= maxBlockSize) - { - var cipherbytes = rsaCsp.Decrypt(data, RSAEncryptionPadding.Pkcs1); - return Encoding.GetEncoding(charset).GetString(cipherbytes); - } - var crypStream = new MemoryStream(data); - var plaiStream = new MemoryStream(); - var buffer = new byte[maxBlockSize]; - var blockSize = crypStream.Read(buffer, 0, maxBlockSize); - while (blockSize > 0) - { - var toDecrypt = new byte[blockSize]; - Array.Copy(buffer, 0, toDecrypt, 0, blockSize); - var cryptograph = rsaCsp.Decrypt(toDecrypt, RSAEncryptionPadding.Pkcs1); - plaiStream.Write(cryptograph, 0, cryptograph.Length); - blockSize = crypStream.Read(buffer, 0, maxBlockSize); - } - - return Encoding.GetEncoding(charset).GetString(plaiStream.ToArray()); - } - catch (Exception ex) - { - throw new AopException("DecryptContent = " + content + ",charset = " + charset, ex); - } - } - - public static string RSADecrypt(string content, string privateKeyPem, string charset, string signType, - bool keyFromFile) - { - try - { - RSA rsaCsp = null; - if (keyFromFile) - rsaCsp = LoadCertificateFile(privateKeyPem, signType); - else - rsaCsp = LoadCertificateString(privateKeyPem, signType); - if (string.IsNullOrEmpty(charset)) - charset = DEFAULT_CHARSET; - var data = Convert.FromBase64String(content); - var maxBlockSize = rsaCsp.KeySize / 8; //解密块最大长度限制 - if (data.Length <= maxBlockSize) - { - var cipherbytes = rsaCsp.Decrypt(data, RSAEncryptionPadding.Pkcs1); - return Encoding.GetEncoding(charset).GetString(cipherbytes); - } - var crypStream = new MemoryStream(data); - var plaiStream = new MemoryStream(); - var buffer = new byte[maxBlockSize]; - var blockSize = crypStream.Read(buffer, 0, maxBlockSize); - while (blockSize > 0) - { - var toDecrypt = new byte[blockSize]; - Array.Copy(buffer, 0, toDecrypt, 0, blockSize); - var cryptograph = rsaCsp.Decrypt(toDecrypt, RSAEncryptionPadding.Pkcs1); - plaiStream.Write(cryptograph, 0, cryptograph.Length); - blockSize = crypStream.Read(buffer, 0, maxBlockSize); - } - - return Encoding.GetEncoding(charset).GetString(plaiStream.ToArray()); - } - catch (Exception ex) - { - throw new AopException("DecryptContent = " + content + ",charset = " + charset, ex); - } - } - - private static byte[] GetPem(string type, byte[] data) - { - var pem = Encoding.UTF8.GetString(data); - var header = string.Format("-----BEGIN {0}-----\\n", type); - var footer = string.Format("-----END {0}-----", type); - var start = pem.IndexOf(header) + header.Length; - var end = pem.IndexOf(footer, start); - var base64 = pem.Substring(start, end - start); - - return Convert.FromBase64String(base64); - } - - private static RSA LoadCertificateFile(string filename, string signType) - { - using (var fs = File.OpenRead(filename)) - { - var data = new byte[fs.Length]; - byte[] res = null; - fs.Read(data, 0, data.Length); - if (data[0] != 0x30) - res = GetPem("RSA PRIVATE KEY", data); - try - { - var rsa = DecodeRSAPrivateKey(res, signType); - return rsa; - } - catch (Exception ex) - { - } - return null; - } - } - - public static RSA LoadCertificateString(string strKey, string signType) - { - byte[] data = null; - //读取带 - //ata = Encoding.Default.GetBytes(strKey); - data = Convert.FromBase64String(strKey); - //data = GetPem("RSA PRIVATE KEY", data); - try - { - var rsa = DecodeRSAPrivateKey(data, signType); - return rsa; - } - catch (Exception ex) - { - throw new AopException("Alipay.AopSdk.Core.Util.AlipaySignature LoadCertificateString DecodeRSAPrivateKey Error", ex); - } - return null; - } - - private static RSA DecodeRSAPrivateKey(byte[] privkey, string signType) - { - byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; - - // --------- Set up stream to decode the asn.1 encoded RSA private key ------ - var mem = new MemoryStream(privkey); - var binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading - byte bt = 0; - ushort twobytes = 0; - var elems = 0; - try - { - twobytes = binr.ReadUInt16(); - if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) - binr.ReadByte(); //advance 1 byte - else if (twobytes == 0x8230) - binr.ReadInt16(); //advance 2 bytes - else - return null; - - twobytes = binr.ReadUInt16(); - if (twobytes != 0x0102) //version number - return null; - bt = binr.ReadByte(); - if (bt != 0x00) - return null; - - - //------ all private key components are Integer sequences ---- - elems = GetIntegerSize(binr); - MODULUS = binr.ReadBytes(elems); - - elems = GetIntegerSize(binr); - E = binr.ReadBytes(elems); - - elems = GetIntegerSize(binr); - D = binr.ReadBytes(elems); - - elems = GetIntegerSize(binr); - P = binr.ReadBytes(elems); - - elems = GetIntegerSize(binr); - Q = binr.ReadBytes(elems); - - elems = GetIntegerSize(binr); - DP = binr.ReadBytes(elems); - - elems = GetIntegerSize(binr); - DQ = binr.ReadBytes(elems); - - elems = GetIntegerSize(binr); - IQ = binr.ReadBytes(elems); - - - // ------- create RSACryptoServiceProvider instance and initialize with public key ----- - var CspParameters = new CspParameters(); - CspParameters.Flags = CspProviderFlags.UseMachineKeyStore; - - var bitLen = 1024; - if ("RSA2".Equals(signType)) - bitLen = 2048; - - var rsa = RSA.Create(); - rsa.KeySize = bitLen; - var rsAparams = new RSAParameters(); - rsAparams.Modulus = MODULUS; - rsAparams.Exponent = E; - rsAparams.D = D; - rsAparams.P = P; - rsAparams.Q = Q; - rsAparams.DP = DP; - rsAparams.DQ = DQ; - rsAparams.InverseQ = IQ; - rsa.ImportParameters(rsAparams); - return rsa; - } - catch (Exception ex) - { - return null; - } - finally - { - binr.Close(); - } - } - - private static int GetIntegerSize(BinaryReader binr) - { - byte bt = 0; - byte lowbyte = 0x00; - byte highbyte = 0x00; - var count = 0; - bt = binr.ReadByte(); - if (bt != 0x02) //expect integer - return 0; - bt = binr.ReadByte(); - - if (bt == 0x81) - { - count = binr.ReadByte(); // data size in next byte - } - else if (bt == 0x82) - { - highbyte = binr.ReadByte(); // data size in next 2 bytes - lowbyte = binr.ReadByte(); - byte[] modint = {lowbyte, highbyte, 0x00, 0x00}; - count = BitConverter.ToInt32(modint, 0); - } - else - { - count = bt; // we already have the data size - } - - while (binr.ReadByte() == 0x00) - //remove high order zeros in data - count -= 1; - binr.BaseStream.Seek(-1, SeekOrigin.Current); //last ReadByte wasn't a removed zero, so back up a byte - return count; - } - } -} +using System; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Alipay.AopSdk.Core.Util +{ + public class AlipaySignature + { + /** 默认编码字符集 */ + private static readonly string DEFAULT_CHARSET = "utf-8"; + + public static string GetSignContent(IDictionary parameters) + { + // 第一步:把字典按Key的字母顺序排序 + IDictionary sortedParams = new SortedDictionary(parameters); + var dem = sortedParams.GetEnumerator(); + + // 第二步:把所有参数名和参数值串在一起 + var query = new StringBuilder(""); + while (dem.MoveNext()) + { + var key = dem.Current.Key; + var value = dem.Current.Value; + if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value)) + query.Append(key).Append("=").Append(value).Append("&"); + } + var content = query.ToString().Substring(0, query.Length - 1); + + return content; + } + + public static string RSASign(IDictionary parameters, string privateKeyPem, string charset, + string signType) + { + var signContent = GetSignContent(parameters); + + return RSASignCharSet(signContent, privateKeyPem, charset, signType); + } + + public static string RSASign(string data, string privateKeyPem, string charset, string signType) + { + return RSASignCharSet(data, privateKeyPem, charset, signType); + } + + ///* + public static string RSASign(IDictionary parameters, string privateKeyPem, string charset, + bool keyFromFile, string signType) + { + var signContent = GetSignContent(parameters); + + return RSASignCharSet(signContent, privateKeyPem, charset, keyFromFile, signType); + } + + public static string RSASign(string data, string privateKeyPem, string charset, string signType, bool keyFromFile) + { + return RSASignCharSet(data, privateKeyPem, charset, keyFromFile, signType); + } + + //*/ + public static string RSASignCharSet(string data, string privateKeyPem, string charset, string signType) + { + RSA rsaCsp = LoadCertificateFile(privateKeyPem, signType); + byte[] dataBytes = null; + if (string.IsNullOrEmpty(charset)) + dataBytes = Encoding.UTF8.GetBytes(data); + else + dataBytes = Encoding.GetEncoding(charset).GetBytes(data); + + var signatureBytes = rsaCsp.SignData(dataBytes, "RSA2".Equals(signType) ? HashAlgorithmName.SHA256 : HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); + + return Convert.ToBase64String(signatureBytes); + } + + + public static string RSASignCharSet(string data, string privateKeyPem, string charset, bool keyFromFile, + string signType) + { + byte[] signatureBytes = null; + try + { + RSA rsaCsp = null; + rsaCsp = keyFromFile ? LoadCertificateFile(privateKeyPem, signType) : LoadCertificateString(privateKeyPem, signType); + + byte[] dataBytes = null; + if (string.IsNullOrEmpty(charset)) + dataBytes = Encoding.UTF8.GetBytes(data); + else + dataBytes = Encoding.GetEncoding(charset).GetBytes(data); + if (null == rsaCsp) + throw new AopException("您使用的私钥格式错误,请检查RSA私钥配置" + ",charset = " + charset); + signatureBytes = rsaCsp.SignData(dataBytes, "RSA2".Equals(signType) ? HashAlgorithmName.SHA256 : HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); + } + catch (Exception ex) + { + throw new AopException($"您使用的私钥格式错误,请检查RSA私钥配置,charset = {charset},异常信息:{ex.Message}", ex); + } + return Convert.ToBase64String(signatureBytes); + } + + + public static bool RSACheckV1(IDictionary parameters, string publicKeyPem, string charset) + { + var sign = parameters["sign"]; + + parameters.Remove("sign"); + parameters.Remove("sign_type"); + var signContent = GetSignContent(parameters); + return RSACheckContent(signContent, sign, publicKeyPem, charset, "RSA"); + } + + public static bool RSACheckV1(IDictionary parameters, string publicKeyPem) + { + var sign = parameters["sign"]; + + parameters.Remove("sign"); + parameters.Remove("sign_type"); + var signContent = GetSignContent(parameters); + + return RSACheckContent(signContent, sign, publicKeyPem, DEFAULT_CHARSET, "RSA"); + } + + public static bool RSA2Check(IDictionary parameters, string publicKeyPem) + { + var sign = parameters["sign"]; + + parameters.Remove("sign"); + parameters.Remove("sign_type"); + var signContent = GetSignContent(parameters); + + return RSACheckContent(signContent, sign, publicKeyPem, DEFAULT_CHARSET, "RSA2"); + } + + public static bool RSACheckV1(IDictionary parameters, string publicKeyPem, string charset, + string signType, bool keyFromFile) + { + var sign = parameters["sign"]; + + parameters.Remove("sign"); + parameters.Remove("sign_type"); + var signContent = GetSignContent(parameters); + return RSACheckContent(signContent, sign, publicKeyPem, charset, signType, keyFromFile); + } + + public static bool RSACheckV2(IDictionary parameters, string publicKeyPem, string charset) + { + var sign = parameters["sign"]; + + parameters.Remove("sign"); + parameters.Remove("sign_type"); + var signContent = GetSignContent(parameters); + + return RSACheckContent(signContent, sign, publicKeyPem, charset, "RSA"); + } + + public static bool RSACheckV2(IDictionary parameters, string publicKeyPem, string charset, + string signType, bool keyFromFile) + { + var sign = parameters["sign"]; + parameters.Remove("sign"); + parameters.Remove("sign_type"); + var signContent = GetSignContent(parameters); + + return RSACheckContent(signContent, sign, publicKeyPem, charset, signType, keyFromFile); + } + + public static RSA CreateRsaProviderFromPublicKey(string publicKeyString,string signType) + { + // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" + byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 }; + byte[] seq = new byte[15]; + + var x509Key = Convert.FromBase64String(publicKeyString); + + // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------ + using (MemoryStream mem = new MemoryStream(x509Key)) + { + using (BinaryReader binr = new BinaryReader(mem)) //wrap Memory Stream with BinaryReader for easy reading + { + byte bt = 0; + ushort twobytes = 0; + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8230) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + seq = binr.ReadBytes(15); //read the Sequence OID + if (!CompareBytearrays(seq, seqOid)) //make sure Sequence for OID is correct + return null; + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8203) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + bt = binr.ReadByte(); + if (bt != 0x00) //expect null byte next + return null; + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8230) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + twobytes = binr.ReadUInt16(); + byte lowbyte = 0x00; + byte highbyte = 0x00; + + if (twobytes == 0x8102) //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 + else if (twobytes == 0x8202) + { + highbyte = binr.ReadByte(); //advance 2 bytes + lowbyte = binr.ReadByte(); + } + else + return null; + byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order + int modsize = BitConverter.ToInt32(modint, 0); + + int firstbyte = binr.PeekChar(); + if (firstbyte == 0x00) + { //if first byte (highest order) of modulus is zero, don't include it + binr.ReadByte(); //skip this null byte + modsize -= 1; //reduce modulus buffer size by 1 + } + + byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes + + if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data + return null; + int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values) + byte[] exponent = binr.ReadBytes(expbytes); + + // ------- create RSACryptoServiceProvider instance and initialize with public key ----- + var rsa = RSA.Create(); + rsa.KeySize = signType == "RSA" ? 1024 : 2048; + RSAParameters rsaKeyInfo = new RSAParameters(); + rsaKeyInfo.Modulus = modulus; + rsaKeyInfo.Exponent = exponent; + rsa.ImportParameters(rsaKeyInfo); + + return rsa; + } + + } + } + + private static bool CompareBytearrays(byte[] a, byte[] b) + { + if (a.Length != b.Length) + return false; + int i = 0; + foreach (byte c in a) + { + if (c != b[i]) + return false; + i++; + } + return true; + } + + public static bool RSACheckContent(string signContent, string sign, string publicKeyPem, string charset, + string signType) + { + try + { + if (string.IsNullOrEmpty(charset)) + charset = DEFAULT_CHARSET; + + var sPublicKeyPem = File.ReadAllText(publicKeyPem); + + var rsa = CreateRsaProviderFromPublicKey(sPublicKeyPem, signType); + + if ("RSA2".Equals(signType)) + { + + + var bVerifyResultOriginal = rsa.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), + Convert.FromBase64String(sign),HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + return bVerifyResultOriginal; + } + else + { + + var bVerifyResultOriginal = rsa.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), + Convert.FromBase64String(sign), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); + return bVerifyResultOriginal; + } + } + catch + { + return false; + } + } + + public static bool RSACheckContent(string signContent, string sign, string publicKeyPem, string charset, + string signType, bool keyFromFile) + { + try + { + if (string.IsNullOrEmpty(charset)) + charset = DEFAULT_CHARSET; + + string sPublicKeyPem= publicKeyPem; + + if (keyFromFile) + { + sPublicKeyPem = File.ReadAllText(publicKeyPem); + } + var rsa = CreateRsaProviderFromPublicKey(sPublicKeyPem, signType); + + if ("RSA2".Equals(signType)) + { + + + var bVerifyResultOriginal = rsa.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), + Convert.FromBase64String(sign), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + return bVerifyResultOriginal; + } + else + { + var bVerifyResultOriginal = rsa.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), + Convert.FromBase64String(sign), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); + return bVerifyResultOriginal; + } + } + catch + { + return false; + } + } + + public static bool RSACheckContent(string signContent, string sign, string publicKeyPem, string charset, + bool keyFromFile) + { + try + { + string sPublicKeyPem= publicKeyPem; + if (keyFromFile) + { + sPublicKeyPem = File.ReadAllText(publicKeyPem); + } + var rsa = CreateRsaProviderFromPublicKey(sPublicKeyPem, "RSA"); + var sha1 = new SHA1CryptoServiceProvider(); + if (string.IsNullOrEmpty(charset)) + charset = DEFAULT_CHARSET; + var bVerifyResultOriginal = rsa.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), + Convert.FromBase64String(sign),HashAlgorithmName.SHA1,RSASignaturePadding.Pkcs1); + return bVerifyResultOriginal; + } + catch (Exception ex) + { + var s = ex.Message; + return false; + } + } + + public static string CheckSignAndDecrypt(IDictionary parameters, string alipayPublicKey, + string cusPrivateKey, bool isCheckSign, + bool isDecrypt) + { + var charset = parameters["charset"]; + var bizContent = parameters["biz_content"]; + if (isCheckSign) + if (!RSACheckV2(parameters, alipayPublicKey, charset)) + throw new AopException("rsaCheck failure:rsaParams=" + parameters); + + if (isDecrypt) + return RSADecrypt(bizContent, cusPrivateKey, charset, "RSA"); + + return bizContent; + } + + public static string CheckSignAndDecrypt(IDictionary parameters, string alipayPublicKey, + string cusPrivateKey, bool isCheckSign, + bool isDecrypt, string signType, bool keyFromFile) + { + var charset = parameters["charset"]; + var bizContent = parameters["biz_content"]; + if (isCheckSign) + if (!RSACheckV2(parameters, alipayPublicKey, charset, signType, keyFromFile)) + throw new AopException("rsaCheck failure:rsaParams=" + parameters); + + if (isDecrypt) + return RSADecrypt(bizContent, cusPrivateKey, charset, signType, keyFromFile); + + return bizContent; + } + + public static string encryptAndSign(string bizContent, string alipayPublicKey, + string cusPrivateKey, string charset, bool isEncrypt, + bool isSign, string signType, bool keyFromFile) + { + var sb = new StringBuilder(); + if (string.IsNullOrEmpty(charset)) + charset = DEFAULT_CHARSET; + sb.Append(""); + if (isEncrypt) + { +// 加密 + sb.Append(""); + var encrypted = RSAEncrypt(bizContent, alipayPublicKey, charset, keyFromFile); + sb.Append("" + encrypted + ""); + sb.Append("" + signType + ""); + if (isSign) + { + var sign = RSASign(encrypted, cusPrivateKey, charset, signType, keyFromFile); + sb.Append("" + sign + ""); + sb.Append("" + signType + ""); + } + sb.Append(""); + } + else if (isSign) + { +// 不加密,但需要签名 + sb.Append(""); + sb.Append("" + bizContent + ""); + var sign = RSASign(bizContent, cusPrivateKey, charset, signType, keyFromFile); + sb.Append("" + sign + ""); + sb.Append("" + signType + ""); + sb.Append(""); + } + else + { +// 不加密,不加签 + sb.Append(bizContent); + } + return sb.ToString(); + } + + public static string encryptAndSign(string bizContent, string alipayPublicKey, + string cusPrivateKey, string charset, bool isEncrypt, + bool isSign) + { + var sb = new StringBuilder(); + if (string.IsNullOrEmpty(charset)) + charset = DEFAULT_CHARSET; + sb.Append(""); + if (isEncrypt) + { +// 加密 + sb.Append(""); + var encrypted = RSAEncrypt(bizContent, alipayPublicKey, charset); + sb.Append("" + encrypted + ""); + sb.Append("RSA"); + if (isSign) + { + var sign = RSASign(encrypted, cusPrivateKey, charset, "RSA"); + sb.Append("" + sign + ""); + sb.Append("RSA"); + } + sb.Append(""); + } + else if (isSign) + { +// 不加密,但需要签名 + sb.Append(""); + sb.Append("" + bizContent + ""); + var sign = RSASign(bizContent, cusPrivateKey, charset, "RSA"); + sb.Append("" + sign + ""); + sb.Append("RSA"); + sb.Append(""); + } + else + { +// 不加密,不加签 + sb.Append(bizContent); + } + return sb.ToString(); + } + + public static string RSAEncrypt(string content, string publicKeyPem, string charset) + { + try + { + var sPublicKeyPEM = File.ReadAllText(publicKeyPem); + var rsa = CreateRsaProviderFromPublicKey(sPublicKeyPEM, "RSA"); + if (string.IsNullOrEmpty(charset)) + charset = DEFAULT_CHARSET; + var data = Encoding.GetEncoding(charset).GetBytes(content); + var maxBlockSize = rsa.KeySize / 8 - 11; //加密块最大长度限制 + if (data.Length <= maxBlockSize) + { + var cipherbytes = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1); + return Convert.ToBase64String(cipherbytes); + } + var plaiStream = new MemoryStream(data); + var crypStream = new MemoryStream(); + var buffer = new byte[maxBlockSize]; + var blockSize = plaiStream.Read(buffer, 0, maxBlockSize); + while (blockSize > 0) + { + var toEncrypt = new byte[blockSize]; + Array.Copy(buffer, 0, toEncrypt, 0, blockSize); + var cryptograph = rsa.Encrypt(toEncrypt, RSAEncryptionPadding.Pkcs1); + crypStream.Write(cryptograph, 0, cryptograph.Length); + blockSize = plaiStream.Read(buffer, 0, maxBlockSize); + } + + return Convert.ToBase64String(crypStream.ToArray(), Base64FormattingOptions.None); + } + catch (Exception ex) + { + throw new AopException("EncryptContent = " + content + ",charset = " + charset, ex); + } + } + + public static string RSAEncrypt(string content, string publicKeyPem, string charset, bool keyFromFile) + { + try + { + string sPublicKeyPEM= publicKeyPem; + if (keyFromFile) + { + sPublicKeyPEM = File.ReadAllText(publicKeyPem); + } + var rsa = CreateRsaProviderFromPublicKey(publicKeyPem, "RSA"); + if (string.IsNullOrEmpty(charset)) + charset = DEFAULT_CHARSET; + var data = Encoding.GetEncoding(charset).GetBytes(content); + var maxBlockSize = rsa.KeySize / 8 - 11; //加密块最大长度限制 + if (data.Length <= maxBlockSize) + { + var cipherbytes = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1); + return Convert.ToBase64String(cipherbytes); + } + var plaiStream = new MemoryStream(data); + var crypStream = new MemoryStream(); + var buffer = new byte[maxBlockSize]; + var blockSize = plaiStream.Read(buffer, 0, maxBlockSize); + while (blockSize > 0) + { + var toEncrypt = new byte[blockSize]; + Array.Copy(buffer, 0, toEncrypt, 0, blockSize); + var cryptograph = rsa.Encrypt(toEncrypt, RSAEncryptionPadding.Pkcs1); + crypStream.Write(cryptograph, 0, cryptograph.Length); + blockSize = plaiStream.Read(buffer, 0, maxBlockSize); + } + + return Convert.ToBase64String(crypStream.ToArray(), Base64FormattingOptions.None); + } + catch (Exception ex) + { + throw new AopException("EncryptContent = " + content + ",charset = " + charset, ex); + } + } + + public static string RSADecrypt(string content, string privateKeyPem, string charset, string signType) + { + try + { + var rsaCsp = LoadCertificateFile(privateKeyPem, signType); + if (string.IsNullOrEmpty(charset)) + charset = DEFAULT_CHARSET; + var data = Convert.FromBase64String(content); + var maxBlockSize = rsaCsp.KeySize / 8; //解密块最大长度限制 + if (data.Length <= maxBlockSize) + { + var cipherbytes = rsaCsp.Decrypt(data, RSAEncryptionPadding.Pkcs1); + return Encoding.GetEncoding(charset).GetString(cipherbytes); + } + var crypStream = new MemoryStream(data); + var plaiStream = new MemoryStream(); + var buffer = new byte[maxBlockSize]; + var blockSize = crypStream.Read(buffer, 0, maxBlockSize); + while (blockSize > 0) + { + var toDecrypt = new byte[blockSize]; + Array.Copy(buffer, 0, toDecrypt, 0, blockSize); + var cryptograph = rsaCsp.Decrypt(toDecrypt, RSAEncryptionPadding.Pkcs1); + plaiStream.Write(cryptograph, 0, cryptograph.Length); + blockSize = crypStream.Read(buffer, 0, maxBlockSize); + } + + return Encoding.GetEncoding(charset).GetString(plaiStream.ToArray()); + } + catch (Exception ex) + { + throw new AopException("DecryptContent = " + content + ",charset = " + charset, ex); + } + } + + public static string RSADecrypt(string content, string privateKeyPem, string charset, string signType, + bool keyFromFile) + { + try + { + RSA rsaCsp = null; + if (keyFromFile) + rsaCsp = LoadCertificateFile(privateKeyPem, signType); + else + rsaCsp = LoadCertificateString(privateKeyPem, signType); + if (string.IsNullOrEmpty(charset)) + charset = DEFAULT_CHARSET; + var data = Convert.FromBase64String(content); + var maxBlockSize = rsaCsp.KeySize / 8; //解密块最大长度限制 + if (data.Length <= maxBlockSize) + { + var cipherbytes = rsaCsp.Decrypt(data, RSAEncryptionPadding.Pkcs1); + return Encoding.GetEncoding(charset).GetString(cipherbytes); + } + var crypStream = new MemoryStream(data); + var plaiStream = new MemoryStream(); + var buffer = new byte[maxBlockSize]; + var blockSize = crypStream.Read(buffer, 0, maxBlockSize); + while (blockSize > 0) + { + var toDecrypt = new byte[blockSize]; + Array.Copy(buffer, 0, toDecrypt, 0, blockSize); + var cryptograph = rsaCsp.Decrypt(toDecrypt, RSAEncryptionPadding.Pkcs1); + plaiStream.Write(cryptograph, 0, cryptograph.Length); + blockSize = crypStream.Read(buffer, 0, maxBlockSize); + } + + return Encoding.GetEncoding(charset).GetString(plaiStream.ToArray()); + } + catch (Exception ex) + { + throw new AopException("DecryptContent = " + content + ",charset = " + charset, ex); + } + } + + private static byte[] GetPem(string type, byte[] data) + { + var pem = Encoding.UTF8.GetString(data); + var header = string.Format("-----BEGIN {0}-----\\n", type); + var footer = string.Format("-----END {0}-----", type); + var start = pem.IndexOf(header) + header.Length; + var end = pem.IndexOf(footer, start); + var base64 = pem.Substring(start, end - start); + + return Convert.FromBase64String(base64); + } + + private static RSA LoadCertificateFile(string filename, string signType) + { + using (var fs = File.OpenRead(filename)) + { + var data = new byte[fs.Length]; + byte[] res = null; + fs.Read(data, 0, data.Length); + if (data[0] != 0x30) + res = GetPem("RSA PRIVATE KEY", data); + try + { + var rsa = DecodeRSAPrivateKey(res, signType); + return rsa; + } + catch (Exception ex) + { + } + return null; + } + } + + public static RSA LoadCertificateString(string strKey, string signType) + { + byte[] data = null; + //读取带 + //ata = Encoding.Default.GetBytes(strKey); + data = Convert.FromBase64String(strKey); + //data = GetPem("RSA PRIVATE KEY", data); + try + { + var rsa = DecodeRSAPrivateKey(data, signType); + return rsa; + } + catch (Exception ex) + { + throw new AopException("Alipay.AopSdk.Core.Util.AlipaySignature LoadCertificateString DecodeRSAPrivateKey Error", ex); + } + return null; + } + + private static RSA DecodeRSAPrivateKey(byte[] privkey, string signType) + { + byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + + // --------- Set up stream to decode the asn.1 encoded RSA private key ------ + var mem = new MemoryStream(privkey); + var binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading + byte bt = 0; + ushort twobytes = 0; + var elems = 0; + try + { + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8230) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + twobytes = binr.ReadUInt16(); + if (twobytes != 0x0102) //version number + return null; + bt = binr.ReadByte(); + if (bt != 0x00) + return null; + + + //------ all private key components are Integer sequences ---- + elems = GetIntegerSize(binr); + MODULUS = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + E = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + D = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + P = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + Q = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + DP = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + DQ = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + IQ = binr.ReadBytes(elems); + + + // ------- create RSACryptoServiceProvider instance and initialize with public key ----- + var CspParameters = new CspParameters(); + CspParameters.Flags = CspProviderFlags.UseMachineKeyStore; + + var bitLen = 1024; + if ("RSA2".Equals(signType)) + bitLen = 2048; + + var rsa = RSA.Create(); + rsa.KeySize = bitLen; + var rsAparams = new RSAParameters(); + rsAparams.Modulus = MODULUS; + rsAparams.Exponent = E; + rsAparams.D = D; + rsAparams.P = P; + rsAparams.Q = Q; + rsAparams.DP = DP; + rsAparams.DQ = DQ; + rsAparams.InverseQ = IQ; + rsa.ImportParameters(rsAparams); + return rsa; + } + catch (Exception ex) + { + return null; + } + finally + { + binr.Close(); + } + } + + private static int GetIntegerSize(BinaryReader binr) + { + byte bt = 0; + byte lowbyte = 0x00; + byte highbyte = 0x00; + var count = 0; + bt = binr.ReadByte(); + if (bt != 0x02) //expect integer + return 0; + bt = binr.ReadByte(); + + if (bt == 0x81) + { + count = binr.ReadByte(); // data size in next byte + } + else if (bt == 0x82) + { + highbyte = binr.ReadByte(); // data size in next 2 bytes + lowbyte = binr.ReadByte(); + byte[] modint = {lowbyte, highbyte, 0x00, 0x00}; + count = BitConverter.ToInt32(modint, 0); + } + else + { + count = bt; // we already have the data size + } + + while (binr.ReadByte() == 0x00) + //remove high order zeros in data + count -= 1; + binr.BaseStream.Seek(-1, SeekOrigin.Current); //last ReadByte wasn't a removed zero, so back up a byte + return count; + } + } +} diff --git a/Infrastructure/ServiceClient/Alipay.AopSdk.Core/Util/RSAHelper.cs b/Infrastructure/ServiceClient/Alipay.AopSdk.Core/Util/RSAHelper.cs index 8ada138..7fb51af 100644 --- a/Infrastructure/ServiceClient/Alipay.AopSdk.Core/Util/RSAHelper.cs +++ b/Infrastructure/ServiceClient/Alipay.AopSdk.Core/Util/RSAHelper.cs @@ -1,320 +1,320 @@ -using System; -using System.IO; -using System.Security.Cryptography; -using System.Text; - -namespace RSATest -{ - /// - /// RSA加解密 使用OpenSSL的公钥加密/私钥解密 - /// - /// 公私钥请使用openssl生成 ssh-keygen -t rsa 命令生成的公钥私钥是不行的 - /// - /// 作者:李志强 - /// 时间:2017年10月30日15:50:14 - /// QQ:501232752 - /// - public class RSAHelper - { - private readonly RSA _privateKeyRsaProvider; - private readonly RSA _publicKeyRsaProvider; - private readonly HashAlgorithmName _hashAlgorithmName; - private readonly Encoding _encoding; - - /// - /// 实例化RSAHelper - /// - /// 加密算法类型 RSA SHA1;RSA2 SHA256 密钥长度至少为2048 - /// 编码类型 - /// 私钥 - /// 公钥 - public RSAHelper(RSAType rsaType, Encoding encoding, string privateKey, string publicKey = null) - { - _encoding = encoding; - if (!string.IsNullOrEmpty(privateKey)) - { - _privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey); - } - - if (!string.IsNullOrEmpty(publicKey)) - { - _publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey); - } - - _hashAlgorithmName = rsaType == RSAType.RSA ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256; - } - - #region 使用私钥签名 - - /// - /// 使用私钥签名 - /// - /// 原始数据 - /// - public string Sign(string data) - { - byte[] dataBytes = _encoding.GetBytes(data); - - var signatureBytes = _privateKeyRsaProvider.SignData(dataBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1); - - return Convert.ToBase64String(signatureBytes); - } - - #endregion - - #region 使用公钥验证签名 - - /// - /// 使用公钥验证签名 - /// - /// 原始数据 - /// 签名 - /// - public bool Verify(string data,string sign) - { - byte[] dataBytes = _encoding.GetBytes(data); - byte[] signBytes = Convert.FromBase64String(sign); - - var verify = _publicKeyRsaProvider.VerifyData(dataBytes, signBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1); - - return verify; - } - - #endregion - - #region 解密 - - public string Decrypt(string cipherText) - { - if (_privateKeyRsaProvider == null) - { - throw new Exception("_privateKeyRsaProvider is null"); - } - return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), RSAEncryptionPadding.Pkcs1)); - } - - #endregion - - #region 加密 - - public string Encrypt(string text) - { - if (_publicKeyRsaProvider == null) - { - throw new Exception("_publicKeyRsaProvider is null"); - } - return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.Pkcs1)); - } - - #endregion - - #region 使用私钥创建RSA实例 - - public RSA CreateRsaProviderFromPrivateKey(string privateKey) - { - var privateKeyBits = Convert.FromBase64String(privateKey); - - var rsa = RSA.Create(); - var rsaParameters = new RSAParameters(); - - using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits))) - { - byte bt = 0; - ushort twobytes = 0; - twobytes = binr.ReadUInt16(); - if (twobytes == 0x8130) - binr.ReadByte(); - else if (twobytes == 0x8230) - binr.ReadInt16(); - else - throw new Exception("Unexpected value read binr.ReadUInt16()"); - - twobytes = binr.ReadUInt16(); - if (twobytes != 0x0102) - throw new Exception("Unexpected version"); - - bt = binr.ReadByte(); - if (bt != 0x00) - throw new Exception("Unexpected value read binr.ReadByte()"); - - rsaParameters.Modulus = binr.ReadBytes(GetIntegerSize(binr)); - rsaParameters.Exponent = binr.ReadBytes(GetIntegerSize(binr)); - rsaParameters.D = binr.ReadBytes(GetIntegerSize(binr)); - rsaParameters.P = binr.ReadBytes(GetIntegerSize(binr)); - rsaParameters.Q = binr.ReadBytes(GetIntegerSize(binr)); - rsaParameters.DP = binr.ReadBytes(GetIntegerSize(binr)); - rsaParameters.DQ = binr.ReadBytes(GetIntegerSize(binr)); - rsaParameters.InverseQ = binr.ReadBytes(GetIntegerSize(binr)); - } - - rsa.ImportParameters(rsaParameters); - return rsa; - } - - #endregion - - #region 使用公钥创建RSA实例 - - public RSA CreateRsaProviderFromPublicKey(string publicKeyString) - { - // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" - byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 }; - byte[] seq = new byte[15]; - - var x509Key = Convert.FromBase64String(publicKeyString); - - // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------ - using (MemoryStream mem = new MemoryStream(x509Key)) - { - using (BinaryReader binr = new BinaryReader(mem)) //wrap Memory Stream with BinaryReader for easy reading - { - byte bt = 0; - ushort twobytes = 0; - - twobytes = binr.ReadUInt16(); - if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) - binr.ReadByte(); //advance 1 byte - else if (twobytes == 0x8230) - binr.ReadInt16(); //advance 2 bytes - else - return null; - - seq = binr.ReadBytes(15); //read the Sequence OID - if (!CompareBytearrays(seq, seqOid)) //make sure Sequence for OID is correct - return null; - - twobytes = binr.ReadUInt16(); - if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81) - binr.ReadByte(); //advance 1 byte - else if (twobytes == 0x8203) - binr.ReadInt16(); //advance 2 bytes - else - return null; - - bt = binr.ReadByte(); - if (bt != 0x00) //expect null byte next - return null; - - twobytes = binr.ReadUInt16(); - if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) - binr.ReadByte(); //advance 1 byte - else if (twobytes == 0x8230) - binr.ReadInt16(); //advance 2 bytes - else - return null; - - twobytes = binr.ReadUInt16(); - byte lowbyte = 0x00; - byte highbyte = 0x00; - - if (twobytes == 0x8102) //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 - else if (twobytes == 0x8202) - { - highbyte = binr.ReadByte(); //advance 2 bytes - lowbyte = binr.ReadByte(); - } - else - return null; - byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order - int modsize = BitConverter.ToInt32(modint, 0); - - int firstbyte = binr.PeekChar(); - if (firstbyte == 0x00) - { //if first byte (highest order) of modulus is zero, don't include it - binr.ReadByte(); //skip this null byte - modsize -= 1; //reduce modulus buffer size by 1 - } - - byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes - - if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data - return null; - int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values) - byte[] exponent = binr.ReadBytes(expbytes); - - // ------- create RSACryptoServiceProvider instance and initialize with public key ----- - var rsa = RSA.Create(); - RSAParameters rsaKeyInfo = new RSAParameters - { - Modulus = modulus, - Exponent = exponent - }; - rsa.ImportParameters(rsaKeyInfo); - - return rsa; - } - - } - } - - #endregion - - #region 导入密钥算法 - - private int GetIntegerSize(BinaryReader binr) - { - byte bt = 0; - int count = 0; - bt = binr.ReadByte(); - if (bt != 0x02) - return 0; - bt = binr.ReadByte(); - - if (bt == 0x81) - count = binr.ReadByte(); - else - if (bt == 0x82) - { - var highbyte = binr.ReadByte(); - var lowbyte = binr.ReadByte(); - byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; - count = BitConverter.ToInt32(modint, 0); - } - else - { - count = bt; - } - - while (binr.ReadByte() == 0x00) - { - count -= 1; - } - binr.BaseStream.Seek(-1, SeekOrigin.Current); - return count; - } - - private bool CompareBytearrays(byte[] a, byte[] b) - { - if (a.Length != b.Length) - return false; - int i = 0; - foreach (byte c in a) - { - if (c != b[i]) - return false; - i++; - } - return true; - } - - #endregion - - } - - /// - /// RSA算法类型 - /// - public enum RSAType - { - /// - /// SHA1 - /// - RSA = 0, - /// - /// RSA2 密钥长度至少为2048 - /// SHA256 - /// - RSA2 - } +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace RSATest +{ + /// + /// RSA加解密 使用OpenSSL的公钥加密/私钥解密 + /// + /// 公私钥请使用openssl生成 ssh-keygen -t rsa 命令生成的公钥私钥是不行的 + /// + /// 作者:李志强 + /// 时间:2017年10月30日15:50:14 + /// QQ:501232752 + /// + public class RSAHelper + { + private readonly RSA _privateKeyRsaProvider; + private readonly RSA _publicKeyRsaProvider; + private readonly HashAlgorithmName _hashAlgorithmName; + private readonly Encoding _encoding; + + /// + /// 实例化RSAHelper + /// + /// 加密算法类型 RSA SHA1;RSA2 SHA256 密钥长度至少为2048 + /// 编码类型 + /// 私钥 + /// 公钥 + public RSAHelper(RSAType rsaType, Encoding encoding, string privateKey, string publicKey = null) + { + _encoding = encoding; + if (!string.IsNullOrEmpty(privateKey)) + { + _privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey); + } + + if (!string.IsNullOrEmpty(publicKey)) + { + _publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey); + } + + _hashAlgorithmName = rsaType == RSAType.RSA ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256; + } + + #region 使用私钥签名 + + /// + /// 使用私钥签名 + /// + /// 原始数据 + /// + public string Sign(string data) + { + byte[] dataBytes = _encoding.GetBytes(data); + + var signatureBytes = _privateKeyRsaProvider.SignData(dataBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1); + + return Convert.ToBase64String(signatureBytes); + } + + #endregion + + #region 使用公钥验证签名 + + /// + /// 使用公钥验证签名 + /// + /// 原始数据 + /// 签名 + /// + public bool Verify(string data,string sign) + { + byte[] dataBytes = _encoding.GetBytes(data); + byte[] signBytes = Convert.FromBase64String(sign); + + var verify = _publicKeyRsaProvider.VerifyData(dataBytes, signBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1); + + return verify; + } + + #endregion + + #region 解密 + + public string Decrypt(string cipherText) + { + if (_privateKeyRsaProvider == null) + { + throw new Exception("_privateKeyRsaProvider is null"); + } + return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), RSAEncryptionPadding.Pkcs1)); + } + + #endregion + + #region 加密 + + public string Encrypt(string text) + { + if (_publicKeyRsaProvider == null) + { + throw new Exception("_publicKeyRsaProvider is null"); + } + return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.Pkcs1)); + } + + #endregion + + #region 使用私钥创建RSA实例 + + public RSA CreateRsaProviderFromPrivateKey(string privateKey) + { + var privateKeyBits = Convert.FromBase64String(privateKey); + + var rsa = RSA.Create(); + var rsaParameters = new RSAParameters(); + + using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits))) + { + byte bt = 0; + ushort twobytes = 0; + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) + binr.ReadByte(); + else if (twobytes == 0x8230) + binr.ReadInt16(); + else + throw new Exception("Unexpected value read binr.ReadUInt16()"); + + twobytes = binr.ReadUInt16(); + if (twobytes != 0x0102) + throw new Exception("Unexpected version"); + + bt = binr.ReadByte(); + if (bt != 0x00) + throw new Exception("Unexpected value read binr.ReadByte()"); + + rsaParameters.Modulus = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.Exponent = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.D = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.P = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.Q = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.DP = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.DQ = binr.ReadBytes(GetIntegerSize(binr)); + rsaParameters.InverseQ = binr.ReadBytes(GetIntegerSize(binr)); + } + + rsa.ImportParameters(rsaParameters); + return rsa; + } + + #endregion + + #region 使用公钥创建RSA实例 + + public RSA CreateRsaProviderFromPublicKey(string publicKeyString) + { + // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" + byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 }; + byte[] seq = new byte[15]; + + var x509Key = Convert.FromBase64String(publicKeyString); + + // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------ + using (MemoryStream mem = new MemoryStream(x509Key)) + { + using (BinaryReader binr = new BinaryReader(mem)) //wrap Memory Stream with BinaryReader for easy reading + { + byte bt = 0; + ushort twobytes = 0; + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8230) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + seq = binr.ReadBytes(15); //read the Sequence OID + if (!CompareBytearrays(seq, seqOid)) //make sure Sequence for OID is correct + return null; + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8203) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + bt = binr.ReadByte(); + if (bt != 0x00) //expect null byte next + return null; + + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + binr.ReadByte(); //advance 1 byte + else if (twobytes == 0x8230) + binr.ReadInt16(); //advance 2 bytes + else + return null; + + twobytes = binr.ReadUInt16(); + byte lowbyte = 0x00; + byte highbyte = 0x00; + + if (twobytes == 0x8102) //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 + else if (twobytes == 0x8202) + { + highbyte = binr.ReadByte(); //advance 2 bytes + lowbyte = binr.ReadByte(); + } + else + return null; + byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order + int modsize = BitConverter.ToInt32(modint, 0); + + int firstbyte = binr.PeekChar(); + if (firstbyte == 0x00) + { //if first byte (highest order) of modulus is zero, don't include it + binr.ReadByte(); //skip this null byte + modsize -= 1; //reduce modulus buffer size by 1 + } + + byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes + + if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data + return null; + int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values) + byte[] exponent = binr.ReadBytes(expbytes); + + // ------- create RSACryptoServiceProvider instance and initialize with public key ----- + var rsa = RSA.Create(); + RSAParameters rsaKeyInfo = new RSAParameters + { + Modulus = modulus, + Exponent = exponent + }; + rsa.ImportParameters(rsaKeyInfo); + + return rsa; + } + + } + } + + #endregion + + #region 导入密钥算法 + + private int GetIntegerSize(BinaryReader binr) + { + byte bt = 0; + int count = 0; + bt = binr.ReadByte(); + if (bt != 0x02) + return 0; + bt = binr.ReadByte(); + + if (bt == 0x81) + count = binr.ReadByte(); + else + if (bt == 0x82) + { + var highbyte = binr.ReadByte(); + var lowbyte = binr.ReadByte(); + byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; + count = BitConverter.ToInt32(modint, 0); + } + else + { + count = bt; + } + + while (binr.ReadByte() == 0x00) + { + count -= 1; + } + binr.BaseStream.Seek(-1, SeekOrigin.Current); + return count; + } + + private bool CompareBytearrays(byte[] a, byte[] b) + { + if (a.Length != b.Length) + return false; + int i = 0; + foreach (byte c in a) + { + if (c != b[i]) + return false; + i++; + } + return true; + } + + #endregion + + } + + /// + /// RSA算法类型 + /// + public enum RSAType + { + /// + /// SHA1 + /// + RSA = 0, + /// + /// RSA2 密钥长度至少为2048 + /// SHA256 + /// + RSA2 + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/Alipay.AopSdk.Core/obj/Debug/netstandard2.0/Alipay.AopSdk.Core.csprojAssemblyReference.cache b/Infrastructure/ServiceClient/Alipay.AopSdk.Core/obj/Debug/netstandard2.0/Alipay.AopSdk.Core.csprojAssemblyReference.cache index 1e180ea..e0a4104 100644 Binary files a/Infrastructure/ServiceClient/Alipay.AopSdk.Core/obj/Debug/netstandard2.0/Alipay.AopSdk.Core.csprojAssemblyReference.cache and b/Infrastructure/ServiceClient/Alipay.AopSdk.Core/obj/Debug/netstandard2.0/Alipay.AopSdk.Core.csprojAssemblyReference.cache differ diff --git a/Infrastructure/ServiceClient/BaseInfoClient/BaseInfoClient.csproj b/Infrastructure/ServiceClient/BaseInfoClient/BaseInfoClient.csproj index 46f011d..071881e 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/BaseInfoClient.csproj +++ b/Infrastructure/ServiceClient/BaseInfoClient/BaseInfoClient.csproj @@ -1,15 +1,15 @@ - - - - netcoreapp2.2 - - - - - - - - - - - + + + + netcoreapp2.2 + + + + + + + + + + + diff --git a/Infrastructure/ServiceClient/BaseInfoClient/BaseInfoHttpClient.cs b/Infrastructure/ServiceClient/BaseInfoClient/BaseInfoHttpClient.cs index 369579f..e6857ee 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/BaseInfoHttpClient.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/BaseInfoHttpClient.cs @@ -1,24 +1,24 @@ -using System.Net.Http; - -namespace ServiceClient -{ - public class BaseInfoHttpClient - { - private IHttpClientFactory _httpClientFactory; - - internal static string _BaseUrl = ""; - - public string BaseUrl => _BaseUrl; - - public BaseInfoHttpClient(IHttpClientFactory httpClientFactory) - { - _httpClientFactory = httpClientFactory; - } - - public HttpClient CreateHttpClient() - { - return _httpClientFactory.CreateClient(); - } - - } +using System.Net.Http; + +namespace ServiceClient +{ + public class BaseInfoHttpClient + { + private IHttpClientFactory _httpClientFactory; + + internal static string _BaseUrl = ""; + + public string BaseUrl => _BaseUrl; + + public BaseInfoHttpClient(IHttpClientFactory httpClientFactory) + { + _httpClientFactory = httpClientFactory; + } + + public HttpClient CreateHttpClient() + { + return _httpClientFactory.CreateClient(); + } + + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/IServiceCollectionExtension.cs b/Infrastructure/ServiceClient/BaseInfoClient/IServiceCollectionExtension.cs index c7b4539..7850ec3 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/IServiceCollectionExtension.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/IServiceCollectionExtension.cs @@ -1,14 +1,14 @@ -using Microsoft.Extensions.DependencyInjection; - -namespace ServiceClient -{ - public static class IServiceCollectionExtension - { - public static void AddBaseInfoClient(this IServiceCollection service, string baseUrl) - { - BaseInfoHttpClient._BaseUrl = baseUrl; - - service.AddSingleton(); - } - } +using Microsoft.Extensions.DependencyInjection; + +namespace ServiceClient +{ + public static class IServiceCollectionExtension + { + public static void AddBaseInfoClient(this IServiceCollection service, string baseUrl) + { + BaseInfoHttpClient._BaseUrl = baseUrl; + + service.AddSingleton(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Householder/HouseholderItem.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Householder/HouseholderItem.cs index 32f3920..cf4a91e 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Householder/HouseholderItem.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Householder/HouseholderItem.cs @@ -1,13 +1,13 @@ -using Newtonsoft.Json; - -namespace ServiceClient.Response.Householder -{ - public class HouseholderItem - { - [JsonProperty("ID")] public int UserId { get; set; } - - [JsonProperty("name")] public string Name { get; set; } = ""; - - [JsonProperty("mobile")] public string Mobile { get; set; } = ""; - } +using Newtonsoft.Json; + +namespace ServiceClient.Response.Householder +{ + public class HouseholderItem + { + [JsonProperty("ID")] public int UserId { get; set; } + + [JsonProperty("name")] public string Name { get; set; } = ""; + + [JsonProperty("mobile")] public string Mobile { get; set; } = ""; + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Householder/QueryAllHouseholdersByOwnerIdResponse.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Householder/QueryAllHouseholdersByOwnerIdResponse.cs index d7a1cfe..c235a77 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Householder/QueryAllHouseholdersByOwnerIdResponse.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Householder/QueryAllHouseholdersByOwnerIdResponse.cs @@ -1,56 +1,56 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Data; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; -using Newtonsoft.Json; -using ServiceClient; -using ServiceClient.Response.Householder; - -namespace ServiceClient.Response.Householder -{ - - - public class QueryAllHouseholdersByOwnerIdResponse - { - [JsonProperty("userData")] - public List HouseholderItems { get; set; } = new List(); - } -} - -namespace BaseInfoClient.Extension -{ - public static class QueryAllHouseholdersByOwnerIdExtension - { - public static async Task> QueryAllHouseholdersByOwnerId(this BaseInfoHttpClient client - , int ownerId, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetAllBasePerson?OwnerID={ownerId}&Data.IsGetUser=true"); - - var content = await response.Content.ReadAsStringAsync(); - - return content.FromJsonTo>().Data.HouseholderItems; - } - catch (Exception e) - { - LogHelper.Error("根据OwnerId获取住户", e); - - if (throwException) - { - BusinessException.Throw("获取住户信息失败"); - } - else - { - return new List(); - } - } - - return new List(); - } - } +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Data; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; +using Newtonsoft.Json; +using ServiceClient; +using ServiceClient.Response.Householder; + +namespace ServiceClient.Response.Householder +{ + + + public class QueryAllHouseholdersByOwnerIdResponse + { + [JsonProperty("userData")] + public List HouseholderItems { get; set; } = new List(); + } +} + +namespace BaseInfoClient.Extension +{ + public static class QueryAllHouseholdersByOwnerIdExtension + { + public static async Task> QueryAllHouseholdersByOwnerId(this BaseInfoHttpClient client + , int ownerId, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetAllBasePerson?OwnerID={ownerId}&Data.IsGetUser=true"); + + var content = await response.Content.ReadAsStringAsync(); + + return content.FromJsonTo>().Data.HouseholderItems; + } + catch (Exception e) + { + LogHelper.Error("根据OwnerId获取住户", e); + + if (throwException) + { + BusinessException.Throw("获取住户信息失败"); + } + else + { + return new List(); + } + } + + return new List(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Householder/QueryHouseholderInfoByUserIdResponse.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Householder/QueryHouseholderInfoByUserIdResponse.cs index ad48b18..ec23ee1 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Householder/QueryHouseholderInfoByUserIdResponse.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Householder/QueryHouseholderInfoByUserIdResponse.cs @@ -1,54 +1,54 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Data; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using ServiceClient; -using ServiceClient.Response.Householder; - -namespace ServiceClient.Response.Householder -{ - public class QueryHouseholderInfoByUserIdResponse - { - [JsonProperty("userData")] public HouseholderItem HouseholderItem { get; set; } - } -} - -namespace BaseInfoClient.Extension -{ - public static class QueryHouseholderInfoByUserIdExtension - { - public static async Task QueryHouseholderInfoByUserId(this BaseInfoHttpClient client - , int ownerId, int userId, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetOneBasePerson?OwnerID={ownerId}&Data.userId={userId}"); - - var content = await response.Content.ReadAsStringAsync(); - - return content.FromJsonTo>().Data.HouseholderItem; - } - catch (Exception e) - { - LogHelper.Error("根据UserId获取住户", e); - - if (throwException) - { - BusinessException.Throw("获取住户信息失败"); - } - else - { - return new HouseholderItem(); - } - } - - return new HouseholderItem(); - } - } +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Data; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using ServiceClient; +using ServiceClient.Response.Householder; + +namespace ServiceClient.Response.Householder +{ + public class QueryHouseholderInfoByUserIdResponse + { + [JsonProperty("userData")] public HouseholderItem HouseholderItem { get; set; } + } +} + +namespace BaseInfoClient.Extension +{ + public static class QueryHouseholderInfoByUserIdExtension + { + public static async Task QueryHouseholderInfoByUserId(this BaseInfoHttpClient client + , int ownerId, int userId, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetOneBasePerson?OwnerID={ownerId}&Data.userId={userId}"); + + var content = await response.Content.ReadAsStringAsync(); + + return content.FromJsonTo>().Data.HouseholderItem; + } + catch (Exception e) + { + LogHelper.Error("根据UserId获取住户", e); + + if (throwException) + { + BusinessException.Throw("获取住户信息失败"); + } + else + { + return new HouseholderItem(); + } + } + + return new HouseholderItem(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/ManageItem.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/ManageItem.cs index 5ec7a8b..24aea74 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/ManageItem.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/ManageItem.cs @@ -1,130 +1,130 @@ -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Text; - -namespace BaseInfoClient.Response.Manage -{ - public class ManageItem - { - /// - /// 管理员id - /// - public int Id { get; set; } - - /// - /// 创建时间 - /// - public DateTime CreateTime { get; set; } - - /// - /// 更新时间 - /// - public DateTime UpdateTime { get; set; } - - /// - /// 删除标记 - /// - public int DeleteTag { get; set; } - - /// - /// 所属物业ID - /// - public int OwnerId { get; set; } - - /// - /// 更新人ID - /// - public int UpdatorId { get; set; } - - /// - /// 创建人ID - /// - public int CreatorId { get; set; } - - /// - /// 管理员登录名[16 - /// - public string LoginCode { get; set; } - - /// - /// 登录密码[20] - /// - public string Password { get; set; } - - /// - /// 关联的内部人员id - /// - public int workerid { get; set; } - - /// - /// 管理员角色 - /// - public int roleid { get; set; } - - /// - /// 状态 - /// - public int state { get; set; } - - /// - /// 头像地址[30 - /// - public string photourl { get; set; } - - /// - /// 微信openid[50] - /// - public string wxopenid { get; set; } - - /// - /// 微信昵称 - /// - public string wxnickname { get; set; } - - /// - /// 微信头像 - /// - public string wximage { get; set; } - - - /// - /// 注册来源 - /// - public int source { get; set; } - /// - /// 系统ID - /// - public int systemid { get; set; } - /// - /// 管理员手机号 - /// - public string Phone { get; set; } - /// - /// 账号code - /// - public string managercode { get; set; } - - /// - /// 管理员姓名 - /// - public string RealName { get; set; } - /// - /// 电子邮箱 - /// - public string Email { get; set; } - - /// - /// 项目关联 - /// - public string ProjectContact { get; set; } - - public bool IsIntegrator { get; set; } - - /// - /// 是否主管理员权限 - /// - public bool Isroot { get; set; } - - } -} +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Text; + +namespace BaseInfoClient.Response.Manage +{ + public class ManageItem + { + /// + /// 管理员id + /// + public int Id { get; set; } + + /// + /// 创建时间 + /// + public DateTime CreateTime { get; set; } + + /// + /// 更新时间 + /// + public DateTime UpdateTime { get; set; } + + /// + /// 删除标记 + /// + public int DeleteTag { get; set; } + + /// + /// 所属物业ID + /// + public int OwnerId { get; set; } + + /// + /// 更新人ID + /// + public int UpdatorId { get; set; } + + /// + /// 创建人ID + /// + public int CreatorId { get; set; } + + /// + /// 管理员登录名[16 + /// + public string LoginCode { get; set; } + + /// + /// 登录密码[20] + /// + public string Password { get; set; } + + /// + /// 关联的内部人员id + /// + public int workerid { get; set; } + + /// + /// 管理员角色 + /// + public int roleid { get; set; } + + /// + /// 状态 + /// + public int state { get; set; } + + /// + /// 头像地址[30 + /// + public string photourl { get; set; } + + /// + /// 微信openid[50] + /// + public string wxopenid { get; set; } + + /// + /// 微信昵称 + /// + public string wxnickname { get; set; } + + /// + /// 微信头像 + /// + public string wximage { get; set; } + + + /// + /// 注册来源 + /// + public int source { get; set; } + /// + /// 系统ID + /// + public int systemid { get; set; } + /// + /// 管理员手机号 + /// + public string Phone { get; set; } + /// + /// 账号code + /// + public string managercode { get; set; } + + /// + /// 管理员姓名 + /// + public string RealName { get; set; } + /// + /// 电子邮箱 + /// + public string Email { get; set; } + + /// + /// 项目关联 + /// + public string ProjectContact { get; set; } + + public bool IsIntegrator { get; set; } + + /// + /// 是否主管理员权限 + /// + public bool Isroot { get; set; } + + } +} diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/PermissionProjectByManagerItem.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/PermissionProjectByManagerItem.cs index 1947c0e..bd2e3f6 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/PermissionProjectByManagerItem.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/PermissionProjectByManagerItem.cs @@ -1,33 +1,33 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace BaseInfoClient.Response.Manage -{ - public class PermissionProjectByManagerItem - { - /// - /// ID - /// - public int Id { get; set; } - - /// - /// 所属物业ID - /// - public int OwnerId { get; set; } - - /// - /// 管理员数据库ID - /// - public int ManagerId { get; set; } - - /// - /// 项目编码 - /// - public int ProjectCode { get; set; } - /// - /// 小区名称 - /// - public string ProjectName { get; set; } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace BaseInfoClient.Response.Manage +{ + public class PermissionProjectByManagerItem + { + /// + /// ID + /// + public int Id { get; set; } + + /// + /// 所属物业ID + /// + public int OwnerId { get; set; } + + /// + /// 管理员数据库ID + /// + public int ManagerId { get; set; } + + /// + /// 项目编码 + /// + public int ProjectCode { get; set; } + /// + /// 小区名称 + /// + public string ProjectName { get; set; } + } +} diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/QueryAllManageByOwnerIdResponse.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/QueryAllManageByOwnerIdResponse.cs index 6b0080f..c450f38 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/QueryAllManageByOwnerIdResponse.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/QueryAllManageByOwnerIdResponse.cs @@ -1,48 +1,48 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using BaseInfoClient.Response.Manage; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Data; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; -using Newtonsoft.Json; -using ServiceClient; - -namespace BaseInfoClient.Response.Manage -{ - -} -namespace BaseInfoClient.Extension -{ - public static class QueryAllManageByOwnerIdResponse - { - public static async Task QueryManageById(this BaseInfoHttpClient client - , int Id, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/manage/v1/Manager/GetOneManage?Id={Id}"); - - var content = await response.Content.ReadAsStringAsync(); - var result = content.FromJsonTo>(); - return result.Data; - } - catch (Exception e) - { - LogHelper.Error("根据OwnerId获取住户", e); - - if (throwException) - { - BusinessException.Throw("获取住户信息失败"); - } - else - { - return new ManageItem(); - } - } - return new ManageItem(); - } - } -} +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using BaseInfoClient.Response.Manage; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Data; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; +using Newtonsoft.Json; +using ServiceClient; + +namespace BaseInfoClient.Response.Manage +{ + +} +namespace BaseInfoClient.Extension +{ + public static class QueryAllManageByOwnerIdResponse + { + public static async Task QueryManageById(this BaseInfoHttpClient client + , int Id, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/manage/v1/Manager/GetOneManage?Id={Id}"); + + var content = await response.Content.ReadAsStringAsync(); + var result = content.FromJsonTo>(); + return result.Data; + } + catch (Exception e) + { + LogHelper.Error("根据OwnerId获取住户", e); + + if (throwException) + { + BusinessException.Throw("获取住户信息失败"); + } + else + { + return new ManageItem(); + } + } + return new ManageItem(); + } + } +} diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/QueryPermissionProjectByManagerIdResponse.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/QueryPermissionProjectByManagerIdResponse.cs index b3e1214..50ed5ec 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/QueryPermissionProjectByManagerIdResponse.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Manage/QueryPermissionProjectByManagerIdResponse.cs @@ -1,45 +1,45 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using BaseInfoClient.Response.Manage; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Data; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; -using Newtonsoft.Json; -using ServiceClient; -using System.Text; - -namespace BaseInfoClient.Extension -{ - public static class QueryPermissionProjectByManagerIdResponse - { - public static async Task> QueryProjectCodeByManageId(this BaseInfoHttpClient client - , int Id, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/manage/v1/Manager/GetByManageId?ManagerId={Id}"); - - var content = await response.Content.ReadAsStringAsync(); - var result = content.FromJsonTo>>(); - return result.Data; - } - catch (Exception e) - { - LogHelper.Error("根据OwnerId获取住户", e); - - if (throwException) - { - BusinessException.Throw("获取住户信息失败"); - } - else - { - return new List(); - } - } - return new List(); - } - } +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using BaseInfoClient.Response.Manage; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Data; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; +using Newtonsoft.Json; +using ServiceClient; +using System.Text; + +namespace BaseInfoClient.Extension +{ + public static class QueryPermissionProjectByManagerIdResponse + { + public static async Task> QueryProjectCodeByManageId(this BaseInfoHttpClient client + , int Id, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/manage/v1/Manager/GetByManageId?ManagerId={Id}"); + + var content = await response.Content.ReadAsStringAsync(); + var result = content.FromJsonTo>>(); + return result.Data; + } + catch (Exception e) + { + LogHelper.Error("根据OwnerId获取住户", e); + + if (throwException) + { + BusinessException.Throw("获取住户信息失败"); + } + else + { + return new List(); + } + } + return new List(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Project/ProjectItem.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Project/ProjectItem.cs index 5fb554d..847ea9c 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Project/ProjectItem.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Project/ProjectItem.cs @@ -1,18 +1,18 @@ -using Newtonsoft.Json; - -namespace BaseInfoClient.Response.Project -{ - public class ProjectItem - { - [JsonProperty("projectCode")] public int ProjectCode { get; set; } - - [JsonProperty("name")] public string Name { get; set; } = ""; - /// - /// Сַ - /// - [JsonProperty("location")] public string Location { get; set; } = ""; - - - [JsonProperty("projectType")] public int projectType { get; set; } - } +using Newtonsoft.Json; + +namespace BaseInfoClient.Response.Project +{ + public class ProjectItem + { + [JsonProperty("projectCode")] public int ProjectCode { get; set; } + + [JsonProperty("name")] public string Name { get; set; } = ""; + /// + /// Сַ + /// + [JsonProperty("location")] public string Location { get; set; } = ""; + + + [JsonProperty("projectType")] public int projectType { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Project/QueryAllProjectsByOwnerIdResponse.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Project/QueryAllProjectsByOwnerIdResponse.cs index 412ebe9..60f28e4 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Project/QueryAllProjectsByOwnerIdResponse.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Project/QueryAllProjectsByOwnerIdResponse.cs @@ -1,55 +1,55 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using BaseInfoClient.Response.Project; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Data; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; -using Newtonsoft.Json; -using ServiceClient; - -namespace BaseInfoClient.Response.Project -{ - - - public class QueryAllProjectsByOwnerIdResponse - { - [JsonProperty("projectData")] public List ProjectItems { get; set; } = new List(); - } -} - -namespace BaseInfoClient.Extension -{ - public static class QueryAllProjectsByOwnerIdExtension - { - public static async Task> QueryAllProjectsByOwnerIdAsync(this BaseInfoHttpClient client - , int ownerId, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetAllBaseProject?OwnerID={ownerId}&Data.IsGetproject=true"); - - var content = await response.Content.ReadAsStringAsync(); - - return content.FromJsonTo>().Data.ProjectItems; - } - catch (Exception e) - { - LogHelper.Error("根据OwnerId获取小区", e); - - if (throwException) - { - BusinessException.Throw("获取小区信息失败"); - } - else - { - return new List(); - } - } - - return new List(); - } - } +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using BaseInfoClient.Response.Project; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Data; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; +using Newtonsoft.Json; +using ServiceClient; + +namespace BaseInfoClient.Response.Project +{ + + + public class QueryAllProjectsByOwnerIdResponse + { + [JsonProperty("projectData")] public List ProjectItems { get; set; } = new List(); + } +} + +namespace BaseInfoClient.Extension +{ + public static class QueryAllProjectsByOwnerIdExtension + { + public static async Task> QueryAllProjectsByOwnerIdAsync(this BaseInfoHttpClient client + , int ownerId, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetAllBaseProject?OwnerID={ownerId}&Data.IsGetproject=true"); + + var content = await response.Content.ReadAsStringAsync(); + + return content.FromJsonTo>().Data.ProjectItems; + } + catch (Exception e) + { + LogHelper.Error("根据OwnerId获取小区", e); + + if (throwException) + { + BusinessException.Throw("获取小区信息失败"); + } + else + { + return new List(); + } + } + + return new List(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Project/QueryOneProjectByCodeResponse.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Project/QueryOneProjectByCodeResponse.cs index 266cd17..56291ce 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Project/QueryOneProjectByCodeResponse.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Project/QueryOneProjectByCodeResponse.cs @@ -1,53 +1,53 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using BaseInfoClient.Response.Project; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Data; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; -using Newtonsoft.Json; -using ServiceClient; - -namespace BaseInfoClient.Response.Project -{ - public class QueryOneProjectByCodeResponse - { - [JsonProperty("projectData")] public ProjectItem ProjectItem { get; set; } - } -} - -namespace BaseInfoClient.Extension -{ - public static class QueryProjectByCodeResponseExtension - { - public static async Task QueryOneProjectByCodeAsync(this BaseInfoHttpClient client - , int ownerId, int projectCode, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetOneBaseProject?OwnerID={ownerId}&Data.projectCode={projectCode}"); - - var content = await response.Content.ReadAsStringAsync(); - - return content.FromJsonTo>().Data.ProjectItem; - } - catch (Exception e) - { - LogHelper.Error("根据ProjectCode获取小区", e); - - if (throwException) - { - BusinessException.Throw("获取小区信息失败"); - } - else - { - return new ProjectItem(); - } - } - - return new ProjectItem(); - } - } +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using BaseInfoClient.Response.Project; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Data; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; +using Newtonsoft.Json; +using ServiceClient; + +namespace BaseInfoClient.Response.Project +{ + public class QueryOneProjectByCodeResponse + { + [JsonProperty("projectData")] public ProjectItem ProjectItem { get; set; } + } +} + +namespace BaseInfoClient.Extension +{ + public static class QueryProjectByCodeResponseExtension + { + public static async Task QueryOneProjectByCodeAsync(this BaseInfoHttpClient client + , int ownerId, int projectCode, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetOneBaseProject?OwnerID={ownerId}&Data.projectCode={projectCode}"); + + var content = await response.Content.ReadAsStringAsync(); + + return content.FromJsonTo>().Data.ProjectItem; + } + catch (Exception e) + { + LogHelper.Error("根据ProjectCode获取小区", e); + + if (throwException) + { + BusinessException.Throw("获取小区信息失败"); + } + else + { + return new ProjectItem(); + } + } + + return new ProjectItem(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/PropertyEmployee/EmployeeItem.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/PropertyEmployee/EmployeeItem.cs index c5ce277..86474ee 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/PropertyEmployee/EmployeeItem.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/PropertyEmployee/EmployeeItem.cs @@ -1,17 +1,17 @@ -using Newtonsoft.Json; - -namespace ServiceClient.Response.PropertyEmployee -{ - public class EmployeeItem - { - [JsonProperty("ID")] public int UserId { get; set; } - - [JsonProperty("mobile")] public string Mobile { get; set; } = ""; - - [JsonProperty("name")] public string Name { get; set; } = ""; - - [JsonProperty("projectCode")] public int ProjectCode { get; set; } - - [JsonProperty("isInternal")] public bool IsInternal { get; set; } - } +using Newtonsoft.Json; + +namespace ServiceClient.Response.PropertyEmployee +{ + public class EmployeeItem + { + [JsonProperty("ID")] public int UserId { get; set; } + + [JsonProperty("mobile")] public string Mobile { get; set; } = ""; + + [JsonProperty("name")] public string Name { get; set; } = ""; + + [JsonProperty("projectCode")] public int ProjectCode { get; set; } + + [JsonProperty("isInternal")] public bool IsInternal { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/PropertyEmployee/QueryAllEmployeesByOwnerIdResponse.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/PropertyEmployee/QueryAllEmployeesByOwnerIdResponse.cs index 528373a..a5d68f3 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/PropertyEmployee/QueryAllEmployeesByOwnerIdResponse.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/PropertyEmployee/QueryAllEmployeesByOwnerIdResponse.cs @@ -1,57 +1,57 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Data; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using ServiceClient; -using ServiceClient.Response.PropertyEmployee; -using ServiceClient.Response.User; - -namespace ServiceClient.Response.PropertyEmployee -{ - public class QueryAllEmployeesByOwnerIdResponse - { - [JsonProperty("staffData")] - public List EmployeeInfos { get; set; }=new List(); - } -} - - -namespace BaseInfoClient.Extension -{ - public static class QueryAllEmployeesByOwnerIdResponseExtension - { - public static async Task> QueryAllEmployeesByOwnerId(this BaseInfoHttpClient client - , int ownerId, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetAllBasePerson?Data.IsGetSaff=true&OwnerID={ownerId}"); - - var content = await response.Content.ReadAsStringAsync(); - - return content.FromJsonTo>().Data.EmployeeInfos; - } - catch (Exception e) - { - LogHelper.Error("根据OwnerId获取物业员工",e); - - if (throwException) - { - BusinessException.Throw("获取员工信息失败"); - } - else - { - return new List(); - } - } - - return new List(); - } - } +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Data; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using ServiceClient; +using ServiceClient.Response.PropertyEmployee; +using ServiceClient.Response.User; + +namespace ServiceClient.Response.PropertyEmployee +{ + public class QueryAllEmployeesByOwnerIdResponse + { + [JsonProperty("staffData")] + public List EmployeeInfos { get; set; }=new List(); + } +} + + +namespace BaseInfoClient.Extension +{ + public static class QueryAllEmployeesByOwnerIdResponseExtension + { + public static async Task> QueryAllEmployeesByOwnerId(this BaseInfoHttpClient client + , int ownerId, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetAllBasePerson?Data.IsGetSaff=true&OwnerID={ownerId}"); + + var content = await response.Content.ReadAsStringAsync(); + + return content.FromJsonTo>().Data.EmployeeInfos; + } + catch (Exception e) + { + LogHelper.Error("根据OwnerId获取物业员工",e); + + if (throwException) + { + BusinessException.Throw("获取员工信息失败"); + } + else + { + return new List(); + } + } + + return new List(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/PropertyEmployee/QueryEmployeeInfoByUserIdResponse.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/PropertyEmployee/QueryEmployeeInfoByUserIdResponse.cs index 8615df8..9d1136e 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/PropertyEmployee/QueryEmployeeInfoByUserIdResponse.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/PropertyEmployee/QueryEmployeeInfoByUserIdResponse.cs @@ -1,57 +1,57 @@ -using System; -using System.Threading.Tasks; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Data; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; -using Newtonsoft.Json; -using ServiceClient; -using ServiceClient.Response.PropertyEmployee; -using ServiceClient.Response.User; - -namespace ServiceClient.Response.PropertyEmployee -{ - - - public class QueryEmployeeInfoByUserIdResponse - { - [JsonProperty("staffData")] public EmployeeItem UserInfo { get; set; } = new EmployeeItem(); - } -} - -namespace BaseInfoClient.Extension -{ - public static class QueryEmployeeInfoByUserIdResponseExtension - { - public static async Task QueryEmployeeInfoByUserId(this BaseInfoHttpClient client, int ownerId, - int userId, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetOneBasePerson?Data.staffId={userId}&OwnerID={ownerId}"); - - var content = await response.Content.ReadAsStringAsync(); - - return content.FromJsonTo>().Data.UserInfo; - } - catch (Exception e) - { - LogHelper.Error("根据员工Id获取员工信息",e); - - if (throwException) - { - BusinessException.Throw("获取员工信息失败"); - } - else - { - return new EmployeeItem(); - } - } - - return new EmployeeItem(); - } - - - } +using System; +using System.Threading.Tasks; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Data; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; +using Newtonsoft.Json; +using ServiceClient; +using ServiceClient.Response.PropertyEmployee; +using ServiceClient.Response.User; + +namespace ServiceClient.Response.PropertyEmployee +{ + + + public class QueryEmployeeInfoByUserIdResponse + { + [JsonProperty("staffData")] public EmployeeItem UserInfo { get; set; } = new EmployeeItem(); + } +} + +namespace BaseInfoClient.Extension +{ + public static class QueryEmployeeInfoByUserIdResponseExtension + { + public static async Task QueryEmployeeInfoByUserId(this BaseInfoHttpClient client, int ownerId, + int userId, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetOneBasePerson?Data.staffId={userId}&OwnerID={ownerId}"); + + var content = await response.Content.ReadAsStringAsync(); + + return content.FromJsonTo>().Data.UserInfo; + } + catch (Exception e) + { + LogHelper.Error("根据员工Id获取员工信息",e); + + if (throwException) + { + BusinessException.Throw("获取员工信息失败"); + } + else + { + return new EmployeeItem(); + } + } + + return new EmployeeItem(); + } + + + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Room/QueryAllHouseholderRoomsByOwnerIdResponse.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Room/QueryAllHouseholderRoomsByOwnerIdResponse.cs index a371eff..2aa17d0 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Room/QueryAllHouseholderRoomsByOwnerIdResponse.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Room/QueryAllHouseholderRoomsByOwnerIdResponse.cs @@ -1,54 +1,54 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Data; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; -using Newtonsoft.Json; -using ServiceClient; -using ServiceClient.Response.Room; - -namespace ServiceClient.Response.Room -{ - public class QueryAllHouseholderRoomsByOwnerIdResponse - { - [JsonProperty("userToRoomData")] - public List UserRoomItems { get; set; } = new List(); - } -} - -namespace BaseInfoClient.Extension -{ - public static class QueryAllHouseholderRoomsByOwnerIdResponseExtension - { - public static async Task> QueryAllHouseholderRoomsByOwnerId(this BaseInfoHttpClient client - , int ownerId, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetAllBasePerson?Data.IsGetUserToRoom=true&OwnerID={ownerId}"); - - var content = await response.Content.ReadAsStringAsync(); - - return content.FromJsonTo>().Data.UserRoomItems; - } - catch (Exception e) - { - LogHelper.Error("根据UserId获取用户房间信息", e); - - if (throwException) - { - BusinessException.Throw("获取用户房间信息失败"); - } - else - { - return new List(); - } - } - - return new List(); - } - } +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Data; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; +using Newtonsoft.Json; +using ServiceClient; +using ServiceClient.Response.Room; + +namespace ServiceClient.Response.Room +{ + public class QueryAllHouseholderRoomsByOwnerIdResponse + { + [JsonProperty("userToRoomData")] + public List UserRoomItems { get; set; } = new List(); + } +} + +namespace BaseInfoClient.Extension +{ + public static class QueryAllHouseholderRoomsByOwnerIdResponseExtension + { + public static async Task> QueryAllHouseholderRoomsByOwnerId(this BaseInfoHttpClient client + , int ownerId, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetAllBasePerson?Data.IsGetUserToRoom=true&OwnerID={ownerId}"); + + var content = await response.Content.ReadAsStringAsync(); + + return content.FromJsonTo>().Data.UserRoomItems; + } + catch (Exception e) + { + LogHelper.Error("根据UserId获取用户房间信息", e); + + if (throwException) + { + BusinessException.Throw("获取用户房间信息失败"); + } + else + { + return new List(); + } + } + + return new List(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Room/QueryHouseholderRoomsByUserIdResponse.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Room/QueryHouseholderRoomsByUserIdResponse.cs index 6a6eadf..8dbff63 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Room/QueryHouseholderRoomsByUserIdResponse.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Room/QueryHouseholderRoomsByUserIdResponse.cs @@ -1,57 +1,57 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Data; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using ServiceClient; -using ServiceClient.Response.Room; - -namespace ServiceClient.Response.Room -{ - - - public class QueryHouseholderRoomsByUserIdResponse - { - [JsonProperty("userToRoomData")] - public List UserRoomItems { get; set; } = new List(); - } -} - -namespace BaseInfoClient.Extension -{ - public static class QueryHouseholderRoomsByUserIdExtension - { - public static async Task> QueryHouseholderRoomsByUserId(this BaseInfoHttpClient client - , int ownerId, int userId, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetOneBasePerson?Data.userToroomUserId={userId}&OwnerID={ownerId}"); - - var content = await response.Content.ReadAsStringAsync(); - - return content.FromJsonTo>().Data.UserRoomItems; - } - catch (Exception e) - { - LogHelper.Error("根据UserId获取用户房间信息", e); - - if (throwException) - { - BusinessException.Throw("获取用户房间信息失败"); - } - else - { - return new List(); - } - } - - return new List(); - } - } +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Data; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using ServiceClient; +using ServiceClient.Response.Room; + +namespace ServiceClient.Response.Room +{ + + + public class QueryHouseholderRoomsByUserIdResponse + { + [JsonProperty("userToRoomData")] + public List UserRoomItems { get; set; } = new List(); + } +} + +namespace BaseInfoClient.Extension +{ + public static class QueryHouseholderRoomsByUserIdExtension + { + public static async Task> QueryHouseholderRoomsByUserId(this BaseInfoHttpClient client + , int ownerId, int userId, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetOneBasePerson?Data.userToroomUserId={userId}&OwnerID={ownerId}"); + + var content = await response.Content.ReadAsStringAsync(); + + return content.FromJsonTo>().Data.UserRoomItems; + } + catch (Exception e) + { + LogHelper.Error("根据UserId获取用户房间信息", e); + + if (throwException) + { + BusinessException.Throw("获取用户房间信息失败"); + } + else + { + return new List(); + } + } + + return new List(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Room/UserRoomItem.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Room/UserRoomItem.cs index 15ec962..dd0a4e7 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Room/UserRoomItem.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Room/UserRoomItem.cs @@ -1,25 +1,25 @@ -using Newtonsoft.Json; - -namespace ServiceClient.Response.Room -{ - public class UserRoomItem - { - [JsonProperty("userId")] public int UserId { get; set; } - - [JsonProperty("roomCode")] public string RoomCode { get; set; } = ""; - - [JsonProperty("deleteTag")] public int DeleteTag { get; set; } - - [JsonProperty("state")] public int State { get; set; } - - [JsonProperty("floor")] public int Floor { get; set; } - - [JsonProperty("roomNo")] public string RoomNo { get; set; } - - [JsonProperty("projectCode")] public int ProjectCode { get; set; } - - [JsonProperty("buildCode")] public string BuildCode { get; set; } - - [JsonProperty("unit")] public string Unit { get; set; } - } +using Newtonsoft.Json; + +namespace ServiceClient.Response.Room +{ + public class UserRoomItem + { + [JsonProperty("userId")] public int UserId { get; set; } + + [JsonProperty("roomCode")] public string RoomCode { get; set; } = ""; + + [JsonProperty("deleteTag")] public int DeleteTag { get; set; } + + [JsonProperty("state")] public int State { get; set; } + + [JsonProperty("floor")] public int Floor { get; set; } + + [JsonProperty("roomNo")] public string RoomNo { get; set; } + + [JsonProperty("projectCode")] public int ProjectCode { get; set; } + + [JsonProperty("buildCode")] public string BuildCode { get; set; } + + [JsonProperty("unit")] public string Unit { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/User/QueryVisiterAndUserByWxOpenIdResponse.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/User/QueryVisiterAndUserByWxOpenIdResponse.cs index 87f35e5..98be058 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/User/QueryVisiterAndUserByWxOpenIdResponse.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/User/QueryVisiterAndUserByWxOpenIdResponse.cs @@ -1,63 +1,63 @@ -using System; -using System.Threading.Tasks; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Data; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using ServiceClient; -using ServiceClient.Response.Householder; -using ServiceClient.Response.User; - -namespace ServiceClient.Response.User -{ - public class QueryVisiterAndUserByWxOpenIdResponse - { - [JsonProperty("userData")] - public HouseholderItem HouseholderItem { get; set; } - - [JsonProperty("visterData")] - public VisterItem VisterItem { get; set; } - } -} - -namespace BaseInfoClient.Extension -{ - public static class QueryVisiterAndUserByWxOpenIdResponseExtension - { - public static async Task QueryVisiterAndUserByWxOpenId( - this BaseInfoHttpClient client, string openId,bool throwException = false) - { - try - { - var response = - await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetUserVisterByOpenID?openId={openId}"); - //var response = - // await client.CreateHttpClient().GetAsync( - // $"https://localhost:44324/api/baseinfo/v1/BaseData/GetUserVisterByOpenID?openId={openId}"); - - var content = await response.Content.ReadAsStringAsync(); - - return content.FromJsonTo>().Data; - } - catch (Exception e) - { - LogHelper.Error("根据openId查询用户",e); - - if (throwException) - { - BusinessException.Throw("获取用户信息失败"); - } - else - { - return new QueryVisiterAndUserByWxOpenIdResponse(); - } - } - - return new QueryVisiterAndUserByWxOpenIdResponse(); - } - } - +using System; +using System.Threading.Tasks; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Data; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using ServiceClient; +using ServiceClient.Response.Householder; +using ServiceClient.Response.User; + +namespace ServiceClient.Response.User +{ + public class QueryVisiterAndUserByWxOpenIdResponse + { + [JsonProperty("userData")] + public HouseholderItem HouseholderItem { get; set; } + + [JsonProperty("visterData")] + public VisterItem VisterItem { get; set; } + } +} + +namespace BaseInfoClient.Extension +{ + public static class QueryVisiterAndUserByWxOpenIdResponseExtension + { + public static async Task QueryVisiterAndUserByWxOpenId( + this BaseInfoHttpClient client, string openId,bool throwException = false) + { + try + { + var response = + await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetUserVisterByOpenID?openId={openId}"); + //var response = + // await client.CreateHttpClient().GetAsync( + // $"https://localhost:44324/api/baseinfo/v1/BaseData/GetUserVisterByOpenID?openId={openId}"); + + var content = await response.Content.ReadAsStringAsync(); + + return content.FromJsonTo>().Data; + } + catch (Exception e) + { + LogHelper.Error("根据openId查询用户",e); + + if (throwException) + { + BusinessException.Throw("获取用户信息失败"); + } + else + { + return new QueryVisiterAndUserByWxOpenIdResponse(); + } + } + + return new QueryVisiterAndUserByWxOpenIdResponse(); + } + } + } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/User/QueryVisterByVisterIdResponse.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/User/QueryVisterByVisterIdResponse.cs index ab96687..0eb2eef 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/User/QueryVisterByVisterIdResponse.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/User/QueryVisterByVisterIdResponse.cs @@ -1,53 +1,53 @@ -using System; -using System.Threading.Tasks; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Data; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; -using Newtonsoft.Json; -using ServiceClient; -using ServiceClient.Response.User; - - -namespace ServiceClient.Response.User -{ - public class QueryVisterByVisterIdResponse - { - [JsonProperty("visterData")] public VisterItem VisterItem { get; set; } = new VisterItem(); - } -} - -namespace BaseInfoClient.Extension -{ - public static class QueryVisterByVisterIdResponseExtension - { - public static async Task QueryVisterByVisterId(this BaseInfoHttpClient client, int ownerId, - int visterId, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetOneBasePerson?OwnerID={ownerId}&Data.visterId={visterId}"); - - var content = await response.Content.ReadAsStringAsync(); - - return content.FromJsonTo>().Data.VisterItem; - } - catch (Exception e) - { - LogHelper.Error("根据访客Id查询访客信息",e); - - if (throwException) - { - BusinessException.Throw("获取访客信息失败"); - } - else - { - return new VisterItem(); - } - } - - return new VisterItem(); - } - } +using System; +using System.Threading.Tasks; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Data; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; +using Newtonsoft.Json; +using ServiceClient; +using ServiceClient.Response.User; + + +namespace ServiceClient.Response.User +{ + public class QueryVisterByVisterIdResponse + { + [JsonProperty("visterData")] public VisterItem VisterItem { get; set; } = new VisterItem(); + } +} + +namespace BaseInfoClient.Extension +{ + public static class QueryVisterByVisterIdResponseExtension + { + public static async Task QueryVisterByVisterId(this BaseInfoHttpClient client, int ownerId, + int visterId, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetOneBasePerson?OwnerID={ownerId}&Data.visterId={visterId}"); + + var content = await response.Content.ReadAsStringAsync(); + + return content.FromJsonTo>().Data.VisterItem; + } + catch (Exception e) + { + LogHelper.Error("根据访客Id查询访客信息",e); + + if (throwException) + { + BusinessException.Throw("获取访客信息失败"); + } + else + { + return new VisterItem(); + } + } + + return new VisterItem(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/User/VisterItem.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/User/VisterItem.cs index 2fd1978..2eb2c02 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/User/VisterItem.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/User/VisterItem.cs @@ -1,97 +1,97 @@ -using System; -using Newtonsoft.Json; - -namespace ServiceClient.Response.User -{ - public class VisterItem - { - /// - /// 邀请人姓名 - /// - [JsonProperty("username")] - public string UserName { get; set; } - - /// - /// 访客姓名 - /// - [JsonProperty("visitorname")] - public string VisitorName { get; set; } - - /// - /// 访客电话 - /// - [JsonProperty("visitorphone")] - public string VisitorPhone { get; set; } - - /// - /// 20 前台登记 10 用户邀请 30 人脸访问 40员工端邀请 - /// - [JsonProperty("visitortype")] - public int VisitorType { get; set; } - - [JsonProperty("openid")] public string OpenId { get; set; } - - /// - /// 来访日期 - /// - [JsonProperty("entrytime")] - public DateTime EntryTime { get; set; } - - [JsonProperty("expirytime")] public DateTime ExpiryTime { get; set; } - - [JsonProperty("projectcode")] public int ProjectCode { get; set; } - - [JsonProperty("buildcode")] public string BuildCode { get; set; } - - [JsonProperty("unit")] public string Unit { get; set; } - - [JsonProperty("room")] public string Room { get; set; } - - [JsonProperty("reason")] public string Reason { get; set; } - - /// - /// 邀请函模板类型 - /// - [JsonProperty("templatetype")] - public int TemplateType { get; set; } - - /// - /// 10:申请中 20:申请通过 30: 黑名单用户 40:申请作废 - /// - [JsonProperty("stats")] - public int Stats { get; set; } - - /// - /// 访客接受时间 - /// - [JsonProperty("accepttime")] - public DateTime AcceptTime { get; set; } - - /// - /// 备注 - /// - [JsonProperty("bak")] - public string Bak { get; set; } - - /// - /// 微信头像 - /// - [JsonProperty("wxImgUrl")] - public string WxImgUrl { get; set; } - - /// - /// 人脸地址 - /// - [JsonProperty("faceUrl")] - public string FaceUrl { get; set; } - - /// - /// 访客人员ID - /// - [JsonProperty("userId")] - public System.Int32? UserId { get; set; } = 0; - - [JsonProperty("ID")] - public int Id { get; set; } - } +using System; +using Newtonsoft.Json; + +namespace ServiceClient.Response.User +{ + public class VisterItem + { + /// + /// 邀请人姓名 + /// + [JsonProperty("username")] + public string UserName { get; set; } + + /// + /// 访客姓名 + /// + [JsonProperty("visitorname")] + public string VisitorName { get; set; } + + /// + /// 访客电话 + /// + [JsonProperty("visitorphone")] + public string VisitorPhone { get; set; } + + /// + /// 20 前台登记 10 用户邀请 30 人脸访问 40员工端邀请 + /// + [JsonProperty("visitortype")] + public int VisitorType { get; set; } + + [JsonProperty("openid")] public string OpenId { get; set; } + + /// + /// 来访日期 + /// + [JsonProperty("entrytime")] + public DateTime EntryTime { get; set; } + + [JsonProperty("expirytime")] public DateTime ExpiryTime { get; set; } + + [JsonProperty("projectcode")] public int ProjectCode { get; set; } + + [JsonProperty("buildcode")] public string BuildCode { get; set; } + + [JsonProperty("unit")] public string Unit { get; set; } + + [JsonProperty("room")] public string Room { get; set; } + + [JsonProperty("reason")] public string Reason { get; set; } + + /// + /// 邀请函模板类型 + /// + [JsonProperty("templatetype")] + public int TemplateType { get; set; } + + /// + /// 10:申请中 20:申请通过 30: 黑名单用户 40:申请作废 + /// + [JsonProperty("stats")] + public int Stats { get; set; } + + /// + /// 访客接受时间 + /// + [JsonProperty("accepttime")] + public DateTime AcceptTime { get; set; } + + /// + /// 备注 + /// + [JsonProperty("bak")] + public string Bak { get; set; } + + /// + /// 微信头像 + /// + [JsonProperty("wxImgUrl")] + public string WxImgUrl { get; set; } + + /// + /// 人脸地址 + /// + [JsonProperty("faceUrl")] + public string FaceUrl { get; set; } + + /// + /// 访客人员ID + /// + [JsonProperty("userId")] + public System.Int32? UserId { get; set; } = 0; + + [JsonProperty("ID")] + public int Id { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Visitor/QueryVisitorByOpenidOrId.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Visitor/QueryVisitorByOpenidOrId.cs index 7298347..e59a762 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Visitor/QueryVisitorByOpenidOrId.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Visitor/QueryVisitorByOpenidOrId.cs @@ -1,145 +1,145 @@ -using BaseInfoClient.Response.Visitor; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Data; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; -using ServiceClient; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json; - - -namespace BaseInfoClient.Extension -{ - public static class QueryVisitorByOpenidOrId - { - public static async Task> QueryVisitorByOpenId(this BaseInfoHttpClient client - , QueryMenJinVisitorRequest param, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/visitor/v1/Request/QueryByOpenId?OwnerId={param.OwnerId}&Data.OpenId={param.OpenId}"); - - var content = await response.Content.ReadAsStringAsync(); - var result = content.FromJsonTo>>(); - return result.Data; - } - catch (Exception e) - { - LogHelper.Error("根据OwnerId获取住户", e); - - if (throwException) - { - BusinessException.Throw("获取住户信息失败"); - } - else - { - return new List(); - } - } - return new List(); - } - - public static async Task QueryVisitorById(this BaseInfoHttpClient client - , QueryMenJinVisitorRequest param, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/visitor/v1/Request/QueryById?OwnerId={param.OwnerId}&Data.Id={param.Id}&Data.Type={param.Type}"); - - var content = await response.Content.ReadAsStringAsync(); - var result = content.FromJsonTo>(); - return result.Data; - } - catch (Exception e) - { - LogHelper.Error("根据OwnerId获取住户", e); - - if (throwException) - { - BusinessException.Throw("获取住户信息失败"); - } - else - { - return new VisitorResponseItem(); - } - } - return new VisitorResponseItem(); - } - - /// - /// 根据人脸ID获取访客信息 - /// - /// - /// - /// - /// - public static async Task QueryVisitorByFaceId(this BaseInfoHttpClient client - , int ownerId,string faceId, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/visitor/v1/Request/QueryByFaceId?OwnerId={ownerId}&Data.FaceId={faceId}"); - - var content = await response.Content.ReadAsStringAsync(); - var result = content.FromJsonTo>(); - return result.Data; - } - catch (Exception e) - { - LogHelper.Error("根据OwnerId获取住户", e); - - if (throwException) - { - BusinessException.Throw("获取住户信息失败"); - } - else - { - return new VisitorResponseItem(); - } - } - return new VisitorResponseItem(); - } - - - /// - /// 根据人脸ID获取访客信息 - /// - /// - /// - /// - /// - public static async Task> QueryVisitorProFace(this BaseInfoHttpClient client - , int projectCode, string buildCode,string unit,int operaterID, int ownerID, bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/doorway/v1/device/GetFacesClient?OperaterID={operaterID}&OwnerID={ownerID}&Data.ProjectCode={projectCode}&Data.BuildCode={buildCode}&Data.Unit={unit}&Data.UserType=0"); - - var content = await response.Content.ReadAsStringAsync(); - var result = content.FromJsonTo>>(); - return result.Data; - } - catch (Exception e) - { - LogHelper.Error("根据OwnerId获取住户", e); - - if (throwException) - { - BusinessException.Throw("获取住户设备信息失败"); - } - else - { - return new List(); - } - } - return new List(); - } - } -} +using BaseInfoClient.Response.Visitor; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Data; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; +using ServiceClient; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json; + + +namespace BaseInfoClient.Extension +{ + public static class QueryVisitorByOpenidOrId + { + public static async Task> QueryVisitorByOpenId(this BaseInfoHttpClient client + , QueryMenJinVisitorRequest param, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/visitor/v1/Request/QueryByOpenId?OwnerId={param.OwnerId}&Data.OpenId={param.OpenId}"); + + var content = await response.Content.ReadAsStringAsync(); + var result = content.FromJsonTo>>(); + return result.Data; + } + catch (Exception e) + { + LogHelper.Error("根据OwnerId获取住户", e); + + if (throwException) + { + BusinessException.Throw("获取住户信息失败"); + } + else + { + return new List(); + } + } + return new List(); + } + + public static async Task QueryVisitorById(this BaseInfoHttpClient client + , QueryMenJinVisitorRequest param, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/visitor/v1/Request/QueryById?OwnerId={param.OwnerId}&Data.Id={param.Id}&Data.Type={param.Type}"); + + var content = await response.Content.ReadAsStringAsync(); + var result = content.FromJsonTo>(); + return result.Data; + } + catch (Exception e) + { + LogHelper.Error("根据OwnerId获取住户", e); + + if (throwException) + { + BusinessException.Throw("获取住户信息失败"); + } + else + { + return new VisitorResponseItem(); + } + } + return new VisitorResponseItem(); + } + + /// + /// 根据人脸ID获取访客信息 + /// + /// + /// + /// + /// + public static async Task QueryVisitorByFaceId(this BaseInfoHttpClient client + , int ownerId,string faceId, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/visitor/v1/Request/QueryByFaceId?OwnerId={ownerId}&Data.FaceId={faceId}"); + + var content = await response.Content.ReadAsStringAsync(); + var result = content.FromJsonTo>(); + return result.Data; + } + catch (Exception e) + { + LogHelper.Error("根据OwnerId获取住户", e); + + if (throwException) + { + BusinessException.Throw("获取住户信息失败"); + } + else + { + return new VisitorResponseItem(); + } + } + return new VisitorResponseItem(); + } + + + /// + /// 根据人脸ID获取访客信息 + /// + /// + /// + /// + /// + public static async Task> QueryVisitorProFace(this BaseInfoHttpClient client + , int projectCode, string buildCode,string unit,int operaterID, int ownerID, bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/doorway/v1/device/GetFacesClient?OperaterID={operaterID}&OwnerID={ownerID}&Data.ProjectCode={projectCode}&Data.BuildCode={buildCode}&Data.Unit={unit}&Data.UserType=0"); + + var content = await response.Content.ReadAsStringAsync(); + var result = content.FromJsonTo>>(); + return result.Data; + } + catch (Exception e) + { + LogHelper.Error("根据OwnerId获取住户", e); + + if (throwException) + { + BusinessException.Throw("获取住户设备信息失败"); + } + else + { + return new List(); + } + } + return new List(); + } + } +} diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/Visitor/VisitorItem.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/Visitor/VisitorItem.cs index 632e1ec..4ec5093 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/Visitor/VisitorItem.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/Visitor/VisitorItem.cs @@ -1,56 +1,56 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace BaseInfoClient.Response.Visitor -{ - public class VisitorResponseItem - { - public int Id { get; set; } - - public DateTime ExpiryTime { get; set; } - public DateTime EntryTime { get; set; } - public string Unit { get; set; } - public string BuildCode { get; set; } - public int ProjectCode { get; set; } - /// - /// 10邀约 20申请 - /// - public int Type { get; set; } - public string Reason { get; set; } - public string VisitorName { get; set; } - /// - /// 访客电话 - /// - public string VisitorPhone { get; set; } - public int CheckUserId { get; set; } - /// - /// 审核人姓名 - /// - public string CheckUserName { get; set; } - public string Room { get; set; } - /// - /// 状态 10 审核中 20 已通过 30 已拒绝 - /// - public int State { get; set; } - } - public class QueryMenJinVisitorRequest - { - public int Id { get; set; } - public string OpenId { get; set; } - public DateTime InTime { get; set; } - /// - /// 10 申请 20 邀约 - /// - public int Type { get; set; } - public int OwnerId { get; set; } - } - - public class QueryDeviceByBuildResponse - { - public string Ip { get; set; } - public string PassWord { get; set; } - public string DeviceNo { get; set; } - public int Port { get; set; } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace BaseInfoClient.Response.Visitor +{ + public class VisitorResponseItem + { + public int Id { get; set; } + + public DateTime ExpiryTime { get; set; } + public DateTime EntryTime { get; set; } + public string Unit { get; set; } + public string BuildCode { get; set; } + public int ProjectCode { get; set; } + /// + /// 10邀约 20申请 + /// + public int Type { get; set; } + public string Reason { get; set; } + public string VisitorName { get; set; } + /// + /// 访客电话 + /// + public string VisitorPhone { get; set; } + public int CheckUserId { get; set; } + /// + /// 审核人姓名 + /// + public string CheckUserName { get; set; } + public string Room { get; set; } + /// + /// 状态 10 审核中 20 已通过 30 已拒绝 + /// + public int State { get; set; } + } + public class QueryMenJinVisitorRequest + { + public int Id { get; set; } + public string OpenId { get; set; } + public DateTime InTime { get; set; } + /// + /// 10 申请 20 邀约 + /// + public int Type { get; set; } + public int OwnerId { get; set; } + } + + public class QueryDeviceByBuildResponse + { + public string Ip { get; set; } + public string PassWord { get; set; } + public string DeviceNo { get; set; } + public int Port { get; set; } + } +} diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/`Build/BuildItem.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/`Build/BuildItem.cs index ed3d823..7ff4f89 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/`Build/BuildItem.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/`Build/BuildItem.cs @@ -1,13 +1,13 @@ -using Newtonsoft.Json; - -namespace BaseInfoClient.Response.Build -{ - public class BuildItem - { - [JsonProperty("projectCode")] public int ProjectCode { get; set; } - - [JsonProperty("buildCode")] public string BuildCode { get; set; } = ""; - - [JsonProperty("name")] public string Name { get; set; } = ""; - } +using Newtonsoft.Json; + +namespace BaseInfoClient.Response.Build +{ + public class BuildItem + { + [JsonProperty("projectCode")] public int ProjectCode { get; set; } + + [JsonProperty("buildCode")] public string BuildCode { get; set; } = ""; + + [JsonProperty("name")] public string Name { get; set; } = ""; + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/BaseInfoClient/Response/`Build/QueryAllBuildsByOwnerIdResponse.cs b/Infrastructure/ServiceClient/BaseInfoClient/Response/`Build/QueryAllBuildsByOwnerIdResponse.cs index 9d77178..bc0e4d9 100644 --- a/Infrastructure/ServiceClient/BaseInfoClient/Response/`Build/QueryAllBuildsByOwnerIdResponse.cs +++ b/Infrastructure/ServiceClient/BaseInfoClient/Response/`Build/QueryAllBuildsByOwnerIdResponse.cs @@ -1,55 +1,55 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using BaseInfoClient.Response.Build; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Data; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; -using Newtonsoft.Json; -using ServiceClient; - -namespace BaseInfoClient.Response.Build -{ - - - public class QueryAllBuildsByOwnerIdResponse - { - [JsonProperty("buildData")] public List BuildItems { get; set; } = new List(); - } -} - -namespace BaseInfoClient.Extension -{ - public static class QuerAllyBuildsByOwnerIdExtension - { - public static async Task> QueryAllBuildsByOwnerIdAsync(this BaseInfoHttpClient client, int ownerId, - bool throwException = false) - { - try - { - var response = await client.CreateHttpClient().GetAsync( - $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetAllBaseProject?OwnerID={ownerId}&Data.IsGetBuild=true"); - - var content = await response.Content.ReadAsStringAsync(); - - return content.FromJsonTo>().Data.BuildItems; - } - catch (Exception e) - { - LogHelper.Error("根据OwnerId获取楼宇", e); - - if (throwException) - { - BusinessException.Throw("获取楼宇信息失败"); - } - else - { - return new List(); - } - } - - return new List(); - } - } +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using BaseInfoClient.Response.Build; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Data; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; +using Newtonsoft.Json; +using ServiceClient; + +namespace BaseInfoClient.Response.Build +{ + + + public class QueryAllBuildsByOwnerIdResponse + { + [JsonProperty("buildData")] public List BuildItems { get; set; } = new List(); + } +} + +namespace BaseInfoClient.Extension +{ + public static class QuerAllyBuildsByOwnerIdExtension + { + public static async Task> QueryAllBuildsByOwnerIdAsync(this BaseInfoHttpClient client, int ownerId, + bool throwException = false) + { + try + { + var response = await client.CreateHttpClient().GetAsync( + $"{client.BaseUrl}/api/baseinfo/v1/BaseData/GetAllBaseProject?OwnerID={ownerId}&Data.IsGetBuild=true"); + + var content = await response.Content.ReadAsStringAsync(); + + return content.FromJsonTo>().Data.BuildItems; + } + catch (Exception e) + { + LogHelper.Error("根据OwnerId获取楼宇", e); + + if (throwException) + { + BusinessException.Throw("获取楼宇信息失败"); + } + else + { + return new List(); + } + } + + return new List(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/DataBodyAttribute.cs b/Infrastructure/ServiceClient/MsgCenterClient/DataBodyAttribute.cs index f6a11ec..79e0f9d 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/DataBodyAttribute.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/DataBodyAttribute.cs @@ -1,14 +1,14 @@ -using System; - -namespace MsgCenterClient -{ - public class DataBodyAttribute : Attribute - { - public int Order { get; } - - public DataBodyAttribute(int order) - { - Order = order; - } - } +using System; + +namespace MsgCenterClient +{ + public class DataBodyAttribute : Attribute + { + public int Order { get; } + + public DataBodyAttribute(int order) + { + Order = order; + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/IServiceCollectionExtension.cs b/Infrastructure/ServiceClient/MsgCenterClient/IServiceCollectionExtension.cs index 39dd6fd..06b8b4f 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/IServiceCollectionExtension.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/IServiceCollectionExtension.cs @@ -1,14 +1,14 @@ -using Microsoft.Extensions.DependencyInjection; - -namespace MsgCenterClient -{ - public static class IServiceCollectionExtension - { - public static void AddMsgCenterClient(this IServiceCollection service, string baseUrl) - { - MsgCenterHttpClient._BaseUrl = baseUrl; - - service.AddSingleton(); - } - } +using Microsoft.Extensions.DependencyInjection; + +namespace MsgCenterClient +{ + public static class IServiceCollectionExtension + { + public static void AddMsgCenterClient(this IServiceCollection service, string baseUrl) + { + MsgCenterHttpClient._BaseUrl = baseUrl; + + service.AddSingleton(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/MsgCenterClient.csproj b/Infrastructure/ServiceClient/MsgCenterClient/MsgCenterClient.csproj index 7a39c51..16e0fe8 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/MsgCenterClient.csproj +++ b/Infrastructure/ServiceClient/MsgCenterClient/MsgCenterClient.csproj @@ -1,15 +1,15 @@ - - - - netcoreapp2.2 - - - - - - - - - - - + + + + netcoreapp2.2 + + + + + + + + + + + diff --git a/Infrastructure/ServiceClient/MsgCenterClient/MsgCenterHttpClient.cs b/Infrastructure/ServiceClient/MsgCenterClient/MsgCenterHttpClient.cs index d9913d1..f3aa21b 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/MsgCenterHttpClient.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/MsgCenterHttpClient.cs @@ -1,79 +1,79 @@ -using System; -using System.Net.Http; -using System.Threading.Tasks; -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Extension; -using Hncore.Infrastructure.Serializer; -using Hncore.Infrastructure.WebApi; -using MsgCenterClient.WechatMpTplMsg; - -namespace MsgCenterClient -{ - public class MsgCenterHttpClient - { - private IHttpClientFactory _httpClientFactory; - - internal static string _BaseUrl = ""; - - public string BaseUrl => _BaseUrl; - - public MsgCenterHttpClient(IHttpClientFactory httpClientFactory) - { - _httpClientFactory = httpClientFactory; - } - - private HttpClient CreateHttpClient() - { - return _httpClientFactory.CreateClient(); - } - - /// - /// 发送微信公众号模板消息 - /// - /// - /// - public async Task SendWechatMpTplMsg(MsgBase msgBase) - { - var body = msgBase.ToRequestObject(); - - try - { - var res = await CreateHttpClient() - .PostAsJsonGetString(BaseUrl + "/api/msgcenter/v1/msg/SendMPTplMessage", body); - - return res.FromJsonTo(); - } - catch (Exception e) - { - LogHelper.Error("发送微信公众号模板消息失败", e + "\n消息内容:\n" + body.ToJson(true)); - - return new ApiResult(ResultCode.C_UNKNOWN_ERROR); - } - } - - /// - /// 发送微信小程序模板消息 - /// - /// - /// - public async Task SendMiniAppTplMsg(MiniAppMsgBase msgBase) - { - var body = msgBase.ToRequestObject(); - - try - { - var res = await CreateHttpClient() - .PostAsJsonGetString(BaseUrl + "/api/msgcenter/v1/msg/SendMiniAppTplMessage", body); - - return res.FromJsonTo(); - } - catch (Exception e) - { - LogHelper.Error("发送小程序模板消息失败", e + "\n消息内容:\n" + body.ToJson(true)); - - return new ApiResult(ResultCode.C_UNKNOWN_ERROR); - } - } - - } +using System; +using System.Net.Http; +using System.Threading.Tasks; +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Extension; +using Hncore.Infrastructure.Serializer; +using Hncore.Infrastructure.WebApi; +using MsgCenterClient.WechatMpTplMsg; + +namespace MsgCenterClient +{ + public class MsgCenterHttpClient + { + private IHttpClientFactory _httpClientFactory; + + internal static string _BaseUrl = ""; + + public string BaseUrl => _BaseUrl; + + public MsgCenterHttpClient(IHttpClientFactory httpClientFactory) + { + _httpClientFactory = httpClientFactory; + } + + private HttpClient CreateHttpClient() + { + return _httpClientFactory.CreateClient(); + } + + /// + /// 发送微信公众号模板消息 + /// + /// + /// + public async Task SendWechatMpTplMsg(MsgBase msgBase) + { + var body = msgBase.ToRequestObject(); + + try + { + var res = await CreateHttpClient() + .PostAsJsonGetString(BaseUrl + "/api/msgcenter/v1/msg/SendMPTplMessage", body); + + return res.FromJsonTo(); + } + catch (Exception e) + { + LogHelper.Error("发送微信公众号模板消息失败", e + "\n消息内容:\n" + body.ToJson(true)); + + return new ApiResult(ResultCode.C_UNKNOWN_ERROR); + } + } + + /// + /// 发送微信小程序模板消息 + /// + /// + /// + public async Task SendMiniAppTplMsg(MiniAppMsgBase msgBase) + { + var body = msgBase.ToRequestObject(); + + try + { + var res = await CreateHttpClient() + .PostAsJsonGetString(BaseUrl + "/api/msgcenter/v1/msg/SendMiniAppTplMessage", body); + + return res.FromJsonTo(); + } + catch (Exception e) + { + LogHelper.Error("发送小程序模板消息失败", e + "\n消息内容:\n" + body.ToJson(true)); + + return new ApiResult(ResultCode.C_UNKNOWN_ERROR); + } + } + + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMiniAppTplMsg/FangKeShenHeMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMiniAppTplMsg/FangKeShenHeMsg.cs index e5856cb..78e5bbc 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMiniAppTplMsg/FangKeShenHeMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMiniAppTplMsg/FangKeShenHeMsg.cs @@ -1,50 +1,50 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 访客审核通知 - /// 模板编号:ku4vArgTpMOvwBeKQpjj6iE1nhVJyHL9xeQUjkUv5sY - /// 公众号模板库模板标题:认证成功通知 - /// - public class FangKeShenHeMsg : MiniAppMsgBase - { - public FangKeShenHeMsg(int ownerId, string appId, string openId) - : base("ku4vArgTpMOvwBeKQpjj6iE1nhVJyHL9xeQUjkUv5sY", ownerId, appId, openId) - { - } - - /// - /// 审核结果 - /// - [DataBody(1)] - public DataItem ShenHeJieGuo { get; set; } - - /// - /// 受访单位 - /// - [DataBody(2)] - public DataItem ShouFangDanWei { get; set; } - - /// - /// 事由 - /// - [DataBody(3)] - public DataItem ShiYou { get; set; } - - /// - /// 访客姓名 - /// - [DataBody(4)] - public DataItem FangKeXingMing { get; set; } - - /// - /// 手机号 - /// - [DataBody(5)] - public DataItem ShouJi { get; set; } - /// - /// 备注 - /// - [DataBody(6)] - public DataItem BeiZhu { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 访客审核通知 + /// 模板编号:ku4vArgTpMOvwBeKQpjj6iE1nhVJyHL9xeQUjkUv5sY + /// 公众号模板库模板标题:认证成功通知 + /// + public class FangKeShenHeMsg : MiniAppMsgBase + { + public FangKeShenHeMsg(int ownerId, string appId, string openId) + : base("ku4vArgTpMOvwBeKQpjj6iE1nhVJyHL9xeQUjkUv5sY", ownerId, appId, openId) + { + } + + /// + /// 审核结果 + /// + [DataBody(1)] + public DataItem ShenHeJieGuo { get; set; } + + /// + /// 受访单位 + /// + [DataBody(2)] + public DataItem ShouFangDanWei { get; set; } + + /// + /// 事由 + /// + [DataBody(3)] + public DataItem ShiYou { get; set; } + + /// + /// 访客姓名 + /// + [DataBody(4)] + public DataItem FangKeXingMing { get; set; } + + /// + /// 手机号 + /// + [DataBody(5)] + public DataItem ShouJi { get; set; } + /// + /// 备注 + /// + [DataBody(6)] + public DataItem BeiZhu { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMiniAppTplMsg/MsgBase.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMiniAppTplMsg/MsgBase.cs index 8f10b2b..1dd9c43 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMiniAppTplMsg/MsgBase.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMiniAppTplMsg/MsgBase.cs @@ -1,102 +1,102 @@ -using System.Collections.Generic; -using System.Linq; - -namespace MsgCenterClient.WechatMpTplMsg -{ - public class MiniAppMsgBase - { - /// - /// - /// - /// 模板Id - /// 物业Id - /// 公众号AppId - /// 用户OpenId - public MiniAppMsgBase(string templateId, int ownerId, string appId, string openId) - { - TemplateId = templateId; - OwnerId = ownerId; - AppId = appId; - OpenId = openId; - } - - /// - /// 模板Id - /// - public string TemplateId { get; } - - /// - /// 物业Id - /// - public int OwnerId { get; } - - /// - /// 公众号AppId - /// - public string AppId { get; } - - /// - /// 用户openId - /// - public string OpenId { get; } - - /// - /// 跳转的小程序页面 - /// - public string Page { get; set; } - - /// - /// 表单id - /// - public string FormId { get; set; } - - /// - /// 强调的字,可以为空 - /// - public string EmphasisKeyword { get; set; } - - public object ToRequestObject() - { - SortedDictionary bodyDic = new SortedDictionary(); - - var type = GetType(); - var properties = type.GetProperties(); - - foreach (var property in properties) - { - var bodyAttr = property.GetCustomAttributes(typeof(DataBodyAttribute), false); - - if (!bodyAttr.Any()) - { - continue; - } - - int order = ((DataBodyAttribute) bodyAttr[0]).Order; - - DataItem value = property.GetValue(this, null) as DataItem; - - if (value == null) - { - value = new DataItem(); - } - - bodyDic[order] = value; - } - - return new - { - key = TemplateId, - OwnerId = OwnerId, - From = AppId, - To = OpenId, - Content = new - { - page=this.Page, - form_id=this.FormId, - emphasis_keyword=this.EmphasisKeyword, - items = bodyDic.Values.Select(t => new {value = t.Value, color = t.Color}).ToList() - } - }; - } - } +using System.Collections.Generic; +using System.Linq; + +namespace MsgCenterClient.WechatMpTplMsg +{ + public class MiniAppMsgBase + { + /// + /// + /// + /// 模板Id + /// 物业Id + /// 公众号AppId + /// 用户OpenId + public MiniAppMsgBase(string templateId, int ownerId, string appId, string openId) + { + TemplateId = templateId; + OwnerId = ownerId; + AppId = appId; + OpenId = openId; + } + + /// + /// 模板Id + /// + public string TemplateId { get; } + + /// + /// 物业Id + /// + public int OwnerId { get; } + + /// + /// 公众号AppId + /// + public string AppId { get; } + + /// + /// 用户openId + /// + public string OpenId { get; } + + /// + /// 跳转的小程序页面 + /// + public string Page { get; set; } + + /// + /// 表单id + /// + public string FormId { get; set; } + + /// + /// 强调的字,可以为空 + /// + public string EmphasisKeyword { get; set; } + + public object ToRequestObject() + { + SortedDictionary bodyDic = new SortedDictionary(); + + var type = GetType(); + var properties = type.GetProperties(); + + foreach (var property in properties) + { + var bodyAttr = property.GetCustomAttributes(typeof(DataBodyAttribute), false); + + if (!bodyAttr.Any()) + { + continue; + } + + int order = ((DataBodyAttribute) bodyAttr[0]).Order; + + DataItem value = property.GetValue(this, null) as DataItem; + + if (value == null) + { + value = new DataItem(); + } + + bodyDic[order] = value; + } + + return new + { + key = TemplateId, + OwnerId = OwnerId, + From = AppId, + To = OpenId, + Content = new + { + page=this.Page, + form_id=this.FormId, + emphasis_keyword=this.EmphasisKeyword, + items = bodyDic.Values.Select(t => new {value = t.Value, color = t.Color}).ToList() + } + }; + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/AssetDeductMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/AssetDeductMsg.cs index a115ff0..5d0d290 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/AssetDeductMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/AssetDeductMsg.cs @@ -1,68 +1,68 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 虚拟资产冲抵成功通知 - /// 模板编号:OPENTM417732701 - /// - public class AssetDeductSuccessMsg : MsgBase - { - public AssetDeductSuccessMsg(int ownerId, string appId, string openId) - : base("OPENTM417732701", ownerId, appId, openId) - { - } - - /// - /// 账单应缴总金额 - /// - [DataBody(1)] - public DataItem Amount { get; set; } - - /// - /// 当前余额(账单金额冲抵后结存金额) - /// - [DataBody(2)] - public DataItem BalanceAmount { get; set; } - - /// - /// 扣款时间(账单冲抵完成时间) - /// - [DataBody(3)] - public DataItem SuccessTime { get; set; } - - /// - /// 扣款方式(默认为:余额冲抵) - /// - [DataBody(4)] - public DataItem PayType { get; set; }=new DataItem(){Value = "余额冲抵"}; - } - - /// - /// 虚拟资产冲抵失败通知 - /// 模板编号:OPENTM414769357 - /// - public class AssetDeductFailMsg : MsgBase - { - public AssetDeductFailMsg(int ownerId, string appId, string openId) - : base("OPENTM414769357", ownerId, appId, openId) - { - } - - /// - /// 扣费时间(所有账单扣费失败时间) - /// - [DataBody(1)] - public DataItem FailTime { get; set; } - - /// - /// 扣费金额(所有冲抵失败账单的金额总和) - /// - [DataBody(2)] - public DataItem Amount { get; set; } - - /// - /// 账户余额(虚拟帐户中剩余金额) - /// - [DataBody(3)] - public DataItem BalanceAmount { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 虚拟资产冲抵成功通知 + /// 模板编号:OPENTM417732701 + /// + public class AssetDeductSuccessMsg : MsgBase + { + public AssetDeductSuccessMsg(int ownerId, string appId, string openId) + : base("OPENTM417732701", ownerId, appId, openId) + { + } + + /// + /// 账单应缴总金额 + /// + [DataBody(1)] + public DataItem Amount { get; set; } + + /// + /// 当前余额(账单金额冲抵后结存金额) + /// + [DataBody(2)] + public DataItem BalanceAmount { get; set; } + + /// + /// 扣款时间(账单冲抵完成时间) + /// + [DataBody(3)] + public DataItem SuccessTime { get; set; } + + /// + /// 扣款方式(默认为:余额冲抵) + /// + [DataBody(4)] + public DataItem PayType { get; set; }=new DataItem(){Value = "余额冲抵"}; + } + + /// + /// 虚拟资产冲抵失败通知 + /// 模板编号:OPENTM414769357 + /// + public class AssetDeductFailMsg : MsgBase + { + public AssetDeductFailMsg(int ownerId, string appId, string openId) + : base("OPENTM414769357", ownerId, appId, openId) + { + } + + /// + /// 扣费时间(所有账单扣费失败时间) + /// + [DataBody(1)] + public DataItem FailTime { get; set; } + + /// + /// 扣费金额(所有冲抵失败账单的金额总和) + /// + [DataBody(2)] + public DataItem Amount { get; set; } + + /// + /// 账户余额(虚拟帐户中剩余金额) + /// + [DataBody(3)] + public DataItem BalanceAmount { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/CheLiangShenHeShiBaiMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/CheLiangShenHeShiBaiMsg.cs index cf5c818..2b8e878 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/CheLiangShenHeShiBaiMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/CheLiangShenHeShiBaiMsg.cs @@ -1,27 +1,27 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 车辆审核不通过通知 - /// 模板编号:OPENTM408157154 - /// 公众号模板库模板标题:审核不过通知 - /// - public class CheLiangShenHeShiBaiMsg: MsgBase - { - public CheLiangShenHeShiBaiMsg(int ownerId, string appId, string openId) - : base("OPENTM408157154", ownerId, appId, openId) - { - } - - /// - /// 姓名 - /// - [DataBody(1)] - public DataItem XingMing { get; set; } - - /// - /// 手机号 - /// - [DataBody(2)] - public DataItem ShouJiHao { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 车辆审核不通过通知 + /// 模板编号:OPENTM408157154 + /// 公众号模板库模板标题:审核不过通知 + /// + public class CheLiangShenHeShiBaiMsg: MsgBase + { + public CheLiangShenHeShiBaiMsg(int ownerId, string appId, string openId) + : base("OPENTM408157154", ownerId, appId, openId) + { + } + + /// + /// 姓名 + /// + [DataBody(1)] + public DataItem XingMing { get; set; } + + /// + /// 手机号 + /// + [DataBody(2)] + public DataItem ShouJiHao { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/CheLiangShenHeTiJiaoMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/CheLiangShenHeTiJiaoMsg.cs index 43a7e28..d8e7572 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/CheLiangShenHeTiJiaoMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/CheLiangShenHeTiJiaoMsg.cs @@ -1,27 +1,27 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 车辆审核申请提交成功通知 - /// 模板编号:OPENTM411517700 - /// 公众号模板库模板标题:申请提交成功通知 - /// - public class CheLiangShenHeTiJiaoMsg: MsgBase - { - public CheLiangShenHeTiJiaoMsg(int ownerId, string appId, string openId) - : base("OPENTM411517700", ownerId, appId, openId) - { - } - - /// - /// 服务类型 - /// - [DataBody(1)] - public DataItem FuWuLeiXing { get; set; } - - /// - /// 提交时间 - /// - [DataBody(2)] - public DataItem TiJiaoShiJian { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 车辆审核申请提交成功通知 + /// 模板编号:OPENTM411517700 + /// 公众号模板库模板标题:申请提交成功通知 + /// + public class CheLiangShenHeTiJiaoMsg: MsgBase + { + public CheLiangShenHeTiJiaoMsg(int ownerId, string appId, string openId) + : base("OPENTM411517700", ownerId, appId, openId) + { + } + + /// + /// 服务类型 + /// + [DataBody(1)] + public DataItem FuWuLeiXing { get; set; } + + /// + /// 提交时间 + /// + [DataBody(2)] + public DataItem TiJiaoShiJian { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/CheLiangShenHeTongGuoMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/CheLiangShenHeTongGuoMsg.cs index 9cd56af..2122686 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/CheLiangShenHeTongGuoMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/CheLiangShenHeTongGuoMsg.cs @@ -1,39 +1,39 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 车辆审核通过通知 - /// 模板编号:OPENTM416664350 - /// 公众号模板库模板标题:审核通过提醒 - /// - public class CheLiangShenHeTongGuoMsg: MsgBase - { - public CheLiangShenHeTongGuoMsg( int ownerId, string appId, string openId) - : base("OPENTM416664350", ownerId, appId, openId) - { - } - - /// - /// 姓名 - /// - [DataBody(1)] - public DataItem XingMing { get; set; } - - /// - /// 手机号 - /// - [DataBody(2)] - public DataItem ShouJiHao { get; set; } - - /// - /// 车牌号 - /// - [DataBody(3)] - public DataItem ChePaiHao { get; set; } - - /// - /// 审核时间 - /// - [DataBody(4)] - public DataItem ShenHeShiJian { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 车辆审核通过通知 + /// 模板编号:OPENTM416664350 + /// 公众号模板库模板标题:审核通过提醒 + /// + public class CheLiangShenHeTongGuoMsg: MsgBase + { + public CheLiangShenHeTongGuoMsg( int ownerId, string appId, string openId) + : base("OPENTM416664350", ownerId, appId, openId) + { + } + + /// + /// 姓名 + /// + [DataBody(1)] + public DataItem XingMing { get; set; } + + /// + /// 手机号 + /// + [DataBody(2)] + public DataItem ShouJiHao { get; set; } + + /// + /// 车牌号 + /// + [DataBody(3)] + public DataItem ChePaiHao { get; set; } + + /// + /// 审核时间 + /// + [DataBody(4)] + public DataItem ShenHeShiJian { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/DataItem.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/DataItem.cs index aecce67..c00bd76 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/DataItem.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/DataItem.cs @@ -1,28 +1,28 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - public class DataItem - { - public string Value { get; set; } = ""; - - // - // 摘要: - // 16进制颜色代码,如:#FF0000 - public string Color { get; set; } = "#173177"; - - public DataItem() - { - - } - - public DataItem(string value) - { - Value = value; - } - - public DataItem(string value, string color) - { - Value = value; - Color = color; - } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + public class DataItem + { + public string Value { get; set; } = ""; + + // + // 摘要: + // 16进制颜色代码,如:#FF0000 + public string Color { get; set; } = "#173177"; + + public DataItem() + { + + } + + public DataItem(string value) + { + Value = value; + } + + public DataItem(string value, string color) + { + Value = value; + Color = color; + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/FangKeDengJiTongZhi.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/FangKeDengJiTongZhi.cs index d5fd7dc..e057ffb 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/FangKeDengJiTongZhi.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/FangKeDengJiTongZhi.cs @@ -1,36 +1,36 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace MsgCenterClient.WechatMpTplMsg -{ - public class FangKeDengJiTongZhi : MsgBase - { - public FangKeDengJiTongZhi(int ownerId, string appId, string openId) - : base("OPENTM417110808", ownerId, appId, openId) - { - - } - - /// - /// 标题 - /// - [DataBody(1)] - public DataItem Name { get; set; } - /// - /// 标题 - /// - [DataBody(2)] - public DataItem Company { get; set; } - /// - /// 标题 - /// - [DataBody(3)] - public DataItem Reason { get; set; } - /// - /// 标题 - /// - [DataBody(4)] - public DataItem Time { get; set; } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace MsgCenterClient.WechatMpTplMsg +{ + public class FangKeDengJiTongZhi : MsgBase + { + public FangKeDengJiTongZhi(int ownerId, string appId, string openId) + : base("OPENTM417110808", ownerId, appId, openId) + { + + } + + /// + /// 标题 + /// + [DataBody(1)] + public DataItem Name { get; set; } + /// + /// 标题 + /// + [DataBody(2)] + public DataItem Company { get; set; } + /// + /// 标题 + /// + [DataBody(3)] + public DataItem Reason { get; set; } + /// + /// 标题 + /// + [DataBody(4)] + public DataItem Time { get; set; } + } +} diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/FangWuRenZhengChengGongMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/FangWuRenZhengChengGongMsg.cs index 0c0a42e..9aecf60 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/FangWuRenZhengChengGongMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/FangWuRenZhengChengGongMsg.cs @@ -1,33 +1,33 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 房屋认证成功通知 - /// 模板编号:OPENTM403179452 - /// 公众号模板库模板标题:认证成功通知 - /// - public class FangWuRenZhengChengGongMsg : MsgBase - { - public FangWuRenZhengChengGongMsg(int ownerId, string appId, string openId) - : base("OPENTM403179452", ownerId, appId, openId) - { - } - - /// - /// 认证类型 - /// - [DataBody(1)] - public DataItem RenZhengLeiXing { get; set; } - - /// - /// 审核结果 - /// - [DataBody(2)] - public DataItem ShenHeJieGuo { get; set; } - - /// - /// 审核时间 - /// - [DataBody(3)] - public DataItem ShenHeShiJian { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 房屋认证成功通知 + /// 模板编号:OPENTM403179452 + /// 公众号模板库模板标题:认证成功通知 + /// + public class FangWuRenZhengChengGongMsg : MsgBase + { + public FangWuRenZhengChengGongMsg(int ownerId, string appId, string openId) + : base("OPENTM403179452", ownerId, appId, openId) + { + } + + /// + /// 认证类型 + /// + [DataBody(1)] + public DataItem RenZhengLeiXing { get; set; } + + /// + /// 审核结果 + /// + [DataBody(2)] + public DataItem ShenHeJieGuo { get; set; } + + /// + /// 审核时间 + /// + [DataBody(3)] + public DataItem ShenHeShiJian { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/FangWuRenZhengShiBaiMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/FangWuRenZhengShiBaiMsg.cs index 9726095..aa82651 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/FangWuRenZhengShiBaiMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/FangWuRenZhengShiBaiMsg.cs @@ -1,39 +1,39 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 房屋认证失败通知 - /// 模板编号:OPENTM403179639 - /// 公众号模板库模板标题:认证失败通知 - /// - public class FangWuRenZhengShiBaiMsg: MsgBase - { - public FangWuRenZhengShiBaiMsg(int ownerId, string appId, string openId) - : base("OPENTM403179639", ownerId, appId, openId) - { - } - - /// - /// 认证类型 - /// - [DataBody(1)] - public DataItem RenZhengLeiXing { get; set; } - - /// - /// 审核结果 - /// - [DataBody(2)] - public DataItem ShenHeJieGuo { get; set; } - - /// - /// 审核时间 - /// - [DataBody(3)] - public DataItem ShenHeShiJian { get; set; } - - /// - /// 结果描述 - /// - [DataBody(4)] - public DataItem JieGuoMiaoShu { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 房屋认证失败通知 + /// 模板编号:OPENTM403179639 + /// 公众号模板库模板标题:认证失败通知 + /// + public class FangWuRenZhengShiBaiMsg: MsgBase + { + public FangWuRenZhengShiBaiMsg(int ownerId, string appId, string openId) + : base("OPENTM403179639", ownerId, appId, openId) + { + } + + /// + /// 认证类型 + /// + [DataBody(1)] + public DataItem RenZhengLeiXing { get; set; } + + /// + /// 审核结果 + /// + [DataBody(2)] + public DataItem ShenHeJieGuo { get; set; } + + /// + /// 审核时间 + /// + [DataBody(3)] + public DataItem ShenHeShiJian { get; set; } + + /// + /// 结果描述 + /// + [DataBody(4)] + public DataItem JieGuoMiaoShu { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/GongDanWanJieMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/GongDanWanJieMsg.cs index 3dca16e..84d95a4 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/GongDanWanJieMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/GongDanWanJieMsg.cs @@ -1,33 +1,33 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 工单处理完结 - /// 模板编号:OPENTM201820050 - /// 公众号模板库模板标题:工单进度通知 - /// - public class GongDanWanJieMsg: MsgBase - { - public GongDanWanJieMsg( int ownerId, string appId, string openId) - : base("OPENTM201820050", ownerId, appId, openId) - { - } - - /// - /// 工单号 - /// - [DataBody(1)] - public DataItem GongDanHao { get; set; } - - /// - /// 工单进度 - /// - [DataBody(2)] - public DataItem GongDanJinDu { get; set; } - - /// - /// 工单处理人 - /// - [DataBody(3)] - public DataItem GongDanChuLiRen { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 工单处理完结 + /// 模板编号:OPENTM201820050 + /// 公众号模板库模板标题:工单进度通知 + /// + public class GongDanWanJieMsg: MsgBase + { + public GongDanWanJieMsg( int ownerId, string appId, string openId) + : base("OPENTM201820050", ownerId, appId, openId) + { + } + + /// + /// 工单号 + /// + [DataBody(1)] + public DataItem GongDanHao { get; set; } + + /// + /// 工单进度 + /// + [DataBody(2)] + public DataItem GongDanJinDu { get; set; } + + /// + /// 工单处理人 + /// + [DataBody(3)] + public DataItem GongDanChuLiRen { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/JiaoFeiChengGongMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/JiaoFeiChengGongMsg.cs index c5eecea..2c81b8a 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/JiaoFeiChengGongMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/JiaoFeiChengGongMsg.cs @@ -1,33 +1,33 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 缴费成功通知 - /// 模板编号:OPENTM412117951 - /// 公众号模板库模板标题:缴费成功通知 - /// - public class JiaoFeiChengGongMsg : MsgBase - { - public JiaoFeiChengGongMsg(int ownerId, string appId, string openId) - : base("OPENTM412117951", ownerId, appId, openId) - { - } - - /// - /// 缴费时间 - /// - [DataBody(1)] - public DataItem JiaoFeiShiJian { get; set; } - - /// - /// 缴费方式 - /// - [DataBody(2)] - public DataItem JiaoFeiFangShi { get; set; } - - /// - /// 缴费金额 - /// - [DataBody(3)] - public DataItem JiaoFeiJinE { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 缴费成功通知 + /// 模板编号:OPENTM412117951 + /// 公众号模板库模板标题:缴费成功通知 + /// + public class JiaoFeiChengGongMsg : MsgBase + { + public JiaoFeiChengGongMsg(int ownerId, string appId, string openId) + : base("OPENTM412117951", ownerId, appId, openId) + { + } + + /// + /// 缴费时间 + /// + [DataBody(1)] + public DataItem JiaoFeiShiJian { get; set; } + + /// + /// 缴费方式 + /// + [DataBody(2)] + public DataItem JiaoFeiFangShi { get; set; } + + /// + /// 缴费金额 + /// + [DataBody(3)] + public DataItem JiaoFeiJinE { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/JieDanMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/JieDanMsg.cs index cb581cd..68ba4cb 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/JieDanMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/JieDanMsg.cs @@ -1,33 +1,33 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 接单通知 - /// 模板编号:OPENTM201820050 - /// 公众号模板库模板标题:工单进度通知 - /// - public class JieDanMsg: MsgBase - { - public JieDanMsg(int ownerId, string appId, string openId) - : base("OPENTM201820050", ownerId, appId, openId) - { - } - - /// - /// 工单号 - /// - [DataBody(1)] - public DataItem GongDanHao { get; set; } - - /// - /// 工单进度 - /// - [DataBody(2)] - public DataItem GongDanJinDu { get; set; } - - /// - /// 工单处理人 - /// - [DataBody(3)] - public DataItem GongDanChuLiRen { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 接单通知 + /// 模板编号:OPENTM201820050 + /// 公众号模板库模板标题:工单进度通知 + /// + public class JieDanMsg: MsgBase + { + public JieDanMsg(int ownerId, string appId, string openId) + : base("OPENTM201820050", ownerId, appId, openId) + { + } + + /// + /// 工单号 + /// + [DataBody(1)] + public DataItem GongDanHao { get; set; } + + /// + /// 工单进度 + /// + [DataBody(2)] + public DataItem GongDanJinDu { get; set; } + + /// + /// 工单处理人 + /// + [DataBody(3)] + public DataItem GongDanChuLiRen { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/LinShiDaoFangMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/LinShiDaoFangMsg.cs index 6f49b19..674aed9 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/LinShiDaoFangMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/LinShiDaoFangMsg.cs @@ -1,33 +1,33 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 临时到访通知 - /// 模板编号:5NE7oojOE4jhUpv8bixYqWgfkqcOInVBTjb_lHWPrSw - /// 公众号模板库模板标题:物业管理通知 - /// - public class LinShiDaoFangMsg: MsgBase - { - public LinShiDaoFangMsg(int ownerId, string appId, string openId) - : base("5NE7oojOE4jhUpv8bixYqWgfkqcOInVBTjb_lHWPrSw", ownerId, appId, openId) - { - } - - /// - /// 标题 - /// - [DataBody(1)] - public DataItem BiaoTi { get; set; } - - /// - /// 发布时间 - /// - [DataBody(2)] - public DataItem FaBuShiJian { get; set; } - - /// - /// 内容 - /// - [DataBody(3)] - public DataItem NeiRong { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 临时到访通知 + /// 模板编号:5NE7oojOE4jhUpv8bixYqWgfkqcOInVBTjb_lHWPrSw + /// 公众号模板库模板标题:物业管理通知 + /// + public class LinShiDaoFangMsg: MsgBase + { + public LinShiDaoFangMsg(int ownerId, string appId, string openId) + : base("5NE7oojOE4jhUpv8bixYqWgfkqcOInVBTjb_lHWPrSw", ownerId, appId, openId) + { + } + + /// + /// 标题 + /// + [DataBody(1)] + public DataItem BiaoTi { get; set; } + + /// + /// 发布时间 + /// + [DataBody(2)] + public DataItem FaBuShiJian { get; set; } + + /// + /// 内容 + /// + [DataBody(3)] + public DataItem NeiRong { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/MenJinYaoShiShouQuanMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/MenJinYaoShiShouQuanMsg.cs index 2efdadc..aa1c528 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/MenJinYaoShiShouQuanMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/MenJinYaoShiShouQuanMsg.cs @@ -1,33 +1,33 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 门禁钥匙授权通知 - /// 模板编号:OPENTM408634701 - /// 公众号模板库模板标题:授权成功通知 - /// - public class MenJinYaoShiShouQuanMsg: MsgBase - { - public MenJinYaoShiShouQuanMsg( int ownerId, string appId, string openId) - : base("OPENTM408634701", ownerId, appId, openId) - { - } - - /// - /// 授权人 - /// - [DataBody(1)] - public DataItem ShouQunRen { get; set; } - - /// - /// 被授权人 - /// - [DataBody(2)] - public DataItem BeiShouQunRen { get; set; } - - /// - /// 授权状态 - /// - [DataBody(3)] - public DataItem ShouQuanZhuangTai { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 门禁钥匙授权通知 + /// 模板编号:OPENTM408634701 + /// 公众号模板库模板标题:授权成功通知 + /// + public class MenJinYaoShiShouQuanMsg: MsgBase + { + public MenJinYaoShiShouQuanMsg( int ownerId, string appId, string openId) + : base("OPENTM408634701", ownerId, appId, openId) + { + } + + /// + /// 授权人 + /// + [DataBody(1)] + public DataItem ShouQunRen { get; set; } + + /// + /// 被授权人 + /// + [DataBody(2)] + public DataItem BeiShouQunRen { get; set; } + + /// + /// 授权状态 + /// + [DataBody(3)] + public DataItem ShouQuanZhuangTai { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/MsgBase.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/MsgBase.cs index 4caf0d7..bb9276a 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/MsgBase.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/MsgBase.cs @@ -1,117 +1,117 @@ -using System.Collections.Generic; -using System.Linq; - -namespace MsgCenterClient.WechatMpTplMsg -{ - public class MsgBase - { - /// - /// - /// - /// 模板Id - /// 物业Id - /// 公众号AppId - /// 用户OpenId - public MsgBase(string templateId, int ownerId, string appId, string openId) - { - TemplateId = templateId; - OwnerId = ownerId; - AppId = appId; - OpenId = openId; - } - - /// - /// 头部内容 - /// - public DataItem Head { get; set; } - - /// - /// 底部内容 - /// - public DataItem Foot { get; set; } - - /// - /// 模板Id - /// - public string TemplateId { get; } - - /// - /// 物业Id - /// - public int OwnerId { get; } - - /// - /// 公众号AppId - /// - public string AppId { get; } - - /// - /// 用户openId - /// - public string OpenId { get; } - - /// - /// 跳转的Url - /// - public string Url { get; set; } - - /// - /// 跳转的小程序的Appid,为空的话默认跳转h5指定的url - /// - public string MiniAppId { get; set; } - - - public object ToRequestObject() - { - SortedDictionary bodyDic = new SortedDictionary(); - - var type = GetType(); - var properties = type.GetProperties(); - - foreach (var property in properties) - { - var bodyAttr = property.GetCustomAttributes(typeof(DataBodyAttribute), false); - - if (!bodyAttr.Any()) - { - continue; - } - - int order = ((DataBodyAttribute) bodyAttr[0]).Order; - - DataItem value = property.GetValue(this, null) as DataItem; - - if (value == null) - { - value = new DataItem(); - } - - bodyDic[order] = value; - } - - return new - { - key = TemplateId, - Content = new - { - Url, - MiniAppId, - first = new - { - value = Head?.Value, - color = Head?.Color - }, - remark = new - { - value = Foot?.Value, - color = Foot?.Color - }, - items = bodyDic.Values.Select(t => new {value = t.Value, color = t.Color}).ToList() - }, - OwnerId = OwnerId, - From = AppId, - To = OpenId - }; - } - } +using System.Collections.Generic; +using System.Linq; + +namespace MsgCenterClient.WechatMpTplMsg +{ + public class MsgBase + { + /// + /// + /// + /// 模板Id + /// 物业Id + /// 公众号AppId + /// 用户OpenId + public MsgBase(string templateId, int ownerId, string appId, string openId) + { + TemplateId = templateId; + OwnerId = ownerId; + AppId = appId; + OpenId = openId; + } + + /// + /// 头部内容 + /// + public DataItem Head { get; set; } + + /// + /// 底部内容 + /// + public DataItem Foot { get; set; } + + /// + /// 模板Id + /// + public string TemplateId { get; } + + /// + /// 物业Id + /// + public int OwnerId { get; } + + /// + /// 公众号AppId + /// + public string AppId { get; } + + /// + /// 用户openId + /// + public string OpenId { get; } + + /// + /// 跳转的Url + /// + public string Url { get; set; } + + /// + /// 跳转的小程序的Appid,为空的话默认跳转h5指定的url + /// + public string MiniAppId { get; set; } + + + public object ToRequestObject() + { + SortedDictionary bodyDic = new SortedDictionary(); + + var type = GetType(); + var properties = type.GetProperties(); + + foreach (var property in properties) + { + var bodyAttr = property.GetCustomAttributes(typeof(DataBodyAttribute), false); + + if (!bodyAttr.Any()) + { + continue; + } + + int order = ((DataBodyAttribute) bodyAttr[0]).Order; + + DataItem value = property.GetValue(this, null) as DataItem; + + if (value == null) + { + value = new DataItem(); + } + + bodyDic[order] = value; + } + + return new + { + key = TemplateId, + Content = new + { + Url, + MiniAppId, + first = new + { + value = Head?.Value, + color = Head?.Color + }, + remark = new + { + value = Foot?.Value, + color = Foot?.Color + }, + items = bodyDic.Values.Select(t => new {value = t.Value, color = t.Color}).ToList() + }, + OwnerId = OwnerId, + From = AppId, + To = OpenId + }; + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/PaiGongMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/PaiGongMsg.cs index 599d795..7f5f346 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/PaiGongMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/PaiGongMsg.cs @@ -1,33 +1,33 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 派工通知 - /// 模板编号:OPENTM201820050 - /// 公众号模板库模板标题:工单进度通知 - /// - public class PaiGongMsg: MsgBase - { - public PaiGongMsg( int ownerId, string appId, string openId) - : base("OPENTM201820050", ownerId, appId, openId) - { - } - - /// - /// 工单号 - /// - [DataBody(1)] - public DataItem GongDanHao { get; set; } - - /// - /// 工单进度 - /// - [DataBody(2)] - public DataItem GongDanJinDu { get; set; } - - /// - /// 工单处理人 - /// - [DataBody(3)] - public DataItem GongDanChuLiRen { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 派工通知 + /// 模板编号:OPENTM201820050 + /// 公众号模板库模板标题:工单进度通知 + /// + public class PaiGongMsg: MsgBase + { + public PaiGongMsg( int ownerId, string appId, string openId) + : base("OPENTM201820050", ownerId, appId, openId) + { + } + + /// + /// 工单号 + /// + [DataBody(1)] + public DataItem GongDanHao { get; set; } + + /// + /// 工单进度 + /// + [DataBody(2)] + public DataItem GongDanJinDu { get; set; } + + /// + /// 工单处理人 + /// + [DataBody(3)] + public DataItem GongDanChuLiRen { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/RenLianRenZhengChengGongMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/RenLianRenZhengChengGongMsg.cs index 1a54557..66d4690 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/RenLianRenZhengChengGongMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/RenLianRenZhengChengGongMsg.cs @@ -1,33 +1,33 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 人脸钥匙认证成功通知 - /// 模板编号:OPENTM403179452 - /// 公众号模板库模板标题:认证成功通知 - /// - public class RenLianRenZhengChengGongMsg: MsgBase - { - public RenLianRenZhengChengGongMsg( int ownerId, string appId, string openId) - : base("OPENTM403179452", ownerId, appId, openId) - { - } - - /// - /// 认证类型 - /// - [DataBody(1)] - public DataItem RenZhengLeiXing { get; set; } - - /// - /// 审核结果 - /// - [DataBody(2)] - public DataItem ShenHeJieGuo { get; set; } - - /// - /// 审核时间 - /// - [DataBody(3)] - public DataItem ShenHeShiJian { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 人脸钥匙认证成功通知 + /// 模板编号:OPENTM403179452 + /// 公众号模板库模板标题:认证成功通知 + /// + public class RenLianRenZhengChengGongMsg: MsgBase + { + public RenLianRenZhengChengGongMsg( int ownerId, string appId, string openId) + : base("OPENTM403179452", ownerId, appId, openId) + { + } + + /// + /// 认证类型 + /// + [DataBody(1)] + public DataItem RenZhengLeiXing { get; set; } + + /// + /// 审核结果 + /// + [DataBody(2)] + public DataItem ShenHeJieGuo { get; set; } + + /// + /// 审核时间 + /// + [DataBody(3)] + public DataItem ShenHeShiJian { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/RenLianRenZhengShiBaiMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/RenLianRenZhengShiBaiMsg.cs index 82e0ee6..067e54d 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/RenLianRenZhengShiBaiMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/RenLianRenZhengShiBaiMsg.cs @@ -1,39 +1,39 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 人脸钥匙认证失败通知 - /// 模板编号:OPENTM403179639 - /// 公众号模板库模板标题:认证失败通知 - /// - public class RenLianRenZhengShiBaiMsg: MsgBase - { - public RenLianRenZhengShiBaiMsg( int ownerId, string appId, string openId) - : base("OPENTM403179639", ownerId, appId, openId) - { - } - - /// - /// 认证类型 - /// - [DataBody(1)] - public DataItem RenZhengLeiXing { get; set; } - - /// - /// 审核结果 - /// - [DataBody(2)] - public DataItem ShenHeJieGuo { get; set; } - - /// - /// 审核时间 - /// - [DataBody(3)] - public DataItem ShenHeShiJian { get; set; } - - /// - /// 结果描述 - /// - [DataBody(4)] - public DataItem JieGuoMiaoShu { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 人脸钥匙认证失败通知 + /// 模板编号:OPENTM403179639 + /// 公众号模板库模板标题:认证失败通知 + /// + public class RenLianRenZhengShiBaiMsg: MsgBase + { + public RenLianRenZhengShiBaiMsg( int ownerId, string appId, string openId) + : base("OPENTM403179639", ownerId, appId, openId) + { + } + + /// + /// 认证类型 + /// + [DataBody(1)] + public DataItem RenZhengLeiXing { get; set; } + + /// + /// 审核结果 + /// + [DataBody(2)] + public DataItem ShenHeJieGuo { get; set; } + + /// + /// 审核时间 + /// + [DataBody(3)] + public DataItem ShenHeShiJian { get; set; } + + /// + /// 结果描述 + /// + [DataBody(4)] + public DataItem JieGuoMiaoShu { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/ShouDongCuiJiaoMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/ShouDongCuiJiaoMsg.cs index c1764c6..3b59075 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/ShouDongCuiJiaoMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/ShouDongCuiJiaoMsg.cs @@ -1,27 +1,27 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 催费通知(手动催缴) - /// 模板编号:OPENTM411227201 - /// 公众号模板库模板标题:待付账单通知 - /// - public class ShouDongCuiJiaoMsg : MsgBase - { - public ShouDongCuiJiaoMsg(int ownerId, string appId, string openId) - : base("OPENTM411227201", ownerId, appId, openId) - { - } - - /// - /// 账单金额 - /// - [DataBody(1)] - public DataItem ZhangDanJinE { get; set; } - - /// - /// 账单日期 - /// - [DataBody(2)] - public DataItem ZhangDanRiQi { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 催费通知(手动催缴) + /// 模板编号:OPENTM411227201 + /// 公众号模板库模板标题:待付账单通知 + /// + public class ShouDongCuiJiaoMsg : MsgBase + { + public ShouDongCuiJiaoMsg(int ownerId, string appId, string openId) + : base("OPENTM411227201", ownerId, appId, openId) + { + } + + /// + /// 账单金额 + /// + [DataBody(1)] + public DataItem ZhangDanJinE { get; set; } + + /// + /// 账单日期 + /// + [DataBody(2)] + public DataItem ZhangDanRiQi { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/YaoYueDaoFangMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/YaoYueDaoFangMsg.cs index 1776c71..e061672 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/YaoYueDaoFangMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/YaoYueDaoFangMsg.cs @@ -1,33 +1,33 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 邀请访客到访通知 - /// 模板编号:rKssp0BPmK-XmGXCbrh3f6e9NVpb75Zqzui8Hcx26dE - /// 公众号模板库模板标题:来访通知 - /// - public class YaoYueDaoFangMsg: MsgBase - { - public YaoYueDaoFangMsg(int ownerId, string appId, string openId) - : base("OPENTM408101810", ownerId, appId, openId) - { - } - - /// - /// 访客名称 - /// - [DataBody(1)] - public DataItem FangKeMingCheng { get; set; } - - /// - /// 访客电话 - /// - [DataBody(2)] - public DataItem FangKeDianHua { get; set; } - - /// - /// 来访时间 - /// - [DataBody(3)] - public DataItem LaiFangShiJian { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 邀请访客到访通知 + /// 模板编号:rKssp0BPmK-XmGXCbrh3f6e9NVpb75Zqzui8Hcx26dE + /// 公众号模板库模板标题:来访通知 + /// + public class YaoYueDaoFangMsg: MsgBase + { + public YaoYueDaoFangMsg(int ownerId, string appId, string openId) + : base("OPENTM408101810", ownerId, appId, openId) + { + } + + /// + /// 访客名称 + /// + [DataBody(1)] + public DataItem FangKeMingCheng { get; set; } + + /// + /// 访客电话 + /// + [DataBody(2)] + public DataItem FangKeDianHua { get; set; } + + /// + /// 来访时间 + /// + [DataBody(3)] + public DataItem LaiFangShiJian { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/ZiDongCuiJiaoMsg.cs b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/ZiDongCuiJiaoMsg.cs index 54d65e1..dad0b83 100644 --- a/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/ZiDongCuiJiaoMsg.cs +++ b/Infrastructure/ServiceClient/MsgCenterClient/WechatMpTplMsg/ZiDongCuiJiaoMsg.cs @@ -1,27 +1,27 @@ -namespace MsgCenterClient.WechatMpTplMsg -{ - /// - /// 催费通知(自动催缴) - /// 模板编号:OPENTM411227201 - /// 公众号模板库模板标题:待付账单通知 - /// - public class ZiDongCuiJiaoMsg : MsgBase - { - public ZiDongCuiJiaoMsg(int ownerId, string appId, string openId) - : base("OPENTM411227201", ownerId, appId, openId) - { - } - - /// - /// 账单金额 - /// - [DataBody(1)] - public DataItem ZhangDanJinE { get; set; } - - /// - /// 账单日期 - /// - [DataBody(2)] - public DataItem ZhangDanRiQi { get; set; } - } +namespace MsgCenterClient.WechatMpTplMsg +{ + /// + /// 催费通知(自动催缴) + /// 模板编号:OPENTM411227201 + /// 公众号模板库模板标题:待付账单通知 + /// + public class ZiDongCuiJiaoMsg : MsgBase + { + public ZiDongCuiJiaoMsg(int ownerId, string appId, string openId) + : base("OPENTM411227201", ownerId, appId, openId) + { + } + + /// + /// 账单金额 + /// + [DataBody(1)] + public DataItem ZhangDanJinE { get; set; } + + /// + /// 账单日期 + /// + [DataBody(2)] + public DataItem ZhangDanRiQi { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/DaiFu.cs b/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/DaiFu.cs index 7f9416f..a6c08da 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/DaiFu.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/DaiFu.cs @@ -1,26 +1,26 @@ -using System.Threading.Tasks; -using Hncore.Infrastructure.Extension; -using Hncore.Infrastructure.Serializer; -using Hncore.Infrastructure.WebApi; -using Hncore.Payment.Request; -using PaymentCenterClient; - -namespace Hncore.Payment.ClientExtension -{ - public static class DaiFu - { - /// - /// 单笔代付 - /// - /// - /// - /// - public static async Task SingleDaiFu(this PaymentCenterHttpClient client, SingleDaiFuRequest request) - { - var res = await client.CreateHttpClient() - .PostAsJsonGetString($"{client.BaseUrl}api/paymentcenter/v1/ZhongXin/DaiFu/SingleDaiFu", request); - - return res.FromJsonTo(); - } - } +using System.Threading.Tasks; +using Hncore.Infrastructure.Extension; +using Hncore.Infrastructure.Serializer; +using Hncore.Infrastructure.WebApi; +using Hncore.Payment.Request; +using PaymentCenterClient; + +namespace Hncore.Payment.ClientExtension +{ + public static class DaiFu + { + /// + /// 单笔代付 + /// + /// + /// + /// + public static async Task SingleDaiFu(this PaymentCenterHttpClient client, SingleDaiFuRequest request) + { + var res = await client.CreateHttpClient() + .PostAsJsonGetString($"{client.BaseUrl}api/paymentcenter/v1/ZhongXin/DaiFu/SingleDaiFu", request); + + return res.FromJsonTo(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/EPay.cs b/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/EPay.cs index 574cf47..56dc653 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/EPay.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/EPay.cs @@ -1,27 +1,27 @@ -using Hncore.Payment.Request; -using System.Threading.Tasks; -using Hncore.Infrastructure.Extension; -using Hncore.Infrastructure.Serializer; -using Hncore.Infrastructure.WebApi; -using PaymentCenterClient; - -namespace Hncore.Payment.ClientExtension -{ - public static class EPay - { - /// - /// 创建Pos机订单(推送订单到Pos机) - /// - /// - /// - /// - public static async Task CreatePosOrder(this PaymentCenterHttpClient client, - EPayCreateOrderRequest request) - { - var res = await client.CreateHttpClient() - .PostAsJsonGetString($"{client.BaseUrl}api/paymentcenter/v1/EPay/PushOrder", request); - - return res.FromJsonTo(); - } - } +using Hncore.Payment.Request; +using System.Threading.Tasks; +using Hncore.Infrastructure.Extension; +using Hncore.Infrastructure.Serializer; +using Hncore.Infrastructure.WebApi; +using PaymentCenterClient; + +namespace Hncore.Payment.ClientExtension +{ + public static class EPay + { + /// + /// 创建Pos机订单(推送订单到Pos机) + /// + /// + /// + /// + public static async Task CreatePosOrder(this PaymentCenterHttpClient client, + EPayCreateOrderRequest request) + { + var res = await client.CreateHttpClient() + .PostAsJsonGetString($"{client.BaseUrl}api/paymentcenter/v1/EPay/PushOrder", request); + + return res.FromJsonTo(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/OffLinePay.cs b/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/OffLinePay.cs index cf877c6..c3704c2 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/OffLinePay.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/OffLinePay.cs @@ -1,26 +1,26 @@ -using System.Threading.Tasks; -using Hncore.Infrastructure.Extension; -using Hncore.Infrastructure.Serializer; -using Hncore.Infrastructure.WebApi; -using Hncore.Payment.Request; -using PaymentCenterClient; - -namespace Hncore.Payment.ClientExtension -{ - /// - /// 线下支付 - /// - public static class OffLinePay - { - public static async Task CreateOffLinePaySuccessedRecord(this PaymentCenterHttpClient client, - CreateOffLinePaySuccessedRecordRequest request) - { - var res = await client.CreateHttpClient() - .PostAsJsonGetString( - $"{client.BaseUrl}api/paymentcenter/v1/Payment/CreateOffLinePaySuccessedRecord", - request); - - return res.FromJsonTo(); - } - } +using System.Threading.Tasks; +using Hncore.Infrastructure.Extension; +using Hncore.Infrastructure.Serializer; +using Hncore.Infrastructure.WebApi; +using Hncore.Payment.Request; +using PaymentCenterClient; + +namespace Hncore.Payment.ClientExtension +{ + /// + /// 线下支付 + /// + public static class OffLinePay + { + public static async Task CreateOffLinePaySuccessedRecord(this PaymentCenterHttpClient client, + CreateOffLinePaySuccessedRecordRequest request) + { + var res = await client.CreateHttpClient() + .PostAsJsonGetString( + $"{client.BaseUrl}api/paymentcenter/v1/Payment/CreateOffLinePaySuccessedRecord", + request); + + return res.FromJsonTo(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/QrPay.cs b/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/QrPay.cs index 436bc78..a233d70 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/QrPay.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/QrPay.cs @@ -1,30 +1,30 @@ -using System.Threading.Tasks; -using Hncore.Infrastructure.Extension; -using Hncore.Infrastructure.Serializer; -using Hncore.Infrastructure.WebApi; -using Hncore.Payment.Request; -using Hncore.Payment.Response; -using PaymentCenterClient; - -namespace Hncore.Payment.ClientExtension -{ - public static class QrPay - { - /// - /// 扫码支付下单 - /// - /// - /// - /// - public static async Task> QrPayCreateOrder( - this PaymentCenterHttpClient client, - QrPayCreateOrderRequest request) - { - var res = await client.CreateHttpClient() - .PostAsJsonGetString($"{client.BaseUrl}api/paymentcenter/v1/QrPay/CreateOrder", - request); - - return res.FromJsonTo>(); - } - } +using System.Threading.Tasks; +using Hncore.Infrastructure.Extension; +using Hncore.Infrastructure.Serializer; +using Hncore.Infrastructure.WebApi; +using Hncore.Payment.Request; +using Hncore.Payment.Response; +using PaymentCenterClient; + +namespace Hncore.Payment.ClientExtension +{ + public static class QrPay + { + /// + /// 扫码支付下单 + /// + /// + /// + /// + public static async Task> QrPayCreateOrder( + this PaymentCenterHttpClient client, + QrPayCreateOrderRequest request) + { + var res = await client.CreateHttpClient() + .PostAsJsonGetString($"{client.BaseUrl}api/paymentcenter/v1/QrPay/CreateOrder", + request); + + return res.FromJsonTo>(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/QueryOrder.cs b/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/QueryOrder.cs index 022dad5..b205bc1 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/QueryOrder.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/QueryOrder.cs @@ -1,26 +1,26 @@ -using System.Threading.Tasks; -using Hncore.Infrastructure.Serializer; -using Hncore.Infrastructure.WebApi; -using Hncore.Payment.Response; -using PaymentCenterClient; - -namespace Hncore.Payment.ClientExtension -{ - public static class QueryOrderExtension - { - /// - /// 订单查询 - /// - /// - /// - /// - public static async Task> QueryOrder(this PaymentCenterHttpClient client, - string orderNo) - { - var res = await client.CreateHttpClient() - .GetStringAsync($"{client.BaseUrl}api/paymentcenter/v1/Payment/QueryOrder?orderNo={orderNo}"); - - return res.FromJsonTo>(); - } - } +using System.Threading.Tasks; +using Hncore.Infrastructure.Serializer; +using Hncore.Infrastructure.WebApi; +using Hncore.Payment.Response; +using PaymentCenterClient; + +namespace Hncore.Payment.ClientExtension +{ + public static class QueryOrderExtension + { + /// + /// 订单查询 + /// + /// + /// + /// + public static async Task> QueryOrder(this PaymentCenterHttpClient client, + string orderNo) + { + var res = await client.CreateHttpClient() + .GetStringAsync($"{client.BaseUrl}api/paymentcenter/v1/Payment/QueryOrder?orderNo={orderNo}"); + + return res.FromJsonTo>(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/SwipeCard.cs b/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/SwipeCard.cs index 721d51b..d586a62 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/SwipeCard.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/SwipeCard.cs @@ -1,26 +1,26 @@ -using System.Threading.Tasks; -using Hncore.Infrastructure.Extension; -using Hncore.Infrastructure.Serializer; -using Hncore.Infrastructure.WebApi; -using Hncore.Payment.Request; -using PaymentCenterClient; - -namespace Hncore.Payment.ClientExtension -{ - public static class SwipeCard - { - /// - /// 刷卡支付下单 - /// - /// - /// - /// - public static async Task SwipeCardCreateOrder(this PaymentCenterHttpClient client, SwipeCardCreateOrderRequest request) - { - var res = await client.CreateHttpClient() - .PostAsJsonGetString($"{client.BaseUrl}api/paymentcenter/v1/SwipeCard/CreateOrder", request); - - return res.FromJsonTo(); - } - } +using System.Threading.Tasks; +using Hncore.Infrastructure.Extension; +using Hncore.Infrastructure.Serializer; +using Hncore.Infrastructure.WebApi; +using Hncore.Payment.Request; +using PaymentCenterClient; + +namespace Hncore.Payment.ClientExtension +{ + public static class SwipeCard + { + /// + /// 刷卡支付下单 + /// + /// + /// + /// + public static async Task SwipeCardCreateOrder(this PaymentCenterHttpClient client, SwipeCardCreateOrderRequest request) + { + var res = await client.CreateHttpClient() + .PostAsJsonGetString($"{client.BaseUrl}api/paymentcenter/v1/SwipeCard/CreateOrder", request); + + return res.FromJsonTo(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/WechatJsPay.cs b/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/WechatJsPay.cs index 22cc5d8..b0f674b 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/WechatJsPay.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/ClientExtension/WechatJsPay.cs @@ -1,30 +1,30 @@ -using System.Threading.Tasks; -using Hncore.Infrastructure.Extension; -using Hncore.Infrastructure.Serializer; -using Hncore.Infrastructure.Service; -using Hncore.Infrastructure.WebApi; -using Hncore.Payment.Request; -using Hncore.Payment.Response; -using PaymentCenterClient; - -namespace Hncore.Payment.ClientExtension -{ - public static class WechatJsPay - { - /// - /// 微信小程序、公众号支付下单 - /// - /// - /// - /// - public static async Task WechatJsPayCreateOrder(this ServiceHttpClient client, - WechatJsPayCreateOrderRequest request) - { - var res = await client.CreateInternalClient() - .PostAsJsonGetString($"{client.BaseUrl}/api/paymentcenter/v1/WechatJsPay/CreateOrder", - request); - //WechatJsPayCreateOrderResponse - return res.FromJsonTo(); - } - } +using System.Threading.Tasks; +using Hncore.Infrastructure.Extension; +using Hncore.Infrastructure.Serializer; +using Hncore.Infrastructure.Service; +using Hncore.Infrastructure.WebApi; +using Hncore.Payment.Request; +using Hncore.Payment.Response; +using PaymentCenterClient; + +namespace Hncore.Payment.ClientExtension +{ + public static class WechatJsPay + { + /// + /// 微信小程序、公众号支付下单 + /// + /// + /// + /// + public static async Task WechatJsPayCreateOrder(this ServiceHttpClient client, + WechatJsPayCreateOrderRequest request) + { + var res = await client.CreateInternalClient() + .PostAsJsonGetString($"{client.BaseUrl}/api/paymentcenter/v1/WechatJsPay/CreateOrder", + request); + //WechatJsPayCreateOrderResponse + return res.FromJsonTo(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Enum/OrderType.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Enum/OrderType.cs index d6a64d0..bb0fce0 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Enum/OrderType.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Enum/OrderType.cs @@ -1,25 +1,25 @@ -namespace Hncore.Payment.Enum -{ - public enum OrderType - { - /// - /// 短信订单 - /// - SmsOrder = 0, - - /// - /// 产品订单 - /// - Product = 1, - - /// - /// 课程订单 - /// - Course = 2, - - /// - /// 课程套餐订单 - /// - CoursePackage =3, - } +namespace Hncore.Payment.Enum +{ + public enum OrderType + { + /// + /// 短信订单 + /// + SmsOrder = 0, + + /// + /// 产品订单 + /// + Product = 1, + + /// + /// 课程订单 + /// + Course = 2, + + /// + /// 课程套餐订单 + /// + CoursePackage =3, + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentChannel.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentChannel.cs index c918419..559fb55 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentChannel.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentChannel.cs @@ -1,15 +1,15 @@ -namespace Hncore.Payment.Enum -{ - public enum PaymentChannel - { - /// - /// 全付通 - /// - QuanFuTong = 0, - - /// - /// 汇旺财 - /// - WeiFuTong = 10 - } +namespace Hncore.Payment.Enum +{ + public enum PaymentChannel + { + /// + /// 全付通 + /// + QuanFuTong = 0, + + /// + /// 汇旺财 + /// + WeiFuTong = 10 + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentMethod.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentMethod.cs index 02ee9e6..34f52f4 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentMethod.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentMethod.cs @@ -1,30 +1,30 @@ -namespace Hncore.Payment.Enum -{ - /// - /// 支付方式 - /// - public enum PaymentMethod - { - None = 0, - /// - /// 微信付款码支付 - /// - WechatSwipeCardPay = 1, - /// - /// 微信扫码支付 - /// - WechatQrPay = 2, - /// - /// 支付宝付款码支付 - /// - AliSwipeCardPay = 3, - /// - /// 支付宝扫码支付 - /// - AliQrPay = 4, - /// - /// 微信公众号支付 - /// - WechatJsAppPay = 5 - } +namespace Hncore.Payment.Enum +{ + /// + /// 支付方式 + /// + public enum PaymentMethod + { + None = 0, + /// + /// 微信付款码支付 + /// + WechatSwipeCardPay = 1, + /// + /// 微信扫码支付 + /// + WechatQrPay = 2, + /// + /// 支付宝付款码支付 + /// + AliSwipeCardPay = 3, + /// + /// 支付宝扫码支付 + /// + AliQrPay = 4, + /// + /// 微信公众号支付 + /// + WechatJsAppPay = 5 + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentStatus.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentStatus.cs index 4204c71..c12de7a 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentStatus.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentStatus.cs @@ -1,35 +1,35 @@ -namespace Hncore.Payment.Enum -{ - public enum PaymentStatus - { - /// - /// 未支付 - /// - NotPay = 10, - - /// - /// 已支付 - /// - OkPay = 20, - - /// - /// 过期 - /// - Expire = 30, - - /// - /// 支付失败 - /// - Fail = 40, - - /// - /// 支付成功,回调失败 - /// - CallbackFail = 50, - - /// - /// 支付中 - /// - Paying = 60 - } +namespace Hncore.Payment.Enum +{ + public enum PaymentStatus + { + /// + /// 未支付 + /// + NotPay = 10, + + /// + /// 已支付 + /// + OkPay = 20, + + /// + /// 过期 + /// + Expire = 30, + + /// + /// 支付失败 + /// + Fail = 40, + + /// + /// 支付成功,回调失败 + /// + CallbackFail = 50, + + /// + /// 支付中 + /// + Paying = 60 + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentType.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentType.cs index 1d42df0..c0fb6a8 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentType.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Enum/PaymentType.cs @@ -1,72 +1,72 @@ -using System.ComponentModel; - -namespace Hncore.Payment.Enum -{ - public enum PaymentType - { - /// - /// 线下支付-现金 - /// - [Description("线下支付-现金")] OfflinePayCash = 10, - - /// - /// 线下支付-支票 - /// - [Description("线下支付-支票")] OfflinePayCheck = 20, - - /// - /// 线下支付-银行转账 - /// - [Description("线下支付-银行转账")] OfflinePayBank = 30, - - /// - /// 线下支付-pos机刷卡 - /// - [Description("线下支付-pos机刷卡")] OfflinePayPOS = 40, - - /// - /// 线下支付-支付宝直接转账 - /// - [Description("线下支付-支付宝直接转账")] OfflinePayAlipay = 50, - - /// - /// 线下支付-微信直接转账 - /// - [Description("线下支付-微信直接转账")] OfflinePayWechat = 60, - - /// - /// 线上支付-微信支付 - /// - [Description("线上支付-微信支付")] OnlinePayWechart = 70, - - /// - /// 线上支付-POS机储蓄卡刷卡 - /// - [Description("线上支付-POS机储蓄卡刷卡")] OnlinePosDeposit = 80, - - /// - /// 线上支付-POS机信用卡刷卡 - /// - [Description("线上支付-POS机信用卡刷卡")] OnlinePosCredit = 90, - - /// - /// 线上支付-支付宝 - /// - [Description("线上支付-支付宝")] OnlineAlipay = 100, - - /// - /// 停车劵免费 - /// - [Description("停车劵免费")] ParkTicketFree = 110, - - /// - /// 余额冲抵 - /// - [Description("余额冲抵")] BalanceOffset =120, - - /// - /// 其他支付方式 - /// - [Description("其他支付方式")] Other = 250 - } +using System.ComponentModel; + +namespace Hncore.Payment.Enum +{ + public enum PaymentType + { + /// + /// 线下支付-现金 + /// + [Description("线下支付-现金")] OfflinePayCash = 10, + + /// + /// 线下支付-支票 + /// + [Description("线下支付-支票")] OfflinePayCheck = 20, + + /// + /// 线下支付-银行转账 + /// + [Description("线下支付-银行转账")] OfflinePayBank = 30, + + /// + /// 线下支付-pos机刷卡 + /// + [Description("线下支付-pos机刷卡")] OfflinePayPOS = 40, + + /// + /// 线下支付-支付宝直接转账 + /// + [Description("线下支付-支付宝直接转账")] OfflinePayAlipay = 50, + + /// + /// 线下支付-微信直接转账 + /// + [Description("线下支付-微信直接转账")] OfflinePayWechat = 60, + + /// + /// 线上支付-微信支付 + /// + [Description("线上支付-微信支付")] OnlinePayWechart = 70, + + /// + /// 线上支付-POS机储蓄卡刷卡 + /// + [Description("线上支付-POS机储蓄卡刷卡")] OnlinePosDeposit = 80, + + /// + /// 线上支付-POS机信用卡刷卡 + /// + [Description("线上支付-POS机信用卡刷卡")] OnlinePosCredit = 90, + + /// + /// 线上支付-支付宝 + /// + [Description("线上支付-支付宝")] OnlineAlipay = 100, + + /// + /// 停车劵免费 + /// + [Description("停车劵免费")] ParkTicketFree = 110, + + /// + /// 余额冲抵 + /// + [Description("余额冲抵")] BalanceOffset =120, + + /// + /// 其他支付方式 + /// + [Description("其他支付方式")] Other = 250 + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Enum/ResultCode.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Enum/ResultCode.cs index 08755fb..692bfb3 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Enum/ResultCode.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Enum/ResultCode.cs @@ -1,156 +1,156 @@ -using System.ComponentModel; - -namespace Hncore.Payment.Enum -{ - public enum ResultCode - { - /// - /// 未知错误 - /// - [Description("服务正在更新中,请稍后再试")] C_UNKNOWN_ERROR = 0, - - /// - /// 成功 - /// - [Description("成功")] C_SUCCESS = 10000, - - /// - /// 验证码 - /// - [Description("验证码错误")] C_VERIFY_CODE_ERROR = 10001, - - /// - /// 参数 - /// - [Description("服务正在更新中,请稍后再试")] C_PARAM_ERROR = 10002, - - /// - /// 登录名 - /// - [Description("登录名错误")] C_LONGIN_NAME_ERROR = 10003, - - /// - /// 密码 - /// - [Description("密码错误")] C_PASSWORD_ERROR = 10004, - - /// - /// 无效操作 - /// - [Description("非法操作")] C_INVALID_ERROR = 10005, - - /// - /// 文件 - /// - [Description("文件错误")] C_FILE_ERROR = 10006, - - /// - /// 已存在错误 - /// - [Description("资源已存在错误")] C_ALREADY_EXISTS_ERROR = 10007, - - /// - /// 资源无法访问:不是资源的拥有者 - /// - [Description("不是资源的拥有者,资源无法访问")] C_OWNER_ERROR = 10008, - - /// - /// 资源不存在 - /// - [Description("资源不存在")] C_NOT_EXISTS_ERROR = 10009, - - /// - /// 新建角色出错 - /// - [Description("创建角色出错")] C_ROLE_CREATE_ERROR = 10010, - - /// - /// 新建权限出错 - /// - [Description("新建权限错误")] C_PERMISSION_CREATE_ERROR = 10011, - - /// - /// 绑定角色和权限出错 - /// - [Description("绑定角色和权限出错")] C_ROLE_PERMISSION_CREATE_ERROR = 10012, - - /// - /// 服务器繁忙,请稍后再试! - /// - [Description("服务器繁忙")] C_Server_Is_Busy = 10013, - - /// - /// 访问被禁止 - /// - [Description("禁止访问")] C_Access_Forbidden = 10014, - - /// - /// 非法操作 - /// - [Description("非法操作")] C_Illegal_Operation = 10015, - - /// - /// 无效的openID - /// - [Description("OpenID无效")] C_OPENID_ERROR = 10016, - - /// - /// 返回错误,但无需理会 - /// - [Description("可忽略的错误")] C_IGNORE_ERROR = 10017, - - /// - /// 用户信息错误 - /// - [Description("用户信息错误")] C_USERINFO_ERROR = 10018, - - /// - /// 用户需要认证 - /// - [Description("用户需要认证")] C_USER_SELECT_ERROR = 10019, - - /// - /// 过期 - /// - [Description("超时错误")] C_TIMEOUT_ERROR = 10020, - - /// - /// 手机和验证码不匹配 - /// - [Description("手机和验证码不匹配")] C_PHONE_CODE_ERROR = 10021, - - /// - /// 微信没有选择楼 - /// - [Description("微信没有选择楼")] C_WX_UNIT_UNSELECT_ERROR = 10022, - - /// - /// 黑名单错误 - /// - [Description("黑名单错误")] C_BLACKLIST_ERROR = 10023, - - /// - /// 支付失败 - /// - [Description("支付失败")] C_PAY_FAIL = 10024, - - /// - /// 重定向 - /// - [Description("重定向")] C_REDIRECT_URL = 100302, - - [Description("用户重定向")] C_USER_REDIRECT_URL = 900302, - - - [Description("人脸已经存在")] C_FACEKEY_EXIST_ERROR = 900303, - - [Description("人脸角度不正确")] C_FACE_ANGLE_ERROR = 900304, - - [Description("退款失败")] C_PAY_Refund = 900305, - - /// - /// 用户支付中 - /// - [Description("用户支付中")] C_USERPAYING = 900306 - } +using System.ComponentModel; + +namespace Hncore.Payment.Enum +{ + public enum ResultCode + { + /// + /// 未知错误 + /// + [Description("服务正在更新中,请稍后再试")] C_UNKNOWN_ERROR = 0, + + /// + /// 成功 + /// + [Description("成功")] C_SUCCESS = 10000, + + /// + /// 验证码 + /// + [Description("验证码错误")] C_VERIFY_CODE_ERROR = 10001, + + /// + /// 参数 + /// + [Description("服务正在更新中,请稍后再试")] C_PARAM_ERROR = 10002, + + /// + /// 登录名 + /// + [Description("登录名错误")] C_LONGIN_NAME_ERROR = 10003, + + /// + /// 密码 + /// + [Description("密码错误")] C_PASSWORD_ERROR = 10004, + + /// + /// 无效操作 + /// + [Description("非法操作")] C_INVALID_ERROR = 10005, + + /// + /// 文件 + /// + [Description("文件错误")] C_FILE_ERROR = 10006, + + /// + /// 已存在错误 + /// + [Description("资源已存在错误")] C_ALREADY_EXISTS_ERROR = 10007, + + /// + /// 资源无法访问:不是资源的拥有者 + /// + [Description("不是资源的拥有者,资源无法访问")] C_OWNER_ERROR = 10008, + + /// + /// 资源不存在 + /// + [Description("资源不存在")] C_NOT_EXISTS_ERROR = 10009, + + /// + /// 新建角色出错 + /// + [Description("创建角色出错")] C_ROLE_CREATE_ERROR = 10010, + + /// + /// 新建权限出错 + /// + [Description("新建权限错误")] C_PERMISSION_CREATE_ERROR = 10011, + + /// + /// 绑定角色和权限出错 + /// + [Description("绑定角色和权限出错")] C_ROLE_PERMISSION_CREATE_ERROR = 10012, + + /// + /// 服务器繁忙,请稍后再试! + /// + [Description("服务器繁忙")] C_Server_Is_Busy = 10013, + + /// + /// 访问被禁止 + /// + [Description("禁止访问")] C_Access_Forbidden = 10014, + + /// + /// 非法操作 + /// + [Description("非法操作")] C_Illegal_Operation = 10015, + + /// + /// 无效的openID + /// + [Description("OpenID无效")] C_OPENID_ERROR = 10016, + + /// + /// 返回错误,但无需理会 + /// + [Description("可忽略的错误")] C_IGNORE_ERROR = 10017, + + /// + /// 用户信息错误 + /// + [Description("用户信息错误")] C_USERINFO_ERROR = 10018, + + /// + /// 用户需要认证 + /// + [Description("用户需要认证")] C_USER_SELECT_ERROR = 10019, + + /// + /// 过期 + /// + [Description("超时错误")] C_TIMEOUT_ERROR = 10020, + + /// + /// 手机和验证码不匹配 + /// + [Description("手机和验证码不匹配")] C_PHONE_CODE_ERROR = 10021, + + /// + /// 微信没有选择楼 + /// + [Description("微信没有选择楼")] C_WX_UNIT_UNSELECT_ERROR = 10022, + + /// + /// 黑名单错误 + /// + [Description("黑名单错误")] C_BLACKLIST_ERROR = 10023, + + /// + /// 支付失败 + /// + [Description("支付失败")] C_PAY_FAIL = 10024, + + /// + /// 重定向 + /// + [Description("重定向")] C_REDIRECT_URL = 100302, + + [Description("用户重定向")] C_USER_REDIRECT_URL = 900302, + + + [Description("人脸已经存在")] C_FACEKEY_EXIST_ERROR = 900303, + + [Description("人脸角度不正确")] C_FACE_ANGLE_ERROR = 900304, + + [Description("退款失败")] C_PAY_Refund = 900305, + + /// + /// 用户支付中 + /// + [Description("用户支付中")] C_USERPAYING = 900306 + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/IServiceCollectionExtension.cs b/Infrastructure/ServiceClient/PaymentCenterClient/IServiceCollectionExtension.cs index 57eb28b..4cdf7be 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/IServiceCollectionExtension.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/IServiceCollectionExtension.cs @@ -1,21 +1,21 @@ -using Hncore.Infrastructure.Extension; -using Microsoft.Extensions.DependencyInjection; - -namespace PaymentCenterClient -{ - public static class IServiceCollectionExtension - { - public static void AddPaymentCenterClient(this IServiceCollection service, string baseUrl = "") - { - if (!baseUrl.Has()) - { - baseUrl = "http://paymentcenter/"; - } - - PaymentCenterHttpClient._BaseUrl = baseUrl; - - service.AddHttpClient(); - service.AddSingleton(); - } - } +using Hncore.Infrastructure.Extension; +using Microsoft.Extensions.DependencyInjection; + +namespace PaymentCenterClient +{ + public static class IServiceCollectionExtension + { + public static void AddPaymentCenterClient(this IServiceCollection service, string baseUrl = "") + { + if (!baseUrl.Has()) + { + baseUrl = "http://paymentcenter/"; + } + + PaymentCenterHttpClient._BaseUrl = baseUrl; + + service.AddHttpClient(); + service.AddSingleton(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/PaymentCenterClient.csproj b/Infrastructure/ServiceClient/PaymentCenterClient/PaymentCenterClient.csproj index ada64a8..40b424d 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/PaymentCenterClient.csproj +++ b/Infrastructure/ServiceClient/PaymentCenterClient/PaymentCenterClient.csproj @@ -1,13 +1,13 @@ - - - - netcoreapp2.2 - - - - - - - - - + + + + netcoreapp2.2 + + + + + + + + + diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/PaymentCenterHttpClient.cs b/Infrastructure/ServiceClient/PaymentCenterClient/PaymentCenterHttpClient.cs index b96c33e..0e75bad 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/PaymentCenterHttpClient.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/PaymentCenterHttpClient.cs @@ -1,25 +1,25 @@ -using System.Net.Http; - -namespace PaymentCenterClient -{ - public class PaymentCenterHttpClient - { - private IHttpClientFactory _httpClientFactory; - - internal static string _BaseUrl = ""; - - public PaymentCenterHttpClient(){} - - public PaymentCenterHttpClient(IHttpClientFactory httpClientFactory) - { - _httpClientFactory = httpClientFactory; - } - - public string BaseUrl => _BaseUrl; - - public HttpClient CreateHttpClient() - { - return _httpClientFactory.CreateClient("PaymentCenterClient"); - } - } +using System.Net.Http; + +namespace PaymentCenterClient +{ + public class PaymentCenterHttpClient + { + private IHttpClientFactory _httpClientFactory; + + internal static string _BaseUrl = ""; + + public PaymentCenterHttpClient(){} + + public PaymentCenterHttpClient(IHttpClientFactory httpClientFactory) + { + _httpClientFactory = httpClientFactory; + } + + public string BaseUrl => _BaseUrl; + + public HttpClient CreateHttpClient() + { + return _httpClientFactory.CreateClient("PaymentCenterClient"); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Request/CreateOffLinePaySuccessedRecordRequest.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Request/CreateOffLinePaySuccessedRecordRequest.cs index 78e3a8b..e7be8f8 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Request/CreateOffLinePaySuccessedRecordRequest.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Request/CreateOffLinePaySuccessedRecordRequest.cs @@ -1,58 +1,58 @@ -using System.Collections.Generic; -using Hncore.Payment.Enum; - -namespace Hncore.Payment.Request -{ - public class CreateOffLinePaySuccessedRecordRequest: PaymentRequestBase - { - /// - /// 总金额,单位:分 - /// - public int TotalFee { get; set; } - - /// - /// 商品描述 - /// - public string Body { get; set; } - - /// - /// 支付类型 - /// - public PaymentType PaymentType { get; set; } - - /// - /// 支付方式 - /// - public PaymentMethod PaymentMethod { get; set; } - - /// - /// 业务订单号 - /// - public string OrderId { get; set; } - - /// - /// 订单类型 - /// - public OrderType OrderType { get; set; } - - /// - /// 是否来自POS机 - /// - public bool FromPos { get; set; } - - /// - /// 回调地址 - /// - public string CallbackUrl { get; set; } - - /// - /// 业务方附加信息,回调时原样返回 - /// - public string Attach { get; set; } - - /// - /// 支付成功后要发送的mqtt消息 - /// - public List MqttMessages { get; set; } = new List(); - } +using System.Collections.Generic; +using Hncore.Payment.Enum; + +namespace Hncore.Payment.Request +{ + public class CreateOffLinePaySuccessedRecordRequest: PaymentRequestBase + { + /// + /// 总金额,单位:分 + /// + public int TotalFee { get; set; } + + /// + /// 商品描述 + /// + public string Body { get; set; } + + /// + /// 支付类型 + /// + public PaymentType PaymentType { get; set; } + + /// + /// 支付方式 + /// + public PaymentMethod PaymentMethod { get; set; } + + /// + /// 业务订单号 + /// + public string OrderId { get; set; } + + /// + /// 订单类型 + /// + public OrderType OrderType { get; set; } + + /// + /// 是否来自POS机 + /// + public bool FromPos { get; set; } + + /// + /// 回调地址 + /// + public string CallbackUrl { get; set; } + + /// + /// 业务方附加信息,回调时原样返回 + /// + public string Attach { get; set; } + + /// + /// 支付成功后要发送的mqtt消息 + /// + public List MqttMessages { get; set; } = new List(); + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Request/CreateOrderRequestBase.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Request/CreateOrderRequestBase.cs index 74295ab..8a2f7e2 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Request/CreateOrderRequestBase.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Request/CreateOrderRequestBase.cs @@ -1,37 +1,37 @@ -using Hncore.Payment.Enum; -using System.Collections.Generic; -namespace Hncore.Payment.Request -{ - public class CreateOrderRequestBase: PaymentRequestBase - { - /// - /// 业务方附加信息,回调时原样返回 - /// - public string Attach { get; set; } - - /// - /// 总金额,单位:分 - /// - public int TotalFee { get; set; } - - /// - /// 支付类型 - /// - public PaymentType PaymentType { get; set; } = PaymentType.OnlinePayWechart; - - /// - /// 回调地址 - /// - public string CallbackUrl { get; set; } - - /// - /// 商品描述 - /// - public string Body { get; set; } - - /// - /// 业务订单号 - /// - public string OrderId { get; set; } - } +using Hncore.Payment.Enum; +using System.Collections.Generic; +namespace Hncore.Payment.Request +{ + public class CreateOrderRequestBase: PaymentRequestBase + { + /// + /// 业务方附加信息,回调时原样返回 + /// + public string Attach { get; set; } + + /// + /// 总金额,单位:分 + /// + public int TotalFee { get; set; } + + /// + /// 支付类型 + /// + public PaymentType PaymentType { get; set; } = PaymentType.OnlinePayWechart; + + /// + /// 回调地址 + /// + public string CallbackUrl { get; set; } + + /// + /// 商品描述 + /// + public string Body { get; set; } + + /// + /// 业务订单号 + /// + public string OrderId { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Request/EPayCreateOrderRequest.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Request/EPayCreateOrderRequest.cs index a070875..4c10d4b 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Request/EPayCreateOrderRequest.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Request/EPayCreateOrderRequest.cs @@ -1,10 +1,10 @@ -namespace Hncore.Payment.Request -{ - /// - /// POS机推送订单请求 - /// - public class EPayCreateOrderRequest : CreateOrderRequestBase - { - - } -} +namespace Hncore.Payment.Request +{ + /// + /// POS机推送订单请求 + /// + public class EPayCreateOrderRequest : CreateOrderRequestBase + { + + } +} diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Request/MqttMessage.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Request/MqttMessage.cs index 12bc9ec..97bd1fe 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Request/MqttMessage.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Request/MqttMessage.cs @@ -1,9 +1,9 @@ -namespace Hncore.Payment.Request -{ - public class MqttMessage - { - public string Topic { get; set; } - - public string Payload { get; set; } - } +namespace Hncore.Payment.Request +{ + public class MqttMessage + { + public string Topic { get; set; } + + public string Payload { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Request/PaymentRequestBase.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Request/PaymentRequestBase.cs index fc99825..7ffd52f 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Request/PaymentRequestBase.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Request/PaymentRequestBase.cs @@ -1,12 +1,12 @@ -using Hncore.Payment.Enum; - -namespace Hncore.Payment.Request -{ - public class PaymentRequestBase - { - public int TenantId { get; set; } - - public int StoreId { get; set; } = 0; - - } +using Hncore.Payment.Enum; + +namespace Hncore.Payment.Request +{ + public class PaymentRequestBase + { + public int TenantId { get; set; } + + public int StoreId { get; set; } = 0; + + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Request/QrPayCreateOrderRequest.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Request/QrPayCreateOrderRequest.cs index b15281c..edaba2a 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Request/QrPayCreateOrderRequest.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Request/QrPayCreateOrderRequest.cs @@ -1,28 +1,28 @@ -namespace Hncore.Payment.Request -{ - /// - /// 扫码支付请求 - /// - public class QrPayCreateOrderRequest: CreateOrderRequestBase - { - /// - /// 目标平台,微信、支付宝 - /// - public TargetPlatform TargetPlatform { get; set; } - } - - /// - /// 目标平台,微信、支付宝 - /// - public enum TargetPlatform - { - /// - /// 微信 - /// - Wechat=1, - /// - /// 支付宝 - /// - Alipay=2 - } +namespace Hncore.Payment.Request +{ + /// + /// 扫码支付请求 + /// + public class QrPayCreateOrderRequest: CreateOrderRequestBase + { + /// + /// 目标平台,微信、支付宝 + /// + public TargetPlatform TargetPlatform { get; set; } + } + + /// + /// 目标平台,微信、支付宝 + /// + public enum TargetPlatform + { + /// + /// 微信 + /// + Wechat=1, + /// + /// 支付宝 + /// + Alipay=2 + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Request/SingleDaiFuRequest.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Request/SingleDaiFuRequest.cs index 3d59345..ea4193d 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Request/SingleDaiFuRequest.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Request/SingleDaiFuRequest.cs @@ -1,33 +1,33 @@ -namespace Hncore.Payment.Request -{ - /// - /// 单笔代付请求 - /// - public class SingleDaiFuRequest : PaymentRequestBase - { - /// - /// 订单Id - /// - public string OrderId { get; set; } - - /// - /// 收款人姓名 - /// - public string AccName { get; set; } - - /// - /// 收款人账号 - /// - public string AccNo { get; set; } - - /// - /// 转账金额,单位:分 - /// - public int Amount { get; set; } - - /// - /// 用途 - /// - public string Purpose { get; set; } - } +namespace Hncore.Payment.Request +{ + /// + /// 单笔代付请求 + /// + public class SingleDaiFuRequest : PaymentRequestBase + { + /// + /// 订单Id + /// + public string OrderId { get; set; } + + /// + /// 收款人姓名 + /// + public string AccName { get; set; } + + /// + /// 收款人账号 + /// + public string AccNo { get; set; } + + /// + /// 转账金额,单位:分 + /// + public int Amount { get; set; } + + /// + /// 用途 + /// + public string Purpose { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Request/SwipeCardCreateOrderRequest.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Request/SwipeCardCreateOrderRequest.cs index b08e308..0a0e517 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Request/SwipeCardCreateOrderRequest.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Request/SwipeCardCreateOrderRequest.cs @@ -1,13 +1,13 @@ -namespace Hncore.Payment.Request -{ - /// - /// 刷卡支付请求 - /// - public class SwipeCardCreateOrderRequest : CreateOrderRequestBase - { - /// - /// 扫码支付授权码, 设备读取用户展示的条码或者二维码信息 - /// - public string AuthCode { get; set; } - } +namespace Hncore.Payment.Request +{ + /// + /// 刷卡支付请求 + /// + public class SwipeCardCreateOrderRequest : CreateOrderRequestBase + { + /// + /// 扫码支付授权码, 设备读取用户展示的条码或者二维码信息 + /// + public string AuthCode { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Request/WechatJsPayCreateOrderRequest.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Request/WechatJsPayCreateOrderRequest.cs index 0e792d7..b19fd5b 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Request/WechatJsPayCreateOrderRequest.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Request/WechatJsPayCreateOrderRequest.cs @@ -1,40 +1,40 @@ -namespace Hncore.Payment.Request -{ - /// - /// 微信小程序、公众号支付请求 - /// - public class WechatJsPayCreateOrderRequest: CreateOrderRequestBase - { - /// - /// 支付环境 - /// - public PayEnvironment PayEnvironment { get; set; } - - /// - /// 微信用户关注商家公众号的openid - /// - public string UserOpenId { get; set; } - - /// - /// 公众账号或小程序ID - /// - public string AppId { get; set; } - - public int UserId { get; set; } - } - - /// - /// 支付环境 - /// - public enum PayEnvironment - { - /// - /// 小程序支付 - /// - WeApp=1, - /// - /// 公众号支付 - /// - H5=2 - } +namespace Hncore.Payment.Request +{ + /// + /// 微信小程序、公众号支付请求 + /// + public class WechatJsPayCreateOrderRequest: CreateOrderRequestBase + { + /// + /// 支付环境 + /// + public PayEnvironment PayEnvironment { get; set; } + + /// + /// 微信用户关注商家公众号的openid + /// + public string UserOpenId { get; set; } + + /// + /// 公众账号或小程序ID + /// + public string AppId { get; set; } + + public int UserId { get; set; } + } + + /// + /// 支付环境 + /// + public enum PayEnvironment + { + /// + /// 小程序支付 + /// + WeApp=1, + /// + /// 公众号支付 + /// + H5=2 + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Response/QrPayCreateOrderResponse.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Response/QrPayCreateOrderResponse.cs index 2a92ad7..d386c8f 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Response/QrPayCreateOrderResponse.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Response/QrPayCreateOrderResponse.cs @@ -1,15 +1,15 @@ -namespace Hncore.Payment.Response -{ - public class QrPayCreateOrderResponse - { - /// - /// 商户可用此参数自定义去生成二维码后展示出来进行扫码支付 - /// - public string CodeUrl { get; set; } - - /// - /// 此参数的值即是根据code_url生成的可以扫码支付的二维码图片地址 - /// - public string CodeImgUrl { get; set; } - } +namespace Hncore.Payment.Response +{ + public class QrPayCreateOrderResponse + { + /// + /// 商户可用此参数自定义去生成二维码后展示出来进行扫码支付 + /// + public string CodeUrl { get; set; } + + /// + /// 此参数的值即是根据code_url生成的可以扫码支付的二维码图片地址 + /// + public string CodeImgUrl { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Response/QueryOrderResponse.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Response/QueryOrderResponse.cs index 50c06a8..80c808c 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Response/QueryOrderResponse.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Response/QueryOrderResponse.cs @@ -1,11 +1,11 @@ -using Hncore.Payment.Enum; - -namespace Hncore.Payment.Response -{ - public class QueryOrderResponse - { - public PaymentStatus PaymentStatus { get; set; } - public PaymentType PayType { get; set; } - public string PaymentMessage { get; set; } - } +using Hncore.Payment.Enum; + +namespace Hncore.Payment.Response +{ + public class QueryOrderResponse + { + public PaymentStatus PaymentStatus { get; set; } + public PaymentType PayType { get; set; } + public string PaymentMessage { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/Response/WechatJsPayCreateOrderResponse.cs b/Infrastructure/ServiceClient/PaymentCenterClient/Response/WechatJsPayCreateOrderResponse.cs index 683db92..77b1fa4 100644 --- a/Infrastructure/ServiceClient/PaymentCenterClient/Response/WechatJsPayCreateOrderResponse.cs +++ b/Infrastructure/ServiceClient/PaymentCenterClient/Response/WechatJsPayCreateOrderResponse.cs @@ -1,10 +1,10 @@ -namespace Hncore.Payment.Response -{ - public class WechatJsPayCreateOrderResponse - { - /// - /// 原生态js支付信息或小程序支付信息 - /// - public string PayInfo { get; set; } - } +namespace Hncore.Payment.Response +{ + public class WechatJsPayCreateOrderResponse + { + /// + /// 原生态js支付信息或小程序支付信息 + /// + public string PayInfo { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/PaymentCenterClient/obj/Debug/netcoreapp2.2/PaymentCenterClient.csprojAssemblyReference.cache b/Infrastructure/ServiceClient/PaymentCenterClient/obj/Debug/netcoreapp2.2/PaymentCenterClient.csprojAssemblyReference.cache index 0823c36..00f2cea 100644 Binary files a/Infrastructure/ServiceClient/PaymentCenterClient/obj/Debug/netcoreapp2.2/PaymentCenterClient.csprojAssemblyReference.cache and b/Infrastructure/ServiceClient/PaymentCenterClient/obj/Debug/netcoreapp2.2/PaymentCenterClient.csprojAssemblyReference.cache differ diff --git a/Infrastructure/ServiceClient/ScheduledTaskClient/IServiceCollectionExtension.cs b/Infrastructure/ServiceClient/ScheduledTaskClient/IServiceCollectionExtension.cs index 30aa106..68985f1 100644 --- a/Infrastructure/ServiceClient/ScheduledTaskClient/IServiceCollectionExtension.cs +++ b/Infrastructure/ServiceClient/ScheduledTaskClient/IServiceCollectionExtension.cs @@ -1,14 +1,14 @@ -using Microsoft.Extensions.DependencyInjection; - -namespace ScheduledTaskClient -{ - public static class IServiceCollectionExtension - { - public static void AddMsgCenterClient(this IServiceCollection service, string baseUrl="http://scheduledtask") - { - ScheduledTaskHttpClient._BaseUrl = baseUrl; - - service.AddSingleton(); - } - } +using Microsoft.Extensions.DependencyInjection; + +namespace ScheduledTaskClient +{ + public static class IServiceCollectionExtension + { + public static void AddMsgCenterClient(this IServiceCollection service, string baseUrl="http://scheduledtask") + { + ScheduledTaskHttpClient._BaseUrl = baseUrl; + + service.AddSingleton(); + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledMessage.cs b/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledMessage.cs index 0981fd3..a0f3afe 100644 --- a/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledMessage.cs +++ b/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledMessage.cs @@ -1,35 +1,35 @@ -using System; - -namespace ScheduledTaskClient -{ - /// - /// 计划消息 - /// - public class ScheduledMessage - { - /// - /// 消息名称 - /// - public string MessageName { get; set; } - - /// - /// 计划类型 - /// - public ScheduledType ScheduledType { get; set; } - - /// - /// 延迟计划延迟时间 - /// - public TimeSpan Delaye { get; set; } - - /// - /// 定期计划cron表达式 - /// - public string Cron { get; set; } - - /// - /// 消息内容 - /// - public string Content { get; set; } - } +using System; + +namespace ScheduledTaskClient +{ + /// + /// 计划消息 + /// + public class ScheduledMessage + { + /// + /// 消息名称 + /// + public string MessageName { get; set; } + + /// + /// 计划类型 + /// + public ScheduledType ScheduledType { get; set; } + + /// + /// 延迟计划延迟时间 + /// + public TimeSpan Delaye { get; set; } + + /// + /// 定期计划cron表达式 + /// + public string Cron { get; set; } + + /// + /// 消息内容 + /// + public string Content { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledTaskClient.csproj b/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledTaskClient.csproj index 86706b0..76c0a6e 100644 --- a/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledTaskClient.csproj +++ b/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledTaskClient.csproj @@ -1,11 +1,11 @@ - - - - netcoreapp2.2 - - - - - - - + + + + netcoreapp2.2 + + + + + + + diff --git a/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledTaskHttpClient.cs b/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledTaskHttpClient.cs index 50a6a91..96c0d68 100644 --- a/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledTaskHttpClient.cs +++ b/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledTaskHttpClient.cs @@ -1,50 +1,50 @@ -using System; -using System.Net.Http; -using System.Threading.Tasks; -using Etor.Infrastructure.Common; -using Etor.Infrastructure.Extension; -using Etor.Infrastructure.Serializer; -using Etor.Infrastructure.WebApi; - -namespace ScheduledTaskClient -{ - public class ScheduledTaskHttpClient - { - private IHttpClientFactory _httpClientFactory; - - internal static string _BaseUrl = ""; - - public ScheduledTaskHttpClient(IHttpClientFactory httpClientFactory) - { - _httpClientFactory = httpClientFactory; - } - - public string BaseUrl => _BaseUrl; - - private HttpClient CreateHttpClient() - { - return _httpClientFactory.CreateClient(); - } - - /// - /// 设置计划消息 - /// - /// - /// - public async Task SetScheduledMmessage(ScheduledMessage message) - { - try - { - var res = await CreateHttpClient() - .PostAsJsonGetString("/api/scheduledtask/v1/message/Set", message); - - return res.FromJsonTo(); - } - catch (Exception e) - { - LogHelper.Error("设置计划消息失败", $"{e}\n消息内容:\n{message.ToJson(true)}"); - return new ApiResult(ResultCode.C_UNKNOWN_ERROR); - } - } - } +using System; +using System.Net.Http; +using System.Threading.Tasks; +using Etor.Infrastructure.Common; +using Etor.Infrastructure.Extension; +using Etor.Infrastructure.Serializer; +using Etor.Infrastructure.WebApi; + +namespace ScheduledTaskClient +{ + public class ScheduledTaskHttpClient + { + private IHttpClientFactory _httpClientFactory; + + internal static string _BaseUrl = ""; + + public ScheduledTaskHttpClient(IHttpClientFactory httpClientFactory) + { + _httpClientFactory = httpClientFactory; + } + + public string BaseUrl => _BaseUrl; + + private HttpClient CreateHttpClient() + { + return _httpClientFactory.CreateClient(); + } + + /// + /// 设置计划消息 + /// + /// + /// + public async Task SetScheduledMmessage(ScheduledMessage message) + { + try + { + var res = await CreateHttpClient() + .PostAsJsonGetString("/api/scheduledtask/v1/message/Set", message); + + return res.FromJsonTo(); + } + catch (Exception e) + { + LogHelper.Error("设置计划消息失败", $"{e}\n消息内容:\n{message.ToJson(true)}"); + return new ApiResult(ResultCode.C_UNKNOWN_ERROR); + } + } + } } \ No newline at end of file diff --git a/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledType.cs b/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledType.cs index 802bc5d..d105676 100644 --- a/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledType.cs +++ b/Infrastructure/ServiceClient/ScheduledTaskClient/ScheduledType.cs @@ -1,18 +1,18 @@ -namespace ScheduledTaskClient -{ - /// - /// 计划类型 - /// - public enum ScheduledType - { - /// - /// 延迟 - /// - Delayed = 1, - - /// - /// 定期 - /// - Recurring = 2 - } +namespace ScheduledTaskClient +{ + /// + /// 计划类型 + /// + public enum ScheduledType + { + /// + /// 延迟 + /// + Delayed = 1, + + /// + /// 定期 + /// + Recurring = 2 + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/ChannelType.cs b/Infrastructure/WxApi/ChannelType.cs index 40e7685..d2a93ef 100644 --- a/Infrastructure/WxApi/ChannelType.cs +++ b/Infrastructure/WxApi/ChannelType.cs @@ -1,20 +1,20 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Threading.Tasks; - -namespace Hncore.Wx.Open.Enums -{ - public enum ChannelType - { - [Description("公众号")] - MP=1, - [Description("小程序")] - MiniApp=2, - [Description("短信")] - Sms=3, - [Description("小程序订阅消息")] - MiniAppSubscribe = 4, - } -} +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Threading.Tasks; + +namespace Hncore.Wx.Open.Enums +{ + public enum ChannelType + { + [Description("公众号")] + MP=1, + [Description("小程序")] + MiniApp=2, + [Description("短信")] + Sms=3, + [Description("小程序订阅消息")] + MiniAppSubscribe = 4, + } +} diff --git a/Infrastructure/WxApi/Cryptography.cs b/Infrastructure/WxApi/Cryptography.cs index 43b9133..05b5f77 100644 --- a/Infrastructure/WxApi/Cryptography.cs +++ b/Infrastructure/WxApi/Cryptography.cs @@ -1,232 +1,232 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Security.Cryptography; -using System.IO; -using System.Net; -namespace Tencent -{ - class Cryptography - { - public static UInt32 HostToNetworkOrder(UInt32 inval) - { - UInt32 outval = 0; - for (int i = 0; i < 4; i++) - outval = (outval << 8) + ((inval >> (i * 8)) & 255); - return outval; - } - - public static Int32 HostToNetworkOrder(Int32 inval) - { - Int32 outval = 0; - for (int i = 0; i < 4; i++) - outval = (outval << 8) + ((inval >> (i * 8)) & 255); - return outval; - } - /// - /// 解密方法 - /// - /// 密文 - /// - /// - /// - public static string AES_decrypt(String Input, string EncodingAESKey, ref string appid) - { - byte[] Key; - Key = Convert.FromBase64String(EncodingAESKey + "="); - byte[] Iv = new byte[16]; - Array.Copy(Key, Iv, 16); - byte[] btmpMsg = AES_decrypt(Input, Iv, Key); - - int len = BitConverter.ToInt32(btmpMsg, 16); - len = IPAddress.NetworkToHostOrder(len); - - - byte[] bMsg = new byte[len]; - byte[] bAppid = new byte[btmpMsg.Length - 20 - len]; - Array.Copy(btmpMsg, 20, bMsg, 0, len); - Array.Copy(btmpMsg, 20+len , bAppid, 0, btmpMsg.Length - 20 - len); - string oriMsg = Encoding.UTF8.GetString(bMsg); - appid = Encoding.UTF8.GetString(bAppid); - - - return oriMsg; - } - - public static String AES_encrypt(String Input, string EncodingAESKey, string appid) - { - byte[] Key; - Key = Convert.FromBase64String(EncodingAESKey + "="); - byte[] Iv = new byte[16]; - Array.Copy(Key, Iv, 16); - string Randcode = CreateRandCode(16); - byte[] bRand = Encoding.UTF8.GetBytes(Randcode); - byte[] bAppid = Encoding.UTF8.GetBytes(appid); - byte[] btmpMsg = Encoding.UTF8.GetBytes(Input); - byte[] bMsgLen = BitConverter.GetBytes(HostToNetworkOrder(btmpMsg.Length)); - byte[] bMsg = new byte[bRand.Length + bMsgLen.Length + bAppid.Length + btmpMsg.Length]; - - Array.Copy(bRand, bMsg, bRand.Length); - Array.Copy(bMsgLen, 0, bMsg, bRand.Length, bMsgLen.Length); - Array.Copy(btmpMsg, 0, bMsg, bRand.Length + bMsgLen.Length, btmpMsg.Length); - Array.Copy(bAppid, 0, bMsg, bRand.Length + bMsgLen.Length + btmpMsg.Length, bAppid.Length); - - return AES_encrypt(bMsg, Iv, Key); - - } - private static string CreateRandCode(int codeLen) - { - string codeSerial = "2,3,4,5,6,7,a,c,d,e,f,h,i,j,k,m,n,p,r,s,t,A,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,U,V,W,X,Y,Z"; - if (codeLen == 0) - { - codeLen = 16; - } - string[] arr = codeSerial.Split(','); - string code = ""; - int randValue = -1; - Random rand = new Random(unchecked((int)DateTime.Now.Ticks)); - for (int i = 0; i < codeLen; i++) - { - randValue = rand.Next(0, arr.Length - 1); - code += arr[randValue]; - } - return code; - } - - private static String AES_encrypt(String Input, byte[] Iv, byte[] Key) - { - var aes = new RijndaelManaged(); - //秘钥的大小,以位为单位 - aes.KeySize = 256; - //支持的块大小 - aes.BlockSize = 128; - //填充模式 - aes.Padding = PaddingMode.PKCS7; - aes.Mode = CipherMode.CBC; - aes.Key = Key; - aes.IV = Iv; - var encrypt = aes.CreateEncryptor(aes.Key, aes.IV); - byte[] xBuff = null; - - using (var ms = new MemoryStream()) - { - using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write)) - { - byte[] xXml = Encoding.UTF8.GetBytes(Input); - cs.Write(xXml, 0, xXml.Length); - } - xBuff = ms.ToArray(); - } - String Output = Convert.ToBase64String(xBuff); - return Output; - } - - private static String AES_encrypt(byte[] Input, byte[] Iv, byte[] Key) - { - var aes = new RijndaelManaged(); - //秘钥的大小,以位为单位 - aes.KeySize = 256; - //支持的块大小 - aes.BlockSize = 128; - //填充模式 - //aes.Padding = PaddingMode.PKCS7; - aes.Padding = PaddingMode.None; - aes.Mode = CipherMode.CBC; - aes.Key = Key; - aes.IV = Iv; - var encrypt = aes.CreateEncryptor(aes.Key, aes.IV); - byte[] xBuff = null; - - #region 自己进行PKCS7补位,用系统自己带的不行 - byte[] msg = new byte[Input.Length + 32 - Input.Length % 32]; - Array.Copy(Input, msg, Input.Length); - byte[] pad = KCS7Encoder(Input.Length); - Array.Copy(pad, 0, msg, Input.Length, pad.Length); - #endregion - - #region 注释的也是一种方法,效果一样 - //ICryptoTransform transform = aes.CreateEncryptor(); - //byte[] xBuff = transform.TransformFinalBlock(msg, 0, msg.Length); - #endregion - - using (var ms = new MemoryStream()) - { - using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write)) - { - cs.Write(msg, 0, msg.Length); - } - xBuff = ms.ToArray(); - } - - String Output = Convert.ToBase64String(xBuff); - return Output; - } - - private static byte[] KCS7Encoder(int text_length) - { - int block_size = 32; - // 计算需要填充的位数 - int amount_to_pad = block_size - (text_length % block_size); - if (amount_to_pad == 0) - { - amount_to_pad = block_size; - } - // 获得补位所用的字符 - char pad_chr = chr(amount_to_pad); - string tmp = ""; - for (int index = 0; index < amount_to_pad; index++) - { - tmp += pad_chr; - } - return Encoding.UTF8.GetBytes(tmp); - } - /** - * 将数字转化成ASCII码对应的字符,用于对明文进行补码 - * - * @param a 需要转化的数字 - * @return 转化得到的字符 - */ - static char chr(int a) - { - - byte target = (byte)(a & 0xFF); - return (char)target; - } - private static byte[] AES_decrypt(String Input, byte[] Iv, byte[] Key) - { - RijndaelManaged aes = new RijndaelManaged(); - aes.KeySize = 256; - aes.BlockSize = 128; - aes.Mode = CipherMode.CBC; - aes.Padding = PaddingMode.None; - aes.Key = Key; - aes.IV = Iv; - var decrypt = aes.CreateDecryptor(aes.Key, aes.IV); - byte[] xBuff = null; - using (var ms = new MemoryStream()) - { - using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write)) - { - byte[] xXml = Convert.FromBase64String(Input); - byte[] msg = new byte[xXml.Length + 32 - xXml.Length % 32]; - Array.Copy(xXml, msg, xXml.Length); - cs.Write(xXml, 0, xXml.Length); - } - xBuff = decode2(ms.ToArray()); - } - return xBuff; - } - private static byte[] decode2(byte[] decrypted) - { - int pad = (int)decrypted[decrypted.Length - 1]; - if (pad < 1 || pad > 32) - { - pad = 0; - } - byte[] res = new byte[decrypted.Length - pad]; - Array.Copy(decrypted, 0, res, 0, decrypted.Length - pad); - return res; - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Security.Cryptography; +using System.IO; +using System.Net; +namespace Tencent +{ + class Cryptography + { + public static UInt32 HostToNetworkOrder(UInt32 inval) + { + UInt32 outval = 0; + for (int i = 0; i < 4; i++) + outval = (outval << 8) + ((inval >> (i * 8)) & 255); + return outval; + } + + public static Int32 HostToNetworkOrder(Int32 inval) + { + Int32 outval = 0; + for (int i = 0; i < 4; i++) + outval = (outval << 8) + ((inval >> (i * 8)) & 255); + return outval; + } + /// + /// 解密方法 + /// + /// 密文 + /// + /// + /// + public static string AES_decrypt(String Input, string EncodingAESKey, ref string appid) + { + byte[] Key; + Key = Convert.FromBase64String(EncodingAESKey + "="); + byte[] Iv = new byte[16]; + Array.Copy(Key, Iv, 16); + byte[] btmpMsg = AES_decrypt(Input, Iv, Key); + + int len = BitConverter.ToInt32(btmpMsg, 16); + len = IPAddress.NetworkToHostOrder(len); + + + byte[] bMsg = new byte[len]; + byte[] bAppid = new byte[btmpMsg.Length - 20 - len]; + Array.Copy(btmpMsg, 20, bMsg, 0, len); + Array.Copy(btmpMsg, 20+len , bAppid, 0, btmpMsg.Length - 20 - len); + string oriMsg = Encoding.UTF8.GetString(bMsg); + appid = Encoding.UTF8.GetString(bAppid); + + + return oriMsg; + } + + public static String AES_encrypt(String Input, string EncodingAESKey, string appid) + { + byte[] Key; + Key = Convert.FromBase64String(EncodingAESKey + "="); + byte[] Iv = new byte[16]; + Array.Copy(Key, Iv, 16); + string Randcode = CreateRandCode(16); + byte[] bRand = Encoding.UTF8.GetBytes(Randcode); + byte[] bAppid = Encoding.UTF8.GetBytes(appid); + byte[] btmpMsg = Encoding.UTF8.GetBytes(Input); + byte[] bMsgLen = BitConverter.GetBytes(HostToNetworkOrder(btmpMsg.Length)); + byte[] bMsg = new byte[bRand.Length + bMsgLen.Length + bAppid.Length + btmpMsg.Length]; + + Array.Copy(bRand, bMsg, bRand.Length); + Array.Copy(bMsgLen, 0, bMsg, bRand.Length, bMsgLen.Length); + Array.Copy(btmpMsg, 0, bMsg, bRand.Length + bMsgLen.Length, btmpMsg.Length); + Array.Copy(bAppid, 0, bMsg, bRand.Length + bMsgLen.Length + btmpMsg.Length, bAppid.Length); + + return AES_encrypt(bMsg, Iv, Key); + + } + private static string CreateRandCode(int codeLen) + { + string codeSerial = "2,3,4,5,6,7,a,c,d,e,f,h,i,j,k,m,n,p,r,s,t,A,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,U,V,W,X,Y,Z"; + if (codeLen == 0) + { + codeLen = 16; + } + string[] arr = codeSerial.Split(','); + string code = ""; + int randValue = -1; + Random rand = new Random(unchecked((int)DateTime.Now.Ticks)); + for (int i = 0; i < codeLen; i++) + { + randValue = rand.Next(0, arr.Length - 1); + code += arr[randValue]; + } + return code; + } + + private static String AES_encrypt(String Input, byte[] Iv, byte[] Key) + { + var aes = new RijndaelManaged(); + //秘钥的大小,以位为单位 + aes.KeySize = 256; + //支持的块大小 + aes.BlockSize = 128; + //填充模式 + aes.Padding = PaddingMode.PKCS7; + aes.Mode = CipherMode.CBC; + aes.Key = Key; + aes.IV = Iv; + var encrypt = aes.CreateEncryptor(aes.Key, aes.IV); + byte[] xBuff = null; + + using (var ms = new MemoryStream()) + { + using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write)) + { + byte[] xXml = Encoding.UTF8.GetBytes(Input); + cs.Write(xXml, 0, xXml.Length); + } + xBuff = ms.ToArray(); + } + String Output = Convert.ToBase64String(xBuff); + return Output; + } + + private static String AES_encrypt(byte[] Input, byte[] Iv, byte[] Key) + { + var aes = new RijndaelManaged(); + //秘钥的大小,以位为单位 + aes.KeySize = 256; + //支持的块大小 + aes.BlockSize = 128; + //填充模式 + //aes.Padding = PaddingMode.PKCS7; + aes.Padding = PaddingMode.None; + aes.Mode = CipherMode.CBC; + aes.Key = Key; + aes.IV = Iv; + var encrypt = aes.CreateEncryptor(aes.Key, aes.IV); + byte[] xBuff = null; + + #region 自己进行PKCS7补位,用系统自己带的不行 + byte[] msg = new byte[Input.Length + 32 - Input.Length % 32]; + Array.Copy(Input, msg, Input.Length); + byte[] pad = KCS7Encoder(Input.Length); + Array.Copy(pad, 0, msg, Input.Length, pad.Length); + #endregion + + #region 注释的也是一种方法,效果一样 + //ICryptoTransform transform = aes.CreateEncryptor(); + //byte[] xBuff = transform.TransformFinalBlock(msg, 0, msg.Length); + #endregion + + using (var ms = new MemoryStream()) + { + using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write)) + { + cs.Write(msg, 0, msg.Length); + } + xBuff = ms.ToArray(); + } + + String Output = Convert.ToBase64String(xBuff); + return Output; + } + + private static byte[] KCS7Encoder(int text_length) + { + int block_size = 32; + // 计算需要填充的位数 + int amount_to_pad = block_size - (text_length % block_size); + if (amount_to_pad == 0) + { + amount_to_pad = block_size; + } + // 获得补位所用的字符 + char pad_chr = chr(amount_to_pad); + string tmp = ""; + for (int index = 0; index < amount_to_pad; index++) + { + tmp += pad_chr; + } + return Encoding.UTF8.GetBytes(tmp); + } + /** + * 将数字转化成ASCII码对应的字符,用于对明文进行补码 + * + * @param a 需要转化的数字 + * @return 转化得到的字符 + */ + static char chr(int a) + { + + byte target = (byte)(a & 0xFF); + return (char)target; + } + private static byte[] AES_decrypt(String Input, byte[] Iv, byte[] Key) + { + RijndaelManaged aes = new RijndaelManaged(); + aes.KeySize = 256; + aes.BlockSize = 128; + aes.Mode = CipherMode.CBC; + aes.Padding = PaddingMode.None; + aes.Key = Key; + aes.IV = Iv; + var decrypt = aes.CreateDecryptor(aes.Key, aes.IV); + byte[] xBuff = null; + using (var ms = new MemoryStream()) + { + using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write)) + { + byte[] xXml = Convert.FromBase64String(Input); + byte[] msg = new byte[xXml.Length + 32 - xXml.Length % 32]; + Array.Copy(xXml, msg, xXml.Length); + cs.Write(xXml, 0, xXml.Length); + } + xBuff = decode2(ms.ToArray()); + } + return xBuff; + } + private static byte[] decode2(byte[] decrypted) + { + int pad = (int)decrypted[decrypted.Length - 1]; + if (pad < 1 || pad > 32) + { + pad = 0; + } + byte[] res = new byte[decrypted.Length - pad]; + Array.Copy(decrypted, 0, res, 0, decrypted.Length - pad); + return res; + } + } +} diff --git a/Infrastructure/WxApi/Enums.cs b/Infrastructure/WxApi/Enums.cs index ef5a859..3cd72be 100644 --- a/Infrastructure/WxApi/Enums.cs +++ b/Infrastructure/WxApi/Enums.cs @@ -1,309 +1,309 @@ -namespace Hncore.Wx.Open -{ - /// - /// 选项设置信息选项名称 - /// - public enum OptionName - { - /// - /// 地理位置上报选项 - /// 0 无上报 - /// 1 进入会话时上报 - /// 2 每5s上报 - /// - location_report, - /// - /// 语音识别开关选项 - /// 0 关闭语音识别 - /// 1 开启语音识别 - /// - voice_recognize, - /// - /// 客服开关选项 - /// 0 关闭多客服 - /// 1 开启多客服 - /// - customer_service - } - - /// - /// 公众号第三方平台推送消息类型 - /// - public enum RequestInfoType - { - - #region 授权消息和事件 - /// - /// 推送component_verify_ticket协议 - /// - component_verify_ticket, - /// - /// 推送取消授权通知 - /// - unauthorized, - /// - /// 更新授权 - /// - updateauthorized, - /// - /// 授权成功通知 - /// - authorized, - /// - /// 小程序注册审核事件推送 - /// - notify_third_fasteregister, - - #endregion - - #region 公众号交互的事件 - /// - /// 关注事件 - /// - event_subscribe, - /// - /// 取消关注事件 - /// - event_unsubscribe, - /// - /// 扫描关注 - /// - event_subscribe_qrscene, - /// - /// 扫描已关注的事件 - /// - event_SCAN, - /// - /// 上报地理位置 - /// - event_LOCATION, - /// - /// 自定义菜单事件 - /// - event_CLICK, - /// - /// 点击菜单跳转链接 - /// - event_VIEW, - #endregion - - #region 公众号交互消息 - /// - /// 文本消息 - /// - text, - /// - /// 图片消息 - /// - image, - /// - /// 语音消息 - /// - voice, - /// - /// 视频消息 - /// - video, - /// - /// 音乐消息 - /// - music, - /// - /// 图文消息 - /// - news, - - /// - /// 未知消息 - /// - none - #endregion - } - - /// - /// 应用授权作用域 - /// - public enum OAuthScope - { - /// - /// 不弹出授权页面,直接跳转,只能获取用户openid - /// - snsapi_base, - /// - /// 弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息 - /// - snsapi_userinfo, - /// - /// 网站应用授权登录 - /// - snsapi_login, - } - - /// - /// 授权方公众号类型 - /// - public enum ServiceType - { -#pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释 - 订阅号 = 0, - 由历史老帐号升级后的订阅号 = 1, - 服务号 = 2 -#pragma warning restore CS1591 // 缺少对公共可见类型或成员的 XML 注释 - } - - /// - /// 授权方认证类型 - /// - public enum VerifyType - { -#pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释 - 未认证 = -1, - 微信认证 = 0, - 新浪微博认证 = 1, - 腾讯微博认证 = 2, - 已资质认证通过但还未通过名称认证 = 3, - 已资质认证通过还未通过名称认证但通过了新浪微博认证 = 4, - 已资质认证通过还未通过名称认证但通过了腾讯微博认证 = 5 -#pragma warning restore CS1591 // 缺少对公共可见类型或成员的 XML 注释 - } - - /// - /// 公众号/小程序授权给开发者的权限集列表(1-15为公众号权限,17-19为小程序权限)。 - /// 请注意:1)该字段的返回不会考虑公众号是否具备该权限集的权限(因为可能部分具备),请根据公众号的帐号类型和认证情况,来判断公众号的接口权限。 - /// - public enum FuncscopeCategory - { -#pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释 - 消息管理权限 = 1, - 用户管理权限 = 2, - 帐号服务权限 = 3, - 网页服务权限 = 4, - 微信小店权限 = 5, - 微信多客服权限 = 6, - 群发与通知权限 = 7, - 微信卡券权限 = 8, - 微信扫一扫权限 = 9, - 微信连WIFI权限 = 10, - 素材管理权限 = 11, - 微信摇周边权限 = 12, - 微信门店权限 = 13, - 微信支付权限 = 14, - 自定义菜单权限 = 15, - 获取认证状态及信息 = 16, - 帐号管理权限_小程序 = 17, - 开发管理权限_小程序 = 18, - 客服消息管理权限_小程序 = 19, - 微信登录权限_小程序 = 20, - 数据分析权限_小程序 = 21, - 城市服务接口权限 = 22, - 广告管理权限 = 23, - 开放平台帐号管理权限 = 24, - 开放平台帐号管理权限_小程序 = 25, - 微信电子发票权限 = 26, - 快速注册小程序权限 = 27, - 小程序管理权限 = 33, - 微信卡路里权限 = 35 -#pragma warning restore CS1591 // 缺少对公共可见类型或成员的 XML 注释 - } - - /// - /// 小程序“修改服务器地址”接口的action类型 - /// - public enum ModifyDomainAction - { - /// - /// 添加 - /// - add, - /// - /// 删除 - /// - delete, - /// - /// 覆盖 - /// - set, - /// - /// 获取 - /// - get - } - - /// - /// 小程序“线上代码的可见状态”接口的action类型 - /// - public enum ChangVisitStatusAction - { - open, - close - } - - /// - /// 帐号类型(1:订阅号,2:服务号,3:小程序) - /// - public enum AccountType - { - 订阅号 = 1, - 服务号 = 2, - 小程序 = 3 - } - - /// - /// 主体类型(1:企业) - /// - public enum PrincipalType - { - 企业 = 1 - } - - /// - /// 1:实名验证成功,2:实名验证中,3:实名验证失败 - /// - public enum RealNameStatus - { - 实名验证成功 = 1, - 实名验证中 = 2, - 实名验证失败 = 3 - } - - /// - /// 小程序昵称审核状态,1:审核中,2:审核失败,3:审核成功 - /// - public enum AuditStat - { - 审核中 = 1, - 审核失败 = 2, - 审核成功 = 3 - } - - /// - /// 小程序类目审核状态,1:审核中,2:审核失败,3:审核成功 - /// - public enum AuditStatus - { - 审核中 = 1, - 审核不通过 = 2, - 审核通过 = 3 - } - - /// - /// 要授权的帐号类型 - /// - public enum LoginAuthType - { - 默认, - 仅展示公众号 = 1, - 仅展示小程序 = 2, - 表示公众号和小程序都展示 = 3 - } - - /// - /// 企业代码类型 1:统一社会信用代码(18位) 2:组织机构代码(9位xxxxxxxx-x) 3:营业执照注册号(15位) - /// - public enum CodeType - { - 统一社会信用代码 =1, - 组织机构代码=2, - 营业执照注册号=3 - } -} +namespace Hncore.Wx.Open +{ + /// + /// 选项设置信息选项名称 + /// + public enum OptionName + { + /// + /// 地理位置上报选项 + /// 0 无上报 + /// 1 进入会话时上报 + /// 2 每5s上报 + /// + location_report, + /// + /// 语音识别开关选项 + /// 0 关闭语音识别 + /// 1 开启语音识别 + /// + voice_recognize, + /// + /// 客服开关选项 + /// 0 关闭多客服 + /// 1 开启多客服 + /// + customer_service + } + + /// + /// 公众号第三方平台推送消息类型 + /// + public enum RequestInfoType + { + + #region 授权消息和事件 + /// + /// 推送component_verify_ticket协议 + /// + component_verify_ticket, + /// + /// 推送取消授权通知 + /// + unauthorized, + /// + /// 更新授权 + /// + updateauthorized, + /// + /// 授权成功通知 + /// + authorized, + /// + /// 小程序注册审核事件推送 + /// + notify_third_fasteregister, + + #endregion + + #region 公众号交互的事件 + /// + /// 关注事件 + /// + event_subscribe, + /// + /// 取消关注事件 + /// + event_unsubscribe, + /// + /// 扫描关注 + /// + event_subscribe_qrscene, + /// + /// 扫描已关注的事件 + /// + event_SCAN, + /// + /// 上报地理位置 + /// + event_LOCATION, + /// + /// 自定义菜单事件 + /// + event_CLICK, + /// + /// 点击菜单跳转链接 + /// + event_VIEW, + #endregion + + #region 公众号交互消息 + /// + /// 文本消息 + /// + text, + /// + /// 图片消息 + /// + image, + /// + /// 语音消息 + /// + voice, + /// + /// 视频消息 + /// + video, + /// + /// 音乐消息 + /// + music, + /// + /// 图文消息 + /// + news, + + /// + /// 未知消息 + /// + none + #endregion + } + + /// + /// 应用授权作用域 + /// + public enum OAuthScope + { + /// + /// 不弹出授权页面,直接跳转,只能获取用户openid + /// + snsapi_base, + /// + /// 弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息 + /// + snsapi_userinfo, + /// + /// 网站应用授权登录 + /// + snsapi_login, + } + + /// + /// 授权方公众号类型 + /// + public enum ServiceType + { +#pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释 + 订阅号 = 0, + 由历史老帐号升级后的订阅号 = 1, + 服务号 = 2 +#pragma warning restore CS1591 // 缺少对公共可见类型或成员的 XML 注释 + } + + /// + /// 授权方认证类型 + /// + public enum VerifyType + { +#pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释 + 未认证 = -1, + 微信认证 = 0, + 新浪微博认证 = 1, + 腾讯微博认证 = 2, + 已资质认证通过但还未通过名称认证 = 3, + 已资质认证通过还未通过名称认证但通过了新浪微博认证 = 4, + 已资质认证通过还未通过名称认证但通过了腾讯微博认证 = 5 +#pragma warning restore CS1591 // 缺少对公共可见类型或成员的 XML 注释 + } + + /// + /// 公众号/小程序授权给开发者的权限集列表(1-15为公众号权限,17-19为小程序权限)。 + /// 请注意:1)该字段的返回不会考虑公众号是否具备该权限集的权限(因为可能部分具备),请根据公众号的帐号类型和认证情况,来判断公众号的接口权限。 + /// + public enum FuncscopeCategory + { +#pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释 + 消息管理权限 = 1, + 用户管理权限 = 2, + 帐号服务权限 = 3, + 网页服务权限 = 4, + 微信小店权限 = 5, + 微信多客服权限 = 6, + 群发与通知权限 = 7, + 微信卡券权限 = 8, + 微信扫一扫权限 = 9, + 微信连WIFI权限 = 10, + 素材管理权限 = 11, + 微信摇周边权限 = 12, + 微信门店权限 = 13, + 微信支付权限 = 14, + 自定义菜单权限 = 15, + 获取认证状态及信息 = 16, + 帐号管理权限_小程序 = 17, + 开发管理权限_小程序 = 18, + 客服消息管理权限_小程序 = 19, + 微信登录权限_小程序 = 20, + 数据分析权限_小程序 = 21, + 城市服务接口权限 = 22, + 广告管理权限 = 23, + 开放平台帐号管理权限 = 24, + 开放平台帐号管理权限_小程序 = 25, + 微信电子发票权限 = 26, + 快速注册小程序权限 = 27, + 小程序管理权限 = 33, + 微信卡路里权限 = 35 +#pragma warning restore CS1591 // 缺少对公共可见类型或成员的 XML 注释 + } + + /// + /// 小程序“修改服务器地址”接口的action类型 + /// + public enum ModifyDomainAction + { + /// + /// 添加 + /// + add, + /// + /// 删除 + /// + delete, + /// + /// 覆盖 + /// + set, + /// + /// 获取 + /// + get + } + + /// + /// 小程序“线上代码的可见状态”接口的action类型 + /// + public enum ChangVisitStatusAction + { + open, + close + } + + /// + /// 帐号类型(1:订阅号,2:服务号,3:小程序) + /// + public enum AccountType + { + 订阅号 = 1, + 服务号 = 2, + 小程序 = 3 + } + + /// + /// 主体类型(1:企业) + /// + public enum PrincipalType + { + 企业 = 1 + } + + /// + /// 1:实名验证成功,2:实名验证中,3:实名验证失败 + /// + public enum RealNameStatus + { + 实名验证成功 = 1, + 实名验证中 = 2, + 实名验证失败 = 3 + } + + /// + /// 小程序昵称审核状态,1:审核中,2:审核失败,3:审核成功 + /// + public enum AuditStat + { + 审核中 = 1, + 审核失败 = 2, + 审核成功 = 3 + } + + /// + /// 小程序类目审核状态,1:审核中,2:审核失败,3:审核成功 + /// + public enum AuditStatus + { + 审核中 = 1, + 审核不通过 = 2, + 审核通过 = 3 + } + + /// + /// 要授权的帐号类型 + /// + public enum LoginAuthType + { + 默认, + 仅展示公众号 = 1, + 仅展示小程序 = 2, + 表示公众号和小程序都展示 = 3 + } + + /// + /// 企业代码类型 1:统一社会信用代码(18位) 2:组织机构代码(9位xxxxxxxx-x) 3:营业执照注册号(15位) + /// + public enum CodeType + { + 统一社会信用代码 =1, + 组织机构代码=2, + 营业执照注册号=3 + } +} diff --git a/Infrastructure/WxApi/MessageHandler.cs b/Infrastructure/WxApi/MessageHandler.cs index 79698b6..3c60cdc 100644 --- a/Infrastructure/WxApi/MessageHandler.cs +++ b/Infrastructure/WxApi/MessageHandler.cs @@ -1,12 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Hncore.Wx.Open -{ - public class MessageHandler - { - - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Hncore.Wx.Open +{ + public class MessageHandler + { + + } +} diff --git a/Infrastructure/WxApi/Model/WxMenuModel.cs b/Infrastructure/WxApi/Model/WxMenuModel.cs index 95cdb5a..cf5b1cb 100644 --- a/Infrastructure/WxApi/Model/WxMenuModel.cs +++ b/Infrastructure/WxApi/Model/WxMenuModel.cs @@ -1,12 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Hncore.Pass.MsgCenter.WxOpen.Model -{ - public class WxMenuModel - { - } - -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Hncore.Pass.MsgCenter.WxOpen.Model +{ + public class WxMenuModel + { + } + +} diff --git a/Infrastructure/WxApi/Model/WxOpenModel.cs b/Infrastructure/WxApi/Model/WxOpenModel.cs index 7ce2aed..6297fae 100644 --- a/Infrastructure/WxApi/Model/WxOpenModel.cs +++ b/Infrastructure/WxApi/Model/WxOpenModel.cs @@ -1,98 +1,98 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Hncore.Wx.Open -{ - - public class wechat_access_token - { - public string access_token { get; set; } - public int expires_in { get; set; } - public string refresh_token { get; set; } - public string openid { get; set; } - public string scope { get; set; } - public int errcode { get; set; } - public string errmsg { get; set; } - } - - public class authorizer_info - { - public string nick_name { get; set; } - public string head_img { get; set; } - public Service_Type_Info service_type_info { get; set; } - public Verify_Type_Info verify_type_info { get; set; } - public string user_name { get; set; } - public string alias { get; set; } - public string qrcode_url { get; set; } - public bussiness_info business_info { get; set; } - public int idc { get; set; } - public string principal_name { get; set; } - public string signature { get; set; } - } - - public class Service_Type_Info - { - public int id { get; set; } - } - - public class Verify_Type_Info - { - public int id { get; set; } - } - - public class bussiness_info - { - public int open_pay { get; set; } - public int open_shake { get; set; } - public int open_scan { get; set; } - public int open_card { get; set; } - public int open_store { get; set; } - } - /// - /// 授权信息数据模型 - /// - /// - public class authorization_info - { - /// - /// 授权方(物业公众号)的AppId - /// - public string authorizer_appid { get; set; } - /// - /// 授权方(物业公众号)的访问令牌AccessToken - /// - public string authorizer_access_token { get; set; } - /// - /// 授权方访问令牌的过期时间 - /// - public int expires_in { get; set; } - /// - /// 授权方刷新令牌,当访问令牌过期时,使用此刷新令牌重新获取新的访问令牌(此字段要保存) - /// - public string authorizer_refresh_token { get; set; } - /// - /// 授权给开发者的权限集列表,ID为1到26分别代表: 1、消息管理权限 2、用户管理权限 3、帐号服务权限 4、网页服务权限 5、微信小店权限 6、微信多客服权限 7、群发与通知权限 8、微信卡券权限 9、微信扫一扫权限 10、微信连WIFI权限 11、素材管理权限 12、微信摇周边权限 13、微信门店权限 15、自定义菜单权限 16、获取认证状态及信息 17、帐号管理权限(小程序) 18、开发管理与数据分析权限(小程序) 19、客服消息管理权限(小程序) 20、微信登录权限(小程序) 21、数据分析权限(小程序) 22、城市服务接口权限 23、广告管理权限 24、开放平台帐号管理权限 25、 开放平台帐号管理权限(小程序) 26、微信电子发票权限 41、搜索widget的权限 请注意: 1)该字段的返回不会考虑公众号是否具备该权限集的权限(因为可能部分具备),请根据公众号的帐号类型和认证情况,来判断公众号的接口权限。 - /// - public func_info[] func_info { get; set; } - } - - public class func_info - { - public funcscope_category funcscope_category { get; set; } - } - - public class funcscope_category - { - public int id { get; set; } - } - - - public class WechatThirdpartApplicationInfomation - { - public authorizer_info authorizier_info { get; set; } - public authorization_info authorization_info { get; set; } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Hncore.Wx.Open +{ + + public class wechat_access_token + { + public string access_token { get; set; } + public int expires_in { get; set; } + public string refresh_token { get; set; } + public string openid { get; set; } + public string scope { get; set; } + public int errcode { get; set; } + public string errmsg { get; set; } + } + + public class authorizer_info + { + public string nick_name { get; set; } + public string head_img { get; set; } + public Service_Type_Info service_type_info { get; set; } + public Verify_Type_Info verify_type_info { get; set; } + public string user_name { get; set; } + public string alias { get; set; } + public string qrcode_url { get; set; } + public bussiness_info business_info { get; set; } + public int idc { get; set; } + public string principal_name { get; set; } + public string signature { get; set; } + } + + public class Service_Type_Info + { + public int id { get; set; } + } + + public class Verify_Type_Info + { + public int id { get; set; } + } + + public class bussiness_info + { + public int open_pay { get; set; } + public int open_shake { get; set; } + public int open_scan { get; set; } + public int open_card { get; set; } + public int open_store { get; set; } + } + /// + /// 授权信息数据模型 + /// + /// + public class authorization_info + { + /// + /// 授权方(物业公众号)的AppId + /// + public string authorizer_appid { get; set; } + /// + /// 授权方(物业公众号)的访问令牌AccessToken + /// + public string authorizer_access_token { get; set; } + /// + /// 授权方访问令牌的过期时间 + /// + public int expires_in { get; set; } + /// + /// 授权方刷新令牌,当访问令牌过期时,使用此刷新令牌重新获取新的访问令牌(此字段要保存) + /// + public string authorizer_refresh_token { get; set; } + /// + /// 授权给开发者的权限集列表,ID为1到26分别代表: 1、消息管理权限 2、用户管理权限 3、帐号服务权限 4、网页服务权限 5、微信小店权限 6、微信多客服权限 7、群发与通知权限 8、微信卡券权限 9、微信扫一扫权限 10、微信连WIFI权限 11、素材管理权限 12、微信摇周边权限 13、微信门店权限 15、自定义菜单权限 16、获取认证状态及信息 17、帐号管理权限(小程序) 18、开发管理与数据分析权限(小程序) 19、客服消息管理权限(小程序) 20、微信登录权限(小程序) 21、数据分析权限(小程序) 22、城市服务接口权限 23、广告管理权限 24、开放平台帐号管理权限 25、 开放平台帐号管理权限(小程序) 26、微信电子发票权限 41、搜索widget的权限 请注意: 1)该字段的返回不会考虑公众号是否具备该权限集的权限(因为可能部分具备),请根据公众号的帐号类型和认证情况,来判断公众号的接口权限。 + /// + public func_info[] func_info { get; set; } + } + + public class func_info + { + public funcscope_category funcscope_category { get; set; } + } + + public class funcscope_category + { + public int id { get; set; } + } + + + public class WechatThirdpartApplicationInfomation + { + public authorizer_info authorizier_info { get; set; } + public authorization_info authorization_info { get; set; } + } +} diff --git a/Infrastructure/WxApi/Notice/InfoTypeHelper.cs b/Infrastructure/WxApi/Notice/InfoTypeHelper.cs index f7857aa..6c99583 100644 --- a/Infrastructure/WxApi/Notice/InfoTypeHelper.cs +++ b/Infrastructure/WxApi/Notice/InfoTypeHelper.cs @@ -1,56 +1,56 @@ -using System; -using System.Xml.Linq; - -namespace Hncore.Wx.Open -{ - public static class InfoTypeHelper - { - /// - /// 根据xml信息返回类型 - /// 授权信息返回的是 InfoType - /// 微信交互消息和事件返回的是 MsgType - /// - /// - /// - public static RequestInfoType GetRequestInfoType(XDocument doc) - { - var reqType = ""; - var typeNode = doc.Root.Element("InfoType"); - if (typeNode != null) - { - reqType = typeNode.Value; - } - else - { - typeNode = doc.Root.Element("MsgType"); - reqType = typeNode.Value; - if (reqType == "event") - { - reqType = "event_" + doc.Root.Element("Event").Value; - var eventKey = doc.Root.Element("EventKey"); - if (null != (eventKey) && eventKey.Value.StartsWith("qrscene_")) - { - reqType = "event_subscribe_qrscene"; - } - } - } - return GetRequestInfoType(reqType); - } - - /// - /// 根据xml信息,返回InfoType - /// - /// - public static RequestInfoType GetRequestInfoType(string str) - { - try - { - return (RequestInfoType)Enum.Parse(typeof(RequestInfoType), str, true); - } - catch - { - return RequestInfoType.none; - } - } - } -} +using System; +using System.Xml.Linq; + +namespace Hncore.Wx.Open +{ + public static class InfoTypeHelper + { + /// + /// 根据xml信息返回类型 + /// 授权信息返回的是 InfoType + /// 微信交互消息和事件返回的是 MsgType + /// + /// + /// + public static RequestInfoType GetRequestInfoType(XDocument doc) + { + var reqType = ""; + var typeNode = doc.Root.Element("InfoType"); + if (typeNode != null) + { + reqType = typeNode.Value; + } + else + { + typeNode = doc.Root.Element("MsgType"); + reqType = typeNode.Value; + if (reqType == "event") + { + reqType = "event_" + doc.Root.Element("Event").Value; + var eventKey = doc.Root.Element("EventKey"); + if (null != (eventKey) && eventKey.Value.StartsWith("qrscene_")) + { + reqType = "event_subscribe_qrscene"; + } + } + } + return GetRequestInfoType(reqType); + } + + /// + /// 根据xml信息,返回InfoType + /// + /// + public static RequestInfoType GetRequestInfoType(string str) + { + try + { + return (RequestInfoType)Enum.Parse(typeof(RequestInfoType), str, true); + } + catch + { + return RequestInfoType.none; + } + } + } +} diff --git a/Infrastructure/WxApi/Notice/MessageBase.cs b/Infrastructure/WxApi/Notice/MessageBase.cs index a540f0d..3af088f 100644 --- a/Infrastructure/WxApi/Notice/MessageBase.cs +++ b/Infrastructure/WxApi/Notice/MessageBase.cs @@ -1,16 +1,16 @@ -using System.Threading.Tasks; - -namespace Hncore.Wx.Open -{ - /// - /// 请求消息接口 - /// - public interface IMessageBase - { - string AppId { get; set; } - long CreateTime { get; set; } - RequestInfoType InfoType { get; } - Task Handler(); - - } -} +using System.Threading.Tasks; + +namespace Hncore.Wx.Open +{ + /// + /// 请求消息接口 + /// + public interface IMessageBase + { + string AppId { get; set; } + long CreateTime { get; set; } + RequestInfoType InfoType { get; } + Task Handler(); + + } +} diff --git a/Infrastructure/WxApi/Notice/MessageDefault.cs b/Infrastructure/WxApi/Notice/MessageDefault.cs index 34d76c8..437052e 100644 --- a/Infrastructure/WxApi/Notice/MessageDefault.cs +++ b/Infrastructure/WxApi/Notice/MessageDefault.cs @@ -1,38 +1,38 @@ -/* - - - - 123456789 - - - - - - */ -using System.Threading.Tasks; - -namespace Hncore.Wx.Open -{ - /// - /// 扫描二维码关注 - /// - public class MessageDefault : IMessageBase - { - public MessageDefault() - { - - } - public RequestInfoType InfoType - { - get { return RequestInfoType.none; } - } - - public string AppId { get; set; } - public long CreateTime { get; set; } - - public async Task Handler() - { - return true; - } - } -} +/* + + + + 123456789 + + + + + + */ +using System.Threading.Tasks; + +namespace Hncore.Wx.Open +{ + /// + /// 扫描二维码关注 + /// + public class MessageDefault : IMessageBase + { + public MessageDefault() + { + + } + public RequestInfoType InfoType + { + get { return RequestInfoType.none; } + } + + public string AppId { get; set; } + public long CreateTime { get; set; } + + public async Task Handler() + { + return true; + } + } +} diff --git a/Infrastructure/WxApi/Notice/MessageFactory.cs b/Infrastructure/WxApi/Notice/MessageFactory.cs index e592ffc..36b5ac1 100644 --- a/Infrastructure/WxApi/Notice/MessageFactory.cs +++ b/Infrastructure/WxApi/Notice/MessageFactory.cs @@ -1,95 +1,95 @@ -using Hncore.Infrastructure.Common; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.IO; -using System.Xml; -using System.Xml.Linq; - -namespace Hncore.Wx.Open -{ - /// - /// RequestMessage工厂 - /// - public static class MessageFactory - { - - public static IServiceCollection Service { get; set; } - /// - /// 获取XDocument转换后的IRequestMessageBase实例。 - /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常 - /// - /// - public static IMessageBase GetRequestEntity(XDocument doc) - { - IMessageBase requestMessage = null; - RequestInfoType infoType; - - try - { - infoType = InfoTypeHelper.GetRequestInfoType(doc); - switch (infoType) - { - case RequestInfoType.component_verify_ticket: - requestMessage = new MessageComponentVerifyTicket(doc); - break; - case RequestInfoType.unauthorized: - requestMessage = new MessageUnauthorized(doc); - break; - case RequestInfoType.authorized: - requestMessage = new MessageAuthorized(doc); - break; - case RequestInfoType.updateauthorized: - requestMessage = new MessageUpdateAuthorized(doc); - break; - case RequestInfoType.notify_third_fasteregister: - requestMessage = new MessageThirdFasteRegister(doc); - break; - case RequestInfoType.event_subscribe_qrscene: - requestMessage = new MessageEventSubscribeQrscene(doc); - break; - case RequestInfoType.event_SCAN: - requestMessage = new MessageEventScan(doc); - break; - case RequestInfoType.event_subscribe: - requestMessage = new MessageEventSubscribe(doc); - break; - default: - return new MessageDefault(); - } - } - catch (Exception ex) - { - LogHelper.Error("MessageFactory 解析失败", ex.Message); - } - return requestMessage; - } - - - /// - /// 获取XDocument转换后的IRequestMessageBase实例。 - /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常 - /// - /// - public static IMessageBase GetRequestEntity(string xml) - { - return GetRequestEntity(XDocument.Parse(xml)); - } - - - /// - /// 获取XDocument转换后的IRequestMessageBase实例。 - /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常 - /// - /// 如Request.InputStream - /// - public static IMessageBase GetRequestEntity(Stream stream) - { - using (XmlReader xr = XmlReader.Create(stream)) - { - var doc = XDocument.Load(xr); - - return GetRequestEntity(doc); - } - } - } -} +using Hncore.Infrastructure.Common; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.IO; +using System.Xml; +using System.Xml.Linq; + +namespace Hncore.Wx.Open +{ + /// + /// RequestMessage工厂 + /// + public static class MessageFactory + { + + public static IServiceCollection Service { get; set; } + /// + /// 获取XDocument转换后的IRequestMessageBase实例。 + /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常 + /// + /// + public static IMessageBase GetRequestEntity(XDocument doc) + { + IMessageBase requestMessage = null; + RequestInfoType infoType; + + try + { + infoType = InfoTypeHelper.GetRequestInfoType(doc); + switch (infoType) + { + case RequestInfoType.component_verify_ticket: + requestMessage = new MessageComponentVerifyTicket(doc); + break; + case RequestInfoType.unauthorized: + requestMessage = new MessageUnauthorized(doc); + break; + case RequestInfoType.authorized: + requestMessage = new MessageAuthorized(doc); + break; + case RequestInfoType.updateauthorized: + requestMessage = new MessageUpdateAuthorized(doc); + break; + case RequestInfoType.notify_third_fasteregister: + requestMessage = new MessageThirdFasteRegister(doc); + break; + case RequestInfoType.event_subscribe_qrscene: + requestMessage = new MessageEventSubscribeQrscene(doc); + break; + case RequestInfoType.event_SCAN: + requestMessage = new MessageEventScan(doc); + break; + case RequestInfoType.event_subscribe: + requestMessage = new MessageEventSubscribe(doc); + break; + default: + return new MessageDefault(); + } + } + catch (Exception ex) + { + LogHelper.Error("MessageFactory 解析失败", ex.Message); + } + return requestMessage; + } + + + /// + /// 获取XDocument转换后的IRequestMessageBase实例。 + /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常 + /// + /// + public static IMessageBase GetRequestEntity(string xml) + { + return GetRequestEntity(XDocument.Parse(xml)); + } + + + /// + /// 获取XDocument转换后的IRequestMessageBase实例。 + /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常 + /// + /// 如Request.InputStream + /// + public static IMessageBase GetRequestEntity(Stream stream) + { + using (XmlReader xr = XmlReader.Create(stream)) + { + var doc = XDocument.Load(xr); + + return GetRequestEntity(doc); + } + } + } +} diff --git a/Infrastructure/WxApi/Notice/MpMessage/MessageEventScan.cs b/Infrastructure/WxApi/Notice/MpMessage/MessageEventScan.cs index 35e9cfc..7e1ba60 100644 --- a/Infrastructure/WxApi/Notice/MpMessage/MessageEventScan.cs +++ b/Infrastructure/WxApi/Notice/MpMessage/MessageEventScan.cs @@ -1,60 +1,60 @@ -/* - - - - 123456789 - - - - - - */ -using Hncore.Pass.MsgCenter.Constant; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using System.Xml.Linq; -using Hncore.Pass.MsgCenter.Util; -namespace Hncore.Wx.Open -{ - /// - /// 扫描二维码关注 - /// - public class MessageEventScan : MessageMPBase - { - public MessageEventScan(XDocument doc) : base(doc) - { - this.EventKey = doc.Root.Element("EventKey").Value; - this.Ticket = doc.Root.Element("Ticket").Value; - } - public override RequestInfoType InfoType - { - get { return RequestInfoType.event_SCAN; } - } - - /// - /// 事件KEY值,qrscene_为前缀,后面为二维码的参数值 - /// - public string EventKey { get; set; } - /// - /// 二维码的ticket,可用来换取二维码图片 - /// - public string Ticket { get; set; } - - public override async Task Handler() - { - ///参数形式 method?a=1&b=2 - var dataUrl = this.EventKey; - var model = UrlHelper.ParseUrl(dataUrl); - - if (model.Method == "addtag") - { - var tagid = model.Args["tagid"]; - - WxOpenApi.AddTag(this.AppId, new List() { this.FromUserName }, tagid); - } - return true; - } - } -} +/* + + + + 123456789 + + + + + + */ +using Hncore.Pass.MsgCenter.Constant; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Xml.Linq; +using Hncore.Pass.MsgCenter.Util; +namespace Hncore.Wx.Open +{ + /// + /// 扫描二维码关注 + /// + public class MessageEventScan : MessageMPBase + { + public MessageEventScan(XDocument doc) : base(doc) + { + this.EventKey = doc.Root.Element("EventKey").Value; + this.Ticket = doc.Root.Element("Ticket").Value; + } + public override RequestInfoType InfoType + { + get { return RequestInfoType.event_SCAN; } + } + + /// + /// 事件KEY值,qrscene_为前缀,后面为二维码的参数值 + /// + public string EventKey { get; set; } + /// + /// 二维码的ticket,可用来换取二维码图片 + /// + public string Ticket { get; set; } + + public override async Task Handler() + { + ///参数形式 method?a=1&b=2 + var dataUrl = this.EventKey; + var model = UrlHelper.ParseUrl(dataUrl); + + if (model.Method == "addtag") + { + var tagid = model.Args["tagid"]; + + WxOpenApi.AddTag(this.AppId, new List() { this.FromUserName }, tagid); + } + return true; + } + } +} diff --git a/Infrastructure/WxApi/Notice/MpMessage/MessageEventSubscribe.cs b/Infrastructure/WxApi/Notice/MpMessage/MessageEventSubscribe.cs index 95d6b7d..7dc2bd6 100644 --- a/Infrastructure/WxApi/Notice/MpMessage/MessageEventSubscribe.cs +++ b/Infrastructure/WxApi/Notice/MpMessage/MessageEventSubscribe.cs @@ -1,38 +1,38 @@ -/* - - - - 123456789 - - - - */ -using Hncore.Infrastructure.Common; -using Microsoft.EntityFrameworkCore; -using System.Threading.Tasks; -using System.Xml.Linq; -namespace Hncore.Wx.Open -{ - /// - /// 关注 - /// - public class MessageEventSubscribe : MessageMPBase - { - public MessageEventSubscribe(XDocument doc) : base(doc) - { - } - public override RequestInfoType InfoType - { - get { return RequestInfoType.event_subscribe; } - } - - public override async Task Handler() - { - LogHelper.Info("MessageEventSubscribe", $"AppId={this.AppId},openid={this.FromUserName}"); - var userInfo = await WxOpenApi.GetUserUnionIDinfo(this.AppId, this.FromUserName); - LogHelper.Info("MessageEventSubscribe_userInfo", $"AppId={this.AppId},unionid={ userInfo.unionid}"); - - return true; - } - } -} +/* + + + + 123456789 + + + + */ +using Hncore.Infrastructure.Common; +using Microsoft.EntityFrameworkCore; +using System.Threading.Tasks; +using System.Xml.Linq; +namespace Hncore.Wx.Open +{ + /// + /// 关注 + /// + public class MessageEventSubscribe : MessageMPBase + { + public MessageEventSubscribe(XDocument doc) : base(doc) + { + } + public override RequestInfoType InfoType + { + get { return RequestInfoType.event_subscribe; } + } + + public override async Task Handler() + { + LogHelper.Info("MessageEventSubscribe", $"AppId={this.AppId},openid={this.FromUserName}"); + var userInfo = await WxOpenApi.GetUserUnionIDinfo(this.AppId, this.FromUserName); + LogHelper.Info("MessageEventSubscribe_userInfo", $"AppId={this.AppId},unionid={ userInfo.unionid}"); + + return true; + } + } +} diff --git a/Infrastructure/WxApi/Notice/MpMessage/MessageEventSubscribeQrscene.cs b/Infrastructure/WxApi/Notice/MpMessage/MessageEventSubscribeQrscene.cs index e4081f8..83533b1 100644 --- a/Infrastructure/WxApi/Notice/MpMessage/MessageEventSubscribeQrscene.cs +++ b/Infrastructure/WxApi/Notice/MpMessage/MessageEventSubscribeQrscene.cs @@ -1,64 +1,64 @@ -/* - - - - 123456789 - - - - - - */ -using Hncore.Pass.MsgCenter.Util; -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using System.Xml.Linq; - -namespace Hncore.Wx.Open -{ - /// - /// 扫描二维码关注 - /// - public class MessageEventSubscribeQrscene : MessageMPBase - { - public MessageEventSubscribeQrscene(XDocument doc) : base(doc) - { - this.EventKey = doc.Root.Element("EventKey").Value; - this.Ticket = doc.Root.Element("Ticket").Value; - } - public override RequestInfoType InfoType - { - get { return RequestInfoType.event_subscribe_qrscene; } - } - - /// - /// 事件KEY值,qrscene_为前缀,后面为二维码的参数值 - /// - public string EventKey { get; set; } - /// - /// 二维码的ticket,可用来换取二维码图片 - /// - public string Ticket { get; set; } - - public override async Task Handler() - { - ///参数形式 method?a=1&b=2 - var dataUrl = EventKey.TrimStart("qrscene_".ToCharArray()); - var model = UrlHelper.ParseUrl(dataUrl); - - if (model.Method == "addtag") - { - var tagid = model.Args["tagid"]; - - WxOpenApi.AddTag(this.AppId, new List() { this.FromUserName }, tagid); - } - - var userInfo = await WxOpenApi.GetUserUnionIDinfo(this.AppId, this.FromUserName); - - - return true; - } - } -} +/* + + + + 123456789 + + + + + + */ +using Hncore.Pass.MsgCenter.Util; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace Hncore.Wx.Open +{ + /// + /// 扫描二维码关注 + /// + public class MessageEventSubscribeQrscene : MessageMPBase + { + public MessageEventSubscribeQrscene(XDocument doc) : base(doc) + { + this.EventKey = doc.Root.Element("EventKey").Value; + this.Ticket = doc.Root.Element("Ticket").Value; + } + public override RequestInfoType InfoType + { + get { return RequestInfoType.event_subscribe_qrscene; } + } + + /// + /// 事件KEY值,qrscene_为前缀,后面为二维码的参数值 + /// + public string EventKey { get; set; } + /// + /// 二维码的ticket,可用来换取二维码图片 + /// + public string Ticket { get; set; } + + public override async Task Handler() + { + ///参数形式 method?a=1&b=2 + var dataUrl = EventKey.TrimStart("qrscene_".ToCharArray()); + var model = UrlHelper.ParseUrl(dataUrl); + + if (model.Method == "addtag") + { + var tagid = model.Args["tagid"]; + + WxOpenApi.AddTag(this.AppId, new List() { this.FromUserName }, tagid); + } + + var userInfo = await WxOpenApi.GetUserUnionIDinfo(this.AppId, this.FromUserName); + + + return true; + } + } +} diff --git a/Infrastructure/WxApi/Notice/MpMessage/MessageMPBase.cs b/Infrastructure/WxApi/Notice/MpMessage/MessageMPBase.cs index 74732e8..d8b69fa 100644 --- a/Infrastructure/WxApi/Notice/MpMessage/MessageMPBase.cs +++ b/Infrastructure/WxApi/Notice/MpMessage/MessageMPBase.cs @@ -1,35 +1,35 @@ -using System.Threading.Tasks; -using System.Xml.Linq; - -namespace Hncore.Wx.Open -{ - - /// - /// 请求消息 - /// - public class MessageMPBase : IMessageBase - { - - public MessageMPBase(XDocument doc) - { - this.FromUserName = doc.Root.Element("FromUserName").Value; - this.ToUserName = doc.Root.Element("ToUserName").Value; - this.CreateTime = long.Parse(doc.Root.Element("CreateTime").Value); - } - public string AppId { get; set; } - public string FromUserName { get; set; } - public string ToUserName { get; set; } - public long CreateTime { get; set; } - public virtual RequestInfoType InfoType - { - get { return RequestInfoType.component_verify_ticket; } - } - - - public virtual async Task Handler() - { - return true; - } - - } -} +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace Hncore.Wx.Open +{ + + /// + /// 请求消息 + /// + public class MessageMPBase : IMessageBase + { + + public MessageMPBase(XDocument doc) + { + this.FromUserName = doc.Root.Element("FromUserName").Value; + this.ToUserName = doc.Root.Element("ToUserName").Value; + this.CreateTime = long.Parse(doc.Root.Element("CreateTime").Value); + } + public string AppId { get; set; } + public string FromUserName { get; set; } + public string ToUserName { get; set; } + public long CreateTime { get; set; } + public virtual RequestInfoType InfoType + { + get { return RequestInfoType.component_verify_ticket; } + } + + + public virtual async Task Handler() + { + return true; + } + + } +} diff --git a/Infrastructure/WxApi/Notice/OpenMessage/MessageAuthorized.cs b/Infrastructure/WxApi/Notice/OpenMessage/MessageAuthorized.cs index 8d26d4a..eeb6545 100644 --- a/Infrastructure/WxApi/Notice/OpenMessage/MessageAuthorized.cs +++ b/Infrastructure/WxApi/Notice/OpenMessage/MessageAuthorized.cs @@ -1,45 +1,45 @@ -/* - - 第三方平台appid - 1413192760 - authorized - 公众号appid - 授权码(code) - 过期时间 - - */ -using System; -using System.Xml.Linq; - -namespace Hncore.Wx.Open -{ - /// - /// 授权成功通知 - /// - public class MessageAuthorized : MessageOpenBase - { - public MessageAuthorized(XDocument doc) : base(doc) - { - this.AuthorizerAppid = doc.Root.Element("AuthorizerAppid").Value; - this.AuthorizationCode = doc.Root.Element("AuthorizationCode").Value; - this.AuthorizationCodeExpiredTime = DateTimeOffset.Parse(doc.Root.Element("AuthorizationCodeExpiredTime").Value); - } - public override RequestInfoType InfoType - { - get { return RequestInfoType.authorized; } - } - - /// - /// 公众号appid - /// - public string AuthorizerAppid { get; set; } - /// - /// 授权码(code) - /// - public string AuthorizationCode { get; set; } - /// - /// 过期时间 - /// - public DateTimeOffset AuthorizationCodeExpiredTime { get; set; } - } -} +/* + + 第三方平台appid + 1413192760 + authorized + 公众号appid + 授权码(code) + 过期时间 + + */ +using System; +using System.Xml.Linq; + +namespace Hncore.Wx.Open +{ + /// + /// 授权成功通知 + /// + public class MessageAuthorized : MessageOpenBase + { + public MessageAuthorized(XDocument doc) : base(doc) + { + this.AuthorizerAppid = doc.Root.Element("AuthorizerAppid").Value; + this.AuthorizationCode = doc.Root.Element("AuthorizationCode").Value; + this.AuthorizationCodeExpiredTime = DateTimeOffset.Parse(doc.Root.Element("AuthorizationCodeExpiredTime").Value); + } + public override RequestInfoType InfoType + { + get { return RequestInfoType.authorized; } + } + + /// + /// 公众号appid + /// + public string AuthorizerAppid { get; set; } + /// + /// 授权码(code) + /// + public string AuthorizationCode { get; set; } + /// + /// 过期时间 + /// + public DateTimeOffset AuthorizationCodeExpiredTime { get; set; } + } +} diff --git a/Infrastructure/WxApi/Notice/OpenMessage/MessageComponentVerifyTicket.cs b/Infrastructure/WxApi/Notice/OpenMessage/MessageComponentVerifyTicket.cs index 580ea9e..2b45ab7 100644 --- a/Infrastructure/WxApi/Notice/OpenMessage/MessageComponentVerifyTicket.cs +++ b/Infrastructure/WxApi/Notice/OpenMessage/MessageComponentVerifyTicket.cs @@ -1,32 +1,32 @@ -using Hncore.Pass.MsgCenter.Constant; -using System.Threading.Tasks; -using System.Xml.Linq; - -namespace Hncore.Wx.Open -{ - -// -// -// 1413192605 -// -// -// - public class MessageComponentVerifyTicket : MessageOpenBase - { - public MessageComponentVerifyTicket(XDocument doc):base(doc) - { - this.ComponentVerifyTicket = doc.Root.Element("ComponentVerifyTicket").Value; - } - public override RequestInfoType InfoType - { - get { return RequestInfoType.component_verify_ticket; } - } - public string ComponentVerifyTicket { get; set; } - - public override async Task Handler() - { - //把ticket存入redis中 - return await RedisHelper.SetAsync(ConstantConfig.Redis_Psipwechat_Ticket_Key, this.ComponentVerifyTicket); - } - } -} +using Hncore.Pass.MsgCenter.Constant; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace Hncore.Wx.Open +{ + +// +// +// 1413192605 +// +// +// + public class MessageComponentVerifyTicket : MessageOpenBase + { + public MessageComponentVerifyTicket(XDocument doc):base(doc) + { + this.ComponentVerifyTicket = doc.Root.Element("ComponentVerifyTicket").Value; + } + public override RequestInfoType InfoType + { + get { return RequestInfoType.component_verify_ticket; } + } + public string ComponentVerifyTicket { get; set; } + + public override async Task Handler() + { + //把ticket存入redis中 + return await RedisHelper.SetAsync(ConstantConfig.Redis_Psipwechat_Ticket_Key, this.ComponentVerifyTicket); + } + } +} diff --git a/Infrastructure/WxApi/Notice/OpenMessage/MessageOpenBase.cs b/Infrastructure/WxApi/Notice/OpenMessage/MessageOpenBase.cs index b43e696..878858d 100644 --- a/Infrastructure/WxApi/Notice/OpenMessage/MessageOpenBase.cs +++ b/Infrastructure/WxApi/Notice/OpenMessage/MessageOpenBase.cs @@ -1,28 +1,28 @@ -using System.Threading.Tasks; -using System.Xml.Linq; - -namespace Hncore.Wx.Open -{ - - /// - /// 请求消息 - /// - public class MessageOpenBase : IMessageBase - { - public MessageOpenBase(XDocument doc) - { - this.AppId = doc.Root.Element("AppId").Value; - this.CreateTime = long.Parse(doc.Root.Element("CreateTime").Value); - } - public string AppId { get; set; } - public long CreateTime { get; set; } - public virtual RequestInfoType InfoType - { - get { return RequestInfoType.component_verify_ticket; } - } - public virtual async Task Handler() - { - return true; - } - } -} +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace Hncore.Wx.Open +{ + + /// + /// 请求消息 + /// + public class MessageOpenBase : IMessageBase + { + public MessageOpenBase(XDocument doc) + { + this.AppId = doc.Root.Element("AppId").Value; + this.CreateTime = long.Parse(doc.Root.Element("CreateTime").Value); + } + public string AppId { get; set; } + public long CreateTime { get; set; } + public virtual RequestInfoType InfoType + { + get { return RequestInfoType.component_verify_ticket; } + } + public virtual async Task Handler() + { + return true; + } + } +} diff --git a/Infrastructure/WxApi/Notice/OpenMessage/MessageThirdFasteRegister.cs b/Infrastructure/WxApi/Notice/OpenMessage/MessageThirdFasteRegister.cs index 57ab14b..2e1f426 100644 --- a/Infrastructure/WxApi/Notice/OpenMessage/MessageThirdFasteRegister.cs +++ b/Infrastructure/WxApi/Notice/OpenMessage/MessageThirdFasteRegister.cs @@ -1,70 +1,70 @@ -using System; -using System.Xml.Linq; - -namespace Hncore.Wx.Open -{ - /// - /// 注册审核事件推送 - /// - public class MessageThirdFasteRegister : MessageOpenBase - { - public MessageThirdFasteRegister(XDocument doc) : base(doc) - { - - } - public override RequestInfoType InfoType - { - get { return RequestInfoType.notify_third_fasteregister; } - } - - /// - /// 创建小程序appid - /// - public string appid { get; set; } - - public string status { get; set; } - /// - /// 第三方授权码 - /// - public string auth_code { get; set; } - - public string msg { get; set; } - - /// - /// 注册时提交的资料 - /// - public info info {get;set;} - } - - /// - /// 注册时提交的资料信息 - /// - public class info - { - /// - /// 企业名称 - /// - public string name { get; set; } - - /// - /// 企业代码 - /// - public string code { get; set; } - /// - /// 企业代码类型 - /// - public CodeType code_type { get; set; } - /// - /// 法人微信号 - /// - public string legal_persona_wechat { get; set; } - /// - /// 法人姓名 - /// - public string legal_persona_name { get; set; } - /// - /// 第三方联系电话 - /// - public string component_phone { get; set; } - } -} +using System; +using System.Xml.Linq; + +namespace Hncore.Wx.Open +{ + /// + /// 注册审核事件推送 + /// + public class MessageThirdFasteRegister : MessageOpenBase + { + public MessageThirdFasteRegister(XDocument doc) : base(doc) + { + + } + public override RequestInfoType InfoType + { + get { return RequestInfoType.notify_third_fasteregister; } + } + + /// + /// 创建小程序appid + /// + public string appid { get; set; } + + public string status { get; set; } + /// + /// 第三方授权码 + /// + public string auth_code { get; set; } + + public string msg { get; set; } + + /// + /// 注册时提交的资料 + /// + public info info {get;set;} + } + + /// + /// 注册时提交的资料信息 + /// + public class info + { + /// + /// 企业名称 + /// + public string name { get; set; } + + /// + /// 企业代码 + /// + public string code { get; set; } + /// + /// 企业代码类型 + /// + public CodeType code_type { get; set; } + /// + /// 法人微信号 + /// + public string legal_persona_wechat { get; set; } + /// + /// 法人姓名 + /// + public string legal_persona_name { get; set; } + /// + /// 第三方联系电话 + /// + public string component_phone { get; set; } + } +} diff --git a/Infrastructure/WxApi/Notice/OpenMessage/MessageUnauthorized.cs b/Infrastructure/WxApi/Notice/OpenMessage/MessageUnauthorized.cs index 64102ee..f254ae0 100644 --- a/Infrastructure/WxApi/Notice/OpenMessage/MessageUnauthorized.cs +++ b/Infrastructure/WxApi/Notice/OpenMessage/MessageUnauthorized.cs @@ -1,44 +1,44 @@ - -/* - - 第三方平台appid - 1413192760 - unauthorized - 公众号appid - -*/ -using Hncore.Infrastructure.Common; -using System; -using System.Threading.Tasks; -using System.Xml.Linq; - -namespace Hncore.Wx.Open -{ - public class MessageUnauthorized : MessageOpenBase - { - public MessageUnauthorized(XDocument doc) : base(doc) - { - this.AuthorizerAppid = doc.Root.Element("AuthorizerAppid").Value; - } - public override RequestInfoType InfoType - { - get { return RequestInfoType.unauthorized; } - } - public string AuthorizerAppid { get; set; } - - public override async Task Handler() - { - if (!string.IsNullOrEmpty(this.AuthorizerAppid)) - { - try - { - } - catch(Exception ex) - { - LogHelper.Error("MessageUnauthorized",ex.Message); - } - } - return false; - } - } -} + +/* + + 第三方平台appid + 1413192760 + unauthorized + 公众号appid + +*/ +using Hncore.Infrastructure.Common; +using System; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace Hncore.Wx.Open +{ + public class MessageUnauthorized : MessageOpenBase + { + public MessageUnauthorized(XDocument doc) : base(doc) + { + this.AuthorizerAppid = doc.Root.Element("AuthorizerAppid").Value; + } + public override RequestInfoType InfoType + { + get { return RequestInfoType.unauthorized; } + } + public string AuthorizerAppid { get; set; } + + public override async Task Handler() + { + if (!string.IsNullOrEmpty(this.AuthorizerAppid)) + { + try + { + } + catch(Exception ex) + { + LogHelper.Error("MessageUnauthorized",ex.Message); + } + } + return false; + } + } +} diff --git a/Infrastructure/WxApi/Notice/OpenMessage/MessageUpdateAuthorized.cs b/Infrastructure/WxApi/Notice/OpenMessage/MessageUpdateAuthorized.cs index c1b95aa..2bdc757 100644 --- a/Infrastructure/WxApi/Notice/OpenMessage/MessageUpdateAuthorized.cs +++ b/Infrastructure/WxApi/Notice/OpenMessage/MessageUpdateAuthorized.cs @@ -1,36 +1,36 @@ - -using System; -using System.Xml.Linq; - -namespace Hncore.Wx.Open -{ - /// - /// 授权更新通知 - /// - public class MessageUpdateAuthorized : MessageOpenBase - { - public MessageUpdateAuthorized(XDocument doc) : base(doc) - { - this.AuthorizerAppid = doc.Root.Element("AuthorizerAppid").Value; - this.AuthorizationCode = doc.Root.Element("AuthorizationCode").Value; - this.AuthorizationCodeExpiredTime = DateTimeOffset.Parse(doc.Root.Element("AuthorizationCodeExpiredTime").Value); - } - public override RequestInfoType InfoType - { - get { return RequestInfoType.updateauthorized; } - } - - /// - /// 公众号appid - /// - public string AuthorizerAppid { get; set; } - /// - /// 授权码(code) - /// - public string AuthorizationCode { get; set; } - /// - /// 过期时间 - /// - public DateTimeOffset AuthorizationCodeExpiredTime { get; set; } - } -} + +using System; +using System.Xml.Linq; + +namespace Hncore.Wx.Open +{ + /// + /// 授权更新通知 + /// + public class MessageUpdateAuthorized : MessageOpenBase + { + public MessageUpdateAuthorized(XDocument doc) : base(doc) + { + this.AuthorizerAppid = doc.Root.Element("AuthorizerAppid").Value; + this.AuthorizationCode = doc.Root.Element("AuthorizationCode").Value; + this.AuthorizationCodeExpiredTime = DateTimeOffset.Parse(doc.Root.Element("AuthorizationCodeExpiredTime").Value); + } + public override RequestInfoType InfoType + { + get { return RequestInfoType.updateauthorized; } + } + + /// + /// 公众号appid + /// + public string AuthorizerAppid { get; set; } + /// + /// 授权码(code) + /// + public string AuthorizationCode { get; set; } + /// + /// 过期时间 + /// + public DateTimeOffset AuthorizationCodeExpiredTime { get; set; } + } +} diff --git a/Infrastructure/WxApi/Request/GetAuthenticationUrlRequest.cs b/Infrastructure/WxApi/Request/GetAuthenticationUrlRequest.cs index 62e3a2a..4159732 100644 --- a/Infrastructure/WxApi/Request/GetAuthenticationUrlRequest.cs +++ b/Infrastructure/WxApi/Request/GetAuthenticationUrlRequest.cs @@ -1,15 +1,15 @@ -namespace Etor.Wx.Open -{ - /// - /// 获取公众号授权连接的URL - /// - public class GetAuthenticationUrlRequest - { - public string component_appid { get; set; } - /// - /// 从来 - /// - public string pre_auth_code { get; set; } - public string redirect_uri { get; set; } - } +namespace Etor.Wx.Open +{ + /// + /// 获取公众号授权连接的URL + /// + public class GetAuthenticationUrlRequest + { + public string component_appid { get; set; } + /// + /// 从来 + /// + public string pre_auth_code { get; set; } + public string redirect_uri { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Request/GetAuthorizerClientUserOpenIdRequest.cs b/Infrastructure/WxApi/Request/GetAuthorizerClientUserOpenIdRequest.cs index 13437e0..04d9313 100644 --- a/Infrastructure/WxApi/Request/GetAuthorizerClientUserOpenIdRequest.cs +++ b/Infrastructure/WxApi/Request/GetAuthorizerClientUserOpenIdRequest.cs @@ -1,10 +1,10 @@ -namespace Etor.Wx.Open -{ - public class GetAuthorizerClientUserOpenIdRequest - { - public object AuthorizerAppId { get; set; } - public object CallbackCode { get; set; } - public object AppID { get; set; } - public object ComponentAccessToken { get; set; } - } +namespace Etor.Wx.Open +{ + public class GetAuthorizerClientUserOpenIdRequest + { + public object AuthorizerAppId { get; set; } + public object CallbackCode { get; set; } + public object AppID { get; set; } + public object ComponentAccessToken { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Request/GetAuthorizerInfoRequest.cs b/Infrastructure/WxApi/Request/GetAuthorizerInfoRequest.cs index 7ab68e3..2fef0be 100644 --- a/Infrastructure/WxApi/Request/GetAuthorizerInfoRequest.cs +++ b/Infrastructure/WxApi/Request/GetAuthorizerInfoRequest.cs @@ -1,17 +1,17 @@ -namespace Etor.Wx.Open -{ - - - //{"authorizer_info":{"nick_name":"etor生活","head_img":"http:\/\/wx.qlogo.cn\/mmopen\/nlGmMCWo3wjyEnPPhOv2ygZbyEfyHmQHURK1odOyqGTys5kpdwFCmFo4PV6j2lCtkIWzqCJJvy9Ml7LS1XqUY3wsYn5lHKRX\/0","service_type_info":{"id":2},"verify_type_info":{"id":0},"user_name":"gh_d2ce4e1abd93","alias":"","qrcode_url":"http:\/\/mmbiz.qpic.cn\/mmbiz_jpg\/OdctpfnnOo6dEuSOQRFTK9V4ue1yxH7UGAZuKtJlN5M64Grm8tRWgSEnrYWIPlSUf2AaKwialhGWh4wLbHbZ1ng\/0","business_info":{"open_pay":0,"open_shake":0,"open_scan":0,"open_card":0,"open_store":0},"idc":1,"principal_name":"河南云拓智能科技有限公司","signature":"etor生活,围绕商业综合体为周边人群提供智慧、便捷化服务的生活助手"},"authorization_info":{"authorizer_appid":"wx5cf944c37bf234ee","authorizer_refresh_token":"refreshtoken@@@fxrfTkTrpHPEHMDjGFWvljuB_JFW4VPQY7kmkbjamXY","func_info":[{"funcscope_category":{"id":1}},{"funcscope_category":{"id":15}},{"funcscope_category":{"id":4}},{"funcscope_category":{"id":7}},{"funcscope_category":{"id":2}},{"funcscope_category":{"id":3}},{"funcscope_category":{"id":11}}]}} - - - - - - public class GetAuthorizerInfoRequest - { - public string component_access_token { get; set; } - public string component_appid { get; set; } - public string authorizer_appid { get; set; } - } +namespace Etor.Wx.Open +{ + + + //{"authorizer_info":{"nick_name":"etor生活","head_img":"http:\/\/wx.qlogo.cn\/mmopen\/nlGmMCWo3wjyEnPPhOv2ygZbyEfyHmQHURK1odOyqGTys5kpdwFCmFo4PV6j2lCtkIWzqCJJvy9Ml7LS1XqUY3wsYn5lHKRX\/0","service_type_info":{"id":2},"verify_type_info":{"id":0},"user_name":"gh_d2ce4e1abd93","alias":"","qrcode_url":"http:\/\/mmbiz.qpic.cn\/mmbiz_jpg\/OdctpfnnOo6dEuSOQRFTK9V4ue1yxH7UGAZuKtJlN5M64Grm8tRWgSEnrYWIPlSUf2AaKwialhGWh4wLbHbZ1ng\/0","business_info":{"open_pay":0,"open_shake":0,"open_scan":0,"open_card":0,"open_store":0},"idc":1,"principal_name":"河南云拓智能科技有限公司","signature":"etor生活,围绕商业综合体为周边人群提供智慧、便捷化服务的生活助手"},"authorization_info":{"authorizer_appid":"wx5cf944c37bf234ee","authorizer_refresh_token":"refreshtoken@@@fxrfTkTrpHPEHMDjGFWvljuB_JFW4VPQY7kmkbjamXY","func_info":[{"funcscope_category":{"id":1}},{"funcscope_category":{"id":15}},{"funcscope_category":{"id":4}},{"funcscope_category":{"id":7}},{"funcscope_category":{"id":2}},{"funcscope_category":{"id":3}},{"funcscope_category":{"id":11}}]}} + + + + + + public class GetAuthorizerInfoRequest + { + public string component_access_token { get; set; } + public string component_appid { get; set; } + public string authorizer_appid { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Request/GetAuthorizerInvokeAccessTokenRequest.cs b/Infrastructure/WxApi/Request/GetAuthorizerInvokeAccessTokenRequest.cs index a67218a..3f7937e 100644 --- a/Infrastructure/WxApi/Request/GetAuthorizerInvokeAccessTokenRequest.cs +++ b/Infrastructure/WxApi/Request/GetAuthorizerInvokeAccessTokenRequest.cs @@ -1,25 +1,25 @@ -namespace Etor.Wx.Open -{ - /// - /// 获取代表的第三方App的api执行权限 - /// - public class GetAuthorizerInvokeAccessTokenRequest - { - /// - /// 第三方平台的访问令牌 - /// - public string component_access_token { get; set; } - /// - /// 第三方平台的AppId - /// - public string component_appid { get; set; } - /// - /// 授权码,在公众号授权后,发送到回调地址上 - /// 从拿到authorization_code - /// - public string authorization_code - { - get; set; - } - } +namespace Etor.Wx.Open +{ + /// + /// 获取代表的第三方App的api执行权限 + /// + public class GetAuthorizerInvokeAccessTokenRequest + { + /// + /// 第三方平台的访问令牌 + /// + public string component_access_token { get; set; } + /// + /// 第三方平台的AppId + /// + public string component_appid { get; set; } + /// + /// 授权码,在公众号授权后,发送到回调地址上 + /// 从拿到authorization_code + /// + public string authorization_code + { + get; set; + } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Request/GetComponentAccessTokenRequest.cs b/Infrastructure/WxApi/Request/GetComponentAccessTokenRequest.cs index 91d6d4d..ad8c3bb 100644 --- a/Infrastructure/WxApi/Request/GetComponentAccessTokenRequest.cs +++ b/Infrastructure/WxApi/Request/GetComponentAccessTokenRequest.cs @@ -1,17 +1,17 @@ -namespace Etor.Wx.Open -{ - /// - /// 获取第三方App的AccessToken - /// 使用 - /// - /// - public class GetComponentAccessTokenRequest - { - public string component_appid { get; set; } - public string component_appsecret { get; set; } - /// - /// 这个请求可以拿到 - /// - public string component_verify_ticket { get; set; } - } +namespace Etor.Wx.Open +{ + /// + /// 获取第三方App的AccessToken + /// 使用 + /// + /// + public class GetComponentAccessTokenRequest + { + public string component_appid { get; set; } + public string component_appsecret { get; set; } + /// + /// 这个请求可以拿到 + /// + public string component_verify_ticket { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Request/GetComponentVerifyTicketRequest.cs b/Infrastructure/WxApi/Request/GetComponentVerifyTicketRequest.cs index 047dc13..48b84d9 100644 --- a/Infrastructure/WxApi/Request/GetComponentVerifyTicketRequest.cs +++ b/Infrastructure/WxApi/Request/GetComponentVerifyTicketRequest.cs @@ -1,10 +1,10 @@ -namespace Etor.Wx.Open -{ - /// - /// 从微信推送的消息内拉取ticket - /// - public class GetComponentVerifyTicketRequest - { - public string TicketSourceServerUrl { get; set; } - } +namespace Etor.Wx.Open +{ + /// + /// 从微信推送的消息内拉取ticket + /// + public class GetComponentVerifyTicketRequest + { + public string TicketSourceServerUrl { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Request/GetPreAuthCodeRequest.cs b/Infrastructure/WxApi/Request/GetPreAuthCodeRequest.cs index 7a6fcbd..f6b3db3 100644 --- a/Infrastructure/WxApi/Request/GetPreAuthCodeRequest.cs +++ b/Infrastructure/WxApi/Request/GetPreAuthCodeRequest.cs @@ -1,11 +1,11 @@ -namespace Etor.Wx.Open -{ - public class GetPreAuthCodeRequest - { - /// - /// 拿到的 - /// - public string component_access_token { get; set; } - public string component_appid { get; set; } - } +namespace Etor.Wx.Open +{ + public class GetPreAuthCodeRequest + { + /// + /// 拿到的 + /// + public string component_access_token { get; set; } + public string component_appid { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Request/GetSavedAuthorizerInfoRequest.cs b/Infrastructure/WxApi/Request/GetSavedAuthorizerInfoRequest.cs index 018d37c..46d64a8 100644 --- a/Infrastructure/WxApi/Request/GetSavedAuthorizerInfoRequest.cs +++ b/Infrastructure/WxApi/Request/GetSavedAuthorizerInfoRequest.cs @@ -1,8 +1,8 @@ -namespace Etor.Wx.Open -{ - public class GetSavedAuthorizerInfoRequest - { - public string DomainUrl { get; set; } - public string AppId { get; set; } - } +namespace Etor.Wx.Open +{ + public class GetSavedAuthorizerInfoRequest + { + public string DomainUrl { get; set; } + public string AppId { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Request/GetWechatTicketRequest.cs b/Infrastructure/WxApi/Request/GetWechatTicketRequest.cs index 600d7ec..308cbf4 100644 --- a/Infrastructure/WxApi/Request/GetWechatTicketRequest.cs +++ b/Infrastructure/WxApi/Request/GetWechatTicketRequest.cs @@ -1,9 +1,9 @@ -namespace Etor.Wx.Open -{ - /// - /// 获取wechat推送的ticket - /// - public class GetWechatTicketRequest - { - } +namespace Etor.Wx.Open +{ + /// + /// 获取wechat推送的ticket + /// + public class GetWechatTicketRequest + { + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Request/GetWxJsConfigRequest.cs b/Infrastructure/WxApi/Request/GetWxJsConfigRequest.cs index b72c469..112a557 100644 --- a/Infrastructure/WxApi/Request/GetWxJsConfigRequest.cs +++ b/Infrastructure/WxApi/Request/GetWxJsConfigRequest.cs @@ -1,51 +1,51 @@ -using Hncore.Infrastructure.Extension; -using System; -using System.Collections.Generic; - -namespace Etor.Wx.Open -{ - public class jsapi_ticket - { - public static object get_locker = new object(); - public int errcode { get; set; } - public string errmsg { get; set; } - public string ticket { get; set; } - public int expires_in { get; set; } - public int created_timestamp { get; set; } - - public bool is_expired - { - get - { - var dt = (DateTime.Now.TimestampFrom19700101() - this.created_timestamp); - - return errcode != 0 || dt < 0 || dt > 6000; - } - } - } - public class wx_config - { - public bool debug { get; set; } - public string appId { get; set; } - public string timestamp { get; set; } - public string nonceStr { get; set; } - public string signature { get; set; } - public List jsApiList { get; set; } - } - - - /// - /// 获取wxjs配置请求 - /// - public class GetWxJsConfigRequest - { - /// - /// 公众号appid - /// - public string Appid { get; set; } - /// - /// 当前的请求地址 - /// - public string CurrentUrl { get; set; } - } +using Hncore.Infrastructure.Extension; +using System; +using System.Collections.Generic; + +namespace Etor.Wx.Open +{ + public class jsapi_ticket + { + public static object get_locker = new object(); + public int errcode { get; set; } + public string errmsg { get; set; } + public string ticket { get; set; } + public int expires_in { get; set; } + public int created_timestamp { get; set; } + + public bool is_expired + { + get + { + var dt = (DateTime.Now.TimestampFrom19700101() - this.created_timestamp); + + return errcode != 0 || dt < 0 || dt > 6000; + } + } + } + public class wx_config + { + public bool debug { get; set; } + public string appId { get; set; } + public string timestamp { get; set; } + public string nonceStr { get; set; } + public string signature { get; set; } + public List jsApiList { get; set; } + } + + + /// + /// 获取wxjs配置请求 + /// + public class GetWxJsConfigRequest + { + /// + /// 公众号appid + /// + public string Appid { get; set; } + /// + /// 当前的请求地址 + /// + public string CurrentUrl { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Request/RefreshAuthorizerInvokeAccessTokenRequest.cs b/Infrastructure/WxApi/Request/RefreshAuthorizerInvokeAccessTokenRequest.cs index 7ace0a4..6d58180 100644 --- a/Infrastructure/WxApi/Request/RefreshAuthorizerInvokeAccessTokenRequest.cs +++ b/Infrastructure/WxApi/Request/RefreshAuthorizerInvokeAccessTokenRequest.cs @@ -1,19 +1,19 @@ -namespace Etor.Wx.Open -{ - // { - //"component_appid":"appid_value", - //"authorizer_appid":"auth_appid_value", - //"authorizer_refresh_token":"refresh_token_value", - //} - - /// - /// 刷新从得到的AccessToken - /// - public class RefreshAuthorizerInvokeAccessTokenRequest - { - public string component_appid { get; set; } - public string authorizer_appid { get; set; } - public string authorizer_refresh_token { get; set; } - public string component_access_token { get; set; } - } +namespace Etor.Wx.Open +{ + // { + //"component_appid":"appid_value", + //"authorizer_appid":"auth_appid_value", + //"authorizer_refresh_token":"refresh_token_value", + //} + + /// + /// 刷新从得到的AccessToken + /// + public class RefreshAuthorizerInvokeAccessTokenRequest + { + public string component_appid { get; set; } + public string authorizer_appid { get; set; } + public string authorizer_refresh_token { get; set; } + public string component_access_token { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Request/SaveAuthorizerInfoRequest.cs b/Infrastructure/WxApi/Request/SaveAuthorizerInfoRequest.cs index 1b906b2..a81206d 100644 --- a/Infrastructure/WxApi/Request/SaveAuthorizerInfoRequest.cs +++ b/Infrastructure/WxApi/Request/SaveAuthorizerInfoRequest.cs @@ -1,9 +1,9 @@ -namespace Hncore.Wx.Open -{ - public class SaveAuthorizerInfoRequest - { - public string Domain { get; set; } - public authorizer_info AuthorizerInfo { get; set; } - public authorization_info AuthorizationInfo { get; set; } - } +namespace Hncore.Wx.Open +{ + public class SaveAuthorizerInfoRequest + { + public string Domain { get; set; } + public authorizer_info AuthorizerInfo { get; set; } + public authorization_info AuthorizationInfo { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Request/SaveWechatAppMenuRequest.cs b/Infrastructure/WxApi/Request/SaveWechatAppMenuRequest.cs index 2304515..7a75148 100644 --- a/Infrastructure/WxApi/Request/SaveWechatAppMenuRequest.cs +++ b/Infrastructure/WxApi/Request/SaveWechatAppMenuRequest.cs @@ -1,8 +1,8 @@ -using System.Collections.Generic; - -namespace Hncore.Wx.Open -{ - public class SaveWechatAppMenuRequest - { - } +using System.Collections.Generic; + +namespace Hncore.Wx.Open +{ + public class SaveWechatAppMenuRequest + { + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Request/UpdateWechatTicketRequest.cs b/Infrastructure/WxApi/Request/UpdateWechatTicketRequest.cs index 1dd0292..2a17695 100644 --- a/Infrastructure/WxApi/Request/UpdateWechatTicketRequest.cs +++ b/Infrastructure/WxApi/Request/UpdateWechatTicketRequest.cs @@ -1,10 +1,10 @@ -namespace Etor.Wx.Open -{ - /// - /// 更新微信推送的票据 - /// - public class UpdateWechatTicketRequest - { - public string NewTicket { get; set; } - } +namespace Etor.Wx.Open +{ + /// + /// 更新微信推送的票据 + /// + public class UpdateWechatTicketRequest + { + public string NewTicket { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Request/UploadWxImageMaterialRequest.cs b/Infrastructure/WxApi/Request/UploadWxImageMaterialRequest.cs index b5f9ba7..798cd91 100644 --- a/Infrastructure/WxApi/Request/UploadWxImageMaterialRequest.cs +++ b/Infrastructure/WxApi/Request/UploadWxImageMaterialRequest.cs @@ -1,38 +1,38 @@ -namespace Etor.Wx.Open -{ - public class UploadWxImageMaterialRequest - { - /// - /// 是否永久素材 - /// - public bool IsTemp { get; set; } - /// - /// image 图片 thumb 缩略图 - /// - public string MediaType { get; set; } - /// - /// 图片名称 - /// - public string imagename { get; set; } - /// - /// 分组id,默认0 - /// - public int groupid { get; set; } - - /// - /// 小区/写字楼编码 - /// - public string projectcode { get; set; } - - /// - /// 公众号appid - /// - public string appid { get; set; } - /// - ///图片地址 - /// - public string url { get; set; } - - - } -} +namespace Etor.Wx.Open +{ + public class UploadWxImageMaterialRequest + { + /// + /// 是否永久素材 + /// + public bool IsTemp { get; set; } + /// + /// image 图片 thumb 缩略图 + /// + public string MediaType { get; set; } + /// + /// 图片名称 + /// + public string imagename { get; set; } + /// + /// 分组id,默认0 + /// + public int groupid { get; set; } + + /// + /// 小区/写字楼编码 + /// + public string projectcode { get; set; } + + /// + /// 公众号appid + /// + public string appid { get; set; } + /// + ///图片地址 + /// + public string url { get; set; } + + + } +} diff --git a/Infrastructure/WxApi/Request/UploadWxMediaRequest.cs b/Infrastructure/WxApi/Request/UploadWxMediaRequest.cs index c1fac1a..34eca42 100644 --- a/Infrastructure/WxApi/Request/UploadWxMediaRequest.cs +++ b/Infrastructure/WxApi/Request/UploadWxMediaRequest.cs @@ -1,9 +1,9 @@ -using System.Collections.Generic; - -namespace Etor.Wx.Open -{ - public class UploadWxMediaRequest - { - - } -} +using System.Collections.Generic; + +namespace Etor.Wx.Open +{ + public class UploadWxMediaRequest + { + + } +} diff --git a/Infrastructure/WxApi/Request/WechatRequestBase.cs b/Infrastructure/WxApi/Request/WechatRequestBase.cs index f53b67e..6c1ccc9 100644 --- a/Infrastructure/WxApi/Request/WechatRequestBase.cs +++ b/Infrastructure/WxApi/Request/WechatRequestBase.cs @@ -1,16 +1,16 @@ -namespace Etor.Wx.Open -{ - public class WechatRequestBase - { - public int OwnerID { get; set; } - public int OperaterID { get; set; } - public int ProjectCode { get; set; } - protected string _url; - public string url { get { return _url; } } - public string access_token { get; set; } - } - public class WechatRequestBase : WechatRequestBase - { - public TData post_body { get; set; } - } -} +namespace Etor.Wx.Open +{ + public class WechatRequestBase + { + public int OwnerID { get; set; } + public int OperaterID { get; set; } + public int ProjectCode { get; set; } + protected string _url; + public string url { get { return _url; } } + public string access_token { get; set; } + } + public class WechatRequestBase : WechatRequestBase + { + public TData post_body { get; set; } + } +} diff --git a/Infrastructure/WxApi/Response/CreateQrcodeResponse.cs b/Infrastructure/WxApi/Response/CreateQrcodeResponse.cs index e05b028..591dc27 100644 --- a/Infrastructure/WxApi/Response/CreateQrcodeResponse.cs +++ b/Infrastructure/WxApi/Response/CreateQrcodeResponse.cs @@ -1,10 +1,10 @@ -using System.Collections.Generic; - -namespace Hncore.Wx.Open -{ - public class CreateQrcodeResponse : ResponseBase - { - public string ticket { get; set; } - public string url { get; set; } - } +using System.Collections.Generic; + +namespace Hncore.Wx.Open +{ + public class CreateQrcodeResponse : ResponseBase + { + public string ticket { get; set; } + public string url { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/GetAuthenticationUrlResponse.cs b/Infrastructure/WxApi/Response/GetAuthenticationUrlResponse.cs index 5a2b600..db0aafa 100644 --- a/Infrastructure/WxApi/Response/GetAuthenticationUrlResponse.cs +++ b/Infrastructure/WxApi/Response/GetAuthenticationUrlResponse.cs @@ -1,6 +1,6 @@ -namespace Hncore.Wx.Open -{ - public class GetAuthenticationUrlResponse : ResponseBase - { - } +namespace Hncore.Wx.Open +{ + public class GetAuthenticationUrlResponse : ResponseBase + { + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/GetAuthorizerClientUserOpenIdResponse.cs b/Infrastructure/WxApi/Response/GetAuthorizerClientUserOpenIdResponse.cs index d4d6630..c3e335e 100644 --- a/Infrastructure/WxApi/Response/GetAuthorizerClientUserOpenIdResponse.cs +++ b/Infrastructure/WxApi/Response/GetAuthorizerClientUserOpenIdResponse.cs @@ -1,7 +1,7 @@ -namespace Hncore.Wx.Open -{ - public class GetAuthorizerClientUserOpenIdResponse : ResponseBase - { - public wechat_access_token AccessToken { get; set; } - } +namespace Hncore.Wx.Open +{ + public class GetAuthorizerClientUserOpenIdResponse : ResponseBase + { + public wechat_access_token AccessToken { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/GetAuthorizerInfoResponse.cs b/Infrastructure/WxApi/Response/GetAuthorizerInfoResponse.cs index 363b5a4..3a12add 100644 --- a/Infrastructure/WxApi/Response/GetAuthorizerInfoResponse.cs +++ b/Infrastructure/WxApi/Response/GetAuthorizerInfoResponse.cs @@ -1,9 +1,9 @@ -namespace Hncore.Wx.Open -{ - public class GetAuthorizerInfoResponse : ResponseBase - { - public authorizer_info authorizer_info { get; set; } - public authorization_info authorization_info { get; set; } - public string content { get; set; } - } +namespace Hncore.Wx.Open +{ + public class GetAuthorizerInfoResponse : ResponseBase + { + public authorizer_info authorizer_info { get; set; } + public authorization_info authorization_info { get; set; } + public string content { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/GetAuthorizerInvokeAccessTokenResponse.cs b/Infrastructure/WxApi/Response/GetAuthorizerInvokeAccessTokenResponse.cs index 7c3b167..1788b6b 100644 --- a/Infrastructure/WxApi/Response/GetAuthorizerInvokeAccessTokenResponse.cs +++ b/Infrastructure/WxApi/Response/GetAuthorizerInvokeAccessTokenResponse.cs @@ -1,32 +1,32 @@ -namespace Hncore.Wx.Open -{ - // { - //"authorization_info": - //{ - //"authorizer_appid": "wxf8b4f85f3a794e77", - //"authorizer_access_token": "QXjUqNqfYVH0yBE1iI_7vuN_9gQbpjfK7hYwJ3P7xOa88a89-Aga5x1NMYJyB8G2yKt1KCl0nPC3W9GJzw0Zzq_dBxc8pxIGUNi_bFes0qM", - //"expires_in": 7200, - //"authorizer_refresh_token": "dTo-YCXPL4llX-u1W1pPpnp8Hgm4wpJtlR6iV0doKdY", - //"func_info": - // [ - //{"funcscope_category": {"id": 1}}, - //{"funcscope_category": {"id": 2}}, - //{"funcscope_category": {"id": 3}} - //] - //} - //} - - - /// - /// 授权码换取访问令牌结果类 - /// - /// - /// - public class GetAuthorizerInvokeAccessTokenResponse:ResponseBase - { - /// - /// 授权信息对象 - /// - public authorization_info authorization_info { get; set; } - } +namespace Hncore.Wx.Open +{ + // { + //"authorization_info": + //{ + //"authorizer_appid": "wxf8b4f85f3a794e77", + //"authorizer_access_token": "QXjUqNqfYVH0yBE1iI_7vuN_9gQbpjfK7hYwJ3P7xOa88a89-Aga5x1NMYJyB8G2yKt1KCl0nPC3W9GJzw0Zzq_dBxc8pxIGUNi_bFes0qM", + //"expires_in": 7200, + //"authorizer_refresh_token": "dTo-YCXPL4llX-u1W1pPpnp8Hgm4wpJtlR6iV0doKdY", + //"func_info": + // [ + //{"funcscope_category": {"id": 1}}, + //{"funcscope_category": {"id": 2}}, + //{"funcscope_category": {"id": 3}} + //] + //} + //} + + + /// + /// 授权码换取访问令牌结果类 + /// + /// + /// + public class GetAuthorizerInvokeAccessTokenResponse:ResponseBase + { + /// + /// 授权信息对象 + /// + public authorization_info authorization_info { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/GetComponentAccessTokenResponse.cs b/Infrastructure/WxApi/Response/GetComponentAccessTokenResponse.cs index 714117d..1017bb2 100644 --- a/Infrastructure/WxApi/Response/GetComponentAccessTokenResponse.cs +++ b/Infrastructure/WxApi/Response/GetComponentAccessTokenResponse.cs @@ -1,18 +1,18 @@ -namespace Hncore.Wx.Open -{ - - // { - //"component_access_token":"61W3mEpU66027wgNZ_MhGHNQDHnFATkDa9-2llqrMBjUwxRSNPbVsMmyD-yq8wZETSoE5NQgecigDrSHkPtIYA", - //"expires_in":7200 - //} - - - /// - /// - /// - public class GetComponentAccessTokenResponse : ResponseBase - { - public string component_access_token { get; set; } - - } +namespace Hncore.Wx.Open +{ + + // { + //"component_access_token":"61W3mEpU66027wgNZ_MhGHNQDHnFATkDa9-2llqrMBjUwxRSNPbVsMmyD-yq8wZETSoE5NQgecigDrSHkPtIYA", + //"expires_in":7200 + //} + + + /// + /// + /// + public class GetComponentAccessTokenResponse : ResponseBase + { + public string component_access_token { get; set; } + + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/GetComponentVerifyTicketResponse.cs b/Infrastructure/WxApi/Response/GetComponentVerifyTicketResponse.cs index d5928ae..d669101 100644 --- a/Infrastructure/WxApi/Response/GetComponentVerifyTicketResponse.cs +++ b/Infrastructure/WxApi/Response/GetComponentVerifyTicketResponse.cs @@ -1,10 +1,10 @@ -namespace Hncore.Wx.Open -{ - /// - /// - /// - public class GetComponentVerifyTicketResponse:ResponseBase - { - public string ComponentVerifyTicket { get; set; } - } +namespace Hncore.Wx.Open +{ + /// + /// + /// + public class GetComponentVerifyTicketResponse:ResponseBase + { + public string ComponentVerifyTicket { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/GetGetWebAccessTokenResponse.cs b/Infrastructure/WxApi/Response/GetGetWebAccessTokenResponse.cs index b8c8975..5704134 100644 --- a/Infrastructure/WxApi/Response/GetGetWebAccessTokenResponse.cs +++ b/Infrastructure/WxApi/Response/GetGetWebAccessTokenResponse.cs @@ -1,10 +1,10 @@ -namespace Hncore.Wx.Open -{ - public class GetGetWebAccessTokenResponse : ResponseBase - { - public string access_token { get; set; } - public string refresh_token { get; set; } - public string openid { get; set; } - public string scope { get; set; } - } +namespace Hncore.Wx.Open +{ + public class GetGetWebAccessTokenResponse : ResponseBase + { + public string access_token { get; set; } + public string refresh_token { get; set; } + public string openid { get; set; } + public string scope { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/GetJsApiTicketResponse.cs b/Infrastructure/WxApi/Response/GetJsApiTicketResponse.cs index a456c9a..f97a26d 100644 --- a/Infrastructure/WxApi/Response/GetJsApiTicketResponse.cs +++ b/Infrastructure/WxApi/Response/GetJsApiTicketResponse.cs @@ -1,13 +1,13 @@ -using Hncore.Wx.Open; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Hncore.Pass.MsgCenter.WxOpen.Response -{ - public class GetJsApiTicketResponse : ResponseBase - { - public string ticket { get; set; } - } -} +using Hncore.Wx.Open; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Hncore.Pass.MsgCenter.WxOpen.Response +{ + public class GetJsApiTicketResponse : ResponseBase + { + public string ticket { get; set; } + } +} diff --git a/Infrastructure/WxApi/Response/GetMpAccessTokenResponse.cs b/Infrastructure/WxApi/Response/GetMpAccessTokenResponse.cs index 330c97c..428f3c5 100644 --- a/Infrastructure/WxApi/Response/GetMpAccessTokenResponse.cs +++ b/Infrastructure/WxApi/Response/GetMpAccessTokenResponse.cs @@ -1,12 +1,12 @@ -namespace Hncore.Wx.Open -{ - - //{"access_token":"ACCESS_TOKEN","expires_in":7200} - /// - /// - /// - public class GetAccessTokenResponse : ResponseBase - { - public string access_token { get; set; } - } +namespace Hncore.Wx.Open +{ + + //{"access_token":"ACCESS_TOKEN","expires_in":7200} + /// + /// + /// + public class GetAccessTokenResponse : ResponseBase + { + public string access_token { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/GetPreAuthCodeResponse.cs b/Infrastructure/WxApi/Response/GetPreAuthCodeResponse.cs index 2f73579..0964104 100644 --- a/Infrastructure/WxApi/Response/GetPreAuthCodeResponse.cs +++ b/Infrastructure/WxApi/Response/GetPreAuthCodeResponse.cs @@ -1,17 +1,17 @@ -namespace Hncore.Wx.Open -{ - - // { - //"pre_auth_code":"Cx_Dk6qiBE0Dmx4EmlT3oRfArPvwSQ-oa3NL_fwHM7VI08r52wazoZX2Rhpz1dEw", - //"expires_in":600 - //} - - - /// - /// - /// - public class GetPreAuthCodeResponse:ResponseBase - { - public string pre_auth_code { get; set; } - } +namespace Hncore.Wx.Open +{ + + // { + //"pre_auth_code":"Cx_Dk6qiBE0Dmx4EmlT3oRfArPvwSQ-oa3NL_fwHM7VI08r52wazoZX2Rhpz1dEw", + //"expires_in":600 + //} + + + /// + /// + /// + public class GetPreAuthCodeResponse:ResponseBase + { + public string pre_auth_code { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/GetSavedAuthorizerInfoResponse.cs b/Infrastructure/WxApi/Response/GetSavedAuthorizerInfoResponse.cs index 4d827fc..af10dbc 100644 --- a/Infrastructure/WxApi/Response/GetSavedAuthorizerInfoResponse.cs +++ b/Infrastructure/WxApi/Response/GetSavedAuthorizerInfoResponse.cs @@ -1,6 +1,6 @@ -namespace Hncore.Wx.Open -{ - public class GetSavedAuthorizerInfoResponse:ResponseBase - { - } +namespace Hncore.Wx.Open +{ + public class GetSavedAuthorizerInfoResponse:ResponseBase + { + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/GetTagsResponse.cs b/Infrastructure/WxApi/Response/GetTagsResponse.cs index 3e10a58..857383b 100644 --- a/Infrastructure/WxApi/Response/GetTagsResponse.cs +++ b/Infrastructure/WxApi/Response/GetTagsResponse.cs @@ -1,18 +1,18 @@ -using System.Collections.Generic; - -namespace Hncore.Wx.Open -{ - public class GetTagsResponse : ResponseBase - { - public List tags { get; set; } - } - - public class TagItem - { - public int id { get; set; } - - public string name { get; set; } - - public int count { get; set; } - } +using System.Collections.Generic; + +namespace Hncore.Wx.Open +{ + public class GetTagsResponse : ResponseBase + { + public List tags { get; set; } + } + + public class TagItem + { + public int id { get; set; } + + public string name { get; set; } + + public int count { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/GetTemplateResponse.cs b/Infrastructure/WxApi/Response/GetTemplateResponse.cs index 92918c5..a4993c3 100644 --- a/Infrastructure/WxApi/Response/GetTemplateResponse.cs +++ b/Infrastructure/WxApi/Response/GetTemplateResponse.cs @@ -1,7 +1,7 @@ -namespace Hncore.Wx.Open -{ - public class GetTemplateResponse : ResponseBase - { - public string template_id { get; set; } - } +namespace Hncore.Wx.Open +{ + public class GetTemplateResponse : ResponseBase + { + public string template_id { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/GetTempleteListResponse.cs b/Infrastructure/WxApi/Response/GetTempleteListResponse.cs index 36d2442..2a49f54 100644 --- a/Infrastructure/WxApi/Response/GetTempleteListResponse.cs +++ b/Infrastructure/WxApi/Response/GetTempleteListResponse.cs @@ -1,20 +1,20 @@ -using System.Collections.Generic; - -namespace Hncore.Wx.Open -{ - public class GetTempleteListResponse : ResponseBase - { - public List template_list { get; set; } - } - - public class TempleteItem - { - public string template_id { get; set; } - public string title { get; set; } - public string primary_industry { get; set; } - public string deputy_industry { get; set; } - } - -} - - +using System.Collections.Generic; + +namespace Hncore.Wx.Open +{ + public class GetTempleteListResponse : ResponseBase + { + public List template_list { get; set; } + } + + public class TempleteItem + { + public string template_id { get; set; } + public string title { get; set; } + public string primary_industry { get; set; } + public string deputy_industry { get; set; } + } + +} + + diff --git a/Infrastructure/WxApi/Response/GetUserinfoResponse.cs b/Infrastructure/WxApi/Response/GetUserinfoResponse.cs index a2fb437..80e5d4a 100644 --- a/Infrastructure/WxApi/Response/GetUserinfoResponse.cs +++ b/Infrastructure/WxApi/Response/GetUserinfoResponse.cs @@ -1,17 +1,17 @@ -using System.Collections.Generic; - -namespace Hncore.Wx.Open -{ - public class GetUserinfoResponse : ResponseBase - { - public string openid { get; set; } - public string nickname { get; set; } - public string sex { get; set; } - public string province { get; set; } - public string city { get; set; } - public string country { get; set; } - public string headimgurl { get; set; } - public List privilege { get; set; } - public string unionid { get; set; } - } +using System.Collections.Generic; + +namespace Hncore.Wx.Open +{ + public class GetUserinfoResponse : ResponseBase + { + public string openid { get; set; } + public string nickname { get; set; } + public string sex { get; set; } + public string province { get; set; } + public string city { get; set; } + public string country { get; set; } + public string headimgurl { get; set; } + public List privilege { get; set; } + public string unionid { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/GetWechatTicketResponse.cs b/Infrastructure/WxApi/Response/GetWechatTicketResponse.cs index 8ec2cc5..0e666e5 100644 --- a/Infrastructure/WxApi/Response/GetWechatTicketResponse.cs +++ b/Infrastructure/WxApi/Response/GetWechatTicketResponse.cs @@ -1,10 +1,10 @@ -namespace Hncore.Wx.Open -{ - /// - /// - /// -public class GetWechatTicketResponse:ResponseBase -{ - public string Ticket { get; set; } -} +namespace Hncore.Wx.Open +{ + /// + /// + /// +public class GetWechatTicketResponse:ResponseBase +{ + public string Ticket { get; set; } +} } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/RefreshAuthorizerInvokeAccessTokenResponse.cs b/Infrastructure/WxApi/Response/RefreshAuthorizerInvokeAccessTokenResponse.cs index 0a45e81..bf57be5 100644 --- a/Infrastructure/WxApi/Response/RefreshAuthorizerInvokeAccessTokenResponse.cs +++ b/Infrastructure/WxApi/Response/RefreshAuthorizerInvokeAccessTokenResponse.cs @@ -1,17 +1,17 @@ -namespace Hncore.Wx.Open -{ - // { - //"authorizer_access_token": "aaUl5s6kAByLwgV0BhXNuIFFUqfrR8vTATsoSHukcIGqJgrc4KmMJ-JlKoC_-NKCLBvuU1cWPv4vDcLN8Z0pn5I45mpATruU0b51hzeT1f8", - //"expires_in": 7200, - //"authorizer_refresh_token": "BstnRqgTJBXb9N2aJq6L5hzfJwP406tpfahQeLNxX0w" - //} - - /// - /// - /// - public class GetAuthorizerAccessTokenResponse : ResponseBase - { - public string authorizer_access_token { get; set; } - public string authorizer_refresh_token { get; set; } - } +namespace Hncore.Wx.Open +{ + // { + //"authorizer_access_token": "aaUl5s6kAByLwgV0BhXNuIFFUqfrR8vTATsoSHukcIGqJgrc4KmMJ-JlKoC_-NKCLBvuU1cWPv4vDcLN8Z0pn5I45mpATruU0b51hzeT1f8", + //"expires_in": 7200, + //"authorizer_refresh_token": "BstnRqgTJBXb9N2aJq6L5hzfJwP406tpfahQeLNxX0w" + //} + + /// + /// + /// + public class GetAuthorizerAccessTokenResponse : ResponseBase + { + public string authorizer_access_token { get; set; } + public string authorizer_refresh_token { get; set; } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/SaveAuthorizerInfoResponse.cs b/Infrastructure/WxApi/Response/SaveAuthorizerInfoResponse.cs index 1f716e7..f86c257 100644 --- a/Infrastructure/WxApi/Response/SaveAuthorizerInfoResponse.cs +++ b/Infrastructure/WxApi/Response/SaveAuthorizerInfoResponse.cs @@ -1,7 +1,7 @@ -namespace Hncore.Wx.Open -{ - public class SaveAuthorizerInfoResponse : ResponseBase - { - - } +namespace Hncore.Wx.Open +{ + public class SaveAuthorizerInfoResponse : ResponseBase + { + + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/SaveWechatAppMenuResponse.cs b/Infrastructure/WxApi/Response/SaveWechatAppMenuResponse.cs index 887df57..bc94ece 100644 --- a/Infrastructure/WxApi/Response/SaveWechatAppMenuResponse.cs +++ b/Infrastructure/WxApi/Response/SaveWechatAppMenuResponse.cs @@ -1,7 +1,7 @@ -namespace Hncore.Wx.Open -{ - public class SaveWechatAppMenuResponse : ResponseBase - { - - } +namespace Hncore.Wx.Open +{ + public class SaveWechatAppMenuResponse : ResponseBase + { + + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/UpdateWechatTicketResponse.cs b/Infrastructure/WxApi/Response/UpdateWechatTicketResponse.cs index 3a1cff5..fd5152e 100644 --- a/Infrastructure/WxApi/Response/UpdateWechatTicketResponse.cs +++ b/Infrastructure/WxApi/Response/UpdateWechatTicketResponse.cs @@ -1,12 +1,12 @@ -namespace Hncore.Wx.Open -{ - /// - /// - /// - public class UpdateWechatTicketResponse : ResponseBase - { - public UpdateWechatTicketResponse() { - - } - } +namespace Hncore.Wx.Open +{ + /// + /// + /// + public class UpdateWechatTicketResponse : ResponseBase + { + public UpdateWechatTicketResponse() { + + } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Response/UploadMediaResponse.cs b/Infrastructure/WxApi/Response/UploadMediaResponse.cs index b1f972b..f20bf8a 100644 --- a/Infrastructure/WxApi/Response/UploadMediaResponse.cs +++ b/Infrastructure/WxApi/Response/UploadMediaResponse.cs @@ -1,20 +1,20 @@ -namespace Hncore.Wx.Open -{ - public class UploadMediaResponse:ResponseBase - { - public string type { get; set; } - public string media_id { get; set; } - public int created_at { get; set; } - } - public class UploadImageMediaResponse : ResponseBase - { - public string url { get; set; } - public string media_id { get; set; } - } - - - - - - -} +namespace Hncore.Wx.Open +{ + public class UploadMediaResponse:ResponseBase + { + public string type { get; set; } + public string media_id { get; set; } + public int created_at { get; set; } + } + public class UploadImageMediaResponse : ResponseBase + { + public string url { get; set; } + public string media_id { get; set; } + } + + + + + + +} diff --git a/Infrastructure/WxApi/Response/WechatNotificationResponses.cs b/Infrastructure/WxApi/Response/WechatNotificationResponses.cs index c79c524..d941a44 100644 --- a/Infrastructure/WxApi/Response/WechatNotificationResponses.cs +++ b/Infrastructure/WxApi/Response/WechatNotificationResponses.cs @@ -1,22 +1,22 @@ -using System.Collections.Generic; - -namespace Hncore.Wx.Open -{ - public class WechatNotificationTemplate - { - public string template_id { get; set; } - public string title { get; set; } - public string primary_industry { get; set; } - public string deputy_industry { get; set; } - public string content { get; set; } - public string example { get; set; } - } - public class GetAllPrivateTemplateResponse : ResponseBase - { - public List template_list { get; set; } - } - public class WechatAddNotificationTemplateResponse : ResponseBase - { - public string template_id { get; set; } - } -} +using System.Collections.Generic; + +namespace Hncore.Wx.Open +{ + public class WechatNotificationTemplate + { + public string template_id { get; set; } + public string title { get; set; } + public string primary_industry { get; set; } + public string deputy_industry { get; set; } + public string content { get; set; } + public string example { get; set; } + } + public class GetAllPrivateTemplateResponse : ResponseBase + { + public List template_list { get; set; } + } + public class WechatAddNotificationTemplateResponse : ResponseBase + { + public string template_id { get; set; } + } +} diff --git a/Infrastructure/WxApi/Response/WxResponseBase.cs b/Infrastructure/WxApi/Response/WxResponseBase.cs index 408be0d..04dc460 100644 --- a/Infrastructure/WxApi/Response/WxResponseBase.cs +++ b/Infrastructure/WxApi/Response/WxResponseBase.cs @@ -1,23 +1,23 @@ -using Hncore.Infrastructure.Extension; -using System; - -namespace Hncore.Wx.Open -{ - public class ResponseBase - { - public int errcode { get; set; } - public string errmsg { get; set; } - public int expires_in { get; set; } - public long create_from { get; set; } - public virtual bool need_to_refresh_token - { - get - { - var timespan = (DateTime.Now.TimestampFrom19700101() - create_from); - //此处不应该等于0 errcode!=0表明微信返回的token有错误 需要刷新 ==0是正确的 - //提前10分钟过期 - return errcode != 0 || timespan < 0 || timespan > expires_in-10*60; - } - } - } -} +using Hncore.Infrastructure.Extension; +using System; + +namespace Hncore.Wx.Open +{ + public class ResponseBase + { + public int errcode { get; set; } + public string errmsg { get; set; } + public int expires_in { get; set; } + public long create_from { get; set; } + public virtual bool need_to_refresh_token + { + get + { + var timespan = (DateTime.Now.TimestampFrom19700101() - create_from); + //此处不应该等于0 errcode!=0表明微信返回的token有错误 需要刷新 ==0是正确的 + //提前10分钟过期 + return errcode != 0 || timespan < 0 || timespan > expires_in-10*60; + } + } + } +} diff --git a/Infrastructure/WxApi/TemplateMessage/SendResult.cs b/Infrastructure/WxApi/TemplateMessage/SendResult.cs index 6bbf701..87df744 100644 --- a/Infrastructure/WxApi/TemplateMessage/SendResult.cs +++ b/Infrastructure/WxApi/TemplateMessage/SendResult.cs @@ -1,15 +1,15 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Hncore.Wx.Open -{ - public class SendResult - { - public int errcode { get; set; } - public string errmsg { get; set; } - public long msgid { get; set; } - - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Hncore.Wx.Open +{ + public class SendResult + { + public int errcode { get; set; } + public string errmsg { get; set; } + public long msgid { get; set; } + + } +} diff --git a/Infrastructure/WxApi/TemplateMessage/TemplateApi.cs b/Infrastructure/WxApi/TemplateMessage/TemplateApi.cs index fef54f8..7ffc85b 100644 --- a/Infrastructure/WxApi/TemplateMessage/TemplateApi.cs +++ b/Infrastructure/WxApi/TemplateMessage/TemplateApi.cs @@ -1,266 +1,266 @@ -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Extension; -using Hncore.Infrastructure.Serializer; -using Hncore.Pass.MsgCenter.Constant; -using Hncore.Pass.MsgCenter.Util; -using Hncore.Wx.Open.Enums; -using System.Net.Http; -using System.Threading.Tasks; - -namespace Hncore.Wx.Open -{ - public static class TemplateApi - { - private static IHttpClientFactory _HttpClientFactory; - - public static void Init(IHttpClientFactory HttpClientFactory) - { - _HttpClientFactory = HttpClientFactory; - } - private static HttpClient GetHttpClient() - { - return _HttpClientFactory.CreateClient("WxOpen"); - } - /// - /// 开放平台或者公众平台或者小程序发送模板消息 - /// - /// 公众号appid - /// 模板id - /// openid ,号分割 - /// 数据 - /// - public static async Task SendTemplateMessageAsync(string appId, string to, ChannelType chennel, TemplateBaseModel tData) - { - var wxAppSecret = WxOpenApi.GetWxAppSecret(appId); - var access_token = ""; - if (!string.IsNullOrWhiteSpace(wxAppSecret))//公众平台或者小程序直接发送模板消息 - { - access_token = await WxOpenApi.GetAccessToken(appId, wxAppSecret); - } - else//开放平台代公众平台发送模板消息 - { - access_token = await WxOpenApi.GetAuthorizerAccessToken(appId); - } - - var tplId =await GetTemplateIdAsync(appId, tData.template_id); - - if (string.IsNullOrWhiteSpace(tplId)) - { - LogHelper.Error("没有找到对应的模板Id", $"appid={appId},tpl={tData.template_id}"); - return new SendResult() - { - errcode = 10001, - errmsg = "没有对应的模板" - }; - } - - tData.template_id = tplId; - var userList = to.Split(','); - foreach (var touser in userList) - { - tData.touser = touser; - var reqData = tData.ToData(); - if (chennel == ChannelType.MP) - { - mp_send(access_token, reqData); - } - else if (chennel == ChannelType.MiniApp) - { - miniapp_send(access_token, reqData); - } - } - return new SendResult(); - } - - /// - /// 发送小程序订阅消息 - /// - /// 小程序appid - /// 模板id - /// openid ,号分割 - /// 数据 - /// - public static async Task SendSubscribeMessageAsync(string appId, string to, TemplateBaseModel tData) - { - var wxAppSecret = WxOpenApi.GetWxAppSecret(appId); - - var access_token = await WxOpenApi.GetAccessToken(appId, wxAppSecret); - - var userList = to.Split(','); - foreach (var touser in userList) - { - tData.touser = touser; - var reqData = tData.ToData(); - miniapp_subscribe_send(access_token, reqData); - } - return new SendResult(); - } - - - /// - /// 根据短模板编号得到对应的模板id - /// - /// - /// - /// - public static async Task GetTemplateIdAsync(string appId, string short_tpl_id) - { - if (!short_tpl_id.StartsWith("OPENTM") && !short_tpl_id.StartsWith("TM")&& !short_tpl_id.StartsWith("ETOR")) - { - return short_tpl_id; - } - var key = string.Format(ConstantConfig.Redis_TempleteId_Key, appId, short_tpl_id); - var templete_id = await RedisHelper.GetAsync(key); - if (!string.IsNullOrWhiteSpace(templete_id)) - { - return templete_id; - } - - var access_token = await WxOpenApi.GetAuthorizerAccessToken(appId); - var ret = await get_tpl(access_token, short_tpl_id); - if (ret.errcode == 0) - { - await RedisHelper.SetAsync(key, ret.template_id); - return ret.template_id; - } - return ""; - } - - public static async Task mp_send(string access_token, object reqData) - { - if (string.IsNullOrWhiteSpace(access_token)) - { - return new SendResult() - { - errcode = 1000, - errmsg = "access_token 不存在" - }; - } - string urlFormat = $"cgi-bin/message/template/send?access_token={access_token}"; - LogHelper.Debug("mp_send_req", reqData.ToJson()); - var respJson = await GetHttpClient().PostAsJsonGetString(urlFormat, reqData); - var response = respJson.FromJsonToOrDefault(); - if (response.errcode > 0) - { - LogHelper.Error("mp_send_respJson", respJson); - return response; - } - return response; - } - public static async Task miniapp_send(string access_token, object reqData) - { - if (string.IsNullOrWhiteSpace(access_token)) - { - return new SendResult() - { - errcode = 1000, - errmsg = "access_token 不存在" - }; - } - string urlFormat = $"cgi-bin/message/wxopen/template/send?access_token={access_token}"; - LogHelper.Debug("mp_send_req", reqData.ToJson()); - var respJson = await GetHttpClient().PostAsJsonGetString(urlFormat, reqData); - var response = respJson.FromJsonToOrDefault(); - if (response.errcode > 0) - { - LogHelper.Error("miniapp_send_respJson", respJson); - return response; - } - return response; - } - - //小程序订阅消息 - public static async Task miniapp_subscribe_send(string access_token, object reqData) - { - if (string.IsNullOrWhiteSpace(access_token)) - { - return new SendResult() - { - errcode = 1000, - errmsg = "access_token 不存在" - }; - } - string urlFormat = $"cgi-bin/message/subscribe/send?access_token={access_token}"; - LogHelper.Debug("miniapp_subscribe_send", reqData.ToJson()); - var respJson = await GetHttpClient().PostAsJsonGetString(urlFormat, reqData); - var response = respJson.FromJsonToOrDefault(); - if (response.errcode > 0) - { - LogHelper.Error("miniapp_subscribe_send", respJson); - return response; - } - return response; - } - - - public static async Task uniform_send(string access_token, object reqData) - { - if (string.IsNullOrWhiteSpace(access_token)) - { - return new SendResult() - { - errcode = 1000, - errmsg = "access_token 不存在" - }; - } - - string urlFormat = $"cgi-bin/message/wxopen/template/uniform_send?access_token={access_token}"; - LogHelper.Debug("SendTemplateMessageAsync_Req", reqData.ToJson()); - var respJson = await GetHttpClient().PostAsJsonGetString(urlFormat, reqData); - var response = respJson.FromJsonToOrDefault(); - if (response.errcode > 0) - { - LogHelper.Debug("SendTemplateMessageAsync_respJson", respJson); - return response; - } - return new SendResult(); - } - - public static async Task get_tpl(string access_token, string short_tpl_id) - { - if (string.IsNullOrWhiteSpace(access_token)) - { - return new GetTemplateResponse() - { - errcode = 1000, - errmsg = "access_token 不存在" - }; - } - var reqData = new - { - template_id_short = short_tpl_id - }; - string urlFormat = $"cgi-bin/template/api_add_template?access_token={access_token}"; - LogHelper.Debug("get_tpl", reqData.ToJson()); - var respJson = await GetHttpClient().PostAsJsonGetString(urlFormat, reqData); - var response = respJson.FromJsonToOrDefault(); - if (response.errcode > 0) - { - LogHelper.Error("get_tpl_respJson", respJson); - return response; - } - return response; - } - - private static async Task get_tpl_list(string access_token) - { - if (string.IsNullOrWhiteSpace(access_token)) - { - return new GetTempleteListResponse() - { - errcode = 1000, - errmsg = "access_token 不存在" - }; - } - string urlFormat = $"cgi-bin/template/get_all_private_template?access_token={access_token}"; - var respJson = await GetHttpClient().GetStringAsync(urlFormat); - var response = respJson.FromJsonToOrDefault(); - if (response.errcode > 0) - { - LogHelper.Error("get_tpl_respJson", respJson); - return response; - } - return response; - } - } -} +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Extension; +using Hncore.Infrastructure.Serializer; +using Hncore.Pass.MsgCenter.Constant; +using Hncore.Pass.MsgCenter.Util; +using Hncore.Wx.Open.Enums; +using System.Net.Http; +using System.Threading.Tasks; + +namespace Hncore.Wx.Open +{ + public static class TemplateApi + { + private static IHttpClientFactory _HttpClientFactory; + + public static void Init(IHttpClientFactory HttpClientFactory) + { + _HttpClientFactory = HttpClientFactory; + } + private static HttpClient GetHttpClient() + { + return _HttpClientFactory.CreateClient("WxOpen"); + } + /// + /// 开放平台或者公众平台或者小程序发送模板消息 + /// + /// 公众号appid + /// 模板id + /// openid ,号分割 + /// 数据 + /// + public static async Task SendTemplateMessageAsync(string appId, string to, ChannelType chennel, TemplateBaseModel tData) + { + var wxAppSecret = WxOpenApi.GetWxAppSecret(appId); + var access_token = ""; + if (!string.IsNullOrWhiteSpace(wxAppSecret))//公众平台或者小程序直接发送模板消息 + { + access_token = await WxOpenApi.GetAccessToken(appId, wxAppSecret); + } + else//开放平台代公众平台发送模板消息 + { + access_token = await WxOpenApi.GetAuthorizerAccessToken(appId); + } + + var tplId =await GetTemplateIdAsync(appId, tData.template_id); + + if (string.IsNullOrWhiteSpace(tplId)) + { + LogHelper.Error("没有找到对应的模板Id", $"appid={appId},tpl={tData.template_id}"); + return new SendResult() + { + errcode = 10001, + errmsg = "没有对应的模板" + }; + } + + tData.template_id = tplId; + var userList = to.Split(','); + foreach (var touser in userList) + { + tData.touser = touser; + var reqData = tData.ToData(); + if (chennel == ChannelType.MP) + { + mp_send(access_token, reqData); + } + else if (chennel == ChannelType.MiniApp) + { + miniapp_send(access_token, reqData); + } + } + return new SendResult(); + } + + /// + /// 发送小程序订阅消息 + /// + /// 小程序appid + /// 模板id + /// openid ,号分割 + /// 数据 + /// + public static async Task SendSubscribeMessageAsync(string appId, string to, TemplateBaseModel tData) + { + var wxAppSecret = WxOpenApi.GetWxAppSecret(appId); + + var access_token = await WxOpenApi.GetAccessToken(appId, wxAppSecret); + + var userList = to.Split(','); + foreach (var touser in userList) + { + tData.touser = touser; + var reqData = tData.ToData(); + miniapp_subscribe_send(access_token, reqData); + } + return new SendResult(); + } + + + /// + /// 根据短模板编号得到对应的模板id + /// + /// + /// + /// + public static async Task GetTemplateIdAsync(string appId, string short_tpl_id) + { + if (!short_tpl_id.StartsWith("OPENTM") && !short_tpl_id.StartsWith("TM")&& !short_tpl_id.StartsWith("ETOR")) + { + return short_tpl_id; + } + var key = string.Format(ConstantConfig.Redis_TempleteId_Key, appId, short_tpl_id); + var templete_id = await RedisHelper.GetAsync(key); + if (!string.IsNullOrWhiteSpace(templete_id)) + { + return templete_id; + } + + var access_token = await WxOpenApi.GetAuthorizerAccessToken(appId); + var ret = await get_tpl(access_token, short_tpl_id); + if (ret.errcode == 0) + { + await RedisHelper.SetAsync(key, ret.template_id); + return ret.template_id; + } + return ""; + } + + public static async Task mp_send(string access_token, object reqData) + { + if (string.IsNullOrWhiteSpace(access_token)) + { + return new SendResult() + { + errcode = 1000, + errmsg = "access_token 不存在" + }; + } + string urlFormat = $"cgi-bin/message/template/send?access_token={access_token}"; + LogHelper.Debug("mp_send_req", reqData.ToJson()); + var respJson = await GetHttpClient().PostAsJsonGetString(urlFormat, reqData); + var response = respJson.FromJsonToOrDefault(); + if (response.errcode > 0) + { + LogHelper.Error("mp_send_respJson", respJson); + return response; + } + return response; + } + public static async Task miniapp_send(string access_token, object reqData) + { + if (string.IsNullOrWhiteSpace(access_token)) + { + return new SendResult() + { + errcode = 1000, + errmsg = "access_token 不存在" + }; + } + string urlFormat = $"cgi-bin/message/wxopen/template/send?access_token={access_token}"; + LogHelper.Debug("mp_send_req", reqData.ToJson()); + var respJson = await GetHttpClient().PostAsJsonGetString(urlFormat, reqData); + var response = respJson.FromJsonToOrDefault(); + if (response.errcode > 0) + { + LogHelper.Error("miniapp_send_respJson", respJson); + return response; + } + return response; + } + + //小程序订阅消息 + public static async Task miniapp_subscribe_send(string access_token, object reqData) + { + if (string.IsNullOrWhiteSpace(access_token)) + { + return new SendResult() + { + errcode = 1000, + errmsg = "access_token 不存在" + }; + } + string urlFormat = $"cgi-bin/message/subscribe/send?access_token={access_token}"; + LogHelper.Debug("miniapp_subscribe_send", reqData.ToJson()); + var respJson = await GetHttpClient().PostAsJsonGetString(urlFormat, reqData); + var response = respJson.FromJsonToOrDefault(); + if (response.errcode > 0) + { + LogHelper.Error("miniapp_subscribe_send", respJson); + return response; + } + return response; + } + + + public static async Task uniform_send(string access_token, object reqData) + { + if (string.IsNullOrWhiteSpace(access_token)) + { + return new SendResult() + { + errcode = 1000, + errmsg = "access_token 不存在" + }; + } + + string urlFormat = $"cgi-bin/message/wxopen/template/uniform_send?access_token={access_token}"; + LogHelper.Debug("SendTemplateMessageAsync_Req", reqData.ToJson()); + var respJson = await GetHttpClient().PostAsJsonGetString(urlFormat, reqData); + var response = respJson.FromJsonToOrDefault(); + if (response.errcode > 0) + { + LogHelper.Debug("SendTemplateMessageAsync_respJson", respJson); + return response; + } + return new SendResult(); + } + + public static async Task get_tpl(string access_token, string short_tpl_id) + { + if (string.IsNullOrWhiteSpace(access_token)) + { + return new GetTemplateResponse() + { + errcode = 1000, + errmsg = "access_token 不存在" + }; + } + var reqData = new + { + template_id_short = short_tpl_id + }; + string urlFormat = $"cgi-bin/template/api_add_template?access_token={access_token}"; + LogHelper.Debug("get_tpl", reqData.ToJson()); + var respJson = await GetHttpClient().PostAsJsonGetString(urlFormat, reqData); + var response = respJson.FromJsonToOrDefault(); + if (response.errcode > 0) + { + LogHelper.Error("get_tpl_respJson", respJson); + return response; + } + return response; + } + + private static async Task get_tpl_list(string access_token) + { + if (string.IsNullOrWhiteSpace(access_token)) + { + return new GetTempleteListResponse() + { + errcode = 1000, + errmsg = "access_token 不存在" + }; + } + string urlFormat = $"cgi-bin/template/get_all_private_template?access_token={access_token}"; + var respJson = await GetHttpClient().GetStringAsync(urlFormat); + var response = respJson.FromJsonToOrDefault(); + if (response.errcode > 0) + { + LogHelper.Error("get_tpl_respJson", respJson); + return response; + } + return response; + } + } +} diff --git a/Infrastructure/WxApi/TemplateMessage/TemplateModel.cs b/Infrastructure/WxApi/TemplateMessage/TemplateModel.cs index 06553b6..159df3b 100644 --- a/Infrastructure/WxApi/TemplateMessage/TemplateModel.cs +++ b/Infrastructure/WxApi/TemplateMessage/TemplateModel.cs @@ -1,129 +1,129 @@ -using System; -using System.Collections.Generic; - -namespace Hncore.Wx.Open -{ - public class TemplateBaseModel - { - public string touser { get; set; } - public string template_id { get; set; } - public List Items { get; set; } = new List(); - - //{ - // "touser":"touser", - // "template_id": "TEMPLATE_ID", - // "data": { - // "keyword1": { - // "value": "339208499" - // }, - // "keyword2": { - // "value": "2015年01月05日 12:30" - // }, - // "keyword3": { - // "value": "腾讯微信总部" - // } , - // "keyword4": { - // "value": "广州市海珠区新港中路397号" - // } - // } - //} - public virtual Dictionary ToData() - { - var data = new Dictionary() { - { "touser",touser}, - {"template_id",template_id} - }; - var index = 1; - var dataItems = new Dictionary() { }; - Items.ForEach(m => - { - dataItems[$"keyword{index}"] = m; - index++; - }); - data["data"] = dataItems; - return data; - } - } - - public class TemplateMPModel: TemplateBaseModel - { - public string Url { get; set; } - public string MiniAppId { get; set; } - public TemplateDataItem first { get; set; } - public TemplateDataItem remark { get; set; } - public override Dictionary ToData() - { - var ret = base.ToData(); - var data = ret ["data"] as Dictionary; - if (first != null) data["first"] = first; - if (remark != null) data["remark"] = remark; - if (!string.IsNullOrWhiteSpace(Url)) ret["url"] = Url; - if (!string.IsNullOrWhiteSpace(MiniAppId)) ret["miniprogram"] = new - { - appid = MiniAppId, - pagepath = Url - }; - return ret; - } - } - - public class TemplateMiniAppModel : TemplateBaseModel - { - public string page { get; set; } - public string form_id { get; set; } - public string emphasis_keyword { get; set; } - public override Dictionary ToData() - { - var ret = base.ToData(); - if (!string.IsNullOrWhiteSpace(page)) ret["page"] = page; - if (!string.IsNullOrWhiteSpace(form_id)) ret["form_id"] = form_id; - if (!string.IsNullOrWhiteSpace(emphasis_keyword)) ret["emphasis_keyword"] = emphasis_keyword; - return ret; - } - } - - public class TemplateDataItem - { - public TemplateDataItem(string v, string c = "#173177") - { - value = v; - color = c; - } - - public string name { get; set; } - public string value { get; set; } - // - // 摘要: - // 16进制颜色代码,如:#FF0000 - public string color { get; set; } - } - - - /// - /// 小程序订阅消息 - /// - public class SubscribeMiniAppModel : TemplateBaseModel - { - public string page { get; set; } - public override Dictionary ToData() - { - var ret = base.ToData(); - - var data = new Dictionary() { - { "touser",touser}, - {"template_id",template_id} - }; - var index = 1; - var dataItems = new Dictionary() { }; - Items.ForEach(m => - { - var num = index.ToString().PadLeft(2, '0'); - dataItems[m.name] = new { value = m.value }; - index++; - }); - data["data"] = dataItems; - if (!string.IsNullOrWhiteSpace(page)) ret["page"] = page; - return data; - } - } -} +using System; +using System.Collections.Generic; + +namespace Hncore.Wx.Open +{ + public class TemplateBaseModel + { + public string touser { get; set; } + public string template_id { get; set; } + public List Items { get; set; } = new List(); + + //{ + // "touser":"touser", + // "template_id": "TEMPLATE_ID", + // "data": { + // "keyword1": { + // "value": "339208499" + // }, + // "keyword2": { + // "value": "2015年01月05日 12:30" + // }, + // "keyword3": { + // "value": "腾讯微信总部" + // } , + // "keyword4": { + // "value": "广州市海珠区新港中路397号" + // } + // } + //} + public virtual Dictionary ToData() + { + var data = new Dictionary() { + { "touser",touser}, + {"template_id",template_id} + }; + var index = 1; + var dataItems = new Dictionary() { }; + Items.ForEach(m => + { + dataItems[$"keyword{index}"] = m; + index++; + }); + data["data"] = dataItems; + return data; + } + } + + public class TemplateMPModel: TemplateBaseModel + { + public string Url { get; set; } + public string MiniAppId { get; set; } + public TemplateDataItem first { get; set; } + public TemplateDataItem remark { get; set; } + public override Dictionary ToData() + { + var ret = base.ToData(); + var data = ret ["data"] as Dictionary; + if (first != null) data["first"] = first; + if (remark != null) data["remark"] = remark; + if (!string.IsNullOrWhiteSpace(Url)) ret["url"] = Url; + if (!string.IsNullOrWhiteSpace(MiniAppId)) ret["miniprogram"] = new + { + appid = MiniAppId, + pagepath = Url + }; + return ret; + } + } + + public class TemplateMiniAppModel : TemplateBaseModel + { + public string page { get; set; } + public string form_id { get; set; } + public string emphasis_keyword { get; set; } + public override Dictionary ToData() + { + var ret = base.ToData(); + if (!string.IsNullOrWhiteSpace(page)) ret["page"] = page; + if (!string.IsNullOrWhiteSpace(form_id)) ret["form_id"] = form_id; + if (!string.IsNullOrWhiteSpace(emphasis_keyword)) ret["emphasis_keyword"] = emphasis_keyword; + return ret; + } + } + + public class TemplateDataItem + { + public TemplateDataItem(string v, string c = "#173177") + { + value = v; + color = c; + } + + public string name { get; set; } + public string value { get; set; } + // + // 摘要: + // 16进制颜色代码,如:#FF0000 + public string color { get; set; } + } + + + /// + /// 小程序订阅消息 + /// + public class SubscribeMiniAppModel : TemplateBaseModel + { + public string page { get; set; } + public override Dictionary ToData() + { + var ret = base.ToData(); + + var data = new Dictionary() { + { "touser",touser}, + {"template_id",template_id} + }; + var index = 1; + var dataItems = new Dictionary() { }; + Items.ForEach(m => + { + var num = index.ToString().PadLeft(2, '0'); + dataItems[m.name] = new { value = m.value }; + index++; + }); + data["data"] = dataItems; + if (!string.IsNullOrWhiteSpace(page)) ret["page"] = page; + return data; + } + } +} diff --git a/Infrastructure/WxApi/Util/Constant.cs b/Infrastructure/WxApi/Util/Constant.cs index 72e4d8b..bb9c611 100644 --- a/Infrastructure/WxApi/Util/Constant.cs +++ b/Infrastructure/WxApi/Util/Constant.cs @@ -1,106 +1,106 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Hncore.Pass.MsgCenter.Constant -{ - public class ConstantConfig - { - /// - /// 微信开放平台定期推送的ticket 标识 - /// - public const string Redis_Psipwechat_Ticket_Key = "psipwechat_ticket"; - - /// - /// 微信开放平台AccessToken 标识 - /// - public const string Redis_ComponentAccessToken_Key = "WEIXIN:{0}_wx_component_token.json"; - - /// - /// 微信开放平台accessToken 标识{authorizer_appid} - /// - public const string Redis_AuthorizerAccessToken_Key = "WEIXIN:wx_authorizer_token_{0}"; - - /// - /// 微信开放平台refresh_authorizer_token 标识{authorizer_appid} - /// - public const string Redis_Refresh_AuthorizerAccessToken_Key = "WEIXIN:wx_refresh_authorizer_token_{0}"; - - - /// - /// 微信公众平台 mp_access_token 标识{appid} - /// - public const string Redis_MP_AccessToken_Key = "WEIXIN:wx_mp_access_token_{0}"; - - - - /// - /// 微信公众平台 mp_access_token 标识{openid} - /// - public const string Redis_MP_GetUserinfoByWebAccessToken_Key = "WEIXIN:userinfo_by_web_accesstoken_{0}"; - - /// - /// 微信公众平台 mp_access_token 标识{openid} - /// - public const string Redis_MP_GetUserUnionIDInfo_Key = "WEIXIN:userinfo_uniono_info_{0}"; - - /// - /// 微信公众平台 mp_access_token 标识{openid} - /// - public const string Redis_MP_GetUserOpenIdInfo_Key = "WEIXIN:userinfo_openid_info_{0}"; - - - - /// - /// 公众号模板key {appid}_{tplId} - /// - public const string Redis_TempleteId_Key = "WEIXIN:TempleteId_{0}_{1}"; - - /// - /// 公众号的基本信息{公众号appid} - /// - public const string Redis_MP_Info_Key = "WEIXIN:mp_info_{0}"; - - - /// - /// 发送消息公众号模板消息标识 - /// - public const string RabbitMQ_Send_Message_Key = "msgcenter_send_msg_{0}"; - /// - /// 发送消息公众号模板消息标识 - /// - public const string RabbitMQ_Send_Message_MP_Key = "msgcenter_send_msg_1"; - - /// - /// 送消息小程序模板消息标识 - /// - public const string RabbitMQ_Send_Message_MiniApp_Key = "msgcenter_send_msg_2"; - - /// - /// 送消息短信模板消息标识 - /// - public const string RabbitMQ_Send_Message_Sms_Key = "msgcenter_send_msg_3"; - - /// - /// 送消小程序订阅消息标识 - /// - public const string RabbitMQ_Send_Message_Subscribe_Key = "msgcenter_send_msg_4"; - - - public const string RabbitMQ_Send_Message_Test_Key = "msgcenter_send_msg_4"; - - - /// - /// 发email消息 - /// - public const string RabbitMQ_Send_Message_Email = "Etor.PSIP.Msgcenter.SendEmail"; - - /// - /// 公众号模板key {uuid} - /// - public const string Redis_WxScanWait_Key = "WEIXIN:WxScanWait_{0}"; - - public const string Redis_MP_Js_Ticket_Key = "WEIXIN:mp_js_ticket_{0}"; - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Hncore.Pass.MsgCenter.Constant +{ + public class ConstantConfig + { + /// + /// 微信开放平台定期推送的ticket 标识 + /// + public const string Redis_Psipwechat_Ticket_Key = "psipwechat_ticket"; + + /// + /// 微信开放平台AccessToken 标识 + /// + public const string Redis_ComponentAccessToken_Key = "WEIXIN:{0}_wx_component_token.json"; + + /// + /// 微信开放平台accessToken 标识{authorizer_appid} + /// + public const string Redis_AuthorizerAccessToken_Key = "WEIXIN:wx_authorizer_token_{0}"; + + /// + /// 微信开放平台refresh_authorizer_token 标识{authorizer_appid} + /// + public const string Redis_Refresh_AuthorizerAccessToken_Key = "WEIXIN:wx_refresh_authorizer_token_{0}"; + + + /// + /// 微信公众平台 mp_access_token 标识{appid} + /// + public const string Redis_MP_AccessToken_Key = "WEIXIN:wx_mp_access_token_{0}"; + + + + /// + /// 微信公众平台 mp_access_token 标识{openid} + /// + public const string Redis_MP_GetUserinfoByWebAccessToken_Key = "WEIXIN:userinfo_by_web_accesstoken_{0}"; + + /// + /// 微信公众平台 mp_access_token 标识{openid} + /// + public const string Redis_MP_GetUserUnionIDInfo_Key = "WEIXIN:userinfo_uniono_info_{0}"; + + /// + /// 微信公众平台 mp_access_token 标识{openid} + /// + public const string Redis_MP_GetUserOpenIdInfo_Key = "WEIXIN:userinfo_openid_info_{0}"; + + + + /// + /// 公众号模板key {appid}_{tplId} + /// + public const string Redis_TempleteId_Key = "WEIXIN:TempleteId_{0}_{1}"; + + /// + /// 公众号的基本信息{公众号appid} + /// + public const string Redis_MP_Info_Key = "WEIXIN:mp_info_{0}"; + + + /// + /// 发送消息公众号模板消息标识 + /// + public const string RabbitMQ_Send_Message_Key = "msgcenter_send_msg_{0}"; + /// + /// 发送消息公众号模板消息标识 + /// + public const string RabbitMQ_Send_Message_MP_Key = "msgcenter_send_msg_1"; + + /// + /// 送消息小程序模板消息标识 + /// + public const string RabbitMQ_Send_Message_MiniApp_Key = "msgcenter_send_msg_2"; + + /// + /// 送消息短信模板消息标识 + /// + public const string RabbitMQ_Send_Message_Sms_Key = "msgcenter_send_msg_3"; + + /// + /// 送消小程序订阅消息标识 + /// + public const string RabbitMQ_Send_Message_Subscribe_Key = "msgcenter_send_msg_4"; + + + public const string RabbitMQ_Send_Message_Test_Key = "msgcenter_send_msg_4"; + + + /// + /// 发email消息 + /// + public const string RabbitMQ_Send_Message_Email = "Etor.PSIP.Msgcenter.SendEmail"; + + /// + /// 公众号模板key {uuid} + /// + public const string Redis_WxScanWait_Key = "WEIXIN:WxScanWait_{0}"; + + public const string Redis_MP_Js_Ticket_Key = "WEIXIN:mp_js_ticket_{0}"; + } +} diff --git a/Infrastructure/WxApi/Util/HostContext.cs b/Infrastructure/WxApi/Util/HostContext.cs index dca9235..cbdaad2 100644 --- a/Infrastructure/WxApi/Util/HostContext.cs +++ b/Infrastructure/WxApi/Util/HostContext.cs @@ -1,18 +1,18 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Threading.Tasks; - -namespace Hncore.Pass.MsgCenter.Util -{ - public class HostContext - { - public static IConfiguration Configuration { get; set; } - - public static IHttpClientFactory HttpClientFactory { get; set; } - } -} +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; + +namespace Hncore.Pass.MsgCenter.Util +{ + public class HostContext + { + public static IConfiguration Configuration { get; set; } + + public static IHttpClientFactory HttpClientFactory { get; set; } + } +} diff --git a/Infrastructure/WxApi/Util/ServiceContext.cs b/Infrastructure/WxApi/Util/ServiceContext.cs index 86756a7..0982413 100644 --- a/Infrastructure/WxApi/Util/ServiceContext.cs +++ b/Infrastructure/WxApi/Util/ServiceContext.cs @@ -1,33 +1,33 @@ -using Microsoft.Extensions.DependencyInjection; -using System; - -namespace Hncore.Pass.MsgCenter.Util -{ - public class ServiceContext - { - private static IServiceProvider _serviceProvider; - public static void Initialize(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - - /// - /// 构建实例 - /// - /// - /// - public static T Resolve() where T : class - { - return _serviceProvider.GetService(); - } - /// - /// 构建类型 - /// - /// - /// - public static object Resolve(Type type) - { - return _serviceProvider.GetService(type); - } - } +using Microsoft.Extensions.DependencyInjection; +using System; + +namespace Hncore.Pass.MsgCenter.Util +{ + public class ServiceContext + { + private static IServiceProvider _serviceProvider; + public static void Initialize(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + } + + /// + /// 构建实例 + /// + /// + /// + public static T Resolve() where T : class + { + return _serviceProvider.GetService(); + } + /// + /// 构建类型 + /// + /// + /// + public static object Resolve(Type type) + { + return _serviceProvider.GetService(type); + } + } } \ No newline at end of file diff --git a/Infrastructure/WxApi/Util/UrlHelper.cs b/Infrastructure/WxApi/Util/UrlHelper.cs index b25a406..dc2c685 100644 --- a/Infrastructure/WxApi/Util/UrlHelper.cs +++ b/Infrastructure/WxApi/Util/UrlHelper.cs @@ -1,47 +1,47 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Hncore.Pass.MsgCenter.Util -{ - public class UrlHelper - { - public static UrlMethodModel ParseUrl(string data) - { - var index = data.IndexOf('/'); - if (index != -1) - { - data = data.Substring(index + 1); - } - UrlMethodModel model = new UrlMethodModel(); - var token = data.Split('?'); - if (token.Length > 0) - { - model.Method = token[0]; - } - if (token.Length > 1) - { - var kvs = token[1].Split('&'); - foreach (var item in kvs) - { - var kv = item.Split('='); - if (kv.Length > 1) - { - var key = kv[0].ToLower(); - var value = kv[1]; - model.Args[key] = value; - } - } - } - return model; - } - } - - public class UrlMethodModel - { - public string Method { get; set; } = ""; - - public Dictionary Args { get; set; } = new Dictionary(); - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Hncore.Pass.MsgCenter.Util +{ + public class UrlHelper + { + public static UrlMethodModel ParseUrl(string data) + { + var index = data.IndexOf('/'); + if (index != -1) + { + data = data.Substring(index + 1); + } + UrlMethodModel model = new UrlMethodModel(); + var token = data.Split('?'); + if (token.Length > 0) + { + model.Method = token[0]; + } + if (token.Length > 1) + { + var kvs = token[1].Split('&'); + foreach (var item in kvs) + { + var kv = item.Split('='); + if (kv.Length > 1) + { + var key = kv[0].ToLower(); + var value = kv[1]; + model.Args[key] = value; + } + } + } + return model; + } + } + + public class UrlMethodModel + { + public string Method { get; set; } = ""; + + public Dictionary Args { get; set; } = new Dictionary(); + } +} diff --git a/Infrastructure/WxApi/WxApi.csproj b/Infrastructure/WxApi/WxApi.csproj index 83ea249..fa98788 100644 --- a/Infrastructure/WxApi/WxApi.csproj +++ b/Infrastructure/WxApi/WxApi.csproj @@ -1,15 +1,15 @@ - - - - netstandard2.0 - - - - - - - - - - - + + + + netstandard2.0 + + + + + + + + + + + diff --git a/Infrastructure/WxApi/WxApiExt.cs b/Infrastructure/WxApi/WxApiExt.cs index d75995e..153f1cb 100644 --- a/Infrastructure/WxApi/WxApiExt.cs +++ b/Infrastructure/WxApi/WxApiExt.cs @@ -1,30 +1,30 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Net.Http; - -namespace Hncore.Wx.Open -{ - public static class WxApiExt - { - - public static void AddWxApi(this IServiceCollection services) - { - services.AddHttpClient("WxOpen", client => - { - client.BaseAddress = new Uri("https://api.weixin.qq.com/"); - client.Timeout = TimeSpan.FromSeconds(10); - }); - } - - public static void UseWxApi(this IApplicationBuilder app) - { - var serviceProvider = app.ApplicationServices; - var configuration = serviceProvider.GetService(); - var httpFactory = serviceProvider.GetService(); - WxOpenApi.Init(configuration, httpFactory); - TemplateApi.Init(httpFactory); - } - } -} +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Net.Http; + +namespace Hncore.Wx.Open +{ + public static class WxApiExt + { + + public static void AddWxApi(this IServiceCollection services) + { + services.AddHttpClient("WxOpen", client => + { + client.BaseAddress = new Uri("https://api.weixin.qq.com/"); + client.Timeout = TimeSpan.FromSeconds(10); + }); + } + + public static void UseWxApi(this IApplicationBuilder app) + { + var serviceProvider = app.ApplicationServices; + var configuration = serviceProvider.GetService(); + var httpFactory = serviceProvider.GetService(); + WxOpenApi.Init(configuration, httpFactory); + TemplateApi.Init(httpFactory); + } + } +} diff --git a/Infrastructure/WxApi/WxOpenApi.cs b/Infrastructure/WxApi/WxOpenApi.cs index 9953aa2..ec1e7c7 100644 --- a/Infrastructure/WxApi/WxOpenApi.cs +++ b/Infrastructure/WxApi/WxOpenApi.cs @@ -1,759 +1,759 @@ -using Hncore.Infrastructure.Common; -using Hncore.Infrastructure.Extension; -using Hncore.Infrastructure.Serializer; -using Hncore.Pass.MsgCenter.Constant; -using Hncore.Pass.MsgCenter.Util; -using Hncore.Pass.MsgCenter.WxOpen.Response; -using Microsoft.EntityFrameworkCore.Internal; -using Microsoft.Extensions.Configuration; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Threading.Tasks; -using System.Web; - -namespace Hncore.Wx.Open -{ - public class WxOpenApi - { - private static readonly AsyncLock _mutex1 = new AsyncLock(); - private static readonly AsyncLock _mutex2 = new AsyncLock(); - private static readonly AsyncLock _mutex4 = new AsyncLock(); - - private static Dictionary WxAppMap = new Dictionary(); - - private static IHttpClientFactory _HttpClientFactory; - - public static void Init(IConfiguration config, IHttpClientFactory HttpClientFactory) - { - _HttpClientFactory = HttpClientFactory; - var key = config[$"WxApps:AppID"]; - WxAppMap[key] = config[$"WxApps:AppSecret"]; - //var WxMpApps = config.GetSection("WxApps"); - //var nodes = WxMpApps.GetChildren(); - //for (var i = 0; i < nodes.Count(); i++) - //{ - // var key = config[$"WxApps:{i}:AppID"]; - // var value = config[$"WxApps:{i}:AppSecret"]; - // if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value)) - // WxAppMap[key] = value; - //} - } - - public static string GetWxAppSecret(string appid) - { - if (WxAppMap.ContainsKey(appid)) - return WxAppMap[appid]; - else return ""; - } - - private static HttpClient GetHttpClient() - { - return _HttpClientFactory.CreateClient("WxOpen"); - } - public static async Task GetComponentTicket() - { - return await RedisHelper.GetAsync(ConstantConfig.Redis_Psipwechat_Ticket_Key); - } - - public static async Task SetComponentTicket(string ticket) - { - return await RedisHelper.SetAsync(ConstantConfig.Redis_Psipwechat_Ticket_Key, ticket); - } - - /// - /// 开放平台:得到开放平台的accessToken - /// - /// - public static async Task GetComponentAccessToken() - { - var component_appid = HostContext.Configuration["WxOpen:AppID"]; - var key =string.Format(ConstantConfig.Redis_ComponentAccessToken_Key, component_appid); - var tokenJson = await RedisHelper.GetAsync(key); - var token = tokenJson.FromJsonToOrDefault(); - if (token == null || token.need_to_refresh_token) - { - using (await _mutex1.LockAsync()) - { - tokenJson = await RedisHelper.GetAsync(key); - token = tokenJson.FromJsonToOrDefault(); - if (token != null && !token.need_to_refresh_token) - { - return token.component_access_token; - } - //重新去微信获取 - var ticket =await GetComponentTicket(); - token = await get_component_access_token(ticket); - if (token.errcode == 0) - { - await RedisHelper.SetAsync(key, token.ToJson(), token.expires_in); - return token.component_access_token; - } - else - { - return ""; - } - } - } - return token.component_access_token; - } - - /// - /// 开放平台:得到公众平台的AccessToken - /// - /// - public static async Task GetAuthorizerAccessToken(string authorizer_appid) - { - var key = string.Format(ConstantConfig.Redis_AuthorizerAccessToken_Key, authorizer_appid); - var refresh_key = string.Format(ConstantConfig.Redis_Refresh_AuthorizerAccessToken_Key, authorizer_appid); - var tokenJson = await RedisHelper.GetAsync(key); - var token = tokenJson.FromJsonToOrDefault(); - if (token == null || token.need_to_refresh_token) - { - using (await _mutex2.LockAsync()) - { - tokenJson = await RedisHelper.GetAsync(key); - token = tokenJson.FromJsonToOrDefault(); - if (token != null && !token.need_to_refresh_token) - { - return token.authorizer_access_token; - } - - var authorizer_refresh_token = await RedisHelper.GetAsync(refresh_key); - var component_access_token = await GetComponentAccessToken(); - token = await get_authorizer_access_token_by_refresh(authorizer_appid, authorizer_refresh_token, component_access_token); - if (token.errcode == 0) - { - await RedisHelper.SetAsync(key, token.ToJson(), token.expires_in); - await RedisHelper.SetAsync(refresh_key, token.authorizer_refresh_token,60*60*24*30); - return token.authorizer_access_token; - } - else - { - return ""; - } - } - } - return token.authorizer_access_token; - } - - public static async Task ReFreshAccessToken(string authorizer_appid, string component_access_token) - { - var key = string.Format(ConstantConfig.Redis_AuthorizerAccessToken_Key, authorizer_appid); - var refresh_key = string.Format(ConstantConfig.Redis_Refresh_AuthorizerAccessToken_Key, authorizer_appid); - var authorizer_refresh_token = await RedisHelper.GetAsync(refresh_key); - using (await _mutex4.LockAsync()) - { - var token = await get_authorizer_access_token_by_refresh(authorizer_appid, authorizer_refresh_token, component_access_token); - if (token.errcode == 0) - { - await RedisHelper.SetAsync(key, token.ToJson(), token.expires_in); - await RedisHelper.SetAsync(refresh_key, token.authorizer_refresh_token,60 * 60 * 24 * 30); - } - } - } - - /// - ///开放平台: 通过回调返回授权码的方式获得公众号的accesstoken - /// - /// - /// - public static async Task GetAuthorizerAccessTokenByCode(string authorization_code,Func> callback) - { - var component_access_token = await GetComponentAccessToken(); - var ret = await get_authorizer_access_token_by_callback(authorization_code, component_access_token); - var authorizer_appid = ret.authorization_info.authorizer_appid; - //存access_token的key - var key = string.Format(ConstantConfig.Redis_AuthorizerAccessToken_Key, authorizer_appid); - - //存refresh_access_token的key - var refresh_key = string.Format(ConstantConfig.Redis_Refresh_AuthorizerAccessToken_Key, authorizer_appid); - - var info = new GetAuthorizerAccessTokenResponse() - { - authorizer_access_token = ret.authorization_info.authorizer_access_token, - authorizer_refresh_token = ret.authorization_info.authorizer_refresh_token, - expires_in = ret.authorization_info.expires_in, - create_from = DateTime.Now.TimestampFrom19700101() - }; - - await RedisHelper.SetAsync(key, info.ToJson(), info.expires_in); - await RedisHelper.SetAsync(refresh_key, info.authorizer_refresh_token); - - if (callback != null) - { - return await callback(ret.authorization_info); - } - return info.authorizer_access_token; - } - - /// - ///开放平台: 得到开放平台的预授权码 - /// - /// - public static async Task GetPreAuthCode() - { - var component_access_token = await GetComponentAccessToken(); - var ret = await get_pre_auth_Code(component_access_token); - return ret.pre_auth_code; - } - - - /// - ///开放平台: 代公众号获取用户在公众号的OpenId,以及AccessToken 信息 - /// - /// - /// 结果对象,里边包含了授权令牌信息 - public static async Task GetAuthorizerClientUserOpenIdInfo(string appid, string code) - { - var component_access_token = await GetComponentAccessToken(); - var ret = await get_authorizer_user_openIdifno(appid, code, component_access_token); - return ret; - } - - /// - /// 开放平台:为公众平台授权的url - /// - /// - public static async Task GetAuthorizationUrl(string callback_url) - { - var appID = HostContext.Configuration["WxOpen:AppID"]; ; - var pre_auth_code = await GetPreAuthCode(); - var baseUrl = HostContext.Configuration["BaseInfoUrl"]; - callback_url = $"{baseUrl}/{callback_url}";//回调地址 - - callback_url = HttpUtility.UrlEncode(callback_url); - //开放平台授权地址 - var url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?" + - $"component_appid={appID}" + - $"&pre_auth_code={pre_auth_code}" + - $"&redirect_uri={callback_url}"; - return url; - } - - private static readonly AsyncLock _mutex3 = new AsyncLock(); - /// - /// 【公众平台、小程序】:得到公众平台、小程序的accessToken - /// - /// - public static async Task GetAccessToken(string appid, string secret) - { - var key = string.Format(ConstantConfig.Redis_MP_AccessToken_Key, appid); - var tokenJson = await RedisHelper.GetAsync(key); - var token = tokenJson.FromJsonToOrDefault(); - if (token == null || token.need_to_refresh_token) - { - using (await _mutex3.LockAsync()) - { - tokenJson = await RedisHelper.GetAsync(key); - token = tokenJson.FromJsonToOrDefault(); - if (token != null && !token.need_to_refresh_token) - { - return token.access_token; - } - token = await get_access_token(appid, secret); - if (token.errcode == 0) - { - await RedisHelper.SetAsync(key, token.ToJson(), token.expires_in); - return token.access_token; - } - return ""; - } - } - return token.access_token; - } - /// - /// 公众平台,通过code换取网页授权access_token - /// - /// - /// - /// - public static async Task GetWebAccessToken(string appid, string code) - { - var secret = GetWxAppSecret(appid); - if (string.IsNullOrWhiteSpace(secret)) - { - LogHelper.Error("GetWebAccessToken", $"appid={appid} 没有配置"); - return null; - } - return await get_web_access_token(appid, secret, code); - - } - /// - /// 通过access_token和openid拉取用户信息 - /// - /// - /// - /// - public static async Task GetUserinfoByWebAccessToken(string access_token, string openid) - { - var key = string.Format(ConstantConfig.Redis_MP_GetUserinfoByWebAccessToken_Key, openid); - var userInfo = await RedisHelper.GetAsync(key); - - if (userInfo == null) - { - userInfo = await get_userinfo_by_web_access_token(access_token, openid); - if (userInfo.errcode == 0) - await RedisHelper.SetAsync(key, userInfo.ToJson(), 2 * 60 * 60); - } - return userInfo; - } - - /// - /// 开放平台获得获取用户基本信息(UnionID机制) - /// - /// - /// - /// - public static async Task GetUserUnionIDinfo(string appid, string openid) - { - var key = string.Format(ConstantConfig.Redis_MP_GetUserUnionIDInfo_Key, openid); - var userInfo = await RedisHelper.GetAsync(key); - - if (userInfo == null) - { - var access_token = await GetAuthorizerAccessToken(appid); - userInfo = await get_user_openid_info(access_token, openid); - if (userInfo.errcode == 0) - await RedisHelper.SetAsync(key, userInfo.ToJson(), 2 * 60 * 60); - } - return userInfo; - } - - /// - /// 公众平台获得获取用户基本信息() - /// - /// - /// - /// - public static async Task GetUserinfoByOpenId(string appid, string openid) - { - var key = string.Format(ConstantConfig.Redis_MP_GetUserOpenIdInfo_Key, openid); - var userInfo = await RedisHelper.GetAsync(key); - - if (userInfo == null) - { - var access_token = await GetAccessToken(appid,GetWxAppSecret(appid)); - userInfo = await get_user_openid_info(access_token, openid); - if (userInfo.errcode == 0) - await RedisHelper.SetAsync(key, userInfo.ToJson(), 2 * 60 * 60); - } - return userInfo; - } - - /// - /// 通过开放平台获得公众号的信息 - /// - /// - /// - /// - public static async Task GetMpInfo(string authorizer_appid) - { - var key = string.Format(ConstantConfig.Redis_MP_Info_Key, authorizer_appid); - var mpInfo = await RedisHelper.GetAsync(key); - - if (mpInfo == null) - { - var component_token = await GetComponentAccessToken(); - mpInfo = await get_mp_info(component_token, authorizer_appid); - if (mpInfo.errcode == 0) - await RedisHelper.SetAsync(key, mpInfo.ToJson(), 1 * 60 * 60); - } - return mpInfo.authorizer_info; - } - - /// - /// 为公众平台创建菜单 - /// - /// - /// - public static async Task CreateMPMenu(string access_token, object menu) - { - var ret = await create_mp_menu(access_token, menu); - return ret.errcode == 0; - } - - /// - /// 为公众平台粉丝添加标签 - /// - /// - /// - public static async Task AddTag(string appid, List openIds, string tagId) - { - var access_token = await GetAuthorizerAccessToken(appid); - await add_tag(access_token, openIds, int.Parse(tagId)); - } - - /// - /// 得到公众平台所有标签 - /// - /// - /// - public static async Task GetTags(string appid) - { - var access_token = await GetAuthorizerAccessToken(appid); - return await get_tags(access_token); - } - - /// - /// 得到公众平台jsapi ticket - /// - /// - /// - public static async Task GetJsTicket(string authorizer_appid) - { - var key = string.Format(ConstantConfig.Redis_MP_Js_Ticket_Key, authorizer_appid); - var ticketInfo = await RedisHelper.GetAsync(key); - if (ticketInfo == null) - { - var access_token = await GetAuthorizerAccessToken(authorizer_appid); - ticketInfo = await get_jsapi_ticket(access_token); - if (ticketInfo.errcode == 0) - await RedisHelper.SetAsync(key, ticketInfo.ToJson(), 1 * 60 * 60); - } - return ticketInfo; - } - - /// - /// 为公众平台创建二维码 - /// - /// - /// - public static async Task CreatePermanentQrcode(string appid, string scene_str) - { - var access_token = await GetAuthorizerAccessToken(appid); - return await create_permanent_qrcode(access_token, scene_str); - } - - #region 内部微信接口 - - /// - /// 开放平台:得到access_token - /// - /// - /// - private static async Task get_component_access_token(string ticket) - { - string url = "cgi-bin/component/api_component_token"; - - var reqData = new - { - component_appid = HostContext.Configuration["WxOpen:AppID"], - component_appsecret = HostContext.Configuration["WxOpen:AppSecret"], - component_verify_ticket = ticket, - }; - var respData = await GetHttpClient().PostAsJsonGetString(url, reqData); - var ret = respData.FromJsonTo(); - if (ret.errcode > 0) - { - LogHelper.Error("get_component_access_token", $"errcode={ret.errcode},errmsg={ret.errmsg}"); - } - ret.create_from = DateTime.Now.TimestampFrom19700101(); - LogHelper.Debug("get_component_access_token", respData); - return ret; - } - - - /// - ///开放平台:通过刷新的方式获得公众平台的accesstoken - /// - /// - /// - private static async Task get_authorizer_access_token_by_refresh(string authorizer_appid, string authorizer_refresh_token,string component_access_token) - { - string url = $"cgi-bin/component/api_authorizer_token?component_access_token={component_access_token}"; - var reqData = new - { - component_appid = HostContext.Configuration["WxOpen:AppID"], - authorizer_appid, - authorizer_refresh_token, - }; - - var respData = await GetHttpClient().PostAsJsonGetString(url, reqData); - var ret = respData.FromJsonToOrDefault(); - if (ret.errcode > 0) - { - LogHelper.Error("get_authorizer_access_token_by_refresh", $"errcode={ret.errcode},errmsg={ret.errmsg},authorizer_appid={authorizer_appid}"); - } - ret.create_from = DateTime.Now.TimestampFrom19700101(); - LogHelper.Debug("get_authorizer_access_token_by_callback", respData); - return ret; - } - - /// - ///开放平台: 通过授权码回调方式获得公众平台的accesstoken - /// - /// - /// - private static async Task get_authorizer_access_token_by_callback(string authorization_code,string component_access_token) - { - string url = $"cgi-bin/component/api_query_auth?component_access_token={component_access_token}"; - var reqData = new - { - component_appid = HostContext.Configuration["WxOpen:AppID"], - authorization_code, - }; - var respData = await GetHttpClient().PostAsJsonGetString(url, reqData); - var ret = respData.FromJsonToOrDefault(); - if (ret.errcode > 0) - { - LogHelper.Error("get_authorizer_access_token_by_callback", $"errcode={ret.errcode},errmsg={ret.errmsg}"); - } - ret.create_from = DateTime.Now.TimestampFrom19700101(); - LogHelper.Debug("get_authorizer_access_token_by_callback", respData); - return ret; - } - - /// - ///开放平台: 获取开放平台预授权代码 用于生成授权url - /// - private static async Task get_pre_auth_Code(string component_access_token) - { - string url = $"cgi-bin/component/api_create_preauthcode?component_access_token={component_access_token}"; - var reqData = new - { - component_appid = HostContext.Configuration["WxOpen:AppID"], - }; - - var respData = await GetHttpClient().PostAsJsonGetString(url, reqData); - var ret = respData.FromJsonToOrDefault(); - if (ret.errcode > 0) - { - LogHelper.Error("get_pre_auth_Code", $"errcode={ret.errcode},errmsg={ret.errmsg}"); - } - ret.create_from = DateTime.Now.TimestampFrom19700101(); - LogHelper.Debug("get_pre_auth_Code", respData); - return ret; - } - - /// - /// 开放平台:获得公众平台用户openid信息 - /// - /// - /// - /// - /// - private static async Task get_authorizer_user_openIdifno(string appid, string code, string component_access_token) - { - LogHelper.Debug("get_authorizer_user_openIdifno_params", $"{appid},{code}"); - var component_appid = HostContext.Configuration["WxOpen:AppID"]; - string url = $"sns/oauth2/component/access_token?appid={appid}&code={code}&grant_type=authorization_code&component_appid={component_appid}&component_access_token={component_access_token}"; - - LogHelper.Debug("get_authorizer_user_openIdifno-url", url); - var resp = await GetHttpClient().GetStringAsync(url); - var respData = resp.FromJsonToOrDefault(); - LogHelper.Debug("get_authorizer_user_openIdifno", resp); - return respData; - } - - /// - ///公众平台,小程序: 直接获得公众平台,小程序的accesstoken - /// - /// - /// - private static async Task get_access_token(string appid, string secret) - { - string url = $"cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}"; - - var respData = await GetHttpClient().GetStringAsync(url); - var ret = respData.FromJsonToOrDefault(); - if (ret.errcode > 0) - { - LogHelper.Error("get_mp_access_token", $"errcode={ret.errcode},errmsg={ret.errmsg}"); - } - ret.create_from = DateTime.Now.TimestampFrom19700101(); - LogHelper.Debug("get_mp_access_token", respData); - return ret; - } - - /// - ///公众平台,通过code换取网页授权access_token - ///这里通过code换取的是一个特殊的网页授权access_token,与基础支持中的access_token(该access_token用于调用其他接口)不同 - ///https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842 - /// - /// - /// - private static async Task get_web_access_token(string appid, string secret,string code) - { - string url = $"sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code"; - var respData = await GetHttpClient().GetStringAsync(url); - var ret = respData.FromJsonToOrDefault(); - if (ret.errcode > 0) - { - LogHelper.Error("get_web_access_token", $"errcode={ret.errcode},errmsg={ret.errmsg}"); - } - ret.create_from = DateTime.Now.TimestampFrom19700101(); - LogHelper.Debug("get_web_access_token", respData); - return ret; - } - - /// - /// 如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。 - /// https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842 - /// - /// 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同 - /// - /// - private static async Task get_userinfo_by_web_access_token(string access_token, string openid) - { - string url = $"sns/userinfo?access_token={access_token}&openid={openid}&lang=zh_CN"; - var respData = await GetHttpClient().GetStringAsync(url); - var ret = respData.FromJsonToOrDefault(); - if (ret.errcode > 0) - { - LogHelper.Error("get_userinfo_by_web_access_token", $"errcode={ret.errcode},errmsg={ret.errmsg}"); - } - LogHelper.Debug("get_userinfo_by_web_access_token", respData); - return ret; - } - - private static async Task get_user_openid_info(string access_token, string openid) - { - string url = $"cgi-bin/user/info?access_token={access_token}&openid={openid}&lang=zh_CN"; - var respData = await GetHttpClient().GetStringAsync(url); - var ret = respData.FromJsonToOrDefault(); - if (ret.errcode > 0) - { - LogHelper.Error("get_user_openid_info", $"errcode={ret.errcode},errmsg={ret.errmsg}"); - } - LogHelper.Debug("get_user_openid_info", respData); - return ret; - } - - - /// - /// 通过开放平台得到公众号的信息,主要是 (authorizer_info) - /// - /// - /// - /// - private static async Task get_mp_info(string component_token, string authorizer_appid) - { - string url = $"cgi-bin/component/api_get_authorizer_info?component_access_token={component_token}"; - - var reqData = new - { - authorizer_appid, - component_appid = HostContext.Configuration["WxOpen:AppID"], - }; - var respData = await GetHttpClient().PostAsJsonGetString(url, reqData); - var ret = respData.FromJsonToOrDefault(); - if (ret.errcode > 0) - { - LogHelper.Error("get_mp_info_resp", $"errcode={ret.errcode},errmsg={ret.errmsg}"); - } - LogHelper.Debug("get_mp_info_resp", respData); - return ret; - } - - /// - /// 为公众平台创建菜单 - /// - /// - /// - /// - private static async Task create_mp_menu(string access_token, object menu) - { - string url = $"cgi-bin/menu/create?access_token={access_token}"; - var respData = await GetHttpClient().PostAsJsonGetString(url, menu); - var ret = respData.FromJsonToOrDefault(); - if (ret.errcode > 0) - { - LogHelper.Error("create_mp_menu", $"errcode={ret.errcode},errmsg={ret.errmsg}"); - } - LogHelper.Debug("create_mp_menu", respData); - return ret; - } - - /// - /// 为公众号粉丝打标签 - /// - /// - /// - /// - private static async Task add_tag(string access_token, List openIds,int tagId) - { - string url = $"cgi-bin/tags/members/batchtagging?access_token={access_token}"; - - var reqData = new - { - openid_list = openIds, - tagid = tagId - }; - var respData = await GetHttpClient().PostAsJsonGetString(url, reqData); - var ret = respData.FromJsonToOrDefault(); - if (ret.errcode > 0) - { - LogHelper.Error("add_tag", $"errcode={ret.errcode},errmsg={ret.errmsg}"); - } - LogHelper.Debug("add_tag", respData); - return ret; - } - - /// - /// 创建公众号二维码 - /// - /// - /// - /// - private static async Task get_tags(string access_token) - { - string url = $"cgi-bin/tags/get?access_token={access_token}"; - var respData = await GetHttpClient().GetStringAsync(url); - var ret = respData.FromJsonToOrDefault(); - if (ret.errcode > 0) - { - LogHelper.Error("get_tags", $"errcode={ret.errcode},errmsg={ret.errmsg}"); - } - LogHelper.Debug("get_tags", respData); - return ret; - } - - /// - /// 创建公众号二维码 - /// - /// - /// - /// - private static async Task create_permanent_qrcode(string access_token,string scene_str) - { - string url = $"cgi-bin/qrcode/create?access_token={access_token}"; - //{ "action_name": "QR_LIMIT_STR_SCENE", "action_info": { "scene": { "scene_str": "test"} } } - var reqData = new - { - action_name = "QR_LIMIT_STR_SCENE", - action_info = new - { - scene = new - { - scene_str - } - } - }; - var respData = await GetHttpClient().PostAsJsonGetString(url, reqData); - var ret = respData.FromJsonToOrDefault(); - if (ret.errcode > 0) - { - LogHelper.Error("create_permanent_qrcode", $"errcode={ret.errcode},errmsg={ret.errmsg}"); - } - LogHelper.Debug("create_permanent_qrcode", respData); - return ret; - } - - public static async Task get_jsapi_ticket(string access_token) - { - string url = $"cgi-bin/ticket/getticket?access_token={access_token}&type=jsapi"; - var respData = await GetHttpClient().GetStringAsync(url); - var ret = respData.FromJsonToOrDefault(); - if (ret.errcode > 0) - { - LogHelper.Error("get_jsapi_ticket", $"errcode={ret.errcode},errmsg={ret.errmsg}"); - } - LogHelper.Debug("get_jsapi_ticket", respData); - return ret; - } - - #endregion - } -} +using Hncore.Infrastructure.Common; +using Hncore.Infrastructure.Extension; +using Hncore.Infrastructure.Serializer; +using Hncore.Pass.MsgCenter.Constant; +using Hncore.Pass.MsgCenter.Util; +using Hncore.Pass.MsgCenter.WxOpen.Response; +using Microsoft.EntityFrameworkCore.Internal; +using Microsoft.Extensions.Configuration; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; +using System.Web; + +namespace Hncore.Wx.Open +{ + public class WxOpenApi + { + private static readonly AsyncLock _mutex1 = new AsyncLock(); + private static readonly AsyncLock _mutex2 = new AsyncLock(); + private static readonly AsyncLock _mutex4 = new AsyncLock(); + + private static Dictionary WxAppMap = new Dictionary(); + + private static IHttpClientFactory _HttpClientFactory; + + public static void Init(IConfiguration config, IHttpClientFactory HttpClientFactory) + { + _HttpClientFactory = HttpClientFactory; + var key = config[$"WxApps:AppID"]; + WxAppMap[key] = config[$"WxApps:AppSecret"]; + //var WxMpApps = config.GetSection("WxApps"); + //var nodes = WxMpApps.GetChildren(); + //for (var i = 0; i < nodes.Count(); i++) + //{ + // var key = config[$"WxApps:{i}:AppID"]; + // var value = config[$"WxApps:{i}:AppSecret"]; + // if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value)) + // WxAppMap[key] = value; + //} + } + + public static string GetWxAppSecret(string appid) + { + if (WxAppMap.ContainsKey(appid)) + return WxAppMap[appid]; + else return ""; + } + + private static HttpClient GetHttpClient() + { + return _HttpClientFactory.CreateClient("WxOpen"); + } + public static async Task GetComponentTicket() + { + return await RedisHelper.GetAsync(ConstantConfig.Redis_Psipwechat_Ticket_Key); + } + + public static async Task SetComponentTicket(string ticket) + { + return await RedisHelper.SetAsync(ConstantConfig.Redis_Psipwechat_Ticket_Key, ticket); + } + + /// + /// 开放平台:得到开放平台的accessToken + /// + /// + public static async Task GetComponentAccessToken() + { + var component_appid = HostContext.Configuration["WxOpen:AppID"]; + var key =string.Format(ConstantConfig.Redis_ComponentAccessToken_Key, component_appid); + var tokenJson = await RedisHelper.GetAsync(key); + var token = tokenJson.FromJsonToOrDefault(); + if (token == null || token.need_to_refresh_token) + { + using (await _mutex1.LockAsync()) + { + tokenJson = await RedisHelper.GetAsync(key); + token = tokenJson.FromJsonToOrDefault(); + if (token != null && !token.need_to_refresh_token) + { + return token.component_access_token; + } + //重新去微信获取 + var ticket =await GetComponentTicket(); + token = await get_component_access_token(ticket); + if (token.errcode == 0) + { + await RedisHelper.SetAsync(key, token.ToJson(), token.expires_in); + return token.component_access_token; + } + else + { + return ""; + } + } + } + return token.component_access_token; + } + + /// + /// 开放平台:得到公众平台的AccessToken + /// + /// + public static async Task GetAuthorizerAccessToken(string authorizer_appid) + { + var key = string.Format(ConstantConfig.Redis_AuthorizerAccessToken_Key, authorizer_appid); + var refresh_key = string.Format(ConstantConfig.Redis_Refresh_AuthorizerAccessToken_Key, authorizer_appid); + var tokenJson = await RedisHelper.GetAsync(key); + var token = tokenJson.FromJsonToOrDefault(); + if (token == null || token.need_to_refresh_token) + { + using (await _mutex2.LockAsync()) + { + tokenJson = await RedisHelper.GetAsync(key); + token = tokenJson.FromJsonToOrDefault(); + if (token != null && !token.need_to_refresh_token) + { + return token.authorizer_access_token; + } + + var authorizer_refresh_token = await RedisHelper.GetAsync(refresh_key); + var component_access_token = await GetComponentAccessToken(); + token = await get_authorizer_access_token_by_refresh(authorizer_appid, authorizer_refresh_token, component_access_token); + if (token.errcode == 0) + { + await RedisHelper.SetAsync(key, token.ToJson(), token.expires_in); + await RedisHelper.SetAsync(refresh_key, token.authorizer_refresh_token,60*60*24*30); + return token.authorizer_access_token; + } + else + { + return ""; + } + } + } + return token.authorizer_access_token; + } + + public static async Task ReFreshAccessToken(string authorizer_appid, string component_access_token) + { + var key = string.Format(ConstantConfig.Redis_AuthorizerAccessToken_Key, authorizer_appid); + var refresh_key = string.Format(ConstantConfig.Redis_Refresh_AuthorizerAccessToken_Key, authorizer_appid); + var authorizer_refresh_token = await RedisHelper.GetAsync(refresh_key); + using (await _mutex4.LockAsync()) + { + var token = await get_authorizer_access_token_by_refresh(authorizer_appid, authorizer_refresh_token, component_access_token); + if (token.errcode == 0) + { + await RedisHelper.SetAsync(key, token.ToJson(), token.expires_in); + await RedisHelper.SetAsync(refresh_key, token.authorizer_refresh_token,60 * 60 * 24 * 30); + } + } + } + + /// + ///开放平台: 通过回调返回授权码的方式获得公众号的accesstoken + /// + /// + /// + public static async Task GetAuthorizerAccessTokenByCode(string authorization_code,Func> callback) + { + var component_access_token = await GetComponentAccessToken(); + var ret = await get_authorizer_access_token_by_callback(authorization_code, component_access_token); + var authorizer_appid = ret.authorization_info.authorizer_appid; + //存access_token的key + var key = string.Format(ConstantConfig.Redis_AuthorizerAccessToken_Key, authorizer_appid); + + //存refresh_access_token的key + var refresh_key = string.Format(ConstantConfig.Redis_Refresh_AuthorizerAccessToken_Key, authorizer_appid); + + var info = new GetAuthorizerAccessTokenResponse() + { + authorizer_access_token = ret.authorization_info.authorizer_access_token, + authorizer_refresh_token = ret.authorization_info.authorizer_refresh_token, + expires_in = ret.authorization_info.expires_in, + create_from = DateTime.Now.TimestampFrom19700101() + }; + + await RedisHelper.SetAsync(key, info.ToJson(), info.expires_in); + await RedisHelper.SetAsync(refresh_key, info.authorizer_refresh_token); + + if (callback != null) + { + return await callback(ret.authorization_info); + } + return info.authorizer_access_token; + } + + /// + ///开放平台: 得到开放平台的预授权码 + /// + /// + public static async Task GetPreAuthCode() + { + var component_access_token = await GetComponentAccessToken(); + var ret = await get_pre_auth_Code(component_access_token); + return ret.pre_auth_code; + } + + + /// + ///开放平台: 代公众号获取用户在公众号的OpenId,以及AccessToken 信息 + /// + /// + /// 结果对象,里边包含了授权令牌信息 + public static async Task GetAuthorizerClientUserOpenIdInfo(string appid, string code) + { + var component_access_token = await GetComponentAccessToken(); + var ret = await get_authorizer_user_openIdifno(appid, code, component_access_token); + return ret; + } + + /// + /// 开放平台:为公众平台授权的url + /// + /// + public static async Task GetAuthorizationUrl(string callback_url) + { + var appID = HostContext.Configuration["WxOpen:AppID"]; ; + var pre_auth_code = await GetPreAuthCode(); + var baseUrl = HostContext.Configuration["BaseInfoUrl"]; + callback_url = $"{baseUrl}/{callback_url}";//回调地址 + + callback_url = HttpUtility.UrlEncode(callback_url); + //开放平台授权地址 + var url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?" + + $"component_appid={appID}" + + $"&pre_auth_code={pre_auth_code}" + + $"&redirect_uri={callback_url}"; + return url; + } + + private static readonly AsyncLock _mutex3 = new AsyncLock(); + /// + /// 【公众平台、小程序】:得到公众平台、小程序的accessToken + /// + /// + public static async Task GetAccessToken(string appid, string secret) + { + var key = string.Format(ConstantConfig.Redis_MP_AccessToken_Key, appid); + var tokenJson = await RedisHelper.GetAsync(key); + var token = tokenJson.FromJsonToOrDefault(); + if (token == null || token.need_to_refresh_token) + { + using (await _mutex3.LockAsync()) + { + tokenJson = await RedisHelper.GetAsync(key); + token = tokenJson.FromJsonToOrDefault(); + if (token != null && !token.need_to_refresh_token) + { + return token.access_token; + } + token = await get_access_token(appid, secret); + if (token.errcode == 0) + { + await RedisHelper.SetAsync(key, token.ToJson(), token.expires_in); + return token.access_token; + } + return ""; + } + } + return token.access_token; + } + /// + /// 公众平台,通过code换取网页授权access_token + /// + /// + /// + /// + public static async Task GetWebAccessToken(string appid, string code) + { + var secret = GetWxAppSecret(appid); + if (string.IsNullOrWhiteSpace(secret)) + { + LogHelper.Error("GetWebAccessToken", $"appid={appid} 没有配置"); + return null; + } + return await get_web_access_token(appid, secret, code); + + } + /// + /// 通过access_token和openid拉取用户信息 + /// + /// + /// + /// + public static async Task GetUserinfoByWebAccessToken(string access_token, string openid) + { + var key = string.Format(ConstantConfig.Redis_MP_GetUserinfoByWebAccessToken_Key, openid); + var userInfo = await RedisHelper.GetAsync(key); + + if (userInfo == null) + { + userInfo = await get_userinfo_by_web_access_token(access_token, openid); + if (userInfo.errcode == 0) + await RedisHelper.SetAsync(key, userInfo.ToJson(), 2 * 60 * 60); + } + return userInfo; + } + + /// + /// 开放平台获得获取用户基本信息(UnionID机制) + /// + /// + /// + /// + public static async Task GetUserUnionIDinfo(string appid, string openid) + { + var key = string.Format(ConstantConfig.Redis_MP_GetUserUnionIDInfo_Key, openid); + var userInfo = await RedisHelper.GetAsync(key); + + if (userInfo == null) + { + var access_token = await GetAuthorizerAccessToken(appid); + userInfo = await get_user_openid_info(access_token, openid); + if (userInfo.errcode == 0) + await RedisHelper.SetAsync(key, userInfo.ToJson(), 2 * 60 * 60); + } + return userInfo; + } + + /// + /// 公众平台获得获取用户基本信息() + /// + /// + /// + /// + public static async Task GetUserinfoByOpenId(string appid, string openid) + { + var key = string.Format(ConstantConfig.Redis_MP_GetUserOpenIdInfo_Key, openid); + var userInfo = await RedisHelper.GetAsync(key); + + if (userInfo == null) + { + var access_token = await GetAccessToken(appid,GetWxAppSecret(appid)); + userInfo = await get_user_openid_info(access_token, openid); + if (userInfo.errcode == 0) + await RedisHelper.SetAsync(key, userInfo.ToJson(), 2 * 60 * 60); + } + return userInfo; + } + + /// + /// 通过开放平台获得公众号的信息 + /// + /// + /// + /// + public static async Task GetMpInfo(string authorizer_appid) + { + var key = string.Format(ConstantConfig.Redis_MP_Info_Key, authorizer_appid); + var mpInfo = await RedisHelper.GetAsync(key); + + if (mpInfo == null) + { + var component_token = await GetComponentAccessToken(); + mpInfo = await get_mp_info(component_token, authorizer_appid); + if (mpInfo.errcode == 0) + await RedisHelper.SetAsync(key, mpInfo.ToJson(), 1 * 60 * 60); + } + return mpInfo.authorizer_info; + } + + /// + /// 为公众平台创建菜单 + /// + /// + /// + public static async Task CreateMPMenu(string access_token, object menu) + { + var ret = await create_mp_menu(access_token, menu); + return ret.errcode == 0; + } + + /// + /// 为公众平台粉丝添加标签 + /// + /// + /// + public static async Task AddTag(string appid, List openIds, string tagId) + { + var access_token = await GetAuthorizerAccessToken(appid); + await add_tag(access_token, openIds, int.Parse(tagId)); + } + + /// + /// 得到公众平台所有标签 + /// + /// + /// + public static async Task GetTags(string appid) + { + var access_token = await GetAuthorizerAccessToken(appid); + return await get_tags(access_token); + } + + /// + /// 得到公众平台jsapi ticket + /// + /// + /// + public static async Task GetJsTicket(string authorizer_appid) + { + var key = string.Format(ConstantConfig.Redis_MP_Js_Ticket_Key, authorizer_appid); + var ticketInfo = await RedisHelper.GetAsync(key); + if (ticketInfo == null) + { + var access_token = await GetAuthorizerAccessToken(authorizer_appid); + ticketInfo = await get_jsapi_ticket(access_token); + if (ticketInfo.errcode == 0) + await RedisHelper.SetAsync(key, ticketInfo.ToJson(), 1 * 60 * 60); + } + return ticketInfo; + } + + /// + /// 为公众平台创建二维码 + /// + /// + /// + public static async Task CreatePermanentQrcode(string appid, string scene_str) + { + var access_token = await GetAuthorizerAccessToken(appid); + return await create_permanent_qrcode(access_token, scene_str); + } + + #region 内部微信接口 + + /// + /// 开放平台:得到access_token + /// + /// + /// + private static async Task get_component_access_token(string ticket) + { + string url = "cgi-bin/component/api_component_token"; + + var reqData = new + { + component_appid = HostContext.Configuration["WxOpen:AppID"], + component_appsecret = HostContext.Configuration["WxOpen:AppSecret"], + component_verify_ticket = ticket, + }; + var respData = await GetHttpClient().PostAsJsonGetString(url, reqData); + var ret = respData.FromJsonTo(); + if (ret.errcode > 0) + { + LogHelper.Error("get_component_access_token", $"errcode={ret.errcode},errmsg={ret.errmsg}"); + } + ret.create_from = DateTime.Now.TimestampFrom19700101(); + LogHelper.Debug("get_component_access_token", respData); + return ret; + } + + + /// + ///开放平台:通过刷新的方式获得公众平台的accesstoken + /// + /// + /// + private static async Task get_authorizer_access_token_by_refresh(string authorizer_appid, string authorizer_refresh_token,string component_access_token) + { + string url = $"cgi-bin/component/api_authorizer_token?component_access_token={component_access_token}"; + var reqData = new + { + component_appid = HostContext.Configuration["WxOpen:AppID"], + authorizer_appid, + authorizer_refresh_token, + }; + + var respData = await GetHttpClient().PostAsJsonGetString(url, reqData); + var ret = respData.FromJsonToOrDefault(); + if (ret.errcode > 0) + { + LogHelper.Error("get_authorizer_access_token_by_refresh", $"errcode={ret.errcode},errmsg={ret.errmsg},authorizer_appid={authorizer_appid}"); + } + ret.create_from = DateTime.Now.TimestampFrom19700101(); + LogHelper.Debug("get_authorizer_access_token_by_callback", respData); + return ret; + } + + /// + ///开放平台: 通过授权码回调方式获得公众平台的accesstoken + /// + /// + /// + private static async Task get_authorizer_access_token_by_callback(string authorization_code,string component_access_token) + { + string url = $"cgi-bin/component/api_query_auth?component_access_token={component_access_token}"; + var reqData = new + { + component_appid = HostContext.Configuration["WxOpen:AppID"], + authorization_code, + }; + var respData = await GetHttpClient().PostAsJsonGetString(url, reqData); + var ret = respData.FromJsonToOrDefault(); + if (ret.errcode > 0) + { + LogHelper.Error("get_authorizer_access_token_by_callback", $"errcode={ret.errcode},errmsg={ret.errmsg}"); + } + ret.create_from = DateTime.Now.TimestampFrom19700101(); + LogHelper.Debug("get_authorizer_access_token_by_callback", respData); + return ret; + } + + /// + ///开放平台: 获取开放平台预授权代码 用于生成授权url + /// + private static async Task get_pre_auth_Code(string component_access_token) + { + string url = $"cgi-bin/component/api_create_preauthcode?component_access_token={component_access_token}"; + var reqData = new + { + component_appid = HostContext.Configuration["WxOpen:AppID"], + }; + + var respData = await GetHttpClient().PostAsJsonGetString(url, reqData); + var ret = respData.FromJsonToOrDefault(); + if (ret.errcode > 0) + { + LogHelper.Error("get_pre_auth_Code", $"errcode={ret.errcode},errmsg={ret.errmsg}"); + } + ret.create_from = DateTime.Now.TimestampFrom19700101(); + LogHelper.Debug("get_pre_auth_Code", respData); + return ret; + } + + /// + /// 开放平台:获得公众平台用户openid信息 + /// + /// + /// + /// + /// + private static async Task get_authorizer_user_openIdifno(string appid, string code, string component_access_token) + { + LogHelper.Debug("get_authorizer_user_openIdifno_params", $"{appid},{code}"); + var component_appid = HostContext.Configuration["WxOpen:AppID"]; + string url = $"sns/oauth2/component/access_token?appid={appid}&code={code}&grant_type=authorization_code&component_appid={component_appid}&component_access_token={component_access_token}"; + + LogHelper.Debug("get_authorizer_user_openIdifno-url", url); + var resp = await GetHttpClient().GetStringAsync(url); + var respData = resp.FromJsonToOrDefault(); + LogHelper.Debug("get_authorizer_user_openIdifno", resp); + return respData; + } + + /// + ///公众平台,小程序: 直接获得公众平台,小程序的accesstoken + /// + /// + /// + private static async Task get_access_token(string appid, string secret) + { + string url = $"cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}"; + + var respData = await GetHttpClient().GetStringAsync(url); + var ret = respData.FromJsonToOrDefault(); + if (ret.errcode > 0) + { + LogHelper.Error("get_mp_access_token", $"errcode={ret.errcode},errmsg={ret.errmsg}"); + } + ret.create_from = DateTime.Now.TimestampFrom19700101(); + LogHelper.Debug("get_mp_access_token", respData); + return ret; + } + + /// + ///公众平台,通过code换取网页授权access_token + ///这里通过code换取的是一个特殊的网页授权access_token,与基础支持中的access_token(该access_token用于调用其他接口)不同 + ///https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842 + /// + /// + /// + private static async Task get_web_access_token(string appid, string secret,string code) + { + string url = $"sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code"; + var respData = await GetHttpClient().GetStringAsync(url); + var ret = respData.FromJsonToOrDefault(); + if (ret.errcode > 0) + { + LogHelper.Error("get_web_access_token", $"errcode={ret.errcode},errmsg={ret.errmsg}"); + } + ret.create_from = DateTime.Now.TimestampFrom19700101(); + LogHelper.Debug("get_web_access_token", respData); + return ret; + } + + /// + /// 如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。 + /// https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842 + /// + /// 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同 + /// + /// + private static async Task get_userinfo_by_web_access_token(string access_token, string openid) + { + string url = $"sns/userinfo?access_token={access_token}&openid={openid}&lang=zh_CN"; + var respData = await GetHttpClient().GetStringAsync(url); + var ret = respData.FromJsonToOrDefault(); + if (ret.errcode > 0) + { + LogHelper.Error("get_userinfo_by_web_access_token", $"errcode={ret.errcode},errmsg={ret.errmsg}"); + } + LogHelper.Debug("get_userinfo_by_web_access_token", respData); + return ret; + } + + private static async Task get_user_openid_info(string access_token, string openid) + { + string url = $"cgi-bin/user/info?access_token={access_token}&openid={openid}&lang=zh_CN"; + var respData = await GetHttpClient().GetStringAsync(url); + var ret = respData.FromJsonToOrDefault(); + if (ret.errcode > 0) + { + LogHelper.Error("get_user_openid_info", $"errcode={ret.errcode},errmsg={ret.errmsg}"); + } + LogHelper.Debug("get_user_openid_info", respData); + return ret; + } + + + /// + /// 通过开放平台得到公众号的信息,主要是 (authorizer_info) + /// + /// + /// + /// + private static async Task get_mp_info(string component_token, string authorizer_appid) + { + string url = $"cgi-bin/component/api_get_authorizer_info?component_access_token={component_token}"; + + var reqData = new + { + authorizer_appid, + component_appid = HostContext.Configuration["WxOpen:AppID"], + }; + var respData = await GetHttpClient().PostAsJsonGetString(url, reqData); + var ret = respData.FromJsonToOrDefault(); + if (ret.errcode > 0) + { + LogHelper.Error("get_mp_info_resp", $"errcode={ret.errcode},errmsg={ret.errmsg}"); + } + LogHelper.Debug("get_mp_info_resp", respData); + return ret; + } + + /// + /// 为公众平台创建菜单 + /// + /// + /// + /// + private static async Task create_mp_menu(string access_token, object menu) + { + string url = $"cgi-bin/menu/create?access_token={access_token}"; + var respData = await GetHttpClient().PostAsJsonGetString(url, menu); + var ret = respData.FromJsonToOrDefault(); + if (ret.errcode > 0) + { + LogHelper.Error("create_mp_menu", $"errcode={ret.errcode},errmsg={ret.errmsg}"); + } + LogHelper.Debug("create_mp_menu", respData); + return ret; + } + + /// + /// 为公众号粉丝打标签 + /// + /// + /// + /// + private static async Task add_tag(string access_token, List openIds,int tagId) + { + string url = $"cgi-bin/tags/members/batchtagging?access_token={access_token}"; + + var reqData = new + { + openid_list = openIds, + tagid = tagId + }; + var respData = await GetHttpClient().PostAsJsonGetString(url, reqData); + var ret = respData.FromJsonToOrDefault(); + if (ret.errcode > 0) + { + LogHelper.Error("add_tag", $"errcode={ret.errcode},errmsg={ret.errmsg}"); + } + LogHelper.Debug("add_tag", respData); + return ret; + } + + /// + /// 创建公众号二维码 + /// + /// + /// + /// + private static async Task get_tags(string access_token) + { + string url = $"cgi-bin/tags/get?access_token={access_token}"; + var respData = await GetHttpClient().GetStringAsync(url); + var ret = respData.FromJsonToOrDefault(); + if (ret.errcode > 0) + { + LogHelper.Error("get_tags", $"errcode={ret.errcode},errmsg={ret.errmsg}"); + } + LogHelper.Debug("get_tags", respData); + return ret; + } + + /// + /// 创建公众号二维码 + /// + /// + /// + /// + private static async Task create_permanent_qrcode(string access_token,string scene_str) + { + string url = $"cgi-bin/qrcode/create?access_token={access_token}"; + //{ "action_name": "QR_LIMIT_STR_SCENE", "action_info": { "scene": { "scene_str": "test"} } } + var reqData = new + { + action_name = "QR_LIMIT_STR_SCENE", + action_info = new + { + scene = new + { + scene_str + } + } + }; + var respData = await GetHttpClient().PostAsJsonGetString(url, reqData); + var ret = respData.FromJsonToOrDefault(); + if (ret.errcode > 0) + { + LogHelper.Error("create_permanent_qrcode", $"errcode={ret.errcode},errmsg={ret.errmsg}"); + } + LogHelper.Debug("create_permanent_qrcode", respData); + return ret; + } + + public static async Task get_jsapi_ticket(string access_token) + { + string url = $"cgi-bin/ticket/getticket?access_token={access_token}&type=jsapi"; + var respData = await GetHttpClient().GetStringAsync(url); + var ret = respData.FromJsonToOrDefault(); + if (ret.errcode > 0) + { + LogHelper.Error("get_jsapi_ticket", $"errcode={ret.errcode},errmsg={ret.errmsg}"); + } + LogHelper.Debug("get_jsapi_ticket", respData); + return ret; + } + + #endregion + } +} diff --git a/Infrastructure/WxApi/WxOpenCrypt.cs b/Infrastructure/WxApi/WxOpenCrypt.cs index 5bea97c..8f7264f 100644 --- a/Infrastructure/WxApi/WxOpenCrypt.cs +++ b/Infrastructure/WxApi/WxOpenCrypt.cs @@ -1,222 +1,222 @@ -using System; -using System.Collections; -//using System.Web; -using System.Security.Cryptography; -using System.Text; -using System.Xml; -using Tencent; -//-40001 : 签名验证错误 -//-40002 : xml解析失败 -//-40003 : sha加密生成签名失败 -//-40004 : AESKey 非法 -//-40005 : appid 校验错误 -//-40006 : AES 加密失败 -//-40007 : AES 解密失败 -//-40008 : 解密后得到的buffer非法 -//-40009 : base64加密异常 -//-40010 : base64解密异常 -namespace Hncore.Wx.Open -{ - public class WxOpenCrypt - { - string m_sToken; - string m_sEncodingAESKey; - string m_sAppID; - enum WXBizMsgCryptErrorCode - { - WXBizMsgCrypt_OK = 0, - WXBizMsgCrypt_ValidateSignature_Error = -40001, - WXBizMsgCrypt_ParseXml_Error = -40002, - WXBizMsgCrypt_ComputeSignature_Error = -40003, - WXBizMsgCrypt_IllegalAesKey = -40004, - WXBizMsgCrypt_ValidateAppid_Error = -40005, - WXBizMsgCrypt_EncryptAES_Error = -40006, - WXBizMsgCrypt_DecryptAES_Error = -40007, - WXBizMsgCrypt_IllegalBuffer = -40008, - WXBizMsgCrypt_EncodeBase64_Error = -40009, - WXBizMsgCrypt_DecodeBase64_Error = -40010 - }; - - //构造函数 - // @param sToken: 公众平台上,开发者设置的Token - // @param sEncodingAESKey: 公众平台上,开发者设置的EncodingAESKey - // @param sAppID: 公众帐号的appid - public WxOpenCrypt(string sToken, string sEncodingAESKey, string sAppID) - { - m_sToken = sToken; - m_sAppID = sAppID; - m_sEncodingAESKey = sEncodingAESKey; - } - - - // 检验消息的真实性,并且获取解密后的明文 - // @param sMsgSignature: 签名串,对应URL参数的msg_signature - // @param sTimeStamp: 时间戳,对应URL参数的timestamp - // @param sNonce: 随机串,对应URL参数的nonce - // @param sPostData: 密文,对应POST请求的数据 - // @param sMsg: 解密后的原文,当return返回0时有效 - // @return: 成功0,失败返回对应的错误码 - public int DecryptMsg(string sMsgSignature, string sTimeStamp, string sNonce, string sPostData, ref string sMsg) - { - if (m_sEncodingAESKey.Length!=43) - { - return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey; - } - XmlDocument doc = new XmlDocument(); - XmlNode root; - string sEncryptMsg; - try - { - doc.LoadXml(sPostData); - root = doc.FirstChild; - sEncryptMsg = root["Encrypt"].InnerText; - } - catch (Exception) - { - return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ParseXml_Error; - } - //verify signature - int ret = 0; - ret = VerifySignature(m_sToken, sTimeStamp, sNonce, sEncryptMsg, sMsgSignature); - if (ret != 0) - return ret; - //decrypt - string cpid = ""; - try - { - sMsg= Cryptography.AES_decrypt(sEncryptMsg, m_sEncodingAESKey, ref cpid); - // sMsg = SecurityHelper.Decrypt(sEncryptMsg, m_sEncodingAESKey); - } - catch (FormatException) - { - return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecodeBase64_Error; - } - catch (Exception) - { - return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecryptAES_Error; - } - if (cpid != m_sAppID) - return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateAppid_Error; - return 0; - } - - //将企业号回复用户的消息加密打包 - // @param sReplyMsg: 企业号待回复用户的消息,xml格式的字符串 - // @param sTimeStamp: 时间戳,可以自己生成,也可以用URL参数的timestamp - // @param sNonce: 随机串,可以自己生成,也可以用URL参数的nonce - // @param sEncryptMsg: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串, - // 当return返回0时有效 - // return:成功0,失败返回对应的错误码 - public int EncryptMsg(string sReplyMsg, string sTimeStamp, string sNonce, ref string sEncryptMsg) - { - if (m_sEncodingAESKey.Length!=43) - { - return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey; - } - string raw = ""; - try - { - raw= Cryptography.AES_encrypt(sReplyMsg, m_sEncodingAESKey, m_sAppID); - //raw = SecurityHelper.AESEncrypt(sReplyMsg, m_sEncodingAESKey); - } - catch (Exception) - { - return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_EncryptAES_Error; - } - string MsgSigature = ""; - int ret = 0; - ret = GenarateSinature(m_sToken, sTimeStamp, sNonce, raw, ref MsgSigature); - if (0 != ret) - return ret; - sEncryptMsg = ""; - - string EncryptLabelHead = ""; - string MsgSigLabelHead = ""; - string TimeStampLabelHead = ""; - string NonceLabelHead = ""; - sEncryptMsg = sEncryptMsg + "" + EncryptLabelHead + raw + EncryptLabelTail; - sEncryptMsg = sEncryptMsg + MsgSigLabelHead + MsgSigature + MsgSigLabelTail; - sEncryptMsg = sEncryptMsg + TimeStampLabelHead + sTimeStamp + TimeStampLabelTail; - sEncryptMsg = sEncryptMsg + NonceLabelHead + sNonce + NonceLabelTail; - sEncryptMsg += ""; - return 0; - } - - public class DictionarySort : System.Collections.IComparer - { - public int Compare(object oLeft, object oRight) - { - string sLeft = oLeft as string; - string sRight = oRight as string; - int iLeftLength = sLeft.Length; - int iRightLength = sRight.Length; - int index = 0; - while (index < iLeftLength && index < iRightLength) - { - if (sLeft[index] < sRight[index]) - return -1; - else if (sLeft[index] > sRight[index]) - return 1; - else - index++; - } - return iLeftLength - iRightLength; - - } - } - //Verify Signature - public static int VerifySignature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, string sSigture) - { - string hash = ""; - int ret = 0; - ret = GenarateSinature(sToken, sTimeStamp, sNonce, sMsgEncrypt, ref hash); - if (ret != 0) - return ret; - //System.Console.WriteLine(hash); - if (hash == sSigture) - return 0; - else - { - return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateSignature_Error; - } - } - - public static int GenarateSinature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt ,ref string sMsgSignature) - { - ArrayList AL = new ArrayList(); - AL.Add(sToken); - AL.Add(sTimeStamp); - AL.Add(sNonce); - AL.Add(sMsgEncrypt); - AL.Sort(new DictionarySort()); - string raw = ""; - for (int i = 0; i < AL.Count; ++i) - { - raw += AL[i]; - } - - SHA1 sha; - ASCIIEncoding enc; - string hash = ""; - try - { - sha = new SHA1CryptoServiceProvider(); - enc = new ASCIIEncoding(); - byte[] dataToHash = enc.GetBytes(raw); - byte[] dataHashed = sha.ComputeHash(dataToHash); - hash = BitConverter.ToString(dataHashed).Replace("-", ""); - hash = hash.ToLower(); - } - catch (Exception) - { - return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ComputeSignature_Error; - } - sMsgSignature = hash; - return 0; - } - } -} +using System; +using System.Collections; +//using System.Web; +using System.Security.Cryptography; +using System.Text; +using System.Xml; +using Tencent; +//-40001 : 签名验证错误 +//-40002 : xml解析失败 +//-40003 : sha加密生成签名失败 +//-40004 : AESKey 非法 +//-40005 : appid 校验错误 +//-40006 : AES 加密失败 +//-40007 : AES 解密失败 +//-40008 : 解密后得到的buffer非法 +//-40009 : base64加密异常 +//-40010 : base64解密异常 +namespace Hncore.Wx.Open +{ + public class WxOpenCrypt + { + string m_sToken; + string m_sEncodingAESKey; + string m_sAppID; + enum WXBizMsgCryptErrorCode + { + WXBizMsgCrypt_OK = 0, + WXBizMsgCrypt_ValidateSignature_Error = -40001, + WXBizMsgCrypt_ParseXml_Error = -40002, + WXBizMsgCrypt_ComputeSignature_Error = -40003, + WXBizMsgCrypt_IllegalAesKey = -40004, + WXBizMsgCrypt_ValidateAppid_Error = -40005, + WXBizMsgCrypt_EncryptAES_Error = -40006, + WXBizMsgCrypt_DecryptAES_Error = -40007, + WXBizMsgCrypt_IllegalBuffer = -40008, + WXBizMsgCrypt_EncodeBase64_Error = -40009, + WXBizMsgCrypt_DecodeBase64_Error = -40010 + }; + + //构造函数 + // @param sToken: 公众平台上,开发者设置的Token + // @param sEncodingAESKey: 公众平台上,开发者设置的EncodingAESKey + // @param sAppID: 公众帐号的appid + public WxOpenCrypt(string sToken, string sEncodingAESKey, string sAppID) + { + m_sToken = sToken; + m_sAppID = sAppID; + m_sEncodingAESKey = sEncodingAESKey; + } + + + // 检验消息的真实性,并且获取解密后的明文 + // @param sMsgSignature: 签名串,对应URL参数的msg_signature + // @param sTimeStamp: 时间戳,对应URL参数的timestamp + // @param sNonce: 随机串,对应URL参数的nonce + // @param sPostData: 密文,对应POST请求的数据 + // @param sMsg: 解密后的原文,当return返回0时有效 + // @return: 成功0,失败返回对应的错误码 + public int DecryptMsg(string sMsgSignature, string sTimeStamp, string sNonce, string sPostData, ref string sMsg) + { + if (m_sEncodingAESKey.Length!=43) + { + return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey; + } + XmlDocument doc = new XmlDocument(); + XmlNode root; + string sEncryptMsg; + try + { + doc.LoadXml(sPostData); + root = doc.FirstChild; + sEncryptMsg = root["Encrypt"].InnerText; + } + catch (Exception) + { + return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ParseXml_Error; + } + //verify signature + int ret = 0; + ret = VerifySignature(m_sToken, sTimeStamp, sNonce, sEncryptMsg, sMsgSignature); + if (ret != 0) + return ret; + //decrypt + string cpid = ""; + try + { + sMsg= Cryptography.AES_decrypt(sEncryptMsg, m_sEncodingAESKey, ref cpid); + // sMsg = SecurityHelper.Decrypt(sEncryptMsg, m_sEncodingAESKey); + } + catch (FormatException) + { + return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecodeBase64_Error; + } + catch (Exception) + { + return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecryptAES_Error; + } + if (cpid != m_sAppID) + return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateAppid_Error; + return 0; + } + + //将企业号回复用户的消息加密打包 + // @param sReplyMsg: 企业号待回复用户的消息,xml格式的字符串 + // @param sTimeStamp: 时间戳,可以自己生成,也可以用URL参数的timestamp + // @param sNonce: 随机串,可以自己生成,也可以用URL参数的nonce + // @param sEncryptMsg: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串, + // 当return返回0时有效 + // return:成功0,失败返回对应的错误码 + public int EncryptMsg(string sReplyMsg, string sTimeStamp, string sNonce, ref string sEncryptMsg) + { + if (m_sEncodingAESKey.Length!=43) + { + return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey; + } + string raw = ""; + try + { + raw= Cryptography.AES_encrypt(sReplyMsg, m_sEncodingAESKey, m_sAppID); + //raw = SecurityHelper.AESEncrypt(sReplyMsg, m_sEncodingAESKey); + } + catch (Exception) + { + return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_EncryptAES_Error; + } + string MsgSigature = ""; + int ret = 0; + ret = GenarateSinature(m_sToken, sTimeStamp, sNonce, raw, ref MsgSigature); + if (0 != ret) + return ret; + sEncryptMsg = ""; + + string EncryptLabelHead = ""; + string MsgSigLabelHead = ""; + string TimeStampLabelHead = ""; + string NonceLabelHead = ""; + sEncryptMsg = sEncryptMsg + "" + EncryptLabelHead + raw + EncryptLabelTail; + sEncryptMsg = sEncryptMsg + MsgSigLabelHead + MsgSigature + MsgSigLabelTail; + sEncryptMsg = sEncryptMsg + TimeStampLabelHead + sTimeStamp + TimeStampLabelTail; + sEncryptMsg = sEncryptMsg + NonceLabelHead + sNonce + NonceLabelTail; + sEncryptMsg += ""; + return 0; + } + + public class DictionarySort : System.Collections.IComparer + { + public int Compare(object oLeft, object oRight) + { + string sLeft = oLeft as string; + string sRight = oRight as string; + int iLeftLength = sLeft.Length; + int iRightLength = sRight.Length; + int index = 0; + while (index < iLeftLength && index < iRightLength) + { + if (sLeft[index] < sRight[index]) + return -1; + else if (sLeft[index] > sRight[index]) + return 1; + else + index++; + } + return iLeftLength - iRightLength; + + } + } + //Verify Signature + public static int VerifySignature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, string sSigture) + { + string hash = ""; + int ret = 0; + ret = GenarateSinature(sToken, sTimeStamp, sNonce, sMsgEncrypt, ref hash); + if (ret != 0) + return ret; + //System.Console.WriteLine(hash); + if (hash == sSigture) + return 0; + else + { + return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateSignature_Error; + } + } + + public static int GenarateSinature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt ,ref string sMsgSignature) + { + ArrayList AL = new ArrayList(); + AL.Add(sToken); + AL.Add(sTimeStamp); + AL.Add(sNonce); + AL.Add(sMsgEncrypt); + AL.Sort(new DictionarySort()); + string raw = ""; + for (int i = 0; i < AL.Count; ++i) + { + raw += AL[i]; + } + + SHA1 sha; + ASCIIEncoding enc; + string hash = ""; + try + { + sha = new SHA1CryptoServiceProvider(); + enc = new ASCIIEncoding(); + byte[] dataToHash = enc.GetBytes(raw); + byte[] dataHashed = sha.ComputeHash(dataToHash); + hash = BitConverter.ToString(dataHashed).Replace("-", ""); + hash = hash.ToLower(); + } + catch (Exception) + { + return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ComputeSignature_Error; + } + sMsgSignature = hash; + return 0; + } + } +} diff --git a/Infrastructure/WxApi/obj/Debug/netstandard2.0/WxApi.csprojAssemblyReference.cache b/Infrastructure/WxApi/obj/Debug/netstandard2.0/WxApi.csprojAssemblyReference.cache index 9ee691e..8a8826a 100644 Binary files a/Infrastructure/WxApi/obj/Debug/netstandard2.0/WxApi.csprojAssemblyReference.cache and b/Infrastructure/WxApi/obj/Debug/netstandard2.0/WxApi.csprojAssemblyReference.cache differ diff --git a/Infrastructure/log_storage/build.bat b/Infrastructure/log_storage/build.bat index 729ac31..bc9c73c 100644 --- a/Infrastructure/log_storage/build.bat +++ b/Infrastructure/log_storage/build.bat @@ -1,3 +1,3 @@ -set GOARCH=amd64 -set GOOS=linux +set GOARCH=amd64 +set GOOS=linux go build \ No newline at end of file diff --git a/Infrastructure/log_storage/go.mod b/Infrastructure/log_storage/go.mod index 70b1438..bbb3a5a 100644 --- a/Infrastructure/log_storage/go.mod +++ b/Infrastructure/log_storage/go.mod @@ -1,8 +1,8 @@ -module log_storage - -go 1.13 - -require ( - github.com/go-redis/redis v6.15.2+incompatible - github.com/lib/pq v1.2.0 -) +module log_storage + +go 1.13 + +require ( + github.com/go-redis/redis v6.15.2+incompatible + github.com/lib/pq v1.2.0 +) diff --git a/Infrastructure/log_storage/go.sum b/Infrastructure/log_storage/go.sum index fa3d437..8b74866 100644 --- a/Infrastructure/log_storage/go.sum +++ b/Infrastructure/log_storage/go.sum @@ -1,4 +1,4 @@ -github.com/go-redis/redis v6.15.2+incompatible h1:9SpNVG76gr6InJGxoZ6IuuxaCOQwDAhzyXg+Bs+0Sb4= -github.com/go-redis/redis v6.15.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= -github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0= -github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/go-redis/redis v6.15.2+incompatible h1:9SpNVG76gr6InJGxoZ6IuuxaCOQwDAhzyXg+Bs+0Sb4= +github.com/go-redis/redis v6.15.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0= +github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= diff --git a/Infrastructure/log_storage/logparse/logparse.go b/Infrastructure/log_storage/logparse/logparse.go index db1c37b..52e32ab 100644 --- a/Infrastructure/log_storage/logparse/logparse.go +++ b/Infrastructure/log_storage/logparse/logparse.go @@ -1,131 +1,131 @@ -package logparse - -import ( - "encoding/json" - "fmt" - "strings" - "unicode/utf8" -) - -type filebeat struct { - Message string `json:"message"` -} - -type Log struct { - Time string - Title string - Message string - Level string - App string -} - -var lineSplitChar = "\n" -var leftMiddleBracketsChar = "[" -var rightMiddleBracketsChar = "]" -var assemblyChars = "Assembly" -var titleChars = "Title" -var messageChars = "Message :" -var sysLogStartChars1 = "at lambda_method(Closure , Object )" -var sysLogStartChars2 = "at Microsoft.Extensions." -var sysLogStartChars3 = "at Microsoft.AspNetCore" - -func LogParseStart(parse <-chan *string, db chan<- *Log) { - - for fileBeatStr := range parse { - - jsonobj := filebeat{} - - err := json.Unmarshal([]byte(*fileBeatStr), &jsonobj) - - if err != nil { - println(err) - } - - log, err := parseLog(&jsonobj.Message) - - if err != nil { - fmt.Println(err) - } else { - db <- log - } - - } -} - -func parseLog(logChars *string) (log *Log, err error) { - - defer func() { - if p := recover(); p != nil { - err = fmt.Errorf("解析日志失败:%v", p) - } - }() - - log = &Log{} - - lines := strings.Split(*logChars, lineSplitChar) - - for index, line := range lines { - - i := index + 1 - - if i == 1 && strings.HasPrefix(line, leftMiddleBracketsChar) { - - timeEndIndex := strings.Index(line, rightMiddleBracketsChar) - - log.Level = slice(line, timeEndIndex+2, -1) - log.Time = slice(line, strings.Index(line, leftMiddleBracketsChar)+1, timeEndIndex-1) - } - - if i == 2 && strings.HasPrefix(line, assemblyChars) { - - log.App = strings.TrimSpace(slice(line, 9, -1)) - } - - if i == 3 && strings.HasPrefix(line, titleChars) { - log.Title = slice(line, 7, -1) - } - - if i > 3 { - - if utf8Len(line) > 0 { - - if i == 4 && strings.HasPrefix(line, messageChars) { - line = slice(line, 9, -1) - } - - if log.Level == "ERROR" && - (strings.HasPrefix(strings.TrimSpace(line), sysLogStartChars1) || - strings.HasPrefix(strings.TrimSpace(line), sysLogStartChars2) || - strings.HasPrefix(strings.TrimSpace(line), sysLogStartChars3)) { - - continue - } - } - - log.Message += line + "\n" - } - - } - - return -} - -func slice(str string, start int, end int) string { - - str2 := []rune(str) - - len := len(str2) - - if start < 0 || start > len { - start = 0 - } - if end < 0 || end > len { - end = len - } - - return string(str2[start:end]) -} - -func utf8Len(str string) int { - return utf8.RuneCountInString(str) -} +package logparse + +import ( + "encoding/json" + "fmt" + "strings" + "unicode/utf8" +) + +type filebeat struct { + Message string `json:"message"` +} + +type Log struct { + Time string + Title string + Message string + Level string + App string +} + +var lineSplitChar = "\n" +var leftMiddleBracketsChar = "[" +var rightMiddleBracketsChar = "]" +var assemblyChars = "Assembly" +var titleChars = "Title" +var messageChars = "Message :" +var sysLogStartChars1 = "at lambda_method(Closure , Object )" +var sysLogStartChars2 = "at Microsoft.Extensions." +var sysLogStartChars3 = "at Microsoft.AspNetCore" + +func LogParseStart(parse <-chan *string, db chan<- *Log) { + + for fileBeatStr := range parse { + + jsonobj := filebeat{} + + err := json.Unmarshal([]byte(*fileBeatStr), &jsonobj) + + if err != nil { + println(err) + } + + log, err := parseLog(&jsonobj.Message) + + if err != nil { + fmt.Println(err) + } else { + db <- log + } + + } +} + +func parseLog(logChars *string) (log *Log, err error) { + + defer func() { + if p := recover(); p != nil { + err = fmt.Errorf("解析日志失败:%v", p) + } + }() + + log = &Log{} + + lines := strings.Split(*logChars, lineSplitChar) + + for index, line := range lines { + + i := index + 1 + + if i == 1 && strings.HasPrefix(line, leftMiddleBracketsChar) { + + timeEndIndex := strings.Index(line, rightMiddleBracketsChar) + + log.Level = slice(line, timeEndIndex+2, -1) + log.Time = slice(line, strings.Index(line, leftMiddleBracketsChar)+1, timeEndIndex-1) + } + + if i == 2 && strings.HasPrefix(line, assemblyChars) { + + log.App = strings.TrimSpace(slice(line, 9, -1)) + } + + if i == 3 && strings.HasPrefix(line, titleChars) { + log.Title = slice(line, 7, -1) + } + + if i > 3 { + + if utf8Len(line) > 0 { + + if i == 4 && strings.HasPrefix(line, messageChars) { + line = slice(line, 9, -1) + } + + if log.Level == "ERROR" && + (strings.HasPrefix(strings.TrimSpace(line), sysLogStartChars1) || + strings.HasPrefix(strings.TrimSpace(line), sysLogStartChars2) || + strings.HasPrefix(strings.TrimSpace(line), sysLogStartChars3)) { + + continue + } + } + + log.Message += line + "\n" + } + + } + + return +} + +func slice(str string, start int, end int) string { + + str2 := []rune(str) + + len := len(str2) + + if start < 0 || start > len { + start = 0 + } + if end < 0 || end > len { + end = len + } + + return string(str2[start:end]) +} + +func utf8Len(str string) int { + return utf8.RuneCountInString(str) +} diff --git a/Infrastructure/log_storage/logstorage/logstorage.go b/Infrastructure/log_storage/logstorage/logstorage.go index c422eff..bd1c316 100644 --- a/Infrastructure/log_storage/logstorage/logstorage.go +++ b/Infrastructure/log_storage/logstorage/logstorage.go @@ -1,29 +1,29 @@ -package logstorage - -import ( - "database/sql" - "fmt" - "log_storage/logparse" -) - -func PgsqlStorageStart(logchan <-chan *logparse.Log, dbconn string) { - - db, err := sql.Open("postgres", dbconn) - - if err != nil { - panic("pgsql连接失败") - } - - for log := range logchan { - - sql := "INSERT INTO psiplog (time,title,message,level,app) VALUES($1,$2,$3,$4,$5);" - - _, err := db.Exec(sql, log.Time, log.Title, log.Message, log.Level, log.App) - - if err != nil { - fmt.Println(err) - } else { - fmt.Println("入库一条数据") - } - } -} +package logstorage + +import ( + "database/sql" + "fmt" + "log_storage/logparse" +) + +func PgsqlStorageStart(logchan <-chan *logparse.Log, dbconn string) { + + db, err := sql.Open("postgres", dbconn) + + if err != nil { + panic("pgsql连接失败") + } + + for log := range logchan { + + sql := "INSERT INTO psiplog (time,title,message,level,app) VALUES($1,$2,$3,$4,$5);" + + _, err := db.Exec(sql, log.Time, log.Title, log.Message, log.Level, log.App) + + if err != nil { + fmt.Println(err) + } else { + fmt.Println("入库一条数据") + } + } +} diff --git a/Infrastructure/log_storage/main.go b/Infrastructure/log_storage/main.go index 89300a8..7120a85 100644 --- a/Infrastructure/log_storage/main.go +++ b/Infrastructure/log_storage/main.go @@ -1,40 +1,40 @@ -package main - -import ( - "flag" - "log_storage/logparse" - "log_storage/logstorage" - logreids "log_storage/redis" - "strconv" - - "github.com/go-redis/redis" - _ "github.com/lib/pq" -) - -func main() { - - redisAddr := flag.String("RedisAddr", "", "reids server ip地址") - redisPort := flag.Int("RedisPort", 6379, "redis端口号") - redisPassword := flag.String("RedisPwd", "", "redis密码") - pgsqlConn := flag.String("PgsqlConn", "", "pgsql连接字符串(host=192.168.1.245 port=5432 user=postgres password=123456 dbname=log)") - - flag.Parse() - - redisClient := redis.NewClient(&redis.Options{ - Addr: *redisAddr + ":" + strconv.Itoa(*redisPort), - Password: *redisPassword, - DB: 14, - }) - - parseChan := make(chan *string) - dbChan := make(chan *logparse.Log) - - go logstorage.PgsqlStorageStart(dbChan, *pgsqlConn) - go logparse.LogParseStart(parseChan, dbChan) - go logreids.RedisPullStart(parseChan, redisClient) - - waiting := make(chan interface{}) - - <-waiting - -} +package main + +import ( + "flag" + "log_storage/logparse" + "log_storage/logstorage" + logreids "log_storage/redis" + "strconv" + + "github.com/go-redis/redis" + _ "github.com/lib/pq" +) + +func main() { + + redisAddr := flag.String("RedisAddr", "", "reids server ip地址") + redisPort := flag.Int("RedisPort", 6379, "redis端口号") + redisPassword := flag.String("RedisPwd", "", "redis密码") + pgsqlConn := flag.String("PgsqlConn", "", "pgsql连接字符串(host=192.168.1.245 port=5432 user=postgres password=123456 dbname=log)") + + flag.Parse() + + redisClient := redis.NewClient(&redis.Options{ + Addr: *redisAddr + ":" + strconv.Itoa(*redisPort), + Password: *redisPassword, + DB: 14, + }) + + parseChan := make(chan *string) + dbChan := make(chan *logparse.Log) + + go logstorage.PgsqlStorageStart(dbChan, *pgsqlConn) + go logparse.LogParseStart(parseChan, dbChan) + go logreids.RedisPullStart(parseChan, redisClient) + + waiting := make(chan interface{}) + + <-waiting + +} diff --git a/Infrastructure/log_storage/redis/redispull.go b/Infrastructure/log_storage/redis/redispull.go index cd35fae..2df6faf 100644 --- a/Infrastructure/log_storage/redis/redispull.go +++ b/Infrastructure/log_storage/redis/redispull.go @@ -1,32 +1,32 @@ -package redis - -import ( - "fmt" - "github.com/go-redis/redis" - "time" -) - -func RedisPullStart(parse chan<- *string, client *redis.Client) { - - pong, err := client.Ping().Result() - - if err != nil { - panic("redis连接失败") - } - - fmt.Println(pong, err) - - for { - - vals, err := client.BLPop(0, "filebeat").Result() - - if err != nil { - fmt.Println(err) - time.Sleep(time.Second * 10) - } - - if len(vals) == 2 { - parse <- &vals[1] - } - } -} +package redis + +import ( + "fmt" + "github.com/go-redis/redis" + "time" +) + +func RedisPullStart(parse chan<- *string, client *redis.Client) { + + pong, err := client.Ping().Result() + + if err != nil { + panic("redis连接失败") + } + + fmt.Println(pong, err) + + for { + + vals, err := client.BLPop(0, "filebeat").Result() + + if err != nil { + fmt.Println(err) + time.Sleep(time.Second * 10) + } + + if len(vals) == 2 { + parse <- &vals[1] + } + } +} diff --git a/Infrastructure/log_storage/run.sh b/Infrastructure/log_storage/run.sh index 3d4eff6..f71525c 100644 --- a/Infrastructure/log_storage/run.sh +++ b/Infrastructure/log_storage/run.sh @@ -1,5 +1,5 @@ -#!/bin/bash -exec $(dirname "$0")/log_storage \ --RedisAddr=192.168.1.245 \ --RedisPwd=123456 \ +#!/bin/bash +exec $(dirname "$0")/log_storage \ +-RedisAddr=192.168.1.245 \ +-RedisPwd=123456 \ -PgsqlConn="host=192.168.1.245 port=5432 user=postgres password=123456 dbname=log sslmode=disable" \ No newline at end of file