Anders Hattestad
Feb 18, 2014
  5735
(1 votes)

Query content of inherit type or those that implements an interface

Sometimes when I do import jobs, I check if a content type have a specific property. If a page exists I update it, and if not I create a new. Other times I want to find some pages that inherits form a basepage type and get those pages that have some properties set.
To find a page if it exists with testKey I used

var items = ContentModelUsage.Service.ListContentOfContentType(
    ContentTypeRepository.Service.Load<MyPageType>())
        .Select(x =>
        x.ContentLink.CreateReferenceWithoutVersion())
    .Distinct()
    .Select(x => ContentLoader.Service.Get<MyPageType>(x))
    .OfType<MyPageType>()
    .Where(p => !p.IsDeleted)
    .Where(p => p.MyTestProperty == testKey)
    .ToList();

The problem with this code is that it is slow. I could of course grab all items, and select on that collection, but then I need to update the list with new items. The ListContentOfContentType takes in my case 350ms to execute, and the Get takes practical zero ms (after first time). Therefore, what I will do is to cache the ListContentOfType, but clear it content is added or removed.

Another problem is that the above code does not find content that inherits MyPageType, or implements an interface.

I therefore made myself a method that finds all content types that is, or inherits or implements an interface.

public static List<ContentType> GetContentTypesOfType(Type inheritTypeOrInterface)
{
    var list = ContentTypeRepository.Service.List().
        Where(
            p => p.ModelType != null &&
            (
                p.ModelType.IsSubclassOf(inheritTypeOrInterface) ||
                p.ModelType == inheritTypeOrInterface ||
                (inheritTypeOrInterface.IsInterface && inheritTypeOrInterface.IsAssignableFrom(p.ModelType))
            )
        ).
        ToList();
    return list;
}

In addition, used that to find all content reference for a type or interface

public static IList<ContentReference> GetReferenceOf(Type inheritTypeOrInterface)
{

    var list = GetContentTypesOfType(inheritTypeOrInterface);
    var result = new List<ContentReference>();
    foreach (var contentType in list)
    {
        var subResult = GetUsagesSpesificType(contentType);
        if (subResult != null)
            result.AddRange(subResult);
    }
    return result;

}
public static IList<ContentReference> GetUsagesSpesificType(ContentType contentType)
{

    var cacheKey = CacheKeyStart + contentType.ModelType;
    var result = EPiServer.CacheManager.Get(cacheKey) as CacheResult;
    if (result == null)
    {
        if (contentType != null)
        {
            var allItems = ContentModelUsage.Service.ListContentOfContentType(contentType).
                Select(x => x.ContentLink.CreateReferenceWithoutVersion()).
                Distinct().ToList();
            result = new CacheResult(allItems);

        }
        else
        {
            result = new CacheResult(null);

        }
        EPiServer.CacheManager.Add(cacheKey, result, System.Web.Caching.CacheItemPriority.BelowNormal);

    }
    return result.GetList();
}

I cache the result for the specific contentType but not for the aggregate list. This is because it is difficult to clear the cache of those aggregate lists. I can therefore easy make a method that returns all content of a specific type or interface.

public static List<T> GetContentOf<T>(ILanguageSelector selector) 
{
    var result = new List<T>();
    foreach (var item in ContentLoader.Service.GetItems(GetReferenceOf(typeof(T)), selector))
        if (item is T)
            result.Add((T)item);;
    return result;
}

The only thing I need now is to clear the cache if new content is added or deleted.

public void Initialize(EPiServer.Framework.Initialization.InitializationEngine context)
{
    DataFactory.Instance.CreatedContent += Instance_ClearCache;
    DataFactory.Instance.DeletedContent += Instance_ClearCache;
}

void Instance_ClearCache(object sender, ContentEventArgs e)
{
    if (e.Content != null)
    {
        var contentType=ContentTypeRepository.Service.Load(e.Content.GetOriginalType());
        if (contentType != null)
        {
            var cacheKey = CacheKeyStart + contentType.ModelType;
            EPiServer.CacheManager.Remove(cacheKey);
        }
    }
}

So it can be used to find pages that inherits from a base pagetype that have a BasePropertyName equals to shouldBe

var items3 = FindContent.GetContentOf<BasePageType>(LanguageSelector.MasterLanguage()).
    Where(p => !p.IsDeleted).
    Where(p => p.BasePropertyName == shouldBe);

var items4 = FindContent.GetContentOfExcludeDeleted<IHaveInterface>(LanguageSelector.MasterLanguage()).
    Where(p => p.InterfaceName==shouldBe);

The complete code is here

Feb 18, 2014

Comments

Please login to comment.
Latest blogs
Opti ID overview

Opti ID allows you to log in once and switch between Optimizely products using Okta, Entra ID, or a local account. You can also manage all your use...

K Khan | Jul 26, 2024

Getting Started with Optimizely SaaS using Next.js Starter App - Extend a component - Part 3

This is the final part of our Optimizely SaaS CMS proof-of-concept (POC) blog series. In this post, we'll dive into extending a component within th...

Raghavendra Murthy | Jul 23, 2024 | Syndicated blog

Optimizely Graph – Faceting with Geta Categories

Overview As Optimizely Graph (and Content Cloud SaaS) makes its global debut, it is known that there are going to be some bugs and quirks. One of t...

Eric Markson | Jul 22, 2024 | Syndicated blog

Integration Bynder (DAM) with Optimizely

Bynder is a comprehensive digital asset management (DAM) platform that enables businesses to efficiently manage, store, organize, and share their...

Sanjay Kumar | Jul 22, 2024

Frontend Hosting for SaaS CMS Solutions

Introduction Now that CMS SaaS Core has gone into general availability, it is a good time to start discussing where to host the head. SaaS Core is...

Minesh Shah (Netcel) | Jul 20, 2024

Optimizely London Dev Meetup 11th July 2024

On 11th July 2024 in London Niteco and Netcel along with Optimizely ran the London Developer meetup. There was an great agenda of talks that we put...

Scott Reed | Jul 19, 2024