Five New Optimizely Certifications are Here! Validate your expertise and advance your career with our latest certification exams. Click here to find out more

Janaka Fernando
Apr 2, 2015
  8014
(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
Optimizely Configured Commerce and Spire CMS - Figuring out Handlers

I recently entered the world of Optimizely Configured Commerce and Spire CMS. Intriguing, interesting and challenging at the same time, especially...

Ritu Madan | Mar 12, 2025

Another console app for calling the Optimizely CMS REST API

Introducing a Spectre.Console.Cli app for exploring an Optimizely SaaS CMS instance and to source code control definitions.

Johan Kronberg | Mar 11, 2025 |

Extending UrlResolver to Generate Lowercase Links in Optimizely CMS 12

When working with Optimizely CMS 12, URL consistency is crucial for SEO and usability. By default, Optimizely does not enforce lowercase URLs, whic...

Santiago Morla | Mar 7, 2025 |

Optimizing Experiences with Optimizely: Custom Audience Criteria for Mobile Visitors

In today’s mobile-first world, delivering personalized experiences to visitors using mobile devices is crucial for maximizing engagement and...

Nenad Nicevski | Mar 5, 2025 |

Unable to view Optimizely Forms submissions when some values are too long

I discovered a form where the form submissions could not be viewed in the Optimizely UI, only downloaded. Learn how to fix the issue.

Tomas Hensrud Gulla | Mar 4, 2025 |

CMS 12 DXP Migrations - Time Zones

When it comes to migrating a project from CMS 11 and .NET Framework on the DXP to CMS 12 and .NET Core one thing you need to be aware of is the...

Scott Reed | Mar 4, 2025