Adding More Helpers (ie ItemEventReceiverHelper)?

Jul 28, 2009 at 9:20 PM

Hi,

I like the idea of WebConfigModHelper class, and IMO this could go as well to Lookup Fields, List Creation and ItemEventReceiver, for example, if we want to bind a item event receiver to the list and unbind we could have smth like this:

public static class ItemEventReceiverHelper
    {
        public static void Register<T>(SPList list, T receiver, params SPEventReceiverType[] receiverTypes)
            where T : SPItemEventReceiver
        {
            Type type = typeof(T);
            string assemblyFullName = type.Assembly.FullName;
            string typeFullName = type.FullName;

            foreach(var receiverType in receiverTypes)
            {
                list.EventReceivers.Add(receiverType, assemblyFullName, typeFullName);
                list.Update();
            }
        }

        public static void Unregister<T>(SPList list, T receiver, params SPEventReceiverType[] receiverTypes)
            where T : SPItemEventReceiver
        {
            var toBeDeleted = new List<Guid>();

            Type type = typeof(T);
            string assemblyFullName = type.Assembly.FullName;
            string typeFullName = type.FullName;

            foreach(SPEventReceiverDefinition eventReceiverDef in list.EventReceivers)
            {
                foreach(var receiverType in receiverTypes)
                {
                    if(eventReceiverDef.Type == receiverType)
                    {
                        if(eventReceiverDef.Assembly == assemblyFullName && eventReceiverDef.Name == typeFullName)
                            toBeDeleted.Add(eventReceiverDef.Id);
                    }
                }
            }

            foreach(var id in toBeDeleted)
            {
                list.EventReceivers[id].Delete();
            }

            list.Update();
        }
    }

IMO almost every one is creating their own methods to do this stuff, and not always in proper way. By incorporating this in P&P for sharepoint lots of end users whould not have to look for the answer over internet.

Cheers,

   Jakub G