Notification Services

Notification Services is a programming framework used to create applications that generate and send messages to subscribers. Applications created with this framework have a variety of uses. This article, the first of a multi-part series, introduces you to this framework. It is excerpted from chapter 18 of the book Programming SQL Server 2005, written by Bill Hamilton (O'Reilly, 2006; ISBN: 0596004796). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 6
March 08, 2007
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

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.

Creating a Notification Services Application

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:

  1. 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.
  2. 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.
  3. Create a subscription management application that lets users sign up and manage their subscriptions and target devices.
  4. Create a subscription management application using NMO subscription management classes.
  5. Create custom event providers, content formatters, and delivery protocols as required.
  6. 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.

Programming Notification Services

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.


Figure 18-2.  NMO class hierarchy

Creating a Notification Services Application and Service

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:

  1. Create a Visual Studio 2005 C# console application in the C:\PSS2005 directory. Name the projectNotificationServices.
  2. Add the following references to the project:

    • Microsoft.SqlServer.ConnectionInfo
    • Microsoft.SqlServer.NotificationServices
    • Microsoft.SqlServer.Smo
  3. 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;

       private const string baseDirectoryPath = @"C:\PSS2005\NotificationServices";
       private const string nsServer = "NSServerName";
       private const string serviceUserName = "NSUSerName";
       private const string servicePassword = "NSPassword";

       
    static void Main(string[] args)
       {
           Server server = new Server("(local)");

           
    // create a new instance 
           NotificationServices ns = server.NotificationServices;
           nsi = new Instance(ns, "StockWatch");

           
    CreateDeliveryChannel();

          
    // create a new application in the StockWatch instance
           a = new Application(nsi, "StockWatchApp");
           a.BaseDirectoryPath = baseDirectoryPath;

          
    CreateEventClass();
           CreateSubscriptionClass();
           CreateNotificationClass();
           CreateHostedEventProvider();
           CreateGenerator();
           CreateDistributor();
           CreateVacuumSchedule();

          
    a.QuantumDuration = new TimeSpan(0, 0, 15);
           a.PerformanceQueryInterval = new TimeSpan(0, 0, 5);
           a.SubscriptionQuantumLimit = 1;
           a.ChronicleQuantumLimit = 1;
           a.VacuumRetentionAge = new TimeSpan(0, 0, 1);

          
    nsi.Applications.Add(a);

          
    Console.WriteLine("Added application.");

          
    nsi.Create();
           nsi.RegisterLocal(serviceUserName, servicePassword);
           nsi.Enable();

          
    Console.WriteLine("Application enabled." + Environment.NewLine);

          
    CreateSubscriber();
           CreateSubscription();


           Console.WriteLine(Environment.NewLine + "Press any key to continue.");
           Console.ReadKey();
       }

       private static void CreateDeliveryChannel()
       {
           DeliveryChannelArgument dca;
           // add file delivery channel
           DeliveryChannel dcFile =
              
    new DeliveryChannel(nsi, "StockWatchFileDeliveryChannel");
           dcFile.ProtocolName = "File";
           dca = new DeliveryChannelArgument(dcFile, "FileName");
           dca.Value = baseDirectoryPath + @"\Notifications\FileNotifications.txt";
       dcFile.DeliveryChannelArguments.Add(dca);
           nsi.DeliveryChannels.Add(dcFile);
           Console.WriteLine("Added delivery channel: " + dcFile.Name);

          
    // add email delivery channel
           DeliveryChannel dcEmail =
              
    new DeliveryChannel(nsi, "StockWatchEmailDeliveryChannel");
           dcEmail.ProtocolName = "SMTP";
           nsi.DeliveryChannels.Add(dcEmail);
           Console.WriteLine("Added delivery channel: " + dcEmail.Name);
      
    }

      
    private static void CreateEventClass()
       {
           EventClass ec = new EventClass(a, "StockWatchEvents");

          
    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);

           
    a.EventClasses.Add(ec);

          
    Console.WriteLine("Added event class: " + ec.Name);
       }

       
    private static void CreateSubscriptionClass()
       {
           SubscriptionClass sc = new SubscriptionClass(a, "StockWatchSubscriptions");

          
    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";

          
    ser.EventClassName = "StockWatchEvents";

          
    sc.SubscriptionEventRules.Add(ser);

          
    a.SubscriptionClasses.Add(sc);

          
    Console.WriteLine("Added subscription class: " + sc.Name);
       }

       
    private static void CreateNotificationClass() 
       {
           NotificationClass nc = new NotificationClass(a, "StockWatchNotifications");

          
    NotificationField nf;
           nf = new NotificationField(nc, "Symbol");
           nf.Type = "nvarchar(6)";
           nc.NotificationFields.Add(nf);
           nf = new NotificationField(nc, "Price");
           nf.Type = "float";
           nc.NotificationFields.Add(nf);

           
    ContentFormatter cf = new ContentFormatter(nc, "XsltFormatter");

           
    ContentFormatterArgument cfa;
           cfa = new ContentFormatterArgument(cf, "XsltBaseDirectoryPath");
           cfa.Value = a.BaseDirectoryPath + @"\AppDefinition"; 
          cf.ContentFormatterArguments.Add(cfa);
           cfa = new ContentFormatterArgument(cf, "XsltFileName");
           cfa.Value = "StockWatch.xslt"; 
          cf.ContentFormatterArguments.Add(cfa);

          
    nc.ContentFormatter = cf;
           nc.DigestDelivery = true;

          
    ProtocolField pf;

          
    // add file notification class protocol
           NotificationClassProtocol ncpFile =
               new NotificationClassProtocol(nc, "File");

           
    pf = new ProtocolField(ncpFile, "Symbol");
           pf.FieldReference = "Symbol";
           ncpFile.ProtocolFields.Add(pf);
           pf = new ProtocolField(ncpFile, "Price");
           pf.FieldReference = "Price";
           ncpFile.ProtocolFields.Add(pf);

         
    nc.NotificationClassProtocols.Add(ncpFile);

          
    // add email notification class protocol
           NotificationClassProtocol ncpEmail =
               new NotificationClassProtocol(nc, "SMTP");

          
    pf = new ProtocolField(ncpEmail, "Subject");
           pf.SqlExpression = "'Stock watch: ' + CONVERT(nvarchar(30), GETDATE())";
           ncpEmail.ProtocolFields.Add(pf);
           pf = new ProtocolField(ncpEmail, "BodyFormat");
           pf.SqlExpression = "'html'";
           ncpEmail.ProtocolFields.Add(pf);
           pf = new ProtocolField(ncpEmail, "From");
           pf.SqlExpression = 'notification@StockWatchService.com';
           ncpEmail.ProtocolFields.Add(pf);
           pf = new ProtocolField(ncpEmail, "Priority");
           pf.SqlExpression = "'Normal'";
           ncpEmail.ProtocolFields.Add(pf);
           pf = new ProtocolField(ncpEmail, "To");
           pf.SqlExpression = "DeviceAddress";
           ncpEmail.ProtocolFields.Add(pf); 

          
    nc.NotificationClassProtocols.Add(ncpEmail);

          
    nc.ExpirationAge = new TimeSpan(1, 0, 0);

          
    a.NotificationClasses.Add(nc);

          
    Console.WriteLine("Added notification class: " + nc.Name);
       }

      
    private static void CreateHostedEventProvider()
      
    {
           HostedEventProvider hep = new HostedEventProvider(a, "StockWatchHEP");
           hep.ClassName = "FileSystemWatcherProvider";
           hep.SystemName = nsServer;

           
    HostedEventProviderArgument hepa;
           hepa = new HostedEventProviderArgument(hep, "WatchDirectory");
           hepa.Value = baseDirectoryPath + @"\Events"; 
       hep.HostedEventProviderArguments.Add(hepa);
           hepa = new HostedEventProviderArgument(hep, "SchemaFile");
           hepa.Value = baseDirectoryPath + @"\AppDefinition\EventsSchema.xsd"; 
      hep.HostedEventProviderArguments.Add(hepa);
           hepa = new HostedEventProviderArgument(hep, "EventClassName");
           hepa.Value = "StockWatchEvents"; 
      hep.HostedEventProviderArguments.Add(hepa);

          
    a.HostedEventProviders.Add(hep);
       }

      
    private static void CreateGenerator()
      
    {
           // create a new generator for the application
           Generator g = new Generator(a, "StockWatchGenerator");
           g.SystemName = nsServer;
           a.Generator = g;

           Console.WriteLine("Created generator: " + g.Name);
       }

       
    private static void CreateDistributor()
      
    {
           Distributor d = new Distributor(a, "StockWatchDistributor");
           d.SystemName = nsServer;
           d.QuantumDuration = new TimeSpan(0, 0, 15);
           a.Distributors.Add(d);

          
    Console.WriteLine("Added distributor: " + d.Name);
       }

       
    private static void CreateVacuumSchedule() 
       {
           VacuumSchedule vs = new VacuumSchedule(a, "StockWatchVacuumSchedule");
           vs.StartTime = new TimeSpan(0, 0, 0);
           a.VacuumSchedules.Add(vs);

          
    Console.WriteLine("Added vacuum schedule: " + vs.Name);
       }

       
    private static void CreateSubscriber()
       {
           ns.NSInstance swnsi = new ns.NSInstance("StockWatch");

          
    ns.Subscriber s;
           ns.SubscriberDevice sd;

          
    // create a subscriber
           s = new ns.Subscriber(swnsi);
           s.SubscriberId = @"KristinHamilton";
           s.Add();
           Console.WriteLine("Added subscriber: " + s.SubscriberId);

           
    // create a file subscriber device
           sd = new ns.SubscriberDevice();
           sd.Initialize(swnsi);
           sd.DeviceName = "StockWatchSubscriberDevice";
           sd.SubscriberId = "KristinHamilton";
           sd.DeviceTypeName = "File";
           sd.DeviceAddress = KristinH@StockWatch.ns;
           sd.DeliveryChannelName = "StockWatchFileDeliveryChannel";
           sd.Add();
           Console.WriteLine("Added subscriber file device.");

           
    // create a subscriber
           s = new ns.Subscriber(swnsi);
           s.SubscriberId = @"TonyHamilton";
           s.Add();
           Console.WriteLine("Added subscriber: " + s.SubscriberId);

           
    // create an email subscriber device
           sd = new ns.SubscriberDevice();
           sd.Initialize(swnsi);
           sd.DeviceName = "StockWatchSubscriberDevice";
           sd.SubscriberId = "TonyHamilton";
           sd.DeviceTypeName = "Email";
           sd.DeviceAddress = TonyH@StockWatchNS.ns;
           sd.DeliveryChannelName = "StockWatchEmailDeliveryChannel";
           sd.Add();
           Console.WriteLine("Added subscriber email device.");
      
    }

      
    private static void CreateSubscription()
      
    {
           ns.NSInstance swnsi = new ns.NSInstance("StockWatch");
           ns.NSApplication a = new ns.NSApplication(swnsi, "StockWatchApp");

           
    ns.Subscription s;

          
    // add subscriptions
           s = new ns.Subscription();
           s.Initialize(a, "StockWatchSubscriptions");
           s.SetFieldValue("DeviceName", "StockWatchSubscriberDevice");
           s.SetFieldValue("SubscriberLocale", "en-us");
           s.SubscriberId = "KristinHamilton";
           s.SetFieldValue("Symbol", "ABC");
           s.SetFieldValue("Price", "0.00");
           s.Add();
           Console.WriteLine("Added subscription: " + s.SubscriberId);

           
    s = new ns.Subscription();
           s.Initialize(a, "StockWatchSubscriptions");
           s.SetFieldValue("DeviceName", "StockWatchSubscriberDevice");
           s.SetFieldValue("SubscriberLocale", "en-us");
           s.SubscriberId = "TonyHamilton";
           s.SetFieldValue("Symbol", "DEF");
           s.SetFieldValue("Price", "0.00");
           s.Add();
           Console.WriteLine("Added subscription: " + s.SubscriberId);
      
    }
    }
     
  4. 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.
  5. Compile and execute the code. The results are shown in Figure 18-3.


    Figure 18-3.  Results for Notification Services example
  6. 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.
  7. 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
  8. Right-click theStockWatch service and select Start from the context menu to start the service.
  9. Right-click theStockWatch service and select Properties from the context menu to display the Instance Properties dialog box, shown in Figure 18-5.


    Figure 18-5.  StockWatch application instance properties
  10. Select the Windows Services page to display the service status, as shown in Figure 18-6. The service should be running.
  11. 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.
  12. 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
  13. 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.

    Example 18-2. EventSchema.xsd

    <xsd:schema xmlns:xsd="http://www.w3.org/2001/
    XMLSchema"
      xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
      <xsd:element name="event" sql:relation="FlightEvents">

        <xsd:complexType>
         
    <xsd:sequence>
            <xsd:element name="Symbol" type="xsd:string" />
            <xsd:element name="Price" type="xsd:float" />
         
    </xsd:sequence> 
        </xsd:complexType>
      </xsd:element>
    </xsd:schema>
     
  14. 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.

    Example 18-3. StockWatch.xslt

    <fixml version="1.0" encoding="UTF-8" fi>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/ Transform">

        <xsl:template match="notifications">
        <html>
           <body>
               StockWatch Price Update<br/><br/>
               <xsl:apply-template/>
               <br/><br/>
               <i>SQL Server StockWatch Notification Services</i><br/><br/>
       </body>
       </html>
       </xsl:template>

       <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>
     
  15. 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.

    Example 18-4. EventData.xml

    <eventData>
        <event>
            <Symbol>ABC</Symbol>
            <Price>3.83</Price>
        </event>
        <event>
            <Symbol>DEF</Symbol>
            <Price>5.75</Price>
        </event>
        <event>
            <Symbol>GHI</Symbol>
            <Price>1.22</Price>
        </event>
    </eventData>
  16. 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.
  17. 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.

blog comments powered by Disqus
MS SQL SERVER ARTICLES

- Windows Azure Media Services Launched by Mic...
- Windows Server 8 Cloud Backup Beta Released
- Idera Announces SQL Compliance Manager 3.6
- Idera SQL Doctor 3.0 and MS SQL Changes
- Microsoft Cuts Windows Azure Compute and Sto...
- Express5800 to Mesh with SQL Server 2012
- Microsoft Azure Outage
- Windows Azure Server Supported by RealCloud ...
- Idera Releases SQL Diagnostic Manager v7.1
- MS SQL Sever 2012 Launch, New Idera Release
- OpenText Azure Cloud Solution, Geminaire Raa...
- Melissa Data Releases MatchUp Tool for SQL S...
- Glovia`s G2 ERP Solution to Support SQL Serv...
- Upgrade Assistant for SQL Server 2012 Releas...
- Azure Update Features Several New Improvemen...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 7 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials