Adding Event Receiver extension method

Seriously, how many times have you written code like this to add an event receiver to a list:

string assembly = "Assembly.Name, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxx";
string classname = "Assembly.NameSpace.Class";
 

SPList list = web.Lists["TargetList"];

list.EventReceivers.Add(SPEventReceiverType.ItemAdded, assembly, classname);

The problem with this code (besides that it´s ugly) is that it´s totally unmanageable. What if we changed the version of the assembly or something like that. No, it´s time for something new. Wouldn´t it be nice to be able to write something like this instead:

list.EventReceivers.Add<MyEventReceiver>(SPEventReceiverType.ItemAdded);

…where MyEventReceiver holds the ItemAdded event implementation.

With the new extension method capability we could simply add a “new” add method to the SPEventReceiverDefinitionCollection class that looks something like this:

static class SPEventReceiverDefinitionCollectionExtensions
{
    public static void Add<T>(this SPEventReceiverDefinitionCollection collection, SPEventReceiverType receiverType) where T : class
    {
        // add event receiver
        var assembly = new
        {
            Token = AssemblyManager<T>.AssemblyFullName,
            Class = AssemblyManager<T>.ClassFullName
        };

        collection.Add(receiverType, assembly.Token, assembly.Class);
    }
}

AssemblyManager is simply a class that helps out with getting some information from the typeof(T) Type, looks like this:

static class AssemblyManager<T>
{

    public static string ClassFullName
    {
        get
        {
            Type type = typeof(T);
            return type.FullName;
        }
    }

    public static string AssemblyFullName
    {
        get
        {
            Type type = typeof(T);
            return type.Assembly.GetName().FullName;
        }
    }
}

I know…it´s no rocket science, but extremely handy.

Note: Thanks to Johan Aspenlind who originally wrote this code!

Advertisements

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: