Since Friday we’ve made some significant changes to the event model in Umbraco version 4. This means that it is not backwards compatible with Beta 2, take 3.
We’ve introduced these breaking changes a bit late in the development cycle, but due to the lack of focus on events so far we hope that it is a minimal number of installations we will affect with this change. From a technical standpoint they are absolutely worth it. We’ve added 2 major changes:
Simplified
We’ve simplified the way you hook into events by adding an extra level of abstraction. So no more working with an interface with 10 unused fields.
Cancellable
All before events can now cancel out the associated action. So the BeforePublish event can actually stop the publishing from happening.
Code sample
To hook into umbraco’s events, you need to register your code when umbraco starts up. You do this by using the umbraco.BusinessLofic.ApplicationBase class and an empty constructor. A sample application could look like this:
public class AppBase : umbraco.BusinessLogic.ApplicationBase {
public AppBase() {
umbraco.cms.businesslogic.web.Document.BeforePublish += new umbraco.cms.businesslogic.web.Document.PublishEventHandler(Document_BeforePublish);
}
void Document_BeforePublish(umbraco.cms.businesslogic.web.Document sender, umbraco.cms.businesslogic.PublishEventArgs e) {
umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, sender.Id,sender.Text + " is about to be published");
//cancel the publishing
e.Cancel = true;
}
}
The above code subscribes to the BeforePublish event, logs the document about to be published, and then cancels the publishing by setting e.Cancel to true.
Umbraco will automatically detect all ApplicationBase classes and instantiate them on start-up, and thereby ensuring that the events work.
Boost / Nitro compatible
Files placed in the App_Code folder will also be detected by umbraco. This means you can redistribute your event handlers as basic .cs files, and be Nitro Compatible (Nitros forbid compiled code)
Intelli-sense support
Finally, umbraco events are fully supported by intelli-sense in visual studio. So after adding the Umbraco dll’s (businesslogic.dll & cms.dll) to a project it is possible to just write:
umbraco.cms.businesslogic.web.Document.BeforePublish += and then hit the tab button twice. This will generate all the plumbing code to subscribe to the BeforePublish event.
Future reference
For future reference, the sample code has been placed in the API Cheatsheet book under documentation.