Capturing and Modifying Sharepoint Alerts Through Alert Handlers

Introduction

SharePoint assists users by providing optional alerts by email/SMS to get notifications of changes in a list/library such as when an item is added, modified, or deleted. These alerts are sent using a pre-defined template. Alert handlers allow developers to do some custom action when an alert is triggered.

Note. Alert handlers are triggered only for email alerts.

Scope

In this article, we will explore how to capture email alerts with an alert handler and modify the Alert Template using a custom class.

Implementation

To create an alert handler we need to create a global assembly that contains a class that implements the "IAlertNotifyHandler" interface in Microsoft.SharePoint assembly. The IAlertNotifyHandler interface contains only one method, "OnNotification" for intercepting the e-mail alert and to modify it.

Procedure

The procedure to do that is

  • Create and Deploy an Alert Notification Handler Assembly
  • Create an Alert Template

Create and Deploy an Alert Notification Handler Assembly

To create an alert notification handler we need to create a public/shared assembly. You can use a Visual Studio Class Library project template or SharePoint Project template. In this example, I am using the SharePoint Project Template to avoid signing and deployment overhead. Let us start.

Step 1. Open Visual Studio 2010 and create a new project. From the New Project window select the "Empty SharePoint Project" template and name it "SampleAlertHandler" and click "OK".

Step 2. In the next window (SharePoint Customization Wizard) give your website URL and select "Deploy as a farm solution" then click the "Finish" button.

Step 3. Add a new class file to the SampleAlertHandler project with the name "CustomAlertHandler". Now open CustomAlertHandler.cs and replace the code with the following snippet:

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace SampleAlertHandler
{
    public class CustomAlertHandler : IAlertNotifyHandler
    {
        public bool OnNotification(SPAlertHandlerParams ahp)
        {
            try
            {
                using (SPSite site = new SPSite(ahp.siteUrl + ahp.webUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists[ahp.a.ListID];
                        string to = ahp.headers["to"].ToString();
                        string subject = list.Title.ToString();
                        string body = string.Empty;
                        var eventType = (SPEventType)ahp.eventData[0].eventType;
                        if (eventType == SPEventType.Add)
                        {
                            body = "An item is added";
                        }
                        else if (eventType == SPEventType.Modify)
                        {
                            body = "An item is modified";
                        }
                        else if (eventType == SPEventType.Delete)
                        {
                            body = "An item is deleted";
                        }
                        SPUtility.SendEmail(web, true, false, to, subject, body);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}

In the code above we are modifying the Alert Template inside the OnNotification method, that is being called prior to sending the alert. The SPAlertHandlerParams (app) contains all the information about the alert. The app. headers include email properties such as from, to, Subject etcetera from which we are fetching the recipient address (to). In this example, we are using the title of the list (from which the alert is triggered) as the subject. To construct the email body we are using app.eventData[0].eventType (SPEventType) property that indicates the type of alert event that occurred. Finally, we are sending an email using the SendEmail method of the "SPUtility" class.

Step 4. Now our alert handler assembly is ready to deploy. Go to the Build menu and click "Deploy Solution". Assuming that the deployment was successful, verify the presence of the SampleAlertHandler assembly in the GAC (C:\Windows\assembly).

Deploy Solution

Note. Take note of the Version and Public Key Token since we require these when creating the Alert Template.

Create an Alert Template

Alert Templates are XML files that define the content and appearance of both e-mail (alerttemplates.xml) and SMS (alerttemplates_sms.xml) alerts. Alert Templates are located in the "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\XML" folder.

In this example, we only deal with an e-mail Alert Template (alerttemplates.xml). If you open the alerttemplates.xml you will see that there are 16 different AlertTemplate elements defined in it for various types of lists. The "Name" attribute of the AlertTemplate specifies the Template type.

Now we can create an Alert Template for our alert handler.

Step 1. Move to the 14 hives "TEMPLATE\XML" folder and make a copy of alerttemplates.xml and name it "custom_alerttemplates.xml".

Note. It is recommended to keep the original templates intact because any future SharePoint updates will overwrite your changes.

Step 2. Open the "custom_alerttemplates.xml" in Visual Studio or any other XML editor and locate the AlertTemplate element that is defined for the DocumentLibrary template type (since we are using the document library to test our notification handler in this example).

<AlertTemplate Type="List" Name="SPAlertTemplateType.DocumentLibrary">

Step 3. Locate the Properties element inside the AlertTemplate tag and add the following two elements to it.

<Properties>
    <NotificationHandlerAssembly>SampleAlertHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a3902394782e8e4e</NotificationHandlerAssembly>
    <NotificationHandlerClassName>SampleAlertHandler.CustomAlertHandler</NotificationHandlerClassName>
    <!-- Other properties -->
</Properties>

Note. The PublicKeyToken must be the same as the one we noted earlier in the GAC

Step 4. Now we can change the default template of our website. Open a command window in the 14 hive "TEMPLATE\XML" folder and run the following command:

stsadm -o updatealerttemplates -filename "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\XML\custom_alerttemplates.xml" -url "your site url"

Step 5. Restart IIS, to do this run the iisreset command in a command window.

Step 6. As a final step, we need to restart the SharePoint 2010 Timer service (since it is what sends the alerts). To do this, run the services.msc command in the command window; that will open the Services Window where the "SharePoint 2010 Timer Service" is located and restart it.

Now the custom alert handler configuration is completed.

References

Summary

In this article, we explored how to create and configure a custom email alert handler for document libraries. To test the notification handler you need to turn on the alerts in a document library as shown in the image below.

Library tool

Note. To debug the notification handler, you need to attach the debugger to the OWSTIMER process.