Building Custom Alert Result Channels in SharePoint Portal Server 2003

 

Patrick Tisseghem
U2U

June 2004

Applies to:
     Microsoft® Office SharePoint® Portal Server 2003

Summary: Understand how .NET developers can extend Microsoft Office SharePoint Portal Server 2003 with custom alert result channels. Learn about offering users extra channels on which to receive alert results. This article works through the Quick Alerts alert result channel as an example. (16 printed pages)

Contents

Introduction
Starting with the DeliveryChannel Class
Subscribing to an Alert
Alerts Web Parts
How Users Get Notified
Creating the Quick Alerts Delivery Channel
Deploying the Custom Channel
Using the Quick Alerts Channel
Customizing the New Alert Page
Conclusion
Additional Resources
About the Author

Introduction

Visitors to Microsoft® Office SharePoint® Portal Server portal or team sites surely are aware of the Alert Me link. You can get notified when content within one of the sites is created, updated, or deleted. To get the alert results, a user must create an alert. Out of the box, Microsoft Office SharePoint Portal Server 2003 is able to notify a user either through the portal site or through an e-mail message.

This article describes how developers using the .NET Framework can extend SharePoint Portal Server 2003 with a custom alert result channel for their users. We will work through the Quick Alerts alert result channel as an example.

Note   The article only applies to SharePoint Portal Server 2003 and not to Microsoft Windows® SharePoint Services.

Users can be notified with an alert, which is a toast, or a small window that pops up when activated from an application running in the alert result area of the taskbar. Microsoft MSN® Messenger is a good example of an application that uses alerts. Using the Microsoft Alerts Version 6.0 SDK for the .NET Framework, you can write code to program MSN Messenger to display your own alerts. Unfortunately, with Microsoft Alerts, you must send the alert result first to the Microsoft Alert Web service before the actual user gets to see the alert result. Many companies will not allow this type of communication for a number of reasons. One reason is that they simply do not let employees use MSN Messenger within their corporate walls. Therefore, because we want to focus on the issues related to SharePoint Portal Server 2003, the example will use a client tool to simulate the Messenger Microsoft Alert.

Note   If you want to use the Microsoft Alerts SDK, you should also explore the Microsoft Alerts Web site to find more details on how to act as an alerts provider for Messenger.

We will cover the basic steps of creating, registering, and using your own alert result channel. Then we will look closer into more advanced functionality with the customization of the alert page.

Starting with the DeliveryChannel Class

Notifications or alerts are delivered to the user by means of a delivery or alert result channel. SharePoint Portal Server 2003 exposes two channels by default, so that visitors can be notified when content within their SharePoint sites is created, modified, or deleted. One channel is the portal site itself, where users in their My Site see a summary of the alerts they have subscribed to by way of a Web Part that available within the private view of their My Site. The second alert result channel is, of course, through e-mail delivery, and is the only channel that is available when running Microsoft Windows SharePoint Services.

You implement both channels by using two classes, PortalChannel and EmailChannel, exposed in the SharePoint Portal Server 2003 object model. The object model is documented in the Microsoft SharePoint Products and Technologies 2003 Software Development Kit (SDK).

You can find these two classes in the Microsoft.SharePoint.Portal assembly (figure 1); both derive from the base DeliveryChannel class.

  • PortalChannel is responsible for dropping alert results in the portal site itself. The alert results are displayed in the private view of the user's My Site.
  • EmailChannel is used to deliver the alert result in e-mail format to the user.

Figure1. Delivery channels and custom QuickAlertsChannel inherit from Microsoft.SharePoint.Portal.Alerts.DeliveryChannel class

As a developer, you can extend SharePoint Portal Server 2003 by creating additional ways of delivering the alert results to the user. Examples of extra custom delivery or alert result channels can be instant messaging, media-specific delivery of the alert results, and RSS-like aggregations.

You start by using the DeliveryChannel base class as the parent class for your own custom delivery channel. We will demonstrate how to derive a QuickAlertsChannel class from the base DeliveryChannel class.

Subscribing to an Alert

The first action the user must take is to register how he or she wants to be notified when certain actions occur within an area, a list, a document library, or other types of content providers within SharePoint portal or team sites. This action is called subscribing to an alert, and the user does it by clicking the Alert Me link.

Behind the scenes, SharePoint Portal Server 2003 consults its MYPORTAL_SERV Microsoft SQL Server™ database to find out what the possible delivery channels are. SharePoint Portal Server redirects the user to the NewAlert.aspx page (figure 2) on which it displays a user interface (UI) block for each registered channel. The inner part of the red rectangle displays the UI blocks rendered for the two default delivery channels in SharePoint Portal Server 2003.

Figure 2. NewAlert.aspx page showing UI for two delivery channels

SharePoint Portal Server 2003 stores your alert in the MYPORTAL_SERV SQL Server database when the user clicks OK. You can verify this by opening the sub_UserSubscription table. The GUID of the user account is linked to the ID of the alert. You can find more details regarding the alerts in the related sub_SubscriptionXXX tables.

Alerts Web Parts

You can create a small Web Part to display the various alerts a user has created within the portal site. Your Web Part can also display all of the registered delivery channels and information regarding the different types of alerts and alert results (figure 3). By default, SharePoint Portal Server 2003 offers different types of alerts, and it is possible to create your own custom alert type. By doing this, you define a new scope or type of event to which users can be alerted.

Figure 3. Web Part displaying subscribed-to alerts, registered delivery channels, and available alert and alert result types

You can use the following lines of code within a Web Part. Creating a Web Part is explained in a number of articles and in the SharePoint Products and Technologies 2003 SDK. For more information, see Additional Resources. Drop the following code into the RenderWebPart() method of your Web Part class.

AlertManager am = new AlertManager(PortalContext.Current);
StringBuilder sb = new StringBuilder();
sb.AppendFormat("<B>Alerts I subscribed to</B><BR>");
foreach(Alert alert in am.GetMyAlerts())
{
   sb.AppendFormat("Alert {0}.<BR>",alert.Name);
}
sb.AppendFormat("<HR><B>Delivery Channels</B><BR>");
foreach(DeliveryChannel dc in am.Configuration.DeliveryChannels)
{
   if(dc.GetSettings().Notification == null)
      sb.AppendFormat("->{0} ({1}) - Notification: n/a<BR>",
            dc.DisplayName,dc.ChannelId);
   else
      sb.AppendFormat("->{0} ({1}) - Notification: n/a<BR>",
            dc.DisplayName,dc.ChannelId,
               dc.GetSettings().Notification.ToString());
}
sb.AppendFormat("<HR><B>Possible Alert Types</B><BR>");         
foreach(AlertType at in am.Configuration.AlertTypes)
{
   sb.AppendFormat("->{0} ({1})<BR>",
         at.TypeDisplayName,at.AlertGroupDisplayName);
}
sb.AppendFormat("<HR><B>Possible Notification Types</B><BR>");
NotificationManager nm = new NotificationManager
         (PortalContext.Current);
foreach(NotificationType nt in
         nm.Configuration.NotificationTypes)
{
   sb.AppendFormat("->{0}<BR>",nt.NotificationTypeId);
}
   output.Write(sb.ToString());

The entry point for any alert-related task is the AlertManager class, which is available in the Microsoft.SharePoint.Portal.Alerts namespace. Use the AlertManager class when you want to retrieve the list of alerts for the user who is currently logged on. The constructor for the AlertManager object needs the current PortalContext. After you have created the object, you can start retrieving all the alerts that the user is currently subscribed to, the list of registered delivery channels, and the possible alert types.

How Users Get Notified

The example in figure 3 shows that the user created an alert for the Events list in the portal site. SharePoint Portal Server 2003 does not immediately notify the user when an action occurs within the list, and the result of the alert is not visible immediately on the My Site of the user. The time of the actual delivery depends on the crawling frequency. After a crawl takes place, the user sees a new entry in the My Alerts Summary Web Part (figure 4).

Figure 4. Alert result on the user's My Site

Creating the Quick Alerts Delivery Channel

Now we can look at how you can create your own custom delivery channel. You will create a third delivery channel called the Quick Alerts channel. Users creating an alert on the portal site will have the option of being notified not only by an e-mail message or an entry in the My Alerts Summary Web Part, but also through a small client application that will display a little toast (alert).

You must create custom delivery channels in a .NET Framework class library. The assembly has to be strongly named and deployed in the global assembly cache. Your .NET Framework class library project needs a reference to the Microsoft.SharePoint.Portal.dll. This assembly contains the base Microsoft.SharePoint.Portal.Alerts.DeliveryChannel class from which you will derive your own class.

public class QuickAlertChannel: DeliveryChannel
{
   public QuickAlertChannel()   {}
}

The alert result channel is identified by two properties you have to override: the internal ChannelID and the DisplayName that will be visible within the SharePoint site itself.

private string channelID  = "QA";
private string displayName = "Quick Alerts";
public override string ChannelId 
{
   get {   return channelID;   }   
}
public override string DisplayName
{
   get {   return displayName; }
}

You have one additional property you can override in the class. You can use the SortKey property to control the order position for the UI block rendered in the NewAlert.aspx page (see figure 2). The following code shows how you can specify to SharePoint Portal Server 2003 that it needs to generate the UI block for your Quick Alerts channel right after the UI blocks for the two default channels.

public override string SortKey
{
   get
   {
      return "ZZZLast";
   }
}

You also need to override three methods of your base class.

  • GetControl() defines what the user is going to see in the alert page. You can add a custom delivery channel without writing a UI at all. (For information about using this method to replace the UI rendered by SharePoint Portal Server 2003 with your own ASP.NET server control, see Additional Resources.)

  • GetSettings() is used for specific settings related to your custom channel. When an alert result is created, SharePoint Portal Server 2003 asks each of the registered delivery channels for any custom settings for its implementation.

  • Send() is used to send the custom alert result. The Send() method brings in three parameters:

    The Microsoft.SharePoint.Portal.Alerts.NotificationSite object, giving you access to the portal site to which alert results are sent.

    Microsoft.SharePoint.Portal.Topology.PortalZone, which is for internal use and is not documented.

    The notification text in XML format, the important parameter, which is simply a string of parameters providing extra channel-specific information.

public override   
      Microsoft.SharePoint.Portal.Alerts.DeliveryChannel.ChannelControl  
      GetControl()
{
      return base.GetControl ();
}
public override DeliveryChannelSettings GetSettings()
{
      return base.GetSettings ();
}
public override void Send(NotificationSite site, 
       Microsoft.SharePoint.Portal.Topology.PortalZone renderLinkZone,
       System.Xml.XmlDocument notification, string parameters)
{
      notification.Save(@"C:\notificationdump.html");
}

As shown in figure 3, a number of alert result types exist by default (AlertResultNotification, AlertNewsLetterNotification, AlertCreationConfirmation, AlertAutoDeactivationNotification). Each of these alert result types is called when needed by SharePoint Portal Server 2003, and is responsible for delivering the alert result data in XML format. XSL is then executed on the data and the formatted alert result is provided to the registered delivery channels.

For testing purposes, you can simply output this XML to a file and review the contents. When you create an alert, SharePoint Portal Server 2003 creates an instance of an AlertCreationConfirmation alert result type. Each of the registered delivery channels gets the formatted XML data and processes that data accordingly. The Portal channel is not doing anything with the incoming data. It delegates the work to the Microsoft.SharePoint.Portal.WebControls.Alerts.SummaryView Web Part displayed on the My Site. The Web Part enumerates over the alert results using the Microsoft.SharePoint.Portal.Alerts.AlertCollection. The Email channel is actually the only one processing the incoming data, creating and sending the e-mail message to the user. The alert result type defines the frequency of delivery. The Email channel can process AlertResultNotification alert result types and AlertNewsLetterNotification alert result types. The former results in an immediate alert, the latter is used for a daily or weekly roll-up mail.

The XML data is very e-mail-oriented because the Email channel is the one that primarily deals with the data. You can, however, customize the XML templates and the XSL that is used for formatting the alert result. The XML files are stored in \Program Files\Common Files\Microsoft Shared\Web Server Extensions\60\Template\LCID\XML, where LCID is the locale ID. The SharePoint Products and Technologies 2003 SDK discusses the different XML and XSL files and their purpose.

The goal of the Quick Alerts channel is to display a toast on the client computer by using a small .NET Framework client application that is available in the alert result area. For this, you can store the alert information in a SQL Server database and have the client application polling this database at intervals. You can do this by using direct access to the database or through a Web service. You can replace the code inside the Send() method with the following snippet to prepare this. The code retrieves the account and the message from the incoming alert result in XML format and the rest of the code is the insertion into a custom database and table.

XmlNode ownerNode = null;
XmlNode messageNode = null;
string owner = string.Empty;
string message = string.Empty;
ownerNode = notification.SelectSingleNode("//A[@id='Owner']");
messageNode = notification.SelectSingleNode("//Headers/Subject");
if((ownerNode!=null)&&(messageNode!=null))
{
owner = ownerNode.InnerText;
message = messageNode.InnerText;
   SqlConnection conn = new SqlConnection
      ("Server=.;Integrated Security=true;Initial Catalog=U2U");
   conn.Open();
   SqlCommand cmd = new SqlCommand
      ("INSERT INTO Alerts (Account,Message) VALUES('" + 
      owner + "','" + message + "')",conn);
   cmd.ExecuteNonQuery();
   conn.Close();
}

Deploying the Custom Channel

You need to register the new Quick Alerts delivery channel before you can use it on the portal site. The Microsoft.SharePoint.Portal.Alerts.DeliveryChannelCollection class provides two methods to register and unregister custom channels.

SharePoint Portal Server 2003 does not provide a tool to accomplish this. You can create a small Windows application (figure 5) or console application with a reference to the Microsoft.SharePoint.Portal.dll and the assembly containing your custom channel.

Figure 5. Windows application to register or unregister a custom channel

You can use late binding techniques to make the tool more generic so that you can simply point to the assembly DLL you want to register.

TopologyManager tm = new TopologyManager(); 
PortalSite ps = tm.PortalSites[new Uri(your portal site url)]; 
PortalContext pc = PortalApplication.GetContext(ps);   
DeliveryChannelCollection.RegisterDeliveryChannel
                (pc, new QuickAlertChannel(),string.Empty);

The RegisterDeliveryChannel method accepts these parameters: the PortalContext, a reference to an object of your custom delivery channel, and possible configuration information provided as a string.

You have to reset your Web server after the execution of the preceding block of code and restart the SharePoint Portal Alert service. The registration of the channel is logged by SharePoint Portal Server 2003. You can find an XXXX-ChannelInstaller.log in the C:\Program Files\SharePoint Portal Server\Logs folder. Following is an excerpt:

0000038F UNK 00000000 00000BB4 Registering DeliveryChannel extension: QA 
Assembly name:CustomNotifications, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d64cb961d296a9a7
class name:CustomNotifications.QuickAlertChannel
configuration:
<BR>       
0000042F UNK 00000000 00000BB4 DeliveryChannel extension: QA registered successfully
Assembly name:CustomNotifications, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d64cb961d296a9a7
class name:CustomNotifications.QuickAlertChannel
configuration:
<BR>                                            

You can unregister channels using the UnregisterDeliveryChannel() method of the DeliveryChannelCollection class.

The result of the registration is directly visible in the custom Web Part available on the home page (figure 6).

Figure 6. New delivery channel registered in SharePoint Portal Server

Using the Quick Alerts Channel

After you have registered the channel successfully, users will see it appear as a third option when they subscribe for a new alert (figure 7). Notice how SharePoint Portal Server 2003, by default, takes care of the UI block, generating a check box for the activation of the delivery option.

Figure 7. Custom delivery option (Quick Alerts check box)

In the previous example, the user has created an alert for the Events list that is available on the portal home page. The addition or modification of an event in this list results in an additional third alert result. The alert is displayed on the user's My Site. We have received an e-mail message and we also have an entry in the custom database (figure 8).

Figure 8. Alert record in the custom database

The user can install the Quick Alerts client application, which installs itself in the alert result area and then monitors this table for any new messages that need to be delivered as a toast to the user (figure 9).

Figure 9. Popping up a message for the alert

Customizing the New Alert Page

You will often need to capture specific information regarding the alert while the user is actually creating the alert itself. You do this in the NewAlert.aspx page.

You have seen previously how the QuickAlertsChannel class that you derived from the DeliveryChannel class overrides a GetChannelControl() method. Until now, you simply returned the DeliveryChannel.ChannelControl reference you got from the base class.

You can, however, create your own ChannelControl class. The ChannelControl class is an ASP.NET server control with some extensions related to the Alerts framework. You can build a fully functional ASP.NET server control and plug it in into the alerts page.

Following is an extract of the class.

Note   Not all of the details that have to do with the state management are included.

[ToolboxData("<{0}:QuickAlertControl runat=server>
         </{0}:QuickAlertControl>")]
public class QuickAlertControl : Microsoft.SharePoint.Portal.Alerts.DeliveryChannel.ChannelControl
{
   bool selected;
   public override bool Selected
   {
      get
      {
         return this.selected;
      }
   }
   public override string ChannelId
   {
      get
      {
         return "QA";
      }
   }
   public override Microsoft.SharePoint.Portal.Alerts.DeliveryChannelSettings Settings
   {
      get
      {
         return null;
      }
      set
      {
      }
   }
   CheckBox cb = null;
   HyperLink hl = null;
   protected override void CreateChildControls()
   {
      this.cb = new CheckBox();
      this.cb.AutoPostBack = true;
      this.Controls.Add(this.cb);
      this.cb.CheckedChanged +=new EventHandler(cb_CheckedChanged);
      this.hl = new HyperLink();
      this.hl.Text = 
                "Download and install our Quick Alert Client Tool!";
       this.hl.href = 
                "http://localhost/downloads/quickalertclient.msi";
       this.Controls.Add(this.hl);
    }
    protected override void RenderContents(HtmlTextWriter writer)
    {
       this.EnsureChildControls();
       writer.RenderBeginTag(HtmlTextWriterTag.P);
       this.cb.RenderControl(writer);
       writer.Write(" Quick Alerts");
       writer.RenderEndTag();
       writer.RenderBeginTag(HtmlTextWriterTag.Ul);
       writer.RenderBeginTag(HtmlTextWriterTag.Li);
       this.hl.RenderControl(writer);
       writer.RenderEndTag();
       writer.RenderEndTag();
    }

   private void cb_CheckedChanged(object sender, EventArgs e)
   {
      this.selected = this.cb.Checked;
   }
}

The control itself inherits from the Microsoft.SharePoint.Portal.Alerts.DeliveryChannel.ChannelControl class, which is not directly visible within the object model. You have to override a number of members when you inherit from this class. The most important method, however, is the RenderContents() which gives you control over what exactly is about to be displayed within the block where your user is able to activate the Quick Alerts delivery channel.

You can see an example of a possible customization in figure 10. The user can activate the alert and also download the small client application that polls the SQL Server database for any alerts it needs to display.

Figure 10. Overriding the UI block generated by SharePoint Portal Server 2003

Conclusion

This article introduced the basic steps for creating your own custom alert result channel using a small Quick Alerts sample. In addition to the two alert results delivered by SharePoint Portal Server 2003 (the My Alerts Summary Web Part on the My Site and the e-mail message), users are notified through a small Messenger-like pop-up window.

Additional Resources

A Developer's Introduction to Web Parts
Building Web Parts for Microsoft SharePoint Products and Technologies (Part I)
Building Web Parts for Microsoft SharePoint Products and Technologies (Part II)
Building Web Parts for Microsoft SharePoint Products and Technologies (Part III)
Creating a System Tray Application
Microsoft SharePoint Portal Server 2003 Administration Guide
Microsoft SharePoint Products and Technologies 2003 Software Development Kit (SDK)

About the Author

Patrick Tisseghem is managing partner at U2U, a .NET-oriented training services company based in Brussels. His main areas of expertise are the .NET Framework and all the products and technologies that relate to the information worker. In this role he is evangelizing SharePoint Portal Server 2003 and Office development for Microsoft in the Benelux.

This article was developed in partnership with A23 Consulting.