添加项目文件。
This commit is contained in:
1 parent
05e131ca4e
commit
514d6f5255
1162 files changed
+81255
No files matched your search
@@ -0,0 +1,81 @@
|
||||
using System;
|
||||
|
||||
namespace WalkingTec.Mvvm.Core.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// DateTime Helper
|
||||
/// </summary>
|
||||
public static class DateTimeHelper
|
||||
{
|
||||
#region DateTime Helper
|
||||
|
||||
public static int WeekOfYear(this DateTime self)
|
||||
{
|
||||
var startDayOfYear = new DateTime(self.Year,1,1);
|
||||
var weekOffset = 7 - ( startDayOfYear.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)startDayOfYear.DayOfWeek) + 1;
|
||||
var weekOfYear = (int)Math.Ceiling((self.DayOfYear - weekOffset) / 7.0 + (weekOffset == 0 ? 0 : 1));
|
||||
|
||||
return weekOfYear;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 指定的一周所在年份 的开始及结束时间
|
||||
/// </summary>
|
||||
/// <param name="yearNum">所在年份</param>
|
||||
/// <param name="weekOfYear">周数</param>
|
||||
/// <param name="startDay">指定周开始时间</param>
|
||||
/// <param name="endDay">指定周结束时间</param>
|
||||
public static void WeekDays(int yearNum, int weekOfYear, out DateTime startDay, out DateTime endDay)
|
||||
{
|
||||
var startDayOfYear = new DateTime(yearNum,1,1,0,0,0);
|
||||
|
||||
var weekOffset = 7 - ( startDayOfYear.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)startDayOfYear.DayOfWeek) + 1;
|
||||
startDay = startDayOfYear.AddDays(7 * (weekOfYear - (weekOffset == 0 ? 0 : 1)) + weekOffset - 7);
|
||||
endDay = startDay.AddDays(7);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region DateTime Extensions
|
||||
|
||||
private static readonly DateTime _jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0,DateTimeKind.Utc);
|
||||
|
||||
/// <summary>
|
||||
/// UTC 1970/01/01 00:00:00
|
||||
/// </summary>
|
||||
public static DateTime Jan1st1970 => _jan1st1970;
|
||||
|
||||
/// <summary>
|
||||
/// 时间戳 ms
|
||||
/// </summary>
|
||||
/// <param name="self"></param>
|
||||
/// <returns>返回标准时间戳 单位 毫秒 注:从 1970/01/01 00:00:00 开始</returns>
|
||||
public static long ToMilliseconds(this DateTime self)
|
||||
{
|
||||
return (long)(self.ToUniversalTime() - Jan1st1970).TotalMilliseconds;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 时间戳 microsecond
|
||||
/// </summary>
|
||||
/// <param name="self"></param>
|
||||
/// <returns>返回标准时间戳 单位 微秒 注:从 1970/01/01 00:00:00 开始</returns>
|
||||
public static long ToMicroseconds(this DateTime self)
|
||||
{
|
||||
return (long)((self.ToUniversalTime() - Jan1st1970).TotalMilliseconds * 1000);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前时间所在周的开始及结束时间
|
||||
/// </summary>
|
||||
/// <param name="self"></param>
|
||||
/// <param name="startDay">指定周开始时间</param>
|
||||
/// <param name="endDay">指定周结束时间</param>
|
||||
public static void WeekDays(this DateTime self, out DateTime startDay, out DateTime endDay)
|
||||
{
|
||||
WeekDays(self.Year, self.WeekOfYear(), out startDay, out endDay);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
//
|
||||
// DistributedCacheExtensions.cs
|
||||
//
|
||||
// Author:
|
||||
// Michael,Vito
|
||||
//
|
||||
// Copyright (c) 2019 WTM
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using Microsoft.Extensions.Caching.Distributed;
|
||||
|
||||
|
||||
namespace WalkingTec.Mvvm.Core.Extensions
|
||||
{
|
||||
public static class DistributedCacheExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// CachingKey 分割符
|
||||
/// </summary>
|
||||
private const string SPLIT_CHAR = ":";
|
||||
|
||||
private static string _instanceName;
|
||||
private static string InstanceName
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_instanceName == null)
|
||||
{
|
||||
_instanceName = Assembly.GetEntryAssembly().GetName().Name + SPLIT_CHAR;
|
||||
}
|
||||
return _instanceName;
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetInstanceName(
|
||||
this IDistributedCache cache,
|
||||
string instanceName)
|
||||
{
|
||||
_instanceName = instanceName + SPLIT_CHAR;
|
||||
}
|
||||
|
||||
#region Get
|
||||
|
||||
public static T Get<T>(
|
||||
this IDistributedCache cache,
|
||||
string key)
|
||||
{
|
||||
var value = cache.GetString(InstanceName + key.ToLower());
|
||||
if (value == null)
|
||||
return default;
|
||||
else
|
||||
return JsonSerializer.Deserialize<T>(value,Core.CoreProgram.DefaultJsonOption);
|
||||
}
|
||||
|
||||
public static async Task<T> GetAsync<T>(
|
||||
this IDistributedCache cache,
|
||||
string key,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var value = await cache.GetStringAsync(InstanceName + key.ToLower(), token);
|
||||
if (value == null)
|
||||
return default;
|
||||
else
|
||||
return JsonSerializer.Deserialize<T>(value, Core.CoreProgram.DefaultJsonOption);
|
||||
}
|
||||
|
||||
public static bool TryGetValue<T>(
|
||||
this IDistributedCache cache,
|
||||
string key,
|
||||
out T outValue)
|
||||
{
|
||||
var value = cache.GetString(InstanceName + key.ToLower());
|
||||
if (value == null)
|
||||
{
|
||||
outValue = default;
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
outValue = JsonSerializer.Deserialize<T>(value, Core.CoreProgram.DefaultJsonOption);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Set
|
||||
|
||||
public static void Add<T>(
|
||||
this IDistributedCache cache,
|
||||
string key,
|
||||
T value,
|
||||
DistributedCacheEntryOptions options = null)
|
||||
{
|
||||
if(options == null && typeof(T) == typeof(LoginUserInfo) ){
|
||||
options = new DistributedCacheEntryOptions()
|
||||
{
|
||||
AbsoluteExpirationRelativeToNow = new System.TimeSpan(7, 0, 0, 0)
|
||||
};
|
||||
}
|
||||
if (options == null)
|
||||
cache.Set(InstanceName + key.ToLower(), Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value, CoreProgram.DefaultJsonOption)));
|
||||
else
|
||||
cache.Set(InstanceName + key.ToLower(), Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value, CoreProgram.DefaultJsonOption)), options);
|
||||
}
|
||||
|
||||
public static async Task AddAsync<T>(
|
||||
this IDistributedCache cache,
|
||||
string key,
|
||||
T value,
|
||||
DistributedCacheEntryOptions options = null,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
if (options == null)
|
||||
await cache.SetAsync(InstanceName + key.ToLower(), Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value, CoreProgram.DefaultJsonOption)), token);
|
||||
else
|
||||
await cache.SetAsync(InstanceName + key.ToLower(), Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value, CoreProgram.DefaultJsonOption)), options, token);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
#region Delete
|
||||
|
||||
public static void Delete(
|
||||
this IDistributedCache cache,
|
||||
string key)
|
||||
{
|
||||
cache.Remove(InstanceName + key.ToLower());
|
||||
}
|
||||
|
||||
public static async Task DeleteAsync(
|
||||
this IDistributedCache cache,
|
||||
string key,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
await cache.RemoveAsync(InstanceName + key.ToLower(), token);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace WalkingTec.Mvvm.Core.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 枚举扩展函数
|
||||
/// </summary>
|
||||
public static class EnumExtension
|
||||
{
|
||||
#region 将枚举类型转化为下拉列表
|
||||
/// <summary>
|
||||
/// 将枚举类型转化为下拉列表
|
||||
/// </summary>
|
||||
/// <param name="self">枚举类型</param>
|
||||
/// <param name="value">value</param>
|
||||
/// <param name="pleaseSelect">pleaseSelect</param>
|
||||
/// <returns>下拉菜单数据列表</returns>
|
||||
public static List<ComboSelectListItem> ToListItems(this Type self, object value = null, bool pleaseSelect = false)
|
||||
{
|
||||
string[] names = null;
|
||||
Array values = null;
|
||||
//如果是枚举
|
||||
if (self.IsEnum)
|
||||
{
|
||||
names = Enum.GetNames(self);
|
||||
values = Enum.GetValues(self);
|
||||
}
|
||||
//如果是nullable的枚举
|
||||
if (self.IsGenericType && self.GenericTypeArguments[0].IsEnum)
|
||||
{
|
||||
names = Enum.GetNames(self.GenericTypeArguments[0]);
|
||||
values = Enum.GetValues(self.GenericTypeArguments[0]);
|
||||
}
|
||||
//生成下拉菜单数据
|
||||
List<ComboSelectListItem> rv = new List<ComboSelectListItem>();
|
||||
if (names != null)
|
||||
{
|
||||
for(int i=0;i<names.Length;i++)
|
||||
{
|
||||
var name = names[i];
|
||||
var newitem = new ComboSelectListItem { Text = PropertyHelper.GetEnumDisplayName(self, name), Value = values.GetValue(i).ToString() };
|
||||
if(value is string)
|
||||
{
|
||||
if (value != null)
|
||||
{
|
||||
string v = value.ToString();
|
||||
var vs = v.Split(',');
|
||||
foreach (var item in vs)
|
||||
{
|
||||
if (item != null && (newitem.Value.ToString() == item.ToString())||name == item.ToString())
|
||||
{
|
||||
newitem.Selected = true;
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (value is IEnumerable it)
|
||||
{
|
||||
foreach (var item in it)
|
||||
{
|
||||
if (item != null && name == item.ToString())
|
||||
{
|
||||
newitem.Selected = true;
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (value != null && name == value.ToString())
|
||||
{
|
||||
newitem.Selected = true;
|
||||
}
|
||||
}
|
||||
rv.Add(newitem);
|
||||
}
|
||||
}
|
||||
if (pleaseSelect == true)
|
||||
{
|
||||
rv.Insert(0, new ComboSelectListItem { Text = CoreProgram._localizer?["Sys.PleaseSelect"], Value = "" });
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace WalkingTec.Mvvm.Core.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 字符串辅助类
|
||||
/// </summary>
|
||||
public static class StringExtension
|
||||
{
|
||||
/// <summary>
|
||||
/// 根据名字获取Id形式
|
||||
/// </summary>
|
||||
/// <param name="fieldName">名字</param>
|
||||
/// <returns>将[].转换成_形式的Id</returns>
|
||||
public static string GetIdByName(this string fieldName)
|
||||
{
|
||||
return fieldName == null ? "" : fieldName.Replace(".", "_").Replace("[", "_").Replace("]", "_");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 格式化URL
|
||||
/// </summary>
|
||||
/// <param name="url">初始url</param>
|
||||
/// <returns>格式化后的url</returns>
|
||||
public static string CorrectUrl(this string url)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url) == true)
|
||||
{
|
||||
url = "";
|
||||
}
|
||||
else
|
||||
{
|
||||
url = url.ToLower();
|
||||
url = url.Trim('/', '\\');
|
||||
if (url.StartsWith("http://") == false && url.StartsWith("https://") == false)
|
||||
{
|
||||
url = "http://" + url;
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
/// <summary>
|
||||
/// 将数据列表转化为逗号分隔的字符串
|
||||
/// </summary>
|
||||
/// <typeparam name="T">源数据类</typeparam>
|
||||
/// <typeparam name="V">文本字段</typeparam>
|
||||
/// <param name="self">源数据List</param>
|
||||
/// <param name="textField">要拼接的文本字段</param>
|
||||
/// <param name="Format">转化文本字段的表达式</param>
|
||||
/// <param name="seperator">分隔符,默认为逗号</param>
|
||||
/// <returns>转化后的字符串</returns>
|
||||
public static string ToSepratedString<T, V>(this IEnumerable<T> self, Expression<Func<T, V>> textField, Func<V, string> Format = null, string seperator = ",")
|
||||
{
|
||||
string rv = "";
|
||||
if (self == null)
|
||||
{
|
||||
return rv;
|
||||
}
|
||||
//循环所有数据
|
||||
for (int i = 0; i < self.Count(); i++)
|
||||
{
|
||||
//获取文本字段的值
|
||||
V text = textField.Compile().Invoke(self.ElementAt(i));
|
||||
string str = "";
|
||||
//如果有转换函数,则调用获取转换后的字符串
|
||||
if (Format == null)
|
||||
{
|
||||
if (text == null)
|
||||
{
|
||||
str = "";
|
||||
}
|
||||
else
|
||||
{
|
||||
str = text.ToString();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
str = Format.Invoke(text);
|
||||
}
|
||||
rv += str;
|
||||
//拼接分隔符
|
||||
if (i < self.Count() - 1)
|
||||
{
|
||||
rv += seperator;
|
||||
}
|
||||
}
|
||||
//返回转化后的字符串
|
||||
return rv;
|
||||
}
|
||||
|
||||
public static string ToSepratedString(this IEnumerable self, Func<object, string> Format = null, string seperator = ",")
|
||||
{
|
||||
string rv = "";
|
||||
if (self == null)
|
||||
{
|
||||
return rv;
|
||||
}
|
||||
foreach (var item in self)
|
||||
{
|
||||
var s = "";
|
||||
if (Format == null)
|
||||
{
|
||||
s = item?.ToString()??"";
|
||||
}
|
||||
else
|
||||
{
|
||||
s = Format.Invoke(item);
|
||||
}
|
||||
if(string.IsNullOrEmpty(s) == false)
|
||||
{
|
||||
rv += s + seperator;
|
||||
}
|
||||
}
|
||||
if (rv.Length > 0)
|
||||
{
|
||||
rv = rv.Substring(0, rv.Length - 1);
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
public static string ToSepratedString(this NameValueCollection self, string seperator = ",")
|
||||
{
|
||||
string rv = "";
|
||||
if (self == null)
|
||||
{
|
||||
return rv;
|
||||
}
|
||||
foreach (var item in self)
|
||||
{
|
||||
rv += item.ToString() + "=" + self[item.ToString()] + seperator;
|
||||
}
|
||||
if (rv.Length > 0)
|
||||
{
|
||||
rv = rv.Substring(0, rv.Length - 1);
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
public static string AppendQuery(this string self,string query)
|
||||
{
|
||||
if(self == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (self.Contains("?"))
|
||||
{
|
||||
self += "&" + query;
|
||||
}
|
||||
else
|
||||
{
|
||||
self += "?" + query;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
public static string AppendQuery(this string self, IDictionary data)
|
||||
{
|
||||
if (self == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
string query = "";
|
||||
foreach (IDictionaryEnumerator item in data)
|
||||
{
|
||||
query += item.Key + "=" + item.Value + "&";
|
||||
}
|
||||
|
||||
if (self.Contains("?"))
|
||||
{
|
||||
self += "&" + query;
|
||||
}
|
||||
else
|
||||
{
|
||||
self += "?" + query;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
public static string AppendQuery(this string self, List<KeyValuePair<string, string>> data)
|
||||
{
|
||||
if (self == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
string query = "";
|
||||
foreach (var item in data)
|
||||
{
|
||||
query += item.Key + "=" + item.Value + "&";
|
||||
}
|
||||
|
||||
if (self.Contains("?"))
|
||||
{
|
||||
self += "&" + query;
|
||||
}
|
||||
else
|
||||
{
|
||||
self += "?" + query;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
public static string ToQueryString(this IEnumerable self, string name=null)
|
||||
{
|
||||
if(self == null)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
if (string.IsNullOrEmpty(name))
|
||||
{
|
||||
name = "id";
|
||||
}
|
||||
string rv = "";
|
||||
foreach (var item in self)
|
||||
{
|
||||
rv += $"{name}={item?.ToString()}&";
|
||||
}
|
||||
if(rv.Length > 0)
|
||||
{
|
||||
rv = rv[0..^1];
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
public static string RemoveSpecialChar(this string self)
|
||||
{
|
||||
if(self == null)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
return self.Replace(Environment.NewLine, "").Replace("\t", string.Empty).Replace("\n", string.Empty).Replace("\r", string.Empty).Replace("\v", string.Empty).Replace("\b", string.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
namespace WalkingTec.Mvvm.Core.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// System Extension
|
||||
/// </summary>
|
||||
public static class SystemExtension
|
||||
{
|
||||
#region Guid Extensions
|
||||
|
||||
public static string ToNoSplitString(this Guid self)
|
||||
{
|
||||
return self.ToString().Replace("-", string.Empty);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 将CrudVM中Entity的关联字段设为空并返回一个新的CrudVM
|
||||
/// </summary>
|
||||
/// <param name="self"></param>
|
||||
/// <returns></returns>
|
||||
public static object GetCleanCrudVM(this object self)
|
||||
{
|
||||
var mtype = self.GetType();
|
||||
if(typeof(IBaseCRUDVM<TopBasePoco>).IsAssignableFrom(mtype))
|
||||
{
|
||||
var rv = mtype.GetConstructor(Type.EmptyTypes).Invoke(null);
|
||||
var toppros = mtype.GetAllProperties();
|
||||
foreach (var tpro in toppros)
|
||||
{
|
||||
if(tpro.Name == "Entity")
|
||||
{
|
||||
var entity = tpro.GetValue(self);
|
||||
var pros = tpro.PropertyType.GetAllProperties();
|
||||
var newEntity = tpro.PropertyType.GetConstructor(Type.EmptyTypes).Invoke(null);
|
||||
bool isBasePoco = typeof(IBasePoco).IsAssignableFrom(tpro.PropertyType);
|
||||
//将所有TopBasePoco的属性赋空值,防止添加关联的重复内容
|
||||
foreach (var pro in pros)
|
||||
{
|
||||
if (pro.PropertyType.GetTypeInfo().IsSubclassOf(typeof(TopBasePoco)) == false)
|
||||
{
|
||||
if (isBasePoco == false || (pro.Name != "UpdateTime" && pro.Name != "UpdateBy"))
|
||||
{
|
||||
pro.SetValue(newEntity, pro.GetValue(entity));
|
||||
}
|
||||
}
|
||||
}
|
||||
tpro.SetValue(rv, newEntity);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (tpro.CanWrite)
|
||||
{
|
||||
tpro.SetValue(rv, tpro.GetValue(self));
|
||||
}
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using Fare;
|
||||
|
||||
namespace WalkingTec.Mvvm.Core.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Type的扩展函数
|
||||
/// </summary>
|
||||
public static class TypeExtension
|
||||
{
|
||||
public static ImmutableDictionary<string, List<PropertyInfo>> _propertyCache { get; set; } = new Dictionary<string, List<PropertyInfo>>().ToImmutableDictionary();
|
||||
/// <summary>
|
||||
/// 判断是否是泛型
|
||||
/// </summary>
|
||||
/// <param name="self">Type类</param>
|
||||
/// <param name="innerType">泛型类型</param>
|
||||
/// <returns>判断结果</returns>
|
||||
public static bool IsGeneric(this Type self, Type innerType)
|
||||
{
|
||||
if (self.GetTypeInfo().IsGenericType && self.GetGenericTypeDefinition() == innerType)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断是否为Nullable<>类型
|
||||
/// </summary>
|
||||
/// <param name="self">Type类</param>
|
||||
/// <returns>判断结果</returns>
|
||||
public static bool IsNullable(this Type self)
|
||||
{
|
||||
return self.IsGeneric(typeof(Nullable<>));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断是否为List<>类型
|
||||
/// </summary>
|
||||
/// <param name="self">Type类</param>
|
||||
/// <returns>判断结果</returns>
|
||||
public static bool IsList(this Type self)
|
||||
{
|
||||
return self.IsGeneric(typeof(List<>)) || self.IsGeneric(typeof(IEnumerable<>));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断是否为List<>类型
|
||||
/// </summary>
|
||||
/// <param name="self">Type类</param>
|
||||
/// <returns>判断结果</returns>
|
||||
public static bool IsListOf<T>(this Type self)
|
||||
{
|
||||
if (self.IsGeneric(typeof(List<>)) && typeof(T).IsAssignableFrom(self.GenericTypeArguments[0]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#region 判断是否为枚举
|
||||
|
||||
/// <summary>
|
||||
/// 判断是否为枚举
|
||||
/// </summary>
|
||||
/// <param name="self">Type类</param>
|
||||
/// <returns>判断结果</returns>
|
||||
public static bool IsEnum(this Type self)
|
||||
{
|
||||
return self.GetTypeInfo().IsEnum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断是否为枚举或者可空枚举
|
||||
/// </summary>
|
||||
/// <param name="self"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsEnumOrNullableEnum(this Type self)
|
||||
{
|
||||
if (self == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (self.IsEnum)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (self.IsGenericType && self.GetGenericTypeDefinition() == typeof(Nullable<>) && self.GetGenericArguments()[0].IsEnum)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 判断是否为值类型
|
||||
/// </summary>
|
||||
/// <param name="self">Type类</param>
|
||||
/// <returns>判断结果</returns>
|
||||
public static bool IsPrimitive(this Type self)
|
||||
{
|
||||
return self.GetTypeInfo().IsPrimitive || self == typeof(decimal);
|
||||
}
|
||||
|
||||
public static bool IsNumber(this Type self)
|
||||
{
|
||||
Type checktype = self;
|
||||
if (self.IsNullable())
|
||||
{
|
||||
checktype = self.GetGenericArguments()[0];
|
||||
}
|
||||
if (checktype == typeof(int) || checktype == typeof(short) || checktype == typeof(long) || checktype == typeof(float) || checktype == typeof(decimal) || checktype == typeof(double))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#region 判断是否是Bool
|
||||
|
||||
public static bool IsBool(this Type self)
|
||||
{
|
||||
return self == typeof(bool);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断是否是 bool or bool?类型
|
||||
/// </summary>
|
||||
/// <param name="self"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsBoolOrNullableBool(this Type self)
|
||||
{
|
||||
if (self == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (self == typeof(bool) || self == typeof(bool?))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public static Dictionary<string, string> GetRandomValues(this Type self)
|
||||
{
|
||||
Dictionary<string, string> rv = new Dictionary<string, string>();
|
||||
string pat = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
|
||||
var pros = self.GetAllProperties();
|
||||
List<string> skipFields = new List<string>()
|
||||
{
|
||||
nameof(TopBasePoco.BatchError),
|
||||
nameof(TopBasePoco.Checked),
|
||||
nameof(TopBasePoco.ExcelIndex),
|
||||
nameof(ITenant.TenantCode)
|
||||
};
|
||||
if (typeof(IBasePoco).IsAssignableFrom(self))
|
||||
{
|
||||
skipFields.AddRange(
|
||||
new string[]{
|
||||
nameof(IBasePoco.CreateBy),
|
||||
nameof(IBasePoco.CreateTime),
|
||||
nameof(IBasePoco.UpdateBy),
|
||||
nameof(IBasePoco.UpdateTime) }
|
||||
);
|
||||
}
|
||||
if (typeof(IPersistPoco).IsAssignableFrom(self))
|
||||
{
|
||||
skipFields.Add(nameof(IPersistPoco.IsValid));
|
||||
}
|
||||
foreach (var pro in pros)
|
||||
{
|
||||
string key = pro.Name;
|
||||
string val = "";
|
||||
var notmapped = pro.GetCustomAttribute<NotMappedAttribute>();
|
||||
if (notmapped == null &&
|
||||
pro.PropertyType.IsList() == false &&
|
||||
pro.PropertyType.IsSubclassOf(typeof(TopBasePoco)) == false &&
|
||||
skipFields.Contains(key) == false
|
||||
)
|
||||
{
|
||||
if (pro.PropertyType.IsNumber())
|
||||
{
|
||||
var range = pro.GetCustomAttribute<RangeAttribute>();
|
||||
int start = 0;
|
||||
int end = 100;
|
||||
if (range != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
start = (int)Math.Truncate(double.Parse(range.Minimum.ToString()));
|
||||
end = (int)Math.Truncate(double.Parse(range.Maximum.ToString()));
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
Random r = new Random();
|
||||
val = r.Next(start, end).ToString();
|
||||
}
|
||||
else if (pro.PropertyType.IsBoolOrNullableBool())
|
||||
{
|
||||
List<string> boolvalues = new List<string> { "true", "false" };
|
||||
if (pro.PropertyType.IsNullable())
|
||||
{
|
||||
boolvalues.Add("null");
|
||||
}
|
||||
Random r = new Random();
|
||||
var index = r.Next(0, boolvalues.Count);
|
||||
val = boolvalues[index];
|
||||
}
|
||||
else if (pro.PropertyType.IsEnumOrNullableEnum())
|
||||
{
|
||||
List<string> enumvalues = new List<string>();
|
||||
Type enumtype = null;
|
||||
if (pro.PropertyType.IsNullable())
|
||||
{
|
||||
enumtype = pro.PropertyType.GenericTypeArguments[0];
|
||||
enumvalues.Add("null");
|
||||
}
|
||||
else
|
||||
{
|
||||
enumtype = pro.PropertyType;
|
||||
}
|
||||
var vs = Enum.GetValues(enumtype);
|
||||
Random r = new Random();
|
||||
var index = r.Next(0, vs.Length);
|
||||
val = enumtype.FullName+"."+ vs.GetValue(index).ToString();
|
||||
}
|
||||
else if (pro.PropertyType == typeof(string))
|
||||
{
|
||||
var length = pro.GetCustomAttribute<StringLengthAttribute>();
|
||||
var min = 1;
|
||||
var max = 20;
|
||||
var l = 0;
|
||||
if (length != null)
|
||||
{
|
||||
if (length.MaximumLength > 0)
|
||||
{
|
||||
max = length.MaximumLength;
|
||||
}
|
||||
if(length.MinimumLength > 0)
|
||||
{
|
||||
min = length.MinimumLength;
|
||||
}
|
||||
}
|
||||
if(min == max)
|
||||
{
|
||||
l = max;
|
||||
}
|
||||
else if(min < max)
|
||||
{
|
||||
l = new Random().Next(min, max);
|
||||
}
|
||||
Random r = new Random();
|
||||
for (int i = 0; i < l; i++)
|
||||
{
|
||||
int index = r.Next(pat.Length);
|
||||
val += pat[index];
|
||||
}
|
||||
val = "\"" + val + "\"";
|
||||
}
|
||||
else if(pro.PropertyType == typeof(DateTime) || pro.PropertyType == typeof(DateTime?))
|
||||
{
|
||||
Random r = new Random();
|
||||
val = DateTime.Now.AddDays(r.Next(-500, 500)).ToString("yyyy-MM-dd HH:mm:ss");
|
||||
val = $"DateTime.Parse(\"{val}\")";
|
||||
}
|
||||
if (pros.Where(x => x.Name.ToLower() + "id" == key.ToLower()).Any())
|
||||
{
|
||||
val = "$fk$";
|
||||
}
|
||||
if (val != "")
|
||||
{
|
||||
if (rv.ContainsKey(key) == false)
|
||||
{
|
||||
rv.Add(key, val);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
public static Dictionary<string, string> GetRandomValuesForTestData(this Type self)
|
||||
{
|
||||
Dictionary<string, string> rv = new Dictionary<string, string>();
|
||||
string pat = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
|
||||
var pros = self.GetAllProperties();
|
||||
List<string> skipFields = new List<string>()
|
||||
{
|
||||
nameof(TopBasePoco.BatchError),
|
||||
nameof(TopBasePoco.Checked),
|
||||
nameof(TopBasePoco.ExcelIndex),
|
||||
nameof(ITenant.TenantCode)
|
||||
};
|
||||
if (typeof(IBasePoco).IsAssignableFrom(self))
|
||||
{
|
||||
skipFields.AddRange(
|
||||
new string[]{
|
||||
nameof(IBasePoco.CreateBy),
|
||||
nameof(IBasePoco.CreateTime),
|
||||
nameof(IBasePoco.UpdateBy),
|
||||
nameof(IBasePoco.UpdateTime) }
|
||||
);
|
||||
}
|
||||
if (typeof(IPersistPoco).IsAssignableFrom(self))
|
||||
{
|
||||
skipFields.Add(nameof(IPersistPoco.IsValid));
|
||||
}
|
||||
foreach (var pro in pros)
|
||||
{
|
||||
string key = pro.Name;
|
||||
string val = "";
|
||||
var notmapped = pro.GetCustomAttribute<NotMappedAttribute>();
|
||||
var required = pro.GetCustomAttributes<RequiredAttribute>() != null;
|
||||
if (notmapped == null &&
|
||||
pro.PropertyType.IsList() == false &&
|
||||
pro.PropertyType.IsSubclassOf(typeof(TopBasePoco)) == false &&
|
||||
skipFields.Contains(key) == false
|
||||
)
|
||||
{
|
||||
if (pro.PropertyType.IsNumber())
|
||||
{
|
||||
if (pro.Name == "ID")
|
||||
{
|
||||
val = "";
|
||||
}
|
||||
else
|
||||
{
|
||||
var range = pro.GetCustomAttribute<RangeAttribute>();
|
||||
int start = 0;
|
||||
int end = 100;
|
||||
if (range != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
start = (int)Math.Truncate(double.Parse(range.Minimum.ToString()));
|
||||
end = (int)Math.Truncate(double.Parse(range.Maximum.ToString()));
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
Random r = new Random();
|
||||
val = r.Next(start, end).ToString();
|
||||
}
|
||||
}
|
||||
else if (pro.PropertyType.IsBoolOrNullableBool())
|
||||
{
|
||||
List<string> boolvalues = new List<string> { "true", "false" };
|
||||
if (pro.PropertyType.IsNullable())
|
||||
{
|
||||
if (required == false)
|
||||
{
|
||||
boolvalues.Add("");
|
||||
}
|
||||
}
|
||||
Random r = new Random();
|
||||
var index = r.Next(0, boolvalues.Count);
|
||||
val = boolvalues[index];
|
||||
}
|
||||
else if (pro.PropertyType.IsEnumOrNullableEnum())
|
||||
{
|
||||
List<string> enumvalues = new List<string>();
|
||||
Type enumtype = null;
|
||||
if (pro.PropertyType.IsNullable())
|
||||
{
|
||||
enumtype = pro.PropertyType.GenericTypeArguments[0];
|
||||
if (required == false)
|
||||
{
|
||||
enumvalues.Add("");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
enumtype = pro.PropertyType;
|
||||
}
|
||||
var vs = Enum.GetValues(enumtype);
|
||||
foreach (var item in vs)
|
||||
{
|
||||
enumvalues.Add((int)item + "");
|
||||
}
|
||||
Random r = new Random();
|
||||
var index = r.Next(0, enumvalues.Count);
|
||||
val = enumvalues[index];
|
||||
}
|
||||
else if (pro.PropertyType == typeof(string))
|
||||
{
|
||||
|
||||
var reg = pro.GetCustomAttribute<RegularExpressionAttribute>();
|
||||
var length = pro.GetCustomAttribute<StringLengthAttribute>();
|
||||
|
||||
if (reg != null) {
|
||||
Xeger x = new Xeger(reg.Pattern);
|
||||
val = x.Generate();
|
||||
if(length != null)
|
||||
{
|
||||
if(length.MaximumLength > 0 && val.Length > length.MaximumLength)
|
||||
{
|
||||
val = val.Substring(0, length.MaximumLength-1);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var min = 1;
|
||||
var max = 20;
|
||||
var l = 0;
|
||||
if (length != null)
|
||||
{
|
||||
if (length.MaximumLength > 0)
|
||||
{
|
||||
max = length.MaximumLength;
|
||||
}
|
||||
if (length.MinimumLength > 0)
|
||||
{
|
||||
min = length.MinimumLength;
|
||||
}
|
||||
}
|
||||
if (min == max)
|
||||
{
|
||||
l = max;
|
||||
}
|
||||
else if (min < max)
|
||||
{
|
||||
l = new Random().Next(min, max);
|
||||
}
|
||||
Random r = new Random();
|
||||
for (int i = 0; i < l; i++)
|
||||
{
|
||||
int index = r.Next(pat.Length);
|
||||
val += pat[index];
|
||||
}
|
||||
}
|
||||
|
||||
val = "\"" + val + "\"";
|
||||
}
|
||||
else if (pro.PropertyType == typeof(DateTime) || pro.PropertyType == typeof(DateTime?))
|
||||
{
|
||||
Random r = new Random();
|
||||
val = DateTime.Now.AddDays(r.Next(-500, 500)).ToString("yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
if (pros.Where(x => x.Name.ToLower() + "id" == key.ToLower()).Any())
|
||||
{
|
||||
val = "$fk$";
|
||||
}
|
||||
if (val != "")
|
||||
{
|
||||
if (rv.ContainsKey(key) == false)
|
||||
{
|
||||
rv.Add(key, val);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
|
||||
public static PropertyInfo GetSingleProperty(this Type self, string name)
|
||||
{
|
||||
if (_propertyCache.ContainsKey(self.FullName) == false)
|
||||
{
|
||||
var properties = self.GetProperties().ToList();
|
||||
_propertyCache = _propertyCache.Add(self.FullName, properties);
|
||||
return properties.Where(x => x.Name == name).FirstOrDefault();
|
||||
}
|
||||
else
|
||||
{
|
||||
return _propertyCache[self.FullName].Where(x => x.Name == name).FirstOrDefault();
|
||||
}
|
||||
}
|
||||
|
||||
public static PropertyInfo GetSingleProperty(this Type self, Func<PropertyInfo,bool> where)
|
||||
{
|
||||
if (_propertyCache.ContainsKey(self.FullName) == false)
|
||||
{
|
||||
var properties = self.GetProperties().ToList();
|
||||
_propertyCache = _propertyCache.Add(self.FullName, properties);
|
||||
return properties.Where(where).FirstOrDefault();
|
||||
}
|
||||
else
|
||||
{
|
||||
return _propertyCache[self.FullName].Where(where).FirstOrDefault();
|
||||
}
|
||||
}
|
||||
|
||||
public static List<PropertyInfo> GetAllProperties(this Type self)
|
||||
{
|
||||
if (_propertyCache.ContainsKey(self.FullName) == false)
|
||||
{
|
||||
var properties = self.GetProperties().ToList();
|
||||
_propertyCache = _propertyCache.Add(self.FullName, properties);
|
||||
return properties;
|
||||
}
|
||||
else
|
||||
{
|
||||
return _propertyCache[self.FullName];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user