EpiServer - How can I find out if a block is being used on any published page?

北慕城南 提交于 2021-01-28 06:47:26

问题


I have an episerver project that has lots of blocks over time some of these blocks are no longer needed, is there a way to see if a created block is being used on any pages in my episerver website?


回答1:


I rarely do this but last time I did I used this code to get all published instances of a custom CodeBlock

// initiate the repos (use dependency injection instead of the ServiceLocator)
var contentTypeRepository = ServiceLocator.Current.GetInstance<EPiServer.DataAbstraction.IContentTypeRepository>();
var contentModelUsage = ServiceLocator.Current.GetInstance<IContentModelUsage>();
var repository = ServiceLocator.Current.GetInstance<IContentRepository>();
var linkRepository = ServiceLocator.Current.GetInstance<IContentSoftLinkRepository>();

// loading a block type
var blockType = contentTypeRepository.Load(typeof(CodeBlock));

// get usages, also includes versions
IList<ContentUsage> usages = contentModelUsage.ListContentOfContentType(blockType);

List<IContent> blocks = usages.Select(contentUsage =>
                        contentUsage.ContentLink.ToReferenceWithoutVersion())
                        .Distinct()
                        .Select(contentReference =>
                                repository.Get<IContent>(contentReference)).ToList();


var unusedBlocks = new List<IContent>();

foreach (IContent block in blocks)
{
    var referencingContentLinks = linkRepository.Load(block.ContentLink, true)
                                .Where(link =>
                                        link.SoftLinkType == ReferenceType.PageLinkReference &&
                                        !ContentReference.IsNullOrEmpty(link.OwnerContentLink))
                                .Select(link => link.OwnerContentLink);

    // if no links
    if (!referencingContentLinks.Any())
    {
        unusedBlocks.Add(block);
    }
}

You'll find the unused block instances in unusedBlocks

Now, as usual, don't use the ServiceLocator unless you like to hide dependencies.



来源:https://stackoverflow.com/questions/49454291/episerver-how-can-i-find-out-if-a-block-is-being-used-on-any-published-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!