Creating a Simple Event Handler for SharePoint – Part 1

12 08 2008

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:

public override void ItemDeleting(SPItemEventProperties properties)
{
//Declare our Variables
string currentuser;
string creator;
//Set up our SharePoint List Item
SPListItem rfq = properties.ListItem;
//Get the Display Name of the Current Logged In User
currentuser = properties.UserDisplayName.ToString();
//Get the value of the Created By Field of the current item
creator = rfq[“Author”].ToString();
//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
creatorname = user.LoginName;
//Compare the two user names to see if they match
if (creator == currentuser)
{
 //Allow deletion of the item

properties.Cancel = false;
}
else
{
//Cancel the Deletion of the item
properties.Cancel = true;
//Raise our Error Message to the user
properties.ErrorMessage = “You are not the creator of this item therefore you cannot delete it.”;
}

 

 

 

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:

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.
Advertisements

Actions

Information

8 responses

5 11 2008
Dishaniti

Hello

Can you guide how can I validate due date i.e. due date should not be less than todays date in Task List?

27 03 2009
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];

27 03 2009
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 🙂

27 03 2009
David HOCQUET

Correcting myself !

SPFieldUserValue authorLookup = new SPFieldUserValue(web, _newsItem[“Author”] as String);
SPUser author = authorLookup.User;

18 09 2009
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?

18 09 2009
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.

6 11 2009
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;
}
}

}

26 03 2010
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

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: