private static void HideTabs(ContentItemDisplay contentItemDisplay, List <string> userGroupAliasses, Rule rule)
 {
     if (rule.Tabs.Any())
     {
         contentItemDisplay.Tabs = contentItemDisplay.Tabs.Where(tab => !rule.Tabs.Contains(tab.Alias) && tab.Properties.Any());
     }
 }
Example #2
0
        private void AssertBasics(ContentItemDisplay result, IContent content)
        {
            Assert.AreEqual(content.Id, result.Id);

            var ownerId = content.CreatorId;

            if (ownerId != 0)
            {
                Assert.IsNotNull(result.Owner);
                Assert.AreEqual(Constants.Security.SuperUserId, result.Owner.UserId);
                Assert.AreEqual("Administrator", result.Owner.Name);
            }
            else
            {
                Assert.IsNull(result.Owner); // because, 0 is no user
            }

            var invariantContent = result.Variants.First();

            Assert.AreEqual(content.ParentId, result.ParentId);
            Assert.AreEqual(content.UpdateDate, invariantContent.UpdateDate);
            Assert.AreEqual(content.CreateDate, invariantContent.CreateDate);
            Assert.AreEqual(content.Name, invariantContent.Name);
            Assert.AreEqual(content.Properties.Count(),
                            ((IContentProperties <ContentPropertyDisplay>)invariantContent).Properties.Count(x => x.Alias.StartsWith("_umb_") == false));
        }
        public async Task PostSave_Simple_Invariant()
        {
            ILocalizationService localizationService = GetRequiredService <ILocalizationService>();

            // Add another language
            localizationService.Save(new LanguageBuilder()
                                     .WithCultureInfo(DkIso)
                                     .WithIsDefault(false)
                                     .Build());

            string url = PrepareApiControllerUrl <ContentController>(x => x.PostSave(null));

            IContentService     contentService     = GetRequiredService <IContentService>();
            IContentTypeService contentTypeService = GetRequiredService <IContentTypeService>();

            IContentType contentType = new ContentTypeBuilder()
                                       .WithId(0)
                                       .AddPropertyType()
                                       .WithAlias("title")
                                       .WithValueStorageType(ValueStorageType.Integer)
                                       .WithPropertyEditorAlias(Constants.PropertyEditors.Aliases.TextBox)
                                       .WithName("Title")
                                       .Done()
                                       .WithContentVariation(ContentVariation.Nothing)
                                       .Build();

            contentTypeService.Save(contentType);

            Content content = new ContentBuilder()
                              .WithId(0)
                              .WithName("Invariant")
                              .WithContentType(contentType)
                              .AddPropertyData()
                              .WithKeyValue("title", "Cool invariant title")
                              .Done()
                              .Build();

            contentService.SaveAndPublish(content);
            ContentItemSave model = new ContentItemSaveBuilder()
                                    .WithContent(content)
                                    .Build();

            // Act
            HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent
            {
                { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" }
            });

            // Assert
            string body = await response.Content.ReadAsStringAsync();

            body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix);

            Assert.Multiple(() =>
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, body);
                ContentItemDisplay display = JsonConvert.DeserializeObject <ContentItemDisplay>(body);
                Assert.AreEqual(1, display.Variants.Count());
            });
        }
        public void Content_Display_To_Json()
        {
            //create 3 tabs with 3 properties each
            var tabs = new List<Tab<ContentPropertyDisplay>>();
            for (var tabIndex = 0; tabIndex < 3; tabIndex ++)
            {
                var props = new List<ContentPropertyDisplay>();
                for (var propertyIndex = 0; propertyIndex < 3; propertyIndex ++)
                {
                    props.Add(new ContentPropertyDisplay
                        {
                            Alias = "property" + propertyIndex,
                            Label = "Property " + propertyIndex,
                            Id = propertyIndex,
                            Value = "value" + propertyIndex,
                            Config = new Dictionary<string, object> {{ propertyIndex.ToInvariantString(), "value" }},
                            Description = "Description " + propertyIndex,
                            View = "~/Views/View" + propertyIndex,
                            HideLabel = false
                        });                    
                }
                tabs.Add(new Tab<ContentPropertyDisplay>()
                    {
                        Alias = "Tab" + tabIndex,
                        Label = "Tab" + tabIndex,
                        Properties = props
                    });
            }

            var displayModel = new ContentItemDisplay
                {
                    Id = 1234,
                    Name = "Test",
                    Tabs = tabs
                };

            var json = JsonConvert.SerializeObject(displayModel);

            var jObject = JObject.Parse(json);

            Assert.AreEqual("1234", jObject["id"].ToString());
            Assert.AreEqual("Test", jObject["name"].ToString());
            Assert.AreEqual(3, jObject["tabs"].Count());
            for (var tab = 0; tab < jObject["tabs"].Count(); tab++)
            {
                Assert.AreEqual("Tab" + tab, jObject["tabs"][tab]["alias"].ToString());
                Assert.AreEqual("Tab" + tab, jObject["tabs"][tab]["label"].ToString());
                Assert.AreEqual(3, jObject["tabs"][tab]["properties"].Count());
                for (var prop = 0; prop < jObject["tabs"][tab]["properties"].Count(); prop++)
                {
                    Assert.AreEqual("property" + prop, jObject["tabs"][tab]["properties"][prop]["alias"].ToString());
                    Assert.AreEqual("Property " + prop, jObject["tabs"][tab]["properties"][prop]["label"].ToString());
                    Assert.AreEqual(prop, jObject["tabs"][tab]["properties"][prop]["id"].Value<int>());
                    Assert.AreEqual("value" + prop, jObject["tabs"][tab]["properties"][prop]["value"].ToString());
                    Assert.AreEqual("{\"" + prop + "\":\"value\"}", jObject["tabs"][tab]["properties"][prop]["config"].ToString(Formatting.None));
                    Assert.AreEqual("Description " + prop, jObject["tabs"][tab]["properties"][prop]["description"].ToString());
                    Assert.AreEqual(false, jObject["tabs"][tab]["properties"][prop]["hideLabel"].Value<bool>());
                }
            }                
        }
        /// <summary>
        /// Used where IContent is not available
        /// </summary>
        /// <param name="contentItem">Content Item to Check</param>
        /// <returns>True if an override exists</returns>
        public static bool CheckOverride(ContentItemDisplay contentItem)
        {
            var contentService = ApplicationContext.Current.Services.ContentService;
            var content        = contentService.GetById(contentItem.Key);

            return(CheckOverride(content));
        }
 // Umbraco.Code.MapAll
 private static void Map(ContentItemDisplayWithSchedule source, ContentItemDisplay target, MapperContext context)
 {
     target.AllowedActions   = source.AllowedActions;
     target.AllowedTemplates = source.AllowedTemplates;
     target.AllowPreview     = source.AllowPreview;
     target.ContentApps      = source.ContentApps;
     target.ContentDto       = source.ContentDto;
     target.ContentTypeAlias = source.ContentTypeAlias;
     target.ContentTypeId    = source.ContentTypeId;
     target.ContentTypeKey   = source.ContentTypeKey;
     target.ContentTypeName  = source.ContentTypeName;
     target.DocumentType     = source.DocumentType;
     target.Errors           = source.Errors;
     target.Icon             = source.Icon;
     target.Id                = source.Id;
     target.IsBlueprint       = source.IsBlueprint;
     target.IsChildOfListView = source.IsChildOfListView;
     target.IsContainer       = source.IsContainer;
     target.IsElement         = source.IsElement;
     target.Key               = source.Key;
     target.Owner             = source.Owner;
     target.ParentId          = source.ParentId;
     target.Path              = source.Path;
     target.PersistedContent  = source.PersistedContent;
     target.SortOrder         = source.SortOrder;
     target.TemplateAlias     = source.TemplateAlias;
     target.TemplateId        = source.TemplateId;
     target.Trashed           = source.Trashed;
     target.TreeNodeUrl       = source.TreeNodeUrl;
     target.Udi               = source.Udi;
     target.UpdateDate        = source.UpdateDate;
     target.Updater           = source.Updater;
     target.Urls              = source.Urls;
     target.Variants          = source.Variants;
 }
Example #7
0
 internal static void HandleAfterMap(IContent content, ContentItemDisplay contentItem)
 {
     if (ShouldAddProductEditor(contentItem))
     {
         AddTab(contentItem);
     }
 }
Example #8
0
        // Umbraco.Code.MapAll -AllowPreview -Errors -PersistedContent
        private void Map(IContent source, ContentItemDisplay target, MapperContext context)
        {
            target.AllowedActions   = GetActions(source);
            target.AllowedTemplates = GetAllowedTemplates(source);
            target.ContentApps      = _commonMapper.GetContentApps(source);
            target.ContentTypeId    = source.ContentType.Id;
            target.ContentTypeKey   = source.ContentType.Key;
            target.ContentTypeAlias = source.ContentType.Alias;
            target.ContentTypeName  = _localizedTextService.UmbracoDictionaryTranslate(source.ContentType.Name);
            target.DocumentType     = _commonMapper.GetContentType(source, context);
            target.Icon             = source.ContentType.Icon;
            target.Id                = source.Id;
            target.IsBlueprint       = source.Blueprint;
            target.IsChildOfListView = DetermineIsChildOfListView(source, context);
            target.IsContainer       = source.ContentType.IsContainer;
            target.IsElement         = source.ContentType.IsElement;
            target.Key               = source.Key;
            target.Owner             = _commonMapper.GetOwner(source, context);
            target.ParentId          = source.ParentId;
            target.Path              = source.Path;
            target.SortOrder         = source.SortOrder;
            target.TemplateAlias     = GetDefaultTemplate(source);
            target.TemplateId        = source.TemplateId ?? default;
            target.Trashed           = source.Trashed;
            target.TreeNodeUrl       = _commonMapper.GetTreeNodeUrl <ContentTreeController>(source);
            target.Udi               = Udi.Create(source.Blueprint ? Constants.UdiEntityType.DocumentBlueprint : Constants.UdiEntityType.Document, source.Key);
            target.UpdateDate        = source.UpdateDate;
            target.Updater           = _commonMapper.GetCreator(source, context);
            target.Urls              = GetUrls(source);
            target.Variants          = _contentVariantMapper.Map(source, context);

            target.ContentDto            = new ContentPropertyCollectionDto();
            target.ContentDto.Properties = context.MapEnumerable <Property, ContentPropertyDto>(source.Properties);
        }
Example #9
0
        public void To_Display_Model_No_Tabs()
        {
            IContentType contentType = _contentTypeBuilder
                                       .WithId(0)
                                       .Build();

            _contentTypeService.Save(contentType);

            Content content = _contentBuilder
                              .WithContentType(contentType)
                              .WithCreatorId(Constants.Security.SuperUserId)
                              .Build();

            ContentItemDisplay result = _sut.Map <IContent, ContentItemDisplay>(content);

            AssertBasics(result, content);

            ContentVariantDisplay invariantContent = result.Variants.First();

            foreach (IProperty p in content.Properties)
            {
                AssertBasicProperty(invariantContent, p);
                AssertDisplayProperty(invariantContent, p);
            }

            Assert.AreEqual(contentType.CompositionPropertyGroups.Count(), invariantContent.Tabs.Count());
        }
            public IDictionary <string, string> Resolve(IContent source, ContentItemDisplay destination, IDictionary <string, string> destMember, ResolutionContext context)
            {
                var contentType = _contentTypeService.Get(source.ContentTypeId);

                return(contentType.AllowedTemplates
                       .Where(t => t.Alias.IsNullOrWhiteSpace() == false && t.Name.IsNullOrWhiteSpace() == false)
                       .ToDictionary(t => t.Alias, t => _localizedTextService.UmbracoDictionaryTranslate(t.Name)));
            }
 private static void HideProperties(ContentItemDisplay contentItemDisplay, List <string> userGroupAliasses, Rule rule)
 {
     if (rule.Properties.Any())
     {
         foreach (var tab in contentItemDisplay.Tabs)
         {
             tab.Properties = tab.Properties.Where(property => !rule.Properties.Contains(property.Alias));
         }
     }
 }
    // Umbraco.Code.MapAll -AllowPreview -Errors -PersistedContent
    private void Map <TVariant>(IContent source, ContentItemDisplay <TVariant> target, MapperContext context)
        where TVariant : ContentVariantDisplay
    {
        // Both GetActions and DetermineIsChildOfListView use parent, so get it once here
        // Parent might already be in context, so check there before using content service
        IContent?parent;

        if (context.Items.TryGetValue("Parent", out var parentObj) &&
            parentObj is IContent typedParent)
        {
            parent = typedParent;
        }
        else
        {
            parent = _contentService.GetParent(source);
        }

        target.AllowedActions   = GetActions(source, parent, context);
        target.AllowedTemplates = GetAllowedTemplates(source);
        target.ContentApps      = _commonMapper.GetContentAppsForEntity(source);
        target.ContentTypeId    = source.ContentType.Id;
        target.ContentTypeKey   = source.ContentType.Key;
        target.ContentTypeAlias = source.ContentType.Alias;
        target.ContentTypeName  =
            _localizedTextService.UmbracoDictionaryTranslate(_cultureDictionary, source.ContentType.Name);
        target.DocumentType      = _commonMapper.GetContentType(source, context);
        target.Icon              = source.ContentType.Icon;
        target.Id                = source.Id;
        target.IsBlueprint       = source.Blueprint;
        target.IsChildOfListView = DetermineIsChildOfListView(source, parent, context);
        target.IsContainer       = source.ContentType.IsContainer;
        target.IsElement         = source.ContentType.IsElement;
        target.Key               = source.Key;
        target.Owner             = _commonMapper.GetOwner(source, context);
        target.ParentId          = source.ParentId;
        target.Path              = source.Path;
        target.SortOrder         = source.SortOrder;
        target.TemplateAlias     = GetDefaultTemplate(source);
        target.TemplateId        = source.TemplateId ?? default;
        target.Trashed           = source.Trashed;
        target.TreeNodeUrl       = _commonTreeNodeMapper.GetTreeNodeUrl <ContentTreeController>(source);
        target.Udi               =
            Udi.Create(source.Blueprint ? Constants.UdiEntityType.DocumentBlueprint : Constants.UdiEntityType.Document, source.Key);
        target.UpdateDate = source.UpdateDate;
        target.Updater    = _commonMapper.GetCreator(source, context);
        target.Urls       = GetUrls(source);
        target.Variants   = _contentVariantMapper.Map <TVariant>(source, context);

        target.ContentDto = new ContentPropertyCollectionDto
        {
            Properties = context.MapEnumerable <IProperty, ContentPropertyDto>(source.Properties).WhereNotNull()
        };
    }
Example #13
0
        public IEnumerable <ContentVariantDisplay> Resolve(IContent source, ContentItemDisplay destination, IEnumerable <ContentVariantDisplay> destMember, ResolutionContext context)
        {
            var result = new List <ContentVariantDisplay>();

            if (!source.ContentType.VariesByCulture())
            {
                //this is invariant so just map the IContent instance to ContentVariationDisplay
                result.Add(context.Mapper.Map <ContentVariantDisplay>(source));
            }
            else
            {
                var allLanguages = _localizationService.GetAllLanguages().OrderBy(x => x.Id).ToList();
                if (allLanguages.Count == 0)
                {
                    return(Enumerable.Empty <ContentVariantDisplay>());                        //this should never happen
                }
                var langs = context.Mapper.Map <IEnumerable <ILanguage>, IEnumerable <Language> >(allLanguages, null, context).ToList();

                //create a variant for each language, then we'll populate the values
                var variants = langs.Select(x =>
                {
                    //We need to set the culture in the mapping context since this is needed to ensure that the correct property values
                    //are resolved during the mapping
                    context.Options.SetCulture(x.IsoCode);
                    return(context.Mapper.Map <IContent, ContentVariantDisplay>(source, null, context));
                }).ToList();

                for (int i = 0; i < langs.Count; i++)
                {
                    var x       = langs[i];
                    var variant = variants[i];

                    variant.Language = x;
                    variant.Name     = source.GetCultureName(x.IsoCode);
                }

                //Put the default language first in the list & then sort rest by a-z
                var defaultLang = variants.SingleOrDefault(x => x.Language.IsDefault);

                //Remove the default language from the list for now
                variants.Remove(defaultLang);

                //Sort the remaining languages a-z
                variants = variants.OrderBy(x => x.Name).ToList();

                //Insert the default language as the first item
                variants.Insert(0, defaultLang);

                return(variants);
            }
            return(result);
        }
Example #14
0
        public void To_Display_Model()
        {
            IContentType contentType = _contentTypeBuilder
                                       .WithId(0)
                                       .AddPropertyGroup()
                                       .WithId(1)
                                       .AddPropertyType()
                                       .Done()
                                       .Done()
                                       .AddPropertyGroup()
                                       .WithId(2)
                                       .AddPropertyType()
                                       .Done()
                                       .Done()
                                       .AddPropertyGroup()
                                       .WithId(3)
                                       .AddPropertyType()
                                       .Done()
                                       .Done()
                                       .AddPropertyGroup()
                                       .WithId(4)
                                       .AddPropertyType()
                                       .Done()
                                       .Done()
                                       .Build();

            _contentTypeService.Save(contentType);

            Content content = _contentBuilder
                              .WithContentType(contentType)
                              .WithCreatorId(Constants.Security.SuperUserId)
                              .Build();

            ContentItemDisplay result = _sut.Map <IContent, ContentItemDisplay>(content);

            AssertBasics(result, content);

            ContentVariantDisplay invariantContent = result.Variants.First();

            foreach (IProperty p in content.Properties)
            {
                AssertBasicProperty(invariantContent, p);
                AssertDisplayProperty(invariantContent, p);
            }

            Assert.AreEqual(4, invariantContent.Tabs.Count());
            Assert.IsTrue(invariantContent.Tabs.First().IsActive);
            Assert.IsTrue(invariantContent.Tabs.Except(new[] { invariantContent.Tabs.First() }).All(x => x.IsActive == false));
        }
Example #15
0
        private void MakePropertiesReadOnly(ContentItemDisplay contentItemDisplay, UmbracoContext context)
        {
            var usergroups = context.Security.CurrentUser.Groups.ToList();

            if (contentItemDisplay.ContentTypeAlias == HomePage.ModelTypeAlias && !usergroups.Exists(x => x.Alias == "admin"))
            {
                var settingsTab = contentItemDisplay.Tabs.FirstOrDefault(x => x.Label == "Settings");

                if (settingsTab != null)
                {
                    settingsTab.Properties.First(x => x.Alias == "brandName").View      = "readonlyvalue";
                    settingsTab.Properties.First(x => x.Alias == "isResellerSite").View = "readonlyvalue";
                }
            }
        }
        public async Task PostSave_Validates_Domains_Exist()
        {
            ILocalizationService localizationService = GetRequiredService <ILocalizationService>();

            localizationService.Save(new LanguageBuilder()
                                     .WithCultureInfo(DkIso)
                                     .WithIsDefault(false)
                                     .Build());

            IContentTypeService contentTypeService = GetRequiredService <IContentTypeService>();
            IContentType        contentType        = new ContentTypeBuilder().WithContentVariation(ContentVariation.Culture).Build();

            contentTypeService.Save(contentType);

            Content content = new ContentBuilder()
                              .WithId(1)
                              .WithContentType(contentType)
                              .WithCultureName(UsIso, "Root")
                              .WithCultureName(DkIso, "Rod")
                              .Build();

            ContentItemSave model = new ContentItemSaveBuilder()
                                    .WithContent(content)
                                    .WithAction(ContentSaveAction.PublishNew)
                                    .Build();

            var url = PrepareApiControllerUrl <ContentController>(x => x.PostSave(null));

            HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent
            {
                { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" }
            });

            var body = await response.Content.ReadAsStringAsync();

            body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix);
            ContentItemDisplay display = JsonConvert.DeserializeObject <ContentItemDisplay>(body);

            ILocalizedTextService localizedTextService = GetRequiredService <ILocalizedTextService>();
            var expectedMessage = localizedTextService.Localize("speechBubbles", "publishWithNoDomains");

            Assert.Multiple(() =>
            {
                Assert.IsNotNull(display);
                Assert.AreEqual(1, display.Notifications.Count(x => x.NotificationType == NotificationStyle.Warning));
                Assert.AreEqual(expectedMessage, display.Notifications.FirstOrDefault(x => x.NotificationType == NotificationStyle.Warning)?.Message);
            });
        }
        private static void SetupBlueprint(ContentItemDisplay content, IContent persistedContent)
        {
            content.AllowPreview = false;

            //set a custom path since the tree that renders this has the content type id as the parent
            content.Path = string.Format("-1,{0},{1}", persistedContent.ContentTypeId, content.Id);

            content.AllowedActions = new[] { "A" };
            content.IsBlueprint    = true;

            var excludeProps = new[] { "_umb_urls", "_umb_releasedate", "_umb_expiredate", "_umb_template" };
            var propsTab     = content.Tabs.Last();

            propsTab.Properties = propsTab.Properties
                                  .Where(p => excludeProps.Contains(p.Alias) == false);
        }
        public IEnumerable <ContentApp> Resolve(IContent source, ContentItemDisplay destination, IEnumerable <ContentApp> destMember, ResolutionContext context)
        {
            var apps = _contentAppDefinitions.GetContentAppsFor(source).ToArray();

            // localize content app names
            foreach (var app in apps)
            {
                var localizedAppName = _localizedTextService.Localize($"apps/{app.Alias}");
                if (localizedAppName.Equals($"[{app.Alias}]", StringComparison.OrdinalIgnoreCase) == false)
                {
                    app.Name = localizedAppName;
                }
            }

            return(apps);
        }
Example #19
0
        private static void AddTab(ContentItemDisplay contentItem)
        {
            var tab = new Tab<ContentPropertyDisplay>
            {
                Alias = Constants.ProductEditor.TabAlias,
                Label = Constants.ProductEditor.TabLabel,
                Id = Constants.ProductEditor.TabId,
                IsActive = true
            };

            AddProperties(ref tab);

            //Is there a better way?
            var tabs = new List<Tab<ContentPropertyDisplay>> {tab};
            tabs.AddRange(contentItem.Tabs);
            contentItem.Tabs = tabs;
        }
Example #20
0
        /// <summary>
        /// Returns an item to be used to display the recycle bin for media
        /// </summary>
        /// <returns></returns>
        public ContentItemDisplay GetRecycleBin()
        {
            var display = new ContentItemDisplay
            {
                Id               = Constants.System.RecycleBinMedia,
                Alias            = "recycleBin",
                ParentId         = -1,
                Name             = Services.TextService.Localize("general/recycleBin"),
                ContentTypeAlias = "recycleBin",
                CreateDate       = DateTime.Now,
                IsContainer      = true,
                Path             = "-1," + Constants.System.RecycleBinMedia
            };

            TabsAndPropertiesResolver.AddListView(display, "media", Services.DataTypeService, Services.TextService);

            return(display);
        }
Example #21
0
        private static void AddTab(ContentItemDisplay contentItem)
        {
            var tab = new Tab <ContentPropertyDisplay>
            {
                Alias    = Constants.ProductEditor.TabAlias,
                Label    = Constants.ProductEditor.TabLabel,
                Id       = Constants.ProductEditor.TabId,
                IsActive = true
            };

            AddProperties(ref tab);

            //Is there a better way?
            var tabs = new List <Tab <ContentPropertyDisplay> > {
                tab
            };

            tabs.AddRange(contentItem.Tabs);
            contentItem.Tabs = tabs;
        }
Example #22
0
        public void To_Display_Model_With_Non_Grouped_Properties()
        {
            IContentType contentType = _contentTypeBuilder
                                       .WithId(0)
                                       .AddPropertyType()
                                       .WithId(1)
                                       .WithValueStorageType(ValueStorageType.Ntext)
                                       .WithPropertyEditorAlias("nonGrouped1")
                                       .WithName("Non Grouped 1")
                                       .Done()
                                       .AddPropertyType()
                                       .WithId(2)
                                       .WithValueStorageType(ValueStorageType.Ntext)
                                       .WithPropertyEditorAlias("nonGrouped2")
                                       .WithName("Non Grouped 2")
                                       .Done()
                                       .Build();

            _contentTypeService.Save(contentType);

            Content content = _contentBuilder
                              .WithContentType(contentType)
                              .WithCreatorId(Constants.Security.SuperUserId)
                              .Build();

            ContentItemDisplay result = _sut.Map <IContent, ContentItemDisplay>(content);

            AssertBasics(result, content);

            ContentVariantDisplay invariantContent = result.Variants.First();

            foreach (IProperty p in content.Properties)
            {
                AssertBasicProperty(invariantContent, p);
                AssertDisplayProperty(invariantContent, p);
            }

            Assert.AreEqual(contentType.CompositionPropertyGroups.Count(), invariantContent.Tabs.Count() - 1);
            Assert.IsTrue(invariantContent.Tabs.Any(x => x.Label == _localizedTextService.Localize("general", "properties")));
            Assert.AreEqual(2, invariantContent.Tabs.Where(x => x.Label == _localizedTextService.Localize("general", "properties")).SelectMany(x => x.Properties.Where(p => p.Alias.StartsWith("_umb_") == false)).Count());
        }
Example #23
0
        private Task <HttpResponseMessage> RemoveInacessibleContentNodesFromPath(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IUser user = ContextHelpers.EnsureUmbracoContext().Security.CurrentUser;

            int[] startNodes = StartNodeRepository.GetCachedStartNodesByUserId(user.Id).Content;

            if (user.UserType.Alias == "admin" || startNodes == null)
            {
                return(base.SendAsync(request, cancellationToken));
            }

            return(base.SendAsync(request, cancellationToken)
                   .ContinueWith(task =>
            {
                HttpResponseMessage response = task.Result;
                if (!response.IsSuccessStatusCode)
                {
                    return response;
                }
                try
                {
                    HttpContent data = response.Content;
                    ContentItemDisplay content = ((ObjectContent)(data)).Value as ContentItemDisplay;

                    if (!PathContainsAStartNode(content.Path, startNodes))
                    {
                        response.StatusCode = HttpStatusCode.Forbidden;     // prevent users from editing a node they shouldn't
                    }

                    content.Path = RemoveStartNodeAncestors(content.Path, startNodes);
                }
                catch (Exception ex)
                {
                    LogHelper.Error <WebApiHandler>("Could not update path.", ex);
                }
                return response;
            }
                                 ));
        }
Example #24
0
        private String GetReadMeProperties()
        {
            List <Tab <ContentPropertyDisplay> > tabs = new List <Tab <ContentPropertyDisplay> > {
                new Tab <ContentPropertyDisplay> {
                    Id         = 0,
                    Label      = "ReadMe",
                    Properties = new List <ContentPropertyDisplay>(),
                    Alias      = "readme",
                }
            };

            ContentItemDisplay contentItemDisplay = new ContentItemDisplay();

            //contentItemDisplay.Id = 1;
            contentItemDisplay.Name = "ReadMe";
            contentItemDisplay.Tabs = tabs;

            var JsonSettings = new JsonSerializerSettings();

            JsonSettings.ContractResolver = new LowercaseContractResolver();
            var json = JsonConvert.SerializeObject(contentItemDisplay);

            return(json);
        }
Example #25
0
        private String GetSettingsProperties()
        {
            try {
                List <ContentPropertyDisplay> authProperties = new List <ContentPropertyDisplay> {
                    new ContentPropertyDisplay {
                        Alias       = "baseUrl",
                        Description = "Enter the Google Custom Search API base URL. For more information visit <a href='https://developers.google.com/custom-search/json-api/v1/overview'>Google Custom Search JSON/Atom API.</a>",
                        HideLabel   = false,
                        Label       = "BaseURL",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = true, Pattern = null
                        },
                        View  = "textbox",
                        Value = settings.BaseURL
                    },
                    new ContentPropertyDisplay {
                        Alias       = "cxKey",
                        Description = "The custom search engine ID to use for this request. Go to <a href='https://cse.google.com/all' target='_blank'>Google CS console</a> to get the token.",
                        HideLabel   = false,
                        Label       = "CX Key",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = true, Pattern = null
                        },
                        Value = settings.CXKey,
                        View  = "textbox"
                    },
                    new ContentPropertyDisplay {
                        Alias       = "apiKey",
                        Description = "JSON/Atom Custom Search API requires the use of an API key. Go to <a href='https://console.developers.google.com/apis/credentials' target='_blank'>Google API console</a>  to create an API key or to retrieve one.",
                        HideLabel   = false,
                        Label       = "API Key",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = true, Pattern = null
                        },
                        Value = settings.APIKey,
                        View  = "textbox"
                    },
                    new ContentPropertyDisplay {
                        Alias       = "redirectAlias",
                        Description = "Enter the document type alias of the search results page.",
                        HideLabel   = false,
                        Label       = "Redirect alias",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = true, Pattern = null
                        },
                        Value = settings.RedirectAlias,
                        View  = "textbox"
                    },
                    new ContentPropertyDisplay {
                        Alias       = "developmentURL",
                        Description = "When working on a environment other than the production environment enter the absolute (including scheme) indexed domain name.",
                        HideLabel   = false,
                        Label       = "Development URL",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value = settings.DevelopmentURL,
                        View  = "textbox"
                    },
                };

                List <ContentPropertyDisplay> basicProperties = new List <ContentPropertyDisplay> {
                    new ContentPropertyDisplay {
                        Alias       = "itemsPerPage",
                        Description = "The number of search results displayed per page.",
                        HideLabel   = false,
                        Config      = new Dictionary <String, Object>()
                        {
                            { "minNumber", "1" },
                            { "maxNumber", "99" }
                        },
                        Label      = "Items per page",
                        Validation = new PropertyTypeValidation {
                            Mandatory = true, Pattern = null
                        },
                        Value = settings.ItemsPerPage,
                        View  = "integer"
                    },
                    new ContentPropertyDisplay {
                        Alias       = "loadMoreSetUp",
                        Description = "Configure the way in which you want your users to load more search results.",
                        HideLabel   = false,
                        Config      = new Dictionary <String, Object>()
                        {
                            { "items", new { Button = "Button", Pagination = "Pagination", Infinite = "Infinite scroll" } },
                            { "multiple", "false" }
                        },
                        Label      = "Load more set-up",
                        Validation = new PropertyTypeValidation {
                            Mandatory = true, Pattern = null
                        },
                        Value = settings.LoadMoreSetUp,
                        View  = "Dropdown"
                    },
                    new ContentPropertyDisplay {
                        Alias       = "maxPaginationPages",
                        Description = "Configure the maximum amount of total pages (before and after the current active page) will be shown.",
                        HideLabel   = false,
                        Label       = "Maximum pagination pages",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value = settings.MaxPaginationPages,
                        View  = "integer"
                    },
                    new ContentPropertyDisplay {
                        Alias       = "showQuery",
                        Description = "Show the search term.",
                        HideLabel   = false,
                        Label       = "Show search term",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value = settings.ShowQuery? "1" : "0",
                        View  = "boolean"
                    },
                    new ContentPropertyDisplay {
                        Alias       = "showTiming",
                        Description = "Shows how long the search query took.",
                        HideLabel   = false,
                        Label       = "Show timing",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value = settings.ShowTiming? "1" : "0",
                        View  = "boolean"
                    },
                    new ContentPropertyDisplay {
                        Alias       = "showTotalCount",
                        Description = "Shows the total amount of search results.",
                        HideLabel   = false,
                        Label       = "Show total count",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value = settings.ShowTotalCount? "1" : "0",
                        View  = "boolean"
                    },
                    new ContentPropertyDisplay {
                        Alias       = "showSpelling",
                        Description = "Show a possible corrected query.",
                        HideLabel   = false,
                        Label       = "Show spelling",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value = settings.ShowSpelling? "1" : "0",
                        View  = "boolean"
                    },
                    new ContentPropertyDisplay {
                        Alias       = "keepQuery",
                        Description = "Keep the query in the input field after the search reqeusted is submitted and results are returned.",
                        HideLabel   = false,
                        Label       = "Keep query",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value = settings.KeepQuery? "1" : "0",
                        View  = "boolean"
                    }
                };

                List <ContentPropertyDisplay> filterProperties = new List <ContentPropertyDisplay> {
                    new ContentPropertyDisplay {
                        Alias       = "dateRestrict",
                        Description = "Restricts results based on a given date. Only results will be shown which are created on or later than the specified date.",
                        HideLabel   = false,
                        Label       = "Date restriction",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value = settings.DateRestrict,
                        View  = "datePicker"
                    },
                    new ContentPropertyDisplay {
                        Alias       = "showFilterFileType",
                        Description = "Shows a filter to search through specific file types such as PDF or .docx",
                        HideLabel   = false,
                        Label       = "Show file type filter",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value = settings.ShowFilterFileType ? "1" : "0",
                        View  = "boolean"
                    },
                    new ContentPropertyDisplay {
                        Alias       = "excludeNodeIds",
                        Description = "Select the nodes to be excluded from the search results",
                        HideLabel   = false,
                        Config      = new Dictionary <String, Object>()
                        {
                            { "multiPicker", "1" },
                            { "showOpenButton", "0" },
                            { "showEditButton", "0" },
                            { "showPathOnHover", "0" },
                            { "startNode", new Dictionary <String, Object>()
                              {
                                  { "query", "" }, { "type", "content" }, { "id", "-1" }
                              } },
                            { "startNodeId", "-1" },
                            { "idType", "udi" }
                        },
                        Editor     = "Umbraco.ContentPicker2",
                        Label      = "Exclude nodes",
                        Validation = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value = settings.ExcludeNodeIds,
                        View  = "contentpicker"
                    },
                };

                List <ContentPropertyDisplay> stylingFilterProperties = new List <ContentPropertyDisplay> {
                    new ContentPropertyDisplay {
                        Alias       = "showThumbnail",
                        Description = "Shows the thumbnail image that is stored in GCS metadata.",
                        HideLabel   = false,
                        Label       = "Show thumbnail",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value = settings.ShowThumbnail ? "1" : "0",
                        View  = "boolean"
                    },
                    new ContentPropertyDisplay {
                        Label       = "Thumbnail fallback",
                        Description = "Image to show when no suitable thumbnail image is found is GCS metadata.",
                        View        = "mediapicker",
                        Config      = new Dictionary <String, Object>()
                        {
                            { "startNodeId", -1 },
                            { "idType", "udi" },
                            { "multiPicker", "" },
                            { "startNodeIsVirtual", false },
                            { "onlyImages", "" },
                            { "disableFolderSelect", "" }
                        },
                        HideLabel  = false,
                        Validation = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value  = settings.ThumbnailFallbackGUID,
                        Alias  = "thumbnailFallbackGUID",
                        Editor = "Umbraco.MediaPicker2",
                    },
                    new ContentPropertyDisplay {
                        Alias       = "loadIconGUID",
                        Description = "Preloader icon.",
                        Config      = new Dictionary <String, Object>()
                        {
                            { "startNodeId", -1 },
                            { "idType", "udi" }
                        },
                        Editor     = "Umbraco.MediaPicker2",
                        HideLabel  = false,
                        Label      = "Preloader icon",
                        Validation = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value = settings.LoadIconGUID,
                        View  = "mediapicker"
                    }
                };

                List <ContentPropertyDisplay> genericProperties = new List <ContentPropertyDisplay> {
                    new ContentPropertyDisplay {
                        Alias       = "lastUpdated",
                        Description = "",
                        HideLabel   = false,
                        Label       = "Last updated",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value                       = settings.LastUpdated != null?settings.LastUpdated.Value.ToString("yyyy-MM-dd") : "",
                                               View = "readonlyvalue"
                    },
                    new ContentPropertyDisplay {
                        Alias       = "dateCreated",
                        Description = "",
                        HideLabel   = false,
                        Label       = "Date Created",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value                       = settings.DateCreated != null?settings.DateCreated.Value.ToString("yyyy-MM-dd") : "",
                                               View = "readonlyvalue"
                    },
                    new ContentPropertyDisplay {
                        Alias       = "id",
                        Description = "",
                        HideLabel   = false,
                        Label       = "Settings ID",
                        Validation  = new PropertyTypeValidation {
                            Mandatory = false, Pattern = null
                        },
                        Value = settings.Id.ToString(),
                        View  = "readonlyvalue"
                    },
                };

                List <Tab <ContentPropertyDisplay> > tabs = new List <Tab <ContentPropertyDisplay> > {
                    new Tab <ContentPropertyDisplay> {
                        Id         = 0,
                        Label      = "Authentication",
                        Properties = authProperties
                    },
                    new Tab <ContentPropertyDisplay> {
                        Id         = 1,
                        Label      = "Set-up",
                        Properties = basicProperties
                    },
                    new Tab <ContentPropertyDisplay>()
                    {
                        Id         = 2,
                        Label      = "Filters",
                        Properties = filterProperties
                    },
                    new Tab <ContentPropertyDisplay>()
                    {
                        Id         = 3,
                        Label      = "Styling",
                        Properties = stylingFilterProperties
                    },
                    new Tab <ContentPropertyDisplay>()
                    {
                        Id         = 4,
                        Label      = "Generic",
                        Properties = genericProperties
                    },
                };

                ContentItemDisplay contentItemDisplay = new ContentItemDisplay();
                //contentItemDisplay.Id = 1;
                contentItemDisplay.ContentTypeName = "Settings";
                contentItemDisplay.Tabs            = tabs;

                var JsonSettings = new JsonSerializerSettings();
                JsonSettings.ContractResolver = new LowercaseContractResolver();
                var json = JsonConvert.SerializeObject(contentItemDisplay, Formatting.Indented, JsonSettings);

                return(json);
            } catch (Exception ex) {
                //LogHelper.Error(System.Reflection.MethodBase.GetCurrentMethod().GetType(), "GCS Error Get Properties", ex);

                ContentItemDisplay contentItemDisplay = new ContentItemDisplay();
                contentItemDisplay.Name = "Settings";
                contentItemDisplay.Tabs = new List <Tab <ContentPropertyDisplay> > {
                    new Tab <ContentPropertyDisplay>()
                    {
                        Id    = 1,
                        Label = "Settings",
                    }
                };

                var JsonSettings = new JsonSerializerSettings();
                JsonSettings.ContractResolver = new LowercaseContractResolver();
                var json = JsonConvert.SerializeObject(contentItemDisplay, Formatting.Indented, JsonSettings);

                return(json);
            }
        }
Example #26
0
 private static bool ShouldAddProductEditor(ContentItemDisplay contentItem)
 {
     return contentItem.Properties.Any(p => p.Alias == Constants.ProductEditor.ProductKeyPropertyAlias);
 }
 private void ShowMessageForPublishStatus(PublishStatus status, ContentItemDisplay display)
 {
     switch (status.StatusType)
     {
         case PublishStatusType.Success:
         case PublishStatusType.SuccessAlreadyPublished:
             display.AddSuccessNotification(
                 ui.Text("speechBubbles", "editContentPublishedHeader", UmbracoUser),
                 ui.Text("speechBubbles", "editContentPublishedText", UmbracoUser));
             break;
         case PublishStatusType.FailedPathNotPublished:
             display.AddWarningNotification(
                 ui.Text("publish"),
                 ui.Text("publish", "contentPublishedFailedByParent",
                         string.Format("{0} ({1})", status.ContentItem.Name, status.ContentItem.Id),
                         UmbracoUser).Trim());
             break;
         case PublishStatusType.FailedCancelledByEvent:
             display.AddWarningNotification(
                 ui.Text("publish"),
                 ui.Text("speechBubbles", "contentPublishedFailedByEvent"));
             break;                
         case PublishStatusType.FailedAwaitingRelease:
             display.AddWarningNotification(
                 ui.Text("publish"),
                 ui.Text("publish", "contentPublishedFailedAwaitingRelease",
                         new[]
                             {
                                 string.Format("{0} ({1})", status.ContentItem.Name, status.ContentItem.Id)
                             },
                         UmbracoUser).Trim());
             break;
         case PublishStatusType.FailedHasExpired:
             //TODO: We should add proper error messaging for this!
         case PublishStatusType.FailedIsTrashed:
             //TODO: We should add proper error messaging for this!
         case PublishStatusType.FailedContentInvalid:
             display.AddWarningNotification(
                 ui.Text("publish"),
                 ui.Text("publish", "contentPublishedFailedInvalid",
                         new[]
                             {
                                 string.Format("{0} ({1})", status.ContentItem.Name, status.ContentItem.Id),
                                 string.Join(",", status.InvalidProperties.Select(x => x.Alias))
                             },
                         UmbracoUser).Trim());
             break;
         default:
             throw new IndexOutOfRangeException();
     }
 }
Example #28
0
 internal static void HandleAfterMap(IContent content, ContentItemDisplay contentItem)
 {
     if (ShouldAddProductEditor(contentItem))
         AddTab(contentItem);
 }
        public void Content_Display_To_Json()
        {
            //create 3 tabs with 3 properties each
            var tabs = new List <Tab <ContentPropertyDisplay> >();

            for (var tabIndex = 0; tabIndex < 3; tabIndex++)
            {
                var props = new List <ContentPropertyDisplay>();
                for (var propertyIndex = 0; propertyIndex < 3; propertyIndex++)
                {
                    props.Add(new ContentPropertyDisplay
                    {
                        Alias  = "property" + propertyIndex,
                        Label  = "Property " + propertyIndex,
                        Id     = propertyIndex,
                        Value  = "value" + propertyIndex,
                        Config = new Dictionary <string, object> {
                            { propertyIndex.ToInvariantString(), "value" }
                        },
                        Description = "Description " + propertyIndex,
                        View        = "~/Views/View" + propertyIndex,
                        HideLabel   = false
                    });
                }
                tabs.Add(new Tab <ContentPropertyDisplay>()
                {
                    Alias      = "Tab" + tabIndex,
                    Label      = "Tab" + tabIndex,
                    Properties = props
                });
            }

            var displayModel = new ContentItemDisplay
            {
                Id       = 1234,
                Variants = new List <ContentVariantDisplay>
                {
                    new ContentVariantDisplay
                    {
                        Name = "Test",
                        Tabs = tabs
                    }
                }
            };

            var json = JsonConvert.SerializeObject(displayModel);

            var jObject = JObject.Parse(json);

            Assert.AreEqual("1234", jObject["id"].ToString());
            Assert.AreEqual("Test", jObject["variants"][0]["name"].ToString());
            var jsonTabs = jObject["variants"][0]["tabs"];

            Assert.AreEqual(3, jsonTabs.Count());
            for (var tab = 0; tab < jsonTabs.Count(); tab++)
            {
                Assert.AreEqual("Tab" + tab, jsonTabs[tab]["alias"].ToString());
                Assert.AreEqual("Tab" + tab, jsonTabs[tab]["label"].ToString());
                Assert.AreEqual(3, jsonTabs[tab]["properties"].Count());
                for (var prop = 0; prop < jsonTabs[tab]["properties"].Count(); prop++)
                {
                    Assert.AreEqual("property" + prop, jsonTabs[tab]["properties"][prop]["alias"].ToString());
                    Assert.AreEqual("Property " + prop, jsonTabs[tab]["properties"][prop]["label"].ToString());
                    Assert.AreEqual(prop, jsonTabs[tab]["properties"][prop]["id"].Value <int>());
                    Assert.AreEqual("value" + prop, jsonTabs[tab]["properties"][prop]["value"].ToString());
                    Assert.AreEqual("{\"" + prop + "\":\"value\"}", jsonTabs[tab]["properties"][prop]["config"].ToString(Formatting.None));
                    Assert.AreEqual("Description " + prop, jsonTabs[tab]["properties"][prop]["description"].ToString());
                    Assert.AreEqual(false, jsonTabs[tab]["properties"][prop]["hideLabel"].Value <bool>());
                }
            }
        }
Example #30
0
 private static bool ShouldAddProductEditor(ContentItemDisplay contentItem)
 {
     return(contentItem.Properties.Any(p => p.Alias == Constants.ProductEditor.ProductKeyPropertyAlias));
 }
Example #31
0
 public SendingContentNotification(ContentItemDisplay content, IUmbracoContext umbracoContext)
 {
     Content        = content;
     UmbracoContext = umbracoContext;
 }
        public async Task PostSave_Checks_Ancestors_For_Domains()
        {
            ILocalizationService localizationService = GetRequiredService <ILocalizationService>();

            localizationService.Save(new LanguageBuilder()
                                     .WithCultureInfo(DkIso)
                                     .WithIsDefault(false)
                                     .Build());

            IContentTypeService contentTypeService = GetRequiredService <IContentTypeService>();
            IContentType        contentType        = new ContentTypeBuilder().WithContentVariation(ContentVariation.Culture).Build();

            contentTypeService.Save(contentType);

            Content rootNode = new ContentBuilder()
                               .WithoutIdentity()
                               .WithContentType(contentType)
                               .WithCultureName(UsIso, "Root")
                               .WithCultureName(DkIso, "Rod")
                               .Build();

            IContentService contentService = GetRequiredService <IContentService>();

            contentService.SaveAndPublish(rootNode);

            Content childNode = new ContentBuilder()
                                .WithoutIdentity()
                                .WithParent(rootNode)
                                .WithContentType(contentType)
                                .WithCultureName(DkIso, "Barn")
                                .WithCultureName(UsIso, "Child")
                                .Build();

            contentService.SaveAndPublish(childNode);

            Content grandChild = new ContentBuilder()
                                 .WithoutIdentity()
                                 .WithParent(childNode)
                                 .WithContentType(contentType)
                                 .WithCultureName(DkIso, "BarneBarn")
                                 .WithCultureName(UsIso, "GrandChild")
                                 .Build();

            contentService.Save(grandChild);

            ILanguage      dkLanguage    = localizationService.GetLanguageByIsoCode(DkIso);
            ILanguage      usLanguage    = localizationService.GetLanguageByIsoCode(UsIso);
            IDomainService domainService = GetRequiredService <IDomainService>();
            var            dkDomain      = new UmbracoDomain("/")
            {
                RootContentId = rootNode.Id,
                LanguageId    = dkLanguage.Id
            };

            var usDomain = new UmbracoDomain("/en")
            {
                RootContentId = childNode.Id,
                LanguageId    = usLanguage.Id
            };

            domainService.Save(dkDomain);
            domainService.Save(usDomain);

            var url = PrepareApiControllerUrl <ContentController>(x => x.PostSave(null));

            ContentItemSave model = new ContentItemSaveBuilder()
                                    .WithContent(grandChild)
                                    .WithAction(ContentSaveAction.Publish)
                                    .Build();

            HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent
            {
                { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" }
            });

            var body = await response.Content.ReadAsStringAsync();

            body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix);
            ContentItemDisplay display = JsonConvert.DeserializeObject <ContentItemDisplay>(body);

            Assert.Multiple(() =>
            {
                Assert.NotNull(display);
                // Assert all is good, a success notification for each culture published and no warnings.
                Assert.AreEqual(2, display.Notifications.Count(x => x.NotificationType == NotificationStyle.Success));
                Assert.AreEqual(0, display.Notifications.Count(x => x.NotificationType == NotificationStyle.Warning));
            });
        }
        public async Task PostSave_Validates_All_Ancestor_Cultures_Are_Considered()
        {
            var sweIso = "sv-SE";
            ILocalizationService localizationService = GetRequiredService <ILocalizationService>();

            //Create 2 new languages
            localizationService.Save(new LanguageBuilder()
                                     .WithCultureInfo(DkIso)
                                     .WithIsDefault(false)
                                     .Build());

            localizationService.Save(new LanguageBuilder()
                                     .WithCultureInfo(sweIso)
                                     .WithIsDefault(false)
                                     .Build());

            IContentTypeService contentTypeService = GetRequiredService <IContentTypeService>();
            IContentType        contentType        = new ContentTypeBuilder().WithContentVariation(ContentVariation.Culture).Build();

            contentTypeService.Save(contentType);

            Content content = new ContentBuilder()
                              .WithoutIdentity()
                              .WithContentType(contentType)
                              .WithCultureName(UsIso, "Root")
                              .Build();

            IContentService contentService = GetRequiredService <IContentService>();

            contentService.SaveAndPublish(content);

            Content childContent = new ContentBuilder()
                                   .WithoutIdentity()
                                   .WithContentType(contentType)
                                   .WithParent(content)
                                   .WithCultureName(DkIso, "Barn")
                                   .WithCultureName(UsIso, "Child")
                                   .Build();

            contentService.SaveAndPublish(childContent);

            Content grandChildContent = new ContentBuilder()
                                        .WithoutIdentity()
                                        .WithContentType(contentType)
                                        .WithParent(childContent)
                                        .WithCultureName(sweIso, "Bjarn")
                                        .Build();


            ContentItemSave model = new ContentItemSaveBuilder()
                                    .WithContent(grandChildContent)
                                    .WithParentId(childContent.Id)
                                    .WithAction(ContentSaveAction.PublishNew)
                                    .Build();

            ILanguage      enLanguage    = localizationService.GetLanguageByIsoCode(UsIso);
            IDomainService domainService = GetRequiredService <IDomainService>();
            var            enDomain      = new UmbracoDomain("/en")
            {
                RootContentId = content.Id,
                LanguageId    = enLanguage.Id
            };

            domainService.Save(enDomain);

            ILanguage dkLanguage = localizationService.GetLanguageByIsoCode(DkIso);
            var       dkDomain   = new UmbracoDomain("/dk")
            {
                RootContentId = childContent.Id,
                LanguageId    = dkLanguage.Id
            };

            domainService.Save(dkDomain);

            var url = PrepareApiControllerUrl <ContentController>(x => x.PostSave(null));

            var result = JsonConvert.SerializeObject(model);
            HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent
            {
                { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" }
            });

            var body = await response.Content.ReadAsStringAsync();

            body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix);
            ContentItemDisplay display = JsonConvert.DeserializeObject <ContentItemDisplay>(body);


            ILocalizedTextService localizedTextService = GetRequiredService <ILocalizedTextService>();
            var expectedMessage = localizedTextService.Localize("speechBubbles", "publishWithMissingDomain", new [] { "sv-SE" });

            Assert.Multiple(() =>
            {
                Assert.NotNull(display);
                Assert.AreEqual(1, display.Notifications.Count(x => x.NotificationType == NotificationStyle.Warning));
                Assert.AreEqual(expectedMessage, display.Notifications.FirstOrDefault(x => x.NotificationType == NotificationStyle.Warning)?.Message);
            });
        }
        public async Task PostSave_Validate_Variants_Empty_Name()
        {
            ILocalizationService localizationService = GetRequiredService <ILocalizationService>();

            // Add another language
            localizationService.Save(new LanguageBuilder()
                                     .WithCultureInfo(DkIso)
                                     .WithIsDefault(false)
                                     .Build());

            string url = PrepareApiControllerUrl <ContentController>(x => x.PostSave(null));

            IContentService     contentService     = GetRequiredService <IContentService>();
            IContentTypeService contentTypeService = GetRequiredService <IContentTypeService>();

            IContentType contentType = new ContentTypeBuilder()
                                       .WithId(0)
                                       .AddPropertyType()
                                       .WithAlias("title")
                                       .WithValueStorageType(ValueStorageType.Integer)
                                       .WithPropertyEditorAlias(Constants.PropertyEditors.Aliases.TextBox)
                                       .WithName("Title")
                                       .Done()
                                       .WithContentVariation(ContentVariation.Culture)
                                       .Build();

            contentTypeService.Save(contentType);

            Content content = new ContentBuilder()
                              .WithId(0)
                              .WithCultureName(UsIso, "English")
                              .WithCultureName(DkIso, "Danish")
                              .WithContentType(contentType)
                              .AddPropertyData()
                              .WithKeyValue("title", "Cool invariant title")
                              .Done()
                              .Build();

            contentService.SaveAndPublish(content);

            content.CultureInfos[0].Name = null; // Removes the name of one of the variants to force an error
            ContentItemSave model = new ContentItemSaveBuilder()
                                    .WithContent(content)
                                    .Build();

            // Act
            HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent
            {
                { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" }
            });

            // Assert
            string body = await response.Content.ReadAsStringAsync();

            body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix);
            Assert.Multiple(() =>
            {
                Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
                ContentItemDisplay display = JsonConvert.DeserializeObject <ContentItemDisplay>(body);
                Assert.AreEqual(2, display.Errors.Count());
                CollectionAssert.Contains(display.Errors.Keys, "Variants[0].Name");
                CollectionAssert.Contains(display.Errors.Keys, "_content_variant_en-US_null_");
            });
        }
Example #35
0
        /// <summary>
        /// Maps the generic tab with custom properties for content
        /// </summary>
        /// <param name="content"></param>
        /// <param name="display"></param>
        /// <param name="dataTypeService"></param>
        /// <param name="localizedText"></param>
        /// <param name="contentTypeService"></param>
        private static void AfterMap(IContent content, ContentItemDisplay display, IDataTypeService dataTypeService,
                                     ILocalizedTextService localizedText, IContentTypeService contentTypeService)
        {
            //map the IsChildOfListView (this is actually if it is a descendant of a list view!)
            //TODO: Fix this shorthand .Ancestors() lookup, at least have an overload to use the current
            if (content.HasIdentity)
            {
                var ancesctorListView = content.Ancestors().FirstOrDefault(x => x.ContentType.IsContainer);
                display.IsChildOfListView = ancesctorListView != null;
            }
            else
            {
                //it's new so it doesn't have a path, so we need to look this up by it's parent + ancestors
                var parent = content.Parent();
                if (parent == null)
                {
                    display.IsChildOfListView = false;
                }
                else if (parent.ContentType.IsContainer)
                {
                    display.IsChildOfListView = true;
                }
                else
                {
                    var ancesctorListView = parent.Ancestors().FirstOrDefault(x => x.ContentType.IsContainer);
                    display.IsChildOfListView = ancesctorListView != null;
                }
            }


            //map the tree node url
            if (HttpContext.Current != null)
            {
                var urlHelper = new UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()));
                var url       = urlHelper.GetUmbracoApiService <ContentTreeController>(controller => controller.GetTreeNode(display.Id.ToString(), null));
                display.TreeNodeUrl = url;
            }

            //fill in the template config to be passed to the template drop down.
            var templateItemConfig = new Dictionary <string, string> {
                { "", "Choose..." }
            };

            foreach (var t in content.ContentType.AllowedTemplates
                     .Where(t => t.Alias.IsNullOrWhiteSpace() == false && t.Name.IsNullOrWhiteSpace() == false))
            {
                templateItemConfig.Add(t.Alias, t.Name);
            }

            if (content.ContentType.IsContainer)
            {
                TabsAndPropertiesResolver.AddListView(display, "content", dataTypeService);
            }

            var properties = new List <ContentPropertyDisplay>
            {
                new ContentPropertyDisplay
                {
                    Alias = string.Format("{0}releasedate", Constants.PropertyEditors.InternalGenericPropertiesPrefix),
                    Label = localizedText.Localize("content/releaseDate"),
                    Value = display.ReleaseDate.HasValue ? display.ReleaseDate.Value.ToIsoString() : null,
                    View  = "datepicker" //TODO: Hard coding this because the templatepicker doesn't necessarily need to be a resolvable (real) property editor
                },
                new ContentPropertyDisplay
                {
                    Alias = string.Format("{0}expiredate", Constants.PropertyEditors.InternalGenericPropertiesPrefix),
                    Label = localizedText.Localize("content/unpublishDate"),
                    Value = display.ExpireDate.HasValue ? display.ExpireDate.Value.ToIsoString() : null,
                    View  = "datepicker" //TODO: Hard coding this because the templatepicker doesn't necessarily need to be a resolvable (real) property editor
                },
                new ContentPropertyDisplay
                {
                    Alias  = string.Format("{0}template", Constants.PropertyEditors.InternalGenericPropertiesPrefix),
                    Label  = "Template", //TODO: localize this?
                    Value  = display.TemplateAlias,
                    View   = "dropdown", //TODO: Hard coding until we make a real dropdown property editor to lookup
                    Config = new Dictionary <string, object>
                    {
                        { "items", templateItemConfig }
                    }
                },
                new ContentPropertyDisplay
                {
                    Alias = string.Format("{0}urls", Constants.PropertyEditors.InternalGenericPropertiesPrefix),
                    Label = localizedText.Localize("content/urls"),
                    Value = string.Join(",", display.Urls),
                    View  = "urllist" //TODO: Hard coding this because the templatepicker doesn't necessarily need to be a resolvable (real) property editor
                }
            };

            TabsAndPropertiesResolver.MapGenericProperties(content, display, properties.ToArray(),
                                                           genericProperties =>
            {
                //TODO: This would be much nicer with the IUmbracoContextAccessor so we don't use singletons
                //If this is a web request and there's a user signed in and the
                // user has access to the settings section, we will
                if (HttpContext.Current != null && UmbracoContext.Current != null && UmbracoContext.Current.Security.CurrentUser != null &&
                    UmbracoContext.Current.Security.CurrentUser.AllowedSections.Any(x => x.Equals(Constants.Applications.Settings)))
                {
                    var currentDocumentType     = contentTypeService.GetContentType(display.ContentTypeAlias);
                    var currentDocumentTypeName = currentDocumentType == null ? string.Empty : currentDocumentType.Name;

                    var currentDocumentTypeId = currentDocumentType == null ? string.Empty : currentDocumentType.Id.ToString(CultureInfo.InvariantCulture);
                    //TODO: Hard coding this is not good
                    var docTypeLink = string.Format("#/settings/framed/settings%252FeditNodeTypeNew.aspx%253Fid%253D{0}", currentDocumentTypeId);

                    //Replace the doc type property
                    var docTypeProp   = genericProperties.First(x => x.Alias == string.Format("{0}doctype", Constants.PropertyEditors.InternalGenericPropertiesPrefix));
                    docTypeProp.Value = new List <object>
                    {
                        new
                        {
                            linkText = currentDocumentTypeName,
                            url      = docTypeLink,
                            target   = "_self", icon = "icon-item-arrangement"
                        }
                    };
                    //TODO: Hard coding this because the templatepicker doesn't necessarily need to be a resolvable (real) property editor
                    docTypeProp.View = "urllist";
                }
            });
        }