Don't miss out Virtual Happy Hour this Friday (April 26).

Try our conversational search powered by Generative AI!

Janaka Fernando
Apr 2, 2015
  16467
(5 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
Solving the mystery of high memory usage

Sometimes, my work is easy, the problem could be resolved with one look (when I’m lucky enough to look at where it needs to be looked, just like th...

Quan Mai | Apr 22, 2024 | Syndicated blog

Search & Navigation reporting improvements

From version 16.1.0 there are some updates on the statistics pages: Add pagination to search phrase list Allows choosing a custom date range to get...

Phong | Apr 22, 2024

Optimizely and the never-ending story of the missing globe!

I've worked with Optimizely CMS for 14 years, and there are two things I'm obsessed with: Link validation and the globe that keeps disappearing on...

Tomas Hensrud Gulla | Apr 18, 2024 | Syndicated blog

Visitor Groups Usage Report For Optimizely CMS 12

This add-on offers detailed information on how visitor groups are used and how effective they are within Optimizely CMS. Editors can monitor and...

Adnan Zameer | Apr 18, 2024 | Syndicated blog