public void Throws_When_Adding_Duplicate_Properties()
    {
        // Arrange
        using (ScopeProvider.CreateScope())
        {
            var repository = CreateRepository();

            // Act
            var stylesheet =
                new Stylesheet("test-update.css")
            {
                Content = "body { color:#000; } .bold {font-weight:bold;}"
            };
            repository.Save(stylesheet);

            stylesheet.AddProperty(new StylesheetProperty("Test", "p", "font-size:2em;"));

            Assert.Throws <DuplicateNameException>(() =>
                                                   stylesheet.AddProperty(new StylesheetProperty("test", "p", "font-size:2em;")));
        }
    }
Exemplo n.º 2
0
        public Attempt <OperationResult> Delete(IDomain domain)
        {
            EventMessages eventMessages = EventMessagesFactory.Get();

            using (IScope scope = ScopeProvider.CreateScope())
            {
                var deletingNotification = new DomainDeletingNotification(domain, eventMessages);
                if (scope.Notifications.PublishCancelable(deletingNotification))
                {
                    scope.Complete();
                    return(OperationResult.Attempt.Cancel(eventMessages));
                }

                _domainRepository.Delete(domain);
                scope.Complete();

                scope.Notifications.Publish(new DomainDeletedNotification(domain, eventMessages).WithStateFrom(deletingNotification));
            }

            return(OperationResult.Attempt.Succeed(eventMessages));
        }
Exemplo n.º 3
0
        public void Can_Perform_Add_On_ScriptRepository()
        {
            // Arrange
            var provider = TestObjects.GetScopeProvider(Logger);

            using (var scope = ScopeProvider.CreateScope())
            {
                var repository = new ScriptRepository(_fileSystems, Mock.Of <IContentSection>());

                // Act
                var script = new Script("test-add-script.js")
                {
                    Content = "/// <reference name=\"MicrosoftAjax.js\"/>"
                };
                repository.Save(script);


                //Assert
                Assert.That(_fileSystem.FileExists("test-add-script.js"), Is.True);
            }
        }
        public Attempt <OperationResult <OperationResultType, EntityContainer> > CreateContainer(int parentId, string name, int userId = Constants.Security.SuperUserId)
        {
            var evtMsgs = EventMessagesFactory.Get();

            using (var scope = ScopeProvider.CreateScope())
            {
                scope.WriteLock(WriteLockIds); // also for containers

                try
                {
                    var container = new EntityContainer(ContainedObjectType)
                    {
                        Name      = name,
                        ParentId  = parentId,
                        CreatorId = userId
                    };

                    var saveEventArgs = new SaveEventArgs <EntityContainer>(container, evtMsgs);
                    if (OnSavingContainerCancelled(scope, saveEventArgs))
                    {
                        scope.Complete();
                        return(OperationResult.Attempt.Cancel(evtMsgs, container));
                    }

                    _containerRepository.Save(container);
                    scope.Complete();

                    saveEventArgs.CanCancel = false;
                    OnSavedContainer(scope, saveEventArgs);
                    // TODO: Audit trail ?

                    return(OperationResult.Attempt.Succeed(evtMsgs, container));
                }
                catch (Exception ex)
                {
                    scope.Complete();
                    return(OperationResult.Attempt.Fail <OperationResultType, EntityContainer>(OperationResultType.FailedCancelledByEvent, evtMsgs, ex));
                }
            }
        }
        public Attempt <OperationResult> SaveContainer(EntityContainer container, int userId = Constants.Security.SuperUserId)
        {
            var evtMsgs = EventMessagesFactory.Get();

            var containerObjectType = ContainerObjectType;

            if (container.ContainerObjectType != containerObjectType)
            {
                var ex = new InvalidOperationException("Not a container of the proper type.");
                return(OperationResult.Attempt.Fail(evtMsgs, ex));
            }

            if (container.HasIdentity && container.IsPropertyDirty("ParentId"))
            {
                var ex = new InvalidOperationException("Cannot save a container with a modified parent, move the container instead.");
                return(OperationResult.Attempt.Fail(evtMsgs, ex));
            }

            using (var scope = ScopeProvider.CreateScope())
            {
                var args = new SaveEventArgs <EntityContainer>(container, evtMsgs);
                if (OnSavingContainerCancelled(scope, args))
                {
                    scope.Complete();
                    return(OperationResult.Attempt.Cancel(evtMsgs));
                }

                scope.WriteLock(WriteLockIds); // also for containers

                _containerRepository.Save(container);
                scope.Complete();

                args.CanCancel = false;
                OnSavedContainer(scope, args);
            }

            // TODO: Audit trail ?

            return(OperationResult.Attempt.Succeed(evtMsgs));
        }
        public void Rebuild_Member_Xml_On_Alias_Change()
        {
            var contentType1 = MockedContentTypes.CreateSimpleMemberType("test1", "Test1");
            var contentType2 = MockedContentTypes.CreateSimpleMemberType("test2", "Test2");

            ServiceContext.MemberTypeService.Save(contentType1);
            ServiceContext.MemberTypeService.Save(contentType2);
            var contentItems1 = MockedMember.CreateSimpleMember(contentType1, 10).ToArray();

            foreach (var x in contentItems1)
            {
                ServiceContext.MemberService.Save(x);
            }
            var contentItems2 = MockedMember.CreateSimpleMember(contentType2, 5).ToArray();

            foreach (var x in contentItems2)
            {
                ServiceContext.MemberService.Save(x);
            }
            //only update the contentType1 alias which will force an xml rebuild for all content of that type
            contentType1.Alias = "newAlias";
            ServiceContext.MemberTypeService.Save(contentType1);

            using (var scope = ScopeProvider.CreateScope())
            {
                foreach (var c in contentItems1)
                {
                    var xml = scope.Database.FirstOrDefault <ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id });
                    Assert.IsNotNull(xml);
                    Assert.IsTrue(xml.Xml.StartsWith("<newAlias"));
                }
                foreach (var c in contentItems2)
                {
                    var xml = scope.Database.FirstOrDefault <ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id });
                    Assert.IsNotNull(xml);
                    Assert.IsTrue(xml.Xml.StartsWith("<test2")); //should remain the same
                }
                scope.Complete();
            }
        }
        public Attempt <OperationResult> DeleteContainer(int containerId, int userId = Constants.Security.SuperUserId)
        {
            var evtMsgs = EventMessagesFactory.Get();

            using (var scope = ScopeProvider.CreateScope())
            {
                scope.WriteLock(WriteLockIds); // also for containers

                var container = _containerRepository.Get(containerId);
                if (container == null)
                {
                    return(OperationResult.Attempt.NoOperation(evtMsgs));
                }

                // 'container' here does not know about its children, so we need
                // to get it again from the entity repository, as a light entity
                var entity = _entityRepository.Get(container.Id);
                if (entity.HasChildren)
                {
                    scope.Complete();
                    return(Attempt.Fail(new OperationResult(OperationResultType.FailedCannot, evtMsgs)));
                }

                var deleteEventArgs = new DeleteEventArgs <EntityContainer>(container, evtMsgs);
                if (OnDeletingContainerCancelled(scope, deleteEventArgs))
                {
                    scope.Complete();
                    return(Attempt.Fail(new OperationResult(OperationResultType.FailedCancelledByEvent, evtMsgs)));
                }

                _containerRepository.Delete(container);
                scope.Complete();

                deleteEventArgs.CanCancel = false;
                OnDeletedContainer(scope, deleteEventArgs);

                return(OperationResult.Attempt.Succeed(evtMsgs));
                // TODO: Audit trail ?
            }
        }
        public void Can_Perform_Add_View_With_Default_Content()
        {
            // Arrange
            using (ScopeProvider.CreateScope())
            {
                var repository = CreateRepository(ScopeProvider);

                // Act
                var template = new Template("test", "test")
                {
                    Content = ViewHelper.GetDefaultFileContent()
                };
                repository.Save(template);

                //Assert
                Assert.That(repository.Get("test"), Is.Not.Null);
                Assert.That(_fileSystems.MvcViewsFileSystem.FileExists("test.cshtml"), Is.True);
                Assert.AreEqual(
                    @"@inherits Umbraco.Web.Mvc.UmbracoViewPage @{ Layout = null;}".StripWhitespace(),
                    template.Content.StripWhitespace());
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Adds a rule
        /// </summary>
        /// <param name="content"></param>
        /// <param name="ruleType"></param>
        /// <param name="ruleValue"></param>
        /// <returns></returns>
        public Attempt <OperationResult <OperationResultType, PublicAccessEntry> > AddRule(IContent content, string ruleType, string ruleValue)
        {
            var evtMsgs = EventMessagesFactory.Get();
            PublicAccessEntry entry;

            using (var scope = ScopeProvider.CreateScope())
            {
                entry = _publicAccessRepository.GetMany().FirstOrDefault(x => x.ProtectedNodeId == content.Id);
                if (entry == null)
                {
                    return(OperationResult.Attempt.Cannot <PublicAccessEntry>(evtMsgs)); // causes rollback
                }
                var existingRule = entry.Rules.FirstOrDefault(x => x.RuleType == ruleType && x.RuleValue == ruleValue);
                if (existingRule == null)
                {
                    entry.AddRule(ruleValue, ruleType);
                }
                else
                {
                    //If they are both the same already then there's nothing to update, exit
                    return(OperationResult.Attempt.Succeed(evtMsgs, entry));
                }

                var savingNotifiation = new PublicAccessEntrySavingNotification(entry, evtMsgs);
                if (scope.Notifications.PublishCancelable(savingNotifiation))
                {
                    scope.Complete();
                    return(OperationResult.Attempt.Cancel(evtMsgs, entry));
                }

                _publicAccessRepository.Save(entry);

                scope.Complete();

                scope.Notifications.Publish(new PublicAccessEntrySavedNotification(entry, evtMsgs).WithStateFrom(savingNotifiation));
            }

            return(OperationResult.Attempt.Succeed(evtMsgs, entry));
        }
Exemplo n.º 10
0
    public void Does_Not_Create_Tag_Data_For_Non_Published_Version()
    {
        var template = TemplateBuilder.CreateTextPageTemplate();

        FileService.SaveTemplate(template);

        // create content type with a tag property
        var contentType = ContentTypeBuilder.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type",
                                                                     mandatoryProperties: true, defaultTemplateId: template.Id);

        CreateAndAddTagsPropertyType(contentType);
        ContentTypeService.Save(contentType);

        // create a content with tags and publish
        var content = ContentBuilder.CreateSimpleContent(contentType, "Tagged content");

        content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags",
                           new[] { "hello", "world", "some", "tags" });
        ContentService.SaveAndPublish(content);

        // edit tags and save
        content.AssignTags(PropertyEditorCollection, DataTypeService, Serializer, "tags", new[] { "another", "world" },
                           true);
        ContentService.Save(content);

        // the (edit) property does contain all tags
        Assert.AreEqual(5, content.Properties["tags"].GetValue().ToString().Split(',').Distinct().Count());

        // but the database still contains the initial two tags
        var propertyTypeId = contentType.PropertyTypes.Single(x => x.Alias == "tags").Id;

        using (var scope = ScopeProvider.CreateScope())
        {
            Assert.AreEqual(4, ScopeAccessor.AmbientScope.Database.ExecuteScalar <int>(
                                "SELECT COUNT(*) FROM cmsTagRelationship WHERE nodeId=@nodeId AND propertyTypeId=@propTypeId",
                                new { nodeId = content.Id, propTypeId = propertyTypeId }));
            scope.Complete();
        }
    }
Exemplo n.º 11
0
    private void AssertCheckBoxListTests(string strXml)
    {
        // Arrange
        var xml             = XElement.Parse(strXml);
        var dataTypeElement = xml.Descendants("DataTypes").First();
        var docTypesElement = xml.Descendants("DocumentTypes").First();
        var element         = xml.Descendants("DocumentSet").First();
        var packageDocument = CompiledPackageContentBase.Create(element);

        // Act
        var dataTypeDefinitions =
            PackageDataInstallation.ImportDataTypes(dataTypeElement.Elements("DataType").ToList(), 0);
        var contentTypes         = PackageDataInstallation.ImportDocumentTypes(docTypesElement.Elements("DocumentType"), 0);
        var importedContentTypes = contentTypes.ToDictionary(x => x.Alias, x => x);
        var contents             = PackageDataInstallation.ImportContentBase(packageDocument.Yield(), importedContentTypes, 0, ContentTypeService, ContentService);
        var numberOfDocs         = (from doc in element.Descendants()
                                    where (string)doc.Attribute("isDoc") == string.Empty
                                    select doc).Count();

        string configuration;

        using (var scope = ScopeProvider.CreateScope())
        {
            var dtos = ScopeAccessor.AmbientScope.Database.Fetch <DataTypeDto>("WHERE nodeId = @Id", new { dataTypeDefinitions.First().Id });
            configuration = dtos.Single().Configuration;
        }

        // Assert
        Assert.That(dataTypeDefinitions, Is.Not.Null);
        Assert.That(dataTypeDefinitions.Any(), Is.True);
        Assert.AreEqual(Constants.PropertyEditors.Aliases.CheckBoxList, dataTypeDefinitions.First().EditorAlias);
        Assert.That(contents, Is.Not.Null);
        Assert.That(contentTypes.Any(), Is.True);
        Assert.That(contents.Any(), Is.True);
        Assert.That(contents.Count(), Is.EqualTo(numberOfDocs));
        Assert.AreEqual(
            "{\"items\":[{\"id\":59,\"value\":\"test\"},{\"id\":60,\"value\":\"test3\"},{\"id\":61,\"value\":\"test2\"}]}",
            configuration);
    }
Exemplo n.º 12
0
        public void Can_Create()
        {
            using (ScopeProvider.CreateScope())
            {
                IDataType dataType = new DataType(new RadioButtonsPropertyEditor(DataValueEditorFactory, IOHelper, LocalizedTextService), ConfigurationEditorJsonSerializer)
                {
                    Name = "test"
                };

                DataTypeRepository.Save(dataType);

                int id = dataType.Id;
                Assert.That(id, Is.GreaterThan(0));

                // Act
                dataType = DataTypeRepository.Get(id);

                // Assert
                Assert.That(dataType, Is.Not.Null);
                Assert.That(dataType.HasIdentity, Is.True);
            }
        }
Exemplo n.º 13
0
        public void TestManyToMany()
        {
            // fetching a POCO that has a list of other POCOs,
            // and fetching these POCOs at the same time,
            // with an n-to-n intermediate table
            //
            // the ORDER BY clause (matching x => x.Id) is required
            // for proper aggregation to take place

            using (var scope = ScopeProvider.CreateScope())
            {
                // this is the raw SQL, but it's better to use expressions and no magic strings!
                //var sql = @"
                //    SELECT zbThing1.id, zbThing1.name, zbThingGroup.id, zbThingGroup.name
                //    FROM zbThing1
                //    JOIN zbThing2Group ON zbThing1.id=zbThing2Group.thingId
                //    JOIN zbThingGroup ON zbThing2Group.groupId=zbThingGroup.id
                //    ORDER BY zbThing1.id";

                var sql = scope.SqlContext.Sql()
                          .Select <Thing4Dto>(r => r.Select(x => x.Groups))
                          .From <Thing4Dto>()
                          .InnerJoin <Thing2GroupDto>().On <Thing4Dto, Thing2GroupDto>((t, t2g) => t.Id == t2g.ThingId)
                          .InnerJoin <ThingGroupDto>().On <Thing2GroupDto, ThingGroupDto>((t2g, tg) => t2g.GroupId == tg.Id)
                          .OrderBy <Thing4Dto>(x => x.Id);

                var dtos = scope.Database.FetchOneToMany <Thing4Dto>(x => x.Groups, /*x => x.Id,*/ sql);

                Assert.AreEqual(2, dtos.Count);
                var dto1 = dtos.FirstOrDefault(x => x.Id == 1);
                Assert.IsNotNull(dto1);
                Assert.AreEqual("one", dto1.Name);
                Assert.IsNotNull(dto1.Groups);
                Assert.AreEqual(2, dto1.Groups.Count);
                var dto2 = dto1.Groups.FirstOrDefault(x => x.Id == 1);
                Assert.IsNotNull(dto2);
                Assert.AreEqual("g-one", dto2.Name);
            }
        }
Exemplo n.º 14
0
        public void GetPagedItemsByContentId_WithVariantCultureContent_ReturnsPaginatedResults()
        {
            Template template = TemplateBuilder.CreateTextPageTemplate();

            FileService.SaveTemplate(template);

            var contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id);

            contentType.Variations = ContentVariation.Culture;
            foreach (var propertyType in contentType.PropertyTypes)
            {
                propertyType.Variations = ContentVariation.Culture;
            }
            FileService.SaveTemplate(contentType.DefaultTemplate);
            ContentTypeService.Save(contentType);

            var content = ContentBuilder.CreateSimpleContent(contentType, "foo", culture: "en-US");

            content.SetCultureName("foo", "en-US");

            ContentService.SaveAndPublish(content, "en-US"); // Draft + Published
            ContentService.SaveAndPublish(content, "en-US"); // New Draft

            using (ScopeProvider.CreateScope())
            {
                var sut   = new DocumentVersionRepository((IScopeAccessor)ScopeProvider);
                var page1 = sut.GetPagedItemsByContentId(content.Id, 0, 2, out var page1Total, 1);
                var page2 = sut.GetPagedItemsByContentId(content.Id, 1, 2, out var page2Total, 1);

                Assert.Multiple(() =>
                {
                    Assert.AreEqual(2, page1.Count());
                    Assert.AreEqual(3, page1Total);

                    Assert.AreEqual(1, page2.Count());
                    Assert.AreEqual(3, page2Total);
                });
            }
        }
        public void CreateKeysAndIndexesOfTDto()
        {
            var logger = new DebugDiagnosticsLogger();

            var builder = Mock.Of <IMigrationBuilder>();

            Mock.Get(builder)
            .Setup(x => x.Build(It.IsAny <Type>(), It.IsAny <IMigrationContext>()))
            .Returns <Type, IMigrationContext>((t, c) =>
            {
                switch (t.Name)
                {
                case "CreateTableOfTDtoMigration":
                    return(new CreateTableOfTDtoMigration(c));

                case "DeleteKeysAndIndexesMigration":
                    return(new DeleteKeysAndIndexesMigration(c));

                case "CreateKeysAndIndexesOfTDtoMigration":
                    return(new CreateKeysAndIndexesOfTDtoMigration(c));

                default:
                    throw new NotSupportedException();
                }
            });

            using (var scope = ScopeProvider.CreateScope())
            {
                var upgrader = new Upgrader(
                    new MigrationPlan("test")
                    .From(string.Empty)
                    .To <CreateTableOfTDtoMigration>("a")
                    .To <DeleteKeysAndIndexesMigration>("b")
                    .To <CreateKeysAndIndexesOfTDtoMigration>("done"));

                upgrader.Execute(ScopeProvider, builder, Mock.Of <IKeyValueService>(), logger);
                scope.Complete();
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Saves the entry
        /// </summary>
        /// <param name="entry"></param>
        public Attempt <OperationResult> Save(PublicAccessEntry entry)
        {
            var evtMsgs = EventMessagesFactory.Get();

            using (var scope = ScopeProvider.CreateScope())
            {
                var saveEventArgs = new SaveEventArgs <PublicAccessEntry>(entry, evtMsgs);
                if (scope.Events.DispatchCancelable(Saving, this, saveEventArgs))
                {
                    scope.Complete();
                    return(OperationResult.Attempt.Cancel(evtMsgs));
                }

                _publicAccessRepository.Save(entry);
                scope.Complete();

                saveEventArgs.CanCancel = false;
                scope.Events.Dispatch(Saved, this, saveEventArgs);
            }

            return(OperationResult.Attempt.Succeed(evtMsgs));
        }
        public void Can_Perform_Add_MasterPage_With_Default_Content()
        {
            // Arrange
            using (ScopeProvider.CreateScope())
            {
                var repository = CreateRepository(ScopeProvider, Mock.Of <ITemplatesSection>(x => x.DefaultRenderingEngine == RenderingEngine.WebForms));

                // Act
                var template = new Template("test", "test");
                repository.Save(template);

                //Assert
                Assert.That(repository.Get("test"), Is.Not.Null);
                Assert.That(_fileSystems.MasterPagesFileSystem.FileExists("test.master"), Is.True);
                Assert.AreEqual(@"<%@ Master Language=""C#"" MasterPageFile=""~/umbraco/masterpages/default.master"" AutoEventWireup=""true"" %>

<asp:Content ContentPlaceHolderID=""ContentPlaceHolderDefault"" runat=""server"">

</asp:Content>
".StripWhitespace(), template.Content.StripWhitespace());
            }
        }
Exemplo n.º 18
0
        private IUser CreateTestUser()
        {
            using IScope scope  = ScopeProvider.CreateScope(autoComplete: true);
            using IDisposable _ = scope.Notifications.Suppress();

            var globalSettings = new GlobalSettings();
            var user           = new User(globalSettings)
            {
                Name     = "Test user",
                Username = "******",
                Email    = "*****@*****.**",
            };

            UserService.Save(user);

            var userGroupA = new UserGroup(ShortStringHelper)
            {
                Alias = "GroupA",
                Name  = "Group A"
            };

            userGroupA.AddAllowedSection("media");
            userGroupA.AddAllowedSection("settings");

            // TODO: This is failing the test
            UserService.Save(userGroupA, new[] { user.Id });

            var userGroupB = new UserGroup(ShortStringHelper)
            {
                Alias = "GroupB",
                Name  = "Group B"
            };

            userGroupB.AddAllowedSection("settings");
            userGroupB.AddAllowedSection("member");
            UserService.Save(userGroupB, new[] { user.Id });

            return(UserService.GetUserById(user.Id));
        }
Exemplo n.º 19
0
        private Attempt <IPartialView> SavePartialView(IPartialView partialView, PartialViewType partialViewType, int userId = 0)
        {
            using (var scope = ScopeProvider.CreateScope())
            {
                var saveEventArgs = new SaveEventArgs <IPartialView>(partialView);
                if (scope.Events.DispatchCancelable(SavingPartialView, this, saveEventArgs))
                {
                    scope.Complete();
                    return(Attempt <IPartialView> .Fail());
                }

                var repository = GetPartialViewRepository(partialViewType);
                repository.Save(partialView);
                saveEventArgs.CanCancel = false;
                Audit(AuditType.Save, userId, -1, partialViewType.ToString());
                scope.Events.Dispatch(SavedPartialView, this, saveEventArgs);

                scope.Complete();
            }

            return(Attempt.Succeed(partialView));
        }
        public void CreateTestData()
        {
            var relateContent = new RelationType(Constants.ObjectTypes.Document, new Guid("C66BA18E-EAF3-4CFF-8A22-41B16D66A972"), "relateContentOnCopy")
            {
                IsBidirectional = true, Name = "Relate Content on Copy"
            };
            var relateContentType = new RelationType(Constants.ObjectTypes.DocumentType, new Guid("A2CB7800-F571-4787-9638-BC48539A0EFB"), "relateContentTypeOnCopy")
            {
                IsBidirectional = true, Name = "Relate ContentType on Copy"
            };

            var provider = TestObjects.GetScopeProvider(Logger);

            using (var scope = ScopeProvider.CreateScope())
            {
                var repository = new RelationTypeRepository((IScopeAccessor)provider, AppCaches.Disabled, Mock.Of <ILogger>());

                repository.Save(relateContent);     //Id 2
                repository.Save(relateContentType); //Id 3
                scope.Complete();
            }
        }
Exemplo n.º 21
0
        public void TestOneToManyOnMany()
        {
            // fetching a POCO that has a list of other POCOs,
            // and fetching these POCOs at the same time,
            // with a pk/fk relationship
            // for several POCOs
            //
            // the ORDER BY clause (matching x => x.Id) is required
            // for proper aggregation to take place

            using (var scope = ScopeProvider.CreateScope())
            {
                // this is the raw SQL, but it's better to use expressions and no magic strings!
                //var sql = @"
                //    SELECT zbThing1.id AS Id, zbThing1.name AS Name,
                //           zbThing2.id AS Things__Id, zbThing2.name AS Things__Name, zbThing2.thingId AS Things__ThingId
                //    FROM zbThing1
                //    JOIN zbThing2 ON zbThing1.id=zbThing2.thingId
                //    ORDER BY zbThing1.id";

                var sql = scope.SqlContext.Sql()
                          .Select <Thing3Dto>(r => r.Select(x => x.Things)) // select Thing3Dto, and Thing2Dto for Things
                          .From <Thing3Dto>()
                          .InnerJoin <Thing2Dto>().On <Thing3Dto, Thing2Dto>(left => left.Id, right => right.ThingId)
                          .OrderBy <Thing3Dto>(x => x.Id);

                var dtos = scope.Database.FetchOneToMany <Thing3Dto>(x => x.Things, /*x => x.Id,*/ sql);

                Assert.AreEqual(2, dtos.Count);
                var dto1 = dtos.FirstOrDefault(x => x.Id == 1);
                Assert.IsNotNull(dto1);
                Assert.AreEqual("one", dto1.Name);
                Assert.IsNotNull(dto1.Things);
                Assert.AreEqual(2, dto1.Things.Count);
                var dto2 = dto1.Things.FirstOrDefault(x => x.Id == 1);
                Assert.IsNotNull(dto2);
                Assert.AreEqual("uno", dto2.Name);
            }
        }
Exemplo n.º 22
0
    public void Can_Clear_Tag_Relations()
    {
        var provider = ScopeProvider;

        using (ScopeProvider.CreateScope())
        {
            // create data to relate to
            // We have to create and save a template, otherwise we get an FK violation on contentType.
            var template = TemplateBuilder.CreateTextPageTemplate();
            FileService.SaveTemplate(template);

            var contentType =
                ContentTypeBuilder.CreateSimpleContentType("test", "Test", defaultTemplateId: template.Id);
            ContentTypeRepository.Save(contentType);

            var content = ContentBuilder.CreateSimpleContent(contentType);
            DocumentRepository.Save(content);

            var   repository = CreateRepository(provider);
            Tag[] tags       = { new Tag {
                                     Text = "tag1", Group = "test"
                                 }, new Tag    {
                                     Text = "tag2", Group = "test"
                                 } };
            repository.Assign(
                content.Id,
                contentType.PropertyTypes.First().Id,
                tags,
                false);

            repository.Assign(
                content.Id,
                contentType.PropertyTypes.First().Id,
                Enumerable.Empty <ITag>());

            var result = repository.GetTagsForEntity(content.Id);
            Assert.AreEqual(0, result.Count());
        }
    }
Exemplo n.º 23
0
        /// <summary>
        /// Saves a <see cref="IDictionaryItem"/> object
        /// </summary>
        /// <param name="dictionaryItem"><see cref="IDictionaryItem"/> to save</param>
        /// <param name="userId">Optional id of the user saving the dictionary item</param>
        public void Save(IDictionaryItem dictionaryItem, int userId = 0)
        {
            using (var scope = ScopeProvider.CreateScope())
            {
                if (scope.Events.DispatchCancelable(SavingDictionaryItem, this, new SaveEventArgs <IDictionaryItem>(dictionaryItem)))
                {
                    scope.Complete();
                    return;
                }

                _dictionaryRepository.Save(dictionaryItem);

                // ensure the lazy Language callback is assigned
                // ensure the lazy Language callback is assigned

                EnsureDictionaryItemLanguageCallback(dictionaryItem);
                scope.Events.Dispatch(SavedDictionaryItem, this, new SaveEventArgs <IDictionaryItem>(dictionaryItem, false));

                Audit(AuditType.Save, "Save DictionaryItem", userId, dictionaryItem.Id, "DictionaryItem");
                scope.Complete();
            }
        }
Exemplo n.º 24
0
        public void Can_Clear_Tag_Relations()
        {
            var provider = TestObjects.GetScopeProvider(Logger);

            using (ScopeProvider.CreateScope())
            {
                var contentRepository = CreateContentRepository(provider, out var contentTypeRepository);

                //create data to relate to
                var contentType = MockedContentTypes.CreateSimpleContentType("test", "Test");
                ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType!
                contentTypeRepository.Save(contentType);

                var content = MockedContent.CreateSimpleContent(contentType);
                contentRepository.Save(content);

                var repository = CreateRepository(provider);
                repository.Assign(
                    content.Id,
                    contentType.PropertyTypes.First().Id,
                    new[]
                {
                    new Tag {
                        Text = "tag1", Group = "test"
                    },
                    new Tag {
                        Text = "tag2", Group = "test"
                    },
                }, false);

                repository.Assign(
                    content.Id,
                    contentType.PropertyTypes.First().Id,
                    Enumerable.Empty <ITag>(), true);

                var result = repository.GetTagsForEntity(content.Id);
                Assert.AreEqual(0, result.Count());
            }
        }
Exemplo n.º 25
0
        public Attempt <OperationResult> Delete(IDomain domain)
        {
            var evtMsgs = EventMessagesFactory.Get();

            using (var scope = ScopeProvider.CreateScope())
            {
                var deleteEventArgs = new DeleteEventArgs <IDomain>(domain, evtMsgs);
                if (scope.Events.DispatchCancelable(Deleting, this, deleteEventArgs))
                {
                    scope.Complete();
                    return(OperationResult.Attempt.Cancel(evtMsgs));
                }

                _domainRepository.Delete(domain);
                scope.Complete();

                deleteEventArgs.CanCancel = false;
                scope.Events.Dispatch(Deleted, this, deleteEventArgs);
            }

            return(OperationResult.Attempt.Succeed(evtMsgs));
        }
        public void Can_Perform_Get_On_RelationTypeRepository()
        {
            // Arrange
            var provider = TestObjects.GetScopeProvider(Logger);

            using (var scope = ScopeProvider.CreateScope())
            {
                var repository = CreateRepository(provider);

                // Act
                var relationType = repository.Get(RelationTypeDto.NodeIdSeed + 2);

                // Assert
                Assert.That(relationType, Is.Not.Null);
                Assert.That(relationType.HasIdentity, Is.True);
                Assert.That(relationType.IsBidirectional, Is.True);
                Assert.That(relationType.Alias, Is.EqualTo("relateContentToMedia"));
                Assert.That(relationType.Name, Is.EqualTo("Relate Content to Media"));
                Assert.That(relationType.ChildObjectType, Is.EqualTo(Constants.ObjectTypes.Media));
                Assert.That(relationType.ParentObjectType, Is.EqualTo(Constants.ObjectTypes.Document));
            }
        }
        public void Can_Perform_Delete()
        {
            // Arrange
            using (ScopeProvider.CreateScope())
            {
                var repository = new StylesheetRepository(_fileSystems);

                // Act
                var stylesheet = new Stylesheet("test-delete.css")
                {
                    Content = "body { color:#000; } .bold {font-weight:bold;}"
                };
                repository.Save(stylesheet);


                repository.Delete(stylesheet);


                //Assert
                Assert.That(_fileSystem.FileExists("test-delete.css"), Is.False);
            }
        }
Exemplo n.º 28
0
        public Attempt <OperationResult <OperationResultType, EntityContainer> > RenameContainer(int id, string name, int userId = Cms.Core.Constants.Security.SuperUserId)
        {
            var evtMsgs = EventMessagesFactory.Get();

            using (var scope = ScopeProvider.CreateScope())
            {
                try
                {
                    var container = _dataTypeContainerRepository.Get(id);

                    //throw if null, this will be caught by the catch and a failed returned
                    if (container == null)
                    {
                        throw new InvalidOperationException("No container found with id " + id);
                    }

                    container.Name = name;

                    var renamingEntityContainerNotification = new EntityContainerRenamingNotification(container, evtMsgs);
                    if (scope.Notifications.PublishCancelable(renamingEntityContainerNotification))
                    {
                        scope.Complete();
                        return(OperationResult.Attempt.Cancel(evtMsgs, container));
                    }

                    _dataTypeContainerRepository.Save(container);
                    scope.Complete();

                    scope.Notifications.Publish(new EntityContainerRenamedNotification(container, evtMsgs).WithStateFrom(renamingEntityContainerNotification));

                    return(OperationResult.Attempt.Succeed(OperationResultType.Success, evtMsgs, container));
                }
                catch (Exception ex)
                {
                    return(OperationResult.Attempt.Fail <EntityContainer>(evtMsgs, ex));
                }
            }
        }
Exemplo n.º 29
0
        public Attempt <OperationResult <OperationResultType, EntityContainer> > CreateContainer(int parentId, Guid key, string name, int userId = Cms.Core.Constants.Security.SuperUserId)
        {
            var evtMsgs = EventMessagesFactory.Get();

            using (var scope = ScopeProvider.CreateScope())
            {
                try
                {
                    var container = new EntityContainer(Cms.Core.Constants.ObjectTypes.DataType)
                    {
                        Name      = name,
                        ParentId  = parentId,
                        CreatorId = userId,
                        Key       = key
                    };

                    var savingEntityContainerNotification = new EntityContainerSavingNotification(container, evtMsgs);
                    if (scope.Notifications.PublishCancelable(savingEntityContainerNotification))
                    {
                        scope.Complete();
                        return(OperationResult.Attempt.Cancel(evtMsgs, container));
                    }

                    _dataTypeContainerRepository.Save(container);
                    scope.Complete();

                    scope.Notifications.Publish(new EntityContainerSavedNotification(container, evtMsgs).WithStateFrom(savingEntityContainerNotification));

                    // TODO: Audit trail ?

                    return(OperationResult.Attempt.Succeed(evtMsgs, container));
                }
                catch (Exception ex)
                {
                    return(OperationResult.Attempt.Fail <EntityContainer>(evtMsgs, ex));
                }
            }
        }
Exemplo n.º 30
0
        public override void CreateTestData()
        {
            base.CreateTestData();

            using (IScope scope = ScopeProvider.CreateScope())
            {
                var      repository  = new RedirectUrlRepository((IScopeAccessor)ScopeProvider, AppCaches.Disabled, Mock.Of <ILogger <RedirectUrlRepository> >());
                IContent rootContent = ContentService.GetRootContent().First();
                var      subPages    = ContentService.GetPagedChildren(rootContent.Id, 0, 3, out _).ToList();
                _firstSubPage  = subPages[0];
                _secondSubPage = subPages[1];
                _thirdSubPage  = subPages[2];


                repository.Save(new RedirectUrl
                {
                    ContentKey = _firstSubPage.Key,
                    Url        = Url,
                    Culture    = CultureEnglish
                });
                Thread.Sleep(1000); //Added delay to ensure timestamp difference as sometimes they seem to have the same timestamp
                repository.Save(new RedirectUrl
                {
                    ContentKey = _secondSubPage.Key,
                    Url        = Url,
                    Culture    = CultureGerman
                });
                Thread.Sleep(1000);
                repository.Save(new RedirectUrl
                {
                    ContentKey = _thirdSubPage.Key,
                    Url        = UrlAlt,
                    Culture    = string.Empty
                });

                scope.Complete();
            }
        }