Friday, March 4, 2011

Add event receiver to a SharePoint list

Recently I have created a generic function to add event receiver to specific SharePoint list.
Explaination is not need as code is very simple to understand.

private void AddEventReceiverToAList(string siteUrl)
{
    using (SPSite site = new SPSite(siteUrl))
    {
        using (SPWeb web = site.OpenWeb())
        {
            try
            {
                SPList list = web.Lists["myList"];
                if (list != null)
                {
                    int receivers = list.EventReceivers.Count;
                    string className = "EventReceiverClass";
                    string asmName = "EventReceiverAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a865f0ecc234ea51";
                    web.AllowUnsafeUpdates = true;
                    bool isAddedReceiverExist = false;
                    for (int i = 0; i < receivers; i++)
                    {
                        SPEventReceiverDefinition eventReceiver = list.EventReceivers[i];
                        if (eventReceiver.Class == className && eventReceiver.Type == SPEventReceiverType.ItemAdded)
                        {
                            isAddedReceiverExist = true;
                            break;
                        }
                    }
                    if (!isAddedReceiverExist)
                        list.EventReceivers.Add(SPEventReceiverType.ItemAdded, asmName, className);
                }
            }
            catch { }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }
    }

1 comment:

  1. hi when i added document programatically my itemAdded event reciver is not firing ?If i change in Synchronous in Element.xml its firing why?itemAdded is asynchronous event then why i need to fire synchronous?pls help me

    ReplyDelete