World is now on Opti ID! Learn more

janaka.fernando
Apr 2, 2015
  8024
(0 votes)

Adding custom logic to your publishing step

With EPiServer there are great, easy ways to add validation to your content.  You can easily add DataAnnotations like [Required] to your properties to individually validate them.

There is also the IValidator  interface you can implement to handle validation of the Save event.  See the documentation for more info - http://world.episerver.com/Documentation/Items/Developers-Guide/EPiServer-CMS/7/Validation/Validation/
 
While both these are a simple and effective, one question I am hearing from developers and customers is how can I set up custom business rules for validating who can publish a content item?
 
 

Content Events to the Rescue!

 
The easiest way here is to use the built in IContentEvents to determine when an event like Content Publishing is triggered.  This applies globally to all sites so I would consider writing this code into an InitializationModule like in the example below.  IContentEvents exposes a number of events, because here we’re interested in before content is published, we will use PublishingContent.  All the events have a pre / post event so there is also a PublishedContent event.
 
[InitializableModule]
    [ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
    public class PublishEventInitializationModule : IInitializableModule
    {
        public void Initialize(InitializationEngine context)
        {
            //Add initialization logic, this method is called once after CMS has been initialized
            var contentEvents = ServiceLocator.Current.GetInstance<IContentEvents>();
            contentEvents.PublishingContent += contentEvents_PublishingContent;
        }
 
        void contentEvents_PublishingContent(object sender, EPiServer.ContentEventArgs e)
        {
            // Your event code here
        }
 
        public void Preload(string[] parameters) { }
 
        public void Uninitialize(InitializationEngine context)
        {
            //Add uninitialization logic
            var contentEvents = ServiceLocator.Current.GetInstance<IContentEvents>();
            contentEvents.PublishingContent -= contentEvents_PublishingContent;
        }
    }

 

Now the interesting bit

 

Let’s say the customer use case is they wanted someone other than the content Creator to be able to publish.  For example, I can publish your work but not my own.

This isn’t standard functionality and fits well into our scenario. 

 

Here’s an example solution to solving this.  Here I am  testing whether the content to be published implements IChangeTrackable which gives us access to the CreatedBy property.  If its the same person as the current user then we want to cancel publishing.

void contentEvents_PublishingContent(object sender, EPiServer.ContentEventArgs e)
{
    // Applies to Pages, Blocks, Media
    if (e.Content is IChangeTrackable)
    {
        string author = string.Empty;
        var content = e.Content as IChangeTrackable;
        author = content.CreatedBy;
 
        bool isSameUser = string.Compare(PrincipalInfo.CurrentPrincipal.Identity.Name, author, true) == 0;
 
        if (isSameUser)
        {
            e.CancelAction = true;
            e.CancelReason = "Unable to publish content created by the same user.  Please mark as 'Ready to Publish' and have another user publish";
        }
    }
}

 

The ContentEventArgs e gives us the content item which we can test against.  It also provides us with properties to cancel the action and provide a message to the editor.  Like the validation options mentioned at the start, this hooks in nicely to the editor so they get error messages like this.

ErrorMessage

 

Polishing it up

 

So now that the validation code is in place I’d tidy a few things up to make this production ready. 

 

To start off I would separate out the concern of the validation into a validator class.  In this example there is only 1 validation but potentially there could be several.  Also importantly this means we can unit test the validator class functionality.  My completed PublishingValidator looks like this.

public class PublishingValidator : IPublishingValidator 
{
    public bool IsTheSameCreator(IContent content, string authorName)
    {
        bool isSameUser = false;
 
        if (content is IChangeTrackable)
        {
            string author = string.Empty;
            var tracked = content as IChangeTrackable;
            author = tracked.CreatedBy;
 
            isSameUser = string.Compare(authorName, author, true) == 0;
        }
 
        return isSameUser;
    }
}

 

My InitializationModule will now use this class through the ServiceLocator.  I registered IPublishingValidator in my dependency resolver initialization.  Finally I will add the LocalizationService to make the error message localized to the editor’s language.  Here is the final code for the PublishingContent event handler.

void contentEvents_PublishingContent(object sender, EPiServer.ContentEventArgs e)
{
    var localizationService = ServiceLocator.Current.GetInstance<LocalizationService>();
    var validator = ServiceLocator.Current.GetInstance<IPublishingValidator>();
 
    // Applies to Pages, Blocks, Media
    if (validator.IsTheSameCreator(e.Content, PrincipalInfo.CurrentPrincipal.Identity.Name))
    {
        e.CancelAction = true;
        e.CancelReason = localizationService.GetString("/ValidationErrors/SameCreator");
    }
}
Apr 02, 2015

Comments

Please login to comment.
Latest blogs
Make Global Assets Site- and Language-Aware at Indexing Time

I had a support case the other day with a question around search on global assets on a multisite. This is the result of that investigation. This co...

dada | Jun 26, 2025

The remote server returned an error: (400) Bad Request – when configuring Azure Storage for an older Optimizely CMS site

How to fix a strange issue that occurred when I moved editor-uploaded files for some old Optimizely CMS 11 solutions to Azure Storage.

Tomas Hensrud Gulla | Jun 26, 2025 |

Enable Opal AI for your Optimizely products

Learn how to enable Opal AI, and meet your infinite workforce.

Tomas Hensrud Gulla | Jun 25, 2025 |

Deploying to Optimizely Frontend Hosting: A Practical Guide

Optimizely Frontend Hosting is a cloud-based solution for deploying headless frontend applications - currently supporting only Next.js projects. It...

Szymon Uryga | Jun 25, 2025

World on Opti ID

We're excited to announce that world.optimizely.com is now integrated with Opti ID! What does this mean for you? New Users:  You can now log in wit...

Patrick Lam | Jun 22, 2025

Avoid Scandinavian Letters in File Names in Optimizely CMS

Discover how Scandinavian letters in file names can break media in Optimizely CMS—and learn a simple code fix to automatically sanitize uploads for...

Henning Sjørbotten | Jun 19, 2025 |