public void AddRelation(EntityRelation relation)
        {
            var key = GetRelationKey(relation.LeftEntity, relation.RightEntity, relation.Role);
            Relations.Add(key, relation);
            Definitions[relation.LeftEntity].Relations.Add(relation);
            Definitions[relation.RightEntity].Relations.Add(relation);

            RelationsKeyHash.Add(string.Format("{0}_{1}", relation.LeftEntity, relation.Role), key);
            RelationsKeyHash.Add(string.Format("{0}_{1}", relation.RightEntity, relation.Role), key);
        }
        public void LeftJoin_InferredWithMatchingSourceAndRelationProperties_MatchesExpected()
        {
            var relations =
                new EntityRelationSet <DataRow>()
                .LeftJoin(row => row.Related.RelatedId, row => row.DependencyEntity.ComplexEntityId)
                .Relations;

            var expected = new EntityRelation(EntityRelationType.LeftJoin);

            expected.Join <FakeRelatedRow, DependencyRow>(row => row.RelatedId, row => row.ComplexEntityId);

            Assert.IsNotNull(relations.FirstOrDefault(x => expected == (EntityRelation)x));
        }
        public void LeftJoin_EntityRelationSetWithTwoExternalRelations_MatchesExpected()
        {
            var relations = new EntityRelationSet <DataRow>().LeftJoin <FakeRelatedRow, DependencyRow>(
                row => row.RelatedId,
                row => row.FakeDependencyEntityId,
                "Alias").Relations;

            var expected = new EntityRelation(EntityRelationType.LeftJoin);

            expected.Join <FakeRelatedRow, DependencyRow>(row => row.RelatedId, row => row.FakeDependencyEntityId, null, "Alias");

            Assert.IsNotNull(relations.FirstOrDefault(x => expected == (EntityRelation)x));
        }
        public EntityRelationResponse Create(EntityRelation relation)
        {
            EntityRelationResponse response = new EntityRelationResponse();

            response.Timestamp = DateTime.UtcNow;
            response.Object    = relation;
            response.Errors    = ValidateRelation(relation, ValidationType.Create);
            if (response.Errors.Count > 0)
            {
                response.Success = false;
                response.Message = "The entity relation was not created. Validation error occurred!";
                return(response);
            }

            try
            {
                var storageRelation = relation.MapTo <DbEntityRelation>();

                if (storageRelation.Id == Guid.Empty)
                {
                    storageRelation.Id = Guid.NewGuid();
                }

                var success = DbContext.Current.RelationRepository.Create(storageRelation);

                if (success)
                {
                    response.Success = true;
                    response.Message = "The entity relation was successfully created!";
                    return(response);
                }
                else
                {
                    response.Success = false;
                    response.Message = "The entity relation was not created! An internal error occurred!";
                    return(response);
                }
            }
            catch (Exception e)
            {
                response.Success   = false;
                response.Object    = relation;
                response.Timestamp = DateTime.UtcNow;
#if DEBUG
                response.Message = e.Message + e.StackTrace;
#else
                response.Message = "The entity relation was not created. An internal error occurred!";
#endif
                return(response);
            }
        }
Beispiel #5
0
 public static EntityRelationModel ToEntityRelationModel(this EntityRelation r)
 {
     return(new EntityRelationModel()
     {
         Name = r.Name,
         MetaType = new MetaTypInfoModel
         {
             Id = r.MetaType.MetaTypeId,
             Name = r.MetaType.Name
         },
         Minimum = r.Minimum,
         Maximum = r.Maximum
     });
 }
        public CommentView ToViewSimple(EntityRelation relation)
        {
            var view = new CommentView();

            this.ApplyToBaseView(relation, view);
            view.createUserId = -relation.entityId2;
            view.content      = relation.value;
            view.parentId     = relation.entityId1;

            //Assume (bad assume!) that these are OK values... we don't know if edit is even supported?
            view.editUserId = view.createUserId;
            view.editDate   = view.createDate;

            return(view);
        }
        protected async Task <EntityPackage> ModifyCheckAsync(EntityRelation existing, Requester requester)
        {
            //Go find the parent. If it's not content, BAD BAD BAD
            var parent = await BasicParentCheckAsync(existing.entityId1, requester);

            var uid = requester.userId;

            //Only the owner (and super users) can edit (until wee get permission overrides set up)
            if (existing.entityId2 != -uid && !services.permissions.IsSuper(requester))
            {
                throw new ForbiddenException($"Cannot update comment {existing.id}");
            }

            return(parent);
        }
Beispiel #8
0
        public override IDesignModel GenerateDesignModel(IXmlElement xmlElement, DesignModelParseContext context)
        {
            var sourceEntity = (Entity)context.DesignModel;
            var name         = xmlElement.GetStringAttributeValue("name");
            var relation     = new EntityRelation(name, xmlElement, xmlElement.ParseLocation)
            {
                Source = sourceEntity,
                DestinationReference = new ClassModelReference(xmlElement.GetStringAttributeValue("destination"),
                                                               sourceEntity.Namespace, sourceEntity.Type, xmlElement.ParseLocation)
            };

            sourceEntity.AddOutgoingRelation(relation);

            // Don't register this design model globally.
            return(null);
        }
        public EntityRelation GetRelation(Enum id, IEnumerable <EntityRelation> relations)
        {
            var relation = relations.FirstOrDefault(x => x.type == keys[id]);

            if (relation == null)
            {
                relation = new EntityRelation()
                {
                    type = keys[id], value = null
                }
            }
            ;

            return(relation);
        }
    }
        public void LeftJoin_InferredWithMatchingRelationProperty_MatchesExpected()
        {
            var relations =
                new EntityRelationSet <DataRow>()
                .LeftJoin(row => row.FakeDataId, row => row.Related.FakeDataId)
                ////.InnerJoin(row => row.Related, row => row.DependencyEntity, row => row.RelatedId, row => row.ComplexEntityId)
                ////.InnerJoin(row => row.OtherAlias, row => row.FakeDataId, row => row.FakeDataId)
                ////.InnerJoin(row => row.OtherAlias, row => row.RelatedDependency, row => row.RelatedId, row => row.ComplexEntityId)
                ////.InnerJoin(row => row.RelatedAlias, row => row.FakeDataId, row => row.FakeDataId)
                .Relations;

            var expected = new EntityRelation(EntityRelationType.LeftJoin);

            expected.Join <DataRow, FakeRelatedRow>(row => row.FakeDataId, row => row.FakeDataId);

            Assert.IsNotNull(relations.FirstOrDefault(x => expected == (EntityRelation)x));
        }
            public AutoTreeChangeNotify(
                IEntityBase oTarget,
                EntityTreeChange enChange,
                IEntityBase oParentEntity,
                IEntityBase oChildEntity,
                EntityRelation enParentChildRelation,
                object oAdditionalInfo)
            {
                m_oTarget = oTarget;

                m_oChangeInfo = m_oTarget.PreTreeChange(
                    enChange,
                    oParentEntity,
                    oChildEntity,
                    enParentChildRelation,
                    oAdditionalInfo);
            }
Beispiel #12
0
        public void ApplyFromEditView(IEditView view, EntityPackage package, string type)
        {
            ApplyFromBaseView(view, package.Entity);

            package.Entity.type = type;

            var relation = new EntityRelation()
            {
                entityId1  = view.createUserId,
                entityId2  = view.id,
                type       = Keys.CreatorRelation,
                value      = view.editUserId.ToString(),
                createDate = view.editDate
            };

            package.Add(relation);
        }
Beispiel #13
0
        public EntityRelationResponse Update(EntityRelation relation)
        {
            EntityRelationResponse response = new EntityRelationResponse();

            response.Timestamp = DateTime.UtcNow;
            response.Object    = relation;
            response.Errors    = ValidateRelation(relation, ValidationType.Update);
            if (response.Errors.Count > 0)
            {
                response.Success = false;
                response.Message = "The entity relation was not updated. Validation error occurred!";
                return(response);
            }

            try
            {
                var storageRelation = relation.MapTo <IStorageEntityRelation>();//ConvertToStorage(relation);
                var success         = relationRepository.Update(storageRelation);

                if (success)
                {
                    response.Success = true;
                    response.Message = "The entity relation was successfully updated!";
                    return(response);
                }
                else
                {
                    response.Success = false;
                    response.Message = "The entity relation was not updated! An internal error occurred!";
                    return(response);
                }
            }
            catch (Exception e)
            {
                response.Success   = false;
                response.Object    = relation;
                response.Timestamp = DateTime.UtcNow;
#if DEBUG
                response.Message = e.Message + e.StackTrace;
#else
                response.Message = "The entity relation was not updated. An internal error occurred!";
#endif
                return(response);
            }
        }
        public EntityTreeChangeInfo PostTreeChange(
            EntityTreeChange enChange,
            IEntityBase oParentEntity,
            IEntityBase oChildEntity,
            EntityRelation enParentChildRelation,
            object oAdditionalInfo)
        {
            EntityTreeChangeInfo oChangeInfo = new EntityTreeChangeInfo(
                enChange,
                oParentEntity,
                oChildEntity,
                enParentChildRelation,
                oAdditionalInfo);

            PostTreeChange(oChangeInfo);

            return(oChangeInfo);
        }
Beispiel #15
0
        public void TestCommentConvertSIMPLE()
        {
            var service = CreateService <CommentViewSource>();

            //Do it the OTHER way since we're only testing the "simple" portion.
            var relation = new EntityRelation()
            {
                entityId1  = 4,
                entityId2  = -6,
                value      = "wow",
                type       = Keys.CommentHack,
                createDate = DateTime.Now
            };

            var temp      = service.ToViewSimple(relation);
            var relation2 = service.FromViewSimple(temp);

            Assert.Equal(relation, relation2);
        }
        static public EntityRelation BuildEntityRelation(EntityRow parentRow, string relationString)
        {
            EntityRelation entityRelation;

#if SILVERLIGHT //避免PolicyBuilder當掉無法編輯
            try
            {
                entityRelation = string.IsNullOrEmpty(relationString) ? new EntityRelation() : transfer.ToObject <EntityRelation>(relationString);
            }
            catch
            {
                entityRelation = new EntityRelation();
            }
#else
            entityRelation = string.IsNullOrEmpty(relationString) ? new EntityRelation() : transfer.ToObject <EntityRelation>(relationString);
#endif
            entityRelation.SetParent(parentRow.Table.Namespace, parentRow.Table.TableName);
            return(entityRelation);
        }
Beispiel #17
0
        public EntityRelation GetRelation(string entity, string role)
        {
            string relKey = null;

            if (!RelationsKeyHash.TryGetValue(string.Format("{0}_{1}", entity, role), out relKey))
            {
                return(null);
            }

            EntityRelation relation = null;

            if (Relations.TryGetValue(relKey, out relation))
            {
                return(relation);
            }
            else
            {
                return(null);
            }
        }
        public void InnerJoin_WithRelationAlias_MatchesExpected()
        {
            var relations = new EntityRelationSet <DataRow>()
                            ////.InnerJoin<FakeRelatedRow>(row => row.FakeDataId, row => row.FakeDataId)
                            ////.InnerJoin<FakeRelatedRow, DependencyRow>(row => row.RelatedId, row => row.ComplexEntityId)
                            .InnerJoin <FakeRelatedRow>(row => row.FakeDataId, row => row.FakeDataId, "OtherAlias")
                            ////.InnerJoin<FakeRelatedRow, DependencyRow>(
                            ////    row => row.RelatedId,
                            ////    "OtherAlias",
                            ////    row => row.ComplexEntityId,
                            ////    "RelatedDependency")
                            ////.InnerJoin<FakeRelatedRow>(row => row.FakeDataId, row => row.FakeDataId, "RelatedAlias")
                            .Relations;

            var expected = new EntityRelation(EntityRelationType.InnerJoin);

            expected.Join <DataRow, FakeRelatedRow>(row => row.FakeDataId, row => row.FakeDataId, null, "OtherAlias");

            var actual = relations.FirstOrDefault();

            Assert.AreEqual(expected, actual);
        }
Beispiel #19
0
        private string[] createQuoteSectionAndAssessment(IMTDService service, BaseExtendable m_project, EntityVersion newVersion, string projName, string projDescription)
        {
            //Quote section
            string[]       returnValue = new string[4];
            BaseExtendable newQuote    = new BaseExtendable(Code.Find(AppCodes.QUOTE_TARGET_TYPE).CID);

            newQuote.Description = projName;
            service.Store(newQuote);


            newVersion.Target_IID      = newQuote.Entity_IID;
            newVersion.Target_Type_CID = Code.Find(AppCodes.QUOTE_TARGET_TYPE);
            newVersion.Version         = "1.0";
            newVersion.Released        = true;
            service.Store(newVersion);

            EntityRelation newRelation = new EntityRelation(Code.Find(AppCodes.QUOTE_TARGET_TYPE));

            newRelation.Entity_IID_1         = m_project.Entity_IID;
            newRelation.Entity_IID_2         = newQuote.Entity_IID;
            newRelation.Entity_2_Version_IID = newVersion.Entity_Version_IID;
            returnValue[0] = Convert.ToString(newVersion.Entity_Version_IID);
            service.Store(newRelation);

            //Assessment
            BaseExtendable newAssessment = new BaseExtendable(Code.Find(AppCodes.ASSESSMENT_TARGET_TYPE).CID);

            newAssessment.Description = projName;
            service.Store(newAssessment);

            EntityRelation newRelation2 = new EntityRelation(Code.Find(AppCodes.ASSESSMENT_TARGET_TYPE));

            newRelation2.Entity_IID_1 = m_project.Entity_IID;
            newRelation2.Entity_IID_2 = newAssessment.Entity_IID;
            returnValue[1]            = Convert.ToString(newAssessment.Entity_IID);
            service.Store(newRelation2);

            return(returnValue);
        }
Beispiel #20
0
            /// <summary>
            /// 添加实体关系
            /// </summary>
            public void AddEntityRelation(string entityA, string relationship, string entityB)
            {
                if (entityA == entityB)
                {
                    return;
                }
                EntityRelation entityRelationA = FindParent(entityA);

                if (entityRelationA == null)
                {
                    entityRelationA        = new EntityRelation();
                    entityRelationA.A      = entityA;
                    entityRelationA.Weight = 0.1;
                    _entityIndex.Add(entityA, entityRelationA);
                }

                EntityRelation entityRelationB = FindParent(entityB);

                if (entityRelationB == null)
                {
                    EntityRelation childEntity = new EntityRelation();
                    childEntity.Weight       = 0.1;
                    childEntity.Relationship = relationship;
                    childEntity.A            = entityB;
                    entityRelationA.AddChild(childEntity);
                    _entityIndex.Add(entityB, childEntity);
                }
                else
                {
                    //entityRelationB.AddChild(childEntity);
                    entityRelationB.Weight += 0.1;
                }

                eeFragment.AddDocument(relationship, new[] { entityA, entityB });
                arFragment.AddDocument(entityB, new[] { entityA, relationship });
                brFragment.AddDocument(entityA, new[] { entityB, relationship });
            }
        static public bool TryGetTable <TEntity>(this IEntityTableSource it, out EntityTableProxy <TEntity> tableProxy, string ns, string tableName, params string[] keys)
        {
            var selectCond = new EntityRelation(ns, tableName, keys);

            return(it.TryGetTable(selectCond, out tableProxy));
        }
        static EntityDatabaseWriterInsert()
        {
            EntityContextConfiguration <TEntityContext> configuration = EntityContextConfiguration.GetConfiguration <TEntityContext>();

            Type typeEntity         = typeof(TEntity);
            Type typeEntityCallBack = typeof(TEntityCallBack);

            PropertyInfo key = configuration.EntityKeys.GetPropEntityKey(typeEntity);

            PropertyInfo[] entityCallBackProperties = typeEntityCallBack.GetEntityAcceptableDataProperties().ToArray();

            #region Generate CallBackData Setter

            #region Expression Tree
#if ET
            {
                int counter = 0;
                int index   = 0;
                int resize  = 0;

                Type typeData      = EntityProxy <TEntity> .DataType;
                Type typeProxyData = typeof(EntityProxy <,>).MakeGenericType(new[] { typeEntity, typeData });

                Type typeEntitySet = typeof(EntitySet <>).MakeGenericType(typeEntity);

                MethodInfo propEntitySetGetMthd = typeEntity.GetProperty("EntitySet", typeEntitySet).GetGetMethod(true);
                MethodInfo mthdOnPropChng       = typeEntity.GetMethod("OnPropertyChanged", BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(string) }, null);
                MethodInfo propDataGetMthd      = typeEntity.GetProperty("Data", BindingFlags.NonPublic | BindingFlags.Instance).GetGetMethod(true);
                FieldInfo  fldItem = typeProxyData.GetField("item");

                ParameterExpression dr = Expression.Parameter(typeof(SqlDataReader), "dr");
                ParameterExpression e  = Expression.Parameter(typeof(TEntity), "e");

                Expression[] expressions = new Expression[(entityCallBackProperties.Length + 1) * 2];

                //key expressions

                expressions[counter++] = Expression.Assign(Expression.Field(Expression.Field(Expression.TypeAs(Expression.Call(e, propDataGetMthd), typeProxyData), fldItem), typeData.GetField(key.Name)), Expression.Call(key.GetDataReaderGetValueMethod(), dr, Expression.Constant(index++)));
                expressions[counter++] = Expression.Call(e, mthdOnPropChng, Expression.Constant(key.Name));

                foreach (PropertyInfo propCallBack in entityCallBackProperties)
                {
                    PropertyInfo   propEntity     = typeEntity.GetProperty(propCallBack.Name);
                    EntityRelation entityRelation = configuration.EntityRelations.GetEntityRelation(propEntity);

                    if (entityRelation == null)
                    {
                        expressions[counter++] = Expression.Assign(Expression.Field(Expression.Field(Expression.TypeAs(Expression.Call(e, propDataGetMthd), typeProxyData), fldItem), typeData.GetField(propCallBack.Name)), Expression.Call(propCallBack.GetDataReaderGetValueMethod(), dr, Expression.Constant(index++)));
                        expressions[counter++] = Expression.Call(e, mthdOnPropChng, Expression.Constant(propCallBack.Name));
                    }
                    else
                    {
                        Type typeEditedEntity   = typeof(EditedEntity <,>).MakeGenericType(typeEntity, propCallBack.PropertyType);
                        Type typeEditedProperty = typeof(EditedProperty <>).MakeGenericType(propCallBack.PropertyType);

                        ConstructorInfo ctrEdtdProp = typeEditedProperty.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(PropertyInfo), propCallBack.PropertyType, propCallBack.PropertyType }, null);
                        ConstructorInfo ctrEdtdEnty = typeEditedEntity.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeEditedProperty, typeof(TrakMode) }, null);

                        Expression expNewEdtdProp = Expression.New(ctrEdtdProp, new Expression[] { Expression.Constant(propEntity), Expression.Field(Expression.Field(Expression.TypeAs(Expression.Call(e, propDataGetMthd), typeProxyData), fldItem), typeData.GetField(propCallBack.Name)), Expression.Call(propCallBack.GetDataReaderGetValueMethod(), dr, Expression.Constant(index++)) });
                        Expression expNewEdtdEnty = Expression.New(ctrEdtdEnty, new Expression[] { expNewEdtdProp, Expression.Constant(TrakMode.None) });

                        MethodInfo mthdCallBack = typeof(EntitySet <TEntity>).GetMethod("CallBack", BindingFlags.NonPublic | BindingFlags.Instance).MakeGenericMethod(propCallBack.PropertyType);

                        expressions[counter++] = Expression.Call(Expression.Call(e, propEntitySetGetMthd), mthdCallBack, new[] { e, expNewEdtdEnty });

                        resize++;
                    }
                }

                if (resize > 0)
                {
                    Array.Resize(ref expressions, expressions.Length - resize);
                }

                SetCallBackData = Expression.Lambda <Action <SqlDataReader, TEntity> >(Expression.Block(expressions), dr, e).Compile();
            }
#endif
            #endregion Expression Tree

            #region IL
#if IL
            {
            }
#endif
            #endregion IL

            #endregion Generate CallBackData Setter
        }
 public void AddChild(EntityRelation relation)
 {
     //BUG:如果存在则需要修改权值
     if (!_children.Contains(relation))
     {
         _children.Add(relation);
         return;
     }
 }
 static public string ToEntityRelationString(EntityRelation entityRelation)
 {
     return(transfer.ToText(entityRelation));
 }
            /// <summary>
            /// 添加实体关系
            /// </summary>
            public void AddEntityRelation(string entityA, string relationship, string entityB)
            {
                if (entityA == entityB)
                {
                    return;
                }
                EntityRelation entityRelationA = FindParent(entityA);
                if (entityRelationA == null)
                {
                    entityRelationA = new EntityRelation();
                    entityRelationA.A = entityA;
                    entityRelationA.Weight = 0.1;
                    _entityIndex.Add(entityA, entityRelationA);
                }

                EntityRelation entityRelationB = FindParent(entityB);
                if (entityRelationB == null)
                {
                    EntityRelation childEntity = new EntityRelation();
                    childEntity.Weight = 0.1;
                    childEntity.Relationship = relationship;
                    childEntity.A = entityB;
                    entityRelationA.AddChild(childEntity);
                    _entityIndex.Add(entityB, childEntity);
                }
                else
                {
                    //entityRelationB.AddChild(childEntity);
                    entityRelationB.Weight += 0.1;
                }

                eeFragment.AddDocument(relationship, new[] { entityA, entityB });
                arFragment.AddDocument(entityB, new[] { entityA, relationship });
                brFragment.AddDocument(entityA, new[] { entityB, relationship });
            }
 protected IStorageEntityRelation CreateEmptyEntityRelationObject(EntityRelation relation)
 {
     var storageService = service.StorageService;
     return storageService.GetObjectFactory().CreateEmptyEntityRelationObject();
 }
Beispiel #27
0
        public EntityRelationResponse Create(EntityRelation relation)
        {
            EntityRelationResponse response = new EntityRelationResponse();

            response.Timestamp = DateTime.UtcNow;
            response.Object    = relation;

            bool hasPermisstion = SecurityContext.HasMetaPermission();

            if (!hasPermisstion)
            {
                response.StatusCode = HttpStatusCode.Forbidden;
                response.Success    = false;
                response.Message    = "User have no permissions to manipulate erp meta.";
                response.Errors.Add(new ErrorModel {
                    Message = "Access denied."
                });
                return(response);
            }

            response.Errors = ValidateRelation(relation, ValidationType.Create);
            if (response.Errors.Count > 0)
            {
                response.Success = false;
                response.Message = "The entity relation was not created. Validation error occurred!";
                return(response);
            }

            try
            {
                var storageRelation = relation.MapTo <DbEntityRelation>();

                if (storageRelation.Id == Guid.Empty)
                {
                    storageRelation.Id = Guid.NewGuid();
                }

                var success = DbContext.Current.RelationRepository.Create(storageRelation);
                Cache.ClearRelations();
                if (success)
                {
                    response.Success = true;
                    response.Message = "The entity relation was successfully created!";
                    return(response);
                }
                else
                {
                    response.Success = false;
                    response.Message = "The entity relation was not created! An internal error occurred!";
                    return(response);
                }
            }
            catch (Exception e)
            {
                Cache.ClearRelations();
                response.Success   = false;
                response.Object    = relation;
                response.Timestamp = DateTime.UtcNow;
#if DEBUG
                response.Message = e.Message + e.StackTrace;
#else
                response.Message = "The entity relation was not created. An internal error occurred!";
#endif
                return(response);
            }
        }
Beispiel #28
0
 public static string GetTableFor(EntityRelation relation)
 {
     return(string.Format("{0}_{1}_{2}", relation.LeftEntity, relation.RightEntity, relation.Role));
 }
Beispiel #29
0
        private void CopyEntityProperties(object sourceObject, string entityTypeName)
        {
            Type entityType;
            if (!this.entityTypeMap.ContainsKey(entityTypeName))
                this.entityTypeMap.Add(entityTypeName, this.destinationContext.GetEntityType(entityTypeName));
            entityType = this.entityTypeMap[entityTypeName];

            if (!this.entityPropertyMap.ContainsKey(entityTypeName))
                this.entityPropertyMap.Add(entityTypeName, new List<EntityRelation>());
            var entityProperties = this.entityPropertyMap[entityTypeName];

            var entity = this.destinationContext.CreateEntityInstance(entityType);

            foreach (var propertyInfo in sourceObject.GetType().GetProperties())
            {
                var entityProperty = entityProperties.Where(x => x.EntityProperty == propertyInfo).SingleOrDefault();
                if (entityProperty == null)
                {
                    var propertyRelationType = GetPropertyRelationType(propertyInfo);
                    entityProperty = new EntityRelation()
                    {
                        EntityProperty = propertyInfo,
                        PropertyEntityType = propertyInfo.PropertyType.IsGenericType ?
                                            propertyInfo.PropertyType.GetGenericArguments()[0] :
                                            propertyInfo.PropertyType,
                        PropertyRelationType = propertyRelationType
                    };
                }
                if (!entityProperties.Contains(entityProperty))
                    entityProperties.Add(entityProperty);

                if (entityProperty.PropertyRelationType == PropertyRelationType.Column)
                {
                    var propertyValue = propertyInfo.GetValue(sourceObject, null);
                    if (propertyValue != null)
                    {
                        this.destinationContext.SetProperty(entity, propertyInfo.Name, propertyValue);
                    }
                }
            }

            var entityKey = sourceObject is EntityReference ? (sourceObject as EntityReference).EntityKey : (sourceObject as EntityObject).EntityKey;
            this.entityKeyMap.Add(entityKey, entity);

            this.destinationContext.AddEntity(entity, entityTypeName);
        }
Beispiel #30
0
        public static List <ResponseTreeNode> GetTreeRecords(List <Entity> entities, List <EntityRelation> relationList, RecordTree tree)
        {
            EntityRelation relation = relationList.FirstOrDefault(r => r.Id == tree.RelationId);

            Guid treeEntityId   = relation.OriginEntityId;
            Guid treeRelFieldId = relation.OriginFieldId;

            Entity treeEntity       = entities.FirstOrDefault(e => e.Id == treeEntityId);
            Field  treeIdField      = treeEntity.Fields.FirstOrDefault(f => f.Id == treeRelFieldId);
            Field  treeParrentField = treeEntity.Fields.FirstOrDefault(f => f.Id == tree.NodeParentIdFieldId);
            Field  nameField        = treeEntity.Fields.FirstOrDefault(f => f.Id == tree.NodeNameFieldId);
            Field  labelField       = treeEntity.Fields.FirstOrDefault(f => f.Id == tree.NodeLabelFieldId);
            Field  weightField      = treeEntity.Fields.FirstOrDefault(f => f.Id == tree.NodeWeightFieldId);

            var relIdField = treeEntity.Fields.Single(x => x.Name == "id");

            List <Guid> fieldIdsToInclude = new List <Guid>();

            if (!fieldIdsToInclude.Contains(treeIdField.Id))
            {
                fieldIdsToInclude.Add(treeIdField.Id);
            }

            if (!fieldIdsToInclude.Contains(treeParrentField.Id))
            {
                fieldIdsToInclude.Add(treeParrentField.Id);
            }

            if (!fieldIdsToInclude.Contains(tree.NodeNameFieldId))
            {
                fieldIdsToInclude.Add(tree.NodeNameFieldId);
            }

            if (!fieldIdsToInclude.Contains(tree.NodeLabelFieldId))
            {
                fieldIdsToInclude.Add(tree.NodeLabelFieldId);
            }

            var weightFieldNonNullable = Guid.Empty;

            if (tree.NodeWeightFieldId.HasValue)
            {
                weightFieldNonNullable = tree.NodeWeightFieldId.Value;
            }
            if (weightField != null && !fieldIdsToInclude.Contains(weightFieldNonNullable))
            {
                fieldIdsToInclude.Add(weightFieldNonNullable);
            }

            string queryFields = string.Empty;

            //Add mandatory fields
            foreach (var fieldId in fieldIdsToInclude)
            {
                var f = treeEntity.Fields.SingleOrDefault(x => x.Id == fieldId);
                if (f != null)
                {
                    if (!queryFields.Contains(f.Name))
                    {
                        queryFields += (f.Name + ",");
                    }
                }
            }
            //Add object properties fields
            foreach (var fieldId in tree.NodeObjectProperties)
            {
                var f = treeEntity.Fields.SingleOrDefault(x => x.Id == fieldId);
                if (f != null)
                {
                    if (!queryFields.Contains(f.Name))
                    {
                        queryFields += (f.Name + ",");
                    }
                }
            }
            queryFields += "id";

            EntityQuery   eq         = new EntityQuery(treeEntity.Name, queryFields);
            RecordManager recMan     = new RecordManager();
            var           allRecords = recMan.Find(eq).Object.Data;

            List <ResponseTreeNode> rootNodes = new List <ResponseTreeNode>();

            foreach (var rootNode in tree.RootNodes.OrderBy(x => x.Name))
            {
                List <ResponseTreeNode> children = new List <ResponseTreeNode>();
                int?rootNodeWeight = null;
                if (weightField != null)
                {
                    rootNodeWeight = rootNode.Weight;
                    children       = GetTreeNodeChildren(allRecords, treeIdField.Name,
                                                         treeParrentField.Name, nameField.Name, labelField.Name, rootNode.Id, weightField.Name, 1, tree.DepthLimit);
                }
                else
                {
                    children = GetTreeNodeChildren(allRecords, treeIdField.Name,
                                                   treeParrentField.Name, nameField.Name, labelField.Name, rootNode.Id, "no-weight", 1, tree.DepthLimit);
                }
                rootNodes.Add(new ResponseTreeNode
                {
                    RecordId = rootNode.RecordId,
                    Id       = rootNode.Id.Value,
                    ParentId = rootNode.ParentId,
                    Name     = rootNode.Name,
                    Label    = rootNode.Label,
                    Weight   = rootNodeWeight,
                    Nodes    = children,
                    Object   = allRecords.SingleOrDefault(x => (Guid)x["id"] == rootNode.RecordId)
                });
            }

            return(rootNodes);
        }
Beispiel #31
0
 public static string GetTableFor(EntityRelation relation)
 {
     return string.Format("{0}_{1}_{2}", relation.LeftEntity, relation.RightEntity, relation.Role);
 }
 protected int GetCount()
 {
     return(EntityRelation.IsSelectAll() ? SelectedRows.Length :
            EntityRelation.IsEmptyKeys() ? 0 : EntityRelation.Keys.Count);
 }
Beispiel #33
0
        public IActionResult OnPost()
        {
            PageInit();
            if (ErpEntity == null)
            {
                return(NotFound());
            }

            try
            {
                if (String.IsNullOrWhiteSpace(Origin) || !Origin.Contains("$"))
                {
                    throw new ValidationException("Origin field is required!");
                }
                if (String.IsNullOrWhiteSpace(Target) || !Target.Contains("$"))
                {
                    throw new ValidationException("Target field is required!");
                }
                var  originSections = Origin.Split('$');
                Guid originEntityId = new Guid(originSections[0]);
                Guid originFieldId  = new Guid(originSections[1]);

                var  targetSections = Target.Split('$');
                Guid targetEntityId = new Guid(targetSections[0]);
                Guid targetFieldId  = new Guid(targetSections[1]);

                var            relMan      = new EntityRelationManager();
                EntityRelation newRelation = new EntityRelation
                {
                    Id             = Guid.NewGuid(),
                    Name           = Name,
                    Label          = Name,            //Label, Boz: removed for convinience
                    Description    = "",              //Description, Boz: removed for convinience
                    System         = IsSystem,
                    OriginEntityId = originEntityId,
                    OriginFieldId  = originFieldId,
                    TargetEntityId = targetEntityId,
                    TargetFieldId  = targetFieldId,
                    RelationType   = Type
                };


                var response = relMan.Create(newRelation);
                if (!response.Success)
                {
                    var exception = new ValidationException(response.Message);
                    exception.Errors = response.Errors.MapTo <ValidationError>();
                    throw exception;
                }
                return(Redirect($"/sdk/objects/entity/r/{ErpEntity.Id}/rl/relations/l"));
            }
            catch (ValidationException ex)
            {
                Validation.Message = ex.Message;
                Validation.Errors  = ex.Errors;
            }
            catch (Exception ex)
            {
                Validation.Message = ex.Message;
                Validation.Errors.Add(new ValidationError("", ex.Message, isSystem: true));
            }

            ErpRequestContext.PageContext = PageContext;

            BeforeRender();
            return(Page());
        }
        public EntityRelationResponse Update(EntityRelation relation)
        {
            EntityRelationResponse response = new EntityRelationResponse();

            response.Timestamp = DateTime.UtcNow;
            response.Object    = relation;

            bool hasPermisstion = SecurityContext.HasMetaPermission();

            if (!hasPermisstion)
            {
                response.StatusCode = HttpStatusCode.Forbidden;
                response.Success    = false;
                response.Message    = "User have no permissions to manipulate erp meta.";
                response.Errors.Add(new ErrorModel {
                    Message = "Access denied."
                });
                return(response);
            }

            response.Errors = ValidateRelation(relation, ValidationType.Update);
            if (response.Errors.Count > 0)
            {
                response.Success = false;
                response.Message = "The entity relation was not updated. Validation error occurred!";
                return(response);
            }

            try
            {
                var storageRelation = relation.MapTo <DbEntityRelation>();
                storageRelation.Name = storageRelation.Name.Trim();
                var success = DbContext.Current.RelationRepository.Update(storageRelation);
                Cache.Clear();
                if (success)
                {
                    response.Success = true;
                    response.Message = "The entity relation was successfully updated!";
                    return(response);
                }
                else
                {
                    response.Success = false;
                    response.Message = "The entity relation was not updated! An internal error occurred!";
                    return(response);
                }
            }
            catch (Exception e)
            {
                Cache.Clear();
                response.Success   = false;
                response.Object    = relation;
                response.Timestamp = DateTime.UtcNow;

                if (ErpSettings.DevelopmentMode)
                {
                    response.Message = e.Message + e.StackTrace;
                }
                else
                {
                    response.Message = "The entity relation was not updated. An internal error occurred!";
                }

                return(response);
            }
        }
Beispiel #35
0
        public PcFieldBaseOptions InitPcFieldBaseOptions(PageComponentContext context)
        {
            var options = new PcFieldBaseOptions();

            //Check if it is defined in form group
            if (context.Items.ContainsKey(typeof(LabelRenderMode)))
            {
                options.LabelMode = (LabelRenderMode)context.Items[typeof(LabelRenderMode)];
            }
            else
            {
                options.LabelMode = LabelRenderMode.Stacked;
            }


            //Check if it is defined in form group
            if (context.Items.ContainsKey(typeof(FieldRenderMode)))
            {
                options.Mode = (FieldRenderMode)context.Items[typeof(FieldRenderMode)];
            }
            else
            {
                options.Mode = FieldRenderMode.Form;
            }

            var baseOptions = JsonConvert.DeserializeObject <PcFieldBaseOptions>(context.Options.ToString());

            Entity mappedEntity = null;
            var    entity       = context.DataModel.GetProperty("Entity");

            if (options.ConnectedEntityId != null)
            {
                mappedEntity = new EntityManager().ReadEntity(options.ConnectedEntityId.Value).Object;
            }
            else if (options.ConnectedEntityId == null && entity is Entity)
            {
                mappedEntity = (Entity)entity;
            }

            if (mappedEntity != null)
            {
                var fieldName = baseOptions.Name;

                EntityRelation relation = null;
                if (fieldName.StartsWith("$"))
                {
                    //Field with relation is set. Mapped entity should be changed
                    var fieldNameArray = fieldName.Replace("$", "").Split(".", StringSplitOptions.RemoveEmptyEntries);
                    if (fieldNameArray.Length == 2)
                    {
                        var relationName = fieldNameArray[0];
                        fieldName = fieldNameArray[1];
                        relation  = new EntityRelationManager().Read(relationName).Object;
                        if (relation != null)
                        {
                            if (relation.OriginEntityId == mappedEntity.Id)
                            {
                                mappedEntity = new EntityManager().ReadEntity(relation.TargetEntityId).Object;
                            }
                            else if (relation.TargetEntityId == mappedEntity.Id)
                            {
                                mappedEntity = new EntityManager().ReadEntity(relation.OriginEntityId).Object;
                            }
                        }
                    }
                }

                var entityField = mappedEntity.Fields.FirstOrDefault(x => x.Name == fieldName);

                //for many to many relation field is always ID and that is not correct
                //so hide this field meta as field is not found
                if (relation != null && relation.RelationType == EntityRelationType.ManyToMany)
                {
                    entityField = null;
                }

                if (entityField != null)
                {
                    switch (entityField.GetFieldType())
                    {
                    case FieldType.AutoNumberField:
                    {
                        var fieldMeta = (AutoNumberField)entityField;
                        options.Template = fieldMeta.DisplayFormat;
                    }
                    break;

                    case FieldType.CurrencyField:
                    {
                        var fieldMeta = (CurrencyField)entityField;
                        options.Min          = fieldMeta.MinValue;
                        options.Min          = fieldMeta.MinValue;
                        options.CurrencyCode = fieldMeta.Currency.Code;
                    }
                    break;

                    case FieldType.EmailField:
                    {
                        var fieldMeta = (EmailField)entityField;
                        options.MaxLength = fieldMeta.MaxLength;
                    }
                    break;

                    case FieldType.NumberField:
                    {
                        var fieldMeta = (NumberField)entityField;
                        options.Min = fieldMeta.MinValue;
                        options.Min = fieldMeta.MinValue;
                        if (fieldMeta.DecimalPlaces != null)
                        {
                            if (int.TryParse(fieldMeta.DecimalPlaces.ToString(), out int outInt))
                            {
                                options.DecimalDigits = outInt;
                            }
                        }
                    }
                    break;

                    case FieldType.PasswordField:
                    {
                        var fieldMeta = (PasswordField)entityField;
                        options.Min = (decimal?)fieldMeta.MinLength;
                        options.Max = (decimal?)fieldMeta.MaxLength;
                    }
                    break;

                    case FieldType.PercentField:
                    {
                        var fieldMeta = (PercentField)entityField;
                        options.Min = fieldMeta.MinValue;
                        options.Min = fieldMeta.MinValue;
                        if (fieldMeta.DecimalPlaces != null)
                        {
                            if (int.TryParse(fieldMeta.DecimalPlaces.ToString(), out int outInt))
                            {
                                options.DecimalDigits = outInt;
                            }
                        }
                    }
                    break;

                    case FieldType.PhoneField:
                    {
                        var fieldMeta = (PhoneField)entityField;
                        options.MaxLength = fieldMeta.MaxLength;
                    }
                    break;

                    case FieldType.TextField:
                    {
                        var fieldMeta = (TextField)entityField;
                        options.MaxLength = fieldMeta.MaxLength;
                    }
                    break;

                    default:
                        break;
                    }
                }
            }

            return(options);
        }
Beispiel #36
0
        private List <ErrorModel> ValidateRelation(EntityRelation relation, ValidationType validationType)
        {
            List <ErrorModel> errors = new List <ErrorModel>();
            var entMan = new EntityManager();

            if (validationType == ValidationType.Update)
            {
                //we cannot update relation with missing Id (Guid.Empty means id is missing)
                //of if there is no relation with this id already
                if (relation.Id == Guid.Empty)
                {
                    errors.Add(new ErrorModel("id", null, "Id is required!"));
                }
                else if (Read(relation.Id).Object == null)
                {
                    errors.Add(new ErrorModel("id", relation.Id.ToString(), "Entity relation with such Id does not exist!"));
                }
            }
            else if (validationType == ValidationType.Create)
            {
                //if id is null, them we later will assing one before create process
                //otherwise check if relation with same id already exists
                if (relation.Id != Guid.Empty && (Read(relation.Id).Object != null))
                {
                    errors.Add(new ErrorModel("id", relation.Id.ToString(), "Entity relation with such Id already exist!"));
                }
            }
            else if (validationType == ValidationType.RelationsOnly)
            {
                //no need to check anything, we need to check only Entities and Fields relations
                //this case is here only for readability
            }

            EntityRelation existingRelation = null;

            if (validationType == ValidationType.Create || validationType == ValidationType.Update)
            {
                //validate name
                // - if name string is correct
                // - then if relation with same name already exists
                var nameValidationErrors = ValidationUtility.ValidateName(relation.Name);
                if (nameValidationErrors.Count > 0)
                {
                    errors.AddRange(nameValidationErrors);
                }
                else
                {
                    existingRelation = Read(relation.Name).Object;
                    if (validationType == ValidationType.Create)
                    {
                        //if relation with same name alfready exists
                        if (existingRelation != null)
                        {
                            errors.Add(new ErrorModel("name", relation.Name, string.Format("Entity relation '{0}' exists already!", relation.Name)));
                        }
                    }
                    else if (validationType == ValidationType.Update)
                    {
                        //if relation with same name alfready and different Id already exists
                        if (existingRelation != null && existingRelation.Id != relation.Id)
                        {
                            errors.Add(new ErrorModel("name", relation.Name, string.Format("Entity relation '{0}' exists already!", relation.Name)));
                        }
                    }
                }
            }
            else if (validationType == ValidationType.RelationsOnly)
            {
                //no need to check anything, we need to check only Entities and Fields relations
                //this case is here only for readability
            }

            errors.AddRange(ValidationUtility.ValidateLabel(relation.Label));

            Entity originEntity = entMan.ReadEntity(relation.OriginEntityId).Object;
            Entity targetEntity = entMan.ReadEntity(relation.TargetEntityId).Object;
            Field  originField  = null;
            Field  targetField  = null;

            if (originEntity == null)
            {
                errors.Add(new ErrorModel("originEntity", relation.OriginEntityId.ToString(), "The origin entity do not exist."));
            }
            else
            {
                originField = originEntity.Fields.SingleOrDefault(x => x.Id == relation.OriginFieldId);
                if (originField == null)
                {
                    errors.Add(new ErrorModel("originField", relation.OriginFieldId.ToString(), "The origin field do not exist."));
                }
                if (!(originField is GuidField))
                {
                    errors.Add(new ErrorModel("originField", relation.OriginFieldId.ToString(), "The origin field should be Unique Identifier (GUID) field."));
                }
            }

            if (targetEntity == null)
            {
                errors.Add(new ErrorModel("targetEntity", relation.TargetEntityId.ToString(), "The target entity do not exist."));
            }
            else
            {
                targetField = targetEntity.Fields.SingleOrDefault(x => x.Id == relation.TargetFieldId);
                if (targetField == null)
                {
                    errors.Add(new ErrorModel("targetField", relation.TargetFieldId.ToString(), "The target field do not exist."));
                }
                if (!(targetField is GuidField))
                {
                    errors.Add(new ErrorModel("targetField", relation.TargetFieldId.ToString(), "The target field should be Unique Identifier (GUID) field."));
                }
            }


            //the second level validation requires no errors on first one
            //so if there are errors in first level we return them
            if (errors.Count > 0)
            {
                return(errors);
            }


            if (validationType == ValidationType.Update)
            {
                if (existingRelation.RelationType != relation.RelationType)
                {
                    errors.Add(new ErrorModel("relationType", relation.RelationType.ToString(),
                                              "The initialy selected relation type is readonly and cannot be changed."));
                }

                if (existingRelation.OriginEntityId != relation.OriginEntityId)
                {
                    errors.Add(new ErrorModel("originEntityId", relation.OriginEntityId.ToString(),
                                              "The origin entity differ from initial one. The initialy selected origin entity is readonly and cannot be changed."));
                }

                if (existingRelation.OriginFieldId != relation.OriginFieldId)
                {
                    errors.Add(new ErrorModel("originFieldId", relation.OriginFieldId.ToString(),
                                              "The origin field differ from initial one. The initialy selected origin field is readonly and cannot be changed."));
                }

                if (existingRelation.TargetEntityId != relation.TargetEntityId)
                {
                    errors.Add(new ErrorModel("targetEntityId", relation.TargetEntityId.ToString(),
                                              "The target entity differ from initial one. The initialy selected target entity is readonly and cannot be changed."));
                }

                if (existingRelation.TargetFieldId != relation.TargetFieldId)
                {
                    errors.Add(new ErrorModel("TargetFieldId", relation.TargetFieldId.ToString(),
                                              "The target field differ from initial one. The initialy selected target field is readonly and cannot be changed."));
                }
            }
            else if (validationType == ValidationType.Create)
            {
                if (relation.RelationType == EntityRelationType.OneToMany || relation.RelationType == EntityRelationType.OneToOne)
                {
                    //validate if target and origin field is same field for following relations
                    if (relation.OriginEntityId == relation.TargetEntityId && relation.OriginFieldId == relation.TargetFieldId)
                    {
                        errors.Add(new ErrorModel("", "", "The origin and target fields cannot be the same."));
                    }

                    //validate there is no other already existing relation with same parameters
                    foreach (var rel in Read().Object)
                    {
                        if (rel.OriginEntityId == relation.OriginEntityId && rel.TargetEntityId == relation.TargetEntityId &&
                            rel.OriginFieldId == relation.OriginFieldId && rel.TargetFieldId == relation.TargetFieldId)
                        {
                            errors.Add(new ErrorModel("", "", "There is already existing relation with same parameters."));
                        }
                    }
                }



                if (relation.RelationType == EntityRelationType.OneToOne || relation.RelationType == EntityRelationType.ManyToMany)
                {
                    if (!originField.Required)
                    {
                        errors.Add(new ErrorModel("originFieldId", relation.OriginFieldId.ToString(), "The origin field must be specified as Required"));
                    }

                    if (!originField.Unique)
                    {
                        errors.Add(new ErrorModel("originFieldId", relation.OriginFieldId.ToString(), "The origin field must be specified as Unique"));
                    }

                    if (!targetField.Required)
                    {
                        errors.Add(new ErrorModel("targetFieldId", relation.TargetFieldId.ToString(), "The target field must be specified as Required"));
                    }

                    if (!targetField.Unique)
                    {
                        errors.Add(new ErrorModel("targetFieldId", relation.TargetFieldId.ToString(), "The target field must be specified as Unique"));
                    }
                }

                if (relation.RelationType == EntityRelationType.OneToMany)
                {
                    if (!originField.Required)
                    {
                        errors.Add(new ErrorModel("originFieldId", relation.OriginFieldId.ToString(), "The origin field must be specified as Required"));
                    }

                    if (!originField.Unique)
                    {
                        errors.Add(new ErrorModel("originFieldId", relation.OriginFieldId.ToString(), "The origin field must be specified as Unique"));
                    }
                }
            }
            if (validationType == ValidationType.RelationsOnly)
            {
                if (relation.RelationType == EntityRelationType.OneToOne || relation.RelationType == EntityRelationType.ManyToMany)
                {
                    if (!originField.Required)
                    {
                        errors.Add(new ErrorModel("originFieldId", relation.OriginFieldId.ToString(), "The origin field must be specified as Required"));
                    }

                    if (!originField.Unique)
                    {
                        errors.Add(new ErrorModel("originFieldId", relation.OriginFieldId.ToString(), "The origin field must be specified as Unique"));
                    }

                    if (!targetField.Required)
                    {
                        errors.Add(new ErrorModel("targetFieldId", relation.TargetFieldId.ToString(), "The target field must be specified as Required"));
                    }

                    if (!targetField.Unique)
                    {
                        errors.Add(new ErrorModel("targetFieldId", relation.TargetFieldId.ToString(), "The target field must be specified as Unique"));
                    }
                }

                if (relation.RelationType == EntityRelationType.OneToMany)
                {
                    if (!originField.Required)
                    {
                        errors.Add(new ErrorModel("originFieldId", relation.OriginFieldId.ToString(), "The origin field must be specified as Required"));
                    }

                    if (!originField.Unique)
                    {
                        errors.Add(new ErrorModel("originFieldId", relation.OriginFieldId.ToString(), "The origin field must be specified as Unique"));
                    }
                }
            }

            return(errors);
        }