Event Handler example

The example is an Event Handler class that catches two moments during the event of deleting a Component.

Initiated
The code in HandlerForInitiated fires when the event is initiated (that is, before the Component is deleted). The method writes a dummy string to the ContextVariables array, and a message to a file (the filename is made unique by including a timestamp).
TransactionCommitted
The code in HandlerForCommitted fires when the event is initiated (that is, after the Component has been successfully deleted). The method retrieves the ContextVariables element that was set during the initiation phase and writes it to a file (again made unique by a timestamp).
using System;
using System.Text;
using Tridion.ContentManager.Extensibility.Events;
using Tridion.ContentManager.Extensibility;
using Tridion.ContentManager.ContentManagement;
using System.IO;

namespace MyEventHandlers
{
	[TcmExtension("MyEventHandlerExtension")]
	public class MyEventHandler : TcmExtension
	{
		public MyEventHandler()
		{
			Subscribe();
		}

		public void Subscribe()
		{
			EventSystem.Subscribe<Component, DeleteEventArgs>(HandlerForInitiated, EventPhases.Initiated);
			EventSystem.Subscribe<Component, DeleteEventArgs>(HandlerForCommitted, EventPhases.TransactionCommitted);
		}

		private void HandlerForInitiated(Component subject, DeleteEventArgs args, EventPhases phase)
		{
			args.ContextVariables.Add("Initiated", "this string was added on initiated phase");
			using (StreamWriter writer = File.CreateText(@"c:\logfolder\Initiated " + DateTime.Now.ToString("HHmmssffff") + ".txt"))
			{
				writer.WriteLine(subject.Title + " is deleted");
				writer.Close();
			}
		}

		private void HandlerForCommitted(Component subject, DeleteEventArgs args, EventPhases phase)
		{
			using (StreamWriter writer = File.CreateText(@"c:\logfolder\Committed " + DateTime.Now.ToString("HHmmssffff") + ".txt"))
			{
				writer.WriteLine(args.ContextVariables["Initiated"].ToString());
				writer.WriteLine(subject.Title + " is deleted");
				writer.Close();
			}
		}
	}
}