Scheduled job to find saved blocks & mark for deletion

Vote:
 

Im fairly new to EpiServer so apologies if I'm using the wrong terminology.

I'm trying to find a way to get a list of all the CMS block that we have saved that are not in use so that we can locate old cms block templates and mark them for deletion.

Any Pointers on where to start?

#248357
Feb 08, 2021 21:55
Vote:
 

I'm not sure how you want to mark the blocks for deletion, but you can identify unreferences blocks with the following SQL query.

SELECT pkID
FROM tblContent
WHERE 
   fkContentTypeId IN (SELECT pkId FROM tblContentType WHERE ContentType = 1) AND     -- all blocks 
   ContentGUID NOT IN (SELECT fkReferencedContentGUID FROM tblContentSoftLink)        -- that are not references
#248360
Edited, Feb 09, 2021 5:42
Vote:
 

In tblContentType ContentType is 1 for all block types and 0 for all page types.

If you want just your custom block types, you could filter by start of namespace, likt this:

SELECT pkID
FROM tblContent
WHERE 
   fkContentTypeId IN (SELECT pkId FROM tblContentType WHERE ContentType = 1 AND ModelType LIKE 'Alloy.%') AND
   ContentGUID NOT IN (SELECT fkReferencedContentGUID FROM tblContentSoftLink)
#248376
Edited, Feb 09, 2021 9:02
Vote:
 

Here are two ways to get the Unused blocks.

  • Implement below code and pass the block type e.g. EventBlock
public void RemoveUnUsedBlocks()
{
            var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();
            var contentTypeRepository = ServiceLocator.Current.GetInstance<IContentTypeRepository>();
            var contentModelUsage = ServiceLocator.Current.GetInstance<IContentModelUsage>();

            // get all usages of EventBlock, including versions
            var contentType = contentTypeRepository.Load<EventBlock>();
            var contentUsages = contentModelUsage.ListContentOfContentType(contentType);

            // get distinct content references without version
            var contentReferences = contentUsages
                .Select(x => x.ContentLink.ToReferenceWithoutVersion())
                .Distinct()
                .ToList();

            // fetch data from DB and filter out the block there reference 
            var instances = contentReferences
                .Select(contentReference => contentLoader.Get<IContent>(contentReference))
                .Where(IsNotReferenced)
                .ToList();

            foreach (var block in instances)
            {
                //Todo : locate old cms block templates here
            }
 }       
private bool IsNotReferenced(IContent content)
{
            return !_contentRepository.GetReferencesToContent(content.ContentLink, false).Any();
}
#248401
Edited, Feb 09, 2021 15:24
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.