mirror of
https://gitee.com/dotnetchina/OpenAuth.Net.git
synced 2025-11-08 02:14:44 +08:00
转移.net core 3.1,为.NET 5做准备
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
|
||||
namespace Infrastructure.Extensions.AutofacManager
|
||||
{
|
||||
/// <summary>
|
||||
/// 提供全局静态获取服务的能力。
|
||||
/// <para>例:AutofacContainerModule.GetService<IPathProvider>()</para>
|
||||
/// </summary>
|
||||
public class AutofacContainerModule
|
||||
{
|
||||
static private IServiceProvider _provider;
|
||||
public static void ConfigServiceProvider(IServiceProvider serviceProvider)
|
||||
{
|
||||
_provider = serviceProvider;
|
||||
}
|
||||
public static TService GetService<TService>() where TService:class
|
||||
{
|
||||
Type typeParameterType = typeof(TService);
|
||||
return (TService)_provider.GetService(typeParameterType);
|
||||
}
|
||||
}
|
||||
}
|
||||
9
Infrastructure/Extensions/AutofacManager/IDependency.cs
Normal file
9
Infrastructure/Extensions/AutofacManager/IDependency.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace Infrastructure.Extensions.AutofacManager
|
||||
{
|
||||
/// <summary>
|
||||
/// 所有AutoFac注入的基类
|
||||
/// </summary>
|
||||
public interface IDependency
|
||||
{
|
||||
}
|
||||
}
|
||||
361
Infrastructure/Extensions/ConvertJsonExtension.cs
Normal file
361
Infrastructure/Extensions/ConvertJsonExtension.cs
Normal file
@@ -0,0 +1,361 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Infrastructure.Extensions
|
||||
{
|
||||
public static class ConvertJsonExtension
|
||||
{
|
||||
#region 私有方法
|
||||
/// <summary>
|
||||
/// 过滤特殊字符
|
||||
/// </summary>
|
||||
/// <param name="s">字符串</param>
|
||||
/// <returns>json字符串</returns>
|
||||
private static string String2Json(String s)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < s.Length; i++)
|
||||
{
|
||||
char c = s.ToCharArray()[i];
|
||||
switch (c)
|
||||
{
|
||||
case '\"':
|
||||
sb.Append("\\\""); break;
|
||||
case '\\':
|
||||
sb.Append("\\\\"); break;
|
||||
case '/':
|
||||
sb.Append("\\/"); break;
|
||||
case '\b':
|
||||
sb.Append("\\b"); break;
|
||||
case '\f':
|
||||
sb.Append("\\f"); break;
|
||||
case '\n':
|
||||
sb.Append("\\n"); break;
|
||||
case '\r':
|
||||
sb.Append("\\r"); break;
|
||||
case '\t':
|
||||
sb.Append("\\t"); break;
|
||||
default:
|
||||
sb.Append(c); break;
|
||||
}
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
/// <summary>
|
||||
/// 格式化字符型、日期型、布尔型
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
private static string StringFormat(string str, Type type)
|
||||
{
|
||||
if (type == typeof(string))
|
||||
{
|
||||
str = String2Json(str);
|
||||
str = "\"" + str + "\"";
|
||||
}
|
||||
else if (type == typeof(DateTime))
|
||||
{
|
||||
str = "\"" + str + "\"";
|
||||
}
|
||||
else if (type == typeof(bool))
|
||||
{
|
||||
str = str.ToLower();
|
||||
}
|
||||
else if (type != typeof(string) && string.IsNullOrEmpty(str))
|
||||
{
|
||||
str = "\"" + str + "\"";
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region list转换成JSON
|
||||
/// <summary>
|
||||
/// list转换为Json
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="list"></param>
|
||||
/// <returns></returns>
|
||||
public static string ListToJson<T>(this IList<T> list)
|
||||
{
|
||||
object obj = list[0];
|
||||
return ListToJson<T>(list, obj.GetType().Name);
|
||||
}
|
||||
/// <summary>
|
||||
/// list转换为json
|
||||
/// </summary>
|
||||
/// <typeparam name="T1"></typeparam>
|
||||
/// <param name="list"></param>
|
||||
/// <param name="p"></param>
|
||||
/// <returns></returns>
|
||||
private static string ListToJson<T>(this IList<T> list, string JsonName)
|
||||
{
|
||||
if (list.Count == 0)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
StringBuilder Json = new StringBuilder();
|
||||
if (string.IsNullOrEmpty(JsonName))
|
||||
JsonName = list[0].GetType().Name;
|
||||
Json.Append("{\"" + JsonName + "\":[");
|
||||
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
T obj = Activator.CreateInstance<T>();
|
||||
PropertyInfo[] pi = obj.GetType().GetProperties();
|
||||
Json.Append("{");
|
||||
for (int j = 0; j < pi.Length; j++)
|
||||
{
|
||||
Type type = pi[j].GetValue(list[i], null).GetType();
|
||||
Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
|
||||
if (j < pi.Length - 1)
|
||||
{
|
||||
Json.Append(",");
|
||||
}
|
||||
}
|
||||
Json.Append("}");
|
||||
if (i < list.Count - 1)
|
||||
{
|
||||
Json.Append(",");
|
||||
}
|
||||
}
|
||||
Json.Append("]}");
|
||||
return Json.ToString();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 对象转换为Json
|
||||
/// <summary>
|
||||
/// 对象转换为json
|
||||
/// </summary>
|
||||
/// <param name="jsonObject">json对象</param>
|
||||
/// <returns>json字符串</returns>
|
||||
public static string ToJson(this object jsonObject)
|
||||
{
|
||||
string jsonString = "{";
|
||||
PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
|
||||
for (int i = 0; i < propertyInfo.Length; i++)
|
||||
{
|
||||
object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
|
||||
string value = string.Empty;
|
||||
if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
|
||||
{
|
||||
value = "'" + objectValue.ToString() + "'";
|
||||
}
|
||||
else if (objectValue is string)
|
||||
{
|
||||
value = "'" + ToJson(objectValue.ToString()) + "'";
|
||||
}
|
||||
else if (objectValue is IEnumerable)
|
||||
{
|
||||
value = ToJson((IEnumerable)objectValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
value = ToJson(objectValue.ToString());
|
||||
}
|
||||
jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
|
||||
}
|
||||
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
|
||||
return jsonString + "}";
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 对象集合转换为json
|
||||
/// <summary>
|
||||
/// 对象集合转换为json
|
||||
/// </summary>
|
||||
/// <param name="array">对象集合</param>
|
||||
/// <returns>json字符串</returns>
|
||||
public static string ToJson(this IEnumerable array)
|
||||
{
|
||||
string jsonString = "{";
|
||||
foreach (object item in array)
|
||||
{
|
||||
jsonString += ToJson(item) + ",";
|
||||
}
|
||||
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
|
||||
return jsonString + "]";
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 普通集合转换Json
|
||||
/// <summary>
|
||||
/// 普通集合转换Json
|
||||
/// </summary>
|
||||
/// <param name="array">集合对象</param>
|
||||
/// <returns>Json字符串</returns>
|
||||
public static string ToArrayString(this IEnumerable array)
|
||||
{
|
||||
string jsonString = "[";
|
||||
foreach (object item in array)
|
||||
{
|
||||
jsonString = ToJson(item.ToString()) + ",";
|
||||
}
|
||||
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
|
||||
return jsonString + "]";
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region DataSet转换为Json
|
||||
/// <summary>
|
||||
/// DataSet转换为Json
|
||||
/// </summary>
|
||||
/// <param name="dataSet">DataSet对象</param>
|
||||
/// <returns>Json字符串</returns>
|
||||
public static string ToJson(this DataSet dataSet)
|
||||
{
|
||||
string jsonString = "{";
|
||||
foreach (DataTable table in dataSet.Tables)
|
||||
{
|
||||
jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
|
||||
}
|
||||
jsonString = jsonString.TrimEnd(',');
|
||||
return jsonString + "}";
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Datatable转换为Json
|
||||
/// <summary>
|
||||
/// Datatable转换为Json
|
||||
/// </summary>
|
||||
/// <param name="table">Datatable对象</param>
|
||||
/// <returns>Json字符串</returns>
|
||||
public static string ToJson(this DataTable dt)
|
||||
{
|
||||
StringBuilder jsonString = new StringBuilder();
|
||||
jsonString.Append("[");
|
||||
DataRowCollection drc = dt.Rows;
|
||||
for (int i = 0; i < drc.Count; i++)
|
||||
{
|
||||
jsonString.Append("{");
|
||||
for (int j = 0; j < dt.Columns.Count; j++)
|
||||
{
|
||||
string strKey = dt.Columns[j].ColumnName;
|
||||
string strValue = drc[i][j].ToString();
|
||||
Type type = dt.Columns[j].DataType;
|
||||
jsonString.Append("\"" + strKey + "\":");
|
||||
strValue = StringFormat(strValue, type);
|
||||
if (j < dt.Columns.Count - 1)
|
||||
{
|
||||
jsonString.Append(strValue + ",");
|
||||
}
|
||||
else
|
||||
{
|
||||
jsonString.Append(strValue);
|
||||
}
|
||||
}
|
||||
jsonString.Append("},");
|
||||
}
|
||||
jsonString.Remove(jsonString.Length - 1, 1);
|
||||
jsonString.Append("]");
|
||||
return jsonString.ToString();
|
||||
}
|
||||
/// <summary>
|
||||
/// DataTable转换为Json
|
||||
/// </summary>
|
||||
public static string ToJson(this DataTable dt, string jsonName)
|
||||
{
|
||||
StringBuilder Json = new StringBuilder();
|
||||
if (string.IsNullOrEmpty(jsonName))
|
||||
jsonName = dt.TableName;
|
||||
Json.Append("{\"" + jsonName + "\":[");
|
||||
if (dt.Rows.Count > 0)
|
||||
{
|
||||
for (int i = 0; i < dt.Rows.Count; i++)
|
||||
{
|
||||
Json.Append("{");
|
||||
for (int j = 0; j < dt.Columns.Count; j++)
|
||||
{
|
||||
Type type = dt.Rows[i][j].GetType();
|
||||
Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
|
||||
if (j < dt.Columns.Count - 1)
|
||||
{
|
||||
Json.Append(",");
|
||||
}
|
||||
}
|
||||
Json.Append("}");
|
||||
if (i < dt.Rows.Count - 1)
|
||||
{
|
||||
Json.Append(",");
|
||||
}
|
||||
}
|
||||
}
|
||||
Json.Append("]}");
|
||||
return Json.ToString();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region DataReader转换为Json
|
||||
/// <summary>
|
||||
/// DataReader转换为Json
|
||||
/// </summary>
|
||||
/// <param name="dataReader">DataReader对象</param>
|
||||
/// <returns>Json字符串</returns>
|
||||
public static string ReaderJson(this IDataReader dataReader)
|
||||
{
|
||||
StringBuilder jsonString = new StringBuilder();
|
||||
Dictionary<string, Type> ModelField = new Dictionary<string, Type>();
|
||||
for (int i = 0; i < dataReader.FieldCount; i++)
|
||||
{
|
||||
ModelField.Add(dataReader.GetName(i), dataReader.GetFieldType(i));
|
||||
}
|
||||
jsonString.Append("[");
|
||||
while (dataReader.Read())
|
||||
{
|
||||
jsonString.Append("{");
|
||||
foreach (KeyValuePair<string, Type> keyVal in ModelField)
|
||||
{
|
||||
Type type = keyVal.Value;
|
||||
string strKey = keyVal.Key;
|
||||
string strValue = dataReader[strKey].ToString();
|
||||
jsonString.Append("\"" + strKey + "\":");
|
||||
strValue = StringFormat(strValue, type);
|
||||
jsonString.Append(strValue + ",");
|
||||
}
|
||||
jsonString.Remove(jsonString.Length - 1, 1);
|
||||
jsonString.Append("},");
|
||||
}
|
||||
dataReader.Close();
|
||||
jsonString.Remove(jsonString.Length - 1, 1);
|
||||
jsonString.Append("]");
|
||||
return jsonString.ToString();
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
public static T DeserializeObject<T>(this string entityString)
|
||||
{
|
||||
if (string.IsNullOrEmpty(entityString))
|
||||
{
|
||||
return default(T);
|
||||
}
|
||||
if (entityString == "{}")
|
||||
{
|
||||
entityString = "[]";
|
||||
}
|
||||
return JsonConvert.DeserializeObject<T>(entityString);
|
||||
}
|
||||
|
||||
public static string Serialize(this object obj, JsonSerializerSettings formatDate = null)
|
||||
{
|
||||
if (obj == null) return null;
|
||||
formatDate = formatDate ?? new JsonSerializerSettings
|
||||
{
|
||||
DateFormatString = "yyyy-MM-dd HH:mm:ss"
|
||||
};
|
||||
return JsonConvert.SerializeObject(obj, formatDate);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
34
Infrastructure/Extensions/DateTimeExtension.cs
Normal file
34
Infrastructure/Extensions/DateTimeExtension.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
using System;
|
||||
|
||||
namespace Infrastructure.Extensions
|
||||
{
|
||||
public static class DateTimeExtension
|
||||
{
|
||||
/// <summary>
|
||||
/// 实现由C# 的时间到 Javascript 的时间的转换
|
||||
/// returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
|
||||
/// </summary>
|
||||
/// <param name="dt"></param>
|
||||
/// <returns></returns>
|
||||
public static double UnixTicks(this DateTime dt)
|
||||
{
|
||||
DateTime d1 = new DateTime(1970, 1, 1);
|
||||
DateTime d2 = dt.AddHours(8).ToUniversalTime();
|
||||
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
|
||||
return ts.TotalMilliseconds;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将毫秒值转成 C# DateTime 类型
|
||||
/// </summary>
|
||||
/// <param name="time"></param>
|
||||
/// <returns></returns>
|
||||
public static DateTime ConvertTime(this long time)
|
||||
{
|
||||
DateTime timeStamp = new DateTime(1970, 1, 1); //得到1970年的时间戳
|
||||
long t = (time + 8 * 60 * 60) * 10000000 + timeStamp.Ticks;
|
||||
DateTime dt = new DateTime(t);
|
||||
return dt;
|
||||
}
|
||||
}
|
||||
}
|
||||
1219
Infrastructure/Extensions/EntityProperties.cs
Normal file
1219
Infrastructure/Extensions/EntityProperties.cs
Normal file
File diff suppressed because it is too large
Load Diff
105
Infrastructure/Extensions/GenericExtension.cs
Normal file
105
Infrastructure/Extensions/GenericExtension.cs
Normal file
@@ -0,0 +1,105 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Infrastructure.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 泛型扩展
|
||||
/// </summary>
|
||||
public static class GenericExtension
|
||||
{
|
||||
public static bool Equal<T>(this T x, T y)
|
||||
{
|
||||
return ((IComparable)(x)).CompareTo(y) == 0;
|
||||
}
|
||||
|
||||
#region ToDictionary
|
||||
/// <summary>
|
||||
/// 将实体指定的字段写入字典
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="t"></param>
|
||||
/// <param name="expression"></param>
|
||||
/// <returns></returns>
|
||||
|
||||
public static Dictionary<string, object> ToDictionary<T>(this T t, Expression<Func<T, object>> expression) where T : class
|
||||
{
|
||||
Dictionary<string, object> dic = new Dictionary<string, object>();
|
||||
string[] fields = expression.GetExpressionToArray();
|
||||
PropertyInfo[] properties = expression == null ? t.GetType().GetProperties() : t.GetType().GetProperties().Where(x => fields.Contains(x.Name)).ToArray();
|
||||
|
||||
foreach (var property in properties)
|
||||
{
|
||||
var value = property.GetValue(t, null);
|
||||
dic.Add(property.Name, value != null ? value.ToString() : "");
|
||||
}
|
||||
return dic;
|
||||
}
|
||||
|
||||
public static Dictionary<string, string> ToDictionary<TInterface, T>(this TInterface t, Dictionary<string, string> dic = null) where T : class, TInterface
|
||||
{
|
||||
if (dic == null)
|
||||
dic = new Dictionary<string, string>();
|
||||
var properties = typeof(T).GetProperties();
|
||||
foreach (var property in properties)
|
||||
{
|
||||
var value = property.GetValue(t, null);
|
||||
if (value == null) continue;
|
||||
dic.Add(property.Name, value != null ? value.ToString() : "");
|
||||
}
|
||||
return dic;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
public static DataTable ToDataTable<T>(this IEnumerable<T> source, Expression<Func<T, object>> columns = null, bool contianKey = true)
|
||||
{
|
||||
DataTable dtReturn = new DataTable();
|
||||
if (source == null) return dtReturn;
|
||||
|
||||
PropertyInfo[] oProps = typeof(T).GetProperties()
|
||||
.Where(x => x.PropertyType.Name != "List`1").ToArray();
|
||||
if (columns != null)
|
||||
{
|
||||
string[] columnArray = columns.GetExpressionToArray();
|
||||
oProps = oProps.Where(x => columnArray.Contains(x.Name)).ToArray();
|
||||
}
|
||||
//移除自增主键
|
||||
PropertyInfo keyType = oProps.GetKeyProperty();// oProps.GetKeyProperty()?.PropertyType;
|
||||
if (!contianKey && keyType != null && (keyType.PropertyType == typeof(int) || keyType.PropertyType == typeof(long)))
|
||||
{
|
||||
oProps = oProps.Where(x => x.Name != keyType.Name).ToArray();
|
||||
}
|
||||
|
||||
foreach (var pi in oProps)
|
||||
{
|
||||
var colType = pi.PropertyType;
|
||||
|
||||
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
|
||||
{
|
||||
colType = colType.GetGenericArguments()[0];
|
||||
}
|
||||
|
||||
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
|
||||
}
|
||||
foreach (var rec in source)
|
||||
{
|
||||
var dr = dtReturn.NewRow();
|
||||
foreach (var pi in oProps)
|
||||
{
|
||||
dr[pi.Name] = pi.GetValue(rec, null) == null
|
||||
? DBNull.Value
|
||||
: pi.GetValue
|
||||
(rec, null);
|
||||
}
|
||||
dtReturn.Rows.Add(dr);
|
||||
}
|
||||
return dtReturn;
|
||||
}
|
||||
}
|
||||
}
|
||||
504
Infrastructure/Extensions/LambdaExtensions.cs
Normal file
504
Infrastructure/Extensions/LambdaExtensions.cs
Normal file
@@ -0,0 +1,504 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using Infrastructure.Const;
|
||||
|
||||
namespace Infrastructure.Extensions
|
||||
{
|
||||
public static class LambdaExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 分页查询
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="queryable"></param>
|
||||
/// <param name="page"></param>
|
||||
/// <param name="size"></param>
|
||||
/// <returns></returns>
|
||||
public static IQueryable<T> TakePage<T>(this IQueryable<T> queryable, int page, int size = 15)
|
||||
{
|
||||
return queryable.TakeOrderByPage<T>(page, size);
|
||||
}
|
||||
/// <summary>
|
||||
/// 分页查询
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="queryable"></param>
|
||||
/// <param name="page"></param>
|
||||
/// <param name="size"></param>
|
||||
/// <param name="orderBy"></param>
|
||||
/// <returns></returns>
|
||||
public static IQueryable<T> TakeOrderByPage<T>(this IQueryable<T> queryable, int page, int size = 15, Expression<Func<T, Dictionary<object, QueryOrderBy>>> orderBy = null)
|
||||
{
|
||||
if (page <= 0)
|
||||
{
|
||||
page = 1;
|
||||
}
|
||||
return Queryable.Take(Queryable.Skip(queryable.GetIQueryableOrderBy(orderBy.GetExpressionToDic()), (page - 1) * size), size);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建lambda表达式:p=>true
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static Expression<Func<T, bool>> True<T>()
|
||||
{
|
||||
return p => true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建lambda表达式:p=>false
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static Expression<Func<T, bool>> False<T>()
|
||||
{
|
||||
|
||||
return p => false;
|
||||
}
|
||||
|
||||
public static ParameterExpression GetExpressionParameter(this Type type)
|
||||
{
|
||||
|
||||
return Expression.Parameter(type, "p");
|
||||
}
|
||||
/// <summary>
|
||||
/// 创建lambda表达式:p=>p.propertyName
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <typeparam name="TKey"></typeparam>
|
||||
/// <param name="sort"></param>
|
||||
/// <returns></returns>
|
||||
public static Expression<Func<T, TKey>> GetExpression<T, TKey>(this string propertyName)
|
||||
{
|
||||
return propertyName.GetExpression<T, TKey>(typeof(T).GetExpressionParameter());
|
||||
}
|
||||
/// <summary>
|
||||
/// 创建委托有返回值的表达式:p=>p.propertyName
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <typeparam name="TKey"></typeparam>
|
||||
/// <param name="sort"></param>
|
||||
/// <returns></returns>
|
||||
public static Func<T, TKey> GetFun<T, TKey>(this string propertyName)
|
||||
{
|
||||
return propertyName.GetExpression<T, TKey>(typeof(T).GetExpressionParameter()).Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建lambda表达式:p=>false
|
||||
/// 在已知TKey字段类型时,如动态排序OrderBy(x=>x.ID)会用到此功能,返回的就是x=>x.ID
|
||||
/// Expression<Func<Out_Scheduling, DateTime>> expression = x => x.CreateDate;指定了类型
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static Expression<Func<T, TKey>> GetExpression<T, TKey>(this string propertyName, ParameterExpression parameter)
|
||||
{
|
||||
if (typeof(TKey).Name == "Object")
|
||||
return Expression.Lambda<Func<T, TKey>>(Expression.Convert(Expression.Property(parameter, propertyName), typeof(object)), parameter);
|
||||
return Expression.Lambda<Func<T, TKey>>(Expression.Property(parameter, propertyName), parameter);
|
||||
}
|
||||
/// <summary>
|
||||
/// 创建lambda表达式:p=>false
|
||||
/// object不能确认字段类型(datetime,int,string),如动态排序OrderBy(x=>x.ID)会用到此功能,返回的就是x=>x.ID
|
||||
/// Expression<Func<Out_Scheduling, object>> expression = x => x.CreateDate;任意类型的字段
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static Expression<Func<T, object>> GetExpression<T>(this string propertyName)
|
||||
{
|
||||
return propertyName.GetExpression<T, object>(typeof(T).GetExpressionParameter());
|
||||
}
|
||||
|
||||
public static Expression<Func<T, object>> GetExpression<T>(this string propertyName, ParameterExpression parameter)
|
||||
{
|
||||
return Expression.Lambda<Func<T, object>>(Expression.Convert(Expression.Property(parameter, propertyName), typeof(object)), parameter);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="propertyName">字段名</param>
|
||||
/// <param name="propertyValue">表达式的值</param>
|
||||
/// <param name="expressionType">创建表达式的类型,如:p=>p.propertyName != propertyValue
|
||||
/// p=>p.propertyName.Contains(propertyValue)</param>
|
||||
/// <returns></returns>
|
||||
public static Expression<Func<T, bool>> CreateExpression<T>(this string propertyName, object propertyValue, LinqExpressionType expressionType)
|
||||
{
|
||||
return propertyName.CreateExpression<T>(propertyValue, null, expressionType);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="propertyName">字段名</param>
|
||||
/// <param name="propertyValue">表达式的值</param>
|
||||
/// <param name="expressionType">创建表达式的类型,如:p=>p.propertyName != propertyValue
|
||||
/// p=>p.propertyName.Contains(propertyValue)</param>
|
||||
/// <returns></returns>
|
||||
private static Expression<Func<T, bool>> CreateExpression<T>(
|
||||
this string propertyName,
|
||||
object propertyValue,
|
||||
ParameterExpression parameter,
|
||||
LinqExpressionType expressionType)
|
||||
{
|
||||
Type proType = typeof(T).GetProperty(propertyName).PropertyType;
|
||||
//创建节点变量如p=>的节点p
|
||||
// parameter ??= Expression.Parameter(typeof(T), "p");//创建参数p
|
||||
parameter = parameter ?? Expression.Parameter(typeof(T), "p");
|
||||
|
||||
//创建节点的属性p=>p.name 属性name
|
||||
MemberExpression memberProperty = Expression.PropertyOrField(parameter, propertyName);
|
||||
if (expressionType == LinqExpressionType.In)
|
||||
{
|
||||
if (!(propertyValue is System.Collections.IList list) || list.Count == 0) throw new Exception("属性值类型不正确");
|
||||
|
||||
bool isStringValue = true;
|
||||
List<object> objList = new List<object>();
|
||||
|
||||
if (proType.ToString() != "System.String")
|
||||
{
|
||||
isStringValue = false;
|
||||
foreach (var value in list)
|
||||
{
|
||||
objList.Add(value.ToString().ChangeType(proType));
|
||||
}
|
||||
list = objList;
|
||||
}
|
||||
|
||||
if (isStringValue)
|
||||
{
|
||||
//string 类型的字段,如果值带有'单引号,EF会默认变成''两个单引号
|
||||
MethodInfo method = typeof(System.Collections.IList).GetMethod("Contains");
|
||||
//创建集合常量并设置为常量的值
|
||||
ConstantExpression constantCollection = Expression.Constant(list);
|
||||
//创建一个表示调用带参数的方法的:new string[]{"1","a"}.Contains("a");
|
||||
MethodCallExpression methodCall = Expression.Call(constantCollection, method, memberProperty);
|
||||
return Expression.Lambda<Func<T, bool>>(methodCall, parameter);
|
||||
}
|
||||
//非string字段,按上面方式处理报异常Null TypeMapping in Sql Tree
|
||||
BinaryExpression body = null;
|
||||
foreach (var value in list)
|
||||
{
|
||||
ConstantExpression constantExpression = Expression.Constant(value);
|
||||
UnaryExpression unaryExpression = Expression.Convert(memberProperty, constantExpression.Type);
|
||||
|
||||
body = body == null
|
||||
? Expression.Equal(unaryExpression, constantExpression)
|
||||
: Expression.OrElse(body, Expression.Equal(unaryExpression, constantExpression));
|
||||
}
|
||||
return Expression.Lambda<Func<T, bool>>(body, parameter);
|
||||
}
|
||||
|
||||
// object value = propertyValue;
|
||||
ConstantExpression constant = proType.ToString() == "System.String"
|
||||
? Expression.Constant(propertyValue) : Expression.Constant(propertyValue.ToString().ChangeType(proType));
|
||||
|
||||
UnaryExpression member = Expression.Convert(memberProperty, constant.Type);
|
||||
Expression<Func<T, bool>> expression;
|
||||
switch (expressionType)
|
||||
{
|
||||
//p=>p.propertyName == propertyValue
|
||||
case LinqExpressionType.Equal:
|
||||
expression = Expression.Lambda<Func<T, bool>>(Expression.Equal(member, constant), parameter);
|
||||
break;
|
||||
//p=>p.propertyName != propertyValue
|
||||
case LinqExpressionType.NotEqual:
|
||||
expression = Expression.Lambda<Func<T, bool>>(Expression.NotEqual(member, constant), parameter);
|
||||
break;
|
||||
// p => p.propertyName > propertyValue
|
||||
case LinqExpressionType.GreaterThan:
|
||||
expression = Expression.Lambda<Func<T, bool>>(Expression.GreaterThan(member, constant), parameter);
|
||||
break;
|
||||
// p => p.propertyName < propertyValue
|
||||
case LinqExpressionType.LessThan:
|
||||
expression = Expression.Lambda<Func<T, bool>>(Expression.LessThan(member, constant), parameter);
|
||||
break;
|
||||
// p => p.propertyName >= propertyValue
|
||||
case LinqExpressionType.ThanOrEqual:
|
||||
expression = Expression.Lambda<Func<T, bool>>(Expression.GreaterThanOrEqual(member, constant), parameter);
|
||||
break;
|
||||
// p => p.propertyName <= propertyValue
|
||||
case LinqExpressionType.LessThanOrEqual:
|
||||
expression = Expression.Lambda<Func<T, bool>>(Expression.LessThanOrEqual(member, constant), parameter);
|
||||
break;
|
||||
// p => p.propertyName.Contains(propertyValue)
|
||||
// p => !p.propertyName.Contains(propertyValue)
|
||||
case LinqExpressionType.Contains:
|
||||
case LinqExpressionType.NotContains:
|
||||
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
|
||||
constant = Expression.Constant(propertyValue, typeof(string));
|
||||
if (expressionType == LinqExpressionType.Contains)
|
||||
{
|
||||
expression = Expression.Lambda<Func<T, bool>>(Expression.Call(member, method, constant), parameter);
|
||||
}
|
||||
else
|
||||
{
|
||||
expression = Expression.Lambda<Func<T, bool>>(Expression.Not(Expression.Call(member, method, constant)), parameter);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// p => p.false
|
||||
expression = False<T>();
|
||||
break;
|
||||
}
|
||||
return expression;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 表达式转换成KeyValList(主要用于多字段排序,并且多个字段的排序规则不一样)
|
||||
/// 如有多个字段进行排序,参数格式为
|
||||
/// Expression<Func<Out_Scheduling, Dictionary<object, bool>>> orderBy = x => new Dictionary<object, bool>() {
|
||||
/// { x.ID, true },
|
||||
/// { x.DestWarehouseName, true }
|
||||
/// };
|
||||
/// 返回的是new Dictionary<object, bool>(){{}}key为排序字段,bool为升降序
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="expression"></param>
|
||||
/// <returns></returns>
|
||||
public static IEnumerable<KeyValuePair<string, QueryOrderBy>> GetExpressionToPair<T>(this Expression<Func<T, Dictionary<object, QueryOrderBy>>> expression)
|
||||
{
|
||||
|
||||
foreach (var exp in ((ListInitExpression)expression.Body).Initializers)
|
||||
{
|
||||
yield return new KeyValuePair<string, QueryOrderBy>(
|
||||
exp.Arguments[0] is MemberExpression ?
|
||||
(exp.Arguments[0] as MemberExpression).Member.Name.ToString()
|
||||
: ((exp.Arguments[0] as UnaryExpression).Operand as MemberExpression).Member.Name,
|
||||
(QueryOrderBy)((exp.Arguments[1] as ConstantExpression).Value));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 表达式转换成KeyValList(主要用于多字段排序,并且多个字段的排序规则不一样)
|
||||
/// 如有多个字段进行排序,参数格式为
|
||||
/// Expression<Func<Out_Scheduling, Dictionary<object, QueryOrderBy>>> orderBy = x => new Dictionary<object, QueryOrderBy>() {
|
||||
/// { x.ID, QueryOrderBy.Desc },
|
||||
/// { x.DestWarehouseName, QueryOrderBy.Asc }
|
||||
/// };
|
||||
/// 返回的是new Dictionary<object, QueryOrderBy>(){{}}key为排序字段,QueryOrderBy为排序方式
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="expression"></param>
|
||||
/// <returns></returns>
|
||||
public static Dictionary<string, QueryOrderBy> GetExpressionToDic<T>(this Expression<Func<T, Dictionary<object, QueryOrderBy>>> expression)
|
||||
{
|
||||
return expression.GetExpressionToPair().Reverse().ToList().ToDictionary(x => x.Key, x => x.Value);
|
||||
}
|
||||
/// <summary>
|
||||
/// 解析多字段排序
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="queryable"></param>
|
||||
/// <param name="orderBySelector">string=排序的字段,bool=true降序/false升序</param>
|
||||
/// <returns></returns>
|
||||
public static IQueryable<TEntity> GetIQueryableOrderBy<TEntity>(this IQueryable<TEntity> queryable, Dictionary<string, QueryOrderBy> orderBySelector)
|
||||
{
|
||||
string[] orderByKeys = orderBySelector.Select(x => x.Key).ToArray();
|
||||
if (orderByKeys == null || orderByKeys.Length == 0) return queryable;
|
||||
|
||||
IOrderedQueryable<TEntity> queryableOrderBy = null;
|
||||
// string orderByKey = orderByKeys[^1];
|
||||
string orderByKey = orderByKeys[orderByKeys.Length-1];
|
||||
queryableOrderBy = orderBySelector[orderByKey] == QueryOrderBy.Desc
|
||||
? queryableOrderBy = queryable.OrderByDescending(orderByKey.GetExpression<TEntity>())
|
||||
: queryable.OrderBy(orderByKey.GetExpression<TEntity>());
|
||||
|
||||
for (int i = orderByKeys.Length - 2; i >= 0; i--)
|
||||
{
|
||||
queryableOrderBy = orderBySelector[orderByKeys[i]] == QueryOrderBy.Desc
|
||||
? queryableOrderBy.ThenByDescending(orderByKeys[i].GetExpression<TEntity>())
|
||||
: queryableOrderBy.ThenBy(orderByKeys[i].GetExpression<TEntity>());
|
||||
}
|
||||
return queryableOrderBy;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取对象表达式指定属性的值
|
||||
/// 如获取:Out_Scheduling对象的ID或基他字段
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="expression">格式 Expression<Func<Out_Scheduling, object>>sch=x=>new {x.v1,x.v2} or x=>x.v1 解析里面的值返回为数组</param>
|
||||
/// <returns></returns>
|
||||
public static string[] GetExpressionToArray<TEntity>(this Expression<Func<TEntity, object>> expression)
|
||||
{
|
||||
string[] propertyNames = null;
|
||||
if (expression.Body is MemberExpression)
|
||||
{
|
||||
propertyNames = new string[] { ((MemberExpression)expression.Body).Member.Name };
|
||||
}
|
||||
else
|
||||
{
|
||||
propertyNames = expression.GetExpressionProperty().Distinct().ToArray();
|
||||
}
|
||||
return propertyNames;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 与下面and生成方式有所不同,如果直接用表达式1.2进行合并产会提示数据源不同的异常,只能使用下面的的and合并
|
||||
/// 此种合并是在使用的同一个数据源(变量),生成的sql语句同样有性能问题(本身可以索引扫描的,生成的sql语句的case when变成索引查找)
|
||||
/// <summary>
|
||||
/// 通过字段动态生成where and /or表达
|
||||
/// 如:有多个where条件,当条件成立时where 1=1 and/or 2=2,依次往后拼接
|
||||
///
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="listParas">ExpressionParameters
|
||||
/// 1、Field生成的字段
|
||||
/// 2、ExpressionType 表达式类型大于、小于、于大=、小于=、contains
|
||||
/// 3、Value表达式的值
|
||||
/// </param>
|
||||
/// <returns></returns>
|
||||
public static Expression<Func<T, bool>> And<T>(List<ExpressionParameters> listExpress)
|
||||
{
|
||||
return listExpress.Compose<T>(Expression.And);
|
||||
}
|
||||
/// <summary>
|
||||
/// 同上面and用法相同
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="listExpress"></param>
|
||||
/// <returns></returns>
|
||||
public static Expression<Func<T, bool>> Or<T>(this List<ExpressionParameters> listExpress)
|
||||
{
|
||||
return listExpress.Compose<T>(Expression.Or);
|
||||
}
|
||||
private static Expression<Func<T, bool>> Compose<T>(this List<ExpressionParameters> listExpress, Func<Expression, Expression, Expression> merge)
|
||||
{
|
||||
ParameterExpression parameter = Expression.Parameter(typeof(T), "p");
|
||||
Expression<Func<T, bool>> expression = null;
|
||||
foreach (ExpressionParameters exp in listExpress)
|
||||
{
|
||||
if (expression == null)
|
||||
{
|
||||
expression = exp.Field.GetExpression<T, bool>(parameter);
|
||||
}
|
||||
else
|
||||
{
|
||||
expression = expression.Compose(exp.Field.GetExpression<T, bool>(parameter), merge);
|
||||
}
|
||||
}
|
||||
return expression;
|
||||
}
|
||||
/// <summary>
|
||||
/// https://blogs.msdn.microsoft.com/meek/2008/05/02/linq-to-entities-combining-predicates/
|
||||
/// 表达式合并(合并生产的sql语句有性能问题)
|
||||
/// 合并两个where条件,如:多个查询条件时,判断条件成立才where
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="first"></param>
|
||||
/// <param name="second"></param>
|
||||
/// <returns></returns>
|
||||
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
|
||||
{
|
||||
return first.Compose(second, Expression.And);
|
||||
}
|
||||
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
|
||||
{
|
||||
return first.Compose(second, Expression.Or);
|
||||
}
|
||||
public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
|
||||
{
|
||||
// build parameter map (from parameters of second to parameters of first)
|
||||
var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
|
||||
// replace parameters in the second lambda expression with parameters from the first
|
||||
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
|
||||
// apply composition of lambda expression bodies to parameters from the first expression
|
||||
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
|
||||
}
|
||||
|
||||
public static IQueryable<Result> GetQueryableSelect<Source, Result>(this IQueryable<Source> queryable)
|
||||
{
|
||||
Expression<Func<Source, Result>> expression = CreateMemberInitExpression<Source, Result>();
|
||||
return queryable.Select(expression);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 动态创建表达式Expression<Func<Animal, User>> expression = CreateMemberInitExpression<Animal, User>();
|
||||
///结果为Expression<Func<Animal, User>> expression1 = x => new User() { Age = x.Age, Species = x.Species };
|
||||
///参照文档https://docs.microsoft.com/zh-cn/dotnet/api/system.linq.expressions.memberinitexpression?redirectedfrom=MSDN&view=netframework-4.8
|
||||
/// </summary>
|
||||
/// <typeparam name="Source"></typeparam>
|
||||
/// <typeparam name="Result"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static Expression<Func<Source, Result>> CreateMemberInitExpression<Source, Result>(Type resultType = null)
|
||||
{
|
||||
resultType = resultType ?? typeof(Result);
|
||||
ParameterExpression left = Expression.Parameter(typeof(Source), "p");
|
||||
NewExpression newExpression = Expression.New(resultType);
|
||||
PropertyInfo[] propertyInfos = resultType.GetProperties();
|
||||
List<MemberBinding> memberBindings = new List<MemberBinding>();
|
||||
foreach (PropertyInfo propertyInfo in propertyInfos)
|
||||
{
|
||||
MemberExpression member = Expression.Property(left, propertyInfo.Name);
|
||||
MemberBinding speciesMemberBinding = Expression.Bind(resultType.GetMember(propertyInfo.Name)[0], member);
|
||||
memberBindings.Add(speciesMemberBinding);
|
||||
}
|
||||
MemberInitExpression memberInitExpression = Expression.MemberInit(newExpression, memberBindings);
|
||||
Expression<Func<Source, Result>> expression = Expression.Lambda<Func<Source, Result>>(memberInitExpression, new ParameterExpression[] { left });
|
||||
return expression;
|
||||
}
|
||||
public static Expression<Func<Source, object>> CreateMemberInitExpression<Source>(Type resultType)
|
||||
{
|
||||
return CreateMemberInitExpression<Source, object>(resultType);
|
||||
}
|
||||
/// <summary>
|
||||
/// 属性判断待完
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
public static IEnumerable<PropertyInfo> GetGenericProperties(this Type type)
|
||||
{
|
||||
return type.GetProperties().GetGenericProperties();
|
||||
}
|
||||
/// <summary>
|
||||
/// 属性判断待完
|
||||
/// </summary>
|
||||
/// <param name="properties"></param>
|
||||
/// <returns></returns>
|
||||
public static IEnumerable<PropertyInfo> GetGenericProperties(this IEnumerable<PropertyInfo> properties)
|
||||
{
|
||||
return properties.Where(x => !x.PropertyType.IsGenericType && x.PropertyType.GetInterface("IList") == null || x.PropertyType.GetInterface("IEnumerable", false) == null);
|
||||
}
|
||||
}
|
||||
|
||||
public class ExpressionParameters
|
||||
{
|
||||
public string Field { get; set; }
|
||||
public LinqExpressionType ExpressionType { get; set; }
|
||||
public object Value { get; set; }
|
||||
// public
|
||||
}
|
||||
public class ParameterRebinder : ExpressionVisitor
|
||||
{
|
||||
|
||||
private readonly Dictionary<ParameterExpression, ParameterExpression> map;
|
||||
public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
|
||||
{
|
||||
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
|
||||
}
|
||||
|
||||
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
|
||||
{
|
||||
return new ParameterRebinder(map).Visit(exp);
|
||||
}
|
||||
protected override Expression VisitParameter(ParameterExpression p)
|
||||
{
|
||||
ParameterExpression replacement;
|
||||
if (map.TryGetValue(p, out replacement))
|
||||
{
|
||||
p = replacement;
|
||||
}
|
||||
return base.VisitParameter(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
1221
Infrastructure/Extensions/ObjectExtension.cs
Normal file
1221
Infrastructure/Extensions/ObjectExtension.cs
Normal file
File diff suppressed because it is too large
Load Diff
88
Infrastructure/Extensions/SecurityEncDecryptExtension.cs
Normal file
88
Infrastructure/Extensions/SecurityEncDecryptExtension.cs
Normal file
@@ -0,0 +1,88 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Infrastructure.Extensions
|
||||
{
|
||||
public static class SecurityEncDecryptExtensions
|
||||
{
|
||||
|
||||
private static byte[] Keys = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
|
||||
/// <summary>
|
||||
/// DES加密字符串
|
||||
/// </summary>
|
||||
/// <param name="encryptString">待加密的字符串</param>
|
||||
/// <param name="encryptKey">加密密钥,要求为16位</param>
|
||||
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
|
||||
|
||||
public static string EncryptDES(this string encryptString, string encryptKey)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 16));
|
||||
byte[] rgbIV = Keys;
|
||||
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
|
||||
|
||||
using (var DCSP = Aes.Create())
|
||||
{
|
||||
using (MemoryStream mStream = new MemoryStream())
|
||||
{
|
||||
using (CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
|
||||
{
|
||||
cStream.Write(inputByteArray, 0, inputByteArray.Length);
|
||||
cStream.FlushFinalBlock();
|
||||
return Convert.ToBase64String(mStream.ToArray()).Replace('+', '_').Replace('/', '~');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception("密码加密异常" + ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DES解密字符串
|
||||
/// </summary>
|
||||
/// <param name="decryptString">待解密的字符串</param>
|
||||
/// <param name="decryptKey">解密密钥,要求为16位,和加密密钥相同</param>
|
||||
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
|
||||
|
||||
public static string DecryptDES(this string decryptString, string decryptKey)
|
||||
{
|
||||
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 16));
|
||||
byte[] rgbIV = Keys;
|
||||
byte[] inputByteArray = Convert.FromBase64String(decryptString.Replace('_', '+').Replace('~', '/'));
|
||||
using (var DCSP = Aes.Create())
|
||||
{
|
||||
using (MemoryStream mStream = new MemoryStream())
|
||||
{
|
||||
using (CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
|
||||
{
|
||||
byte[] inputByteArrays = new byte[inputByteArray.Length];
|
||||
cStream.Write(inputByteArray, 0, inputByteArray.Length);
|
||||
cStream.FlushFinalBlock();
|
||||
return Encoding.UTF8.GetString(mStream.ToArray());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
public static bool TryDecryptDES(this string decryptString, string decryptKey, out string result)
|
||||
{
|
||||
result = "";
|
||||
try
|
||||
{
|
||||
result = DecryptDES(decryptString, decryptKey);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
28
Infrastructure/Extensions/ServerExtension.cs
Normal file
28
Infrastructure/Extensions/ServerExtension.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using Infrastructure.Extensions.AutofacManager;
|
||||
using Infrastructure.Provider;
|
||||
|
||||
namespace Infrastructure.Extensions
|
||||
{
|
||||
public static class ServerExtension
|
||||
{
|
||||
/// <summary>
|
||||
/// 返回的路径后面不带/,拼接时需要自己加上/
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <returns></returns>
|
||||
public static string MapPath(this string path)
|
||||
{
|
||||
return MapPath(path, false);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="rootPath">获取wwwroot路径</param>
|
||||
/// <returns></returns>
|
||||
public static string MapPath(this string path,bool rootPath)
|
||||
{
|
||||
return AutofacContainerModule.GetService<IPathProvider>().MapPath(path,rootPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
610
Infrastructure/Extensions/StringExtension.cs
Normal file
610
Infrastructure/Extensions/StringExtension.cs
Normal file
@@ -0,0 +1,610 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Infrastructure.Const;
|
||||
|
||||
namespace Infrastructure.Extensions
|
||||
{
|
||||
public static class StringExtension
|
||||
{
|
||||
public static bool _windows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
|
||||
/// <summary>
|
||||
/// 自动调整windows/linux下面文件目录斜杠的处理
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <returns></returns>
|
||||
public static string ReplacePath(this string path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path))
|
||||
return "";
|
||||
if (_windows)
|
||||
return path.Replace("/", "\\");
|
||||
return path.Replace("\\", "/");
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把一个字符串转成驼峰规则的字符串
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static string ToCamelCase(this string str)
|
||||
{
|
||||
if(!string.IsNullOrEmpty(str) && str.Length > 1)
|
||||
{
|
||||
return Char.ToLowerInvariant(str[0]) + str.Substring(1);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
private static DateTime dateStart = new DateTime(1970, 1, 1, 8, 0, 0);
|
||||
|
||||
private static long longTime = 621355968000000000;
|
||||
|
||||
private static int samllTime = 10000000;
|
||||
/// <summary>
|
||||
/// 获取时间戳
|
||||
/// </summary>
|
||||
/// <param name="dateTime"></param>
|
||||
/// <returns></returns>
|
||||
public static long GetTimeStamp(this DateTime dateTime)
|
||||
{
|
||||
return (dateTime.ToUniversalTime().Ticks - longTime) / samllTime;
|
||||
}
|
||||
/// <summary>
|
||||
/// 时间戳转换成日期
|
||||
/// </summary>
|
||||
/// <param name="timeStamp"></param>
|
||||
/// <returns></returns>
|
||||
public static DateTime GetTimeSpmpToDate(this object timeStamp)
|
||||
{
|
||||
if (timeStamp == null) return dateStart;
|
||||
DateTime dateTime = new DateTime(longTime + Convert.ToInt64(timeStamp) * samllTime, DateTimeKind.Utc).ToLocalTime();
|
||||
return dateTime;
|
||||
}
|
||||
|
||||
|
||||
public static bool IsUrl(this string str)
|
||||
{
|
||||
if (string.IsNullOrEmpty(str))
|
||||
return false;
|
||||
string Url = @"(http://)?([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
|
||||
return Regex.IsMatch(str, Url);
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 判断是不是正确的手机号码
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsPhoneNo(this string input)
|
||||
{
|
||||
if (string.IsNullOrEmpty(input))
|
||||
return false;
|
||||
if (input.Length != 11)
|
||||
return false;
|
||||
|
||||
if (new Regex(@"^1[3578][01379]\d{8}$").IsMatch(input)
|
||||
|| new Regex(@"^1[34578][01256]\d{8}").IsMatch(input)
|
||||
|| new Regex(@"^(1[012345678]\d{8}|1[345678][0123456789]\d{8})$").IsMatch(input)
|
||||
)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public static string GetDBCondition(this string stringType)
|
||||
{
|
||||
string reslut = "";
|
||||
switch (stringType?.ToLower())
|
||||
{
|
||||
case HtmlElementType.droplist:
|
||||
case HtmlElementType.selectlist:
|
||||
case HtmlElementType.textarea:
|
||||
case HtmlElementType.checkbox:
|
||||
reslut = HtmlElementType.Contains;
|
||||
break;
|
||||
case HtmlElementType.thanorequal:
|
||||
reslut = HtmlElementType.ThanOrEqual;
|
||||
break;
|
||||
case HtmlElementType.lessorequal:
|
||||
reslut = HtmlElementType.LessOrequal;
|
||||
break;
|
||||
case HtmlElementType.gt:
|
||||
reslut = HtmlElementType.GT;
|
||||
break;
|
||||
case HtmlElementType.lt:
|
||||
reslut = HtmlElementType.lt;
|
||||
break;
|
||||
case HtmlElementType.like:
|
||||
reslut = HtmlElementType.like;
|
||||
break;
|
||||
default:
|
||||
reslut = HtmlElementType.Equal;
|
||||
break;
|
||||
}
|
||||
return reslut;
|
||||
}
|
||||
|
||||
public static LinqExpressionType GetLinqCondition(this string stringType)
|
||||
{
|
||||
LinqExpressionType linqExpression;
|
||||
switch (stringType)
|
||||
{
|
||||
case HtmlElementType.Contains:
|
||||
linqExpression = LinqExpressionType.In;
|
||||
break;
|
||||
case HtmlElementType.ThanOrEqual:
|
||||
linqExpression = LinqExpressionType.ThanOrEqual;
|
||||
break;
|
||||
case HtmlElementType.LessOrequal:
|
||||
linqExpression = LinqExpressionType.LessThanOrEqual;
|
||||
break;
|
||||
case HtmlElementType.GT:
|
||||
linqExpression = LinqExpressionType.GreaterThan;
|
||||
break;
|
||||
case HtmlElementType.lt:
|
||||
linqExpression = LinqExpressionType.LessThan;
|
||||
break;
|
||||
case HtmlElementType.like:
|
||||
linqExpression = LinqExpressionType.Contains;
|
||||
break;
|
||||
default:
|
||||
linqExpression = LinqExpressionType.Equal;
|
||||
break;
|
||||
}
|
||||
return linqExpression;
|
||||
}
|
||||
|
||||
public static bool GetGuid(this string guid, out Guid outId)
|
||||
{
|
||||
Guid emptyId = Guid.Empty;
|
||||
return Guid.TryParse(guid, out outId);
|
||||
}
|
||||
|
||||
public static bool IsGuid(this string guid)
|
||||
{
|
||||
Guid newId;
|
||||
return GetGuid(guid, out newId);
|
||||
}
|
||||
|
||||
public static bool IsInt(this object obj)
|
||||
{
|
||||
if (obj == null)
|
||||
return false;
|
||||
bool reslut = Int32.TryParse(obj.ToString(), out int _number);
|
||||
return reslut;
|
||||
|
||||
}
|
||||
public static bool IsDate(this object str)
|
||||
{
|
||||
return IsDate(str, out _);
|
||||
}
|
||||
public static bool IsDate(this object str, out DateTime dateTime)
|
||||
{
|
||||
dateTime = DateTime.Now;
|
||||
if (str == null || str.ToString() == "")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return DateTime.TryParse(str.ToString(), out dateTime);
|
||||
}
|
||||
/// <summary>
|
||||
/// 根据传入格式判断是否为小数
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <param name="formatString">18,5</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsNumber(this string str, string formatString)
|
||||
{
|
||||
if (string.IsNullOrEmpty(str))
|
||||
return false;
|
||||
int precision = 32;
|
||||
int scale = 5;
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(formatString))
|
||||
{
|
||||
precision = 10;
|
||||
scale = 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
string[] numbers = formatString.Split(',');
|
||||
precision = Convert.ToInt32(numbers[0]);
|
||||
scale = numbers.Length == 0 ? 2 : Convert.ToInt32(numbers[1]);
|
||||
}
|
||||
}
|
||||
catch { };
|
||||
return IsNumber(str, precision, scale);
|
||||
}
|
||||
/**/
|
||||
/// <summary>
|
||||
/// 判断一个字符串是否为合法数字(指定整数位数和小数位数)
|
||||
/// </summary>
|
||||
/// <param name="str">字符串</param>
|
||||
/// <param name="precision">整数位数</param>
|
||||
/// <param name="scale">小数位数</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsNumber(this string str, int precision, int scale)
|
||||
{
|
||||
if ((precision == 0) && (scale == 0))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
string pattern = @"(^\d{1," + precision + "}";
|
||||
if (scale > 0)
|
||||
{
|
||||
pattern += @"\.\d{0," + scale + "}$)|" + pattern;
|
||||
}
|
||||
pattern += "$)";
|
||||
return Regex.IsMatch(str, pattern);
|
||||
}
|
||||
|
||||
|
||||
public static bool IsNullOrEmpty(this object str)
|
||||
{
|
||||
if (str == null)
|
||||
return true;
|
||||
return str.ToString() == "";
|
||||
}
|
||||
|
||||
|
||||
public static int GetInt(this object obj)
|
||||
{
|
||||
if (obj == null)
|
||||
return 0;
|
||||
int.TryParse(obj.ToString(), out int _number);
|
||||
return _number;
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 object 中的枚举值
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
/// <remarks></remarks>
|
||||
public static long GetLong(this object obj)
|
||||
{
|
||||
if (obj == null)
|
||||
return 0;
|
||||
|
||||
try
|
||||
{
|
||||
return Convert.ToInt64(Convert.ToDouble(obj));
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 object 中的 float
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
|
||||
public static float GetFloat(this object obj)
|
||||
{
|
||||
if (System.DBNull.Value.Equals(obj) || null == obj)
|
||||
return 0;
|
||||
|
||||
try
|
||||
{
|
||||
return float.Parse(obj.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static double GetDouble(this object obj)
|
||||
{
|
||||
if (System.DBNull.Value.Equals(obj) || null == obj)
|
||||
return 0;
|
||||
|
||||
try
|
||||
{
|
||||
return Convert.ToDouble(obj);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取 object 中的 decimal
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
/// <remarks></remarks>
|
||||
public static decimal GetDecimal(this object obj)
|
||||
{
|
||||
if (System.DBNull.Value.Equals(obj) || null == obj)
|
||||
return 0;
|
||||
|
||||
try
|
||||
{
|
||||
return Convert.ToDecimal(obj);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 object 中的 decimal
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
/// <remarks></remarks>
|
||||
public static dynamic GetDynamic(this object obj)
|
||||
{
|
||||
if (System.DBNull.Value.Equals(obj) || null == obj)
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
string str = obj.ToString();
|
||||
if (IsNumber(str, 25, 15)) return Convert.ToDecimal(obj);
|
||||
else return str;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public static DateTime? GetDateTime(this object obj)
|
||||
{
|
||||
if (System.DBNull.Value.Equals(obj) || null == obj)
|
||||
return null;
|
||||
bool result = DateTime.TryParse(obj.ToString(), out DateTime dateTime);
|
||||
if (!result)
|
||||
return null;
|
||||
return dateTime;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static object ParseTo(this string str, string type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case "System.Boolean":
|
||||
return ToBoolean(str);
|
||||
case "System.SByte":
|
||||
return ToSByte(str);
|
||||
case "System.Byte":
|
||||
return ToByte(str);
|
||||
case "System.UInt16":
|
||||
return ToUInt16(str);
|
||||
case "System.Int16":
|
||||
return ToInt16(str);
|
||||
case "System.uInt32":
|
||||
return ToUInt32(str);
|
||||
case "System.Int32":
|
||||
return ToInt32(str);
|
||||
case "System.UInt64":
|
||||
return ToUInt64(str);
|
||||
case "System.Int64":
|
||||
return ToInt64(str);
|
||||
case "System.Single":
|
||||
return ToSingle(str);
|
||||
case "System.Double":
|
||||
return ToDouble(str);
|
||||
case "System.Decimal":
|
||||
return ToDecimal(str);
|
||||
case "System.DateTime":
|
||||
return ToDateTime(str);
|
||||
case "System.Guid":
|
||||
return ToGuid(str);
|
||||
}
|
||||
throw new NotSupportedException(string.Format("The string of \"{0}\" can not be parsed to {1}", str, type));
|
||||
}
|
||||
|
||||
public static sbyte? ToSByte(this string value)
|
||||
{
|
||||
sbyte value2;
|
||||
if (sbyte.TryParse(value, out value2))
|
||||
{
|
||||
return value2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static byte? ToByte(this string value)
|
||||
{
|
||||
byte value2;
|
||||
if (byte.TryParse(value, out value2))
|
||||
{
|
||||
return value2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static ushort? ToUInt16(this string value)
|
||||
{
|
||||
ushort value2;
|
||||
if (ushort.TryParse(value, out value2))
|
||||
{
|
||||
return value2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static short? ToInt16(this string value)
|
||||
{
|
||||
if (short.TryParse(value, out short value2))
|
||||
{
|
||||
return value2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static uint? ToUInt32(this string value)
|
||||
{
|
||||
uint value2;
|
||||
if (uint.TryParse(value, out value2))
|
||||
{
|
||||
return value2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static ulong? ToUInt64(this string value)
|
||||
{
|
||||
ulong value2;
|
||||
if (ulong.TryParse(value, out value2))
|
||||
{
|
||||
return value2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static long? ToInt64(this string value)
|
||||
{
|
||||
long value2;
|
||||
if (long.TryParse(value, out value2))
|
||||
{
|
||||
return value2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static float? ToSingle(this string value)
|
||||
{
|
||||
float value2;
|
||||
if (float.TryParse(value, out value2))
|
||||
{
|
||||
return value2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static double? ToDouble(this string value)
|
||||
{
|
||||
double value2;
|
||||
if (double.TryParse(value, out value2))
|
||||
{
|
||||
return value2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static decimal? ToDecimal(this string value)
|
||||
{
|
||||
decimal value2;
|
||||
if (decimal.TryParse(value, out value2))
|
||||
{
|
||||
return value2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static bool? ToBoolean(this string value)
|
||||
{
|
||||
bool value2;
|
||||
if (bool.TryParse(value, out value2))
|
||||
{
|
||||
return value2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static Guid? ToGuid(this string str)
|
||||
{
|
||||
Guid value;
|
||||
if (Guid.TryParse(str, out value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static DateTime? ToDateTime(this string value)
|
||||
{
|
||||
DateTime value2;
|
||||
if (DateTime.TryParse(value, out value2))
|
||||
{
|
||||
return value2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int? ToInt32(this string input)
|
||||
{
|
||||
if (string.IsNullOrEmpty(input))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
int value;
|
||||
if (int.TryParse(input, out value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 替换空格字符
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <param name="replacement">替换为该字符</param>
|
||||
/// <returns>替换后的字符串</returns>
|
||||
public static string ReplaceWhitespace(this string input, string replacement = "")
|
||||
{
|
||||
return string.IsNullOrEmpty(input) ? null : Regex.Replace(input, "\\s", replacement, RegexOptions.Compiled);
|
||||
}
|
||||
|
||||
private static char[] randomConstant ={
|
||||
'0','1','2','3','4','5','6','7','8','9',
|
||||
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
|
||||
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
|
||||
};
|
||||
/// <summary>
|
||||
/// 生成指定长度的随机数
|
||||
/// </summary>
|
||||
/// <param name="length"></param>
|
||||
/// <returns></returns>
|
||||
public static string GenerateRandomNumber(this int length)
|
||||
{
|
||||
System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62);
|
||||
Random rd = new Random();
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
newRandom.Append(randomConstant[rd.Next(62)]);
|
||||
}
|
||||
return newRandom.ToString();
|
||||
}
|
||||
public static string MaxSubstring(this string origin, int maxLength)
|
||||
{
|
||||
return origin.Length >= maxLength ? origin.Substring(0, maxLength) : origin;
|
||||
}
|
||||
|
||||
public static string ToMd5(this string origin)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(origin))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var md5Algorithm = MD5.Create();
|
||||
var utf8Bytes = Encoding.UTF8.GetBytes(origin);
|
||||
var md5Hash = md5Algorithm.ComputeHash(utf8Bytes);
|
||||
var hexString = new StringBuilder();
|
||||
foreach (var hexByte in md5Hash)
|
||||
{
|
||||
hexString.Append(hexByte.ToString("x2"));
|
||||
}
|
||||
return hexString.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user