Developer FAQ

How to attach events to Composite C1 Data Stores?

Answer:

First, create a delegate method. (In the example below, it is called MyDataAfterAdd.)

using Composite.Data;
using Composite.Data.Types;
using Composite.Core.Logging;

public static class MyEventRegistrator
{
	static MyEventRegistrator()
	{
        DataEvents<IPage>.OnAfterAdd += new DataEventHandler (MyDataAfterAdd);
	}

	public static void Initialize()
	{
		// initialization code is in the static constructor
	}

	private static void MyDataAfterAdd(object sender, DataEventArgs dataEventArgs)
	{
		IPage page = (IPage)dataEventArgs.Data; // A page with data just added

		// Do your magic here
        LoggingService.LogInformation("MyEventRegistrator", page.Title);
	}
}

Download the source

Next, attach events on the system's initialization.

The best way is to use the [ApplicationStartup] attribute in the Composite.Application namespace also available for files in the App_Code folder. This attribute allows you to have your code executed automatically on the C1 application startup. For this, you need to add two static methods OnBeforeInitialize and OnInitialized.

In our case, we will use the OnInitialized method to call the Initialize method of our event registration class.

using Composite.Core.Application;

[ApplicationStartup]
public class MyAppStartupHandler
{
	public static void OnBeforeInitialize() 
	{
	
	}

	public static void OnInitialized()
	{
		MyEventRegistrator.Initialize();
	}
}

Download the source

That's it. Now replace "//do your magic here" with your code. (Just for illustration, in the above example, we have added the code that writes to the log the title of the page that has been just added.)

This example uses Composite.Data.Types.IPage. You can also use anything that derives from Composite.Data.IData.

Requirements

Composite C1 2.0 SP1 or later