Handle global events

Global events allow you to execute custom code whenever specific actions occur within the system. Events can be raised as a result of both user interaction and the logic of the application itself (default or custom). When you assign a method as a handler for an event, the system automatically executes the code whenever the corresponding action occurs.

For example, when a new page is added to your website, you can use an event handler to load the page’s data, send out the content by email, and use a third-party component to generate a PDF version of the page.

Assigning handlers to events

Use code in the following format to register handlers for global events:

<event class>.<event action>.<event type> += <handler method name>

  • Event class – event classes are containers of events related to groups of functionality
  • Event action – represents a specific action that occurs within the system
  • Event type – determines when exactly the event takes place, typically Before or After the action that invokes it. Some actions only have one type: Execute

For example:



WebPageEvents.UpdateDraft.After += Page_Update_After;

The event handlers provide parameters derived from EventArgs, which you can use to access data related to the action that occurred. The exact type of the parameter depends on the event.

For information about the available event classes, actions, event types and handler parameters, see: Reference - Global system events

You need to register event handlers at the beginning of the application’s life cycle (during application startup). See Run code on application startup for more information.

Example

The following steps describe how to register methods as global event handlers:

  1. Open your project in Visual Studio.

  2. Add custom initialization code that handles the required events.

    • Add the code into a custom Class Library project within your solution. See Integrate custom code for more information.


using CMS;
using CMS.DataEngine;
using CMS.Websites;

// Registers the custom module into the system
[assembly: RegisterModule(typeof(CustomInitializationModule))]

public class CustomInitializationModule : Module
{
    // Module class constructor, the system registers the module under the name "CustomInit"
    public CustomInitializationModule()
        : base("CustomInit")
    {
    }

    // Contains initialization code that is executed when the application starts
    protected override void OnInit()
    {
        base.OnInit();

        // Assigns custom handlers to events   
        WebPageEvents.Create.After += Page_Create_After;   
        WebPageEvents.UpdateDraft.Before += Page_UpdateDraft_Before;
    }

    private void Page_Create_After(object sender, CreateWebPageLanguageVariantEventArgs e)
    {
        // Add custom actions here
    }

    private void Page_UpdateDraft_Before(object sender, UpdateWebPageDraftEventArgs e)
    {
        // Add custom actions here
    }
}