Friday, March 8, 2013

Add EventReceiver To All Lists Programatically


This code to add (itemAdding , itemUpdating , itemDeleting ) event receiver fire in all lists

private void AddEventReceiver(SPWeb myweb)
        {          
         
           SPWeb siteCollection = myweb.Site.RootWeb;            SPContentTypeCollection contentTypeCollection = siteCollection.ContentTypes;
            try            {                string contentTypeName ="myContentType"              
                string contentTypeID = GetContentTypeId(siteCollection, contentTypeName);
                AddReceiverToDiffrentLists(myweb, contentTypeCollection, contentTypeID);                           }            catch            {                //write your code on exception happened            }
            finally            {                siteCollection.Dispose();                myweb.Dispose();            }
        }
        private static string GetContentTypeId(SPWeb myweb, string contentTypeName)        {            return myweb.ContentTypes[contentTypeName].Id.ToString();        }



        private void AddReceiverToDiffrentLists(SPWeb myweb, SPContentTypeCollection contentTypeCollection, string ContentTypeID)        {            SPContentType publPageContentType = fetchContentType(contentTypeCollection, ContentTypeID);            AttachEventReceiverToCT(myweb, publPageContentType);        }
    
  private static void AttachEventReceiverToCT(SPWeb myweb, SPContentType publPageContentType)        {          
            try            {                ArrayList eventTypeArraylist = new ArrayList();
                eventTypeArraylist.Add(SPEventReceiverType.ItemAdding);                eventTypeArraylist.Add(SPEventReceiverType.ItemDeleting);                eventTypeArraylist.Add(SPEventReceiverType.ItemUpdating);
                foreach (var item in eventTypeArraylist)                {                    publPageContentType.EventReceivers.Add((SPEventReceiverType)item, Assembly.GetExecutingAssembly().FullName, "myTestProject.ListDefinitions.ItemReceiver.ItemReceiver");                }
                publPageContentType.Update(true, false);                myweb.Update();            }            catch            {                //write your exception code            }            finally            {                //write your code            }        }
     private SPContentType fetchContentType(SPContentTypeCollection contentTypeCollection, string ID)        {            SPContentType publContentType = null;            foreach (SPContentType contentType in contentTypeCollection)            {
                if (string.Equals(contentType.Id.ToString(), ID, StringComparison.InvariantCultureIgnoreCase))                {                    publContentType = contentType;                    break;                }            }            return publContentType;        }

No comments:

Post a Comment