How to Create a Sandboxed Event Receiver

(Automating business processes with the safety wheels on)

By: Philip Stathis

Use Case
You are developing a solution to automatically delete multiple list items that will be triggered on a specific list after an item is deleted.

You cannot use a workflow since there is no way to have a workflow fire on item deleted. Custom event receivers to the rescue!

Assumptions
For simplicity and other reasons, the solution would be a lot faster to develop and push to production if it were sandboxed. So you checked your use case and the people that will be triggering the delete are in fact the site owners. So a sandboxed process will obey your permissions in the SharePoint sites.

Why is this important? Sandboxed solutions can only be used when you know you are not going to grab external data, or even leave the site collection for that matter. Also, impersonation is not an option so the requirements must dictate no impersonation or elevated code calls.

Code
Let’s start off by creating a new project:

Leave it as sandboxed and specify any site that you will use for testing:

Now we see the familiar event receiver wizard. A handy tool at our disposal:

Select the list you need and the event to handle. In our case we are going to use the OnItemDeleted event:

So far so good, let’s add the deleting code:

We have 2 methods here. The DeleteBulkItems is by far the best and fastest way to delete items in the sandbox domain. This method was taken from:  http://sharepointerz.blogspot.com/2012/05/bulk-delete-list-items.html

It uses the batch processing capability to remove list items given the ID of the item. I went ahead and added a wrapper method of my choosing called RemoveItems. My goal here is to simply specify an SPList object and a query string and be able to call for the delete of all the items.

In a production environment this code should use a configuration list but for our proof of concept here let’s hardcode the entries.

This event receiver would operate right after the announcement was deleted and clean up a temporary list that is no longer in use.

Final Thoughts
This code example was created as a demonstration of how some simple operations can be rapidly developed and submitted to business users. Since this solution is sandboxed, there is no need to involve a farm administrator or announce an iisreset or other outage before using this solution.

Why did I use delete? Seems like an odd choice at first, but users often are asked to clean up temporary surveys or just batch delete outdated tasks. With the query string in CAML a user can pick only the items they need to purge.

Comments are closed.