示例#1
0
        public void From_AttributeType_To_IndexOperation()
        {
            //Arrange

            var attributeType = new AttributeType("test", "Test", "This is a test", new StringSerializationType())
            {
                Id = HiveId.ConvertIntToGuid(123),
                RenderTypeProvider       = Guid.NewGuid().ToString(),
                RenderTypeProviderConfig = "<some><xml/><structure/></some>"
            };

            //Act

            var result = _mapper.Map <AttributeType, NestedHiveIndexOperation>(attributeType);

            //Assert

            Assert.AreEqual("AttributeType", result.ItemCategory);
            Assert.AreEqual(IndexOperationType.Add, result.OperationType);
            Assert.AreEqual(attributeType.Id.Value.ToString(), result.Id.Value);
            Assert.AreEqual(attributeType.RenderTypeProvider, result.Fields["RenderTypeProvider"].FieldValue);
            Assert.AreEqual(attributeType.Alias, result.Fields["Alias"].FieldValue);
            Assert.AreEqual(attributeType.Name, result.Fields["Name"].FieldValue);
            Assert.AreEqual(attributeType.Description, result.Fields["Description"].FieldValue);
            Assert.AreEqual(attributeType.Ordinal, result.Fields["Ordinal"].FieldValue);
            Assert.AreEqual(attributeType.RenderTypeProviderConfig, result.Fields["RenderTypeProviderConfig"].FieldValue);
            VerifyIEntityFields(result, attributeType);
        }
        public void Can_Save_And_Return_Subclass_Of_Typed_Entity()
        {
            //TODO: Update this test so that other providers can override the 'User' object created , for example, create an virtual
            // method to return a subclass of TypedEntity, then change the asserts to be dynamic instead of hard coded
            // then we can get this working for membership tests.

            var admin = new UserGroup()
            {
                Name = "Admin",
                Id   = HiveId.ConvertIntToGuid(999)
            };

            using (var writer = ProviderSetup.UnitFactory.Create())
            {
                writer.EntityRepository.AddOrUpdate(new SystemRoot());
                writer.EntityRepository.AddOrUpdate(FixedEntities.UserGroupVirtualRoot);
                writer.EntityRepository.AddOrUpdate(admin);
                writer.Complete();
            }

            using (var reader = ProviderSetup.UnitFactory.Create())
            {
                var output = reader.EntityRepository.Get <UserGroup>(true, HiveId.ConvertIntToGuid(999));
                Assert.AreEqual(1, output.Count());
                var outputUser = output.Single();
                Assert.AreEqual(admin.Name, outputUser.Name);
                Assert.AreEqual(admin.Id, outputUser.Id);
            }
        }
示例#3
0
        public void WhenSourceIsAccessed_LazyRelation_CallsRepository_WithBothSourceAndDestinationId()
        {
            // Arrange
            var    context          = new FakeFrameworkContext();
            var    providerGroup    = GroupedProviderMockHelper.GenerateProviderGroup(1, 0, 50, context);
            var    idRoot           = new Uri("oh-yeah://this-is-my-root/");
            var    groupUnitFactory = new GroupUnitFactory(providerGroup.Writers, idRoot, FakeHiveCmsManager.CreateFakeRepositoryContext(context), context);
            HiveId int1             = HiveId.ConvertIntToGuid(1);
            HiveId int2             = HiveId.ConvertIntToGuid(2);

            // Act & Assert
            using (var uow = groupUnitFactory.Create())
            {
                var lazyRelation = new LazyRelation <TypedEntity>(uow.Repositories, FixedRelationTypes.DefaultRelationType, int1, int2, 0);

                IReadonlyRelation <IRelatableEntity, IRelatableEntity> blah = lazyRelation;
                IRelationById blah2 = lazyRelation;

                Assert.False(lazyRelation.IsLoaded);
                var source = lazyRelation.Source;
                Assert.True(lazyRelation.IsLoaded);
                var dest = lazyRelation.Destination;

                Assert.NotNull(source);
                Assert.NotNull(dest);
            }
        }
示例#4
0
        public void WhenGetIsCalled_WithMultipleIds_MultipleItemsAreReturned(
            int allItemCount,
            int numbProviderCount,
            int numberOfPassthroughProviders)
        {
            // Arrange
            var    context          = new FakeFrameworkContext();
            var    providerGroup    = GroupedProviderMockHelper.GenerateProviderGroup(numbProviderCount, numberOfPassthroughProviders, allItemCount, context);
            var    idRoot           = new Uri("oh-yeah://this-is-my-root/");
            var    groupUnitFactory = new GroupUnitFactory(providerGroup.Writers, idRoot, FakeHiveCmsManager.CreateFakeRepositoryContext(context), context);
            HiveId int1             = HiveId.ConvertIntToGuid(1);
            HiveId int2             = HiveId.ConvertIntToGuid(2);
            HiveId int3             = HiveId.ConvertIntToGuid(3);


            // Act & Assert
            using (var uow = groupUnitFactory.Create <IContentStore>())
            {
                Assert.NotNull(uow.IdRoot);
                Assert.AreEqual(uow.IdRoot, idRoot);

                // TODO: This looks like a poor test since Get with multiple ids is actually just mocked to return three
                // but the purpose of this test is to establish that when running with multiple providers, some of which
                // are passthrough, only the correct number of items should be returned
                var items = uow.Repositories.Get <TypedEntity>(true, int1, int2, int3);
                Assert.That(items.Count(), Is.EqualTo(3 * numbProviderCount), "item count wrong");

                // Assert that the correct number of relations are returned too including passthrough providers being filtered for
                var parents = uow.Repositories.GetParentRelations(HiveId.Empty);
                Assert.That(parents.Count(), Is.EqualTo(GroupedProviderMockHelper.MockRelationCount * numbProviderCount), "parents count wrong");
            }
        }
        public void From_TypedEntity_With_Relations_To_NodeVersion()
        {
            //Arrange

            var mapper = new ManualMapper(new FakeLookupHelper(), new FakeHiveProvider());

            mapper.Configure();

            var entityParent = HiveModelCreationHelper.MockTypedEntity(false);

            entityParent.Id = HiveId.ConvertIntToGuid(1);
            var entityChild = HiveModelCreationHelper.MockTypedEntity(false);

            entityChild.Id = HiveId.ConvertIntToGuid(2);

            entityParent.Relations.Add(FixedRelationTypes.ContentTreeRelationType, entityChild);

            //Act

            var resultParent = mapper.Map <TypedEntity, NodeVersion>(entityParent);

            //var resultChild = mapper.Map<TypedEntity, NodeVersion>(entityChild);

            //Assert

            Assert.AreEqual(entityParent.EntitySchema.Alias, resultParent.AttributeSchemaDefinition.Alias);
            Assert.AreEqual(entityParent.Attributes.Count, resultParent.Attributes.Count);
            Assert.AreEqual(entityParent.Relations.Count(), resultParent.Node.OutgoingRelations.Count);
            Assert.AreEqual(entityParent.Relations.Single().Source.Id, resultParent.Node.OutgoingRelations.First().StartNode.Id);
            Assert.AreEqual(entityParent.Relations.Single().Destination.Id, resultParent.Node.OutgoingRelations.First().EndNode.Id);

            //BUG: If you call entityChild.Relations.Count() an infinite loop occurs :(
            //Assert.AreEqual(entityChild.Relations.Count(), resultChild.Node.IncomingRelations.Count);
        }
示例#6
0
        public void Create_Path_Id()
        {
            var delegateParameter = new Tuple <HiveId, CSharpCodeBlockType>(HiveId.ConvertIntToGuid(10), CSharpCodeBlockType.NodeFilter);
            var virtualPathId     = delegateParameter.Item1.GetHtmlId() + "_" + delegateParameter.Item2;
            var pathId            = CodeDelegateVirtualPath.GetOrCreateVirtualPathId(delegateParameter, virtualPathId);

            Assert.AreEqual("_DVP_u_guid____00000000000000000000000000000010_NodeFilter", pathId);
        }
示例#7
0
        public void IsSystem_WhenCreatedFromNegativeInt()
        {
            // Arrange
            var id = HiveId.ConvertIntToGuid(-100);

            // Assert
            Assert.IsTrue(id.IsSystem());
        }
示例#8
0
        public void Get_Full_Path()
        {
            var delegateParameter = new Tuple <HiveId, CSharpCodeBlockType>(HiveId.ConvertIntToGuid(10), CSharpCodeBlockType.NodeFilter);
            var virtualPathId     = delegateParameter.Item1.GetHtmlId() + "_" + delegateParameter.Item2;
            var path = CodeDelegateVirtualPath.CreateFullPath(
                CodeDelegateVirtualPath.GetOrCreateVirtualPathId(delegateParameter, virtualPathId), "cs");

            Assert.AreEqual("~/DVP.axd/_DVP_u_guid____00000000000000000000000000000010_NodeFilter.cs", path);
        }
示例#9
0
        public void RelationById_EqualityCheck()
        {
            // Arrange
            var item1 = new RelationById(HiveId.ConvertIntToGuid(5), HiveId.ConvertIntToGuid(10), FixedRelationTypes.DefaultRelationType, 0);
            var item2 = new RelationById(HiveId.ConvertIntToGuid(5), HiveId.ConvertIntToGuid(10), FixedRelationTypes.DefaultRelationType, 0);
            var item3 = new RelationById(HiveId.ConvertIntToGuid(2), HiveId.ConvertIntToGuid(10), FixedRelationTypes.DefaultRelationType, 0);

            // Assert
            Assert.AreEqual(item1, item2);
            Assert.AreNotEqual(item1, item3);
        }
示例#10
0
 private static Func <CallInfo, IEnumerable <IReadonlyRelation <IRelatableEntity, IRelatableEntity> > > MockRelations(int allItemCount)
 {
     return(x =>
     {
         var items = EnumerableExtensions.Range(
             count =>
             new Relation(
                 FixedRelationTypes.DefaultRelationType,
                 HiveModelCreationHelper.MockTypedEntity(HiveId.ConvertIntToGuid(count + 1)),     // We'll use ids starting at 1 for the 'source', with the dest being this + 5 so it creates some child / parent relations over the course of 50 created
                 HiveModelCreationHelper.MockTypedEntity(HiveId.ConvertIntToGuid(count + 5)),
                 0),
             allItemCount).ToArray();
         return items;
     });
 }
示例#11
0
        public void Is_Delegate_Path()
        {
            //first, don't add, but it is valid
            var path = "/DVP.axd/_DVP_u_guid____00000000000000000000000000000010_NodeFilter.cs";

            Assert.IsFalse(CodeDelegateVirtualPath.IsCodeDelegateVirtualPath(path));

            //now, add it to the collection
            var delegateParameter = new Tuple <HiveId, CSharpCodeBlockType>(HiveId.ConvertIntToGuid(10), CSharpCodeBlockType.NodeFilter);
            var virtualPathId     = delegateParameter.Item1.GetHtmlId() + "_" + delegateParameter.Item2;

            CodeDelegateVirtualPath.GetOrCreateVirtualPathId(delegateParameter, virtualPathId);

            //this should pass now that it is added
            Assert.IsTrue(CodeDelegateVirtualPath.IsCodeDelegateVirtualPath(path));
        }
示例#12
0
        public void BackOfficeRouting_Ensure_Default_Tree_Url_Structures()
        {
            //Arrange

            var context = new FakeHttpContextFactory("~/empty", new RouteData());

            var contentTree           = new ContentTreeController(new FakeBackOfficeRequestContext());
            var contentControllerName = RebelController.GetControllerName(contentTree.GetType());
            var contentControllerId   = RebelController.GetControllerId <TreeAttribute>(contentTree.GetType());

            var dataTypeTree           = new DataTypeTreeController(new FakeBackOfficeRequestContext());
            var dataTypeControllerName = RebelController.GetControllerName(dataTypeTree.GetType());
            var dataTypeControllerId   = RebelController.GetControllerId <TreeAttribute>(dataTypeTree.GetType());

            const string action   = "Index";
            var          customId = HiveId.ConvertIntToGuid(123);
            const string area     = "Rebel";

            //Act

            //ensure the area is passed in because we're matchin a URL in an area, otherwise it will not work

            var contentTreeDefaultUrl = UrlHelper.GenerateUrl(null, action, contentControllerName,
                                                              new RouteValueDictionary(new { area, id = HiveId.Empty, treeId = contentControllerId.ToString("N") }),
                                                              RouteTable.Routes, context.RequestContext, true);

            var dataTypeTreeDefaultUrl = UrlHelper.GenerateUrl(null, action, dataTypeControllerName,
                                                               new RouteValueDictionary(new { area, id = HiveId.Empty, treeId = dataTypeControllerId.ToString("N") }),
                                                               RouteTable.Routes, context.RequestContext, true);

            var contentTreeCustomUrl = UrlHelper.GenerateUrl(null, action, contentControllerName,
                                                             new RouteValueDictionary(new { area, id = customId, treeId = contentControllerId.ToString("N") }),
                                                             RouteTable.Routes, context.RequestContext, true);

            var dataTypeTreeCustomUrl = UrlHelper.GenerateUrl(null, action, dataTypeControllerName,
                                                              new RouteValueDictionary(new { area, id = customId, treeId = dataTypeControllerId.ToString("N") }),
                                                              RouteTable.Routes, context.RequestContext, true);

            //Assert

            Assert.AreEqual(string.Format("/Rebel/Trees/{0}", contentControllerName), contentTreeDefaultUrl);
            Assert.AreEqual(string.Format("/Rebel/Trees/{0}", dataTypeControllerName), dataTypeTreeDefaultUrl);
            Assert.AreEqual(string.Format("/Rebel/Trees/{0}/{1}/{2}", contentControllerName, action, HttpUtility.UrlEncode(customId.ToString())), contentTreeCustomUrl);
            Assert.AreEqual(string.Format("/Rebel/Trees/{0}/{1}/{2}", dataTypeControllerName, action, HttpUtility.UrlEncode(customId.ToString())), dataTypeTreeCustomUrl);
        }
示例#13
0
        public void AddingItemsManually_AsParent_ThenAsChild_ThrowsDueToInfiniteCycle()
        {
            // Arrange
            var connectedParent = HiveModelCreationHelper.MockTypedEntity();
            var middleItem      = HiveModelCreationHelper.MockTypedEntity();

            connectedParent.Id = HiveId.ConvertIntToGuid(1); // It's connected with a lazy-loader so it should have an Id
            middleItem.Id      = HiveId.ConvertIntToGuid(2); // It's connected with a lazy-loader so it should have an Id
            var rpc = new RelationProxyCollection(middleItem);

            // Act
            // Add parent to this item
            rpc.EnlistParent(connectedParent, FixedRelationTypes.DefaultRelationType);

            // Assert
            // Try to add the parent as a child of the middle item, hoping it throws
            Assert.Throws <InvalidOperationException>(() => rpc.EnlistChild(connectedParent, FixedRelationTypes.DefaultRelationType));
        }
示例#14
0
        private void InitRepository()
        {
            _testRepository = new List <ContentEditorModel>();

            var tabIds = _docTypes.SelectMany(tabs => tabs.DefinedTabs).Select(x => x.Id).ToList();

            var currTab = 0;

            XmlData.Root.Descendants()
            .Where(x => x.Attribute("isDoc") != null)
            .ToList()
            .ForEach(x =>
            {
                var customProperties = new List <ContentProperty>();
                //create the model
                var parentId = x.Attribute("parentID");
                var publishedScheduledDate   = x.Attribute("publishedScheduledDate");
                var unpublishedScheduledDate = x.Attribute("unPublishedScheduledDate");
                var publishedDate            = x.Attribute("publishedDate");

                //BUG: We need to change this back once the Hive IO provider is fixed and it get its ProviderMetadata.MappingRoot  set
                // (APN) - I've changed back
                //var template = ((string)x.Attribute("template")).IsNullOrWhiteSpace() ? HiveId.Empty : new HiveId((Uri)null, "templates", new HiveIdValue((string)x.Attribute("template")));
                var template = ((string)x.Attribute("template")).IsNullOrWhiteSpace() ? HiveId.Empty : new HiveId(new Uri("storage://templates"), "templates", new HiveIdValue((string)x.Attribute("template")));

                var docType = string.IsNullOrEmpty((string)x.Attribute("nodeType"))
                                      ? null
                                      : DocTypes.Where(d => d.Id == HiveId.ConvertIntToGuid((int)x.Attribute("nodeType"))).SingleOrDefault();

                var contentNode = new ContentEditorModel(HiveId.ConvertIntToGuid((int)x.Attribute("id")))
                {
                    Name              = (string)x.Attribute("nodeName"),
                    DocumentTypeId    = docType == null ? HiveId.Empty : docType.Id,
                    DocumentTypeName  = docType == null ? "" : docType.Name,
                    DocumentTypeAlias = docType == null ? "" : docType.Alias,
                    ParentId          = parentId != null ? HiveId.ConvertIntToGuid((int)parentId) : HiveId.Empty,
                    //assign the properties
                    Properties = GetNodeProperties((int)x.Attribute("id"), template)
                };

                //add the new model
                _testRepository.Add(contentNode);
            });
        }
示例#15
0
        public void AddingItemsLazily_AsParent_CountIsCorrect()
        {
            // Arrange
            var connectedChild = HiveModelCreationHelper.MockTypedEntity();

            connectedChild.Id = HiveId.ConvertIntToGuid(2); // It's connected with a lazy-loader so it should have an Id
            var rpc = new RelationProxyCollection(connectedChild);

            // Act
            rpc.LazyLoadDelegate = ownerIdOfProxyColl =>
            {
                var parent = new RelationById(HiveId.ConvertIntToGuid(1), ownerIdOfProxyColl, FixedRelationTypes.DefaultRelationType, 0);
                return(new RelationProxyBucket(new[] { parent }, Enumerable.Empty <RelationById>()));
            };

            // Assert
            Assert.AreEqual(1, rpc.Count());
            Assert.AreEqual(0, rpc.GetManualProxies().Count());
        }
示例#16
0
        public void AddingItemsLazily_AndManually_AsParent_CountIsCorrect()
        {
            // Arrange
            var existingItemForParent        = HiveModelCreationHelper.MockTypedEntity();
            var unsavedItemForAddingAsParent = HiveModelCreationHelper.MockTypedEntity();
            var connectedChild = HiveModelCreationHelper.MockTypedEntity();

            existingItemForParent.Id = HiveId.ConvertIntToGuid(1); // Assign Ids to mimic a lazy-loading valid scenario
            connectedChild.Id        = HiveId.ConvertIntToGuid(2); // It's connected with a lazy-loader so it should have an Id

            var rpc = new RelationProxyCollection(connectedChild);

            // Act
            // This delegate mimics a lazy-loader, which returns RelationById to stipulate that
            // the lazy loader must return existing items from the datastore
            rpc.LazyLoadDelegate = ownerIdOfCollection =>
            {
                var parent = new RelationById(HiveId.ConvertIntToGuid(1), ownerIdOfCollection, FixedRelationTypes.DefaultRelationType, 0);
                var parentShouldOverrideManuallyAdded = new RelationById(existingItemForParent.Id, ownerIdOfCollection, FixedRelationTypes.DefaultRelationType, 0);
                return(new RelationProxyBucket(new[] { parent, parentShouldOverrideManuallyAdded }, Enumerable.Empty <RelationById>()));
            };
            rpc.EnlistParent(existingItemForParent, FixedRelationTypes.DefaultRelationType);

            // Assert
            Assert.AreEqual(1, rpc.Count());
            Assert.AreEqual(0, rpc.GetManualProxies().Count());

            // Try adding more; count should not be affected
            rpc.EnlistParent(existingItemForParent, FixedRelationTypes.DefaultRelationType);
            rpc.EnlistParent(existingItemForParent, FixedRelationTypes.DefaultRelationType);
            rpc.EnlistParent(existingItemForParent, FixedRelationTypes.DefaultRelationType);
            rpc.EnlistParent(existingItemForParent, FixedRelationTypes.DefaultRelationType);
            Assert.AreEqual(1, rpc.Count());
            Assert.AreEqual(0, rpc.GetManualProxies().Count());

            // This is a second parent so should affect count
            rpc.EnlistParent(unsavedItemForAddingAsParent, FixedRelationTypes.DefaultRelationType);
            Assert.AreEqual(2, rpc.Count());
            Assert.AreEqual(1, rpc.GetManualProxies().Count());
        }
        public void From_EntitySchema_With_Relations_To_AttributeSchemaDefinition()
        {
            //Arrange

            var mapper = new ManualMapper(new FakeLookupHelper(), new FakeHiveProvider());

            mapper.Configure();

            var entityParent = HiveModelCreationHelper.MockEntitySchema("test-schema-parent", "parent");

            entityParent.Id = HiveId.ConvertIntToGuid(1);
            var entityChild = HiveModelCreationHelper.MockEntitySchema("test-schema-child", "child");

            entityChild.Id = HiveId.ConvertIntToGuid(2);

            entityParent.Relations.Add(FixedRelationTypes.SchemaTreeRelationType, entityChild);

            //Act

            var resultParent = mapper.Map <EntitySchema, AttributeSchemaDefinition>(entityParent);

            //var resultChild = mapper.Map<EntitySchema, AttributeSchemaDefinition>(entityChild);

            //Assert

            Assert.AreEqual(entityParent.Alias, resultParent.Alias);
            Assert.AreEqual(entityParent.Name.ToString(), resultParent.Name);
            Assert.AreEqual(entityParent.AttributeDefinitions.Count, resultParent.AttributeDefinitions.Count);
            Assert.AreEqual(entityParent.AttributeTypes.Count, resultParent.AttributeDefinitions.Select(x => x.AttributeType).DistinctBy(x => x.Alias).Count());
            Assert.AreEqual(entityParent.Relations.Count(), resultParent.OutgoingRelations.Count);
            Assert.AreEqual(entityParent.Relations.Single().Source.Id, resultParent.OutgoingRelations.First().StartNode.Id);
            Assert.AreEqual(entityParent.Relations.Single().Destination.Id, resultParent.OutgoingRelations.First().EndNode.Id);

            //BUG: If you call entityChild.Relations.Count() an infinite loop occurs :(
            //Assert.AreEqual(entityChild.Relations.Count(), resultChild.OutgoingRelations.Count);
        }
        public void Can_Save_And_Return_Subclass_Of_Typed_Entity()
        {
            //TODO: Update this test so that other providers can override the 'User' object created , for example, create an virtual
            // method to return a subclass of TypedEntity, then change the asserts to be dynamic instead of hard coded
            // then we can get this working for membership tests.

            var admin = new User()
            {
                Name                   = "Admin",
                Username               = "******",
                Email                  = "*****@*****.**",
                Password               = "******",
                Applications           = new[] { "test1", "test2" },
                Comments               = "comments",
                IsApproved             = true,
                LastActivityDate       = DateTimeOffset.Now,
                LastLoginDate          = DateTimeOffset.Now,
                LastPasswordChangeDate = DateTimeOffset.Now.AddDays(-1),
                PasswordAnswer         = "hello",
                PasswordQuestion       = "hi!",
                PasswordSalt           = "1234",
                SessionTimeout         = 65,
                StartContentHiveId     = HiveId.ConvertIntToGuid(1234),
                StartMediaHiveId       = HiveId.ConvertIntToGuid(321),
                Id = HiveId.ConvertIntToGuid(999)
            };

            using (var writer = ProviderSetup.UnitFactory.Create())
            {
                writer.EntityRepository.AddOrUpdate(new SystemRoot());
                writer.EntityRepository.AddOrUpdate(FixedEntities.UserVirtualRoot);
                writer.EntityRepository.AddOrUpdate(admin);
                writer.Complete();
            }



            using (var reader = ProviderSetup.UnitFactory.Create())
            {
                var output = reader.EntityRepository.Get <User>(true, HiveId.ConvertIntToGuid(999));
                Assert.AreEqual(1, output.Count());
                var outputUser = output.Single();
                Assert.AreEqual(admin.Name, outputUser.Name);
                Assert.AreEqual(admin.Username, outputUser.Username);
                Assert.AreEqual(admin.Email, outputUser.Email);
                Assert.AreEqual(admin.Password, outputUser.Password);
                Assert.AreEqual(admin.Applications, outputUser.Applications);
                Assert.AreEqual(admin.Comments, outputUser.Comments);
                Assert.AreEqual(admin.IsApproved, outputUser.IsApproved);
                Assert.AreNotEqual(admin.LastActivityDate, DateTimeOffset.MinValue);
                Assert.AreEqual(admin.LastActivityDate, outputUser.LastActivityDate);
                Assert.AreNotEqual(admin.LastLoginDate, DateTimeOffset.MinValue);
                Assert.AreEqual(admin.LastLoginDate, outputUser.LastLoginDate);
                Assert.AreNotEqual(admin.LastPasswordChangeDate, DateTimeOffset.MinValue);
                Assert.AreEqual(admin.LastPasswordChangeDate, outputUser.LastPasswordChangeDate);
                Assert.AreEqual(admin.PasswordAnswer, outputUser.PasswordAnswer);
                Assert.AreEqual(admin.PasswordQuestion, outputUser.PasswordQuestion);
                Assert.AreEqual(admin.PasswordSalt, outputUser.PasswordSalt);
                Assert.AreEqual(admin.SessionTimeout, outputUser.SessionTimeout);
                Assert.AreEqual(admin.StartContentHiveId, outputUser.StartContentHiveId);
                Assert.AreEqual(admin.StartMediaHiveId, outputUser.StartMediaHiveId);
                Assert.AreEqual(admin.Id, outputUser.Id);
            }
        }
示例#19
0
        public void Deleting_Schema_Removes_All_Entities()
        {
            Action <NhibernateTestSetupHelper> runTest = setupHelper =>
            {
                //Arrange

                Revision <TypedEntity> content1 = HiveModelCreationHelper.MockVersionedTypedEntity();
                Revision <TypedEntity> content2 = HiveModelCreationHelper.MockVersionedTypedEntity();
                //assign ids to create a relation
                content1.Item.Id = HiveId.ConvertIntToGuid(1);
                content2.Item.Id = HiveId.ConvertIntToGuid(2);
                content1.Item.RelationProxies.EnlistChild(content2.Item, FixedRelationTypes.DefaultRelationType);
                //assign ids to schema and create schema relation
                content1.Item.EntitySchema.Id = HiveId.ConvertIntToGuid(10);
                content2.Item.EntitySchema.Id = HiveId.ConvertIntToGuid(20);
                content1.Item.EntitySchema.RelationProxies.EnlistChild(content2.Item.EntitySchema, FixedRelationTypes.DefaultRelationType);

                using (var uow = setupHelper.ProviderSetup.UnitFactory.Create())
                {
                    uow.EntityRepository.Revisions.AddOrUpdate(content1);
                    //make some versions
                    uow.EntityRepository.Revisions.AddOrUpdate(content2);
                    uow.EntityRepository.Revisions.AddOrUpdate(content1);
                    uow.Complete();
                }
                //PostWriteCallback.Invoke();
                setupHelper.SessionForTest.Clear();

                //Act

                // First check that all items are loadable fine
                using (var uow = setupHelper.ProviderSetup.UnitFactory.Create())
                {
                    var attributeType = uow.EntityRepository.Schemas.Get <EntitySchema>(content1.Item.EntitySchema.Id);
                    Assert.IsNotNull(attributeType);
                    var revisionReloaded = uow.EntityRepository.Revisions.Get <TypedEntity>(content1.Item.Id, content1.MetaData.Id);
                    Assert.IsNotNull(revisionReloaded);
                    var contentReloaded = uow.EntityRepository.Get <TypedEntity>(content1.Item.Id);
                    Assert.IsNotNull(contentReloaded);
                }

                using (var uow = setupHelper.ProviderSetup.UnitFactory.Create())
                {
                    uow.EntityRepository.Schemas.Delete <EntitySchema>(content1.Item.EntitySchema.Id);
                    uow.Complete();
                }
                //PostWriteCallback.Invoke();
                setupHelper.SessionForTest.Clear();

                //Assert

                using (var uow = setupHelper.ProviderSetup.UnitFactory.Create())
                {
                    var attributeType = uow.EntityRepository.Schemas.Get <EntitySchema>(content1.Item.EntitySchema.Id);
                    Assert.IsNull(attributeType);
                    var revisionReloaded = uow.EntityRepository.Revisions.Get <TypedEntity>(content1.Item.Id, content1.MetaData.Id);
                    Assert.IsNull(revisionReloaded);
                    var contentReloaded = uow.EntityRepository.Get <TypedEntity>(content1.Item.Id);
                    Assert.IsNull(contentReloaded);
                }
                //PostWriteCallback.Invoke();
                setupHelper.SessionForTest.Clear();
            };

            //runTest(DirectReadWriteProvider);
            runTest(new NhibernateTestSetupHelper());
        }
示例#20
0
        private void DoCoreAssertions(IHiveManager hiveManager, int totalSchemaCount, int totalEntityCount, int totalAttributeTypeCount, int mediaSchemaCount, IEnumerable <Lazy <Permission, PermissionMetadata> > permissions, ISecurityService securityService)
        {
            //Assert

            using (var uow = hiveManager.OpenReader <IContentStore>())
            {
                Assert.IsTrue(uow.Repositories.Exists <TypedEntity>(FixedHiveIds.SystemRoot));
                Assert.IsTrue(uow.Repositories.Exists <TypedEntity>(FixedEntities.ContentVirtualRoot.Id));
                Assert.IsTrue(uow.Repositories.Exists <TypedEntity>(FixedEntities.ContentRecycleBin.Id));
                Assert.IsTrue(uow.Repositories.Exists <TypedEntity>(FixedEntities.MediaVirtualRoot.Id));
                Assert.IsTrue(uow.Repositories.Exists <TypedEntity>(FixedEntities.MediaRecycleBin.Id));
                Assert.IsTrue(uow.Repositories.Exists <TypedEntity>(Framework.Security.Model.FixedEntities.UserGroupVirtualRoot.Id));
                Assert.IsTrue(uow.Repositories.Exists <TypedEntity>(Framework.Security.Model.FixedEntities.UserVirtualRoot.Id));

                Assert.IsTrue(uow.Repositories.Schemas.Exists <EntitySchema>(FixedSchemas.ContentRootSchema.Id));
                Assert.IsTrue(uow.Repositories.Schemas.Exists <EntitySchema>(FixedSchemas.MediaRootSchema.Id));
                Assert.IsTrue(uow.Repositories.Schemas.Exists <EntitySchema>(Rebel.Framework.Security.Model.FixedSchemas.MembershipUserSchema.Id));
                Assert.IsTrue(uow.Repositories.Schemas.Exists <EntitySchema>(Rebel.Framework.Security.Model.FixedSchemas.UserGroup.Id));
                Assert.IsTrue(uow.Repositories.Schemas.Exists <EntitySchema>(FixedSchemas.MediaFolderSchema.Id));
                Assert.IsTrue(uow.Repositories.Schemas.Exists <EntitySchema>(FixedSchemas.MediaImageSchema.Id));

                //MB: Removed the below as creating of Admin is no longer part of the DataInstallTask
                // Get the admin user and check roles
                //var adminMemberUser = securityService.Users.GetByUsername("admin", false);
                //Assert.NotNull(adminMemberUser);
                //Assert.True(adminMemberUser.Groups.Any());


                var schemas = uow.Repositories.Schemas.GetAll <EntitySchema>().ToArray();

                Assert.IsTrue(schemas.SelectMany(x => x.AttributeGroups).Any());
                Assert.IsTrue(schemas.SelectMany(x => x.AttributeGroups).All(x => x != null));

                //ensure that schemas have relations on them
                var mediaImage = schemas.Where(x => x.Alias == "mediaImage").Single();
                Assert.True(mediaImage.RelationProxies.IsConnected);
                Assert.AreEqual(FixedHiveIds.MediaRootSchema.Value, mediaImage.RelationProxies.Single().Item.SourceId.Value);

                var mediaSchemas = uow.Repositories.Schemas.GetChildren <EntitySchema>(FixedRelationTypes.DefaultRelationType, FixedHiveIds.MediaRootSchema);
                Assert.AreEqual(mediaSchemaCount, mediaSchemas.Count());


                //ensure that the built in attribute types are there and set correctly
                var attributeTypes = uow.Repositories.Schemas.GetAll <AttributeType>().ToArray();
                Assert.IsTrue(attributeTypes.Any(x => x.Alias == StringAttributeType.AliasValue));
                Assert.IsTrue(attributeTypes.Any(x => x.Alias == BoolAttributeType.AliasValue));
                Assert.IsTrue(attributeTypes.Any(x => x.Alias == DateTimeAttributeType.AliasValue));
                Assert.IsTrue(attributeTypes.Any(x => x.Alias == IntegerAttributeType.AliasValue));
                Assert.IsTrue(attributeTypes.Any(x => x.Alias == TextAttributeType.AliasValue));
                Assert.IsTrue(attributeTypes.Any(x => x.Alias == NodeNameAttributeType.AliasValue));
                Assert.IsTrue(attributeTypes.Any(x => x.Alias == SelectedTemplateAttributeType.AliasValue));
                // TODO: Add other in built attribute types

                //now make sure that the render types are set
                var inbuiltString = attributeTypes.Single(x => x.Alias == StringAttributeType.AliasValue);
                Assert.AreEqual(CorePluginConstants.TextBoxPropertyEditorId, inbuiltString.RenderTypeProvider);
                var inbuiltText = attributeTypes.Single(x => x.Alias == TextAttributeType.AliasValue);
                Assert.AreEqual(CorePluginConstants.TextBoxPropertyEditorId, inbuiltText.RenderTypeProvider);
                var inbuiltDateTime = attributeTypes.Single(x => x.Alias == DateTimeAttributeType.AliasValue);
                Assert.AreEqual(CorePluginConstants.DateTimePickerPropertyEditorId, inbuiltDateTime.RenderTypeProvider);
                var inbuiltBool = attributeTypes.Single(x => x.Alias == BoolAttributeType.AliasValue);
                Assert.AreEqual(CorePluginConstants.TrueFalsePropertyEditorId, inbuiltBool.RenderTypeProvider);
                // TODO: Add other in built attribute types

                var entities = uow.Repositories.GetAll <TypedEntity>().ToArray();

                AssertItems(entities, CoreCmsData.RequiredCoreUserGroups(permissions), (x, y) => x.Name == y.Name, x => x.Name);

                var rootCount = entities.Count(x => x.EntitySchema.Alias == CoreCmsData.RequiredCoreRootNodes().First().EntitySchema.Alias);
                Assert.That(rootCount, Is.EqualTo(CoreCmsData.RequiredCoreRootNodes().Count()), "Root count different");

                //var userCount = entities.Where(x => x.EntitySchema.Alias == CoreCmsData.RequiredCoreUsers().First().EntitySchema.Alias).ToList();
                //Assert.That(userCount.Count, Is.EqualTo(CoreCmsData.RequiredCoreUsers().Count()), "User count different");

                var userGroupCount = entities.Count(x => x.EntitySchema.Alias == CoreCmsData.RequiredCoreUserGroups(permissions).First().EntitySchema.Alias);
                Assert.That(userGroupCount, Is.EqualTo(CoreCmsData.RequiredCoreUserGroups(permissions).Count()), "User group count different");

                //MB: Removed the below as administrator setup is no longer part of the DataInstallTask

                /*
                 * var adminUser = entities.SingleOrDefault(x => x.EntitySchema.Id.Value == Framework.Security.Model.FixedHiveIds.MembershipUserSchema.Value);
                 * Assert.IsNotNull(adminUser);
                 * Assert.IsTrue(adminUser.AttributeGroups.All(x => x != null));
                 * Assert.IsTrue(adminUser.AttributeGroups.Any());
                 * Assert.IsTrue(adminUser.EntitySchema.AttributeGroups.All(x => x != null));
                 * Assert.IsTrue(adminUser.EntitySchema.AttributeGroups.Any());
                 * var attributeGroups = adminUser.EntitySchema.AttributeDefinitions.Select(x => new {Def = x, x.AttributeGroup}).ToArray();
                 * var nullGroupsMsg = attributeGroups.Where(x => x.AttributeGroup == null).Select(x => x.Def.Alias).ToArray();
                 * Assert.That(nullGroupsMsg.Length, Is.EqualTo(0), "Group is null for attrib defs: " + string.Join(", ", nullGroupsMsg));
                 */

                //ensure they're all published
                foreach (var e in entities.Where(x => x.IsContent(uow) || x.IsMedia((uow))))
                {
                    var snapshot = uow.Repositories.Revisions.GetLatestSnapshot <TypedEntity>(e.Id);
                    Assert.AreEqual(FixedStatusTypes.Published.Alias, snapshot.Revision.MetaData.StatusType.Alias);
                }

                // Admin user is not longer created as part of the data install task
                //var adminUser = entities.SingleOrDefault(x => x.EntitySchema.Id.Value == FixedHiveIds.UserSchema.Value);
                //Assert.IsNotNull(adminUser);
                //Assert.IsTrue(adminUser.AttributeGroups.All(x => x != null));
                //Assert.IsTrue(adminUser.AttributeGroups.Any());
                //Assert.IsTrue(adminUser.EntitySchema.AttributeGroups.All(x => x != null));
                //Assert.IsTrue(adminUser.EntitySchema.AttributeGroups.Any());
                //Assert.IsTrue(adminUser.EntitySchema.AttributeDefinitions.Select(x => x.AttributeGroup).All(x => x != null));

                var distinctTypesByAlias = attributeTypes.DistinctBy(x => x.Alias).ToArray();
                var actualCount          = attributeTypes.Count();
                var distinctCount        = distinctTypesByAlias.Count();
                var actualCountById      = attributeTypes.DistinctBy(x => x.Id).Count();
                var allWithAliasAndId    = string.Join("\n", attributeTypes.OrderBy(x => x.Alias).Select(x => x.Alias + ": " + x.Id.Value));
                Assert.That(actualCount, Is.EqualTo(distinctCount),
                            "Duplicate AttributeTypes were created: {0} distinct by alias, {1} total loaded from provider, {2} distinct by id. All:{3}".InvariantFormat(distinctCount, actualCount, actualCountById, allWithAliasAndId));

                Assert.AreEqual(totalAttributeTypeCount, actualCount);

                //ensure the default templates are set
                var contentRoot      = new Uri("content://");
                var homePage         = entities.Single(x => x.Id.EqualsIgnoringProviderId(HiveId.ConvertIntToGuid(contentRoot, null, 1048)));
                var templateRoot     = new Uri("storage://templates");
                var templateProvider = "templates";

                Assert.AreEqual(new HiveId(templateRoot, templateProvider, new HiveIdValue("Homepage.cshtml")).ToString(),
                                homePage.Attributes[SelectedTemplateAttributeDefinition.AliasValue].DynamicValue.ToString());

                var installingModules = entities.Single(x => x.Id.EqualsIgnoringProviderId(HiveId.ConvertIntToGuid(contentRoot, null, 1049)));
                Assert.AreEqual(new HiveId(templateRoot, templateProvider, new HiveIdValue("Textpage.cshtml")).ToString(),
                                installingModules.Attributes[SelectedTemplateAttributeDefinition.AliasValue].DynamicValue.ToString());

                var faq = entities.Single(x => x.Id.EqualsIgnoringProviderId(HiveId.ConvertIntToGuid(contentRoot, null, 1059)));
                Assert.AreEqual(new HiveId(templateRoot, templateProvider, new HiveIdValue("Faq.cshtml")).ToString(),
                                faq.Attributes[SelectedTemplateAttributeDefinition.AliasValue].DynamicValue.ToString());

                //ensure the allowed templates are set
                Assert.AreEqual(1, homePage.EntitySchema.GetXmlPropertyAsList <HiveId>("allowed-templates").Count());
                Assert.AreEqual(new HiveId(templateRoot, templateProvider, new HiveIdValue("Homepage.cshtml")).ToString(),
                                homePage.EntitySchema.GetXmlPropertyAsList <HiveId>("allowed-templates").Single().ToString());
                Assert.AreEqual(1, installingModules.EntitySchema.GetXmlPropertyAsList <HiveId>("allowed-templates").Count());
                Assert.AreEqual(new HiveId(templateRoot, templateProvider, new HiveIdValue("Textpage.cshtml")).ToString(),
                                installingModules.EntitySchema.GetXmlPropertyAsList <HiveId>("allowed-templates").Single().ToString());
                Assert.AreEqual(1, faq.EntitySchema.GetXmlPropertyAsList <HiveId>("allowed-templates").Count());
                Assert.AreEqual(new HiveId(templateRoot, templateProvider, new HiveIdValue("Faq.cshtml")).ToString(),
                                faq.EntitySchema.GetXmlPropertyAsList <HiveId>("allowed-templates").Single().ToString());

                //ensure the allowed children are set
                var allowedChildrenOfHomepage = homePage.EntitySchema.GetXmlPropertyAsList <HiveId>("allowed-children").ToArray();
                Assert.AreEqual(2, allowedChildrenOfHomepage.Count());

                // Check installing-modules is an allowed child of homepage
                Assert.That(allowedChildrenOfHomepage.Select(x => x.Value), Has.Some.EqualTo(installingModules.EntitySchema.Id.Value));

                var faqCat = entities.Single(x => x.Id.EqualsIgnoringProviderId(HiveId.ConvertIntToGuid(contentRoot, null, 1060)));
                Assert.AreEqual(1, faq.EntitySchema.GetXmlPropertyAsList <HiveId>("allowed-children").Count());
                Assert.IsTrue(faqCat.EntitySchema.Id.EqualsIgnoringProviderId(faq.EntitySchema.GetXmlPropertyAsList <HiveId>("allowed-children").Single()));

                var faqQuestion = entities.Single(x => x.Id.EqualsIgnoringProviderId(HiveId.ConvertIntToGuid(contentRoot, null, 1067)));
                Assert.AreEqual(1, faqCat.EntitySchema.GetXmlPropertyAsList <HiveId>("allowed-children").Count());
                Assert.IsTrue(faqQuestion.EntitySchema.Id.EqualsIgnoringProviderId(faqCat.EntitySchema.GetXmlPropertyAsList <HiveId>("allowed-children").Single()));

                var userGroups = uow.Repositories.GetAll <UserGroup>()
                                 .Where(x => x.EntitySchema.Alias == UserGroupSchema.SchemaAlias);
                Assert.AreEqual(CoreCmsData.RequiredCoreUserGroups(permissions).Count(), userGroups.Count());
                var adminUserGroup = userGroups.First();
                Assert.AreEqual(1, adminUserGroup.RelationProxies.GetChildRelations(FixedRelationTypes.PermissionRelationType).Count());
                Assert.AreEqual(permissions.Count(),
                                adminUserGroup.RelationProxies.GetChildRelations(FixedRelationTypes.PermissionRelationType).Single().Item.MetaData.Count());
            }

            // Check same method coverage on GroupUnit<T>
            using (var uow = hiveManager.OpenWriter <IContentStore>())
            {
                Assert.IsTrue(uow.Repositories.Exists <TypedEntity>(FixedHiveIds.SystemRoot));
                Assert.IsTrue(uow.Repositories.Schemas.Exists <EntitySchema>(FixedSchemas.ContentRootSchema.Id));
                var schemas = uow.Repositories.Schemas.GetAll <EntitySchema>().ToArray();
                Assert.AreEqual(totalSchemaCount, schemas.Count());
                var mediaImage = schemas.Where(x => x.Alias == "mediaImage").Single();
                Assert.True(mediaImage.RelationProxies.IsConnected);
                Assert.AreEqual(FixedHiveIds.MediaRootSchema.Value, mediaImage.RelationProxies.Single().Item.SourceId.Value);

                var entities = uow.Repositories.GetAll <TypedEntity>().ToArray();
                Assert.AreEqual(totalEntityCount, entities.Count());
                var attributeTypes = uow.Repositories.Schemas.GetAll <AttributeType>().ToArray();
                Assert.AreEqual(totalAttributeTypeCount, attributeTypes.Count());
            }
        }
示例#21
0
        public void HiveEntityExtensions_GetAllIdentifiableItems_Perf()
        {
            // Arrange
            var items = EnumerableExtensions.Range(count => HiveModelCreationHelper.MockTypedEntity(HiveId.ConvertIntToGuid(count + 1)), 250).ToArray();

            // Act & Assert
            using (DisposableTimer.TraceDuration <GroupActorTests>("Starting getting all dependents", "Finished"))
            {
                var allGraph = new List <IReferenceByHiveId>();
                foreach (var typedEntity in items)
                {
                    allGraph.AddRange(typedEntity.GetAllIdentifiableItems().ToArray());
                }
                LogHelper.TraceIfEnabled <GroupActorTests>("Found {0} items", () => allGraph.Count);
            }
        }
示例#22
0
        private HashSet <ContentProperty> GetNodeProperties(int id, HiveId selectedTemplateId)
        {
            var customProperties = new List <ContentProperty>();
            var tabIds           = _docTypes.SelectMany(tabs => tabs.DefinedTabs).Select(x => x.Id).ToList();
            var currTab          = 0;

            var node = XmlData.Root.Descendants()
                       .Where(x => (string)x.Attribute("id") == id.ToString())
                       .Single();

            var docTypeArray = _docTypes.ToArray();
            //get the corresponding doc type for this node
            var docType = docTypeArray
                          .Where(x => x.Id == HiveId.ConvertIntToGuid(int.Parse((string)node.Attribute("nodeType"))))
                          .Single();

            //add node name
            var nodeName = new ContentProperty((HiveId)Guid.NewGuid(),
                                               docType.Properties.Where(x => x.Alias == NodeNameAttributeDefinition.AliasValue).Single(),
                                               new Dictionary <string, object> {
                { "Name", (string)node.Attribute("nodeName") }
            })
            {
                Name  = NodeNameAttributeDefinition.AliasValue,
                Alias = NodeNameAttributeDefinition.AliasValue,
                TabId = docType.DefinedTabs.Where(x => x.Alias == _generalGroup.Alias).Single().Id
            };

            customProperties.Add(nodeName);

            //add selected template (empty)
            var selectedTemplate = new ContentProperty((HiveId)Guid.NewGuid(),
                                                       docType.Properties.Where(x => x.Alias == SelectedTemplateAttributeDefinition.AliasValue).Single(),
                                                       selectedTemplateId.IsNullValueOrEmpty() ? new Dictionary <string, object>() : new Dictionary <string, object> {
                { "TemplateId", selectedTemplateId.ToString() }
            })
            {
                Name  = SelectedTemplateAttributeDefinition.AliasValue,
                Alias = SelectedTemplateAttributeDefinition.AliasValue,
                TabId = docType.DefinedTabs.Where(x => x.Alias == _generalGroup.Alias).Single().Id
            };

            customProperties.Add(selectedTemplate);

            customProperties.AddRange(
                node.Elements()
                .Where(e => e.Attribute("isDoc") == null)
                .Select(e =>
            {
                //Assigning the doc type properties is completely arbitrary here, all I'm doing is
                //aligning a DocumentTypeProperty that contains the DataType that I want to render

                ContentProperty np;
                DocumentTypeProperty dp;
                switch (e.Name.LocalName)
                {
                case "bodyText":
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[0]);
                    dp = docType.Properties.Where(x => x.Alias == "bodyText").Single();
                    np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                    break;

                case "colorSwatchPicker":
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[2]);
                    dp = docType.Properties.Where(x => x.Alias == "colorSwatchPicker").Single();
                    np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                    break;

                case "tags":
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[3]);
                    dp = docType.Properties.Where(x => x.Alias == "tags").Single();
                    np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                    break;

                case "textBox":
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[4]) { OverriddenPreValues = overridenPreVals };
                    dp = docType.Properties.Where(x => x.Alias == "textBox").Single();
                    np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                    break;

                case "publisher":
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[4]) { OverriddenPreValues = overridenPreVals };
                    dp = docType.Properties.Where(x => x.Alias == "publisher").Single();
                    np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                    break;

                case "numberOfPages":
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[4]) { OverriddenPreValues = overridenPreVals };
                    dp = docType.Properties.Where(x => x.Alias == "numberOfPages").Single();
                    np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                    break;

                case "image":
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[4]) { OverriddenPreValues = overridenPreVals };
                    dp         = docType.Properties.Where(x => x.Alias == "image").Single();
                    var values = e.Value.Split(',');
                    np         = new ContentProperty((HiveId)GetNodeProperty(e), dp, new Dictionary <string, object> {
                        { "MediaId", values[0] }, { "Value", values[1] }
                    });
                    break;

                default:
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[1]);
                    dp = docType.Properties.Where(x => x.Alias == e.Name.LocalName).Single();
                    np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                    break;
                }

                //need to set the data type model for this property

                np.Alias = e.Name.LocalName;
                np.Name  = e.Name.LocalName;

                //add to a random tab
                currTab  = 0;        // currTab == 2 ? 0 : ++currTab;
                np.TabId = tabIds[currTab];

                return(np);
            }).ToList());

            return(new HashSet <ContentProperty>(customProperties));
        }
示例#23
0
        private void InitDocTypes()
        {
            Func <Tab[]> generateTabs = () => new[]
            {
                new Tab {
                    Id = HiveId.ConvertIntToGuid(++_tabIdCounter), Alias = "tab1", Name = "Some Content", SortOrder = 0
                },
                new Tab {
                    Id = HiveId.ConvertIntToGuid(++_tabIdCounter), Alias = "tab2", Name = "A second test tab", SortOrder = 1
                },
                new Tab {
                    Id = HiveId.ConvertIntToGuid(++_tabIdCounter), Alias = "tab3", Name = "Other info", SortOrder = 2
                },
                //add the general tab
                new Tab
                {
                    Id = HiveId.ConvertIntToGuid(++_tabIdCounter), Alias = _generalGroup.Alias, Name = _generalGroup.Name, SortOrder = _generalGroup.Ordinal
                }
            };

            var providerGroupRoot = new Uri("content://");
            var homePage          = new DocumentTypeEditorModel(HiveId.ConvertIntToGuid(1045))
            {
                Name             = "Home Page",
                Description      = "Represents a home page node",
                Icon             = "/house.png",
                Thumbnail        = "home.png",
                Alias            = "homePage",
                AllowedTemplates = new List <SelectListItem>(new[]
                {
                    _templates.First()
                }.Select(x => new SelectListItem {
                    Selected = true, Text = x.Name, Value = x.Id.ToString()
                })),
                DefaultTemplateId = _templates.First().Id,
                DefinedTabs       = new HashSet <Tab>(generateTabs.Invoke()),
                InheritFrom       = new[] { new HierarchicalSelectListItem
                                            {
                                                Selected = true,
                                                Value    = FixedHiveIds.ContentRootSchema.ToString()
                                            } },
                AllowedChildren = new[]
                {
                    new SelectListItem
                    {
                        Selected = true,
                        Value    = HiveId.ConvertIntToGuid(providerGroupRoot, "nhibernate", 1046).ToString()
                    },

                    new SelectListItem
                    {
                        Selected = true,
                        Value    = HiveId.ConvertIntToGuid(providerGroupRoot, "nhibernate", 2000).ToString()
                    }
                }
            };

            homePage.Properties = new HashSet <DocumentTypeProperty>(new[]
            {
                CreateNodeName(homePage),
                CreateSelectedTemplateId(homePage),
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[0])
                {
                    Name = "Body Text", Alias = "bodyText", TabId = homePage.DefinedTabs.ElementAt(0).Id, SortOrder = 0
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[1])
                {
                    Name = "Site Name", Alias = "siteName", TabId = homePage.DefinedTabs.ElementAt(1).Id, SortOrder = 1
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[1])
                {
                    Name = "Site Description", Alias = "siteDescription", TabId = homePage.DefinedTabs.ElementAt(1).Id, SortOrder = 2
                },
            });

            var contentPage = new DocumentTypeEditorModel(HiveId.ConvertIntToGuid(1046))
            {
                Name             = "Content Page",
                Description      = "A page for content",
                Icon             = "tree-doc",
                Thumbnail        = "doc.png",
                Alias            = "contentPage",
                AllowedTemplates = new List <SelectListItem>(new[] { _templates.ElementAt(1) }.Select(x => new SelectListItem {
                    Selected = true, Text = x.Name, Value = x.Id.ToString()
                })),
                DefaultTemplateId = _templates.ElementAt(1).Id,
                DefinedTabs       = new HashSet <Tab>(generateTabs.Invoke()),
                InheritFrom       = new[] { new HierarchicalSelectListItem
                                            {
                                                Selected = true,
                                                Value    = FixedHiveIds.ContentRootSchema.ToString()
                                            } },
                AllowedChildren = new[]
                {
                    new SelectListItem
                    {
                        Selected = true,
                        Value    = HiveId.ConvertIntToGuid(providerGroupRoot, "nhibernate", 1046).ToString()
                    }
                }
            };

            contentPage.Properties = new HashSet <DocumentTypeProperty>(new[]
            {
                CreateNodeName(contentPage),
                CreateSelectedTemplateId(contentPage),
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[0])
                {
                    Name = "Body Text", Alias = "bodyText", TabId = contentPage.DefinedTabs.ElementAt(0).Id, SortOrder = 0
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[1])
                {
                    Name = "Rebel Hide in Nav", Alias = "rebelNaviHide", TabId = contentPage.DefinedTabs.ElementAt(1).Id, SortOrder = 4
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[2])
                {
                    Name = "Color Swatch Picker", Alias = "colorSwatchPicker", TabId = contentPage.DefinedTabs.ElementAt(0).Id, SortOrder = 5
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[3])
                {
                    Name = "Tags", Alias = "tags", TabId = contentPage.DefinedTabs.ElementAt(0).Id, SortOrder = 5
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[4])
                {
                    Name = "Textbox", Alias = "textBox", TabId = contentPage.DefinedTabs.ElementAt(0).Id, SortOrder = 5
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[1])
                {
                    Name = "New tree", Alias = "newTree", TabId = contentPage.DefinedTabs.ElementAt(0).Id, SortOrder = 5
                }
            });

            var faq = new DocumentTypeEditorModel(HiveId.ConvertIntToGuid(1055))
            {
                Name             = "Faq",
                Description      = "A Faqs container",
                Icon             = "tree-doc",
                Thumbnail        = "doc.png",
                Alias            = "Faq",
                AllowedTemplates = new List <SelectListItem>(new[] { _templates.ElementAt(2) }.Select(x => new SelectListItem {
                    Selected = true, Text = x.Name, Value = x.Id.ToString()
                })),
                DefaultTemplateId = _templates.ElementAt(2).Id,
                DefinedTabs       = new HashSet <Tab>(generateTabs.Invoke()),
                InheritFrom       = new[] { new HierarchicalSelectListItem
                                            {
                                                Selected = true,
                                                Value    = FixedHiveIds.ContentRootSchema.ToString()
                                            } },
                AllowedChildren = new[]
                {
                    new SelectListItem
                    {
                        Selected = true,
                        Value    = HiveId.ConvertIntToGuid(providerGroupRoot, "nhibernate", 1056).ToString()
                    }
                }
            };

            faq.Properties = new HashSet <DocumentTypeProperty>(new[]
            {
                CreateNodeName(faq),
                CreateSelectedTemplateId(faq),
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[0])
                {
                    Name = "Body Text", Alias = "bodyText", TabId = faq.DefinedTabs.ElementAt(0).Id, SortOrder = 0
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[1])
                {
                    Name = "Rebel Hide in Nav", Alias = "rebelNaviHide", TabId = faq.DefinedTabs.ElementAt(1).Id, SortOrder = 4
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[1])
                {
                    Name = "Show Form", Alias = "ShowForm", TabId = faq.DefinedTabs.ElementAt(0).Id, SortOrder = 5
                },
            });

            var faqCategory = new DocumentTypeEditorModel(HiveId.ConvertIntToGuid(1056))
            {
                Name        = "Faq Category",
                Description = "An Faq category",
                Icon        = "tree-doc",
                Thumbnail   = "doc.png",
                Alias       = "FaqCategory",
                //AllowedTemplates = new List<SelectListItem>(new[] { _templates.ElementAt(3) }.Select(x => new SelectListItem { Selected = true, Text = x.Name, Value = x.Id.ToString() })),
                //DefaultTemplateId = _templates.ElementAt(3).Id,
                DefinedTabs = new HashSet <Tab>(generateTabs.Invoke()),
                InheritFrom = new[] { new HierarchicalSelectListItem
                                      {
                                          Selected = true,
                                          Value    = FixedHiveIds.ContentRootSchema.ToString()
                                      } },
                AllowedChildren = new[]
                {
                    new SelectListItem
                    {
                        Selected = true,
                        Value    = HiveId.ConvertIntToGuid(providerGroupRoot, "nhibernate", 1057).ToString()
                    }
                }
            };

            faqCategory.Properties = new HashSet <DocumentTypeProperty>(new[]
            {
                CreateNodeName(faqCategory),
                CreateSelectedTemplateId(faqCategory),
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[0])
                {
                    Name = "Body Text", Alias = "bodyText", TabId = faqCategory.DefinedTabs.ElementAt(0).Id, SortOrder = 0
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[1])
                {
                    Name = "Rebel Hide in Nav", Alias = "rebelNaviHide", TabId = faqCategory.DefinedTabs.ElementAt(1).Id, SortOrder = 4
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[1])
                {
                    Name = "Show Form", Alias = "ShowForm", TabId = faqCategory.DefinedTabs.ElementAt(0).Id, SortOrder = 5
                },
            });

            var faqQuestion = new DocumentTypeEditorModel(HiveId.ConvertIntToGuid(1057))
            {
                Name        = "Faq Question",
                Description = "An Faq question",
                Icon        = "tree-doc",
                Thumbnail   = "doc.png",
                Alias       = "FaqQuestion",
                //AllowedTemplates = new List<SelectListItem>(new[] { _templates.ElementAt(4) }.Select(x => new SelectListItem { Selected = true, Text = x.Name, Value = x.Id.ToString() })),
                //DefaultTemplateId = _templates.ElementAt(4).Id,
                DefinedTabs = new HashSet <Tab>(generateTabs.Invoke()),
                InheritFrom = new[] { new HierarchicalSelectListItem
                                      {
                                          Selected = true,
                                          Value    = FixedHiveIds.ContentRootSchema.ToString()
                                      } },
            };

            faqQuestion.Properties = new HashSet <DocumentTypeProperty>(new[]
            {
                CreateNodeName(faqQuestion),
                CreateSelectedTemplateId(faqQuestion),
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[0])
                {
                    Name = "Body Text", Alias = "bodyText", TabId = faqQuestion.DefinedTabs.ElementAt(0).Id, SortOrder = 0
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[1])
                {
                    Name = "Question Text", Alias = "questionText", TabId = faqQuestion.DefinedTabs.ElementAt(1).Id, SortOrder = 1
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[1])
                {
                    Name = "Rebel Hide in Nav", Alias = "rebelNaviHide", TabId = faqQuestion.DefinedTabs.ElementAt(1).Id, SortOrder = 4
                },
            });

            var booksPage = new DocumentTypeEditorModel(HiveId.ConvertIntToGuid(2000))
            {
                Name             = "Books Page",
                Description      = "List of usefull books",
                Icon             = "tree-doc",
                Thumbnail        = "doc.png",
                Alias            = "BooksPage",
                AllowedTemplates = new List <SelectListItem>(new[] { _templates.ElementAt(5) }.Select(x => new SelectListItem {
                    Selected = true, Text = x.Name, Value = x.Id.ToString()
                })),
                DefaultTemplateId = _templates.ElementAt(5).Id,
                DefinedTabs       = new HashSet <Tab>(new[]
                {
                    new Tab {
                        Id = HiveId.ConvertIntToGuid(++_tabIdCounter), Alias = "content", Name = "Content", SortOrder = 0
                    },
                    new Tab {
                        Id = HiveId.ConvertIntToGuid(++_tabIdCounter), Alias = _generalGroup.Alias, Name = _generalGroup.Name, SortOrder = _generalGroup.Ordinal
                    }
                }),
                InheritFrom = new[] { new HierarchicalSelectListItem
                                      {
                                          Selected = true,
                                          Value    = FixedHiveIds.ContentRootSchema.ToString()
                                      } },
                AllowedChildren = new[]
                {
                    new SelectListItem
                    {
                        Selected = true,
                        Value    = HiveId.ConvertIntToGuid(providerGroupRoot, "nhibernate", 2001).ToString()
                    }
                }
            };

            booksPage.Properties = new HashSet <DocumentTypeProperty>(new[]
            {
                CreateNodeName(booksPage),
                CreateSelectedTemplateId(booksPage)
            });

            var bookPage = new DocumentTypeEditorModel(HiveId.ConvertIntToGuid(2001))
            {
                Name             = "Book Page",
                Description      = "An individual book",
                Icon             = "tree-doc",
                Thumbnail        = "doc.png",
                Alias            = "BookPage",
                AllowedTemplates = new List <SelectListItem>(new[] { _templates.ElementAt(6) }.Select(x => new SelectListItem {
                    Selected = true, Text = x.Name, Value = x.Id.ToString()
                })),
                DefaultTemplateId = _templates.ElementAt(6).Id,
                DefinedTabs       = new HashSet <Tab>(new[]
                {
                    new Tab {
                        Id = HiveId.ConvertIntToGuid(++_tabIdCounter), Alias = "content", Name = "Content", SortOrder = 0
                    },
                    new Tab {
                        Id = HiveId.ConvertIntToGuid(++_tabIdCounter), Alias = _generalGroup.Alias, Name = _generalGroup.Name, SortOrder = _generalGroup.Ordinal
                    }
                }),
                InheritFrom = new[] { new HierarchicalSelectListItem
                                      {
                                          Selected = true,
                                          Value    = FixedHiveIds.ContentRootSchema.ToString()
                                      } },
            };

            bookPage.Properties = new HashSet <DocumentTypeProperty>(new[]
            {
                CreateNodeName(bookPage),
                CreateSelectedTemplateId(bookPage),
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[0])
                {
                    Name = "Description", Alias = "bodyText", TabId = bookPage.DefinedTabs.ElementAt(0).Id, SortOrder = 0
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[1])
                {
                    Name = "Publisher", Alias = "publisher", TabId = bookPage.DefinedTabs.ElementAt(0).Id, SortOrder = 0
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[6])
                {
                    Name = "Number of Pages", Alias = "numberOfPages", TabId = bookPage.DefinedTabs.ElementAt(0).Id, SortOrder = 0
                },
                new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[7])
                {
                    Name = "Image", Alias = "image", TabId = bookPage.DefinedTabs.ElementAt(0).Id, SortOrder = 0
                }
            });

            _docTypes = new List <DocumentTypeEditorModel>
            {
                homePage,
                contentPage,
                faq,
                faqCategory,
                faqQuestion,
                booksPage,
                bookPage
            };
        }
示例#24
0
        public static AbstractEntityRepositoryFactory MockEntityRepositoryFactory(int allItemCount, ProviderMetadata metadata, IFrameworkContext frameworkContext)
        {
            var entitySession = Substitute.For <AbstractEntityRepository>(metadata, new TransactionMock(), frameworkContext);

            entitySession.CanReadRelations.Returns(true);
            entitySession.CanWriteRelations.Returns(true);

            entitySession
            .PerformGet <TypedEntity>(Arg.Any <bool>(), Arg.Any <HiveId[]>())
            .Returns(x => EnumerableExtensions.Range(count => HiveModelCreationHelper.MockTypedEntity(HiveId.ConvertIntToGuid(count + 1)), 3));

            entitySession
            .PerformGetAll <TypedEntity>()
            .Returns(x => EnumerableExtensions.Range(count => HiveModelCreationHelper.MockTypedEntity(HiveId.ConvertIntToGuid(count + 5)), allItemCount));

            entitySession
            .PerformGetAncestorRelations(Arg.Any <HiveId>(), Arg.Any <RelationType>())
            .Returns(MockRelations(MockRelationCount));

            entitySession
            .PerformGetDescendentRelations(Arg.Any <HiveId>(), Arg.Any <RelationType>())
            .Returns(MockRelations(MockRelationCount));

            entitySession
            .PerformGetParentRelations(Arg.Any <HiveId>(), Arg.Any <RelationType>())
            .Returns(MockRelations(MockRelationCount));

            entitySession
            .PerformGetChildRelations(Arg.Any <HiveId>(), Arg.Any <RelationType>())
            .Returns(MockRelations(MockRelationCount));

            var factory = Substitute.For <AbstractEntityRepositoryFactory>(null, null, null, frameworkContext, null);

            factory.GetRepository().Returns(entitySession);
            return(factory);
        }