Customizing Alert Notifications and Alert Templates in Windows SharePoint Services 3.0

Hello. My name is Albert Meerscheidt and I’m one of the Programming Writers on the Windows SharePoint Services SDK team.

In the coming months I will be posting about the content that’s on the publishing horizon. The first topic that I'd like to discuss is how to customize alert notifications and alert templates in Windows SharePoint Services 3.0. The following is a somewhat abridged version of what you will see in the upcoming SDK update.

   Overview

Alerts are an e-mail subscription notification service in Windows SharePoint Services 3.0. Users can create alerts to be notified of changes to list items (item level alert), documents, lists (list level alert), or document libraries. Alerts in Windows SharePoint Services 3.0 are quite flexible; when you create an alert you have options such as when to be notified and what kind of changes will trigger the alert. Alerts can be managed by users and administrators and customized by developers.

After an alert has been created, changes that fit the criteria specified in the alert are recorded in an event log. Alerts are generated by a timer job that reads the event log, formats the alert email using an alert template, and then sends that email out to the user.

Alert templates are stored in Alerttemplates.xml. Alerttemplates.xml defines the format, contents, and properties used to create alert messages from each list type in Windows SharePoint Services 3.0 . Developers can customize alerts by modifying a copy of Alerttemplates.xml and then loading the customized alert templates using the stsadm -o updatealerttemplates command.

Note Do not modify Alerttemplates.xml itself. Doing so may result in loss of functionality when upgrading or installing service packs.

The <filters> element in each template allows you to create custom triggers for events by using Collaborative Application Markup Language (CAML) queries.

The default timer interval can be changed to adjust the latency of 'immediate' alerts.

   Default Timer Interval

Alert emails can be sent immediately or in a daily or weekly summary. Immediate alerts are not actually immediate; they are sent out after a delay determined by the timer interval. This is done for performance reasons.

The default timer interval is 5 minutes. Thus, if this interval has not been changed you could notice a delay of up to 5 minutes (the default timer interval) before an alert message is generated. Changes are recorded as they occur in an event log (discussed later in this article) and then alert messages are rendered from that log when the next timer job runs.

The default timer interval can be determined using the stsadm command.

stsadm -o getproperty -pn job-immediate-alerts -url<url> command.

The timer interval property can be set using stsadm. In this example I set the interval to 3 minutes.

stsadm -o setproperty -pn job-immediate-alerts -url<url> -pv "every 3 minutes"

For more information about STSADM, see https://technet2.microsoft.com/Office/en-us/library/188f006d-aa66-4784-a65b-a31822aa13f71033.mspx?mfr=true.

   Alert templates

Alert templates are stored in the configuration database and are available at the web application level. Alert templates are defined in Alerttemplates.xml.

Windows SharePoint Services 3.0 ships with the following templates:

Table 1. Predefined alert templates

Alert Template Name

Description

SPAlertTemplateType.GenericList

The first alert template in Alerttemplates.xml. GenericList is used unless there is a match to one of other event types.

SPAlertTemplateType.DocumentLibrary

Notification of changes in document libraries

SPAlertTemplateType.Survey

Notification of changes in surveys

SPAlertTemplateType.Links

Notification of changes in links

SPAlertTemplateType.Announcements

Notification of changes in announcements

SPAlertTemplateType.Contacts

Notification of changes in contacts

SPAlertTemplateType.Events

Notification of changes in events

SPAlertTemplateType.Tasks

Notification of changes in tasks

SPAlertTemplateType.DiscussionBoard

Notification of changes in discussion boards

SPAlertTemplateType.PictureLibrary

Notification of changes in picture libraries

SPAlertTemplateType.XMLForm

Notification of changes in XML form

SPAlertTemplateType.DataConnectionLibrary

Notification of changes in data connection libraries

SPAlertTemplateType.AssignedtoNotification

Assigned to task / issue list notifications

 

Alerttemplates.xml is located at: Local_Drive\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\Template\XML directory.

Note Do not modify Alerttemplates.xml itself. Make changes to a working copy.

 

   Alert Template Format

Alert templates have the following format:

<AlertTemplates>

 <AlertTemplate Type="List" Default="True" Name ="Default Template">

 </AlertTemplate>

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

  <EventTypes IsVisible="True"/>

  <Format>

  </Format>

  <Filters>

    <FilterDefinition>

    </FilterDefinition>

  </Filters>

  </AlertTemplate>

</AlertTemplates>

 

Table 2. Alert Template Attributes

Attribute

Description

Name

The name of the template. Searching on the template names provides an easy way to locate a particular template.

Type

The type attribute can be set to List, Item, or Custom.

Default

Default="True" sets the default alert template.

Filters

If IsVisible = "True", then the filter fields are displayed when creating the alert.

Filter Definitions

Define a filter (query).

Format

Formatting of the email is defined in the <Format> element.

Fields

Specify which fields to render in the alert email.

 

   Filters and Filter Definitions Elements

Filters enable you to create new triggers for an event such as 'the priority of a task has changed'. To modify existing filters or create additional filters modify the <FilterDefinition> element of the appropriate template. Define the query element using inside the filter using Collaborative Application Markup Language (CAML). This query will create an alert event if the event date, end date, or location changes.

 

<FilterDefinition>

   <FriendlyName>$Resources:Alerts_4_filter;</FriendlyName>

   <ShortName>$Resources:Alerts_4_filter_shortname;</ShortName>

   <Query>

   <Or>

   <Or>

   <Neq><FieldRef name="EventDate/New"/>

   <FieldRef name="EventDate/Old"/>

   </Neq>

   <Neq>

  <FieldRef name="EndDate/New"/>

   <FieldRef name="EndDate/Old"/>

   </Neq>

   </Or>

   <Neq>

   <FieldRef name="Location/New"/>

   <FieldRef name="Location/Old"/>

  </Neq>

   </Or>

   </Query>

</FilterDefinition>

 

Resource variables listed in AlertTemplates.xml, such as $Resources:Alerts_anything_filter_shortname, can be found in core.resx; located in the Local_Drive\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\Resources directory.

Note The Query element in the Alerts schema contains no Where element.

 

For more information about CAML query schema, see https://msdn2.microsoft.com/en-us/library/ms467521.aspx.

   

   Format Element

Use the format element of an alert template to modify the look of the alert email. You can also customize the formatting of the alert email by using embedded styles.

<Format>

<Digest> - digest format

    <Subject>

    </Subject>

    <Header>

    </Header>

    <HeaderFieldsHeader>

    </HeaderFieldsHeader>

    <HeaderFields>

    </HeaderFields>

    <HeaderFieldsFooter>

    </HeaderFieldsFooter>

    <RowHeader> - each row’s header (row refers to each item level change in the digest notification)

    </RowHeader>

    <RowFields> - each row’s fields

    </RowFields>

    <RowFooter> - each row’s footer

    </RowFooter>

    <Footer>

    </Footer>

</Digest>

<Immediate> - immediate notification format

    <Subject> - email subject

    </Subject>

    <Header>

    </Header>

    <Fields> - the html for the fields. CAML will go over all the fields and render this part of the template. The field itself should be referenced using <GetVar Name=”OldValue#{Field}” /> or <GetVar Name=”NewValue#{Field}” />

    </Fields>

    <Footer>

  </Footer>

</Immediate>

</Format>

 

    Fields Element

Specify the fields to be rendered in the email.

For example you can specify <GetVar Name="NewValue#{Field}"> inside the <Fields> section. More examples can be seen in AlertTemplates.xml.

To exclude some fields from being rendered in the email, you should include them in the <DigestNotificationExcludedFields> and <ImmediateNotificationExcludedFields> section. DigestNotificationExcludedFields and ImmediateNotificationExcludedFields give you the flexibilty to render different fields for immediate alerts and summary (digest) alerts.

 

In addition to these, CAML is supported. For example you can specify <GetVar Name="NewValue#{Field}"> inside the <Fields> section. More examples can be seen in AlertTemplates.xml.

 

To exclude some fields from being rendered in the email, you should include them in the <DigestNotificationExcludedFields> and <ImmediateNotificationExcludedFields> section.

   Properties Element

The properties element allows you to include or exclude fields from the list that would be shown in the email notification. The example below demonstrates how to exclude fields for both the immediate and summary (digest) alerts.

<Properties>

<ImmediateNotificationExcludedFields>ID;Author;Editor;Modified_x0020_By;Created_x0020_By;_UIVersionString;ContentType;TaskGroup;IsCurrent;Attachments;NumComments;</ImmediateNotificationExcludedFields>

            <DigestNotificationExcludedFields>ID;Author;Editor;Modified_x0020_By;Created_x0020_By;_UIVersionString;ContentType;TaskGroup;IsCurrent;Attachments;NumComments;</DigestNotificationExcludedFields>

        </Properties>

   Customizing the Alert Email

Alert UI elements

In addition to the formatting styles defined in the <format> element, alert templates include formatting instructions for user interface elements, such as the Modify my alert settings, Mobile View, and View <list> buttons, which can be modified or removed.

Modify my alert settings button

The following code displays the Modify my alert settings button:

<GetVar Name="MySubsUrl" URLEncodeAsURL="TRUE"/>

            <HTML><![CDATA[">$Resources:Alerts_link_modify;</a></td>

        <td class="toolbarsep">|</td>]]></HTML>

View list URL button

The following code displays the List URL button:

<GetVar Name="ListUrl" URLEncodeAsURL="TRUE" />

                <HTML><![CDATA[">$Resources:Alerts_link_view; ]]></HTML><GetVar Name="ListName" HTMLEncode="TRUE" />

Mobile View button

The following code displays the Mobile View button:

<Switch>

        <Expr><GetVar Name="MobileUrl"/></Expr>

          <Case Value = "NULL"/>

          <Default>

              <HTML><![CDATA[

        <td class="toolbarsep">|</td>

        <td class="toolbarbutton"><a href="]]></HTML><GetVar Name="MobileUrl" />

     <HTML><![CDATA[">$Resources:Alerts_mobile_view;</a></td>]]></HTML>

         </Default>

</Switch>

Steps to Modify Alerts

You can use any XML editing tool to edit the templates.

1. Create a working copy of AlertTemplates.xml.

Note Remember to always modify a copy of Alerttemplates.xml, not Alerttemplates.xml itself.

2. Edit the working copy that you just created.

3. Use the stsadm command to read the changed templates into the database.
STSADM -o updatealerttemplates -url <https://urlname> -filename <your working copy filename>.

4. Restart IIS.

Note It may be necessary to restart SharePoint Timer Services.

Creating your own alert template

If you want, you can create your own template, and then use the stsadm command to load that template. Pattern your template after one of the templates in Alerttemplates.xml.

 

A particular instance of a list can use a specific alert template by setting the SPList.AlertTemplate property with the desired template. Any new alert created for this list through the subnew.aspx or through the object model using SPAlerts.Add(SPList / SPItem, SPEventType, SPAletFrequency) will pick up the alert template defined for the list.

 

To assign a custom alert template to a specific list

1. Create a new custom template with a unique Name attribute in your working copy of AlertTemplates.xml (You can copy paste the entire section with Name SPAlertTemplateType.GenericList, change the name and modify the sections you want to). Modify the template as necessary. After restarting IIS, write object model code to set the list alert template

SPAlertTemplateCollection ats = new SPAlertTemplateCollection((SPWebService)(WebApplication.Parent)); //give appropriate values for WebApplication

list.AlertTemplate = ats[“name from above”];

list.Update();

 

   Event Logs

Rendering of alert emails occurs some time after the change that generated the alert. Data in the EventCache and EventLog tables is used for rendering the alert since the changed item may no longer exist, or exist in the same form, at the time the email is sent.

The event log uses a SQL table called the EventCache to record SQL level events as they occur. Each row in the table corresponds to an event. The events can be read using the WSS object model. In general, the number of rows written to the table is the minimum necessary to capture the semantics of the event. The assumption is that the reader of the event knows how to use the event row to calculate all the implications of a given event. For example, when a folder is deleted, the folder delete event is the only event written to the change log. No events are written for the files and sub-folders that are contained in the folder. The reader of the folder delete event needs to understand that it implies the deletion of the entire contents of the folder.

By default, the change log retains 15 days worth of data. You can configure this using the “web application general settings” page. There is a timer job that runs daily to delete all expired change log entries.

Change Events

Change events are returned as objects in an SPChangeCollection. Each change object is a subclass of the SPChange object. Depending on the type of SPChange object, different properties are available. The change collection is created by calling SPSite.GetChanges(), SPWeb.GetChanges(), SPList.GetChanges(), or SPContentDatabase.GetChanges(). An SPChangeToken object is passed into GetChanges() to specify where in the log to begin reading. An SPChangeToken can be serialized to a string format by calling the ToString() method.

Use the SPList.CurrentChangeToken property to get the current change token for that list object. There is a similar property on the SPSite, SPWeb, and SPContentDatabase objects. In general, the SPChangeToken from one object cannot be used in the GetChanges() method of another object. The only exception is that the SPChangeToken from an SPContentDatabase can be used in any object contained in that content database. There is also an object called an SPChangeTokenCollection which can be used to store multiple change tokens together, that can then be serialized to one single string.

Change Log Event Types

The following is a description of the event types recorded in the change log.

Table 3. Event Types

Event Type

Description

Add

An object was added. For items, files and folders, the TimeLastModified in the log should be the same as the Created datetime of the object.

Modify

An object was modified. For items, files and folders, the TimeLastModified in the log should be the same as the modified date time of the object.

Delete

An object was deleted.

Rename

An object was renamed. This means that the file name portion of the URL was changed.

MoveInto/MoveAway

An object was renamed. This means that the path portion of the URL was changed. The leaf portion may or may not have been changed also.

Restore

An object was restored from the recycle bin or from a backup. This event signals to a sync client change log reader that it needs to re-sync the object and all its children.

Role Add

A role was added at the scope of the object.

Assignment Add

A role assignment was added at the scope of the object.

System Modify

An object was modified without its Modified date time or Modified By property changing. The TimeLastModified in the log should be the time that the update took place, not the Modified date time property.

Member Add

A member is added to a SharePoint group.

Member Delete

A member is deleted from a SharePoint group.

Role Delete

A role was deleted at the scope of the object.

Role Update

A role was updated at the scope of the object.

Assignment Delete

A role assignment was deleted at the scope of the object.

Navigation

The navigation nodes were updated at the scope of the object.

 

Object Types

The following is a list of the object types that may have changes recorded in the change log. Not all event types are possible on all object types.

Table 4. Object Types

Object Type

Description

Item

This object type applies to all objects that exist in a list: list items, files and folders

List

List object type

Web

Web object type

Site

Site object type

File

This object type applies to files that exist outside of a list and don’t have a corresponding item.

Folder

This object type applies to folders that exist outside of a list and don’t have a corresponding item.

Alert

Alert object type

User

User object type

Group

Group object type

ContentType

Content object type

Field

Field object type

SecurityPolicy

A security policy change has been made at the web application level that affects the entire content database. This event was added late in the development cycle, so it and the content database level restore event are logged as a site level event with a SITEID of “00000000-0000-0000-000000000000”

 

   Conclusion

Alerts are quite flexible; when you create an alert you have options such as when to be notified and what kind of changes will trigger the alert. Alerts can be managed by users and administrators and customized by developers.

Alerts are generated by a timer job that reads the event log, formats the alert email using an alert template, and then sends that email out to the user.Developers can customize these alert emails by modifying alert templates. Alert templates are stored in Alerttemplates.xml. Alerttemplates.xml defines the format, contents, and properties used to create alert messages from each list type in wssversion3. The <filters> element in each template allows you to create custom triggers for events by using Collaborative Application Markup Language (CAML) queries. Developers can customize alerts by modifying a copy of Alerttemplates.xml and then loading the customized alert templates using the stsadm -o updatealerttemplates command.

 

In my next post I'll talk about how to use the IAlertNotifyHandler interface to customize alerts.