Event Receivers
Validating data when an item is added to a
list
Create a list from the SharePoint user
interface called Contacts of template Contacts.
The following screenshot shows the end result:
How to do it…
1. Launch your Visual Studio 2010 IDE as an
administrator (right-click the shortcut
and select Run as administrator).
2. Select File | New | Project. The new project wizard
dialog box as shown will be
displayed (Make sure to select .NET Framework 3.5 in the top drop-down
box):
3. Select Event Receiver under Visual
C# | SharePoint
| 2010 node from Installed
Templates
section on the left-hand side.
4. Name the project ListItemEventReceiver
and provide a directory location
where you
want to save the project and click on OK to proceed to the next step in the
wizard.
5. By default, Visual Studio selects the SharePoint site
available on the machine.
Select Deploy as a Farm
Solution and click on Next to
proceed to the next step
in the wizard:
6. In here, make sure to select List Item Events from
the drop-down for What type of event receiver do you want? and
select Contacts for What
item should be the event source?.
Select the An Item is being added checkbox in the Handle the following events list box. The following screenshot indicates the
selection:
7. Click on Finish
and Visual Studio adds in the
necessary files and opens up the
EventReceiver1.cs. This is the code file in which you
are going to write your
custom event handler.
8. Add the code necessary to validate the phone numbers
and e-mail address of the list.
Your code should look as follows:
using
System;
using
System.Security.Permissions;
using
Microsoft.SharePoint;
using
Microsoft.SharePoint.Security;
using
Microsoft.SharePoint.Utilities;
using
Microsoft.SharePoint.Workflow;
using
System.Text.RegularExpressions;
namespace
ListItemEventReceiver.EventReceiver1
{
///
///
List Item Events
///
public
class EventReceiver1 : SPItemEventReceiver
{
///
/// An
item is being added.
///
public
override void ItemAdding(SPItemEventProperties
properties)
{
base.ItemAdding(properties);
string
sWorkPhone = properties.AfterProperties
["WorkPhone"].ToString();
string
sEmail = properties.AfterProperties["Email"].
ToString();
if
(!string.IsNullOrEmpty(sWorkPhone))
{
if
(!System.Text.RegularExpressions.Regex.
IsMatch(sWorkPhone,
@"^[01]?[- .]?(\([2-9]\
d{2}\)|[2-9]\d{2})[-
.]?\d{3}[- .]?\d{4}$"))
{
properties.Cancel
= true;
}
}
if
(!string.IsNullOrEmpty(sEmail))
{
if
(!System.Text.RegularExpressions.Regex.
IsMatch(sEmail,
@"^(?("")("".+?""@)|(([0-9a-zAZ]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\
w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\
d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zAZ]{
2,6}))$"))
{
properties.Cancel
= true;
}
}
}
}
}
9. Build and execute the solution by pressing F5 or
from menu Debug | Start
Debugging. This should bring up the default
browser with the local site that
you provided in the project creation wizard.
10. From your contacts list, select Add new Item to
add a new item to the contact list.
Here, we will deliberately enter a bad phone format for
the Business Phone field as
shown in the following screenshot to verify our list event
handler:
11. Click on the Save button on the toolbar, this will
invoke the event handler and throws
an error as shown in the next screenshot. If you notice,
the error page indicates that
an event receiver cancelled the request:
12. Close the error dialog and enter a new contact, but
this time using the proper phone
and e-mail format. The contact gets added without any
problem as follows:
Adding a custom error message to the Event Receiver
1. If you have closed your Visual Studio IDE, launch it
now as an administrator
and open the solution file that we created in the previous
recipe.
2. Open EventReceiver1.cs
and add the following two lines of
code just before
the properties.cancel = true line in the workphone regular expression match
"if statement":
string
sErrMsg = "Business Phone is not in correct format";
properties.ErrorMessage
= sErrMsg;
3. Do the same for the Email regular expression match if statement.
Your ItemAdding method
should look like the following code bundle:
public
override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
string
sWorkPhone = properties.AfterProperties
["WorkPhone"].ToString();
string
sEmail = properties.AfterProperties["Email"].
ToString();
if
(!string.IsNullOrEmpty(sWorkPhone))
{
if
(!System.Text.RegularExpressions.Regex.
IsMatch(sWorkPhone,
@"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[-
.]?\d{3}[-
.]?\d{4}$"))
{
string
sErrMsg = "Business Phone is not in
correct
format";
properties.ErrorMessage
= sErrMsg;
properties.Cancel
= true;
}
}
if
(!string.IsNullOrEmpty(sEmail))
{
if (!System.Text.RegularExpressions.Regex.
IsMatch(sEmail,
@"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-
!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\
d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zAZ]{
2,6}))$"))
{
string
sErrMsg = "Email is not in correct
format";
properties.ErrorMessage
= sErrMsg;
properties.Cancel
= true;
}
}
}
4. When you build and run this solution, as done
previously, you should be directed to
the site that you provided in the solution creation
wizard.
5. Enter a new contact with an improper phone format for
the Business Phone field.
You should see the same error screen as shown previously
including a custom error
message that you coded as shown here:
Adding an Application Page to an Event Receiver
1. If you have closed Visual Studio IDE, launch it as an
administrator.
2. Open the previously created ListItemEventReceiver solution.
3. Right-click on the project and select Add New Item to
add an Application Page
as shown in the following screenshot:
4. Name it EventReceiverErrorPage.aspx
and click Add. This will generate an
.aspx page underneath a folder called Layouts. This is a SharePoint mapped folder
hence the green circular icon next to this folder.
Underneath this mapped folder a
subfolder with the same name as the project (in our case ListItemEventReceiver)
is created and this is where you will find you're newly
created Application Page.
5. Open up the .aspx page and add a label under the
section:
runat="server">
6. Change the ID of the label to "lblErrMsg" and clear out the Text attribute. Your
ASPX mark-up should be as follows:
<%@
Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@
Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@
Register Tagprefix="SharePoint" Namespace="Microsoft.
SharePoint.WebControls"
Assembly="Microsoft.SharePoint,
Version=14.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c
"
%>
<%@
Register Tagprefix="Utilities" Namespace="Microsoft.
SharePoint.Utilities"
Assembly="Microsoft.SharePoint,
Version=14.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c
"
%>
<%@
Register Tagprefix="asp" Namespace="System.Web.UI"
Assembly="System.Web.Extensions,
Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35"
%>
<%@
Import Namespace="Microsoft.SharePoint" %>
<%@
Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0,
Culture=neutral,
PublicKeyToken=71e9bce111e9429c" %>
<%@
Page Language="C#" AutoEventWireup="true"
CodeBehind="EventRe
ceiverErrorPage.aspx.cs"
Inherits="ListItemEventReceiver.Layouts.
ListItemEventReceiver.EventReceiverErrorPage"
DynamicMasterPageFil
e="~masterurl/default.master"
%>
runat="server">
Event
Receiver Error
Event
Receiver Error
7. Right-click anywhere on the ASPX page and select View Code to
open the
EventReceiverErrorPage.apsx.cs
file in order to wire the label
created
previously to the error message. The code inside the Page_Load method should be
as follows:
protected
void Page_Load(object sender, EventArgs e)
{
string
sErrMsg = Request.Params["ErrMsg"];
lblErrMsg.Text
= sErrMsg;
}8. Now we need to wire
this page in our Event Receiver whenever there is an error. To do
that, we will open EventReceiver1.cs file and add the following code after the line
that says properties.Cancel
= true:.
properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
properties.RedirectUrl = string.Format("/_layouts/
ListItemEventReceiver/EventReceiverErrorPage.aspx?ErrMsg={0}",
sErrMsg);
9. Enter a new contact with an improper phone
format for the Business Phone field.
You should see your custom error screen and
custom error message as follows:
How