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

View File

@@ -1,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
{
/// <summary>
/// Assembly Util Class
/// </summary>
public static class AssemblyUtil
{
/// <summary>
/// Creates the instance from type name.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="type">The type.</param>
/// <returns></returns>
public static T CreateInstance<T>(string type)
{
return CreateInstance<T>(type, new object[0]);
}
/// <summary>
/// Creates the instance from type name and parameters.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="type">The type.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public static T CreateInstance<T>(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;
}
/// <summary>
/// Gets the type by the full name, also return matched generic type without checking generic type parameters in the name.
/// </summary>
/// <param name="fullTypeName">Full name of the type.</param>
/// <param name="throwOnError">if set to <c>true</c> [throw on error].</param>
/// <param name="ignoreCase">if set to <c>true</c> [ignore case].</param>
/// <returns></returns>
#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
/// <summary>
/// Gets the implement types from assembly.
/// </summary>
/// <typeparam name="TBaseType">The type of the base type.</typeparam>
/// <param name="assembly">The assembly.</param>
/// <returns></returns>
public static IEnumerable<Type> GetImplementTypes<TBaseType>(this Assembly assembly)
{
return assembly.GetExportedTypes().Where(t =>
t.IsSubclassOf(typeof(TBaseType)) && t.IsClass && !t.IsAbstract);
}
/// <summary>
/// Gets the implemented objects by interface.
/// </summary>
/// <typeparam name="TBaseInterface">The type of the base interface.</typeparam>
/// <param name="assembly">The assembly.</param>
/// <returns></returns>
public static IEnumerable<TBaseInterface> GetImplementedObjectsByInterface<TBaseInterface>(this Assembly assembly)
where TBaseInterface : class
{
return GetImplementedObjectsByInterface<TBaseInterface>(assembly, typeof(TBaseInterface));
}
/// <summary>
/// Gets the implemented objects by interface.
/// </summary>
/// <typeparam name="TBaseInterface">The type of the base interface.</typeparam>
/// <param name="assembly">The assembly.</param>
/// <param name="targetType">Type of the target.</param>
/// <returns></returns>
public static IEnumerable<TBaseInterface> GetImplementedObjectsByInterface<TBaseInterface>(this Assembly assembly, Type targetType)
where TBaseInterface : class
{
Type[] arrType = assembly.GetExportedTypes();
var result = new List<TBaseInterface>();
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
/// <summary>
/// Clone object in binary format.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="target">The target.</param>
/// <returns></returns>
public static T BinaryClone<T>(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
/// <summary>
/// Copies the properties of one object to another object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param>
/// <param name="target">The target.</param>
/// <returns></returns>
public static T CopyPropertiesTo<T>(this T source, T target)
{
return source.CopyPropertiesTo(p => true, target);
}
/// <summary>
/// Copies the properties of one object to another object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param>
/// <param name="predict">The properties predict.</param>
/// <param name="target">The target.</param>
/// <returns></returns>
public static T CopyPropertiesTo<T>(this T source, Predicate<PropertyInfo> predict, T target)
{
PropertyInfo[] properties = source.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty);
Dictionary<string, PropertyInfo> 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;
}
/// <summary>
/// Gets the assemblies from string.
/// </summary>
/// <param name="assemblyDef">The assembly def.</param>
/// <returns></returns>
public static IEnumerable<Assembly> GetAssembliesFromString(string assemblyDef)
{
return GetAssembliesFromStrings(assemblyDef.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries));
}
/// <summary>
/// Gets the assemblies from strings.
/// </summary>
/// <param name="assemblies">The assemblies.</param>
/// <returns></returns>
public static IEnumerable<Assembly> GetAssembliesFromStrings(string[] assemblies)
{
List<Assembly> result = new List<Assembly>(assemblies.Length);
foreach (var a in assemblies)
{
result.Add(Assembly.Load(a));
}
return result;
}
public static bool IsImplementedInterface<T, TInterface>()
{
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
{
/// <summary>
/// Assembly Util Class
/// </summary>
public static class AssemblyUtil
{
/// <summary>
/// Creates the instance from type name.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="type">The type.</param>
/// <returns></returns>
public static T CreateInstance<T>(string type)
{
return CreateInstance<T>(type, new object[0]);
}
/// <summary>
/// Creates the instance from type name and parameters.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="type">The type.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public static T CreateInstance<T>(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;
}
/// <summary>
/// Gets the type by the full name, also return matched generic type without checking generic type parameters in the name.
/// </summary>
/// <param name="fullTypeName">Full name of the type.</param>
/// <param name="throwOnError">if set to <c>true</c> [throw on error].</param>
/// <param name="ignoreCase">if set to <c>true</c> [ignore case].</param>
/// <returns></returns>
#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
/// <summary>
/// Gets the implement types from assembly.
/// </summary>
/// <typeparam name="TBaseType">The type of the base type.</typeparam>
/// <param name="assembly">The assembly.</param>
/// <returns></returns>
public static IEnumerable<Type> GetImplementTypes<TBaseType>(this Assembly assembly)
{
return assembly.GetExportedTypes().Where(t =>
t.IsSubclassOf(typeof(TBaseType)) && t.IsClass && !t.IsAbstract);
}
/// <summary>
/// Gets the implemented objects by interface.
/// </summary>
/// <typeparam name="TBaseInterface">The type of the base interface.</typeparam>
/// <param name="assembly">The assembly.</param>
/// <returns></returns>
public static IEnumerable<TBaseInterface> GetImplementedObjectsByInterface<TBaseInterface>(this Assembly assembly)
where TBaseInterface : class
{
return GetImplementedObjectsByInterface<TBaseInterface>(assembly, typeof(TBaseInterface));
}
/// <summary>
/// Gets the implemented objects by interface.
/// </summary>
/// <typeparam name="TBaseInterface">The type of the base interface.</typeparam>
/// <param name="assembly">The assembly.</param>
/// <param name="targetType">Type of the target.</param>
/// <returns></returns>
public static IEnumerable<TBaseInterface> GetImplementedObjectsByInterface<TBaseInterface>(this Assembly assembly, Type targetType)
where TBaseInterface : class
{
Type[] arrType = assembly.GetExportedTypes();
var result = new List<TBaseInterface>();
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
/// <summary>
/// Clone object in binary format.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="target">The target.</param>
/// <returns></returns>
public static T BinaryClone<T>(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
/// <summary>
/// Copies the properties of one object to another object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param>
/// <param name="target">The target.</param>
/// <returns></returns>
public static T CopyPropertiesTo<T>(this T source, T target)
{
return source.CopyPropertiesTo(p => true, target);
}
/// <summary>
/// Copies the properties of one object to another object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param>
/// <param name="predict">The properties predict.</param>
/// <param name="target">The target.</param>
/// <returns></returns>
public static T CopyPropertiesTo<T>(this T source, Predicate<PropertyInfo> predict, T target)
{
PropertyInfo[] properties = source.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty);
Dictionary<string, PropertyInfo> 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;
}
/// <summary>
/// Gets the assemblies from string.
/// </summary>
/// <param name="assemblyDef">The assembly def.</param>
/// <returns></returns>
public static IEnumerable<Assembly> GetAssembliesFromString(string assemblyDef)
{
return GetAssembliesFromStrings(assemblyDef.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries));
}
/// <summary>
/// Gets the assemblies from strings.
/// </summary>
/// <param name="assemblies">The assemblies.</param>
/// <returns></returns>
public static IEnumerable<Assembly> GetAssembliesFromStrings(string[] assemblies)
{
List<Assembly> result = new List<Assembly>(assemblies.Length);
foreach (var a in assemblies)
{
result.Add(Assembly.Load(a));
}
return result;
}
public static bool IsImplementedInterface<T, TInterface>()
{
return typeof(TInterface).IsAssignableFrom(typeof(T));
}
}
}

View File

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

View File

@@ -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);
}
}
}
}

View File

@@ -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<string> _infos = new List<string>();
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<bool> GetAuthority()
{
try
{
string info = ListHelper<string>.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<string> _infos = new List<string>();
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<bool> GetAuthority()
{
try
{
string info = ListHelper<string>.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;
}
}
}
}

View File

@@ -1,102 +1,102 @@
using System.Collections.Generic;
using System.ComponentModel;
namespace Hncore.Infrastructure.Common
{
/// <summary>
/// 文件类型
/// </summary>
public class ContentTypeHelper
{
/// <summary>
/// 图片格式
/// </summary>
public static List<string> ImageList = new List<string>()
{
"image/jpeg",
"application/x-jpe",
"application/x-jpg",
"application/x-bmp",
"image/png",
"application/x-png",
"image/gif"
};
/// <summary>
/// 视频格式
/// </summary>
public static List<string> VideoList = new List<string>()
{
"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
/// <summary>
/// 得到文件类型
/// </summary>
/// <param name="contentType">文件类型</param>
/// <returns></returns>
public static FileTypeEnum GetFileType(string contentType)
{
if (ImageList.Contains(contentType))
{
return FileTypeEnum.Img;
}
if (VideoList.Contains(contentType))
{
return FileTypeEnum.Video;
}
return FileTypeEnum.Unknow;
}
#endregion
}
/// <summary>
/// 文件类型
/// </summary>
public enum FileTypeEnum
{
/// <summary>
/// 未知
/// </summary>
[Description("未知")] Unknow = 0,
/// <summary>
/// 图片
/// </summary>
[Description("图片")] Img = 1,
/// <summary>
/// 音频
/// </summary>
[Description("音频")] Audio = 2,
/// <summary>
/// 视频
/// </summary>
[Description("视频")] Video = 3,
/// <summary>
/// 其他
/// </summary>
[Description("其他")] Other = 4
}
using System.Collections.Generic;
using System.ComponentModel;
namespace Hncore.Infrastructure.Common
{
/// <summary>
/// 文件类型
/// </summary>
public class ContentTypeHelper
{
/// <summary>
/// 图片格式
/// </summary>
public static List<string> ImageList = new List<string>()
{
"image/jpeg",
"application/x-jpe",
"application/x-jpg",
"application/x-bmp",
"image/png",
"application/x-png",
"image/gif"
};
/// <summary>
/// 视频格式
/// </summary>
public static List<string> VideoList = new List<string>()
{
"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
/// <summary>
/// 得到文件类型
/// </summary>
/// <param name="contentType">文件类型</param>
/// <returns></returns>
public static FileTypeEnum GetFileType(string contentType)
{
if (ImageList.Contains(contentType))
{
return FileTypeEnum.Img;
}
if (VideoList.Contains(contentType))
{
return FileTypeEnum.Video;
}
return FileTypeEnum.Unknow;
}
#endregion
}
/// <summary>
/// 文件类型
/// </summary>
public enum FileTypeEnum
{
/// <summary>
/// 未知
/// </summary>
[Description("未知")] Unknow = 0,
/// <summary>
/// 图片
/// </summary>
[Description("图片")] Img = 1,
/// <summary>
/// 音频
/// </summary>
[Description("音频")] Audio = 2,
/// <summary>
/// 视频
/// </summary>
[Description("视频")] Video = 3,
/// <summary>
/// 其他
/// </summary>
[Description("其他")] Other = 4
}
}

View File

@@ -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");
/// <summary>
/// 将10位时间戳转时间
/// </summary>
/// <param name="unixTimeStamp"></param>
/// <returns></returns>
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);
}
/// <summary>
/// 将13位时间戳转为时间
/// </summary>
/// <param name="javaTimeStamp"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 获取时间戳
/// </summary>
/// <param name="target"></param>
/// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳</param>
/// <returns></returns>
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");
/// <summary>
/// 将10位时间戳转时间
/// </summary>
/// <param name="unixTimeStamp"></param>
/// <returns></returns>
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);
}
/// <summary>
/// 将13位时间戳转为时间
/// </summary>
/// <param name="javaTimeStamp"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 获取时间戳
/// </summary>
/// <param name="target"></param>
/// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳</param>
/// <returns></returns>
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);
}
}
}

View File

@@ -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();
}
}
}

View File

@@ -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<bool> CheckSuccess(HttpResponseMessage res)
{
var content = await res.Content.ReadAsStringAsync();
JObject jObject = JsonConvert.DeserializeObject<JObject>(content);
if (jObject["errmsg"].ToString() == "ok" && Convert.ToInt32(jObject["errcode"]) != 0)
{
return false;
}
return true;
}
}
/// <summary>
/// 此消息类型为固定text
/// </summary>
public class TextModel
{
/// <summary>
/// 此消息类型为固定text
/// </summary>
public string msgtype => "text";
/// <summary>
/// 消息内容
/// </summary>
public text text { get; set; }
/// <summary>
/// @人
/// </summary>
public atText at { get; set; }
}
/// <summary>
/// 消息内容
/// </summary>
public class text
{
/// <summary>
/// 消息内容
/// </summary>
public string content { get; set; }
}
/// <summary>
/// @人
/// </summary>
public class atText
{
/// <summary>
/// 被@人的手机号
/// </summary>
public List<string> atMobiles { get; set; }
/// <summary>
/// @所有人时:true,否则为:false
/// </summary>
public bool isAtAll { get; set; } = false;
}
/// <summary>
/// 此消息类型为固定markdown
/// </summary>
public class MarkDownModel
{
/// <summary>
/// 此消息类型为固定markdown
/// </summary>
public string msgtype => "markdown";
/// <summary>
/// 消息内容
/// </summary>
public markdown markdown { get; set; }
/// <summary>
/// @人
/// </summary>
public atMarkdown at { get; set; }
}
/// <summary>
/// 消息内容
/// </summary>
public class markdown
{
/// <summary>
/// 标题
/// </summary>
public string title { get; set; }
/// <summary>
/// 消息内容
/// </summary>
public string text { get; set; }
}
/// <summary>
/// @人
/// </summary>
public class atMarkdown
{
/// <summary>
/// 被@人的手机号
/// </summary>
public List<string> atMobiles { get; set; }
/// <summary>
/// @所有人时:true,否则为:false
/// </summary>
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<bool> CheckSuccess(HttpResponseMessage res)
{
var content = await res.Content.ReadAsStringAsync();
JObject jObject = JsonConvert.DeserializeObject<JObject>(content);
if (jObject["errmsg"].ToString() == "ok" && Convert.ToInt32(jObject["errcode"]) != 0)
{
return false;
}
return true;
}
}
/// <summary>
/// 此消息类型为固定text
/// </summary>
public class TextModel
{
/// <summary>
/// 此消息类型为固定text
/// </summary>
public string msgtype => "text";
/// <summary>
/// 消息内容
/// </summary>
public text text { get; set; }
/// <summary>
/// @人
/// </summary>
public atText at { get; set; }
}
/// <summary>
/// 消息内容
/// </summary>
public class text
{
/// <summary>
/// 消息内容
/// </summary>
public string content { get; set; }
}
/// <summary>
/// @人
/// </summary>
public class atText
{
/// <summary>
/// 被@人的手机号
/// </summary>
public List<string> atMobiles { get; set; }
/// <summary>
/// @所有人时:true,否则为:false
/// </summary>
public bool isAtAll { get; set; } = false;
}
/// <summary>
/// 此消息类型为固定markdown
/// </summary>
public class MarkDownModel
{
/// <summary>
/// 此消息类型为固定markdown
/// </summary>
public string msgtype => "markdown";
/// <summary>
/// 消息内容
/// </summary>
public markdown markdown { get; set; }
/// <summary>
/// @人
/// </summary>
public atMarkdown at { get; set; }
}
/// <summary>
/// 消息内容
/// </summary>
public class markdown
{
/// <summary>
/// 标题
/// </summary>
public string title { get; set; }
/// <summary>
/// 消息内容
/// </summary>
public string text { get; set; }
}
/// <summary>
/// @人
/// </summary>
public class atMarkdown
{
/// <summary>
/// 被@人的手机号
/// </summary>
public List<string> atMobiles { get; set; }
/// <summary>
/// @所有人时:true,否则为:false
/// </summary>
public bool isAtAll { get; set; } = false;
}
}

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -1,69 +1,69 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace Hncore.Infrastructure.Common
{
public static class HttpHelp
{
/// <summary>
/// get请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
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;
}
/// <summary>
/// get 请求带token
/// </summary>
/// <param name="token"></param>
/// <param name="url"></param>
/// <returns></returns>
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
{
/// <summary>
/// get请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
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;
}
/// <summary>
/// get 请求带token
/// </summary>
/// <param name="token"></param>
/// <param name="url"></param>
/// <returns></returns>
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;
}
}
}

View File

@@ -1,85 +1,85 @@
using System;
using System.IO;
using Qiniu.Storage;
using Qiniu.Util;
namespace Hncore.Infrastructure.Common
{
public class ImageCloudHelper
{
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <returns>图片地址</returns>
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
{
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <returns>图片地址</returns>
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;
}
}
}

View File

@@ -1,40 +1,40 @@
using System.IO;
namespace Hncore.Infrastructure.Common
{
/// <summary>
///
/// </summary>
public static class IoHelper
{
#region
/// <summary>
/// 数据流转字节数组
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
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
{
/// <summary>
///
/// </summary>
public static class IoHelper
{
#region
/// <summary>
/// 数据流转字节数组
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
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
}
}

View File

@@ -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<T>
{
#region
/// <summary>
/// 字符串转化为泛型集合
/// </summary>
/// <param name="str">字符串</param>
/// <param name="splitstr">要分割的字符</param>
/// <returns></returns>
public static List<T> StrToList(string str, char splitstr)
{
List<T> list = new List<T>();
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;
}
}
/// <summary>
/// 字符串转化为泛型集合
/// </summary>
/// <param name="str">字符串</param>
/// <returns></returns>
public static List<T> StrToList(string str)
{
return StrToList(str, ',');
}
#endregion
public static string ListToStr(List<T> 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
/// <summary>
/// 转换几个中所有元素的类型
/// </summary>
/// <typeparam name="To"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static List<To> ConvertListType<To>(List<T> list)
{
if (list == null)
{
return null;
}
List<To> newlist = new List<To>();
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
/// <summary>
/// 转化一个DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ToDataTable(IEnumerable<T> list)
{
//创建属性的集合
List<PropertyInfo> pList = new List<PropertyInfo>();
//获得反射的入口
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<T>
{
#region
/// <summary>
/// 字符串转化为泛型集合
/// </summary>
/// <param name="str">字符串</param>
/// <param name="splitstr">要分割的字符</param>
/// <returns></returns>
public static List<T> StrToList(string str, char splitstr)
{
List<T> list = new List<T>();
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;
}
}
/// <summary>
/// 字符串转化为泛型集合
/// </summary>
/// <param name="str">字符串</param>
/// <returns></returns>
public static List<T> StrToList(string str)
{
return StrToList(str, ',');
}
#endregion
public static string ListToStr(List<T> 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
/// <summary>
/// 转换几个中所有元素的类型
/// </summary>
/// <typeparam name="To"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static List<To> ConvertListType<To>(List<T> list)
{
if (list == null)
{
return null;
}
List<To> newlist = new List<To>();
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
/// <summary>
/// 转化一个DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ToDataTable(IEnumerable<T> list)
{
//创建属性的集合
List<PropertyInfo> pList = new List<PropertyInfo>();
//获得反射的入口
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
}
}

View File

@@ -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));
}
}
}

View File

@@ -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<int> 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<int> ExecuteAsync(string connStr, string sql, object param = null)
{
using (var conn = new MySqlConnection(connStr))
{
conn.Open();
return await conn.ExecuteAsync(sql, param);
}
}
}
}

View File

@@ -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();
}
}
}

View File

@@ -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";
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <returns>图片地址</returns>
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);
}
/// <summary>
/// 删除资源
/// </summary>
/// <param name="key"></param>
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<string> 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";
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <returns>图片地址</returns>
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);
}
/// <summary>
/// 删除资源
/// </summary>
/// <param name="key"></param>
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<string> 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;
}
}
}

View File

@@ -1,333 +1,333 @@
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Hncore.Infrastructure.Common
{
/// <summary>
/// RSA加解密 使用OpenSSL的公钥加密/私钥解密
///
/// 公私钥请使用openssl生成 ssh-keygen -t rsa 命令生成的公钥私钥是不行的
/// </summary>
public class RsaHelper
{
private readonly RSA _privateKeyRsaProvider;
private readonly RSA _publicKeyRsaProvider;
private readonly HashAlgorithmName _hashAlgorithmName;
private readonly Encoding _encoding;
/// <summary>
/// 实例化RSAHelper
/// </summary>
/// <param name="rsaType">加密算法类型 RSA SHA1;RSA2 SHA256 密钥长度至少为2048</param>
/// <param name="encoding">编码类型</param>
/// <param name="privateKey">私钥</param>
/// <param name="publicKey">公钥</param>
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 使
/// <summary>
/// 使用私钥签名
/// </summary>
/// <param name="data">原始数据</param>
/// <returns></returns>
public string Sign(string data)
{
byte[] dataBytes = _encoding.GetBytes(data);
var signatureBytes =
_privateKeyRsaProvider.SignData(dataBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1);
return Convert.ToBase64String(signatureBytes);
}
#endregion
#region 使
/// <summary>
/// 使用公钥验证签名
/// </summary>
/// <param name="data">原始数据</param>
/// <param name="sign">签名</param>
/// <returns></returns>
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
}
/// <summary>
/// RSA算法类型
/// </summary>
public enum RsaType
{
/// <summary>
/// SHA1
/// </summary>
RSA = 0,
/// <summary>
/// RSA2 密钥长度至少为2048
/// SHA256
/// </summary>
RSA2
}
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Hncore.Infrastructure.Common
{
/// <summary>
/// RSA加解密 使用OpenSSL的公钥加密/私钥解密
///
/// 公私钥请使用openssl生成 ssh-keygen -t rsa 命令生成的公钥私钥是不行的
/// </summary>
public class RsaHelper
{
private readonly RSA _privateKeyRsaProvider;
private readonly RSA _publicKeyRsaProvider;
private readonly HashAlgorithmName _hashAlgorithmName;
private readonly Encoding _encoding;
/// <summary>
/// 实例化RSAHelper
/// </summary>
/// <param name="rsaType">加密算法类型 RSA SHA1;RSA2 SHA256 密钥长度至少为2048</param>
/// <param name="encoding">编码类型</param>
/// <param name="privateKey">私钥</param>
/// <param name="publicKey">公钥</param>
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 使
/// <summary>
/// 使用私钥签名
/// </summary>
/// <param name="data">原始数据</param>
/// <returns></returns>
public string Sign(string data)
{
byte[] dataBytes = _encoding.GetBytes(data);
var signatureBytes =
_privateKeyRsaProvider.SignData(dataBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1);
return Convert.ToBase64String(signatureBytes);
}
#endregion
#region 使
/// <summary>
/// 使用公钥验证签名
/// </summary>
/// <param name="data">原始数据</param>
/// <param name="sign">签名</param>
/// <returns></returns>
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
}
/// <summary>
/// RSA算法类型
/// </summary>
public enum RsaType
{
/// <summary>
/// SHA1
/// </summary>
RSA = 0,
/// <summary>
/// RSA2 密钥长度至少为2048
/// SHA256
/// </summary>
RSA2
}
}

View File

@@ -1,143 +1,143 @@
using System;
using System.Collections.Generic;
namespace Hncore.Infrastructure.Common
{
public class RandomHelper
{
#region
/// <summary>
/// 随机数最小值
/// </summary>
private static int MiniNum => int.MinValue;
/// <summary>
/// 随机数最大值
/// </summary>
private static int MaxNum => int.MaxValue;
/// <summary>
/// 随机数长度
/// </summary>
private static int RandomLength => 4;
/// <summary>
/// 随机数来源
/// </summary>
private static string RandomString => "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz";
/// <summary>
/// 系统默认生成随机数长度
/// </summary>
private const int RandomLengthPresent = 6;
/// <summary>
/// 系统默认随机数来源
/// </summary>
private const string RandomStringPresent = "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz";
private static readonly Random Random = new Random(DateTime.Now.Millisecond);
#endregion
#region
/// <summary>
/// 产生随机字符
/// </summary>
/// <param name="randomLength">产生随机数长度,默认为-1</param>
/// <param name="randomString">随机数来源</param>
/// <returns></returns>
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
/// <summary>
/// 产生随机数
/// </summary>
/// <param name="minNum">最小随机数</param>
/// <param name="maxNum">最大随机数</param>
/// <returns></returns>
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.01.0
/// <summary>
/// 生成一个0.0到1.0的随机小数
/// </summary>
public double GetRandomDouble()
{
return Random.NextDouble();
}
#endregion
#region
/// <summary>
/// 对一个数组进行随机排序
/// </summary>
/// <typeparam name="T">数组的类型</typeparam>
/// <param name="arr">需要随机排序的数组</param>
public void GetRandomArray<T>(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<string>();
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
/// <summary>
/// 随机数最小值
/// </summary>
private static int MiniNum => int.MinValue;
/// <summary>
/// 随机数最大值
/// </summary>
private static int MaxNum => int.MaxValue;
/// <summary>
/// 随机数长度
/// </summary>
private static int RandomLength => 4;
/// <summary>
/// 随机数来源
/// </summary>
private static string RandomString => "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz";
/// <summary>
/// 系统默认生成随机数长度
/// </summary>
private const int RandomLengthPresent = 6;
/// <summary>
/// 系统默认随机数来源
/// </summary>
private const string RandomStringPresent = "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz";
private static readonly Random Random = new Random(DateTime.Now.Millisecond);
#endregion
#region
/// <summary>
/// 产生随机字符
/// </summary>
/// <param name="randomLength">产生随机数长度,默认为-1</param>
/// <param name="randomString">随机数来源</param>
/// <returns></returns>
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
/// <summary>
/// 产生随机数
/// </summary>
/// <param name="minNum">最小随机数</param>
/// <param name="maxNum">最大随机数</param>
/// <returns></returns>
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.01.0
/// <summary>
/// 生成一个0.0到1.0的随机小数
/// </summary>
public double GetRandomDouble()
{
return Random.NextDouble();
}
#endregion
#region
/// <summary>
/// 对一个数组进行随机排序
/// </summary>
/// <typeparam name="T">数组的类型</typeparam>
/// <param name="arr">需要随机排序的数组</param>
public void GetRandomArray<T>(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<string>();
while (true)
{
var index = GetRandom(0, 32);
list.Add(str[index].ToString());
if (list.Count >= len)
break;
}
return string.Join("", list);
}
#endregion
}
}

View File

@@ -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;
/// <summary>
///
/// </summary>
/// <param name="key">锁的键</param>
/// <param name="outTime">锁超时时间 单位毫秒</param>
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;
/// <summary>
///
/// </summary>
/// <param name="key">锁的键</param>
/// <param name="outTime">锁超时时间 单位毫秒</param>
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;
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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加密
/// <summary>
/// AES加密
/// </summary>
/// <param name="toEncrypt"></param>
/// <returns></returns>
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解密
/// <summary>
/// AES解密
/// </summary>
/// <param name="toDecrypt"></param>
/// <returns></returns>
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加密
/// <summary>
/// MD5加密
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
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加密
/// <summary>
/// 对字符串进行DES加密
/// </summary>
/// <param name="sourceString">待加密的字符串</param>
/// <returns>加密后的BASE64编码的字符串</returns>
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加密后的字符串进行解密
/// <summary>
/// 对DES加密后的字符串进行解密
/// </summary>
/// <param name="encryptedString">待解密的字符串</param>
/// <returns>解密后的字符串</returns>
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解密
/// <summary>
/// JS Aes解密
/// </summary>
/// <param name="toDecrypt"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
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
/// <summary>
/// JsAesEncrypt
/// </summary>
/// <param name="plainText"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
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
/// <summary>
/// 加密隐藏信息(将原信息其中一部分数据替换为特殊字符)
/// </summary>
/// <param name="param">原参数信息</param>
/// <param name="key">更换后的特殊字符</param>
/// <param name="index">下标</param>
/// <param name="length">位数,-1代表到队尾</param>
/// <returns></returns>
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
/// <summary>
/// 将密码使用MD5算法求哈希值
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
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加密
/// <summary>
/// AES加密
/// </summary>
/// <param name="toEncrypt"></param>
/// <returns></returns>
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解密
/// <summary>
/// AES解密
/// </summary>
/// <param name="toDecrypt"></param>
/// <returns></returns>
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加密
/// <summary>
/// MD5加密
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
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加密
/// <summary>
/// 对字符串进行DES加密
/// </summary>
/// <param name="sourceString">待加密的字符串</param>
/// <returns>加密后的BASE64编码的字符串</returns>
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加密后的字符串进行解密
/// <summary>
/// 对DES加密后的字符串进行解密
/// </summary>
/// <param name="encryptedString">待解密的字符串</param>
/// <returns>解密后的字符串</returns>
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解密
/// <summary>
/// JS Aes解密
/// </summary>
/// <param name="toDecrypt"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
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
/// <summary>
/// JsAesEncrypt
/// </summary>
/// <param name="plainText"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
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
/// <summary>
/// 加密隐藏信息(将原信息其中一部分数据替换为特殊字符)
/// </summary>
/// <param name="param">原参数信息</param>
/// <param name="key">更换后的特殊字符</param>
/// <param name="index">下标</param>
/// <param name="length">位数,-1代表到队尾</param>
/// <returns></returns>
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
/// <summary>
/// 将密码使用MD5算法求哈希值
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
public static string HashPassword(string password)
{
using (MD5 md5 = MD5.Create())
{
byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
return Convert.ToBase64String(bytes);
}
}
}
}

View File

@@ -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();
}
}
}
}

View File

@@ -1,88 +1,88 @@
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Hncore.Infrastructure.Common
{
public class UrlHelper
{
#region url参数
/// <summary>
/// 设置url参数
/// </summary>
/// <param name="paramName"></param>
/// <param name="paramValue"></param>
/// <param name="url"></param>
/// <returns></returns>
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<string> 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<string, string> 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参数
/// <summary>
/// 设置url参数
/// </summary>
/// <param name="paramName"></param>
/// <param name="paramValue"></param>
/// <param name="url"></param>
/// <returns></returns>
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<string> 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<string, string> kvs)
{
return string.Join("&", kvs.Select(m => $"{m.Key}={m.Value}"));
}
#endregion
}
}

View File

@@ -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();
}
}
}
}
}