Using GetEntryAssembly in Event Receiver

Have you ever wanted to deny all users from deleting items in a list if they are using the web interface but you still allow an external calling application (f.e. patch) to delete items.
I recently had such a situation where I was asked to write an event receiver that prevented all users from deleting items in a list which I did. Then we had to do some updates which required that some items were deleted. I wrote a patch (an external .exe) that met the requirements but my event receiver stopped me from deleting items.
So, my two options was to either first remove the event receiver and then run my patch and the re-add the event receiver (not pretty) or to find an alternative solution.
The solution was that Assembly.GetEntryAssembly method returns null when called from a web context (the UI for example) but otherwise it is not null.
Here´s an example:
public override void ItemDeleting(SPItemEventProperties properties)
{
    Assembly assembly = Assembly.GetEntryAssembly();
    if (assembly != null)
    {
        return;
    }

Calling from the web interface – assembly is null.

image_thumb1

Calling from an external .exe application – assembly is not null.

image_thumb3

So, now I had a way of finding out if the caller was web based or not and thus I find a way to determine whether or not to run the event receiver.

Note: Original idea by Thomas Persson (get a blog man so I can link to you)

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: