Notification Services is a programming framework based on XML and T-SQL. It is used to create applications that generate and send messages to subscribers. Notifications can be sent according to a schedule, or in response to conditions or events. Notifications can be sent using built-in or custom delivery protocols. They can be delivered to messaging systems such as email or cell phones.
Notification Services applications have a variety of uses, including:
Customer applications Notify customers about statuses, service changes, or products that might meet a customer’s criteria
Business applications Monitor line-of-business data, company operations, and business intelligence data
Employee applications Connect employees as part of workflow or keep them updated with timely information
Architecture
Notification Services applications are based on a subscriber/subscription model. Here are some key terms used to describe the entities participating in a Notification Services application:
Subscriber A user or application that requests and receives the notification
Subscription A request for information, delivery mechanism, and destination for requested notifications
Event A piece of information or an occurrence in which the subscriber is interested
Notification A message containing the information requested by the subscriber in the subscription
Figure 18-1 shows the relationship between these entities.
Figure 18-1. Relationship between Notification Services entities
The Notification Services platform stores system data, and it generates and distributes notifications. It comprises the following:
Notification Services engine, which contains the provider host, generator, and distributor
Notification Services database
A Notification Services application is hosted in a Notification Services instance. The application generates and sends messages to the application’s subscribers—users or other applications. The subscriber creates subscriptions to the application. The application monitors and collects events. Notification Services matches subscriptions to events and generates, formats, and sends a notification to the subscriber when an event and subscription match. The application database stores event, subscription, and notification data and metadata about the Notification Services application. The applications in a Notification Services instance can share subscribers and delivery mechanisms, which allows them to be administered as a group.
A subscription management application manages subscriber and subscription information in Notification Services. Subscription management is the process of managing the subscribers, the information they are interested in (subscriptions), and where to send notifications (device information). Subscription management is handled by a Windows or web application that uses subscription management objects supplied in the Notification Services Management Objects (NMO) classes—a collection of classes used to create and administer Notification Services instances and applications programmatically. The subscription management classes are used to write and read subscriber, subscription, and subscriber device data from Notification Services.
To support both Notification Services applications and subscription management applications, Notification Services provides an API that stores and retrieves subscriber and subscription information, collects and stores event data, matches subscriptions and events to generate notifications, formats the event data into messages according to delivery protocol, and sends messages to subscribers. The remainder of this section describes this process in more detail.
An event provider collects event data from various sources and submits this data to a Notification Services application, which uses one or more event providers. Notification Services ships with three standard event providers:
File System Watcher event provider Triggered when an XML file is added to a watched directory. TheClassNamefor this event provider is FileSystemWatcherProvider.
SQL Server event provider Uses a T-SQL query to get information from a database and create Notification Services events based on the result. TheClassNamefor this event provider isSQLProvider.
Analysis Services event provider Uses a static or dynamic multidimensional expression (MDX) query to get information from an Analysis Services cube, and creates Notification Services events based on the results. SQL Services Analysis Services (SSAS) and MDX queries are discussed in Chapter 18. TheClassNamefor this provider isAnalysisServicesProvider.
You can develop a custom event provider if the standard event providers do not meet your needs.
An event provider is either hosted or nonhosted. A hosted event provider runs within Notification Services, either continuously or according to a schedule. Nonhosted event providers run as external applications and submit events on their own schedule.
An event class represents one type of event that can be submitted to a Notification Services application and used to generate notifications. An event class definition includes field names and data types for the event and supporting data. The event class is used to implement the underlying SQL Server database objects for storing the event data and supporting data.
An event chronicle is a supplemental storage tables for event data. An event chronicle is generally used to store most-recent event data to support scheduled subscriptions. This data is updated as it changes and used whenever a scheduled subscription is evaluated. An event chronicle rule contains the T-SQL queries that maintain the event chronicle data in the underlying SQL Server tables.
A subscription class represents one type of subscription to a Notification Services application. The subscription class definition includes both fields for storing subscription data and a notification generation rule that matches events to subscription data. The subscription class is used by SQL Server to implement the underlying database objects for storing the subscription data and supporting data.
Once events are collected by the event provider, the generator processes subscriptions against those events by applying notification generation rules. The generator settings include which computer runs the generator and how many threads the generator can use when it processes application rules.
A notification class represents one type of notification produced by a Notification Services application. The notification class definition includes fields and data types defining the data that is sent to subscribers, information about the content formatter, and information about how the delivery protocols are used to deliver notifications. The notification class is used to implement the underlying SQL Server database objects for storing the notification data and supporting data.
A distributor is run by the Notification Services engine and governs notification formatting and delivery. Every distributor quantum—a configurable interval—the distributor looks for a work item—a group of notifications—to process. If the distributor finds a work item, it calls the content formatter to transform the notification data and send the formatted notifications to the subscriber using the specified delivery protocol.
The content formatter transforms raw notification data into readable messages in each combination of subscriber locale and device. A content formatter is required for each combination of locale and device. The formatted message can contain raw notification data, dynamic formatted data that is calculated at formatting time, and static text specified by the content formatter.
Architecture
A delivery channel represents a delivery endpoint. Formatted notifications are sent to one or more delivery channels. These in turn package the notifications into delivery protocol packets and send them to the services that deliver the notification messages to a subscriber. Notification Services includes the following standard delivery protocols:
Simple Mail Transfer Protocol (SMTP) Creates and routes notification messages for delivery by an SMTP service.
File protocol Creates and routes notifications to a text file; intended for application testing.
You can develop a custom delivery protocol if the standard ones do not meet your requirements.
In addition to standard message-by-message formatting and delivery, Notification Services offers two options: digest delivery, which groups multiple notification messages to a subscriber into a single message, and multicast delivery, which sends a single notification to multiple subscribers.
You can create and configure Notification Services instances and applications by using XML configuration files and SQL Server 2005 Management Studio, or programmatically by using NMO. An application created and configured using XML configuration files can be managed programmatically using NMO. The next section, “Programming Notification Services,” discusses programming using NMO.
You need to perform the following tasks to create and configure a Notification Services application using XML configuration files:
Create and configure the Notification Services instance. You can do this in one of two ways:
Create an instance configuration file (ICF) for the Notification Services instance. An ICF is an XML file that describes a Notification Services instance. The ICF names the instance and contains metadata about the instance, the SQL Server instance that hosts the instance database, delivery protocols, delivery channels, and encryption. The configuration file also lists applications hosted in the instance.
Use NMO to programmatically configure the Notification Services instance.
Create and configure the Notification Services application. This includes the structure of events, subscriptions, and notifications; configuration information for the distributor and generator; and application execution settings. You can create and configure an application in one of two ways:
Create an application definition file (ADF) for the Notification Services application. An ADF is an XML file that contains metadata defining a Notification Services application. An ADF is required for each application hosted in the Notification Services instance.
Use NMO to configure the Notification Services instance programmatically.
Create a subscription management application that lets users sign up and manage their subscriptions and target devices.
Create a subscription management application using NMO subscription management classes.
Create custom event providers, content formatters, and delivery protocols as required.
Deploy the Notification Services application.
For more information about creating and using ICF and ADF files and the schemas for each file type, see Microsoft SQL Server 2005 Books Online.
You can build a Notification Services solution by configuring the Notification Services instance in the IDF file and defining an ADF for the application, as described in the preceding section. Alternatively, you can use NMO classes to configure the instance and define the instance. Programming with NMO classes is the focus of this section.
NMO contains classes that are used to programmatically create and administer Notification Services instances and applications. Figure 18-2 shows the relationship between NMO classes.
The NMO namespaceMicrosoft.SqlServer.Management.Nmocontains classes used to develop Notification Services instances and applications. TheMicrosoft.SqlServer. NotificationServices namespace contains classes and interfaces for developing custom event providers, content formatters, and delivery protocols. It also contains the subscription management interfaces.
The remainder of this chapter describes the NMO classes and provides examples that show how to use them. You need a reference to the following assemblies to compile and run the examples:
Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.NotificationServices
Microsoft.SqlServer.Smo
NotificationServicesis the top-level class in the NMO class hierarchy and represents a Notification Services server.
This section creates a complete Notification Services application that creates file and email notifications based on changes in a stock price. For the purpose of this example, the stock price information is limited to a stock ticker symbol and price. Two subscribers are created—one that is notified by entries in a text file and one that is notified using email. Each of the two users monitors a single stock—ticker symbolsABC andDEF.
This section shows the application that creates theStockWatchNotification Services application and adds two subscribers and a subscription for each. Subsequent sections discuss the different parts of the application in detail.
Follow these steps to create theStockWatch Notification Services application with two subscribers and a subscription for each, start the service, and generate notifications:
Create a Visual Studio 2005 C# console application in the C:\PSS2005 directory. Name the projectNotificationServices.
Add the following references to the project:
Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.NotificationServices
Microsoft.SqlServer.Smo
Replace the code in Program.cs with the code in Example 18-1. This code is explained in detail throughout the rest of this chapter.
Example 18-1. Notification Services example
using System;
using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlServer.Management.Nmo; using ns = Microsoft.SqlServer.NotificationServices; class Program { private static Instance nsi; private static Application a;
EventField ef; ef = new EventField(ec, "Symbol"); ef.Type = "nvarchar(6)"; ec.EventFields.Add(ef); ef = new EventField(ec, "Price"); ef.Type = "float"; ec.EventFields.Add(ef);
SubscriptionField sf; sf = new SubscriptionField(sc, "DeviceName"); sf.Type = "nvarchar(255)"; sc.SubscriptionFields.Add(sf); sf = new SubscriptionField(sc, "SubscriberLocale"); sf.Type = "nvarchar(10)"; sc.SubscriptionFields.Add(sf); sf = new SubscriptionField(sc, "Symbol"); sf.Type = "nvarchar(6)"; sc.SubscriptionFields.Add(sf); sf = new SubscriptionField(sc, "Price"); sf.Type = "float"; sc.SubscriptionFields.Add(sf);
SubscriptionEventRule ser = new SubscriptionEventRule(sc, "StockWatchSubscriptionsEventRule"); ser.Action = @"INSERT INTO StockWatchNotifications (" + "SubscriberId, DeviceName, SubscriberLocale, Symbol, Price) " + "SELECT s.SubscriberId, s.DeviceName, s.SubscriberLocale, " + "e.Symbol, e.Price " + "FROM StockWatchEvents e, StockWatchSubscriptions s " + "WHERE e.Symbol = s.Symbol";
Replace the following string constant values in lines 13 to 15:
NSServerName The server that runs the Notification Services engine components. Use the name of the local computer for this example.
NSUserName The account theNS$StockWatchservice runs under.
NSPassword The password for theNSUserName account.
Compile and execute the code. The results are shown in Figure 18-3.
Figure 18-3. Results for Notification Services example
Two databases are created when the NMO application is run—StockWatchNSMainandStockWatchStockWatchApp. Ensure that the service login account specified in Step 4 has at least theNSRunServicedatabase role membership for both of these databases.
Refresh the Notification Services node in Object Explorer in SQL Server Management Studio to view the new Notification Services service, as shown in Figure 18-4.
Figure 18-4. Results for StockWatch service example
Right-click theStockWatch service and select Start from the context menu to start the service.
Right-click theStockWatch service and select Properties from the context menu to display the Instance Properties dialog box, shown in Figure 18-5.
Select the Windows Services page to display the service status, as shown in Figure 18-6. The service should be running.
Ensure that the SMTP service—a component of Internet Information Services (IIS)—is installed and started. For more information, see Microsoft SQL Server 2005 Books Online.
Create the following three folders in the C:\PSS2005\NotificationServices directory:
AppDefinition The folder containing the XSLT transformation file used to format notifications (StockWatch.xslt in this example) and the schema for the event data (EventSchema.xsd in this example). These two files are discussed in Steps 13 and 14.
Events The folder in which event data is placed as XML files (named EventData.xml in this example).
Notifications The folder in which file notifications are created.
Figure 18-6. StockWatch Windows Services instance properties
Create a file named EventSchema.xsd, as shown in Example 18-2, in the C:\PSS2005\NotificationServices\AppDefinition folder. This file describes the schema of the event data in the EventData.xml file described in Step 15.
Create a file named StockWatch.xslt, as shown in Example 18-3, in the C:\PSS2005\NotificationServices\AppDefinition folder. This file is used to format the notification data for both file and email notifications.
<xsl:template match="notification"> The price of <b><xsl:value-of select="Symbol" /></b>is now <b> $<xsl:value-of select="Price" /></b><br/> </xsl:template> </xsl:stylesheet>
Create a file named EventData.xml, as shown in Example 18-4, in the C:\PSS2005\NotificationServices folder. This XML file contains the event data. In this example, the events for symbolsABCandDEFhave subscriptions and generate notifications. The event for symbolGHI has no subscriptions and does not generate a notification.
Copy the EventData.xml file into the C:\PSS2005\NotificationServices\Events folder to submit events. The File System Watcher event provider reads data from the application, submits the data to the applicationStockWatchApp, and changes the extension of the event datafile to .done once the file is processed. If there is an error processing the file, the extension of the datafile is changed to .err.
After less than a minute, a notification file named FileNotification.txt is created in the C:\PSS2005\NotificationServices\Notifications folder, as shown in Figure 18-7.
Figure 18-7. FileNotification.txt
The email message shown in Figure 18-8 is also generated. It appears in the C:\ Inetpub\mailroot\Queue folder briefly as a file with an .eml extension and is then moved to the C:\Inetpub\mailroot\Badmail folder because the email address is not valid. To deliver the email, change the email address for the userTonyHamiltonin theCreateSubscriber()method of Example 18-1 to a valid email address by changing theDeviceAddressproperty of theSubscriberDeviceobject for that user.
Notice that both the file and email notifications are formatted using the XSLT transformation StockWatch.xslt, discussed in Step 14.
The remainder of this chapter discusses the code that creates theStockWatchservice, subscribers, and subscriptions.
Please check back next week for the continuation of this article.