/// <summary> /// Validates the entity against rules set for the specific entity against itself. /// </summary> /// <param name="entityRules">This can be a list of all the rules or an already filtered list, the rules will be checked again.</param> /// <param name="theEntity">The entity that is being used to look up rules against its own type and its specific record</param> /// <param name="ruleApplicator">The event or process the event is applied to.</param> /// <returns>Returns the rule that was matched or null if nothing matched</returns> public IJarsRule EvaluateEntityOwnRules(List <IJarsRule> entityRules, IEntityBase theEntity, RuleRunsOn ruleApplicator, RuleEvaluation ruleEvaluation = RuleEvaluation.Both) { var fullFilterList = new List <IJarsRule>(); if (ruleEvaluation == RuleEvaluation.Both) { fullFilterList = entityRules.FindAll(r => r.SourceTypeName == theEntity.GetType().Name&& r.TargetTypeName == theEntity.GetType().Name&& r.RuleEvaluation == ruleEvaluation && r.RuleRunsOn.Contains(ruleApplicator.ToString())); } if (ruleEvaluation == RuleEvaluation.SourceOnly) { fullFilterList = entityRules.FindAll(r => r.SourceTypeName == theEntity.GetType().Name&& r.RuleEvaluation == ruleEvaluation && r.RuleRunsOn.Contains(ruleApplicator.ToString())); } if (ruleEvaluation == RuleEvaluation.TargetOnly) { fullFilterList = entityRules.FindAll(r => r.TargetTypeName == theEntity.GetType().Name&& r.RuleEvaluation == ruleEvaluation && r.RuleRunsOn.Contains(ruleApplicator.ToString())); } //does the entity type meet the its own conditions? //var entityFilterList = fullFilterList.FindAll(rules => rules.TargetEntityId == $"{theEntity.Id}"); if (!fullFilterList.Any()) { return(null); } DataTable entityTable = theEntity.ConvertToDataTable(); foreach (var rule in fullFilterList) { if (ruleEvaluation == RuleEvaluation.Both) { if (!EvaluateRule(entityTable, null, rule)) { return(rule); } if (!EvaluateRule(null, entityTable, rule)) { return(rule); } } else { if (!EvaluateRule(entityTable, null, rule)) { return(rule); } } } return(null); }
/// <summary> /// Evaluate The source entity against the target entity type. /// This is for rules that are set against an entity type rather than a specific entity. /// This does not include self evaluating. /// swapping the source and target will do the reverse check. /// </summary> /// <param name="entityRules">This can be a list of all the rules or an already filtered list, the rules will be checked again.</param> /// <param name="sourceEntity">The entity that acts as the source for the rule</param> /// <param name="targetEntity">The entity that acts as the target for the rule.</param> /// <param name="ruleApplicator">The event or process the event is applied to.</param> /// <returns>Returns the rule that was matched or null if nothing matched</returns> public IJarsRule EvaluateSourceAgainstTargetType(List <IJarsRule> entityRules, IEntityBase sourceEntity, IEntityBase targetEntity, RuleRunsOn ruleApplicator) { var fullTargetFilterList = entityRules.FindAll(r => r.TargetTypeName == targetEntity.GetType().Name&& r.SourceTypeName == sourceEntity.GetType().Name&& r.RuleRunsOn.Contains(ruleApplicator.ToString()) && !r.TargetCriteriaString.Contains($"[{nameof(targetEntity.Id)}] = {targetEntity.Id}")); //does the source rules meet the target conditions? var specificFilterList = fullTargetFilterList.FindAll(rules => string.IsNullOrEmpty(rules.TargetCriteriaString)); if (!specificFilterList.Any()) { return(null); } DataTable sourceTable = sourceEntity.ConvertToDataTable(); DataTable targetTable = sourceEntity.ConvertToDataTable(); foreach (var rule in specificFilterList) { if (!EvaluateRule(sourceTable, targetTable, rule)) { return(rule); } } return(null); }
/// <summary> /// Evaluate The source entity against the target entity only. /// This does not include self evaluating. /// swapping the source and target will do the reverse check. /// </summary> /// <param name="entityRules">This can be a list of all the rules or an already filtered list, the rules will be checked again.</param> /// <param name="sourceEntity">The entity that acts as the source for the rule</param> /// <param name="targetEntity">The entity that acts as the target for the rule.</param> /// <param name="ruleApplicator">The event or process the event is applied to.</param> /// <returns>Returns the rule that was matched or null if nothing matched</returns> public IJarsRule EvaluateSourceAgainstTarget(List <IJarsRule> entityRules, IEntityBase sourceEntity, IEntityBase targetEntity, RuleRunsOn ruleApplicator) { var fullTargetFilterList = entityRules.FindAll(r => r.SourceTypeName == sourceEntity.GetType().Name&& r.TargetTypeName == targetEntity.GetType().Name&& r.TargetCriteriaString.Contains($"[{nameof(targetEntity.Id)}] = {targetEntity.Id}") && r.RuleRunsOn.Contains(ruleApplicator.ToString())); if (!fullTargetFilterList.Any()) { return(null); } //get the first matching rule DataTable sourceTable = sourceEntity.ConvertToDataTable(); DataTable targetTable = targetEntity.ConvertToDataTable(); foreach (var rule in fullTargetFilterList) { //test the source table if (!EvaluateRule(sourceTable, targetTable, rule)) { return(rule); } } return(null); }
/// <summary> /// 判断实体是否存在数据库中 /// </summary> /// <param name="Entity"></param> /// <returns></returns> public bool IsEntityExist(IEntityBase Entity) { string sql = "SELECT count(0) FROM user_tables WHERE TABLE_NAME = '" + Entity.GetType().Name + "'"; DataSet ds = this.odbh.GetDataSet(sql); if (ds == null) { return(false); } if (ds.Tables[0].Rows.Count > 0) { if (int.Parse(ds.Tables[0].Rows[0][0].ToString()) > 0) { return(true); } else { return(false); } } else { return(false); } }
/// <summary> /// Destroy the block /// </summary> /// <param name="entity">entity who destroyed the block</param> /// <param name="block">block that has been destroyed</param> public virtual void Destroy(IEntityBase entity, IStructBlock iBlock) { StructBlock block = (StructBlock)iBlock; BlockDestroyEventArgs eventArgs = RaiseDestroyEvent(entity, block); if (eventArgs.EventCanceled) return; PlaySoundOnDestroy(entity, block); UpdateWorld(block, true); // Check if the entity is a player if ((entity != null) && (entity.GetType() == typeof(Player))) { // Check if the player is in creative mode if (((Player)entity).GameMode == System.Convert.ToByte(1)) { // Don't drop any items as the player is in creative mode goto skipDrop; } } DropItems(entity as EntityBase, block); skipDrop: DamageItem(entity); NotifyNearbyBlocks((EntityBase)entity, block); }
/// <summary> /// 查询指定实体对象的所有值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="EntityInstance"></param> /// <returns></returns> public virtual List <T> QueryAll <T>(IEntityBase EntityInstance) { IDvTable dvt = DalCreateDriveTable(EntityInstance); DataSet ds = dvt.Select(); List <T> result = this.dh.Convert <T>(EntityInstance.GetType(), ds); return(result); }
/// <summary> /// 创建语句 /// </summary> /// <param name="JoinEntity"></param> /// <param name="FieldName"></param> /// <param name="OperatorType"></param> /// <param name="LinkNextOperator"></param> protected void CreateWhereClause(IEntityBase JoinEntity, string FieldName, Operator OperatorType, LinkOperator LinkNextOperator) { this.CheckField(JoinEntity, FieldName); IDvWhere newpw = new DvWhere(); newpw.ClauseItem(JoinEntity, JoinEntity.GetType().GetProperty(FieldName) , GetDescription(OperatorType), GetDescription(LinkNextOperator)); newpw.OperatorItem = OperatorType; this.wherelist.Add(newpw); }
/// <summary> /// This rule check if the source entity has any list properties that contain types that has rules set against the target entity. /// ie. a Job with a sub job line that has restrictions on the target. /// </summary> /// <param name="entityRules">This can be a list of all the rules or an already filtered list, the rules will be checked again.</param> /// <param name="sourceEntity">The entity that acts as the source for the rule</param> /// <param name="targetEntity">The entity that acts as the target for the rule.</param> /// <param name="ruleApplicator">The event or process the event is applied to.</param> /// <returns></returns> public IJarsRule EvaluateSourceChildListsAgainstTarget(List <IJarsRule> entityRules, IEntityBase sourceEntity, IEntityBase targetEntity, RuleRunsOn ruleApplicator) { var sourceDictionaryListTypes = sourceEntity.GetGenericListTypesDictionary(); //get the list of possible rules where the target type is the type of the key value. //https://dotnetable.wordpress.com/2015/06/20/find-all-items-in-list-which-exist-in-another-list-using-linq/ //this can be seen as retrieve all the values from entityRules which also exist in dictionary values. var filteredRules = (from er in entityRules join kVals in sourceDictionaryListTypes.Values on er.SourceTypeName equals kVals.Name select er).Where(r => r.RuleRunsOn.Contains(ruleApplicator.ToString())).ToList(); if (!filteredRules.Any()) { return(null); } /* * * var listType = typeof(List<>); * var constructedListType = listType.MakeGenericType(t); * var instance = Activator.CreateInstance(constructedListType); * */ IJarsRule failRule = null; //test each collection foreach (var dictionaryKey in sourceDictionaryListTypes) { //var itemsListType = typeof(IList<>); //var defaultList = itemsListType.MakeGenericType(dictionaryKey.Value); var sourceItems = (IList)sourceEntity.GetType() .GetProperty(dictionaryKey.Key) .GetValue(sourceEntity); //test the property type first foreach (var subItem in sourceItems) { //test broad failRule = EvaluateSourceAgainstTargetType(filteredRules, subItem as IEntityBase, targetEntity, ruleApplicator); if (failRule != null) { return(failRule); } //test narrow failRule = EvaluateSourceAgainstTarget(filteredRules, subItem as IEntityBase, targetEntity, ruleApplicator); if (failRule != null) { return(failRule); } } } return(null); }
/// <summary> /// 根据条件查询指定实体对象的所有值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="Field"></param> /// <param name="EntityInstance"></param> /// <param name="LinkOpr"></param> /// <param name="Opr"></param> /// <returns></returns> public virtual List <T> QueryEntityList <T>(IEntityBase EntityInstance, string Field, Operator Opr, LinkOperator LinkOpr) { List <T> result = new List <T>(); IDvTable dvt = DalCreateDriveTable(EntityInstance); dvt.WhereClause(Field, Opr, LinkOpr); DataSet ds = dvt.Select(); result = this.dh.Convert <T>(EntityInstance.GetType(), ds); return(result); }
/// <summary> /// Determines if an IEntityBase item has any properties that are generic IList<![CDATA[<T>]]> properties and extracts the types of the IList. /// This is helpfull in the rules processing. /// </summary> /// <param name="entity">The entity that is being inspected</param> /// <returns>The list of Type that contains the types found in generic list properties. Or an empty list if nothing found</returns> public static IList <Type> GetGenericListTypes(this IEntityBase entity) { IList <Type> foundList = new List <Type>(); IEnumerable <Type> genericProperties = entity.GetType().GetProperties().Select(p => p.PropertyType).Where(pi => pi.IsGenericType && pi.GetGenericTypeDefinition() == typeof(IList <>)); if (genericProperties.Any()) { //check if there are list proerties and if they are of a certain type, if they are what type foundList = genericProperties.Select(p => p.GenericTypeArguments[0]).ToList(); } return(foundList); }
public int Update(string tableName, IEntityBase entity, bool merge) { log.Describe($"{nameof(Update)}: {tableName}", new { merge, entity }); var type = entity.GetType(); var columns = ReflectionUtil.GetColumnSchemas(type); var query = new StringBuilder(columns.Count * 32); var values = new List <object>(columns.Count); var pos = 0; query.Write($"UPDATE ") .WriteLine(ResolveTableName(tableName)) .WriteTabbedLine(1, "SET"); for (int i = 0; i < columns.Count; i++) { var column = columns[i]; var value = columns[i].GetValue(entity); var defaultValue = value?.GetType().GetDefault(); if (column.PrimaryKey) { continue; } if (column.Nullable && (merge && value == defaultValue)) { continue; } values.Add(value); query.WriteTabbed(2, '"' + columns[i].Name + '"') .Write(" = @" + pos++) .Write(",") .NewLine(); } query.TrimEndLineBreaks() .TrimEnd(',') .NewLine(); var affected = db.Execute(query.ToString(), values); return(affected); }
/// <summary> /// 根据多个条件子语句查询指定实体对象的所有值 当条件子语句数量为0时返回值为空列表 此方法不考虑联立表查询情况 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="EntityInstance"></param> /// <param name="Clauses"></param> /// <returns></returns> public virtual List <T> QueryEntityList <T>(IEntityBase EntityInstance, List <ClauseElement> Clauses) { List <T> result = new List <T>(); if (Clauses.Count == 0) { return(result); } IDvTable dvt = DalCreateDriveTable(EntityInstance); foreach (ClauseElement ce in Clauses) { dvt.WhereClause(ce.FieldName, ce.Opr, ce.LinkOpr); } DataSet ds = dvt.Select(); result = this.dh.Convert <T>(EntityInstance.GetType(), ds); return(result); }
/// <summary> /// Determines if an entity has any properties that are generic IList<> properties and extract the name and IList<> type of the property. /// This is helpfull in rules processing /// </summary> /// <param name="entity">The entity that might contain the properties of IList<![CDATA[<T>]]> </param> /// <returns>return a readonly dictionary with the property name and type</returns> public static ReadOnlyDictionary <string, Type> GetGenericListTypesDictionary(this IEntityBase entity) { IDictionary <string, Type> foundList = new Dictionary <string, Type>(); IList <Type> foundTypes = new List <Type>(); var entProperties = entity.GetType().GetProperties().Select(p => new { pType = p.PropertyType, pName = p.Name }) .Where(pi => pi.pType.IsGenericType && pi.pType.GetGenericTypeDefinition() == typeof(IList <>)); //IEnumerable<Type> genericProperties = entProperties.Select(t => t.pType); if (entProperties.Any()) { //check if there are list proerties and if they are of a certain type, if they are what type //foundTypes = entProperties.Select(p => p.pType.GenericTypeArguments[0]).ToList(); foreach (var pInfo in entProperties) { foundList.Add(pInfo.pName, pInfo.pType.GenericTypeArguments[0]); } } return(new ReadOnlyDictionary <string, Type>(foundList)); }
/// <summary> /// Evaluates the rules that are linked to the entities involved in the operation being carried out. /// If it doesn't return a rule it means all rules have passed the test. /// </summary> /// <param name="entityRules">The list of rules available for evaluation, this list can be the full list of rules, as it will be filtered according to the passed in target and source entities.</param> /// <param name="sourceEntity">The entity that acts as the source for the rule</param> /// <param name="targetEntity">The entity that acts as the target for the rule.</param> /// <param name="ruleApplicator">The event or process the event is applied to.</param> /// <returns>If a rule gets returned it will be the first rule the process failed on, if nothing gets returned all rules passed.</returns> public IJarsRule EvaluateEntityRules(IList <IJarsRule> entityRules, IEntityBase sourceEntity, IEntityBase targetEntity, RuleRunsOn ruleRunsOn) { IJarsRule failedRule = null; List <IJarsRule> filteredByRuleRunsOnList = entityRules.Where(r => r.RuleRunsOn.Contains(ruleRunsOn.ToString())).ToList(); //first check the rule for source only rules var fullSourceOnlyFilterList = filteredByRuleRunsOnList.FindAll(rules => rules.RuleEvaluation == RuleEvaluation.SourceOnly && rules.SourceTypeName == sourceEntity.GetType().Name); //does the source meet the its own conditions? if (fullSourceOnlyFilterList.Any()) { failedRule = EvaluateEntityOwnRules(fullSourceOnlyFilterList, sourceEntity, ruleRunsOn, RuleEvaluation.SourceOnly); } if (failedRule != null) { return(failedRule); } //first check the rule for source only rules var fullTargeteOnlyFilterList = filteredByRuleRunsOnList.FindAll(rules => rules.RuleEvaluation == RuleEvaluation.TargetOnly && rules.TargetTypeName == targetEntity.GetType().Name); //does the source meet the its own conditions? if (fullTargeteOnlyFilterList.Any()) { failedRule = EvaluateEntityOwnRules(fullTargeteOnlyFilterList, targetEntity, ruleRunsOn, RuleEvaluation.TargetOnly); } if (failedRule != null) { return(failedRule); } //---- from here we test both sides //need to test rules of target type on target type //and source on target type //get all rules linked to the target var fullSourceFilterList = filteredByRuleRunsOnList.FindAll(rules => rules.RuleEvaluation == RuleEvaluation.Both && rules.SourceTypeName == sourceEntity.GetType().Name); //does the source meet the its own conditions? if (fullSourceFilterList.Any()) { failedRule = EvaluateEntityOwnRules(fullSourceFilterList, sourceEntity, ruleRunsOn); if (failedRule != null) { return(failedRule); } //does the target meet the source conditions? failedRule = EvaluateSourceAgainstTarget(fullSourceFilterList, targetEntity, sourceEntity, ruleRunsOn); if (failedRule != null) { return(failedRule); } } var fullTargetFilterList = filteredByRuleRunsOnList.FindAll(rules => rules.TargetTypeName == targetEntity.GetType().Name); //does the target meet the its own conditions? if (fullTargetFilterList.Any()) { failedRule = EvaluateEntityOwnRules(fullTargetFilterList, targetEntity, ruleRunsOn); if (failedRule != null) { return(failedRule); } //does the source meet the target conditions? failedRule = EvaluateSourceAgainstTarget(fullTargetFilterList, sourceEntity, targetEntity, ruleRunsOn); if (failedRule != null) { return(failedRule); } failedRule = EvaluateSourceAgainstTargetType(fullTargetFilterList, sourceEntity, targetEntity, ruleRunsOn); if (failedRule != null) { return(failedRule); } failedRule = EvaluateSourceChildListsAgainstTarget(fullTargetFilterList, sourceEntity, targetEntity, ruleRunsOn); if (failedRule != null) { return(failedRule); } } return(null); }
/// <summary> /// 获取填充xml /// </summary> /// <param name="obj">要填充的实体</param> /// <param name="modelCode">实体名称</param> /// <returns>返回xml</returns> public XElement GetFullXml(IEntityBase obj, string modelCode, SubmitData submitData) { XElement element = null; Metadata meta = new Metadata(); string modelType = string.Empty; if (!string.IsNullOrEmpty(modelCode)) { modelType = modelCode.ToUpper(); } else { modelType = obj.GetType().Name; } List<AutoDictionary> listAutoDic = new List<AutoDictionary>(); string strMainKey = string.Empty; string strMainValue = string.Empty; CommonBLL bll = new CommonBLL(""); #region 处理元数据 #region " T_HR_EMPLOYEEOVERTIMERECORD " if (modelType.ToUpper() == Constants.T_HR_EMPLOYEEOVERTIMERECORD) { strMainKey = "OVERTIMERECORDID"; strMainValue = string.Empty; Type objtype = obj.GetType(); PropertyInfo[] propinfos = objtype.GetProperties(); foreach (PropertyInfo propinfo in propinfos) { string keyValue = propinfo.GetValue(obj, null) != null ? propinfo.GetValue(obj, null).ToString() : string.Empty; if (propinfo.Name == strMainKey) { strMainValue = keyValue; } } if (obj is T_HR_EMPLOYEEOVERTIMERECORD) { T_HR_EMPLOYEEOVERTIMERECORD entity = obj as T_HR_EMPLOYEEOVERTIMERECORD; if (submitData.SubmitFlag != SubmitFlag.New && submitData.ApprovalResult == ApprovalResult.NoPass) { var overtimeDetail = bll.Query<T_HR_EMPLOYEEOVERTIMERECORD>().Where(w => w.OVERTIMERECORDID == strMainValue).ToList(); //Dictionary<object, object> detail = new Dictionary<object, object>(); //detail.Add(overtimeDetail, null);//normItemConfigList 是2级从表列表 Dictionary<object, object> detail = new Dictionary<object, object>(); detail.Add(entity.T_HR_EMPLOYEEOVERTIMEDETAILRD, null); listAutoDic.Add(new AutoDictionary { TableName = modelType, KeyValue = "CREATEUSERID", DataValue = submitData.ApprovalUser.UserID, DataText = submitData.ApprovalUser.UserName, Name = "CREATEUSERID" }); listAutoDic.Add(new AutoDictionary { TableName = modelType, KeyValue = "CREATEPOSTID", DataValue = submitData.ApprovalUser.PostID, DataText = submitData.ApprovalUser.PostName, Name = "CREATEPOSTID" }); listAutoDic.Add(new AutoDictionary { TableName = modelType, KeyValue = "CREATEDEPARTMENTID", DataValue = submitData.ApprovalUser.DepartmentID, DataText = submitData.ApprovalUser.DepartmentName, Name = "CREATEDEPARTMENTID" }); listAutoDic.Add(new AutoDictionary { TableName = modelType, KeyValue = "CREATECOMPANYID", DataValue = submitData.ApprovalUser.CompanyID, DataText = submitData.ApprovalUser.CompanyName, Name = "CREATECOMPANYID" }); } } } #endregion #endregion //auditInfo.ObjXml = metaData.TableToXml(yearNormDraft, null, auditInfo.SystemCode, auditInfo.ModelCode, listAutoDic);// 将Detail设置成了null string xml = meta.TableToXml(obj, null, "HR", modelType, listAutoDic); element = XElement.Parse(xml); //SMT.Portal.Common.MetaData metaData = new MetaData(); return element; }
public (IStatementResult, List <string>) AddNodeWithAll(IEntityBase entity, int deep = int.MaxValue) { var entityAtr = entity.GetType().GetCustomAttribute(typeof(RelationshipAttribute), true); if (entityAtr != null) { var propertiesWithAttribute = entity.GetType().GetProperties() .Select(pi => new { Property = pi.GetValue(entity) as IEntityBase, Attribute = pi.GetCustomAttributes(typeof(RelationshipAttribute), true).LastOrDefault() as RelationshipAttribute }).Where(x => x.Attribute != null).ToList(); var Out = propertiesWithAttribute.Where(x => x.Attribute.Direction != DIRECTION.OUTGOING).ToList().First(); var In = propertiesWithAttribute.Where(x => x.Attribute.Direction != DIRECTION.INCOMING).ToList().First(); var atrr = new RelationshipAttribute(); atrr.Direction = DIRECTION.OUTGOING; atrr.Name = (entityAtr as RelationshipAttribute).Name; var conditions1 = new Lazy <StringBuilder>(); var parameters1 = new Lazy <Dictionary <string, object> >(); bool firstNode1 = true; //foreach (PropertyInfo prop in entity.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) //{ // var ValueEntity = prop.GetValue(entity, null); // parameters1.Value[prop.Name] = ValueEntity; // if (firstNode1) // firstNode1 = false; // else // conditions1.Value.Append(","); // conditions1.Value.Append(string.Format("{0}:${0}", prop.Name)); //} var result1 = MergeRelationship(Out.Property.Uuid, In.Property.Uuid, atrr); //var result1 = MergeRelationship(Out.Property.Uuid, In.Property.Uuid, atrr, parameters1.Value); var ll = new List <string>() { Out.Property.Uuid, In.Property.Uuid }; return(result1, ll); } if (entity == null) { throw new ArgumentNullException("entity"); } bool firstNode = true; var parameters = new Lazy <Dictionary <string, object> >(); // new var referenceParameters = new List <(string, RelationshipAttribute, Dictionary <string, object>)>(); var conditions = new Lazy <StringBuilder>(); List <string> Uuids = new List <string>(); foreach (PropertyInfo prop in entity.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (prop.GetCustomAttribute(typeof(NotMappedAttribute), true) != null) { continue; } //if (prop.Name.Equals("Uuid", StringComparison.CurrentCultureIgnoreCase)) // continue; // new var ValueEntity = prop.GetValue(entity, null); var atr = prop.GetCustomAttribute(typeof(RelationshipAttribute), true); if (atr != null) { switch (ValueEntity) { case EntityBase obj: break; case IEnumerable <EntityBase> enumerable: if (enumerable.Count() != 0) { foreach (var obj in enumerable) { #if DEBUG Console.WriteLine($"object: {obj} in enumerable"); #endif if (deep > 0) { var objType = obj.GetType(); var objAtr = objType.GetCustomAttribute(typeof(RelationshipAttribute), true); if (objAtr == null) { var re = AddNodeWithAll(obj, deep - 1); var res = re.Item1.Summary.Statement.Parameters["Uuid"].ToString(); referenceParameters.Add((res, (RelationshipAttribute)atr, null)); } else { var propsDictionary = new Dictionary <string, object>(); foreach (PropertyInfo propaaa in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (propaaa.GetCustomAttribute(typeof(NotMappedAttribute), true) != null) { continue; } if (propaaa.Name.Equals("Uuid", StringComparison.CurrentCultureIgnoreCase)) { continue; } #if DEBUG Console.WriteLine($"Name: {propaaa.Name}; Type: {propaaa.PropertyType}; Value: {propaaa.GetValue(obj, null)}"); #endif var ValueEntityR = propaaa.GetValue(obj, null); var atrR = (RelationshipAttribute)propaaa.GetCustomAttribute(typeof(RelationshipAttribute), true); if (atrR != null) { if (atrR.Direction == DIRECTION.INCOMING) { var re = AddNodesThroughRelation((EntityBase)ValueEntityR); var res = re.Item1.Summary.Statement.Parameters["Uuid"].ToString(); referenceParameters.Add((res, (RelationshipAttribute)atr, propsDictionary)); for (var i = 0; i < re.Item2.Count; i++) { Uuids.Add(res); } } } propsDictionary[prop.Name] = ValueEntityR; } } } } } break; } continue; } parameters.Value[prop.Name] = ValueEntity; if (firstNode) { firstNode = false; } else { conditions.Value.Append(","); } conditions.Value.Append(string.Format("{0}:${0}", prop.Name)); } var query = $"MERGE @MERGE ON CREATE SET @ONCREATESET ON MATCH SET @ONMATCHSET RETURN @RETURN"; var MERGE = $@"(n:{entity.Label} {{ {nameof(entity.Uuid)}:""{parameters.Value["Uuid"]}"" }})"; var ONCREATESET = ParamsTostring(parameters.Value); var ONMATCHSET = ParamsTostring(parameters.Value, true); var RETURN = $"n"; query = query.Replace("@MERGE", MERGE); query = query.Replace("@ONCREATESET", ONCREATESET); query = query.Replace("@ONMATCHSET", ONMATCHSET); query = query.Replace("@RETURN", RETURN); IStatementResult result = ExecuteQuery(query.ToString(), parameters.Value); foreach (var rel in referenceParameters) { MergeRelationship(parameters.Value["Uuid"].ToString(), rel.Item1, rel.Item2); //CreateRelationship(parameters.Value["Uuid"].ToString(), rel.Item1, rel.Item2, rel.Item3); } //if (result.Summary.Counters.NodesCreated == 0) // throw new Exception("Node creation error!"); return(result, Uuids); }
private object Insert(string tableName, IEntityBase entity, bool insertPrimaryKey, bool upsert, bool merge) { log.Describe($"{nameof(Insert)} into: {tableName}", new { insertPrimaryKey, upsert, merge, entity }); var type = entity.GetType(); var columns = ReflectionUtil.GetColumnSchemas(type); var columnNames = new List <string>(columns.Count); var valuePlaceholders = new List <string>(columns.Count); var values = new List <object>(columns.Count); var query = new StringBuilder(columns.Count * 32); var pos = 0; PostgreSqlColumnSchema pk = null; foreach (var column in columns) { // don't insert PK if specified if (column.PrimaryKey) { pk = column; if (!insertPrimaryKey) { continue; } } var value = column.GetValue(entity); var defaultValue = value?.GetType().GetDefault(); if (column.Nullable && (merge && value == defaultValue)) { continue; } columnNames.Add('"' + column.Name + '"'); valuePlaceholders.Add("@" + pos++); values.Add(value); } query.Write($"INSERT INTO ") .WriteLine(ResolveTableName(tableName)) .WriteTabbedLine(1, $"({string.Join(", ", columnNames)})") .WriteTabbedLine(1, $"VALUES ({string.Join(", ", valuePlaceholders)})"); if (upsert && pk != null) { query.WriteTabbedLine(2, "ON CONFLICT (\"" + pk.Name + "\") DO UPDATE SET "); for (var i = 0; i < valuePlaceholders.Count; i++) { query.WriteTabbed(3, columnNames[i]) .Write(" = ") .Write(valuePlaceholders[i]) .WriteIf(i < valuePlaceholders.Count - 1, ",") .NewLine(); } } if (!insertPrimaryKey && pk != null) { query.WriteTabbedLine(2, "RETURNING \"" + pk.Name + '"'); } var result = db.QuerySingleValue(query.ToString(), values); return(result); }
private IMongoCollection <IEntityBase> GetCollection(IEntityBase entity) { Type type = entity.GetType(); return(collection = database.GetCollection <IEntityBase>(type.Name)); }
public static void ControlToEntity(Control ctl, IEntityBase entity, string attributeName) { Type typ = entity.GetType(); PropertyInfo pi = typ.GetProperty(attributeName, BindingFlags.Public | BindingFlags.Instance); object objValue = null; while (true) { if (ctl is DropDownList) { objValue = ((DropDownList)ctl).SelectedItem.Value; break; } if (ctl is HiddenField) { objValue = ((HiddenField)ctl).Value; break; } if (ctl is esdTextBox) { objValue = ((TextBox)ctl).Text; break; } if (ctl is CheckBox) { CheckBox objCtl = (CheckBox)ctl; objValue = objCtl.Checked ? ConstFlagEstado.ACTIVADO : ConstFlagEstado.DESACTIVADO; break; } if (ctl is esdMaskedTextBox) { objValue = ((esdMaskedTextBox)ctl).Text; break; } if (ctl is esdNumericTextBox) { objValue = ((esdNumericTextBox)ctl).Value; break; } if (ctl is esdDateTextBox) { objValue = DateTime.Parse(((esdDateTextBox)ctl).Text); break; } break; } object objDefVal = pi.GetValue(entity, null); object objNewValue = DataHelper.ChangeType(objValue, pi.PropertyType, objDefVal); pi.SetValue(entity, objNewValue, null); }
public string Resolve(string stringToResolve, IEntityBase dataSource) { StringBuilder resolved = new StringBuilder(); int index = 0; while (index != stringToResolve.Length - 1) { Match sequenceFound = controlSequenceFinder.Match(stringToResolve, index); if (!sequenceFound.Success) { break; } resolved.Append(ResolveTemplateContent(stringToResolve.Substring(index, sequenceFound.Index - index))); string controlSequence = sequenceFound.Groups["expression"].Value; string startTag = $"$([{controlSequence}]"; string endTag = $"$([end-{controlSequence}])"; int length = sequenceFound.Length; index = sequenceFound.Index; int nestedSequences = Count(stringToResolve.Substring(index + startTag.Length, length - startTag.Length), startTag); int endIndex = index + length; while (nestedSequences > 0) { int newEnd = stringToResolve.Substring(endIndex) .IndexOf(endTag, StringComparison.OrdinalIgnoreCase); if (newEnd < 0) { throw new ControlSequenceEndTagNotFoundException(controlSequence); } newEnd = endIndex + newEnd; //Find nested tags between last end tag and this end tag nestedSequences += Count(stringToResolve.Substring(endIndex, newEnd - endIndex), startTag); nestedSequences--; endIndex = newEnd + endTag.Length; } Match controlSequenceDataMatch = greedyContentFinder.Match(stringToResolve, index, endIndex - index); if (!controlSequenceDataMatch.Success) { throw new InvalidOperationException("Should not happen"); } resolved.Append(ResolveControlSequence(controlSequenceDataMatch.Groups["expression"].Value, controlSequenceDataMatch.Groups["parameter"].Value, controlSequenceDataMatch.Groups["content"].Value)); if (controlSequenceDataMatch.Value.Contains('\n')) { Match newlineMatch = newlineSearcher.Match(stringToResolve, endIndex); if (newlineMatch.Success && newlineMatch.Index == endIndex) { endIndex += newlineMatch.Length; } } index = endIndex; } resolved.Append(ResolveTemplateContent(stringToResolve.Substring(index))); return(resolved.ToString()); string ResolveControlSequence(string sequence, string parameter, string content) { switch (sequence.ToUpperInvariant()) { case "IF-EXIST": return(IfSequence(IfExistCondition)); case "IF-SPECIFIED": return(IfSequence(IfSpecifiedCondition)); case "FOREACH": return(ForeachSequence()); case "NO-DUPLICATE-LINES": return(RemoveDuplicateLinesSequence()); default: throw new UnrecognizedControlSequenceException(sequence); } string RemoveDuplicateLinesSequence() { if (!string.IsNullOrEmpty(parameter)) { throw new NoDuplicateLinesParameterMismatchException(); } string[] lines = (Resolve(content, dataSource)).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); return(string.Join(Environment.NewLine, lines.Distinct()) + Environment.NewLine); } string IfSequence(Func <bool> conditionCheck) { if (string.IsNullOrEmpty(parameter)) { throw new IfSequenceParameterMismatchException(); } bool condition = conditionCheck(); return(IfResult(condition)); } bool IfExistCondition() { CommandDefinition definition = dataSource.Value <CommandDefinition>(); Argument argument = definition?.Argument <Argument>(parameter); return(argument != null || dataSource.HasContent(parameter)); } bool IfSpecifiedCondition() { CommandDefinition definition = dataSource.Value <CommandDefinition>(); Argument argument = definition?.Argument <Argument>(parameter); bool specified; if (argument != null) { specified = argument.IsDefined; } else { specified = dataSource.HasContent(parameter) && !string.IsNullOrEmpty(dataSource[parameter].Value <string>()); } return(specified); } string IfResult(bool condition) { string result = string.Empty; string[] elseSplit = content.Split(new[] { "$([else])" }, StringSplitOptions.RemoveEmptyEntries); if (condition) { result = Resolve(elseSplit[0], dataSource); } else if (elseSplit.Length == 2) { result = Resolve(elseSplit[1], dataSource); } return(result); } string ForeachSequence() { StringBuilder foreachResult = new StringBuilder(); if ((content.StartsWith("\n", StringComparison.Ordinal) || content.StartsWith("\r\n", StringComparison.Ordinal)) && (content.EndsWith("\n", StringComparison.Ordinal) || content.EndsWith("\r\n", StringComparison.Ordinal))) { //This would leads to unwanted empty lines content = content.TrimStart('\r').TrimStart('\n'); } string[] nameSplit = parameter.Split(new[] { "[in]" }, StringSplitOptions.RemoveEmptyEntries); if (nameSplit.Length != 2) { throw new ForeachSequenceParameterMismatchException(parameter); } string elementName = nameSplit[0].Trim(); string[] ofTypeSplit = nameSplit[1].Split(new[] { "[of-type]" }, StringSplitOptions.RemoveEmptyEntries); string splitPart = ofTypeSplit.Length == 2 ? ofTypeSplit[1] : ofTypeSplit[0]; string[] split = splitPart.Split(new[] { "[split]" }, StringSplitOptions.RemoveEmptyEntries); string collection = ofTypeSplit.Length == 2 ? ofTypeSplit[0].Trim() : split[0].Trim(); string filter = string.Empty; string splitSize = split.Length == 2 ? split[1].Trim() : string.Empty; if (!int.TryParse(splitSize, out int chunksize)) { chunksize = -1; } if (ofTypeSplit.Length == 2) { filter = split.Length == 2 ? split[0].Trim() : ofTypeSplit[1].Trim(); } string[] path = collection.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); IEnumerable <Entity> data = ResolveRecursively(path); if (!string.IsNullOrEmpty(filter)) { data = data.Where(TemplateEqualsFilter); } ForeachItemContainer container = new ForeachItemContainer(elementName); if (chunksize > 0) { var query = data.Select((entity, idx) => new { idx, entity }); IEnumerable <IEnumerable <Entity> > dataChunks = query.GroupBy(x => x.idx / chunksize, a => a.entity); using (dataSource.AddTemporaryDataSource(container)) using (dataSource.SkipCaching(elementName)) { foreach (IEnumerable <Entity> chunk in dataChunks) { using (dataSource.SkipCaching(EntityKeys.ChunkStartKey)) using (dataSource.SkipCaching(EntityKeys.ChunkEndKey)) { string start = data.TakeWhile(x => !x.Equals(chunk.FirstOrDefault())).Count().ToString(CultureInfo.InvariantCulture); string end = data.TakeWhile(x => !x.Equals(chunk.LastOrDefault())).Count().ToString(CultureInfo.InvariantCulture); if (dataSource is Entity) { Entity dataSourceEntity = dataSource as Entity; container.Current = dataSourceEntity.Create(Guid.NewGuid().ToByteString(), chunk); using (container.Current.AddTemporaryDataSource(new DataChunk(start, end))) foreachResult.Append(Resolve(content, dataSource)); } else { throw new FormattableException($"The datasource should be an entity but is of type {dataSource.GetType()}"); } } } } } else { using (dataSource.AddTemporaryDataSource(container)) using (dataSource.SkipCaching(elementName)) { foreach (Entity entity in data) { container.Current = entity; foreachResult.Append(Resolve(content, dataSource)); } } } return(foreachResult.ToString()); bool TemplateEqualsFilter(Entity entity) { return(entity.Template().TemplateNames(repository) .Any(n => n.Equals(filter, StringComparison.OrdinalIgnoreCase))); } } } string ResolveTemplateContent(string resolvable) { string result = resolvable; Match controlSequenceMatch = templateAccessRegex.Match(resolvable); while (controlSequenceMatch.Success) { string content = controlSequenceMatch.Groups["content"].Value; if (content.StartsWith("[", StringComparison.Ordinal) && content.EndsWith("]", StringComparison.Ordinal)) { throw new WildControlSequenceException(content); } string[] path = content.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); string value = (ResolveRecursively(path)).Value <string>(); if (controlSequenceMatch.Groups["text_control"].Success) { string textControlSequence = controlSequenceMatch.Groups["text_control"].Value; textControlSequence = textControlSequence.Substring(0, textControlSequence.Length - 1); value = ResolveTextControlSequences(value, textControlSequence); } result = result.Replace(controlSequenceMatch.Value, value); controlSequenceMatch = controlSequenceMatch.NextMatch(); } return(result); } IEntityBase ResolveRecursively(string[] path) { IEntityBase current = dataSource; foreach (string part in path) { current = current[part]; if (current.HasValue <string>()) { string value = Resolve(current.Value <string>(), current); current.SetValue(value); } } return(current); } int Count(string data, string substring) { return((data.Length - data.Replace(substring, string.Empty).Length) / substring.Length); } }
/// <summary> /// 获取填充xml /// </summary> /// <param name="obj">要填充的实体</param> /// <param name="modelCode">实体名称</param> /// <returns>返回xml</returns> public XElement GetFullXml(IEntityBase obj, string modelCode, SubmitData submitData) { XElement element = null; Metadata meta = new Metadata(); string modelType = string.Empty; if (!string.IsNullOrEmpty(modelCode)) { modelType = modelCode.ToUpper(); } else { modelType = obj.GetType().Name; } List <AutoDictionary> listAutoDic = new List <AutoDictionary>(); string strMainKey = string.Empty; string strMainValue = string.Empty; CommonBLL bll = new CommonBLL(""); #region 处理元数据 #region " T_HR_EMPLOYEEOVERTIMERECORD " if (modelType.ToUpper() == Constants.T_HR_EMPLOYEEOVERTIMERECORD) { strMainKey = "OVERTIMERECORDID"; strMainValue = string.Empty; Type objtype = obj.GetType(); PropertyInfo[] propinfos = objtype.GetProperties(); foreach (PropertyInfo propinfo in propinfos) { string keyValue = propinfo.GetValue(obj, null) != null?propinfo.GetValue(obj, null).ToString() : string.Empty; if (propinfo.Name == strMainKey) { strMainValue = keyValue; } } if (obj is T_HR_EMPLOYEEOVERTIMERECORD) { T_HR_EMPLOYEEOVERTIMERECORD entity = obj as T_HR_EMPLOYEEOVERTIMERECORD; if (submitData.SubmitFlag != SubmitFlag.New && submitData.ApprovalResult == ApprovalResult.NoPass) { var overtimeDetail = bll.Query <T_HR_EMPLOYEEOVERTIMERECORD>().Where(w => w.OVERTIMERECORDID == strMainValue).ToList(); //Dictionary<object, object> detail = new Dictionary<object, object>(); //detail.Add(overtimeDetail, null);//normItemConfigList 是2级从表列表 Dictionary <object, object> detail = new Dictionary <object, object>(); detail.Add(entity.T_HR_EMPLOYEEOVERTIMEDETAILRD, null); listAutoDic.Add(new AutoDictionary { TableName = modelType, KeyValue = "CREATEUSERID", DataValue = submitData.ApprovalUser.UserID, DataText = submitData.ApprovalUser.UserName, Name = "CREATEUSERID" }); listAutoDic.Add(new AutoDictionary { TableName = modelType, KeyValue = "CREATEPOSTID", DataValue = submitData.ApprovalUser.PostID, DataText = submitData.ApprovalUser.PostName, Name = "CREATEPOSTID" }); listAutoDic.Add(new AutoDictionary { TableName = modelType, KeyValue = "CREATEDEPARTMENTID", DataValue = submitData.ApprovalUser.DepartmentID, DataText = submitData.ApprovalUser.DepartmentName, Name = "CREATEDEPARTMENTID" }); listAutoDic.Add(new AutoDictionary { TableName = modelType, KeyValue = "CREATECOMPANYID", DataValue = submitData.ApprovalUser.CompanyID, DataText = submitData.ApprovalUser.CompanyName, Name = "CREATECOMPANYID" }); } } } #endregion #endregion //auditInfo.ObjXml = metaData.TableToXml(yearNormDraft, null, auditInfo.SystemCode, auditInfo.ModelCode, listAutoDic);// 将Detail设置成了null string xml = meta.TableToXml(obj, null, "HR", modelType, listAutoDic); element = XElement.Parse(xml); //SMT.Portal.Common.MetaData metaData = new MetaData(); return(element); }
public static object GetValueFromAttribute(IEntityBase entity, string attributeName) { Type typ = entity.GetType(); PropertyInfo pi = typ.GetProperty(attributeName, BindingFlags.Public | BindingFlags.Instance); object objValue = pi.GetValue(entity, null); return objValue; }