5.2. Event Handling

WSS v2 offered developers the ability to catch certain user actions in code and react programmatically. These user actions triggered a set of asynchronous events that happened after the user had completed the action. An example is the act of adding a document to a document library. A developer could catch the DocumentAdded event and perform some action. Unfortunately for v2 developers, all of the event handlers were "after-the-fact" handlers. You can't stop a user from performing an action with an event handler. Another limitation of v2 event handlers is that you can only catch events on document and forms libraries.

Fortunately for you, all of this has changed. Now, WSS v3 has a vastly increased number of events developers can take advantage of. These events include "before-the-fact" or synchronous events as well as "after-the-fact" or asynchronous events as illustrated in Figure 5-8. As a developer interested in catching SharePoint events, you are no longer limited to only document libraries and forms libraries. Now you have the ability to catch events on practically every list type that SharePoint offers, as well as at the site level, list, or library level, and at the individual file level. Combine the increase in available functionality of event handlers with Workflow and you'll really have a flexible system.

Figure 5.8. Figure 5-8

5.2.1. Receiving SharePoint Events

To catch SharePoint events at an item level, your classes must inherit from the SPItemEventReceiver base class. From this inheritance, your class will be able to take advantage of the methods shown in the following table.

Public Methods NameDescription
ContextEventItem level event reaction to a SPContext class method call
ItemAddedAsynchronous after event that occurs after a new item has been added to its containing object
ItemAddingSynchronous before event that occurs when a new item is added to its containing object
ItemAttachmentAddedAsynchronous after event that occurs after a user adds an attachment to an item
ItemAttachmentAddingSynchronous before event that occurs when a user adds an attachment to an item
ItemAttachmentDeletedAsynchronous after event that occurs when after a user removes an attachment from an item
ItemAttachmentDeletingSynchronous before event that occurs when a user removes an attachment from an item
ItemCheckedInAsynchronous after event that occurs after an item is checked in
ItemCheckedOutAsynchronous after event that occurs after an item is checked out
ItemCheckingInSynchronous before event that occurs as a file is being checked in
ItemCheckingOutSynchronous before event that occurs after an item is checked out
ItemDeletedAsynchronous after event that occurs after an existing item is completely deleted
ItemDeletingSynchronous before event that occurs before an existing item is completely deleted
ItemFileConvertedAsynchronous after event that occurs after a file has been transformed by the SPFile.Convert method
ItemFileMovedOccurs after a file is moved
ItemFileMovingOccurs when a file is being moved
ItemUncheckedOutSynchronous before event that occurs when an item is being unchecked-out
ItemUncheckingOutSynchronous before event that occurs when an item is being unchecked-out
ItemUpdatedAsynchronous after event that occurs after an existing item is changed, for example, when the user changes data in one or more fields
ItemUpdatingSynchronous before event that occurs when an existing item is changed, for example, when the user changes data in one or more fields
Protected Methods NameDescription
DisableEventFiringPrevents events from being raised (inherited from SPEventReceiverBase)
EnableEventFiringEnables events to be raised (inherited from SPEventReceiverBase)

You can also catch events at the List (SPListEventReceiver), Web (SPWebEventReceiver), Email (SPEmailEventReceiver), and Feature (SPFeatureReceiver) levels.

5.2.2. Write Code to Cancel an Item Deletion

Let's look at a sample event handler to help understand the core concepts behind handling events. Since your previous levels of functionality left you completely unable to prevent an action on a non-document-library list, in this example you'll stop someone from deleting an announcement. While you will be working with the AnnouncementsList type, the following table is a list of available list template types:

List Template TypeTemplate ID
Custom List100
Document Library101
Survey102
Links List103
Announcements List104
Contacts List105
Events List106
Tasks List107
Discussion Board108
Picture Library109

To find these list IDs and the IDs of additional list template types, navigate to the Features directory under the 12TEMPLATE folder on your SharePoint server. Find the folder for the list you are looking for in the Features directory and open the List Templates folder under that. If you were looking for the AnnouncementsList type, you'd navigate to C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12TEMPLATEFEATURESAnnouncementsListListTemplates. Open the XML file in here to find the code represented by Listing 5-4. Pick out the Template ID Type value (Type = 104).

Example 5.4. Listing 5-4
Announcements.xml
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <ListTemplate
        Name="announce"
        Type="104"
        BaseType="0"
        OnQuickLaunch="TRUE"
        SecurityBits="11"
        Sequence="320"
        DisplayName="$Resources:core,announceList;"

Description="$Resources:core,announceList_Desc;"
        Image="/_layouts/images/itann.gif"/>
</Elements>

To create and use your sample event handler, you'll need to do two things. First, you'll need to create the code that will run whenever you catch your desired event. Then you'll need to create a Feature to activate your event handler. Features are described in more depth in Chapter 4, so you won't be focusing on this portion of the task in great detail.

Open Visual Studio and start a new C# Class Library project called EventHandlerExample1. Since event handlers are part of the object model, the first thing you'll need to do is to add a reference to the Microsoft.SharePoint namespace.

  1. Right-click on the References folder and select Add. In the Add Reference dialog, .NET tab, scroll to the bottom and select the Microsoft.SharePoint namespace.

  2. Next, you'll want to rename Class1.cs to CancelAnnouncementDeleteHandler.cs.

You're now ready to begin writing your code.

The CancelAnnouncementDeleteHandler class needs to inherit from the SPItemEventReceiver class to function, so next to the class name put: SPItemEventReceiver. This will give you access to the methods listed in the previous table. You are trying to prevent an item from being deleted, so you will be overriding the ItemDeleting method, as shown in Figure 5-9.

In the ItemDeleting method, you'll cancel the deletion before it happens. Your code should look like Listing 5-5.

Example 5.5. Listing 5-5
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace EventHandlerExample1
{
    class CancelAnnouncementDeleteHandler: SPItemEventReceiver
    {
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            string HandledMessage = ("Announcements can not be deleted from
this list");
            properties.ErrorMessage = HandledMessage;
            properties.Cancel = true;
        }
    }
}

Figure 5.9. Figure 5-9

The next step in getting your event handler to work is to compile your DLL and deploy it to the GAC. Deploying an assembly to the GAC requires a strongly named assembly, so in the Project Properties dialog, click the Signing tab and check the box to sign the assembly, as in Figure 5-10. Be sure to create a new key file if you haven't already. Build the project and deploy it to the GAC by entering the following command into the SDK command prompt, as in Figure 5-11.

gacutil /i "C:Documents and SettingsAdministratorMy DocumentsVisual Studio 2005ProjectsEventHandlerExample1inDebugEventHandlerExample1.dll"

Verify successful deployment by finding your file in the C:Windowsassembly folder. Normally, this GAC deployment would be automated with post-build steps or batch files, but it is presented in manual detail here as a learning exercise.

Figure 5.10. Figure 5-10

Figure 5.11. Figure 5-11

5.2.3. Create a Feature to Enable the Event Handler

The next task is to create and deploy a Feature that activates your event handler.

  1. Back in Visual Studio, add two new XML files to the project. Call the first XML file, Feature.xml, and the second file Elements.xml.

  2. Next, navigate to an existing feature in the C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12TEMPLATEFEATURES folder. You need to create a new folder for your event handler. Create a new folder with the same name as your event handler, as in Figure 5-12.

  3. While you're in the FEATURES directory, here's an example of using one of the Microsoft provided Features for your own Feature.xml and Elements.xml. Navigate into the AnnouncementsList folder and open Feature.xml. Copy the contents of the Announcements Feature.xml file into your own Feature.xml file in Visual Studio. Now navigate down into the AnnouncementsListListTemplate folder and copy the contents of Announcements.xml into your Elements.xml file in Visual Studio. Now it's time to update your Feature.xml and Elements.xml files to match your event handler project.

    Figure 5.12. Figure 5-12
  4. Start with Feature.xml. You'll need a unique Feature Id value, so generate a new GUID with the Create GUID tool on the Visual Studio Tools menu. Next you want to give your Feature a title and description to match its purpose. Finally, set the scope of the Feature to Web. Remove any additional elements such as Version and Hidden. When you're finished, your Feature.xml file should look like Listing 5-6:

    Example 5.6. Listing 5-6
    <?xml version="1.0" encoding="utf-8"?>
    <Feature Id="85DA483B-C3D4-4b5c-8F3A-89331E996305"
        Title="EventHandlerExample1"
        Description="An event handler which will cancel the deletion of an announcements list item and insert a new item announcing that a delete attempt was made"
        Scope="Web"
        xmlns="http://schemas.microsoft.com/sharepoint/">
            <ElementManifests>
                    <ElementManifest Location="Elements.xml"/>
            </ElementManifests>
    </Feature>

  5. With Elements.xml, you need to create a Receivers node in your XML. In Elements.xml, the Receivers node has the following elements and attributes. The ListTemplateID indicates which template type this event handler targets (see the table in the "Write Code to Cancel an Item Deletion" section); in this case, the Announcements List type is 104. The name of the receiver is the name of the project. The type of receiver is the function you've overridden in your DLL. The SequenceNumber is a unique number that identifies this Feature. Microsoft has reserved a significant number of these sequence numbers, but any above 20,000 should be available. The Assembly name is your DLL name, version number, culture, and PublicKeyToken.

  6. To get the PublicKeyToken value, find your DLL in the GAC (C:WindowsAssembly), right-click on it and select Properties. Copy the public key from the properties dialog as illustrated in Figure 5-13. Finally, the class element contains the Namespace.classname of your event handler class.

    Figure 5.13. Figure 5-13

    The Elements.xml file should look like Listing 5-7.

    Example 5.7. Listing 5-7
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
            <Receivers ListTemplateId="104">
                    <Receiver>
                            <Name>EventHandlerExample1</Name>
                            <Type>ItemDeleting</Type>
                            <SequenceNumber>20000</SequenceNumber>
                            <Assembly>
                                    EventHandlerExample1, Version=1.0.0.0,
                                    culture=neutral, PublicKeyToken=db6373fbcacd33ee
                            </Assembly>
    
    <Class>EventHandlerExample1.CancelAnnouncementDeleteHandler</Class>
                            <Data></Data>
                            <Filter></Filter>
                    </Receiver>
            </Receivers>
    </Elements>

  7. Now, it's time to save Feature.xml and Elements.xml and copy them from your project folder to the Features folder you created above.

  8. The next steps are to install and activate the Feature with the stsadm.exe tool and to attempt to delete an announcement. To use stsadm, open a command prompt window and navigate to the bin directory under the 12 folder. First, you need to install the Feature in the site collection. Use the following command:

    C:Program FilesCommon FilesMicrosoft SharedWeb
    server extensions12BINstsadm.exe -o installfeature -filename
    EventHandlerExample1Feature.xml

    The parameters to stsadm to install a new feature are –o installfeature to indicate which action you're performing and –filename (Feature Folder Name Feature.xml) to indicate which feature you're installing.

  9. Once you've installed the Feature, the final step is to activate this Feature. This task can be done from inside the SharePoint UI, but for your purposes stsadm.exe works just as well (since you're already in the command dialog, you'll just activate the Feature from here). Use the following command:

    C:Program FilesCommon FilesMicrosoft SharedWeb
    server extensions12BINstsadm.exe -o activatefeature -filename
    EventHandlerExample1Feature.xml -URL http://localhost

    The parameters to stsadm to activate a new feature are –o activatefeature to indicate which action you're performing, –filename (Feature Folder NameFeature.xml) to indicate which feature you're installing, and -URL url to indicate which Web you're activating for.

    You should have a command window that looks like the one in Figure 5-14.

    Figure 5.14. Figure 5-14

Now go to your site and create an Announcements list and put a few items in it. I've done so with my Sample Announcements list. Select an item and try to delete it. You should get an error message that reads "Announcements can not be deleted from this list" (see Figures 5-15 and 5-16).

Figure 5.15. Figure 5-15

Figure 5.16. Figure 5-16

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.239.231