November Happy Hour will be moved to Thursday December 5th.

smithsson68@gmail.com
Oct 6, 2015
  3762
(3 votes)

Limiting Page Type Instances

We had a requirement to limit the number of instances of a particular page type within parts of the page tree. I developed a simple attribute and validator which implements this.

You add the attribute to your page type class and specifiy the scope of the check. The scope options I added were :

  • Site - only x instances of the page type can exist on the site, anywhere in the page tree. Probably useful for singletons
  • Same parent - only x instances of the page type can exist in the same parent node, i.e. amongst siblings
  • Same parent and descendants - only x instances of the page type can exist in the same parent node including descendant nodes

Obviously, you could easily add more scope variants here to suite your requirements. The code can be found below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using EPiServer;
using EPiServer.Core;
using EPiServer.Validation;

[AttributeUsage(AttributeTargets.Class)]
public class AllowedInstancesAttribute : Attribute
{
    public AllowedInstancesAttribute(int maxInstances)
    {
        MaxInstances = maxInstances;
    }

    public enum InstanceScope
    {
        Site,
        SameParent,
        SameParentOrDescendant
    }

    public int MaxInstances { get; set; }
    public InstanceScope Scope { get; set; }
}

public class AllowedInstancesValidator : IValidate<PageData>
{
    private readonly IContentLoader contentLoader;

    public AllowedInstancesValidator(IContentLoader contentLoader)
    {
        this.contentLoader = contentLoader;
    }

    public IEnumerable<ValidationError> Validate(PageData instance)
    {
        var allowedInstanceAttribute = instance.GetType().GetCustomAttribute<AllowedInstancesAttribute>(true);

        if (allowedInstanceAttribute == null)
        {
            return Enumerable.Empty<ValidationError>();
        }

        var searchRoot = allowedInstanceAttribute.Scope == AllowedInstancesAttribute.InstanceScope.Site
                                ? ContentReference.StartPage
                                : instance.ParentLink;

        var instancesOfType = this.GetInstancesOfType(instance.GetType(), searchRoot, allowedInstanceAttribute.Scope);

        if (instance.PendingPublish)
        {
            instancesOfType++;
        }

        if (instancesOfType > allowedInstanceAttribute.MaxInstances)
        {
            return new[]
            {
                new ValidationError()
                    {
                        ErrorMessage = string.Format("Only {0} instances of this page type can exist at this level", allowedInstanceAttribute.MaxInstances),
                        PropertyName = "PageName",
                        Severity = ValidationErrorSeverity.Error,
                        ValidationType = ValidationErrorType.StorageValidation
                    }
            };
        }

        return Enumerable.Empty<ValidationError>();
    }

    private int GetInstancesOfType(Type type, ContentReference rootPage, AllowedInstancesAttribute.InstanceScope instanceScope)
    {
        var instances = 0;
        var children = contentLoader.GetChildren<IContent>(rootPage, new LoaderOptions());

        foreach (var child in children)
        {
            if (type == child.GetType())
            {
                instances++;
            }

            if (instanceScope == AllowedInstancesAttribute.InstanceScope.SameParent)
            {
                continue;
            }

            instances += this.GetInstancesOfType(type, child.ContentLink, instanceScope);    
        }

        return instances;
    }
}
Oct 06, 2015

Comments

Grzegorz Wiecheć
Grzegorz Wiecheć Oct 6, 2015 08:00 PM

Interesting feature. We implemented something simalar a while ago, but it was not that configurable. Your solution could be useful in many projects.

I could add that validator is not executed when moving content. So if you have "full" tree level and move another page from somewhere else the Validate method will not protect from extending the limit. To solve it we implemented additional validation in MoveContent method of IContentEvents service.

valdis
valdis Oct 7, 2015 12:22 PM

Wrap it up as nuget package please :)

Please login to comment.
Latest blogs
Optimizely SaaS CMS + Coveo Search Page

Short on time but need a listing feature with filters, pagination, and sorting? Create a fully functional Coveo-powered search page driven by data...

Damian Smutek | Nov 21, 2024 | Syndicated blog

Optimizely SaaS CMS DAM Picker (Interim)

Simplify your Optimizely SaaS CMS workflow with the Interim DAM Picker Chrome extension. Seamlessly integrate your DAM system, streamlining asset...

Andy Blyth | Nov 21, 2024 | Syndicated blog

Optimizely CMS Roadmap

Explore Optimizely CMS's latest roadmap, packed with developer-focused updates. From SaaS speed to Visual Builder enhancements, developer tooling...

Andy Blyth | Nov 21, 2024 | Syndicated blog

Set Default Culture in Optimizely CMS 12

Take control over culture-specific operations like date and time formatting.

Tomas Hensrud Gulla | Nov 15, 2024 | Syndicated blog

I'm running Optimizely CMS on .NET 9!

It works 🎉

Tomas Hensrud Gulla | Nov 12, 2024 | Syndicated blog

Recraft's image generation with AI-Assistant for Optimizely

Recraft V3 model is outperforming all other models in the image generation space and we are happy to share: Recraft's new model is now available fo...

Luc Gosso (MVP) | Nov 8, 2024 | Syndicated blog