Ejemplo n.º 1
0
        /// <inheritdoc />
        public virtual string GetSearchableText(BlockListModel blockList, string culture = null, string segment = null)
        {
            StringBuilder sb = new StringBuilder();

            using (TextWriter writer = new StringWriter(sb)) WriteBlockList(writer, blockList, culture, segment);
            return(sb.ToString());
        }
        /// <summary>
        /// Adds a textual representation of the block list value from property with the specified <paramref name="key"/>.
        /// </summary>
        /// <param name="e"></param>
        /// <param name="logger">The logger to be used for logging errors.</param>
        /// <param name="indexingHelper">The indexing helper to be used for getting a textual representation of block list values.</param>
        /// <param name="content">The content item holding the block list value.</param>
        /// <param name="key">The key (or alias) of the property holding the block list value.</param>
        /// <param name="newKey">If specified, the value of this parameter will be used for the key of the new field added to the valueset.</param>
        /// <param name="newKeySuffix">If specified, and <paramref name="newKey"/> is not also specified, the value of this parameter will be appended to <paramref name="key"/>, and used for the key of the new field added to the valueset.</param>
        public static void IndexBlockList(this IndexingItemEventArgs e, ILogger logger, IIndexingHelper indexingHelper, IPublishedContent content, string key, string newKey = null, string newKeySuffix = null)
        {
            // Validate the content and the property
            if (content == null || !content.HasProperty(key))
            {
                return;
            }

            // Get the block list
            BlockListModel blockList = content.Value <BlockListModel>(key);

            if (blockList == null)
            {
                return;
            }

            // Determine the new key
            newKey = newKey ?? $"{key}{newKeySuffix ?? "_search"}";

            // Get the searchable text via the indexing helper
            try {
                string text = indexingHelper.GetSearchableText(blockList);
                if (!string.IsNullOrWhiteSpace(text))
                {
                    e.ValueSet.TryAdd(newKey, text);
                }
            } catch (Exception ex) {
                logger.Error(typeof(ExamineIndexingExtensions), ex, "Failed indexing block list in property {Property} on page with ID {Id}.", key, content.Id);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets the currently available block types.
        /// </summary>
        /// <param name="parentType">The optional parent group type</param>
        /// <returns>The block list model</returns>
        public BlockListModel GetBlockTypes(string parentType = null)
        {
            var model        = new BlockListModel();
            var parent       = App.Blocks.GetByType(parentType);
            var exludeGroups = parent != null && typeof(Piranha.Extend.BlockGroup).IsAssignableFrom(parent.Type);

            foreach (var category in App.Blocks.GetCategories())
            {
                var listCategory = new BlockListModel.ListCategory
                {
                    Name = category
                };

                var items = App.Blocks.GetByCategory(category).Where(i => !i.IsUnlisted);

                // If we have a parent, filter on allowed types
                if (parent != null)
                {
                    if (parent.ItemTypes.Count > 0)
                    {
                        items = items.Where(i => parent.ItemTypes.Contains(i.Type));
                    }

                    if (exludeGroups)
                    {
                        items = items.Where(i => !typeof(Piranha.Extend.BlockGroup).IsAssignableFrom(i.Type));
                    }
                }

                foreach (var block in items)
                {
                    listCategory.Items.Add(new BlockListModel.ListItem
                    {
                        Name = block.Name,
                        Icon = block.Icon,
                        Type = block.TypeName
                    });
                }
                model.Categories.Add(listCategory);
            }

            // Remove empty categories
            var empty = model.Categories.Where(c => c.Items.Count() == 0).ToList();

            foreach (var remove in empty)
            {
                model.Categories.Remove(remove);
            }

            // Calculate type count
            model.TypeCount = model.Categories.Sum(c => c.Items.Count());

            return(model);
        }
        public static IHtmlContent GetBlockListHtml(this IHtmlHelper html, BlockListModel model, string template = DefaultTemplate)
        {
            if (model?.Count == 0)
            {
                return(new HtmlString(string.Empty));
            }

            var view = DefaultFolder + template;

            return(html.Partial(view, model));
        }
Ejemplo n.º 5
0
 /// <inheritdoc />
 public virtual void WriteBlockList(TextWriter writer, BlockListModel blockList, string culture = null, string segment = null)
 {
     if (blockList == null)
     {
         return;
     }
     foreach (BlockListItem block in blockList)
     {
         WriteBlockListItem(writer, block, culture, segment);
     }
 }
Ejemplo n.º 6
0
        public static MvcHtmlString GetBlockListHtml(this HtmlHelper html, BlockListModel model, string template = DefaultTemplate)
        {
            if (model?.Layout == null || !model.Layout.Any())
            {
                return(new MvcHtmlString(string.Empty));
            }

            var view = DefaultFolder + template;

            return(html.Partial(view, model));
        }
Ejemplo n.º 7
0
        public IActionResult Post([FromBody] BlockListModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var blockList = _mapper.Map <DataAccess.Tables.BlockList>(model);

            blockList.UserId = UserId;

            var result = _blockListRepository.Insert(blockList);

            blockList.BlockListId = result.BlockListId;

            return(Ok(_mapper.Map <BlockListModel>(result)));
        }
Ejemplo n.º 8
0
        public IEnumerable <BlockElement> BuildBlockListValues(BlockListModel blocks)
        {
            var blockListValues = new List <BlockElement>();

            if (!blocks.HasAny())
            {
                return(blockListValues);
            }

            foreach (var block in blocks)
            {
                var blockElement = new BlockElement
                {
                    BlockType = block.Content.ContentType.Alias
                };

                switch (block.Content.ContentType.Alias)
                {
                case TextBlock.ModelTypeAlias:
                {
                    var textBlock = new TextBlock(block.Content);

                    blockElement.BlockValue = textBlock.Text.ToString();
                    blockListValues.Add(blockElement);

                    break;
                }

                case ImageBlock.ModelTypeAlias:
                {
                    var imageBlock = new ImageBlock(block.Content);

                    blockElement.BlockValue = imageBlock.Image.Url();
                    blockListValues.Add(blockElement);

                    break;
                }
                }
            }

            return(blockListValues);
        }
Ejemplo n.º 9
0
        public IActionResult Put([FromRoute] int blockListId, [FromBody] BlockListModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (!_blockListRepository.Find(x => x.UserId == UserId && x.BlockListId == model.BlockListId).Any())
            {
                return(Forbid());
            }

            var blockList = _mapper.Map <DataAccess.Tables.BlockList>(model);

            blockList.UserId = UserId;

            var result = _blockListRepository.Update(blockList);

            blockList.BlockListId = result.BlockListId;

            return(Ok(_mapper.Map <BlockListModel>(result)));
        }
        /// <inheritdoc />
        public override object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            // NOTE: The intermediate object is just a json string, we don't actually convert from source -> intermediate since source is always just a json string

            using (_proflog.DebugDuration <BlockListPropertyValueConverter>($"ConvertPropertyToBlockList ({propertyType.DataType.Id})"))
            {
                var configuration            = propertyType.DataType.ConfigurationAs <BlockListConfiguration>();
                var blockConfigMap           = configuration.Blocks.ToDictionary(x => x.ContentElementTypeKey);
                var validSettingElementTypes = blockConfigMap.Values.Select(x => x.SettingsElementTypeKey).Where(x => x.HasValue).Distinct().ToList();

                var contentPublishedElements  = new Dictionary <Guid, IPublishedElement>();
                var settingsPublishedElements = new Dictionary <Guid, IPublishedElement>();

                var layout = new List <BlockListItem>();

                var value = (string)inter;
                if (string.IsNullOrWhiteSpace(value))
                {
                    return(BlockListModel.Empty);
                }

                var converted = _blockListEditorDataConverter.Deserialize(value);
                if (converted.BlockValue.ContentData.Count == 0)
                {
                    return(BlockListModel.Empty);
                }

                var blockListLayout = converted.Layout.ToObject <IEnumerable <BlockListLayoutItem> >();

                // convert the content data
                foreach (var data in converted.BlockValue.ContentData)
                {
                    if (!blockConfigMap.ContainsKey(data.ContentTypeKey))
                    {
                        continue;
                    }

                    var element = _blockConverter.ConvertToElement(data, referenceCacheLevel, preview);
                    if (element == null)
                    {
                        continue;
                    }
                    contentPublishedElements[element.Key] = element;
                }
                // convert the settings data
                foreach (var data in converted.BlockValue.SettingsData)
                {
                    if (!validSettingElementTypes.Contains(data.ContentTypeKey))
                    {
                        continue;
                    }

                    var element = _blockConverter.ConvertToElement(data, referenceCacheLevel, preview);
                    if (element == null)
                    {
                        continue;
                    }
                    settingsPublishedElements[element.Key] = element;
                }

                // if there's no elements just return since if there's no data it doesn't matter what is stored in layout
                if (contentPublishedElements.Count == 0)
                {
                    return(BlockListModel.Empty);
                }

                foreach (var layoutItem in blockListLayout)
                {
                    // get the content reference
                    var contentGuidUdi = (GuidUdi)layoutItem.ContentUdi;
                    if (!contentPublishedElements.TryGetValue(contentGuidUdi.Guid, out var contentData))
                    {
                        continue;
                    }

                    // get the setting reference
                    IPublishedElement settingsData = null;
                    var settingGuidUdi             = layoutItem.SettingsUdi != null ? (GuidUdi)layoutItem.SettingsUdi : null;
                    if (settingGuidUdi != null)
                    {
                        settingsPublishedElements.TryGetValue(settingGuidUdi.Guid, out settingsData);
                    }

                    if (!contentData.ContentType.TryGetKey(out var contentTypeKey))
                    {
                        throw new InvalidOperationException("The content type was not of type " + typeof(IPublishedContentType2));
                    }

                    if (!blockConfigMap.TryGetValue(contentTypeKey, out var blockConfig))
                    {
                        continue;
                    }

                    // this can happen if they have a settings type, save content, remove the settings type, and display the front-end page before saving the content again
                    // we also ensure that the content type's match since maybe the settings type has been changed after this has been persisted.
                    if (settingsData != null)
                    {
                        if (!settingsData.ContentType.TryGetKey(out var settingsElementTypeKey))
                        {
                            throw new InvalidOperationException("The settings element type was not of type " + typeof(IPublishedContentType2));
                        }

                        if (!blockConfig.SettingsElementTypeKey.HasValue || settingsElementTypeKey != blockConfig.SettingsElementTypeKey)
                        {
                            settingsData = null;
                        }
                    }

                    var layoutType = typeof(BlockListItem <,>).MakeGenericType(contentData.GetType(), settingsData?.GetType() ?? typeof(IPublishedElement));
                    var layoutRef  = (BlockListItem)Activator.CreateInstance(layoutType, contentGuidUdi, contentData, settingGuidUdi, settingsData);

                    layout.Add(layoutRef);
                }

                var model = new BlockListModel(layout);
                return(model);
            }
        }
Ejemplo n.º 11
0
        private static void AssertModel(CandidateBlockList blockList, IDictionary <Guid, int> expectedCounts, BlockListModel model)
        {
            Assert.AreEqual(blockList.BlockListType.ToString(), model.Type);

            int expectedCount;

            expectedCounts.TryGetValue(model.Id, out expectedCount);
            Assert.AreEqual(expectedCount, model.Count);
        }
Ejemplo n.º 12
0
 public BlockListModel FilterBlockList(BlockListModel blockList)
 {
     return(new BlockListModel(blockList.Where(x => x.Settings != null && x.Settings.Value <bool>("includeInSummary")).ToList()));
 }
Ejemplo n.º 13
0
        internal static BlockListItemRendering GetBlockListItemData(BlockListItem item, BlockListModel list, string viewPath, ViewDataDictionary viewData)
        {
            if (item == null)
            {
                return(null);
            }

            var contentTypeAlias = item.Content?.ContentType.Alias;

            if (contentTypeAlias.IsNullOrWhiteSpace())
            {
                return(null);
            }

            var rendering = new BlockListItemRendering();

            var controllerName = $"{contentTypeAlias}Surface";

            if (!viewPath.IsNullOrWhiteSpace())
            {
                viewPath = viewPath.EnsureEndsWith("/");
            }

            rendering.RouteValues = new
            {
                blockListItem                 = item,
                blockListItemContext          = new BlockListItemContext(item, list),
                blockListItemContentTypeAlias = contentTypeAlias,
                blockListItemViewPath         = viewPath
            };

            if (SurfaceControllerHelper.SurfaceControllerExists(controllerName, contentTypeAlias, cacheResult: true))
            {
                rendering.ControllerName = controllerName;
                rendering.ActionName     = contentTypeAlias;
            }
            else
            {
                //// See if a default surface controller has been registered
                var defaultController = BlockListCurrent.DefaultBlockListMvcControllerType;
                if (defaultController != null)
                {
                    var defaultControllerName = defaultController.Name.Substring(0, defaultController.Name.LastIndexOf("Controller"));
                    rendering.ControllerName = defaultControllerName;

                    // Try looking for an action named after the content type alias
                    if (string.IsNullOrWhiteSpace(contentTypeAlias) == false && SurfaceControllerHelper.SurfaceControllerExists(defaultControllerName, contentTypeAlias, true))
                    {
                        rendering.ActionName = contentTypeAlias;
                    }
                    // else, just go with a default action name
                    else
                    {
                        rendering.ActionName = "Index";
                    }
                }
                else
                {
                    // fall back to using the default default controller
                    rendering.ControllerName = "DefaultBlockListMvcSurface";
                    rendering.ActionName     = "Index";
                }
            }

            return(rendering);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Renders the specified item and adds the specified list to the ViewDataDictionary for context.
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="item">Block list item to be rendered</param>
        /// <param name="list">The block list the item is a part of</param>
        /// <param name="viewPath">Path to where the block list items partial view is located</param>
        /// <returns></returns>
        public static void RenderBlockListItem(this HtmlHelper helper, BlockListItem item, BlockListModel list = null, string viewPath = "/Views/Partials/Blocks/", ViewDataDictionary viewData = null)
        {
            var rendering = GetBlockListItemData(item, list, viewPath, viewData);

            if (rendering != null)
            {
                helper.RenderAction(rendering.ActionName, rendering.ControllerName, rendering.RouteValues);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Renders the specified item and adds the specified list to the ViewDataDictionary for context.
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="item">Block list item to be rendered</param>
        /// <param name="list">The block list the item is a part of</param>
        /// <param name="viewPath">Path to where the block list items partial view is located</param>
        /// <returns></returns>
        public static HtmlString BlockListItem(this HtmlHelper helper, BlockListItem item, BlockListModel list = null, string viewPath = "/Views/Partials/Blocks/", ViewDataDictionary viewData = null)
        {
            var rendering = GetBlockListItemData(item, list, viewPath, viewData);

            if (rendering == null)
            {
                return(new HtmlString(string.Empty));
            }

            return(helper.Action(rendering.ActionName, rendering.ControllerName, rendering.RouteValues));
        }
 public BlockListItemContext(BlockListItem item, BlockListModel list)
 {
     Item = item;
     List = list;
 }