public ResultDto Post([FromBody] CreateGroupDto inputDto) { bool exist = _freeSql.Select <LinGroup>().Any(r => r.Name == inputDto.Name); if (exist) { throw new LinCmsException("分组已存在,不可创建同名分组", ErrorCode.RepeatField); } LinGroup linGroup = _mapper.Map <LinGroup>(inputDto); List <PermissionDto> permissionDtos = ReflexHelper.GeAssemblyLinCmsAttributes(); _freeSql.Transaction(() => { long groupId = _freeSql.Insert(linGroup).ExecuteIdentity(); //批量插入 List <LinAuth> linAuths = new List <LinAuth>(); inputDto.Auths.ForEach(r => { PermissionDto pdDto = permissionDtos.FirstOrDefault(u => u.Permission == r); if (pdDto == null) { throw new LinCmsException($"不存在此权限:{r}", ErrorCode.NotFound); } linAuths.Add(new LinAuth(r, pdDto.Module, (int)groupId)); }); _freeSql.Insert <LinAuth>().AppendData(linAuths).ExecuteAffrows(); }); return(ResultDto.Success("新建分组成功")); }
/// <summary> /// 将多个实体组合成为一个 字典类型 /// </summary> /// <param name="di"></param> /// <returns></returns> public Dictionary <string, object> EntityToDictionary(Dictionary <string, object> di) { Dictionary <string, object> r = new Dictionary <string, object>(); foreach (var item in di) { if (item.Value is Models.Class.BaseClass) { ReflexHelper.GetPropertyInfos(item.Value.GetType()).ToList().ForEach(pi => { if (pi.GetValue(item.Value, null) == null) { r.Add(pi.Name, null); } else { if (pi.PropertyType == typeof(DateTime)) { r.Add(pi.Name, pi.GetValue(item.Value, null).ToDateTimeFormat("yyyy-MM-dd HH:mm:ss")); } else { r.Add(pi.Name, pi.GetValue(item.Value, null)); } } }); } else { r.Add(item.Key, item.Value); } } return(r); }
/// <summary> /// 设置编号 /// </summary> /// <param name="item"></param> /// <param name="entity"></param> /// <param name="DisplayName"></param> /// <param name="Value"></param> /// <returns></returns> public bool SetNumber(PropertyInfo item, T entity, string DisplayName, object Value) { var _TableInfo = TableInfo.Get(entity); string TableName = _TableInfo.TableName; //获取有特性标记的属性【编号】 var sign = ReflexHelper.GetAttribute <CSetNumberAttribute>(entity.GetType(), item.Name); if (sign != null) { //取ID的值 string KeyValue = string.Empty; var list = ReflexHelper.GetPropertyInfos(entity.GetType()); KeyValue = _TableInfo.KeyFieldInfo.Value.ToStr(); if (string.IsNullOrEmpty(KeyValue) || KeyValue.ToString().Equals(Guid.Empty.ToString())) { var MaxNumber = _FindAnalysis.FindMaxNumber(TableName, item.Name, "", null) + 1; if (MaxNumber == 0) { throw new AggregateException("设置编号错误:数据无法查出!"); } if (item.PropertyType == typeof(int)) { item.SetValue(entity, (MaxNumber.ToString().PadLeft(sign.Length, sign.Str)).ToInt32()); } else { item.SetValue(entity, (MaxNumber).ToStr().PadLeft(sign.Length, sign.Str)); } } } return(true); }
/// <summary> /// 比较两字段值是否相同 /// </summary> /// <param name="item"></param> /// <param name="_Model"></param> /// <param name="DisplayName"></param> /// <param name="Value"></param> /// <returns></returns> public bool CCompare(PropertyInfo item, T _Model, string DisplayName, object Value) { if (Value == null) { return(true); } //获取有特性标记的属性【比较两字段值是否相同】 var _Attribute = ReflexHelper.GetAttribute <CCompareAttribute>(_Model.GetType(), item.Name); if (_Attribute == null) { return(true); } var list = ReflexHelper.GetPropertyInfos(_Model.GetType()); foreach (var info in list) { var infoname = ReflexHelper.GetAttribute <CCompareAttribute>(_Model.GetType(), info.Name); if (info.Name.Equals(_Attribute.OtherProperty) && !info.GetValue(_Model).Equals(Value)) { return(SetErrorMessage(_Attribute.ErrorMessage, DisplayName + "的值与" + infoname + "不匹配", DisplayName)); } } return(true); }
/// <summary> /// FreeSql /// </summary> /// <param name="services"></param> public static void AddContext(this IServiceCollection services, IConfiguration configuration) { IConfigurationSection configurationSection = configuration.GetSection("ConnectionStrings:MySql"); IFreeSql fsql = new FreeSqlBuilder() .UseConnectionString(DataType.MySql, configurationSection.Value) .UseNameConvert(NameConvertType.PascalCaseToUnderscoreWithLower) .UseAutoSyncStructure(true) .UseNoneCommandParameter(true) .UseMonitorCommand(cmd => { Trace.WriteLine(cmd.CommandText + ";"); } ) .Build() .SetDbContextOptions(opt => opt.EnableAddOrUpdateNavigateList = true);//联级保存功能开启(默认为关闭) fsql.Aop.CurdAfter += (s, e) => { Log.Debug($"ManagedThreadId:{Thread.CurrentThread.ManagedThreadId}: FullName:{e.EntityType.FullName}" + $" ElapsedMilliseconds:{e.ElapsedMilliseconds}ms, {e.Sql}"); if (e.ElapsedMilliseconds > 200) { //记录日志 //发送短信给负责人 } }; //敏感词处理 if (configuration["AuditValue:Enable"].ToBoolean()) { IllegalWordsSearch illegalWords = ToolGoodUtils.GetIllegalWordsSearch(); fsql.Aop.AuditValue += (s, e) => { if (e.Column.CsType == typeof(string) && e.Value != null) { string oldVal = (string)e.Value; string newVal = illegalWords.Replace(oldVal); //第二种处理敏感词的方式 //string newVal = oldVal.ReplaceStopWords(); if (newVal != oldVal) { e.Value = newVal; } } }; } services.AddSingleton(fsql); services.AddScoped <UnitOfWorkManager>(); fsql.GlobalFilter.Apply <IDeleteAduitEntity>("IsDeleted", a => a.IsDeleted == false); //在运行时直接生成表结构 fsql.CodeFirst.SyncStructure(ReflexHelper.GetEntityTypes(typeof(IEntity))); services.AddFreeRepository(); }
private bool Start(PropertyInfo item, T _Model) { var DisplayName = ReflexHelper.GetAttribute <FieldAttribute>(_Model.GetType(), item.Name).Alias; var Value = item.GetValue(_Model); if (!CRequired(item, _Model, DisplayName, Value)) { return(false); } if (!CStringLength(item, _Model, DisplayName, Value)) { return(false); } if (!CRegularExpression(item, _Model, DisplayName, Value)) { return(false); } if (!CCompare(item, _Model, DisplayName, Value)) { return(false); } if (!CRepeat(item, _Model, DisplayName, Value)) { return(false); } if (!SetNumber(item, _Model, DisplayName, Value)) { return(false); } return(true); }
public UserInformation Auths() { LinUser linUser = _freeSql.Select <LinUser>().Where(r => r.Id == _currentUser.Id).First(); UserInformation user = _mapper.Map <UserInformation>(linUser); user.Avatar = _currentUser.GetFileUrl(linUser.Avatar); user.GroupName = user.GroupId != null?_freeSql.Select <LinGroup>().Where(r => r.Id == user.GroupId).First()?.Info : ""; if (linUser.IsAdmin()) { user.Auths = new List <IDictionary <string, object> >(); } else { if (linUser.GroupId != 0) { List <LinAuth> listAuths = _freeSql.Select <LinAuth>().Where(r => r.GroupId == linUser.GroupId).ToList(); user.Auths = ReflexHelper.AuthsConvertToTree(listAuths);; } } return(user); }
public async Task <UnifyResponseDto> DispatchPermissions(DispatchPermissionsDto permissionDto) { List <PermissionDefinition> permissionDefinitions = ReflexHelper.GetAssemblyLinCmsAttributes(); await _permissionService.DispatchPermissions(permissionDto, permissionDefinitions); return(UnifyResponseDto.Success("添加权限成功")); }
private StringBuilder GetByModel <T>(T Model, StringBuilder sb) { ReflexHelper.GetPropertyInfos(Model.GetType()).ToList().ForEach(item => { sb.Append("this." + item.Name + "=ko.observable('');"); }); return(sb); }
public void ConvertToTree() { List <PermissionDefinition> linCmsAttributes = ReflexHelper.GeAssemblyLinCmsAttributes(); dynamic obj = ReflexHelper.AuthorizationConvertToTree(linCmsAttributes); string jsonSerializeObject = JsonConvert.SerializeObject(obj); }
public IActionResult GetAllAuths() { List <PermissionDto> linCmsAttributes = ReflexHelper.GeAssemblyLinCmsAttributes(); dynamic obj = ReflexHelper.AuthorizationConvertToTree(linCmsAttributes); return(Ok(obj)); }
public void ReflexHelperTest() { List <PermissionDefinition> attributes = ReflexHelper.GeAssemblyLinCmsAttributes(); foreach (PermissionDefinition attribute in attributes) { _testOutputHelper.WriteLine(attribute.ToString()); } }
public override T Find <T>(string SqlStr, object Param) { var _Model = this._DbHelper.QueryFirstOrDefault <T>(SqlStr, Param); if (_Model == null) { return(ReflexHelper.CreateInstance <T>()); } return(_Model); }
public override T Find <T>(Expression <Func <T, object> > Select, Expression <Func <T, bool> > Where, Expression <Func <T, object> > OrderBy) { var _SQL = this.GetSqlStr(Select, Where, OrderBy); var _Model = this._DbHelper.QueryFirstOrDefault <T>(_SQL.Sql_Parameter, _SQL.Parameter); if (_Model == null) { return(ReflexHelper.CreateInstance <T>()); } return(_Model); }
public override T FindById <T>(Expression <Func <T, object> > Select, object Id) { var _SQL = this.GetSqlStrById(Select, Id, null); var _Model = this._DbHelper.QueryFirstOrDefault <T>(_SQL.Sql_Parameter, _SQL.Parameter); if (_Model == null) { return(ReflexHelper.CreateInstance <T>()); } return(_Model); }
public GroupDto Get(int id) { LinGroup group = _freeSql.Select <LinGroup>().Where(r => r.Id == id).First(); GroupDto groupDto = _mapper.Map <GroupDto>(group); List <LinAuth> listAuths = _freeSql.Select <LinAuth>().Where(r => r.GroupId == id).ToList(); groupDto.Auths = ReflexHelper.AuthsConvertToTree(listAuths); return(groupDto); }
/// <summary> /// 创建主键 /// </summary> /// <returns></returns> private object CreatePrimaryKey <T>(ref MemberInitExpression body, string FiledName, Type type, bool IsIdentity) where T : class, new() { object id; if (type == typeof(Guid?) || type == typeof(Guid)) { var list = new List <MemberBinding>(); var Model = ReflexHelper.CreateInstance <T>(); //检测 用户是否自己设置了主键 var member = (body.Bindings.Where(item => item.Member.Name == FiledName).FirstOrDefault() as MemberAssignment); if (member == null) { id = Guid.NewGuid(); var memberinfo = Model.GetType().GetProperty(FiledName); list.Add(Expression.Bind(memberinfo, Expression.Constant(id, typeof(Guid)))); } else { var value = Parser.Eval(member.Expression); if (value.ToGuid() == Guid.Empty) { id = Guid.NewGuid(); } else { id = value; } } foreach (MemberAssignment item in body.Bindings) { if (item.Member.Name == FiledName) { list.Add(Expression.Bind(item.Member, Expression.Constant(id, item.Expression.Type))); } else { list.Add(Expression.Bind(item.Member, Expression.Constant(Parser.Eval(item.Expression), item.Expression.Type))); } } body = Expression.MemberInit(Expression.New(typeof(T)), list); return(id); } else if ((type == typeof(int?) || (type == typeof(int)) && IsIdentity)) { return(_DbHelper.GetLastInsertId()); } else { return(Parser.Eval(((body.Bindings.Where(item => item.Member.Name == FiledName).FirstOrDefault()) as MemberAssignment).Expression)); } }
private string[] DBS_ClNs() { ModelArticles articleM = new ModelArticles(); string ClName_id = ReflexHelper.Name(() => articleM.id); string ClName_Content = ReflexHelper.Name(() => articleM.Content); string ClName_Money = ReflexHelper.Name(() => articleM.Money); string ClName_Remark = ReflexHelper.Name(() => articleM.Remark); string ClName_TimeAdd = ReflexHelper.Name(() => articleM.TimeAdd); return(new string[] { ClName_id, ClName_Content, ClName_Money, ClName_Remark, ClName_TimeAdd }); }
public bool Check(T _Model) { var list = ReflexHelper.GetPropertyInfos(_Model.GetType()); foreach (var item in list) { if (!this.Start(item, _Model)) { return(false); } } return(true); }
/// <summary> /// 字符串长度验证 /// </summary> /// <param name="item"></param> /// <param name="_Model"></param> /// <param name="DisplayName"></param> /// <param name="Value"></param> /// <returns></returns> public bool CStringLength(PropertyInfo item, T _Model, string DisplayName, object Value) { if (Value == null) { return(true); } //获取有特性标记的属性【字符串长度验证】 var _Attribute = ReflexHelper.GetAttribute <CStringLengthAttribute>(_Model.GetType(), item.Name); if (_Attribute != null && (Value.ToString().Length < _Attribute.MinLength || Value.ToString().Length > _Attribute.MaxLength)) { return(SetErrorMessage(_Attribute.ErrorMessage, DisplayName + "长度介于" + _Attribute.MinLength + "-" + _Attribute.MaxLength + "之间", DisplayName)); } return(true); }
private static List <EntityColumnAttribute> GetEntityColumnAttributes(Type type) { var columns = new List <EntityColumnAttribute>(); foreach (var propertyInfo in ReflexHelper.GetPropertys(type)) { var attribute = propertyInfo.GetCustomAttribute <EntityColumnAttribute>(); if (attribute != null) { attribute.PropertyInfo = propertyInfo; columns.Add(attribute); } } return(columns); }
/// <summary> /// 正则表达式验证 /// </summary> /// <param name="item"></param> /// <param name="_Model"></param> /// <param name="DisplayName"></param> /// <param name="Value"></param> /// <returns></returns> public bool CRegularExpression(PropertyInfo item, T _Model, string DisplayName, object Value) { if (Value == null) { return(true); } //获取有特性标记的属性【正则表达式验证】 var _Attribute = ReflexHelper.GetAttribute <CRegularExpressionAttribute>(_Model.GetType(), item.Name); if (_Attribute != null && !System.Text.RegularExpressions.Regex.IsMatch(Value.ToString(), _Attribute.Pattern)) { return(SetErrorMessage(_Attribute.ErrorMessage, DisplayName + "格式不正确", DisplayName)); } return(true); }
/// <summary> /// 验证数据是否重复 /// </summary> /// <param name="item"></param> /// <param name="_Model"></param> /// <param name="DisplayName"></param> /// <param name="Value"></param> /// <returns></returns> public bool CRepeat(PropertyInfo item, T _Model, string DisplayName, object Value) { if (Value == null) { return(true); } var _TableInfo = TableInfo.Get(_Model); string TableName = _TableInfo.TableName; //获取有特性标记的属性【非空】 var _Attribute = ReflexHelper.GetAttribute <CRepeatAttribute>(_Model.GetType(), item.Name); if (_Attribute == null) { return(true); } //取ID的值 string KeyValue = string.Empty, KeyName = string.Empty; var list = ReflexHelper.GetPropertyInfos(_Model.GetType()); KeyValue = _TableInfo.KeyFieldInfo.Value.ToStr(); KeyName = _TableInfo.KeyFieldInfo.FieldName; string where = string.Empty; if (!string.IsNullOrEmpty(KeyValue) && !KeyValue.ToString().Equals(Guid.Empty.ToString())) { where = " AND " + KeyName + "<>'" + KeyValue + "'"; } //判断条件,是否存在 || 自定义条件 语法 :and filed1='{filed1}' || if (!string.IsNullOrEmpty(_Attribute.Where)) { foreach (var pi in list) { if (_Attribute.Where.Contains("{" + pi.Name + "}")) { where += _Attribute.Where + " "; where = where.Replace("{" + pi.Name + "}", pi.GetValue(_Model) == null ? "" : pi.GetValue(_Model).ToString()); } } } string sql = "SELECT COUNT(1) FROM " + TableName + " WHERE 1=1 AND " + item.Name + "='" + Value + "' " + where; if (_DbHelper.QuerySingleOrDefault <int>(sql, null) > 0) { return(SetErrorMessage(_Attribute.ErrorMessage, DisplayName + "已存在", DisplayName)); } return(true); }
public async Task StartAsync(CancellationToken cancellationToken = default) { try { using var scope = _serviceProvider.CreateScope(); IDataSeedContributor dataSeedContributor = scope.ServiceProvider.GetRequiredService <IDataSeedContributor>(); var permissions = ReflexHelper.GetAssemblyLinCmsAttributes(); await dataSeedContributor.SeedPermissionAsync(permissions); await dataSeedContributor.InitAdminPermission(); } catch (Exception ex) { _logger.LogError($"初始化数据失败!!!{ex.Message}{ex.StackTrace}{ex.InnerException}"); }; }
public override bool EditById <T>(T Set, List <SQL> li) { var list = new List <MemberBinding>(); var fileds = ReflexHelper.GetPropertyInfos(typeof(T));//.Where(w => w.Name != Set.GetKey().FieldName); var _TableInfo = TableInfo.Get(Set); foreach (var item in fileds) { //检测有无忽略字段 if (_TableInfo.Fields.Where(w => w.IsIgnore == true && w.FieldName == item.Name).FirstOrDefault() != null) { continue; } list.Add(Expression.Bind(item, Expression.Constant(item.GetValue(Set), item.PropertyType))); } return(ExecuteById <T>(Expression.MemberInit(Expression.New(typeof(T)), list), li)); }
public Sys_PagingEntity NewPagingEntity(Sys_PagingEntity pe, params object[] ArryEntity) { var dic = new Dictionary <string, object>(); var list = new List <PropertyInfo>(); var colNames = new List <Dictionary <string, string> >(); ArryEntity.ToList().ForEach(item => { //将所有实体里面的属性放入list中 ReflexHelper.GetPropertyInfos(item.GetType()).ToList().ForEach(p => { list.Add(p); }); }); foreach (DataColumn dc in pe.Table.Columns) { dic = new Dictionary <string, object>(); var col = new Dictionary <string, string>(); var pro = list.Find(item => item.Name.Equals(dc.ColumnName)); dic["field"] = dc.ColumnName; dic["align"] = "left"; if (pro == null) { dic["title"] = dc.ColumnName; dic["visible"] = !dc.ColumnName.Equals("_ukid"); col.Add(dc.ColumnName, dc.ColumnName); } else { //获取有特性标记的属性【获取字段别名(中文名称)】 var FiledConfig = pro.GetCustomAttribute(typeof(FieldAttribute)) as FieldAttribute; dic["title"] = (FiledConfig.Alias == "" ? dc.ColumnName : FiledConfig.Alias); dic["visible"] = true; col.Add(dc.ColumnName, dic["title"].ToStr()); } pe.ColNames.Add(col); pe.ColModel.Add(dic); } return(pe); }
public ResultDto DispatchAuths(AuthDto authDto) { List <PermissionDto> permissionDtos = ReflexHelper.GeAssemblyLinCmsAttributes(); List <LinAuth> linAuths = new List <LinAuth>(); foreach (string auth in authDto.Auths) { PermissionDto permission = permissionDtos.FirstOrDefault(r => r.Permission == auth); if (permission == null) { throw new LinCmsException($"异常权限:{auth}"); } linAuths.Add(new LinAuth(auth, permission.Module, authDto.GroupId)); } _freeSql.Insert <LinAuth>(linAuths).ExecuteAffrows(); return(ResultDto.Success("添加权限成功")); }
/// <summary> /// 非空验证 /// </summary> /// <param name="item"></param> /// <param name="_Model"></param> /// <param name="DisplayName"></param> /// <param name="Value"></param> /// <returns></returns> public bool CRequired(PropertyInfo item, T _Model, string DisplayName, object Value) { var fileName = item.Name; var _Attribute = ReflexHelper.GetAttribute <CRequiredAttribute>(_Model.GetType(), item.Name); if (_Attribute == null) { return(true); } if (Value == null) { return(SetErrorMessage(_Attribute.ErrorMessage, DisplayName + "不能为空", DisplayName)); } if (item.PropertyType == typeof(string) && string.IsNullOrEmpty(Value.ToStr())) { return(SetErrorMessage(_Attribute.ErrorMessage, DisplayName + "不能为空", DisplayName)); } if (item.PropertyType == typeof(Guid?) && Value.ToGuid() == Guid.Empty) { return(SetErrorMessage(_Attribute.ErrorMessage, DisplayName + "不能为空", DisplayName)); } return(true); }
protected override void Load(ContainerBuilder builder) { IFreeSql fsql = new FreeSqlBuilder() .UseConnectionString(_configuration) .UseNameConvert(NameConvertType.PascalCaseToUnderscoreWithLower) .UseAutoSyncStructure(true) .UseNoneCommandParameter(true) .UseMonitorCommand(cmd => { Trace.WriteLine(cmd.CommandText + ";"); } ) .Build() .SetDbContextOptions(opt => opt.EnableAddOrUpdateNavigateList = true);//联级保存功能开启(默认为关闭) builder.RegisterInstance(fsql).SingleInstance(); fsql.Aop.CurdAfter += (s, e) => { Log.Debug($"ManagedThreadId:{Thread.CurrentThread.ManagedThreadId}: FullName:{e.EntityType.FullName}" + $" ElapsedMilliseconds:{e.ElapsedMilliseconds}ms, {e.Sql}"); if (e.ElapsedMilliseconds > 200) { //记录日志 //发送短信给负责人 } }; //敏感词处理 if (_configuration["AuditValue:Enable"].ToBoolean()) { IllegalWordsSearch illegalWords = ToolGoodUtils.GetIllegalWordsSearch(); fsql.Aop.AuditValue += (s, e) => { if (e.Column.CsType == typeof(string) && e.Value != null) { string oldVal = (string)e.Value; string newVal = illegalWords.Replace(oldVal); //第二种处理敏感词的方式 //string newVal = oldVal.ReplaceStopWords(); if (newVal != oldVal) { e.Value = newVal; } } }; } //services.AddFreeRepository(); builder.RegisterType(typeof(UnitOfWorkManager)).InstancePerLifetimeScope(); fsql.GlobalFilter.Apply <IDeleteAduitEntity>("IsDeleted", a => a.IsDeleted == false); try { using var objPool = fsql.Ado.MasterPool.Get(); } catch (Exception e) { Log.Logger.Error(e + e.StackTrace + e.Message + e.InnerException); return; } //在运行时直接生成表结构 try { fsql.CodeFirst .SeedData() .SyncStructure(ReflexHelper.GetTypesByTableAttribute()); } catch (Exception e) { Log.Logger.Error(e + e.StackTrace + e.Message + e.InnerException); } }
public void RelfexGetCustomAttributes() { var entityTypes = ReflexHelper.GetEntityTypes(typeof(IEntity)); Assert.True(entityTypes.Length > 0); }