public static JsonEntityQueryResult GetJsonEntityQueryResult(ICollection <EntityRef> entityRefs, ICollection <string> requests)
        {
#pragma warning disable 618
            var svc = new EntityInfoService( );
#pragma warning restore 618
            var entityDataList = new List <EntityData>( );

            for (int i = 0; i < entityRefs.Count; ++i)
            {
                EntityRef entityRef = entityRefs.ElementAt(i);
                string    request   = i < requests.Count ? requests.ElementAt(i) : requests.Last( );

                var        rqObj      = Factory.RequestParser.ParseRequestQuery(request);
                EntityData entityData = svc.GetEntityData(entityRef, rqObj);

                entityDataList.Add(entityData);
            }

            if (entityDataList.Count(p => p != null) == 0)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            var result = new JsonEntityQueryResult(entityDataList);
            return(result);
        }
Exemple #2
0
        /// <summary>
        ///     Decodes the entity.
        /// </summary>
        /// <param name="entityNugget">The entity nugget.</param>
        /// <param name="persistChanges">If true, the nugget is intended to be persisted.</param>
        /// <returns></returns>
        public static IEntity DecodeEntity(EntityNugget entityNugget, bool persistChanges = false)
        {
            if (entityNugget == null)
            {
                return(null);
            }
            if (entityNugget.DataV1 == null)
            {
                return(null);
            }

            // Recover EntityData
            JsonEntityQueryResult jeqr = entityNugget.DataV1;

            jeqr.ResolveIds( );
            long       id         = jeqr.Ids.FirstOrDefault( );
            EntityData entityData = jeqr.GetEntityData(id);

            // Bulk-check security (to fill security cache)
            var entitiesToCheck = jeqr.Entities.Where(je => je.Id > 0).Select(je => new EntityRef(je.Id)).ToList( );

            Factory.EntityAccessControlService.Check(entitiesToCheck, new[] { Permissions.Read });

            // Load as a modified entity structure
#pragma warning disable 618
            var svc = new EntityInfoService( );
#pragma warning restore 618
            IEntity entity = svc.DecodeEntity(entityData, persistChanges);
            return(entity);
        }
Exemple #3
0
 public EntityPackageContext()
 {
     EntitiesVisited = new HashSet <long>();
     Svc             = new EntityInfoService();
     ;
     Result = new JsonQueryResult();
 }
        public void TestTempDeletedChildItemIgnored( )
        {
            var svc = new EntityInfoService( );

            EntityRef orgRef = null;

            try
            {
                var o = new Report
                {
                    Name  = "org rpt",
                    Alias = "shared:a" + Guid.NewGuid( )
                };

                var b = new ReportColumn
                {
                    Name            = "bob",
                    Alias           = "shared:a" + Guid.NewGuid( ),
                    ColumnForReport = o
                };

                EntityData result = svc.GetEntityData(b, EntityRequestHelper.BuildRequest("name, columnForReport.name"));

                result.Relationships[0].Instances[0].DataState = DataState.Delete;

                orgRef = svc.CreateEntity(result);
            }
            finally
            {
                if (orgRef != null)
                {
                    Entity.Delete(orgRef);
                }
            }
        }
        /// <summary>
        ///     Creates a new image
        /// </summary>
        /// <param name="imageFileUploadId">The image file upload identifier.</param>
        /// <param name="imageEntityData">The image entity data.</param>
        /// <returns>The requested data.</returns>
        /// <exception cref="System.ArgumentNullException">@imageEntityData</exception>
        /// <exception cref="System.ArgumentException">@imageEntityData</exception>
        public EntityRef CreateImageFromExistingFile(long imageFileUploadId, EntityData imageEntityData)
        {
            if (imageEntityData == null)
            {
                throw new ArgumentNullException(@"imageEntityData");
            }

            // Create a new image entity
#pragma warning disable 618
            var entityInfoService = new EntityInfoService( );
#pragma warning restore 618
            var imageFile = entityInfoService.CreateEntity(imageEntityData).Entity.AsWritable <ImageFileType>( );

            int width;
            int height;

            using (Stream stream = GetImageDataStream(imageFileUploadId))
            {
                using (Image image = Image.FromStream(stream))
                {
                    width  = image.Width;
                    height = image.Height;
                }
            }
            var existingImage = Entity.Get <ImageFileType>(imageFileUploadId);

            imageFile.FileDataHash  = existingImage.FileDataHash;
            imageFile.FileExtension = existingImage.FileExtension;
            imageFile.ImageWidth    = width;
            imageFile.ImageHeight   = height;
            imageFile.Save( );

            return(imageFile);
        }
        public void CreateInstance( )
        {
            // Define a new entity
            var data = new EntityData
            {
                Fields  = new List <FieldData>( ),
                TypeIds = new EntityRef("test", "person").ToEnumerable( ).ToList( )
            };

            data.Fields.Add(new FieldData
            {
                FieldId = new EntityRef("name"),
                Value   = new TypedValue("Isaac Newton")
            });

            // Create it
            var       svc = new EntityInfoService( );
            EntityRef id  = svc.CreateEntity(data);

            // Verify it was created
            Assert.IsTrue(id.Id > 0, "Positive Id");

            // Select the data
            EntityMemberRequest request = EntityRequestHelper.BuildRequest("name");
            EntityData          result  = svc.GetEntityData(id, request);

            // Verify results
            Assert.AreEqual("Isaac Newton", result.Fields[0].Value.Value);

            svc.DeleteEntity(id);
        }
        public void TestChangeType( )
        {
            // Note: refer to additional tests directly on Entity.ChangeType.

            var svc = new EntityInfoService( );

            IEntity e = null;

            try
            {
                e = Entity.Create(new EntityRef("test:person"));

                var ed = new EntityData
                {
                    Id = e.Id
                };
                ed.TypeIds.Add(new EntityRef("test:manager"));

                svc.UpdateEntityType(ed);
            }
            catch
            {
                if (e != null)
                {
                    e.Delete( );
                }
            }
        }
#pragma warning restore 618

        /// <summary>
        ///     Initializes a new instance of the <see cref="EntityPackage" /> class.
        /// </summary>
        public EntityPackage( )
        {
            _entitiesVisited = new HashSet <long>( );
#pragma warning disable 618
            _svc = new EntityInfoService( );
#pragma warning restore 618
            _result = new JsonQueryResult( );
        }
        public void Test_GetFieldsRelationshipsControlsStructuredQueryString( )
        {
            EntityMemberRequest request = EntityRequestHelper.BuildRequest("k:context.name");

            var        svc    = new EntityInfoService( );
            EntityData result = svc.GetEntityData(new EntityRef("console", "singleLineTextControl"), request);

            Assert.IsNotNull(FindEntity(result, new EntityRef("console", "uiContextHtml").Id));
        }
        public void TestCloneAndUpdateUpdateFields()
        {
            var svc = new EntityInfoService();

            string initialName        = "Initial name" + Guid.NewGuid();
            string initialDescription = "Initial description" + Guid.NewGuid();

            string newName        = "New name" + Guid.NewGuid();
            string newDescription = "New description" + Guid.NewGuid();

            IEntity e = Entity.Create(new EntityRef("test:person"));

            e.SetField("core:name", initialName);
            e.SetField("core:description", initialDescription);
            e.Save();

            Assert.AreEqual(initialName, e.GetField("core:name"));
            Assert.AreEqual(initialDescription, e.GetField("core:description"));

            var data = new EntityData
            {
                Id     = e.Id,
                Fields = new List <FieldData>()
                {
                    new FieldData
                    {
                        FieldId = new EntityRef("name"),
                        Value   = new TypedValue(newName)
                    },
                    new FieldData
                    {
                        FieldId = new EntityRef("description"),
                        Value   = new TypedValue(newDescription)
                    }
                },
                DataState = DataState.Update
            };

            var cloneIdsMap = svc.CloneAndUpdateEntity(data);

            long cloneId;

            Assert.IsTrue(cloneIdsMap.TryGetValue(e.Id, out cloneId), "The initial entity is not found.");

            // Check the fields were cloned
            IEntity clonedEntity = Entity.Get(cloneId);

            Assert.AreEqual(newName, clonedEntity.GetField("core:name"));
            Assert.AreEqual(newDescription, clonedEntity.GetField("core:description"));

            // Check initial entity is not touched
            IEntity initialEntity = Entity.Get(e.Id);

            Assert.AreEqual(initialName, initialEntity.GetField("core:name"));
            Assert.AreEqual(initialDescription, initialEntity.GetField("core:description"));
        }
        public void UpdateField( )
        {
            var rq = new EntityMemberRequest( );

            rq.Fields.Add(new EntityRef("description"));

            var        svc    = new EntityInfoService( );
            EntityData entity = svc.GetEntityData(new EntityRef("test", "person"), rq);

            entity.Fields[0].Value.Value = "Hello world";
            svc.UpdateEntity(entity);
        }
        public void TestCloneAndUpdateTemporaryEntity()
        {
            var svc = new EntityInfoService();

            IEntity e = Entity.Create(new EntityRef("test:person"));

            var ed = new EntityData
            {
                Id = e.Id
            };

            Assert.Throws <InvalidOperationException>(() => svc.CloneAndUpdateEntity(ed));
        }
Exemple #13
0
        /// <summary>
        /// Creates a form entity for a given type.
        /// </summary>
        /// <param name="alias">The alias given to the form.</param>
        /// <param name="name">The name given to the form.</param>
        /// <param name="description">The description given to the form.</param>
        /// <param name="type">The type to create the form for.</param>
        /// <param name="isDefault">Whether the form should be the default for the type.</param>
        /// <returns>The created form entity.</returns>
        public static CustomEditForm CreateForm(string alias, string name, string description, EntityType type, bool isDefault)
        {
            var generator      = new DefaultLayoutGenerator(CurrentUiContext.Html, new EntityRef(type), false);
            var formEntityData = generator.GetLayoutAsEntityData(FormQuery);

            var form = new EntityInfoService().CreateEntity(formEntityData).Entity.AsWritable <CustomEditForm>();

            form.Alias       = alias;
            form.Name        = name;
            form.Description = description;
            if (isDefault)
            {
                form.IsDefaultForEntityType = type;
            }

            return(form);
        }
        public HttpResponseMessage <long> Delete([FromUri] IEnumerable <long> id)
        {
            if (id == null)
            {
                throw new WebArgumentException("No id was specified");
            }

            long[] ids  = id as long[] ?? id.ToArray( );
            var    refs = ids.Distinct().Select(i => new EntityRef(i));

            EventLog.Application.WriteInformation(string.Format("webapi- deleting {0} entities", ids.Length));

#pragma warning disable 618
            var svc = new EntityInfoService();
#pragma warning restore 618
            svc.DeleteEntities(refs);

            EventLog.Application.WriteInformation(string.Format("webapi- deleting complete"));

            return(new HttpResponseMessage <long>(HttpStatusCode.OK));
        }
        public void GetFieldInstanceDbType( )
        {
            /////
            // Define a new entity
            /////
            var data = new EntityData
            {
                Fields  = new List <FieldData>( ),
                TypeIds = new EntityRef("test", "person").ToEnumerable( ).ToList( )
            };

            /////
            // Create it
            /////
            var       svc = new EntityInfoService( );
            EntityRef id  = svc.CreateEntity(data);

            /////
            // Verify it was created
            /////
            Assert.IsTrue(id.Id > 0, "Positive Id");

            EntityMemberRequest fieldRequest = EntityRequestHelper.BuildRequest(@"
				fields.isOfType.name,
				fields.isOfType.alias,
				fields.isOfType.dbType,
				fields.isOfType.dbTypeFull,
				fields.isOfType.readiNowType,
				fields.isOfType.xsdType"                );

            EntityData result = svc.GetEntityData(data.TypeIds.First( ), fieldRequest);

            /////
            // Verify results
            /////
            Assert.AreEqual(1, result.Relationships.Count);

            svc.DeleteEntity(id);
        }
        /// <summary>
        ///     Handles cloning data.
        /// </summary>
        /// <param name="entityData">The entity data.</param>
        /// <returns>The id of the cloned entity</returns>
        private IHttpActionResult HandleCloneAndUpdate(JsonEntityQueryResult entityData)
        {
            // resolve all entity ids above our 'known id hi watermark' that actually do exist
            entityData.ResolveIds();

            long id      = entityData.Ids.FirstOrDefault();
            long cloneId = -1;

            if (id >= JsonEntityQueryResult.BaseNewId)
            {
                return(BadRequest("Cannot clone a temporary entity."));
            }

            EventLog.Application.WriteTrace("Cloning entity " + id);
            EntityData newEntityData = entityData.GetEntityData(id);

            DatabaseContext.RunWithRetry(() =>
            {
                using (DatabaseContext context = DatabaseContext.GetContext(true))
                {
#pragma warning disable 618
                    var svc = new EntityInfoService();
#pragma warning restore 618

                    var clonedIds = svc.CloneAndUpdateEntity(newEntityData);

                    if (!clonedIds.TryGetValue(id, out cloneId))
                    {
                        cloneId = -1;
                    }

                    context.CommitTransaction();
                }
            });

            return(Ok(cloneId));
        }
        public void TestLoopsDontBreakCreate( )
        {
            // Define a new entity
            var data1 = new EntityData
            {
                Fields  = new List <FieldData>( ),
                TypeIds = new EntityRef("test", "person").ToEnumerable( ).ToList( )
            };

            data1.Fields.Add(new FieldData
            {
                FieldId = new EntityRef("name"),
                Value   = new TypedValue("Isaac Newton")
            });

            // Define a new related entity
            var data2 = new EntityData
            {
                Fields  = new List <FieldData>( ),
                TypeIds = new EntityRef("test", "employee").ToEnumerable( ).ToList( )
            };

            data2.Fields.Add(new FieldData
            {
                FieldId = new EntityRef("name"),
                Value   = new TypedValue("Isaac Newtons Emmployer")
            });
            data2.DataState = DataState.Create;

            data1.Relationships = new List <RelationshipData>
            {
                new RelationshipData
                {
                    RelationshipTypeId = new EntityRef("test", "reportsTo"),
                    IsReverse          = false,
                    Instances          = new List <RelationshipInstanceData>
                    {
                        new RelationshipInstanceData
                        {
                            Entity    = data2,
                            DataState = DataState.Create
                        }
                    },
                }
            };

            data2.Relationships = new List <RelationshipData>
            {
                new RelationshipData
                {
                    RelationshipTypeId = new EntityRef("test", "reportsTo"),
                    IsReverse          = false,
                    Instances          = new List <RelationshipInstanceData>
                    {
                        new RelationshipInstanceData
                        {
                            Entity    = data1,
                            DataState = DataState.Create
                        }
                    },
                }
            };

            // Create it
            var       svc = new EntityInfoService( );
            EntityRef id  = svc.CreateEntity(data1);

            // Verify it was created
            Assert.IsTrue(id.Id > 0, "Positive Id");

            svc.DeleteEntity(id);
        }
        public void TestCloneAndUpdateCloneByEntityRelationships()
        {
            var svc = new EntityInfoService();

            EntityType type1 = new EntityType();

            type1.Save();

            EntityType type2 = new EntityType();

            type2.Save();

            Relationship rel = new Relationship
            {
                FromType         = type1,
                ToType           = type2,
                CloneAction_Enum = CloneActionEnum_Enumeration.CloneEntities,
                Cardinality_Enum = CardinalityEnum_Enumeration.ManyToMany
            };

            rel.Save();

            string  initialName   = Guid.NewGuid().ToString();
            IEntity entityRelated = Entity.Create(type2.Id);

            entityRelated.SetField("core:name", initialName);
            entityRelated.Save();

            IEntity entity1 = Entity.Create(type1.Id);

            entity1.SetRelationships(rel, new EntityRelationshipCollection <IEntity> {
                entityRelated
            }, Direction.Forward);
            entity1.Save();

            string newEntityName = Guid.NewGuid().ToString();

            var data = new EntityData
            {
                Id            = entity1.Id,
                Relationships = new List <RelationshipData>
                {
                    new RelationshipData
                    {
                        RelationshipTypeId = new EntityRef(rel),
                        Instances          = new List <RelationshipInstanceData>
                        {
                            new RelationshipInstanceData
                            {
                                DataState = DataState.Unchanged,
                                Entity    = new EntityData
                                {
                                    DataState = DataState.Update,
                                    Id        = new EntityRef(entityRelated.Id),
                                    Fields    = new List <FieldData>()
                                    {
                                        new FieldData
                                        {
                                            FieldId = new EntityRef("name"),
                                            Value   = new TypedValue(newEntityName)
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                DataState = DataState.Update
            };

            var cloneIdsMap = svc.CloneAndUpdateEntity(data);

            long cloneId1, cloneIdRelated;

            Assert.IsTrue(cloneIdsMap.TryGetValue(entity1.Id, out cloneId1), "The initial entity is not found.");
            Assert.IsTrue(cloneIdsMap.TryGetValue(entityRelated.Id, out cloneIdRelated), "The related entity is not found.");

            // Check the relationships were cloned
            IEntity clonedEntity        = Entity.Get(cloneId1);
            var     clonedRelationships = clonedEntity.GetRelationships(rel, Direction.Forward);

            Assert.AreEqual(1, clonedRelationships.Count);
            Assert.IsTrue(clonedRelationships.Any(r => r.Id == cloneIdRelated));
            Assert.IsTrue(clonedRelationships.Any(r => (string)r.GetField("core:name") == newEntityName));

            // Check initial entity is not touched
            IEntity initialEntity        = Entity.Get(entity1.Id);
            var     initialRelationships = initialEntity.GetRelationships(rel, Direction.Forward);

            Assert.AreEqual(1, initialRelationships.Count);
            Assert.IsTrue(initialRelationships.Any(r => r.Id == entityRelated.Id));
            Assert.IsTrue(initialRelationships.Any(r => (string)r.GetField("core:name") == initialName));
        }
        /// <summary>
        ///     Handles post data.
        /// </summary>
        /// <param name="entityData">The entity data.</param>
        /// <param name="returnMap">if set to <c>true</c> [return map].</param>
        /// <returns></returns>
        private HttpResponseMessage HandlePost(JsonEntityQueryResult entityData, bool returnMap)
        {
            Stopwatch sw = Stopwatch.StartNew( );
            long      t1;

            // resolve all entity ids above our 'known id hi watermark' that actually do exist
            entityData.ResolveIds( );

            long id = entityData.Ids.FirstOrDefault( );
            IDictionary <long, IEntity> map = null;

            if (id >= JsonEntityQueryResult.BaseNewId)
            {
                // create
                EventLog.Application.WriteTrace("Creating entity " + id);
                EntityData newEntityData = entityData.GetEntityData(id);

                t1 = sw.ElapsedMilliseconds;

                DatabaseContext.RunWithRetry(() =>
                {
                    using (DatabaseContext context = DatabaseContext.GetContext(true))
                    {
#pragma warning disable 618
                        var svc = new EntityInfoService();
#pragma warning restore 618

                        map = svc.CreateEntityGetMap(newEntityData);

                        IEntity entity = map[newEntityData.Id.Id];
                        id             = entity == null ? -1 : entity.Id;

                        context.CommitTransaction();
                    }
                });


                EventLog.Application.WriteTrace("EntityPost create took {0} msec ({1} to de-json)",
                                                sw.ElapsedMilliseconds, t1);
            }
            else
            {
                map = new Dictionary <long, IEntity>( );

                EventLog.Application.WriteTrace("Updating entity " + id);
                EntityData newEntityData = entityData.GetEntityData(id);

                t1 = sw.ElapsedMilliseconds;


                DatabaseContext.RunWithRetry(() =>
                {
                    using (DatabaseContext context = DatabaseContext.GetContext(true))
                    {
#pragma warning disable 618
                        var svc = new EntityInfoService();
#pragma warning restore 618
                        svc.UpdateEntity(newEntityData);

                        context.CommitTransaction();
                    }
                });

                EventLog.Application.WriteTrace("EntityPost update took {0} msec ({1} to de-json)",
                                                sw.ElapsedMilliseconds, t1);
            }


            HttpResponseMessage httpResponseMessage;

            if (returnMap)
            {
                /////
                // Create a custom response message so the infrastructure framework doesn't serialize it twice.
                /////
                httpResponseMessage = new HttpResponseMessage
                {
                    Content = new StringContent(DictionaryToJson(map))
                };

                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            }
            else
            {
                httpResponseMessage = new HttpResponseMessage <long>(id);
            }

            return(httpResponseMessage);
        }
        public void UpdateRelationships(string cardinality, string options, string expect)
        {
            var type1 = Create <EntityType>(true);
            var type2 = Create <EntityType>(true);
            var rel   = Create <Relationship>( );

            rel.FromType    = type1;
            rel.ToType      = type2;
            rel.Cardinality = Entity.Get <CardinalityEnum>(new EntityRef("core:" + cardinality));
            rel.Save( );

            var inst1  = Entity.Create(type1.Id);
            var inst2a = Entity.Create(type2.Id);
            var inst2b = Entity.Create(type2.Id);
            var inst3  = Entity.Create(type2.Id);

            SetRel(inst1, inst2a, rel);

            if (options.Contains("rel3"))
            {
                SetRel(inst3, inst2b, rel);
            }

            EntityData data = new EntityData
            {
                Id            = new EntityRef(inst1.Id),
                Relationships = new List <RelationshipData>
                {
                    new RelationshipData
                    {
                        RemoveExisting     = options.Contains("removeExisting"),
                        DeleteExisting     = options.Contains("deleteExisting"),
                        AutoCardinality    = options.Contains("autoCardinality"),
                        RelationshipTypeId = new EntityRef(rel.Id),
                        Instances          = new List <RelationshipInstanceData>
                        {
                            new RelationshipInstanceData {
                                DataState = DataState.Create,
                                Entity    = new EntityData {
                                    Id = new EntityRef(inst2b.Id)
                                }
                            }
                        }
                    }
                }
            };

            // Call service
            var svc = new EntityInfoService( );

            svc.UpdateEntity(data);

            Assert.That(Entity.Exists(inst1.Id), Is.EqualTo(expect.Contains("ent1")), "ent1");
            Assert.That(Entity.Exists(inst2a.Id), Is.EqualTo(expect.Contains("ent2a")), "ent2a");
            Assert.That(Entity.Exists(inst2b.Id), Is.EqualTo(expect.Contains("ent2b")), "ent2b");

            var values = inst1.GetRelationships(rel).Select(r => r.Entity.Id).ToList( );

            Assert.That(values.Contains(inst2a.Id), Is.EqualTo(expect.Contains("rel2a")), "rel2a");
            Assert.That(values.Contains(inst2b.Id), Is.EqualTo(expect.Contains("rel2b")), "rel2b");

            var values2 = inst3.GetRelationships(rel).Select(r => r.Entity.Id).ToList( );

            Assert.That(values2.Contains(inst2b.Id), Is.EqualTo(expect.Contains("rel3")), "rel3");
        }
        public void UpdateFieldOnRelatedInstance( )
        {
            // Define a new entity
            var data = new EntityData
            {
                Fields  = new List <FieldData>( ),
                TypeIds = new EntityRef("test", "person").ToEnumerable().ToList()
            };

            data.Fields.Add(new FieldData
            {
                FieldId = new EntityRef("name"),
                Value   = new TypedValue("Isaac Newton")
            });

            // Define a new related entity
            var data2 = new EntityData
            {
                Fields  = new List <FieldData>( ),
                TypeIds = new EntityRef("test", "employee").ToEnumerable().ToList()
            };

            data2.Fields.Add(new FieldData
            {
                FieldId = new EntityRef("name"),
                Value   = new TypedValue("Isaac Newtons Emmployer")
            });
            data2.DataState = DataState.Create;

            data.Relationships = new List <RelationshipData>
            {
                new RelationshipData
                {
                    RelationshipTypeId = new EntityRef("test", "reportsTo"),
                    IsReverse          = false,
                    Instances          = new List <RelationshipInstanceData>
                    {
                        new RelationshipInstanceData
                        {
                            Entity    = data2,
                            DataState = DataState.Create
                        }
                    },
                }
            };

            // Create it
            var       svc = new EntityInfoService( );
            EntityRef id  = svc.CreateEntity(data);

            // Verify it was created
            Assert.IsTrue(id.Id > 0, "Positive Id");

            // Select the data
            EntityMemberRequest request = EntityRequestHelper.BuildRequest("name, test:reportsTo.name");
            EntityData          result  = svc.GetEntityData(id, request);

            // Verify results
            Assert.AreEqual("Isaac Newton", result.Fields[0].Value.Value);

            EntityData employee           = result.Relationships[0].Instances[0].Entity;
            FieldData  employersNameField = employee.Fields[0];

            Assert.AreEqual("Isaac Newtons Emmployer", employersNameField.Value.Value);

            // Update employees name
            employersNameField.Value.Value = "bob";
            employee.DataState             = DataState.Update;

            svc.UpdateEntity(result);

            // comfirm it changed
            EntityData resultAfterUpdate = svc.GetEntityData(id, request);

            employee           = resultAfterUpdate.Relationships[0].Instances[0].Entity;
            employersNameField = employee.Fields[0];
            Assert.AreEqual("bob", employersNameField.Value.Value);

            // delete the referenced Entity leaving the data state of the top entity unchanged
            employee.DataState = DataState.Delete;

            svc.UpdateEntity(resultAfterUpdate);

            // comfirm it deleted
            EntityData resultAfterDelete = svc.GetEntityData(id, request);

            Assert.AreEqual(0, resultAfterDelete.Relationships[0].Instances.Count, "There should be no manager");

            // clean up
            svc.DeleteEntity(id);
        }
        public void UpdateEntityRemoveExistingFromCascadeDeleted()
        {
            /////////////////////////////////////////////////////////////////////////////////////////
            // Arrange
            /////////////////////////////////////////////////////////////////////////////////////////
            var typeA = Create <EntityType>(true);
            var typeB = Create <EntityType>(true);
            var typeC = Create <EntityType>(true);
            var rel1  = Create <Relationship>();

            rel1.FromType         = typeA;
            rel1.ToType           = typeB;
            rel1.Cardinality_Enum = CardinalityEnum_Enumeration.OneToMany;
            rel1.Save();
            var rel2 = Create <Relationship>();

            rel2.FromType         = typeB;
            rel2.ToType           = typeC;
            rel2.Cardinality_Enum = CardinalityEnum_Enumeration.OneToMany;
            rel2.CascadeDeleteTo  = true;
            rel2.Save();

            var aInstance = Entity.Create(typeA.Id);
            var bInstance = Entity.Create(typeB.Id);
            var cInstance = Entity.Create(typeC.Id);

            SetRel(aInstance, bInstance, rel1);
            SetRel(bInstance, cInstance, rel2);

            aInstance.IsTemporaryId.Should().BeFalse();
            bInstance.IsTemporaryId.Should().BeFalse();
            cInstance.IsTemporaryId.Should().BeFalse();
            Entity.Exists(aInstance.Id).Should().BeTrue();
            Entity.Exists(bInstance.Id).Should().BeTrue();
            Entity.Exists(cInstance.Id).Should().BeTrue();

            var children = bInstance.GetRelationships(rel2);

            children.Should().NotBeNull().And.NotBeEmpty();
            children.Count.Should().Be(1);
            children.Select(c => c.Id).Should().Contain(cInstance.Id);

            var data = new EntityData
            {
                // top level node is the "update"
                Id            = new EntityRef(aInstance.Id),
                DataState     = DataState.Update,
                Relationships = new List <RelationshipData>
                {
                    new RelationshipData
                    {
                        RelationshipTypeId = new EntityRef(rel1.Id),
                        Instances          = new List <RelationshipInstanceData>
                        {
                            new RelationshipInstanceData
                            {
                                Entity = new EntityData
                                {
                                    // this is the node we are deleting and removing from
                                    Id            = new EntityRef(bInstance.Id),
                                    DataState     = DataState.Delete,
                                    Relationships = new List <RelationshipData>
                                    {
                                        new RelationshipData
                                        {
                                            RemoveExisting     = true,
                                            RelationshipTypeId = new EntityRef(rel2.Id),
                                            Instances          = new List <RelationshipInstanceData>()
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            /////////////////////////////////////////////////////////////////////////////////////////
            // Act
            /////////////////////////////////////////////////////////////////////////////////////////
            var    svc        = new EntityInfoService();
            Action callUpdate = () => svc.UpdateEntity(data);

            callUpdate.ShouldNotThrow();

            /////////////////////////////////////////////////////////////////////////////////////////
            // Assert
            /////////////////////////////////////////////////////////////////////////////////////////
            Entity.Exists(aInstance.Id).Should().BeTrue();
            Entity.Exists(bInstance.Id).Should().BeFalse();

            // should not have been cascade deleted if it was removed from the relationship
            Entity.Exists(cInstance.Id).Should().BeTrue();
        }
        public void UpdateEntityDeleteItemFromSecuresToRelationship()
        {
            // this case requires that the entity to be delete ONLY receives its access for read/delete through
            // the relationship with the entity being updated.
            // (I.e. activityPrompts removed from promptForArguments relationship with promptUserActivity)

            /////////////////////////////////////////////////////////////////////////////////////////
            // Arrange
            /////////////////////////////////////////////////////////////////////////////////////////
            var parentType = Create <EntityType>();

            parentType.Inherits.Add(UserResource.UserResource_Type);
            parentType.Save();

            var childType = Create <EntityType>();

            childType.Inherits.Add(UserResource.UserResource_Type);
            childType.Save();

            var rel = Create <Relationship>();

            rel.FromType         = parentType;
            rel.ToType           = childType;
            rel.Cardinality_Enum = CardinalityEnum_Enumeration.OneToMany;
            rel.SecuresTo        = true;
            rel.Save();

            var parentInstance = Entity.Create(parentType.Id);
            var childInstance  = Entity.Create(childType.Id);

            SetRel(parentInstance, childInstance, rel);

            parentInstance.IsTemporaryId.Should().BeFalse();
            childInstance.IsTemporaryId.Should().BeFalse();
            Entity.Exists(parentInstance.Id).Should().BeTrue();
            Entity.Exists(childInstance.Id).Should().BeTrue();

            var user = Create <UserAccount>(true);

            user.Name = "UpdateEntityDeleteItemFromSecuresToRelationship";
            user.Save();
            using (new SetUser(user))
            {
                Action getParentNoPermission = () => Entity.Get(parentInstance.Id);
                getParentNoPermission.ShouldThrow <PlatformSecurityException>().WithMessage("*does not have view access to*");

                Action getChildNoPermission = () => Entity.Get(childInstance.Id);
                getChildNoPermission.ShouldThrow <PlatformSecurityException>().WithMessage("*does not have view access to*");
            }

            // grant access via parent
            var query       = TestQueries.Entities(parentType);
            var queryResult = Factory.QueryRunner.ExecuteQuery(query, new QuerySettings {
                SecureQuery = true
            });

            queryResult.Should().NotBeNull();
            queryResult.DataTable.Rows.Count.Should().Be(1);
            queryResult.DataTable.Rows[0].ItemArray.Should().Contain(parentInstance.Id);

            new AccessRuleFactory().AddAllowByQuery(user.As <Subject>(),
                                                    parentType.As <SecurableEntity>(),
                                                    new[] { Permissions.Read, Permissions.Modify, Permissions.Delete },
                                                    query.ToReport());

            Factory.EntityAccessControlService.ClearCaches();

            using (new SetUser(user))
            {
                IEntity p = null;
                Action  getParentPermission = () => p = Entity.Get(parentInstance.Id);
                getParentPermission.ShouldNotThrow();
                p.Should().NotBeNull();
                p.Id.ShouldBeEquivalentTo(parentInstance.Id);

                IEntity c = null;
                Action  getChildPermission = () => c = Entity.Get(childInstance.Id);
                getChildPermission.ShouldNotThrow();
                c.Should().NotBeNull();
                c.Id.ShouldBeEquivalentTo(childInstance.Id);
            }

            var data = new EntityData
            {
                Id            = new EntityRef(parentInstance.Id),
                Relationships = new List <RelationshipData>
                {
                    new RelationshipData
                    {
                        RelationshipTypeId = new EntityRef(rel.Id),
                        Instances          = new List <RelationshipInstanceData>
                        {
                            new RelationshipInstanceData {
                                Entity = new EntityData {
                                    Id = new EntityRef(childInstance.Id), DataState = DataState.Delete
                                }
                            }
                        }
                    }
                }
            };

            /////////////////////////////////////////////////////////////////////////////////////////
            // Act
            /////////////////////////////////////////////////////////////////////////////////////////
            using (new SetUser(user))
            {
                var    svc        = new EntityInfoService();
                Action callUpdate = () => svc.UpdateEntity(data);
                callUpdate.ShouldNotThrow();
            }

            /////////////////////////////////////////////////////////////////////////////////////////
            // Assert
            /////////////////////////////////////////////////////////////////////////////////////////
            Entity.Exists(parentInstance.Id).Should().BeTrue();
            Entity.Exists(childInstance.Id).Should().BeFalse();
        }
Exemple #24
0
        /// <summary>
        ///     Creates a new image
        /// </summary>
        /// <param name="imageFileUploadId">The image file upload id.</param>
        /// <param name="imageEntityData">The image entity data.</param>
        /// <param name="fileExtension">The file extension.</param>
        /// <returns>
        ///     The requested data.
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public EntityRef CreateImageFromUploadedFile(string imageFileUploadId, EntityData imageEntityData, string fileExtension)
        {
            if (string.IsNullOrEmpty(imageFileUploadId))
            {
                throw new ArgumentException(@"The imageFileUploadId is empty.", "imageFileUploadId");
            }

            if (imageEntityData == null)
            {
                throw new ArgumentNullException(@"imageEntityData");
            }

            if (string.IsNullOrEmpty(fileExtension))
            {
                throw new ArgumentNullException(@"fileExtension");
            }

            ImageFileType imageFile;
            string        filePath = string.Empty;

            try
            {
                // Create a new image entity
#pragma warning disable 618
                var entityInfoService = new EntityInfoService( );
#pragma warning restore 618
                imageFile = entityInfoService.CreateEntity(imageEntityData).Entity.AsWritable <ImageFileType>( );

                var        fileManagerService = new FileManagerService( );
                FileDetail fileDetails        = fileManagerService.GetFileDetails(imageFileUploadId);

                filePath = fileDetails.FullName;

                int width;
                int height;

                using (Image image = Image.FromFile(fileDetails.FullName))
                {
                    width  = image.Width;
                    height = image.Height;
                }

                string token;
                using (var source = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    token = FileRepositoryHelper.AddTemporaryFile(source);
                }

                imageFile.FileDataHash  = token;
                imageFile.FileExtension = FileHelper.GetFileExtension(filePath);
                imageFile.ImageWidth    = width;
                imageFile.ImageHeight   = height;
                imageFile.Save( );
            }
            finally
            {
                // Delete the underlying temp file
                if (!string.IsNullOrEmpty(filePath))
                {
                    File.Delete(filePath);
                }
            }

            return(imageFile);
        }
Exemple #25
0
        public void GetFormActionsForForm()
        {
            var personType = Entity.Get <Definition>("core:person");
            var personForm = Entity.Get <CustomEditForm>(personType.DefaultEditForm.Id, true);

            // fetch action for the person type
            var request = new ActionRequestExtended
            {
                EntityTypeId         = personType.Id,
                FormId               = personType.DefaultEditForm.Id,
                ActionDisplayContext = ActionContext.All
            };

            var actionSvc = new ActionService();

            actionSvc.FlushCaches();

            var result = actionSvc.GetFormActionsMenuState(request);

            result.Should().NotBeNull();
            result.Actions.Should().NotBeNull().And.NotBeEmpty();
            result.Actions.Count.Should().Be(2);
            result.Actions.Count(a => a.Name == "Assign Data to App").Should().Be(1);
            result.Actions.Count(a => a.Name == "Person Name Update").Should().Be(1);

            // create new action item and assign it to the form
            // form action
            var actionInfo = result.Actions.Find(a => a.Name == "Person Name Update");
            var wf         = Entity.Get <Workflow>(actionInfo.EntityId);

            // create workflow action item
            var wfActionMenuItem = new WorkflowActionMenuItem
            {
                Name                     = actionInfo.Name,
                MenuIconUrl              = actionInfo.Icon,
                MenuOrder                = actionInfo.Order,
                IsActionButton           = actionInfo.IsButton,
                IsMenuSeparator          = actionInfo.IsSeparator,
                IsContextMenu            = actionInfo.IsContextMenu,
                IsActionItem             = actionInfo.IsMenu,
                IsSystem                 = actionInfo.IsSystem,
                AppliesToSelection       = true,
                AppliesToMultiSelection  = false,
                HtmlActionMethod         = actionInfo.HtmlActionMethod,
                HtmlActionState          = actionInfo.HtmlActionState,
                ActionMenuItemToWorkflow = wf
            };

            var cb = new ConsoleBehavior
            {
                Name = $"DeleteMe_PersonForm_rcb {DateTime.Now}",
                BehaviorActionMenu = new ActionMenu
                {
                    Name = $"DeleteMe_PersonForm_rcb_menu {DateTime.Now}",
                    IncludeActionsAsButtons = new EntityCollection <ActionMenuItem>()
                    {
                        (ActionMenuItem)wfActionMenuItem
                    },
                    MenuItems = new EntityCollection <ActionMenuItem>()
                    {
                        (ActionMenuItem)wfActionMenuItem
                    }
                }
            };

            personForm.ResourceConsoleBehavior = cb;
            personForm.Save();

            var formActionQuery = @"{ k:resourceConsoleBehavior }
                                        .k:behaviorActionMenu.{
                                            { k:menuItems, k:suppressedActions, k:includeActionsAsButtons }.{
                                                {   name, 
                                                    description,
                                                    k:menuIconUrl,
                                                    htmlActionState,
                                                    htmlActionMethod,
                                                    k:isActionButton,
                                                    k:appliesToSelection,
                                                    k:isMenuSeparator, 
                                                    k:menuOrder,
                                                    { isOfType }.{ alias,name },
                                                    { k:actionMenuItemToWorkflow }.{ name },
                                                    { k:actionMenuItemToReportTemplate }.{ name }
                                                }
                                            },
                                            { k:includeTypesForNewButtons, k:suppressedTypesForNewMenu }.id
                                    }";

            // fetch form actions and check there is only one action button assigned to the form
            var entitySvc = new EntityInfoService();

            EntityMemberRequest req = EntityRequestHelper.BuildRequest(formActionQuery);
            var result2             = entitySvc.GetEntityData(personForm.Id, req);

            result2.Should().NotBeNull();

            var rcb = result2.Relationships.Find(a => a.RelationshipTypeId.Alias == "resourceConsoleBehavior");

            rcb.Should().NotBeNull();

            var actionMenu = rcb.Entities.First().Relationships.Find(a => a.RelationshipTypeId.Alias == "behaviorActionMenu");

            actionMenu.Should().NotBeNull();

            var actionButtons = actionMenu.Entities.First().Relationships.Find(a => a.RelationshipTypeId.Alias == "includeActionsAsButtons");

            actionButtons.Should().NotBeNull();

            var nameValue = actionButtons.Entities.First().Fields.Find(f => f.FieldId.Alias == "name").Value.Value;

            nameValue.Should().Be("Person Name Update");


            // delete console behavior
            Entity.Delete(cb.Id);
        }
        /// <summary>
        ///     Add a request for a set of entities and queries.
        /// </summary>
        /// <param name="batch">The batch.</param>
        /// <param name="hintText">A hint about what this query is doing. Use for logging/diagnostics only.</param>
        /// <exception cref="System.ArgumentException">
        /// </exception>
        /// <exception cref="System.Exception">Internal error: batch query mismatch.</exception>
        public void AddEntityRequestBatch(JsonQueryBatchRequest batch, string hintText = null)
        {
            JsonQueryResult result = _result;


#pragma warning disable 618
            EntityInfoService svc = _svc;
#pragma warning restore 618

            var memberRequests = new EntityMemberRequest[batch.Queries.Length];

            foreach (JsonQuerySingleRequest request in batch.Requests)
            {
                string requestHintText = request.Hint ?? hintText;

                _entitiesVisited.Clear( );

                var singleResult = new JsonSingleQueryResult
                {
                    Hint = request.Hint, Ids = new List <long>( )
                };

                try
                {
                    EntityMemberRequest memberRequest;

                    // Do not require access to the individual query components
                    using (PerformanceCounters.Measure(EntityInfoServicePerformanceCounters.CategoryName, EntityInfoServicePerformanceCounters.RequestCountersPrefix))
                        using (new SecurityBypassContext( ))
                        {
                            // Get/parse the request query. (Either parse, or load from previous cache as part of this request).
                            if (request.QueryIndex < 0 || request.QueryIndex >= batch.Queries.Length)
                            {
                                EventLog.Application.WriteError("Cannot locate query string.");
                                singleResult.Code = HttpStatusCode.BadRequest;
                                continue;
                            }
                            memberRequest = memberRequests[request.QueryIndex];
                            if (memberRequest == null)
                            {
                                string queryString = batch.Queries[request.QueryIndex];

                                //// Parse the request
                                try
                                {
                                    memberRequest = Factory.RequestParser.ParseRequestQuery(queryString);
                                }
                                catch (Exception ex)
                                {
                                    EventLog.Application.WriteError(ex.ToString( ));
                                    singleResult.Code = HttpStatusCode.BadRequest;
                                    continue;
                                }
                                memberRequests[request.QueryIndex] = memberRequest;
                            }
                        }

                    // Get the entityRefs
                    IEnumerable <EntityRef> ids = Enumerable.Empty <EntityRef>( );

                    if (request.Aliases != null && request.Aliases.Length > 0)
                    {
                        ids = ids.Union(request.Aliases.Select(ConvertId));
                    }

                    if (request.Ids != null && request.Ids.Length > 0)
                    {
                        ids = ids.Union(request.Ids.Select(ConvertId));
                    }

                    IList <EntityRef> entityRefs = ids.ToList( );

                    if (entityRefs.All(er => er == null))
                    {
                        singleResult.Code = HttpStatusCode.NotFound;
                        continue;
                    }

                    // Run the request
                    IEnumerable <EntityData> entitiesData;
                    try
                    {
                        if (BulkRequestHelper.IsValidForBulkRequest(memberRequest))
                        {
                            var entityRequest = new EntityRequest
                            {
                                QueryType     = request.QueryType,
                                RequestString = memberRequest.RequestString,
                                Hint          = requestHintText,
                                Entities      = entityRefs,
                                Filter        = request.Filter,
                                Isolated      = request.Isolated
                            };

                            // Run the request
                            entitiesData = BulkRequestRunner.GetEntities(entityRequest);

                            singleResult.Cached = entityRequest.ResultFromCache;
                        }
                        else
                        {
                            EventLog.Application.WriteWarning(
                                "Request cannot be handled by BulkRequest. Hint: {0}\n{1}",
                                requestHintText, memberRequest.RequestString);

                            switch (request.QueryType)
                            {
                            case QueryType.Instances:
                                entitiesData = svc.GetEntitiesByType(entityRefs.Single( ), true, memberRequest);
                                break;

                            case QueryType.ExactInstances:
                                entitiesData = svc.GetEntitiesByType(entityRefs.Single( ), false, memberRequest);
                                break;

                            case QueryType.Basic:
                            case QueryType.BasicWithDemand:
                                entitiesData = svc.GetEntitiesData(entityRefs, memberRequest);
                                break;

                            default:
                                throw new ArgumentException(string.Format("Unknown query type {0}", request.QueryType));
                            }
                        }
                    }
                    catch (ArgumentException ex)
                    {
                        // sorry world!
                        if (ex.Message.Contains("does not represent a known entity"))
                        {
                            singleResult.Code = HttpStatusCode.BadRequest;
                            continue;
                        }
                        throw;
                    }

                    // Skip results where access is denied
                    foreach (EntityData entityData in entitiesData.Where(ed => ed != null))
                    {
                        AppendEntityToResult(result, entityData);
                        singleResult.Ids.Add(entityData.Id.Id);
                    }

                    // Set the result to NotFound for Basic and BasicWithDemand only
                    if (request.QueryType == QueryType.Basic || request.QueryType == QueryType.BasicWithDemand)
                    {
                        singleResult.Code = singleResult.Ids.Count > 0
                                                        ? HttpStatusCode.OK
                                                        : HttpStatusCode.NotFound;
                    }
                    else
                    {
                        singleResult.Code = HttpStatusCode.OK;
                    }
                }
                catch (PlatformSecurityException ex)
                {
                    EventLog.Application.WriteWarning(ex.ToString( ));
                    singleResult.Ids.Clear( );
                    singleResult.Code = HttpStatusCode.Forbidden;
                }
                catch (Exception ex)
                {
                    EventLog.Application.WriteError(ex.ToString( ));
                    singleResult.Code = HttpStatusCode.InternalServerError;
                }
                finally
                {
                    // Place in the finally block so we are certain that it gets run exactly once per iteration
                    result.Results.Add(singleResult);
                }
            }

            if (result.Results.Count != batch.Requests.Length)
            {
                // We are indexing by ID, so we must always ensure that request position matches result position.
                throw new Exception("Internal error: batch query mismatch.");
            }
        }
Exemple #27
0
        public void Test_NewDefinitionOnRelated_GetEntitiesUsingInstancesOfType()
        {
            EntityMemberRequest request = EntityRequestHelper.BuildRequest("instancesOfType.{alias,name,description}");
            var svc = GetService();

            // Check before create
            var result = svc.GetEntityData(new EntityRef("core:definition"), request);
            int count  = result.Relationships[0].Instances.Count;

            Assert.IsTrue(count > 1);

            // Define a new form & definition
            var defn = new EntityData
            {
                Fields    = new List <FieldData>(),
                TypeIds   = new EntityRef("core", "definition").ToEnumerable().ToList(),
                DataState = DataState.Create
            };

            defn.Fields.Add(new FieldData
            {
                FieldId = new EntityRef("name"),
                Value   = new TypedValue("TestDefnT " + Guid.NewGuid().ToString())
            });
            var form = new EntityData
            {
                Fields    = new List <FieldData>(),
                TypeIds   = new EntityRef("console", "customEditForm").ToEnumerable().ToList(),
                DataState = DataState.Create
            };

            form.Fields.Add(new FieldData
            {
                FieldId = new EntityRef("name"),
                Value   = new TypedValue("TestFormT " + Guid.NewGuid().ToString())
            });
            form.Relationships = new List <RelationshipData> {
                new RelationshipData
                {
                    RelationshipTypeId = new EntityRef("console", "typeToEditWithForm"),
                    RemoveExisting     = true
                }
            };
            form.Relationships[0].Instances = new List <RelationshipInstanceData> {
                new RelationshipInstanceData
                {
                    Entity    = defn,
                    DataState = DataState.Create
                }
            };
            var svcWrite = new EntityInfoService();

            using (var ctx = DatabaseContext.GetContext(true, preventPostSaveActionsPropagating: true))
            {
                EntityRef id = svcWrite.CreateEntity(form);

                ctx.CommitTransaction();
            }

            // Check after create
            var result2 = svc.GetEntityData(new EntityRef("core:definition"), request);
            int count2  = result2.Relationships[0].Instances.Count;

            Assert.AreEqual(count + 1, count2);
        }