Assume you have a SharePoint list with an ItemDeleting event receiver that cancels deletions, prohibiting users to remove any items even if they have the required permissions. If for some reason you would like to delete an item, you should “inactivate” the event receiver first. Inactivating the event receiver just for the current operation may be not trivial in a production system, as you cannot simply deregister (and then re-register) the event receiver, since your users might start deleting other items in the meantime.
The following code snippet provides a sample console application that performs the deletion even if an event receiver would otherwise cancel the operation. It requires the following command line arguments: URL of the list and the ID of the item that should be deleted.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Microsoft.SharePoint;
- namespace DeleteItem
- {
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- if (args.Length != 2)
- {
- throw new ArgumentException("Incorrect number of parameters. Specify List URL and List item ID.");
- }
- else
- {
- var url = args[0];
- var itemId = int.Parse(args[1]);
- using (SPSite site = new SPSite(url))
- {
- using (SPWeb web = site.OpenWeb())
- {
- var eventFiringHandler = new EventFiringHandler();
- try
- {
- var list = web.GetList(url.Substring(web.Url.Length));
- if (list != null)
- {
- Console.WriteLine("List '{0}' found.", list.Title);
- var item = list.GetItemById(itemId);
- Console.WriteLine("Are you sure to delete item '{0}' (y/n)?", item.Title);
- var response = Console.ReadLine();
- if (response.ToLower() == "y")
- {
- eventFiringHandler.EventFiringEnabled = false;
- item.Delete();
- Console.WriteLine("Item '{0}' deleted.", itemId);
- }
- else
- {
- Console.WriteLine("Deletion cancelled.");
- }
- }
- else
- {
- Console.WriteLine("List '{0}' not found.", url);
- }
- }
- finally
- {
- if (eventFiringHandler != null)
- {
- eventFiringHandler.EventFiringEnabled = true;
- }
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("Exception: {0}\r\n{1}", ex.Message, ex.StackTrace);
- }
- }
- internal class EventFiringHandler : SPItemEventReceiver
- {
- public bool EventFiringEnabled
- {
- get
- {
- return base.EventFiringEnabled;
- }
- set
- {
- base.EventFiringEnabled = value;
- }
- }
- }
- }
- }
