初始化项目

This commit is contained in:
2025-11-20 09:50:21 +08:00
commit 94b24e1a5d
4209 changed files with 1570805 additions and 0 deletions

View File

@@ -0,0 +1,149 @@
using Services.Enums;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace Services.Extensions
{
/// <summary>
/// 缓存扩展
/// </summary>
public static class CacheExtensions
{
public static MvcHtmlString Cache(this HtmlHelper htmlHelper, string cacheName, Func<object> func, CacheTimeType cacheTimeType, int cacheTime)
{
if (!CacheExtensions.CheckCache(cacheName))
{
CacheExtensions.SetCache(cacheName, func().ToString(), cacheTimeType, cacheTime);
}
return MvcHtmlString.Create(CacheExtensions.GetCache<string>(cacheName));
}
/// <summary>
/// 检查缓存名是否存在如果存在则返回True
/// </summary>
/// <param name="cacheName">缓存的枚举类</param>
public static bool CheckCache(string cacheName)
{
return HttpRuntime.Cache[cacheName.ToString()] != null;
}
/// <summary>
/// 获取缓存,未做校验,每次取缓存的时候需要判断缓存是否存在
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheName"></param>
/// <param name="varName"></param>
/// <returns></returns>
public static T GetCache<T>(string cacheName)
{
return (T)((object)HttpRuntime.Cache[cacheName]);
}
public static T GetCacheWithSet<T>(string cacheName, Func<T> valueFunc, CacheTimeType cacheTimeType, int times)
{
if (!CacheExtensions.CheckCache(cacheName))
{
CacheExtensions.SetCache(cacheName, valueFunc(), cacheTimeType, times);
}
return CacheExtensions.GetCache<T>(cacheName);
}
public static T GetCacheWithSet<T>(string cacheName, Func<T> valueFunc)
{
if (!CacheExtensions.CheckCache(cacheName))
{
CacheExtensions.SetCache(cacheName, valueFunc());
}
return CacheExtensions.GetCache<T>(cacheName);
}
/// <summary>
/// 获取缓存集合,未做校验,每次取缓存的时候需要判断缓存是否存在
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheName"></param>
/// <param name="varName"></param>
/// <returns></returns>
public static List<T> GetCacheList<T>(string cacheName)
{
return (List<T>)HttpRuntime.Cache[cacheName];
}
/// <summary>
/// 设置缓存
/// </summary>
/// <param name="cacheName"></param>
/// <param name="value"></param>
/// <param name="cacheTimeType"></param>
/// <param name="cacheTime"></param>
public static void SetCache(string cacheName, object value, CacheTimeType cacheTimeType, int cacheTime)
{
switch (cacheTimeType)
{
case CacheTimeType.ByMinutes:
HttpRuntime.Cache.Insert(cacheName, value, null, DateTime.Now.AddMinutes((double)cacheTime), TimeSpan.Zero);
return;
case CacheTimeType.ByHours:
HttpRuntime.Cache.Insert(cacheName, value, null, DateTime.Now.AddHours((double)cacheTime), TimeSpan.Zero);
return;
case CacheTimeType.ByDays:
HttpRuntime.Cache.Insert(cacheName, value, null, DateTime.Now.AddDays((double)cacheTime), TimeSpan.Zero);
return;
case CacheTimeType.ByYears:
HttpRuntime.Cache.Insert(cacheName, value, null, DateTime.Now.AddYears(cacheTime), TimeSpan.Zero);
return;
default:
return;
}
}
public static void SetCache(string cacheName, object value)
{
HttpRuntime.Cache.Insert(cacheName, value);
}
public static List<string> GetAllCache()
{
List<string> list = new List<string>();
IDictionaryEnumerator enumerator = HttpRuntime.Cache.GetEnumerator();
while (enumerator.MoveNext())
{
list.Add(enumerator.Key.ToString());
}
return list;
}
/// <summary>
/// 清除指定缓存
/// </summary>
/// <param name="cacheName"></param>
public static void ClearCache(string cacheName)
{
if (CacheExtensions.CheckCache(cacheName))
{
HttpRuntime.Cache.Remove(cacheName);
}
}
/// <summary>
/// 重置缓存
/// </summary>
/// <param name="cacheName"></param>
/// <param name="value"></param>
public static void RestCache(string cacheName, object value)
{
if (CacheExtensions.CheckCache(cacheName))
{
HttpRuntime.Cache[cacheName] = value;
return;
}
CacheExtensions.SetCache(cacheName, value);
}
}
}

View File

@@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace Services.Extensions
{
/// <summary>
/// cookie扩展
/// </summary>
public static class CookieExtensions
{
/// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
public static void WriteCookie(string strName, string strValue)
{
HttpCookie httpCookie = HttpContext.Current.Request.Cookies[strName];
if (httpCookie == null)
{
httpCookie = new HttpCookie(strName);
}
httpCookie.Value = strValue;
HttpContext.Current.Response.AppendCookie(httpCookie);
}
/// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
/// <param name="strValue">过期时间(分钟)</param>
public static void WriteCookie(string strName, string strValue, int expires)
{
HttpCookie httpCookie = HttpContext.Current.Request.Cookies[strName];
if (httpCookie == null)
{
httpCookie = new HttpCookie(strName);
}
httpCookie.Value = strValue;
httpCookie.Expires = DateTime.Now.AddMinutes((double)expires);
HttpContext.Current.Response.AppendCookie(httpCookie);
}
/// <summary>
/// 读cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <returns>cookie值</returns>
public static string GetCookie(string strName)
{
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
{
return HttpContext.Current.Request.Cookies[strName].Value.ToString();
}
return "";
}
/// <summary>
/// 检查Cookie,如果存在则为true
/// </summary>
/// <param name="strName"></param>
/// <returns></returns>
public static bool CheckCookie(string strName)
{
return HttpContext.Current.Request.Cookies[strName] != null;
}
/// <summary>
/// 删除Cookie
/// </summary>
/// <param name="strName"></param>
public static void RemoveCookie(string strName)
{
HttpContext.Current.Request.Cookies.Remove(strName);
}
}
}

View File

@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Services.Extensions
{
/// <summary>
/// 异常扩展
/// </summary>
public class CustomException : ApplicationException
{
//记录异常的类型
private CustomExceptionType exceptionType;
public CustomException(CustomExceptionType type) : base()
{
this.exceptionType = type;
}
public CustomException(CustomExceptionType type, string message) : base(message)
{
this.exceptionType = type;
}
public CustomException(string message) : base(message)
{
this.exceptionType = CustomExceptionType.InputValidation;
}
//序列化
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
//重写message方法,以让它显示相应异常提示信息
public override string Message
{
get
{
//根据异常类型从message.xml中读取相应异常提示信息
return base.Message;
//return string.Format(XmlMessageManager.GetXmlMessage((int)exceptionType), base.Message);
}
}
}
public enum CustomExceptionType
{
InputValidation = 1,
hint = 2,
Warning = 3,
Unknown = 8
}
}

View File

@@ -0,0 +1,130 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Services.Extensions
{
/// <summary>
/// 枚举扩展
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// 对枚举器的每个元素执行指定的操作
/// </summary>
/// <typeparam name="T">枚举器类型参数</typeparam>
/// <param name="source">枚举器</param>
/// <param name="action">要对枚举器的每个元素执行的委托</param>
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source.IsNullOrEmpty<T>() || action == null)
{
return;
}
foreach (T obj in source)
{
action(obj);
}
}
/// <summary>
/// 指示指定的枚举器是null还是没有任何元素
/// </summary>
/// <typeparam name="T">枚举器类型参数</typeparam>
/// <param name="source">要测试的枚举器</param>
/// <returns>true:枚举器是null或者没有任何元素 false:枚举器不为null并且包含至少一个元素</returns>
public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
return source == null || !source.Any<T>();
}
/// <summary>
/// 得到枚举中文备注
/// </summary>
/// <param name="enumValue"></param>
/// <returns></returns>
public static string GetEnumDesc(this System.Enum enumValue)
{
string value = enumValue.ToString();
System.Reflection.FieldInfo field = enumValue.GetType().GetField(value);
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性
if (objs.Length == 0) //当描述属性没有时,直接返回名称
return value;
DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
return descriptionAttribute.Description;
}
public static string GetEnumDesc(this Type enumType, object val)
{
string enumvalue = Enum.GetName(enumType, val);
if (string.IsNullOrEmpty(enumvalue))
{
return "";
}
FieldInfo finfo = enumType.GetField(enumvalue);
object[] enumAttr = finfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (enumAttr.Length > 0)
{
DescriptionAttribute desc = (DescriptionAttribute)enumAttr[0];
if (desc != null)
{
return desc.Description;
}
}
return enumvalue;
}
/// <summary>
/// 获取所有的枚举描述和值
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static List<EnumDto> GetEnumListItem(this Type type)
{
List<EnumDto> list = new List<EnumDto>();
// 循环枚举获取所有的Fields
foreach (var field in type.GetFields())
{
// 如果是枚举类型
if (field.FieldType.IsEnum)
{
object tmp = field.GetValue(null);
Enum enumValue = (Enum)tmp;
int intValue = Convert.ToInt32(enumValue);
string showName = enumValue.GetEnumDesc(); // 获取描述和排序
list.Add(new EnumDto { Value = intValue, Description = showName });
}
}
//返回
return list;
}
public class EnumDto
{
/// <summary>
/// 枚举code
/// </summary>
public string Code { get; set; }
/// <summary>
/// 值
/// </summary>
public int Value { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
}
}
}

View File

@@ -0,0 +1,469 @@
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq.Expressions;
using System.Reflection;
namespace System.Linq
{
public static class LinqExtensions
{
/// <summary>通过页面控件动态构建查询</summary>
public static IQueryable<TSource> WhereDynamic<TSource>(this IQueryable<TSource> source,
NameValueCollection nameValues) where TSource : class
{
if (nameValues.Count > 0)
{
//构建 c=>Body中的c
ParameterExpression param = Expression.Parameter(typeof(TSource), "c");
//构建c=>Body中的Body
var body = GetExpressoinBody(param, nameValues);
if (body != null)
{
//将二者拼为c=>Body
var expression = Expression.Lambda<Func<TSource, bool>>(body, param);
//传到Where中当做参数类型为Expression<Func<T,bool>>
return source.Where(expression);
}
}
return source;
}
/// <summary>构建body</summary>
private static Expression GetExpressoinBody(ParameterExpression param, NameValueCollection nameValues)
{
var list = new List<Expression>();
if (nameValues.Count > 0)
{
var plist = param.Type.GetRuntimeProperties().ToDictionary(z => z.Name);//可以加缓存改善性能
foreach (var item in nameValues.AllKeys)
if (item.EndsWith(">") || item.EndsWith(">="))//可能大小查询
{
bool isEqual = item.EndsWith(">=");
string key = isEqual ? item.TrimEnd('=').TrimEnd('>') : item.TrimEnd('>');
if (!plist.ContainsKey(key) || nameValues[item].Length <= 0) continue;
var rType = plist[key].GetMethod.ReturnType;
if (rType == typeof(string)) continue;
var e1 = Expression.Property(param, key);
object dValue;
if (TryParser(nameValues[item], rType, out dValue))
//list.Add(Expression.GreaterThan(e1, Expression.Constant(dValue, rType)));
list.Add(AddGreaterGreaterThan(e1, Expression.Constant(dValue, rType), isEqual));
else if (plist[key].GetMethod.ReturnType.GenericTypeArguments.Count() > 0 && TryParser(nameValues[item], plist[key].GetMethod.ReturnType.GenericTypeArguments[0], out dValue))
//list.Add(Expression.GreaterThan(e1, Expression.Constant(dValue, rType)));
list.Add(AddGreaterGreaterThan(e1, Expression.Constant(dValue, rType), isEqual));
else if (rType == typeof(DateTime?))
{
DateTime enddate = nameValues[item].ToDateTime().GetValueOrDefault();
//list.Add(Expression.GreaterThan(e1, Expression.Constant(enddate, typeof(DateTime?))));
list.Add(AddGreaterGreaterThan(e1, Expression.Constant(enddate, typeof(DateTime?)), isEqual));
}
}
else if (item.EndsWith("<") || item.EndsWith("<="))//可能大小查询
{
bool isEqual = item.EndsWith("<=");
string key = isEqual ? item.TrimEnd('=').TrimEnd('<') : item.TrimEnd('<');
if (!plist.ContainsKey(key) || nameValues[item].Length <= 0) continue;
var rType = plist[key].GetMethod.ReturnType;
if (rType == typeof(string)) continue;
var e1 = Expression.Property(param, key);
object dValue;
if (TryParser(nameValues[item], rType, out dValue))
{
if (rType == typeof(DateTime)) dValue = ((DateTime)dValue).AddDays(1);
//list.Add(Expression.LessThan(e1, Expression.Constant(dValue, rType)));
list.Add(AddGreaterLessThan(e1, Expression.Constant(dValue, rType), isEqual));
}
else if (plist[key].GetMethod.ReturnType.GenericTypeArguments.Count() > 0 && TryParser(nameValues[item], plist[key].GetMethod.ReturnType.GenericTypeArguments[0], out dValue))
{
if (plist[key].GetMethod.ReturnType.GenericTypeArguments[0] == typeof(DateTime)) dValue = ((DateTime)dValue).AddDays(1);
//list.Add(Expression.LessThan(e1, Expression.Constant(dValue, rType)));
list.Add(AddGreaterLessThan(e1, Expression.Constant(dValue, rType), isEqual));
}
else if (rType == typeof(DateTime?))
{
DateTime enddate = nameValues[item].ToDateTime().GetValueOrDefault().AddDays(1);
//list.Add(Expression.LessThan(e1, Expression.Constant(enddate, typeof(DateTime?))));
list.Add(AddGreaterLessThan(e1, Expression.Constant(enddate, typeof(DateTime?)), isEqual));
}
}
else if (plist.ContainsKey(item) && nameValues[item].Length > 0)
{
var e1 = Expression.Property(param, item);
var rType = plist[item].GetMethod.ReturnType;
if (rType == typeof(string))//可能是like查询
{
var value = nameValues[item].Trim('%');
var e2 = Expression.Constant(value, rType);
if (nameValues[item].StartsWith("%") && nameValues[item].EndsWith("%"))
list.Add(Expression.Call(e1, "Contains", null, new Expression[] { e2 }));
else if (nameValues[item].StartsWith("%"))
list.Add(Expression.Call(e1, "EndsWith", null, new Expression[] { e2 }));
else if (nameValues[item].EndsWith("%"))
list.Add(Expression.Call(e1, "StartsWith", null, new Expression[] { e2 }));
else
list.Add(Expression.Equal(e1, e2));
}
else if (nameValues[item].IndexOf(",") > 0)//可能是in查询
{
if (rType == typeof(short))
{
var searchList = TryParser<short>(nameValues[item]);
if (searchList.Any())
list.Add(Expression.Call(Expression.Constant(searchList, rType), "Contains", null, new Expression[] { e1 }));
}
else if (rType == typeof(int))
{
var searchList = TryParser<int>(nameValues[item]);
if (searchList.Any())
list.Add(Expression.Call(Expression.Constant(searchList, rType), "Contains", null, new Expression[] { e1 }));
}
else if (rType == typeof(long))
{
var searchList = TryParser<long>(nameValues[item]);
if (searchList.Any())
list.Add(Expression.Call(Expression.Constant(searchList, rType), "Contains", null, new Expression[] { e1 }));
}
}
else
{
object dValue;
if (TryParser(nameValues[item], rType, out dValue))
list.Add(Expression.Equal(e1, Expression.Constant(dValue, rType)));
}
}
}
return list.Count > 0 ? list.Aggregate(Expression.AndAlso) : null;
}
private static List<T> TryParser<T>(string value)
{
string[] searchArray = value.Split(',');
List<T> dList = new List<T>();
foreach (var l in searchArray)
{
try
{
T dValue = (T)Convert.ChangeType(l, typeof(T));
dList.Add(dValue);
}
catch { }
}
return dList;
}
private static bool TryParser(string value, Type outType, out object dValue)
{
try
{
dValue = Convert.ChangeType(value, outType);
return true;
}
catch
{
dValue = null;
return false;
}
}
//大于
private static Expression AddGreaterGreaterThan(Expression exleft, Expression exright, bool Equal)
{
if (Equal)
{
return Expression.GreaterThanOrEqual(exleft, exright);
}
else
{
return Expression.GreaterThan(exleft, exright);
}
}
//大于
private static Expression AddGreaterLessThan(Expression exleft, Expression exright, bool Equal)
{
if (Equal)
{
return Expression.LessThanOrEqual(exleft, exright);
}
else
{
return Expression.LessThan(exleft, exright);
}
}
/// <summary>
/// 从 System.Collections.Generic.IQueryable`1 创建一个 System.Collections.Generic.List`1。并在集合末尾添加一个默认值为空的TSource实例
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">要从其创建 System.Collections.Generic.List`1 的 System.Collections.Generic.IEnumerable`1。</param>
/// <returns>一个包含输入序列中元素的 System.Collections.Generic.List`1。</returns>
public static List<TSource> ToListAndAddEmpty<TSource>(this IQueryable<TSource> source) where TSource : class
{
List<TSource> list = source.ToList();
TSource addmodel = Activator.CreateInstance<TSource>();
list.Add(addmodel);
return list;
}
/// <summary>
/// 从 System.Collections.Generic.IEnumerable`1 创建一个 System.Collections.Generic.List`1。并在集合末尾添加一个默认值为空的TSource实例
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">要从其创建 System.Collections.Generic.List`1 的 System.Collections.Generic.IEnumerable`1。</param>
/// <returns>一个包含输入序列中元素的 System.Collections.Generic.List`1。</returns>
public static List<TSource> ToListAndAddEmpty<TSource>(this IEnumerable<TSource> source) where TSource : class
{
List<TSource> list = source.ToList();
TSource addmodel = Activator.CreateInstance<TSource>();
list.Add(addmodel);
return list;
}
/// <summary>
/// 动态模糊查询
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要模糊查找的值序列。</param>
/// <typeparam name="TKey">由 keySelector 表示的函数返回的键类型。</typeparam>
/// <param name="keyword">查询关键字(动态模糊在首或尾部添加%)</param>
/// <param name="keyfiled">查询字段</param>
/// <param name="keySelector">查询字段Lamvda表达式(支持多表导航查询)</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IQueryable<TSource> LikeQueryable<TSource, TKey>(this IQueryable<TSource> source, string keyword, params Expression<Func<TSource, TKey>>[] keySelector)
{
try
{
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
Expression body = null;
var list = new List<Expression>();
foreach (var item in keySelector)
{
string[] paramKs = item.Body.ToString().Split('.');
var e1 = Expression.Property(paramT, paramKs[1]);//c.user
for (int i = 2; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
if (e1.Type == typeof(string))
{
var value = keyword.Trim('%');
var e2 = Expression.Constant(value, typeof(string));
if (keyword.StartsWith("%") && keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "Contains", null, new Expression[] { e2 }));
else if (keyword.StartsWith("%"))
list.Add(Expression.Call(e1, "EndsWith", null, new Expression[] { e2 }));
else if (keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "StartsWith", null, new Expression[] { e2 }));
else
list.Add(Expression.Equal(e1, e2));
}
}
body = list.Count > 0 ? list.Aggregate(Expression.OrElse) : null;
//构建c=>Body中的Body
if (body != null)
{
//将二者拼为c=>Body
var expression = Expression.Lambda<Func<TSource, bool>>(body, paramT);
//传到Where中当做参数类型为Expression<Func<T,bool>>
source = source.Where(expression);
}
}
catch
{
}
return source;
}
/// <summary>
/// 动态模糊查询
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要模糊查找的值序列。</param>
/// <param name="keyword">查询关键字(动态模糊在首或尾部添加%)</param>
/// <param name="keyfiled">查询字段</param>
/// <param name="keySelector">查询字段Lamvda表达式(支持多表导航查询)</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IQueryable<TSource> LikeQueryable<TSource>(this IQueryable<TSource> source, string keyword, params string[] keyfiled)
{
try
{
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
Expression body = null;
var list = new List<Expression>();
foreach (var item in keyfiled)
{
string[] paramKs = item.Split('.');
var e1 = Expression.Property(paramT, paramKs[0]);//c.user
for (int i = 1; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
if (e1.Type == typeof(string))
{
var value = keyword.Trim('%');
var e2 = Expression.Constant(value, typeof(string));
if (keyword.StartsWith("%") && keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "Contains", null, new Expression[] { e2 }));
else if (keyword.StartsWith("%"))
list.Add(Expression.Call(e1, "EndsWith", null, new Expression[] { e2 }));
else if (keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "StartsWith", null, new Expression[] { e2 }));
else
list.Add(Expression.Equal(e1, e2));
}
}
body = list.Count > 0 ? list.Aggregate(Expression.OrElse) : null;
//构建c=>Body中的Body
if (body != null)
{
//将二者拼为c=>Body
var expression = Expression.Lambda<Func<TSource, bool>>(body, paramT);
//传到Where中当做参数类型为Expression<Func<T,bool>>
source = source.Where(expression);
}
}
catch
{
}
return source;
}
/// <summary>
/// 外键表动态模糊查询
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要模糊查找的值序列。</param>
/// <typeparam name="TKey">由 keySelector 表示的函数返回的键类型。</typeparam>
/// <param name="keyword">查询关键字(动态模糊在首或尾部添加%)</param>
/// <param name="keyfiledn">查询字段</param>
/// <param name="keySelector">查询字段Lamvda表达式(支持多表导航查询)</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IQueryable<TSource> LikeQueryable<TSource, TKey>(this IQueryable<TSource> source, string keyword, string keyfiled, params Expression<Func<TSource, TKey>>[] keySelector)
{
try
{
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
Expression body = null;
var list = new List<Expression>();
foreach (var item in keySelector)
{
string[] paramKs = item.Body.ToString().Split('.');
var e1 = Expression.Property(paramT, paramKs[1]);//c.user
for (int i = 2; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
e1 = Expression.Property(e1, keyfiled);//c.user.ID
if (e1.Type == typeof(string))
{
var value = keyword.Trim('%');
var e2 = Expression.Constant(value, typeof(string));
if (keyword.StartsWith("%") && keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "Contains", null, new Expression[] { e2 }));
else if (keyword.StartsWith("%"))
list.Add(Expression.Call(e1, "EndsWith", null, new Expression[] { e2 }));
else if (keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "StartsWith", null, new Expression[] { e2 }));
else
list.Add(Expression.Equal(e1, e2));
}
}
body = list.Count > 0 ? list.Aggregate(Expression.OrElse) : null;
//构建c=>Body中的Body
if (body != null)
{
//将二者拼为c=>Body
var expression = Expression.Lambda<Func<TSource, bool>>(body, paramT);
//传到Where中当做参数类型为Expression<Func<T,bool>>
source = source.Where(expression);
}
}
catch
{
}
return source;
}
/// <summary>
/// 动态排序
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要排序查找的值序列。</param>
/// <param name="keyfiled">排序字段</param>
/// <param name="type">排序类型0不排序1升序2降序</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IQueryable<TSource> OrderByQueryable<TSource>(this IQueryable<TSource> source, string keyfiled, int type)
{
try
{
if (type == 0) return source;//不排序
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
string[] paramKs = keyfiled.Split('.');
var e1 = Expression.Property(paramT, paramKs[0]);//c.user
for (int i = 1; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
dynamic expression = Expression.Lambda(e1, paramT);
switch (type)
{
case 1:
source = Queryable.OrderBy(source, expression);
break;
case 2:
source = Queryable.OrderByDescending(source, expression);
break;
default:
break;
}
}
catch
{
}
return source;
}
/// <summary>
/// 动态排序
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要排序查找的值序列。</param>
/// <param name="keyfiled">排序字段</param>
/// <param name="type">排序类型0不排序1升序2降序</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IEnumerable<TSource> OrderByQueryable<TSource>(this IEnumerable<TSource> source, string keyfiled, int type)
{
try
{
if (type == 0) return source;//不排序
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
string[] paramKs = keyfiled.Split('.');
var e1 = Expression.Property(paramT, paramKs[0]);//c.user
for (int i = 1; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
dynamic expression = Expression.Lambda(e1, paramT);
switch (type)
{
case 1:
source = Queryable.OrderBy(source.AsQueryable(), expression);
break;
case 2:
source = Queryable.OrderByDescending(source.AsQueryable(), expression);
break;
default:
break;
}
}
catch
{
}
return source;
}
}
}

View File

@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Services.Extensions
{
/// <summary>
/// 对象扩展
/// </summary>
public static class ModelExtensions
{
/// <summary>
/// 创建一个新的类型的对象,并将现有对象的属性值赋给新对象相同名称的属性
/// </summary>
/// <typeparam name="T">新对象的类型</typeparam>
/// <param name="source">现有对象</param>
/// <returns>新的对象</returns>
public static T ToModel<T>(this object source) where T : new()
{
if (source == null)
{
return default(T);
}
return Activator.CreateInstance<T>().UpdateFrom(source, new string[0]);
}
/// <summary>
/// 将源对象的属性值赋给目标对象相同名称的属性
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <param name="target">目标对象</param>
/// <param name="source">源对象</param>
/// <param name="copyPropertyName">需要复制的属性名,为空时表示复制全部</param>
/// <returns>目标类型</returns>
public static T UpdateFrom<T>(this T target, object source, params string[] copyPropertyName)
{
if (target == null)
{
return default(T);
}
if (source == null)
{
return target;
}
Type typeFromHandle = typeof(T);
foreach (PropertyInfo obj in source.GetType().GetProperties())
{
//PropertyDescriptor propertyDescriptor = (PropertyDescriptor)obj;
if (copyPropertyName == null || copyPropertyName.Length == 0 || copyPropertyName.Contains(obj.Name))
{
PropertyInfo property = typeFromHandle.GetProperty(obj.Name, BindingFlags.Instance | BindingFlags.Public);
if (property != null && property.CanWrite)
{
property.SetValue(target, obj.GetValue(source, null), null);
}
}
}
return target;
}
}
}

View File

@@ -0,0 +1,132 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System
{
/// <summary>
/// 字符串转换扩展
/// </summary>
public static class SafeInputExtensions
{
/// <summary>
/// 将字符串转换成Int类型如果出错则返回0
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static short ToShort(this object str)
{
short result = 0;
if (str != null)
{
short.TryParse(str.ToString(), out result);
}
return result;
}
/// <summary>
/// 将字符串转换成Int类型如果出错则返回0
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static int ToInt(this object str)
{
int result = 0;
if (str != null)
{
int.TryParse(str.ToString(), out result);
}
return result;
}
/// <summary>
/// 将字符串转换成decimal类型如果出错则返回0
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static double ToDouble(this object str)
{
double result = 0.0;
if (str != null)
{
double.TryParse(str.ToString(), out result);
}
return result;
}
public static decimal ToDecimal(this object str)
{
decimal result = 0m;
if (str != null)
{
decimal.TryParse(str.ToString(), out result);
}
return result;
}
public static string ToNone(this object str, string extStr)
{
if (str != null && !string.IsNullOrEmpty(str.ToString()))
{
return str + " " + extStr;
}
return "";
}
/// <summary>
/// 将字符串转换成真假
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool ToBool(this object str)
{
return str != null && str.ToString().Equals("true", StringComparison.CurrentCultureIgnoreCase);
}
/// <summary>
/// 将字符串转换成GUID出错则为Guid.NewGuid()
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static Guid ToGuid(this object str)
{
Guid result = Guid.NewGuid();
if (str != null)
{
Guid.TryParse(str.ToString(), out result);
}
return result;
}
public static DateTime ToDateTime(this object str)
{
DateTime now = DateTime.Now;
if (str != null)
{
DateTime.TryParse(str.ToString(), out now);
}
return now;
}
public static string ToDateTimeRandom()
{
return DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(9999).ToString();
}
public static string ToDateString()
{
return DateTime.Now.ToString("yyyyMMdd");
}
public static string ToBr(this string str)
{
if (!string.IsNullOrEmpty(str))
{
return str.Replace("\r\n", "<br>");
}
return str;
}
}
}

View File

@@ -0,0 +1,402 @@
using Services.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Drawing.Imaging;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Services.Extensions
{
/// <summary>
/// 字符串扩展函数工具类
/// </summary>
public static class StringExtensions
{
/// <summary>
/// 将\r\n替换成BR
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ToSafeBR(this string str)
{
if (!string.IsNullOrEmpty(str))
{
return str.Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>");
}
return str;
}
/// <summary>
/// 得到父部门的ID
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GetDepartmentFatherID(this string str)
{
if (!string.IsNullOrEmpty(str) && str.Length > 2)
{
str = str.Substring(0, str.Length - 3);
}
return str;
}
/// <summary>
/// 截取字符串,超过部分用...代替
/// </summary>
/// <param name="source"></param>
/// <param name="len"></param>
/// <returns></returns>
public static string Substr(this string source, int len)
{
return source.Substr(len, "...");
}
/// <summary>
/// 截取字符串,超过部分用自定义代替
/// </summary>
/// <param name="source"></param>
/// <param name="len"></param>
/// <param name="att"></param>
/// <returns></returns>
public static string Substr(this string source, int len, string att)
{
if (string.IsNullOrEmpty(source))
{
return string.Empty;
}
att = (att ?? string.Empty);
Regex regex = new Regex("[\\u4e00-\\u9fa5]");
Regex regex2 = new Regex("^[A-Za-z0-9]+$");
if (regex.IsMatch(source))
{
if (source.Length <= len)
{
return source;
}
return source.Substring(0, len) + att;
}
else if (regex2.IsMatch(source))
{
if (source.Length <= len * 2)
{
return source;
}
return source.Substring(0, len * 2) + att;
}
else
{
if (source.Length <= len)
{
return source;
}
return source.Substring(0, len) + att;
}
}
public static string InputStr(this string source)
{
if (!string.IsNullOrEmpty(source))
{
Regex regex = new Regex("[\\u4e00-\\u9fa5]");
Regex regex2 = new Regex("^[A-Za-z0-9]+$");
if (regex.IsMatch(source))
{
if (source.Length < 3)
{
return string.Format("{0}**", source[0]);
}
if (source.Length == 3)
{
return string.Format("{0}*{1}", source[0], source[source.Length - 1]);
}
if (source.Length > 3)
{
return string.Format("{0}**{1}", source[0], source[source.Length - 1]);
}
}
else
{
if (!regex2.IsMatch(source))
{
return string.Format("{0}**", source.Substring(0, 2));
}
if (source.Length < 6)
{
return string.Format("{0}**", source.Substring(0, 2));
}
return string.Format("{0}****{1}", source.Substring(0, 2), source.Substring(source.Length - 3, 2));
}
}
return string.Empty;
}
/// <summary>
/// 移除掉所有的Html代码
/// </summary>
/// <param name="strHtml"></param>
/// <returns></returns>
public static string RemoveHtml(this string strHtml)
{
Regex regex = new Regex("<.+?>", RegexOptions.IgnoreCase);
strHtml = regex.Replace(strHtml, "");
strHtml = strHtml.Replace("&nbsp;", "");
return strHtml;
}
/// <summary>
/// 生成0-9随机数
/// </summary>
/// <param name="VcodeNum">生成长度</param>
/// <returns></returns>
public static string RndNum(int VcodeNum)
{
StringBuilder stringBuilder = new StringBuilder(VcodeNum);
Random random = new Random();
for (int i = 1; i < VcodeNum + 1; i++)
{
int num = random.Next(9);
stringBuilder.AppendFormat("{0}", num);
}
return stringBuilder.ToString();
}
/// <summary>
/// 返回星号的加密
/// </summary>
/// <param name="items"></param>
/// <param name="mask"></param>
/// <returns></returns>
public static string MaskStar(Dictionary<string, string> items, bool mask)
{
StringBuilder stringBuilder = new StringBuilder();
if (mask)
{
foreach (KeyValuePair<string, string> keyValuePair in items)
{
stringBuilder.Append(string.Concat(new string[]
{
"$('#",
keyValuePair.Key,
"').attr('name', '",
keyValuePair.Key,
"mask');"
}));
}
stringBuilder.Append("$('.maskstar').attr('disabled', true);");
stringBuilder.Append("$('.maskstar').val('***');");
}
else
{
foreach (KeyValuePair<string, string> keyValuePair2 in items)
{
stringBuilder.Append(string.Concat(new string[]
{
"$('#",
keyValuePair2.Key,
"').attr('name', '",
keyValuePair2.Key,
"');"
}));
stringBuilder.Append(string.Concat(new string[]
{
"$('#",
keyValuePair2.Key,
"').val('",
keyValuePair2.Value,
"');"
}));
}
stringBuilder.Append("$('.maskstar').attr('disabled', false);");
}
return stringBuilder.ToString();
}
/// <summary>
/// 给自动填充使用
/// </summary>
/// <param name="str1"></param>
/// <param name="str2"></param>
/// <returns></returns>
public static string ToAutoComplate(this string str1, string str2)
{
if (!string.IsNullOrEmpty(str1) && !string.IsNullOrEmpty(str2))
{
return str1 + "," + str2;
}
return "";
}
/// <summary>
/// 返回红色字体
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ToRedColor(this int value)
{
if (value != 0)
{
return "<font color='red'>" + value.ToString() + "</font>";
}
return value.ToString();
}
/// <summary>
/// 返回安全的字符串类型如果为NULL则返回空
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ToSafeString(this object value)
{
if (value == null)
{
return "";
}
return value.ToString();
}
/// <summary>
/// 将中文转换成Unicode编码主要用在URL传递中文
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GB2Unicode(this string str)
{
string text = "";
Encoding encoding = Encoding.GetEncoding("GB2312");
Encoding unicode = Encoding.Unicode;
byte[] bytes = encoding.GetBytes(str);
for (int i = 0; i < bytes.Length; i++)
{
string str2 = "%" + bytes[i].ToString("x");
text += str2;
}
return text;
}
/// <summary>
/// 将字符串转换成为大写的MD5
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ToMD5(this string str)
{
MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider();
byte[] array = md5CryptoServiceProvider.ComputeHash(Encoding.Default.GetBytes(str));
StringBuilder stringBuilder = new StringBuilder();
foreach (byte b in array)
{
stringBuilder.Append(b.ToString("x2"));
}
return stringBuilder.ToString().ToUpper();
}
/// <summary>
/// 字节码长度转可读字符串 00000000 bytes 0.0GB
/// </summary>
/// <param name="KSize"></param>
/// <returns></returns>
public static string ByteSizeToString(this long KSize)
{
if (KSize > 0L)
{
string[] array = new string[]
{
"B",
"KB",
"MB",
"GB",
"TB"
};
double num = 0.0;
int num2 = array.Length - 1;
while (num2 >= 0 && (num = Math.Round((double)KSize / Math.Pow(1024.0, (double)num2), 2)) < 1.0)
{
num2--;
}
return string.Format("{0}{1}", num, array[num2]);
}
return string.Empty;
}
/// <summary>
/// 将图片的字节码数组转成 base64 字符串
/// </summary>
/// <param name="img"></param>
/// <param name="format"></param>
/// <returns></returns>
public static string GetImgBase64String(this byte[] img, ImageFormat format)
{
return string.Format("data:image/{0};base64,{1}", format.ToString(), Convert.ToBase64String(img));
}
/// <summary>
/// 将字符串转换成为大写的MD5
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static string GetMD5Code(this string str)
{
StringBuilder stringBuilder = new StringBuilder();
using (MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider())
{
byte[] array = md5CryptoServiceProvider.ComputeHash(Encoding.Default.GetBytes(str));
foreach (byte b in array)
{
stringBuilder.Append(b.ToString("x2"));
}
}
return stringBuilder.ToString();
}
/// <summary>
/// 转码成短字符串
/// </summary>
/// <param name="str">源字符串</param>
/// <param name="version">制码版本</param>
/// <returns>短码数组</returns>
public static string[] EncodeShortString(this string str, ShortStringVersion version)
{
string text = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int length = text.Length;
string md5Code = str.GetMD5Code();
string[] array = new string[4];
FieldInfo field = typeof(ShortStringVersion).GetField(version.ToString());
MaxLengthAttribute maxLengthAttribute = ((MaxLengthAttribute[])field.GetCustomAttributes(typeof(MaxLengthAttribute), false))[0];
int num = 0;
while (num < 4 && text.Length > 0)
{
int i = 1073741823 & Convert.ToInt32("0x" + md5Code.Substring(num * 8, 8), 16);
string text2 = string.Empty;
int index = 61 & i;
while (i > 0)
{
text2 += text[index];
i >>= (int)version;
index = (61 & i);
}
while (text2.Length < maxLengthAttribute.Length)
{
text2 += text[num];
}
array[num] = text2;
num++;
}
return array;
}
/// <summary>
/// 转码成短字符串
/// </summary>
/// <param name="str">源字符串</param>
/// <returns>短码数组</returns>
public static string[] EncodeShortString(this string str)
{
return str.EncodeShortString(ShortStringVersion.Version_1);
}
}
}

View File

@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System
{
public static class TimeExtensions
{
public static DateTime? ToDateTime(this string timeStamp)
{
long ticks = 0L;
if (long.TryParse(timeStamp, out ticks))
{
DateTime dateTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
TimeSpan value = new TimeSpan(ticks);
return new DateTime?(dateTime.Add(value));
}
DateTime now = DateTime.Now;
if (DateTime.TryParse(timeStamp, out now))
{
return new DateTime?(now);
}
return null;
}
}
}