Janaka Fernando
Apr 2, 2015
  17385
(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
Copy Optimizely SaaS CMS Settings to ENV Format Via Bookmarklet

Do you work with multiple Optimizely SaaS CMS instances? Use a bookmarklet to automatically copy them to your clipboard, ready to paste into your e...

Daniel Isaacs | Dec 22, 2024 | Syndicated blog

Increase timeout for long running SQL queries using SQL addon

Learn how to increase the timeout for long running SQL queries using the SQL addon.

Tomas Hensrud Gulla | Dec 20, 2024 | Syndicated blog

Overriding the help text for the Name property in Optimizely CMS

I recently received a question about how to override the Help text for the built-in Name property in Optimizely CMS, so I decided to document my...

Tomas Hensrud Gulla | Dec 20, 2024 | Syndicated blog

Resize Images on the Fly with Optimizely DXP's New CDN Feature

With the latest release, you can now resize images on demand using the Content Delivery Network (CDN). This means no more storing multiple versions...

Satata Satez | Dec 19, 2024

Simplify Optimizely CMS Configuration with JSON Schema

Optimizely CMS is a powerful and versatile platform for content management, offering extensive configuration options that allow developers to...

Hieu Nguyen | Dec 19, 2024

Useful Optimizely CMS Web Components

A list of useful Optimizely CMS components that can be used in add-ons.

Bartosz Sekula | Dec 18, 2024 | Syndicated blog