PANVEGA’s Blog

DotNet Development, SharePoint Customizing, Silverlight, MS Infrastructure and other tips and tricks

How to develope a Custom SP EventReceiver

Posted by PANVEGA on November 5, 2008

In this example I wanna show you how to easy it is to develope a synchron Task für a SP List in Visual Studio. The receiver event fires, when you want to delete e.g. a task from the Tasklist while it is under progress or not complete. That is why we need a synchron Task. Here you cancel the deleting action and throw an error message.

Synchonous event ends with at -ing e.g. ItemDeleting.  Asynchonous event ends with at -ed e.g. ItemDeleted.

Background:

Windows SharePoint Services 3.0 introduces extended support for working with list events. The new event-handling support provides developers an even richer platform for developing custom integration points and building new types of applications on top of Windows SharePoint Services.

Sharepoint 2007 supports various events on Lists. These events can be broadly classified into two categories – Synchronous and Asynchronous. Synchronous events such as “ItemAdding” or “ItemUpdating” occur before the action has taken place.

They occur synchronously, in other words, these are in the singular pipeline of events that must finish in order for the action to take place. This means, you can effectively cancel the occurring event, should you choose to do so.

Asynchronous events on the other hand, such as ItemAdded or ItemUpdated occur after the action has taken place. For instance, you may want to scrub the data after it has been entered, or you may want to email the administrator if a field has been added

Inspecting properties in SPEventReceivers, i.e. the Before (Synchron) Properties and After (Asynchron) Properties , enables you to modify the standard functionality of SharePoint. But how do you access all the propeties.

Note

Make sure to point out that WSS V3 provides significant enhancements over the event support in WSS V2. WSS V2 only supported events on document libraries. Furthermore ,it only supported asynchronous events that were not cancellable.

WSS V3 adds event support so lists and content types are in parity with document libraries. Also note that WSS V3 supports synchronous events that are cancellable as well as asynchronous events that fire after the commitment has already been made to the WSS content database

First of all, you have to install the VSTO extension.

First open Visual Studio. Create a new empty Template –> Add a Class chosse EventReceiver from the list. Give it a name. The Microsoft.SharePoint namespace is already referenced through the template and the string name file, too.

When Visual Studio creates the list definition project, it generates two Microsoft Visual C# source files: ListEventReceiver.cs and ItemEventReceiver.cs. These files contain the implementations of classes that are derived from the SPListEventReceiver and SPItemEventReceiver classes, with overrides of the list and item event-handling methods.

Here we only need the ItemEventReceiver Class. You see your class inherits from the SPItemEventReceiver class.

Uncomment the method ItemDeleting and add the following code.

/// Synchronous before event that occurs before an existing item is completely deleted.
/// A Microsoft.SharePoint.SPItemEventProperties object that represents properties of the event handler.

public override void ItemDeleting(SPItemEventProperties properties)
{
if (Convert.ToInt32(properties.ListItem[“PercentComplete”]) != 1)
{
properties.ErrorMessage = “Sorry task can not deleted since 100% complete!”;
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.Cancel = true;
}

}

Access the Item Column with the Name. You can also access with the GUID or ID if you want. The method triggers a message when the value of the Complete filed is not 100%.

Now deploy the project. The VSTO automatically builds a feature with a Deployment Solution .wsp file. Actually the Visual Studio add the solution to SharePoint and activates the solution. However you can deply it manually.

stsadm -o addsolution -filename EventReceiver.wsp
stsadm -o deploysolution -name EventReceiver.wsp -url http://Server/Site/Subsite
stsadm -o installfeature -filename DeletingEventHandler\Feature.xml
stsadm -o activatefeature -filename DeletingEventHandler\Feature.xml -url http://Server/Site/Subsite

The event switsches to the default Error window and shows your custom ErrorMessage on the screen.

errorscreen

You can now test the list item event receiver by browsing to an instance of the newly created list definition, adding an item to the list, and then attempting to delete the item. Because the ItemDeleting event is being handled and canceled in the event receiver, Windows SharePoint Services cancels the deletion of the item and displays the message from the event receiver.

In the next step, open the Eventreceiver.xml file in your VS project.

<Elements Id=”90c169bf-99f3-40b6-9ec9-836186313183″ xmlns=”http://schemas.microsoft.com/sharepoint/”&gt;
<Receivers ListTemplateOwner=”00bfea71-a83e-497e-9ba0-7a5c597d0107″ ListTemplateId=”107“>
<Receiver>
<Name>ItemDeleted</Name>
<Type>ItemDeleted</Type>
<SequenceNumber>1</SequenceNumber>
<Class>EventReceiver.EventReceiverClassItemEventReceiver</Class>
<Assembly>EventReceiver, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5</Assembly>
</Receiver>
<Receiver>
<Name>ItemDeleting</Name>
<Type>ItemDeleting</Type>

<SequenceNumber>1</SequenceNumber>
<Class>EventReceiver.EventReceiverClassItemEventReceiver</Class>
<Assembly>EventReceiver, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5</Assembly>
</Receiver>
</Receivers>
</Elements>

  • ListTemplateId=”107 is the number of the WSS Task List
  • EventReceiver.EventReceiverClassItemEventReceiver is the fully qualified Name (Namespace.TypName)
  • ListTemplateId=”107 Name and Type describes the apropriate Event
  • The Assembly is deployed in the GAC

http://msdn.microsoft.com/en-us/library/ms431081.aspx

If you want to add an event to a specific list not to all list types you can solve this with the code above. It is pretty easy to create a small application that allows you to associate an event handler with an existing list, library, content type.


private void RegisterForList (string site, string web, string listname,
string assembly, string class) {

SPSite site = new SPSite(site);
SPWeb web = site.OpenWeb(web);
SPList list = web.Lists[listname];

list.EventReceivers.Add (SPEventReceiverType.ItemDeleting, assembly, class);
list.EventReceivers.Add (SPEventReceiverType.ItemDeleted, assembly, class);
}

You have a collection of event receivers developers can manage. The information needed for the registration is the full strong name of the assembly and then the class handling the event.

Information:

Windows SharePoint Services 3.0 extends list event handling in many ways:

  • The scope of events now covers not only document and form libraries but also lists.
  • Events that are triggered by lists can execute managed code when items are added, changed, or deleted.
  • Events at the list level, such as adding or removing fields, can now be handled.
  • Events are fired both before and after an action has occurred, allowing custom validation and potential cancellation of the event.
  • Event handler responses can now be easily communicated back to the user.

An other example:

Here is a sample code that modifies one of the fields in the ItemAdding event. In this example we have a links list, with a custom column called “Tool Tip” (internal name is “Tool_0x0020_Tip”) and we want to set it automatically to the title of the link the user picked:

public override void ItemAdding(SPItemEventProperties properties)

{

string toolTipFieldInternalName = “”;

using (SPWeb web = properties.OpenWeb())

{                toolTipFieldInternalName = web.Lists[properties.ListId].Fields[TOOL_TIP_FIELD_NAME].InternalName;            }

string urlVal = properties.AfterProperties[“URL”].ToString();

SPFieldUrlValue val = new SPFieldUrlValue(urlVal);

string desc = val.Description;

properties.AfterProperties[toolTipFieldInternalName] = desc;        }

Note:

One trap to watch out for is that the keys in the hashtable correspond to the fields’ internal names, so that, for example, any spaces will be encoded as “_x0020_”. To be safe, it pays to use a syntax something like the following:

string myFieldValue = Convert.ToString(properties.AfterProperties[properties.ListItem.Fields[“Field Name”].InternalName]);

More Information:

http://msdn.microsoft.com/en-us/library/ms453149.aspx

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spitemeventreceiver.itemdeleting.aspx

Advertisements

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: