Janaka Fernando
Apr 2, 2015
  17024
(6 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

Apr 2, 2015 01:11 PM

Nice write up, thanks for sharing

Apr 2, 2015 01:28 PM

Nice :)

david.boyd.engage
david.boyd.engage Jun 23, 2015 07:27 AM

Cheers Janaka this is useful.

Vincent
Vincent Mar 6, 2016 08:19 AM

The ContentEvents can't handle Copy Paste scenario. 

When I copied an existing page/product and pasted to another place, which event should I hook up?

James Parkar
James Parkar Mar 7, 2018 02:44 PM

Can we have access to the page that is currently being publish? Actually I need to access one of the property of that page and change its content and save it.

Please login to comment.
Latest blogs
Integrating Optimizely DAM with Your Website

This article is the second in a series about integrating Optimizely DAM with websites. It discusses how to install the necessary package and code t...

Andrew Markham | Sep 28, 2024 | Syndicated blog

Opticon 2024 - highlights

I went to Opticon in Stockholm and here are my brief highlights based on the demos, presentations and roadmaps  Optimizely CMS SaaS will start to...

Daniel Ovaska | Sep 27, 2024

Required fields support in Optimizely Graph

It's been possible to have "required" properties (value must be entered) in the CMS for a long time. The required metadata haven't been reflected i...

Jonas Bergqvist | Sep 25, 2024

How to write a bespoke notification management system

Websites can be the perfect vehicle for notifying customers of important information quickly, whether it’s the latest offer, an operational message...

Nicole Drath | Sep 25, 2024