Tuesday 22 October 2013

Attaching Event Handler To A SharePoint List

Attaching an event handler / event receiver to a custom list in SharePoint can be done programmatically. You can create a console application so that every time you require to attach an event handler to a list, you just need to run that console application.

Below is the full code of the sample console application that will attach an event handler to a SharePoint list via code. Basically, the console application only supports the following type of event:

  • ItemAdding - An event that occurs before an item has been added.
  • ItemAdded - An event that occurs after an item has been added.
  • ItemUpdating - An event that occurs before an item is updated.
  • ItemUpdated- An event that occurs after an item has been updated.
  • ItemDeleting - An event that fires before an item is deleted.
  • ItemDeleted - An event that occurs after an item has been deleted.

Also, the console application requires four input parameters as listed below:
  1. Site URL (the full URL of the SharePoint site)
  2.          e.g. http://www.abc.com/log
  3. List Name (the display name of the list)
  4.          e.g. ListName
  5. Event Receivers (The type of event receivers separated by ';')
  6.          e.g. itemadded;itemupdated
  7. Assembly Path (the location path of the assembly)
  8.          e.g. C:\\Sample.dll

When you run the console application, the format should be:

AttachEventHandlerToSPList <site url> <List Name> <Event Receivers> <Assembly Path>

Example:

AttachEventHandlerToSPList http://www.abc.com/log ListName itemadded;itemupdated C:\\Sample.dll




Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Reflection;

namespace AttachEventHandlerToSPList
{
    class Program
    {
        static void Main(string[] args)
        {
            string strClassName = string.Empty;
            string strAssembly = string.Empty;
            try
            {
                if (args.Length != 4)
                {
                    Console.WriteLine("ERROR: Invalid no. of parameters. \n");
                    usage();
                    Environment.Exit(1);
                }


                string siteURL = args[0]; // "http://www.abc.com/sites/DomainRequest"; //
                string listName = args[1]; // "Branch";  //   "Domain Account Request Application";
                string eventReceivers = args[2]; // "itemadded;itemupdated"; //   "itemadding";
                string path = args[3]; // "C:\Documents and Settings\Administrator\Desktop\.net workflow\DomainRequest\DomainRequestEventHandler\bin\Release\DomainRequestEventHandler.dll"
                //AssemblyName assemblyName = AssemblyName.GetAssemblyName(@"C:\Documents and Settings\Administrator\Desktop\.net workflow\DomainRequest\DomainRequestEventHandler\bin\Release\DomainRequestEventHandler.dll");
                Assembly assembly = Assembly.LoadFrom(@path);
                strAssembly = assembly.FullName;
                Type[] types = assembly.GetTypes();
               

                foreach (Type type in types)
                {
                    if (type.BaseType.Name == "SPItemEventReceiver")
                        strClassName = type.FullName;
                }


                if (!string.IsNullOrEmpty(eventReceivers))
                {
                    string[] events = eventReceivers.ToLower().Split(';');

                    int nCnt = events.Count();

                    if (nCnt > 0)
                    {
                        using (SPSite site = new SPSite(siteURL))
                        {

                            using (SPWeb web = site.OpenWeb())
                            {
                                SPList list = web.Lists[listName];

                                foreach (string eventType in events)
                                {
                                    DeleteEventHandler(list, eventType, strClassName);

                                    switch (eventType)
                                    {
                                        case "itemadding":
                                            {
                                                list.EventReceivers.Add(SPEventReceiverType.ItemAdding,
                                                    strAssembly,
                                                    strClassName);
                                                list.Update();

                                                Console.WriteLine(string.Format("EventHandler (ItemAdding) has been added correctly in {0}!", listName));
                                                break;
                                            }
                                        case "itemadded":
                                            {
                                                list.EventReceivers.Add(SPEventReceiverType.ItemAdded,
                                                    strAssembly,
                                                    strClassName);
                                                list.Update();

                                                Console.WriteLine(string.Format("EventHandler (ItemAdded) has been added correctly in {0}!", listName));
                                                break;
                                            }
                                        case "itemupdating":
                                            {
                                                list.EventReceivers.Add(SPEventReceiverType.ItemUpdating,
                                                    strAssembly,
                                                    strClassName);
                                                list.Update();

                                                Console.WriteLine(string.Format("EventHandler (ItemUpdating) has been added correctly in {0}!", listName));
                                                break;
                                            }
                                        case "itemupdated":
                                            {
                                                list.EventReceivers.Add(SPEventReceiverType.ItemUpdated,
                                                    strAssembly,
                                                    strClassName);
                                                list.Update();

                                                Console.WriteLine(string.Format("EventHandler (ItemUpdated) has been added correctly in {0}!", listName));
                                                break;
                                            }
                                        case "itemdeleting":
                                            {
                                                list.EventReceivers.Add(SPEventReceiverType.ItemDeleting,
                                                    strAssembly,
                                                    strClassName);
                                                list.Update();

                                                Console.WriteLine(string.Format("EventHandler (ItemDeleting) has been added correctly in {0}!", listName));
                                                break;
                                            }
                                        case "itemdeleted":
                                            {
                                                list.EventReceivers.Add(SPEventReceiverType.ItemDeleted,
                                                    strAssembly,
                                                    strClassName);
                                                list.Update();

                                                Console.WriteLine(string.Format("EventHandler (ItemDeleted) has been added correctly in {0}!", listName));
                                                break;
                                            }
                                    }


                                }
                            }

                        }
                      
                    }
                    else
                    {
                        Console.WriteLine("Please input EventReceivers Type (separated by ';' if multiple)");
                    }
                }
            }

            catch (Exception ex)
            {

                Console.WriteLine("Error! stack:" + ex.StackTrace);

                Console.WriteLine("Error! message:" + ex.StackTrace);

                Console.WriteLine("press any key to exit ...");

                Console.Read();

            }

        }


        static void DeleteEventHandler(SPList splist, string eventtype, string strClassNme)
        {
            SPEventReceiverType type = (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), eventtype, true);

            for (int i = 0; i < splist.EventReceivers.Count; i++)
            {
                if (splist.EventReceivers[i].Class == strClassNme)
                {
                    if (splist.EventReceivers[i].Type == type)
                    {
                        splist.EventReceivers[i].Delete();
                        splist.Update();
                        Console.WriteLine(eventtype + " Event deleted to " + splist.Title + " list.");
                    }
                }               
            }
        }


        public static void usage()
        {
            Console.WriteLine("Format: AttachEventHandlerToSPList <site url> <List Name> <Event Receivers> <Assembly Path> \n" +
                              "<site url>             -  The sharepoint site url \n" +
                              "<List Name>            -  The display name of the list \n" +
                              "<Event Receivers>      -  The type of event receivers \n" +
                              "                          separated by ';'. (e.g. itemadded;itemupdated) \n" +
                              "<Assembly Path>        -  The location path of the assembly.");

            Console.WriteLine("e.g. Attach the eventhandler in the List: \n" +
                              "AttachEventHandlerToSPList http://www.abc.com/log ListName itemadded;itemupdated C:\\Sample.dll ");
        }
    }
}




No comments:

Post a Comment