Microsoft Visual Studio 2010 provides a project type that enables you to build event receivers that perform actions before or after selected events on a Microsoft SharePoint 2010 site. This example shows how to add an event to the adding and updating actions
for custom list items.
This SharePoint Visual How To describes the following steps for creating and deploying an event receiver in Visual Studio 2010:
Overriding the itemAdding event and the itemUpdating event.
Verifying that the list to which the item is being added is the Open Position list.
Elevating permissions so that the code can access a secure site to retrieve approved job titles.
Comparing approved Job Titles with the title of a new item that is created in the Open Position list.
Canceling the event when the Job Title is not approved.
In this example, a secure subsite contains a list named Job Definitions that specifies allowed job titles for roles in the organization. Along with job titles, the list also contains confidential salary information for the job title and
is therefore secured from users. In the main site, a list named Open Positions tracks vacancies in the organization. You create two event receivers for the itemAdding and itemUpdating events that verify that the title of the open position matches one of the approved titles in the Job Definitions list.
Prerequisites
Before you start, create the subsite and lists that you will need.
To create the Job Definitions subsite
On the main site, on the Site Actions menu, click New Site.
In the New Site dialog box, click Blank Site.
On the right of the dialog box, click More Options.
In the Title box, type Job Definitions.
In the Web Site Address box, type JobDefinitions.
In the Permissions section, click Use Unique Permissions, and then click Create.
In the Visitors to this site section, select Use an existing group, and then select Team Site Owners. Click OK.
To create the Job Definitions list
-
In the Job Definitions site, create a custom list named
Job Definitions with the following columns:
Add several jobs to this list. Note the titles that you specify for each job that you create because you will need them later.
To create the Open Positions list
Creating an Event Receiver
Next, create an Event Receiver project in Visual Studio 2010, and add code to the events receiver file.
To create a SharePoint 2010 event receiver in Visual Studio 2010
Start Visual Studio 2010.
On the File menu, click New, and then click
Project.
In the New Project dialog box, in the Installed Templates section, expand either Visual Basic or Visual C#, expand SharePoint, and then click 2010.
In the template list, click Event Receiver.
In the Name box, type VerifyJob.
Leave other fields with their default values, and click OK.
In the What local site do you want to use for debugging? list, select your site.
Select the Deploy as a farm solution option, and then click
Next.
On the Choose Event Receiver Settings page, in the What type of event receiver do you want? list, select List Item Events.
In the What Item should be the event source? list, select
Custom List.
Under Handle the following events, select the An item is being added and the An item is being updated check boxes. Click Finish.
To modify the events receiver file
-
In the events receiver file, add the following code to the class.
Public Function CheckItem(ByVal properties As SPItemEventProperties) As Boolean
Dim jobTitle As String = properties.AfterProperties("Title").ToString()
Dim allowed As Boolean = False
Dim jobDefWeb As SPWeb = Nothing
Dim jobDefList As SPList
Dim privilegedAccount As SPUser = properties.Web.AllUsers("SHAREPOINT\SYSTEM")
Dim privilegedToken As SPUserToken = privilegedAccount.UserToken
Try
Using elevatedSite As New SPSite(properties.Web.Url, privilegedToken)
Using elevatedWeb As SPWeb = elevatedSite.OpenWeb()
jobDefWeb = elevatedWeb.Webs("JobDefinitions")
jobDefList = jobDefWeb.Lists("Job Definitions")
For Each item As SPListItem In jobDefList.Items
If item("Title").ToString() = jobTitle Then
allowed = True
Exit For
End If
Next
End Using
End Using
Return (allowed)
Finally
jobDefWeb.Dispose()
End Try
End Function
bool checkItem(SPItemEventProperties properties)
{
string jobTitle = properties.AfterProperties["Title"].ToString();
bool allowed = false;
SPWeb jobDefWeb = null;
SPList jobDefList;
SPUser privilegedAccount = properties.Web.AllUsers[@"SHAREPOINT\SYSTEM"];
SPUserToken privilegedToken = privilegedAccount.UserToken;
try
{
using (SPSite elevatedSite = new SPSite(properties.Web.Url, privilegedToken))
{
using (SPWeb elevatedWeb = elevatedSite.OpenWeb())
{
jobDefWeb = elevatedWeb.Webs["JobDefinitions"];
jobDefList = jobDefWeb.Lists["Job Definitions"];
foreach (SPListItem item in jobDefList.Items)
{
if (item["Title"].ToString() == jobTitle)
{
allowed = true;
break;
}
}
}
}
return (allowed);
}
finally
{
jobDefWeb.Dispose();
}
}
-
In the EventReceiver1 file, replace the ItemAdding method with the following code.
Public Overrides Sub ItemAdding(properties as SPItemEventProperties)
Try
Dim allowed As Boolean = True
If properties.ListTitle = "Open Positions" Then
allowed = CheckItem(properties)
End If
If allowed = False Then
properties.Status = SPEventReceiverStatus.CancelWithError
properties.ErrorMessage = _
"The job you have entered is not defined in the Job Definitions List"
properties.Cancel = True
End If
Catch ex As Exception
properties.Status = SPEventReceiverStatus.CancelWithError
properties.ErrorMessage = ex.Message
properties.Cancel = True
End Try
End Sub
public override void ItemAdding(SPItemEventProperties properties)
{
try
{
bool allowed = true;
if (properties.ListTitle == "Open Positions")
{
allowed = checkItem(properties);
}
if (!allowed)
{
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.ErrorMessage =
"The job you have entered is not defined in the Job Definitions List";
properties.Cancel = true;
}
}
catch (Exception ex)
{
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.ErrorMessage = ex.Message;
properties.Cancel = true;
}
}
-
In the EventReceiver1 file, replace the ItemUpdating method with the following code.
Public Overrides Sub ItemUpdating(properties as SPItemEventProperties)
Try
Dim allowed As Boolean = True
If properties.ListTitle = "Open Positions" Then
allowed = CheckItem(properties)
End If
If allowed = False Then
properties.Status = SPEventReceiverStatus.CancelWithError
properties.ErrorMessage = _
"The job you have entered is not defined in the Job Definitions List"
properties.Cancel = True
End If
Catch ex As Exception
properties.Status = SPEventReceiverStatus.CancelWithError
properties.ErrorMessage = ex.Message
properties.Cancel = True
End Try
End Sub
public override void ItemUpdating(SPItemEventProperties properties)
{
bool allowed = true;
if (properties.ListTitle == "Open Positions")
{
allowed = checkItem(properties);
}
try
{
if (!allowed)
{
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.ErrorMessage =
"The job you have entered is not defined in the Job Definitions List";
properties.Cancel = true;
}
}
catch (Exception ex)
{
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.ErrorMessage = ex.Message;
properties.Cancel = true;
}
}
To deploy the project
In Solution Explorer, right-click the project, and then click Deploy.
In the SharePoint site, in the Open Positions list, click
Add new item.
In the Title field, provide a title for a job description that does not exist in the Job Definitions list in the secured subsite.
Click Save. You receive a message from the event receiver.
In the Title field, provide a title for a job description that exists in the Job Definitions list in the secured subsite.
Click Save. The position is created.
The solution overrides the ItemAdding and ItemUpdating methods and verifies whether the list that is being added to is the Open Positions list. If it is, a call is made to the CheckItem method, passing in the properties that are associated with the event.
In the CheckItem method, the permissions are elevated to ensure successful access to the secured subsite. The job titles that are in the approved list are compared to the job title of the properties.AfterProperties property associated with the event. If any title matches, the allowedBoolean variable is set to true, and the method returns.
Depending on the value of the allowed variable, the calling method either permits the event or sets the properties.ErrorMessage property and then cancels the event using properties.cancel.
|