Subscribing to events

Subscribing to events allows you to execute custom code on a number of events both before and after the event occurs. All you need to follow this guide is an Umbraco installation with some content, e.g. the Fanoe starter kit.

Subscribing to an event

Let's add a string of text to the log when a document is publish.

We'll start by adding a new class to the project. Call it LogWhenPublished. The events are found in the core services so add using Umbraco.Core; and then we need to inherit from the application event handler : ApplicationEventHandler

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Core;
public class LogWhenPublished : ApplicationEventHandler
{
/// Here we'll subscribe to an event
}

First thing to do in our LogWhenPublished class is to override ApplicationStarted and then subscribe to an event in Umbraco.Core.Services.Contentservice.Published.

Go to the backoffice and publish a piece of content. Now open tracelog.txt located in App-Data/Logs/, scroll to the bottom of the document and there you should find the log entry.

Before and after

As you can see our custom code has been executed when we published a piece of content. Actually it executed after the item was published because we used the Published event. If you want to run code before publishing, use Publishing. The same goes for most other events so Saving : Saved, Copying : Copied and so forth.

More information

Umbraco TV

Our.umbraco.com is the community mothership for Umbraco, the open source asp.net cms. With a friendly forum for all your questions, a comprehensive documentation and a ton of packages from the community.
This site is running
Umbraco version 7.13.0