Creating a Simple Event Handler for SharePoint – Part 1

Creating a Simple Event Handler for SharePoint – Part 1

SharePoint Event Handlers Logo

A question often asked by my users was can we prevent other users from deleting or modifying their documents uploaded to a document library, this as we all know is core SharePoint functionality but can be disabled by using event handlers.Event handlers bind/attach to document libraries or any type of SharePoint list and fire a particular piece of code when a specified event occurs. Their are many different events, such as:

ItemAdding – Occurs when an Item is being Added

ItemDeleted – Occurs once an Item has been Deleted

So you see, we can fire our code before the event happens, or after if required.
In this post, we will create a simple event handler for the ‘ItemDeleting’ event so that when a user who is not the creator of the item goes to delete the item they will be presented with an error message.
1. Create a new project in Visual Studio (2005 or 2008 up to you) and select a Class Library (C#)

2.Rename the .cs class file to something suitable and enter the following code:


4.Next we must strongly sign the assembly, so go to project > properties within visual studio, go to the signing tab and click ‘new’, give it an appropriate name and select OK.

Your Solution Explorer should now look like the following:

Visual Studio Solution Explorer

5.You can now debug the solution to build the dll.6.So how do we install this into SharePoint I hear you all ask?, well stay tuned for Part 2 of this tutorial where I will show you how to use ‘features’ to install the event handler into SharePoint.

8 thoughts on “Creating a Simple Event Handler for SharePoint – Part 1

  1. David HOCQUET

    Hi,

    Very usefull thank you !

    A better way to get the Author as a SPUser could be:
    SPFieldLookupValue authorLookupValue = new SPFieldLookupValue(item["Author"] as String);
    SPUser author = web.AllUsers[authorLookupValue.LookupId];

    1. alex350r

      Thanks David, glad it helped.

      The reason I made the post was due to the lack of literature regarding Event Handlers in SharePoint.

      Thanks for the tip regarding the Author :-)

  2. komgal

    This is good, but i have something different to do in ItemDeleting.

    In code that should prevent item from deleting, i need to update one of the fields of item. For example, i need to set item status to “Delete in Process”.
    Looks like setting Cancel=true discards my changes to item fields.

    Have you done something like this?

    1. alex350r

      Thanks,

      To answer your question in your ItemDeleting event you should be able to call properties.listItem["FieldName"] = “Delete in Process” and then a properties.ListItem.Update to commit the changes to the list item. After you have done the item update then try setting properties.cancel = true and the changes should be not be lost.

      Let me know how you get on.

  3. Stefan Thorpe

    I have created a similar version to stop users self approving there own expenses( see below). however I can’t build it as I get an error saying the name web does not exist in this context. Do I need to declare it?

    void SelfApprovalCheck(SPItemEventProperties properties)
    {
    //declare object and assign for current listitem
    SPListItem expenses = properties.ListItem;
    //declare and assign string for current user name
    string currentUser = properties.UserDisplayName.ToString();
    //declare and assign string creator name
    string creator = Convert.ToString(expenses["Author"]);
    //Convert the Author into a SharePoint user id
    int userid = Convert.ToInt32(creator.Substring(0, creator.IndexOf(“;#”)));
    //Get the SharePoint user which matches the ID
    SPUser user = web.AllUsers.GetByID(userid);
    //Set the domain login name of the author user
    string creatorName = user.LoginName;
    //Get approved Status
    string approved = Convert.ToString(expenses["Status"]);
    //Check Approved Status
    if (approved == “Approved”)
    {
    //Compare the two user names to see if they match
    if (creator == currentUser)
    {
    properties.Cancel = true;
    //Raise our Error Message to the user
    properties.ErrorMessage = “You are the creator of this item therefore you cannot Approve it.”;
    }
    else
    {
    //Allow deletion of the item
    properties.Cancel = false;
    }
    }

    }

  4. todd

    Need a little help.
    1) i found the i need to add a refernce to sharepoint.
    Are there an other refernce i need to add?
    2)creatorname in line 17 and web in line 15 does not exist in the current context.
    How do i make them exist?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">