Article Handling Events

An event is way to react to actions that occur in the platform. Each event executor creates a copy of the content being executed. The In-Process API is used to access the community events. To find out what events are available please see the In-Process API Services.

The best practice for creating event handlers is by using the Initialize() method of an IPlugin interface. This allows your plugin to quickly react to changes in the platform and lets administrators enable or disable your functionality if necessary.

Why Should I Handle Events In My Plugin

By setting up an event handler your solution can immediately react to specific events as they occur in the platform. The events usually revolve around two states before and after. This allows the user to determine what stage in the process to act on.

Creating a Before event handler will give you access to an editable event argument that will be returned prior to executing the particular event. For example on a BeforeCreate event you can strip HTML tags from a field that should be text only. These changes will then be applied to the internal object and the save process will be executed.

The opposite is true for the After event handler. All changes have been processed for that event and you will receive a read-only argument. An AfterCreate event can be used for sending notifications. In this instance a Before event handler could be removing foul or abusive language from the content and will be safe to send after it is processed. This is an important distinction since the order of the registered events can not be set or determined.

Creating an Event Handler

This sample uses the Initialize method of an IPlugin interface to register a BeforeCreated event handler for a blog post. Then the handler method then writes a message to the EventLogs.

public void Initialize()
{
    Apis.Get<Blogs>().Events.BeforeCreate += new BlogBeforeCreateEventHandler(BlogEvent_BeforeCreate);
}

private void BlogEvent_BeforeCreate(BlogBeforeCreateEventArgs blog)
{
    var message = string.Format("A blog post with the title "{0}" is about to be created.", blog.Name);
    var options = new EventLogEntryWriteOptions
    {
        Category = "Samples"
    };

    Apis.Get<EventLog>().Write(message, options);
}