Search code examples
c#episerver

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


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?


Solution

  • 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.