Notification Services Home Page

 SQL Server Notification Services Books Online

Highlights of Notification Services Books Online

Notification Services overview

Installing Notification Services

Building a sample application

Building Notification Services applications

Deploying and administering applications

Additional Information on the Web

Notification Services Web site

SQL Server home page

Microsoft Product Support Services

MSDN Online

Using Notification Services Books Online

Getting Started with Books Online

Using Notification Services Books Online


Getting Started with Notification Services Books Online

Use this table for quick access to documentation for Microsoft® SQL Server™ Notification Services.

To learn about | See
Notification Services overview, architecture, and user scenarios | Introducing SQL Server Notification Services
Installing or removing Notification Services | Installing Notification Services
Notification Services programming overview | Introducing Notification Services Programming
Building a sample application | Stock Application Walk-Through
Building notification applications | Building Notification Services Applications Programming Reference
Deploying and managing Notification Services applications | Deploying and Administering Notification Services Tools and Utilities Reference
Defining security accounts and permissions | Managing Security
Analyzing performance | Performance Monitoring and Reporting Stored Procedure Reference
Application definition file (ADF) reference | Application Definition File Reference
Configuration file reference | Configuration File Reference
NSControl command reference | NSControl Commands
FAQ, troubleshooting, and event logs | Troubleshooting

This documentation is provided for informational purposes only. Microsoft makes no warranties, either express or implied, in this document. See the link at the bottom of this page for the full copyright notice.


Documentation Conventions

The following conventions are used in Notification Services Books Online to distinguish elements of text.

Convention | Used for
UPPERCASE | Transact-SQL keywords and SQL elements.
Initial Capitals | Paths and file names.
Bold | Database names, table names, column names, stored procedures, command prompt utilities, menus, commands, dialog box options, programming elements, and text that must be typed exactly as shown.
Italic | User-supplied variables, relationships, and phrasings.
Monospace | Code samples, examples, display text, and error messages.


Displaying Information in Notification Services Books Online

To display information in Notification Services Books Online, use these documentation features:

Expand text
The expand text feature, designated by the plus sign (+), is used to provide additional information within a topic. To view the information, click the plus sign, and a new text window appears. To close the window, click the minus sign (-). When you print a topic, the expanded text also prints.
See Also icon
The See Also icon appears at the top of those topics that contain related topics. Click the icon to see the list of related topics.


Using Notification Services Books Online

Notification Services Books Online is the online documentation provided with Notification Services. Notification Services Books Online appears in a window that contains these panes:

Navigation pane
This pane is located on the left and contains the Contents, Index, Search, and Favorites tabs. The topics on the Contents tab are organized hierarchically by task or subject.
Topic pane
This pane is located on the right and displays the selected topic or the default topic.
Toolbar pane
This pane is located below the Notification Services Books Online title bar and contains the navigation and command buttons.

From the Navigation pane you can find information in Notification Services Books Online by:

  • Navigating through the Contents tab.
  • Typing a keyword from the Index tab.
  • Typing a word or phrase and performing a search from the Search tab.

For more information about these navigation options, see Finding a Topic.

Using the Toolbar Buttons

You can find topics in Notification Services Books Online by using these navigational buttons on the toolbar:

Previous
Displays the previous topic listed in the table of contents.
Next
Displays the next topic listed in the table of contents.
Back
Displays the last topic you viewed.
Forward
Displays the next topic in a previously displayed sequence of topics.
Home
Displays the Notification Services Books Online home page.

Note The toolbar in your Help Viewer might not contain all of the following navigational buttons.

Other buttons on the toolbar are:

Hide
Hides the Navigation pane. When the Navigation pane is hidden, click Show to show the Navigation pane. If you close Notification Services Books Online with the Navigation pane hidden, the pane is hidden the next time you open Notification Services Books Online.
Locate
Displays the location of a topic in the Navigation pane.
Font
Changes the font size in the Topic pane.
Print
Prints the selected topic, with the option to print all subtopics.
Options
Changes several options for viewing topics, and provides another way to explore the documentation.
Navigating Notification Services Books Online

Here are some tips for navigating Notification Services Books Online:

  • To return to the Notification Services home page, click Home on the toolbar.
  • Colored, underlined text indicates links to other topics. To link to another topic, including Web pages, click the colored, underlined text.
  • Many topics contain a list of related topics, titled See Also. To jump to a related topic, click the title of the topic you want to view.
  • If you use a particular topic often, you can add it to your Favorites list. For more information, see Finding a Topic.
  • For shortcut menu commands, right-click the Contents tab or the Topic pane. For more information, see Using Accessibility Features in Notification Services Books Online.
Copying and Printing a Help Topic

To copy or print a topic, use these procedures.

To copy a topic

  1. In the Topic pane, right-click the topic you want to copy, and then click Select All.
  2. Right-click again, and then click Copy. This copies the topic to the Clipboard.
  3. Open the document to which you want to copy the topic.
  4. Position your cursor where you want the information to appear.
  5. On the Edit menu, click Paste.

    Note If you want to copy only part of a topic, select the text you want to copy, right-click, and then click Copy.

To print a topic

There are several ways to print a topic:

  • Right-click the Topic pane, and then click Print.
  • Click the Print icon on the toolbar.
  • On the Contents tab in the Navigation pane, right-click the topic or book name, and then click Print.

Notification Services Books Online displays two dialog boxes for printing:

  • If you are using the Contents tab in the Navigation pane, and the Navigation pane is the active pane, Notification Services Books Online displays the Print Topics dialog box. If you are using Microsoft Internet Explorer version 5.5, do not click Print the Selected headings and all subtopics, as the subtopics might not print.
  • In all other cases, Notification Services Books Online displays the Print dialog box. If you are using Internet Explorer version 5.5 or Internet Explorer 5 and you click Print all linked topics on the Options tab, linked topics may not always print.
Using the Shortcut Menu Commands

This table shows the shortcut menu commands you can use to display and customize information.

Command | Description
Right-click in the table of contents, and then click Close All. | Closes all books or folders. This command works only if the Contents tab is displayed.
Right-click, and then click Print. | Prints the topic.

These commands can be accessed using the keyboard. Press SHIFT+F10 to display the shortcut menu, and then click the appropriate shortcut keys. Or, enable MouseKeys, a feature that enables you to move the mouse cursor using the numeric keypad. Use a MouseKey combination to display the shortcut menu, and then click the appropriate shortcut keys. For more information on MouseKeys, see the Microsoft Windows documentation.


Changing the Way Topics Appear

The size and position of the Notification Services Books Online window and the Navigation and Topic panes can be changed easily:

  • To resize the Navigation or Topic pane, point to the divider between the two panes. When the pointer changes to a double-headed arrow, drag the divider right or left.
  • To shrink or enlarge Notification Services Books Online, point to any corner of the Notification Services Books Online window. When the pointer changes to a double-headed arrow, drag the corner.
  • To change the height or width of Notification Services Books Online, point to the top, bottom, left, or right edge of the Notification Services Books Online window. When the pointer changes to a double-headed arrow, drag the edge.
  • To reposition the Notification Services Books Online window on your screen, click the title bar and drag the window to a new position.

    Note When you open Notification Services Books Online, it appears with the size and position settings that were last specified.


Finding a Topic

To find a topic in Notification Services Books Online, use the tabs in the Navigation pane:

  • Click the Contents tab to browse the table of contents, which is an expandable, hierarchical list of topics.
  • Click the Index tab to see a list of index entries, and then type a term that you want to search for or scroll through the list of terms. Topics are often indexed under more than one entry.
  • Click the Search tab and then type the word to locate every occurrence of a word or phrase that may be contained in Notification Services Books Online. For more information, see Using the Search Tab.

    Note The results of a search are displayed in three columns: Title, Location, and Rank. The ranking of topics under the Rank column is not determined by any standard (for example, alphabetical order or most number of hits). Do not use the ranking to determine which topics to view.

  • Click the navigation buttons on the toolbar. For more information, see Using Notification Services Books Online.
Creating and Using the Favorites List

The Favorites list provides a convenient way to access topics that you frequently refer to.

  • To create a list of favorite topics, locate the topic you want to make a favorite topic, click the Favorites tab, and then click Add.
  • To return to a favorite topic, click the Favorites tab, select the topic, and then click Display.
  • If you want to rename a topic, on the Favorites tab, select the topic, and then type a new name in the Current topic box.
  • To remove a favorite topic, on the Favorites tab, select the topic, and then click Remove.
Accessing a Topic Using a URL

You can use a URL to direct someone to a topic in Notification Services Books Online.

To direct someone to a topic in Notification Services Books Online

  1. On the page to which you want to direct someone, in the Navigation pane, right-click the topic, and then click Jump to URL.
  2. Copy the URL that appears in the Current URL box, and then paste it in an e-mail or other document.
  3. Instruct the person receiving the URL on how to paste the URL in the Jump to this URL dialog box.

    The URL can also be pasted in the Address box in Microsoft Internet Explorer. However, this will not bring up Notification Services Books Online; only the topic that you selected will be displayed.


Using the Search Tab

Notification Services Books Online includes a Search tab that allows you to search through every word in Notification Services Books Online to find a match. For example, if you perform a full-text search on the word "index", every topic that contains the word "index" is listed. You can precisely define a search by using wildcard expressions, nested expressions, and Boolean operators. You can request similar word matches, search only the topic titles, or search the results of an earlier search.

All instances of search terms that are found in the topic files can appear highlighted. To specify highlighting, click the Options button, and then click Search Highlight On. If you are viewing a long topic, only the first 500 instances of a search word or phrase are highlighted. This feature works only with Microsoft Internet Explorer 4.0 or later.

Searching for Topics

A search consists of the word or phrase you want to find. You can use wildcard expressions, nested expressions, Boolean operators, similar word matches, a previous results list, or topic titles to further define your search.

The basic rules for formulating queries are:

  • Searches are not case-sensitive, so you can type your search in uppercase or lowercase characters.
  • You can search for any combination of letters (a-z) and numbers (0-9).
  • Punctuation marks such as the period, colon, semicolon, comma, and hyphen are ignored during a search.
  • Group the elements of your search using double quotation marks or parentheses to set apart each element. You cannot search for quotation marks.

If you are searching for a file name with an extension, you should group the entire string in double quotation marks ("filename.ext"). Otherwise, the period breaks the file name into two separate terms. The default operation between terms is AND, which is the logical equivalent to "filename AND ext".

To find information with full-text search

  1. Click the Search tab, and then type the word or phrase you want to find.
  2. Click the arrow button to add Boolean operators to your search.
  3. Click List Topics, select the topic you want, and then click Display.
  4. To sort the topic list, click the Title, Location, or Rank column heading.

    Note The ranking of topics under the Rank column is not determined by any standard (for example, alphabetical order or most hits). Do not use the ranking to determine which topics to view.

Searching for Words or Phrases

You can search for words or phrases and use wildcard expressions. Wildcard expressions allow you to search for one or more characters using a question mark or asterisk. The table describes the results of these different kinds of searches.

Search for | Example | Results
A single word | select | Topics that contain the word "select". (You will also find its grammatical variations, such as "selector" and "selection".)
A phrase | "new operator" or new operator | Topics that contain the literal phrase "new operator" and all its grammatical variations. Without the quotation marks, the query is equivalent to specifying "new AND operator", which will find topics containing both of the individual words, instead of the phrase.
Wildcard expressions | esc* or 80?86 | Topics that contain the terms "ESC", "escape", "escalation", and so on. The asterisk cannot be the only character in the term. Topics that contain the terms "80186", "80286", "80386", and so on. The question mark cannot be the only character in the term.

Select the Match similar words check box at the bottom of the Search tab to include minor grammatical variations for the phrase you search.

Defining Search Terms

The AND, OR, NOT, and NEAR operators enable you to precisely define your search by creating a relationship between search terms. The following table shows how you can use each of these operators. If an operator is not specified, AND is used. For example, the query "spacing border printing" is equivalent to "spacing AND border AND printing".

Search for | Example | Results
Both terms in the same topic. | dib AND palette | Topics containing both the words "dib" and "palette".
Either term in a topic. | raster OR vector | Topics containing either the word "raster" or the word "vector" or both.
The first term without the second term. | ole NOT dde | Topics containing the word "OLE", but not the word "DDE".
Both terms in the same topic, close together. | user NEAR kernel | Topics containing the word "user" within eight words of the word "kernel".

The characters |, &, and ! do not work as Boolean operators (you must use OR, AND, and NOT).

Note You must define a search phrase that begins with AND, OR, NOT, or NEAR with double quotation marks; otherwise, these words are interpreted as operators, and the search cannot be performed. For example, a search for the phrase NOT FOR REPLICATION returns an error message, and a search for the phrase "NOT FOR REPLICATION" succeeds.

Using Nested Expressions When Searching

Nested expressions allow you to create complex searches for information. For example, "control AND ((active OR dde) NEAR window)" finds topics containing the word "control" along with the words "active" and "window" close together, or containing "control" along with the words "dde" and "window" close together.

The basic rules for searching Help topics using nested expressions are:

  • You can use parentheses to nest expressions within a query. The expressions in parentheses are evaluated before the rest of the query.
  • If a query does not contain a nested expression, it is evaluated from left to right. For example: "Control NOT active OR dde" finds topics containing the word "control" without the word "active", or topics containing the word "dde". On the other hand, "control NOT (active OR dde)" finds topics containing the word "control" without either of the words "active" or "dde".
  • You cannot nest expressions more than five levels deep.

To search only the last group of topics from a previous search

This feature enables you to narrow a search that results in too many topics found. You can search through your results list from a previous search by using this option.

  1. On the Search tab, select the Search previous results check box.
  2. Click List Topics, select the topic you want, and then click Display.

If you want to search through all of the files in Notification Services Books Online, this check box must be cleared. If you have previously used this feature, when you click the Search tab, this check box will be selected.

To find words similar to your search term

This feature enables you to include minor grammatical variations for the phrase you search. For example, a search on the word "add" finds "add", "adds", and "added".

  1. Click the Search tab, type the word or phrase you want to find, and then select the Match similar words check box.
  2. Click List Topics, select the topic you want, and then click Display.

This feature locates only variations of the word with common suffixes. For example, a search on the word "add" finds "added", but it does not find "additive".

To search for words in the titles of Notification Services Books Online topics

  1. Click the Search tab, type the word or phrase you want to find, and then select the Search titles only check box.
  2. Click List Topics, select the topic you want, and then click Display.


Using Accessibility Features in Notification Services Books Online

The following topics describe the accessibility features that can be used for navigating Notification Services Books Online.

For more information about accessibility features and services, see the Accessibility page at the Microsoft Accessibility Web site.

Changing the Appearance of the Text

The formatting, font, and color of the text in Notification Services Books Online can be changed.

To change formatting or styles for accessibility

  1. On the Options menu, click Internet Options, and then click Accessibility.
  2. In the Accessibility dialog box, select the options you want, and then click OK.

These changes do not apply to the Navigation pane or toolbar of Notification Services Books Online. This procedure also changes your accessibility settings for Microsoft Internet Explorer.

To change the font size of a topic

  • On the Options menu, click Internet Options, and then click Fonts.

These changes do not apply to the Navigation pane or toolbar of Notification Services Books Online. This procedure also changes your font settings for Internet Explorer.

To change colors in the Topic pane of Notification Services Books Online

  1. In Microsoft Internet Explorer, on the Tools menu, click Internet Options.
  2. On the General tab, click Colors.
  3. In the Colors dialog box, select the options you want, and then click OK.
  4. To apply the new color settings, in the Internet Options dialog box, click OK.

These changes do not apply to the Navigation pane or toolbar of Notification Services Books Online. This procedure also changes your color settings for Internet Explorer.

Using Keyboard Shortcuts

The following tables show the keyboard shortcuts that can be used for navigating Notification Services Books Online.

Notification Services Books Online
To | Press
Close Notification Services Books Online. | ALT+F4
Switch between Notification Services Books Online and other open windows. | ALT+TAB
Display the Options menu. | ALT+O
Change Internet Explorer settings. The Internet Options dialog box contains accessibility settings. To change these settings, click the General tab, and then click Accessibility. | ALT+O, and then press I
Hide or show the Navigation pane. | ALT+O, and then press T
Print a topic. | ALT+O, and then press P
Move back to the previous topic. | ALT+LEFT ARROW, or ALT+O, and then press B
Move forward to the next topic (provided you have just previously viewed it). | ALT+RIGHT ARROW, or ALT+O, and then press F
Turn on or off search highlighting. | ALT+O, and then press O
Switch between the Navigation pane and the Topic pane. | F6
Scroll through the table of contents, displaying each topic as you scroll. | ALT+UP ARROW, or ALT+DOWN ARROW
Scroll through a topic. | UP ARROW and DOWN ARROW, or PAGE UP and PAGE DOWN
Scroll through all the links in a topic or through all the options on a Navigation pane tab. | TAB
Display the Documentation Feedback form. | SHIFT+CTRL+F
Display the See Also topics for a particular topic. | SHIFT+CTRL+S
Contents Tab
To | Press
Display the Contents tab. | ALT+C
Open and close a book or folder. | Numeric keypad PLUS SIGN and MINUS SIGN, or LEFT ARROW and RIGHT ARROW
Select a topic. | DOWN ARROW and UP ARROW
Display the selected topic. | ENTER
Index Tab
To | Press
Display the Index tab. | ALT+N
Type a keyword to search for. | ALT+W, and then type the word
Select a keyword in the list. | UP ARROW and DOWN ARROW
Display the associated topic. | ALT+D
Search Tab
To | Press
Display the Search tab. | ALT+S
Type a keyword to search for. | ALT+W, and then type the word
Start a search. | ALT+L
Select a topic in the results list. | ALT+T, and then UP ARROW and DOWN ARROW
Display the selected topic. | ALT+D
Search for a word or phrase in a topic. | CTRL+F
Search for a keyword in the result list of a prior search. | ALT+U
Search for words similar to the keyword. For example, to find words such as "running" and "runs" for the keyword "run." | ALT+M
Search only through topic titles. | ALT+R
Favorites Tab
To | Press
Display the Favorites tab. | ALT+I
Add the currently displayed topic to the Favorites list. | ALT+A
Select a topic in the Favorites list. | ALT+P, and then UP ARROW and DOWN ARROW
Display the selected topic. | ALT+D
Remove the selected topic from the list. | ALT+R


Accessibility for People with Disabilities

Microsoft is committed to making its products and services easier for everyone to use. This topic provides information about the following features, products, and services that make Microsoft Windows® 2000, Windows XP, and Notification Services more accessible for people with disabilities:

  • Accessibility of Notification Services
  • Features and hints for customizing Windows 2000 or Windows XP
  • Microsoft services for people who are deaf or hard-of-hearing
  • Microsoft software documentation online, or on audiocassette, floppy disk, or CD
  • Third-party utilities that enhance accessibility
  • Other products and services for people with disabilities

    Note The information in this section applies only to users who license Microsoft products in the United States. If you obtained this product outside the United States, your package contains a subsidiary information card listing Microsoft support services telephone numbers and addresses. You can contact your subsidiary to find out whether the types of products and services described in this section are available in your area.

Notification Services Accessibility Features

In addition to Windows and Windows NT accessibility products and services, the following features make Notification Services more accessible for people with disabilities.

The Help Viewer

The Help Viewer for Microsoft HTML Help is the tool through which you read the product documentation. It is equipped with accessibility features, including shortcut keys for navigation and commands. The Help Viewer also uses some of the accessibility features of Microsoft Internet Explorer. For example, it allows you to change the colors of the display on your computer screen. For more information, see Using Notification Services Books Online.

Customizing Windows

There are many ways you can customize Windows operating systems to make your computer more accessible.

Accessibility features have been built into Windows since the introduction of Windows 95. These features are useful for individuals who have difficulty typing or using a mouse, have moderately impaired vision, or who are deaf or hard-of-hearing. The features can be installed during setup, or you can add them later from your Windows installation disks.

For information about installing and using these features, look up "accessibility" in the Windows Help Index.

You also can use Control Panel and other built-in features to adjust the appearance and behavior of Windows to suit varying vision and motor abilities. These include adjusting colors and sizes, sound volume, and the behavior of the mouse and keyboard.

Dvorak keyboard layouts make the most frequently typed characters on a keyboard more accessible if you have difficulty using the standard QWERTY layout. There are three Dvorak layouts: one if you are a two-handed user, one if you type with your left hand only, and one if you type with your right hand only. You do not need to purchase any special equipment to use these features.

The specific features available, and whether they are built-in or must be obtained separately, depend on which operating system you are using.

Microsoft Services for People Who Are Deaf or Hard-of-Hearing

If you are deaf or hard-of-hearing, complete access to Microsoft product and customer services is available through a text telephone (TTY/TDD) service.

Customer Service

You can contact the Microsoft Sales Information Center on a text telephone by dialing (800) 892-5234 between 6:30 A.M. and 5:30 P.M. Pacific time.

Technical Assistance

For technical assistance in the United States, you can contact Microsoft Technical Support on a text telephone at (425) 635-4948 between 6:00 A.M. and 6:00 P.M. Pacific time, Monday through Friday, excluding holidays. In Canada, dial (905) 568-9641 between 8:00 A.M. and 8:00 P.M. eastern time, Monday through Friday, excluding holidays. Microsoft support services are subject to the prices, terms, and conditions in place at the time the service is used.

Microsoft Documentation in Alternative Formats

In addition to the standard forms of documentation, many Microsoft products are available in other formats to make them more accessible.

If you have difficulty reading or handling printed documentation, you can obtain many Microsoft publications from Recording for the Blind & Dyslexic, Inc. RFB&D distributes these documents to registered, eligible members of their distribution service, either on audio cassettes or on floppy disks. The RFB&D collection contains more than 80,000 titles, including Microsoft product documentation and books from Microsoft Press®. You can download many of these books from the Microsoft Accessibility page at the Microsoft Accessibility Web site.

For more information, contact Recording for the Blind & Dyslexic at the following address or phone numbers:

Recording for the Blind & Dyslexic, Inc.
20 Roszel Road
Princeton, NJ 08540 		Phone:
Fax:
Web: 		(609) 452-0606
(609) 987-8116
http://www.rfbd.org/
Utilities to Enhance Accessibility

A wide variety of hardware and software products are available to make personal computers easier to use for people with disabilities. Among the different types of products available for the Windows operating systems are:

  • Programs that enlarge or alter the color of information on the screen for people with visual impairments
  • Programs that describe information on the screen in Braille or synthesized speech for people who are blind or have difficulty reading
  • Hardware and software utilities that modify the behavior of the mouse and keyboard
  • Programs that enable people to "type" by using a mouse or their voice
  • Word or phrase prediction software that allow users to type more quickly and with fewer keystrokes
  • Alternative input devices, such as single switch or puff-and-sip devices, for people who cannot use a mouse or a keyboard
Getting More Accessibility Information

In addition to the features and resources already described in this section, other products, services, and resources for people with disabilities are available from Microsoft and other organizations.

Microsoft

Microsoft provides a catalog of accessibility aids that can be used with the Windows operating system. You can obtain this catalog from our Web site or by phone:

Microsoft Sales Information Center
One Microsoft Way
Redmond, WA 98052-6393 		Web:
Voice telephone:
Text telephone: 		Microsoft Accessibility Web site
(800) 426-9400
(800) 892-5234
Trace R&D Center

The Trace R&D Center at the University of Wisconsin-Madison publishes a database of more than 18,000 products and other information for people with disabilities. The database is available on their site on the World Wide Web. The Trace R&D Center also publishes a book, titled Trace ResourceBook, which provides descriptions and photographs of about 2,000 products.

To obtain these materials, contact:

Trace R&D Center University of Wisconsin-Madison
5901 Research Park Boulevard
Madison, WI 53719-1252 		Web:
Fax: 		http://trace.wisc.edu/
(608) 262-8848


Additional Notification Services Resources

This table provides Internet resources for information about Notification Services and related products and technologies.

Resource | Address
Notification Services Web site | http://www.microsoft.com/sql/NS/
Microsoft Product Support Services | http://support.microsoft.com/directory
Microsoft newsgroups | news://news.microsoft.com/
Microsoft Windows Hardware Compatibility List | http://www.microsoft.com/hcl
Microsoft MSDN® | http://msdn.microsoft.com
Professional Association for SQL Server | http://www.sqlpass.org/
Microsoft SQL Server Developer Center | http://msdn.microsoft.com/sql/
SQL Server Magazine | http://www.sqlmag.com/
Microsoft SQL Server Support | http://support.microsoft.com/support/sql
TechNet site | http://www.microsoft.com/technet/
Microsoft SQL Server | http://www.microsoft.com/sql
XML Web Services | http://www.msdn.microsoft.com/xml/default.asp


Microsoft SQL Server Notification Services Copyright and Disclaimer

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

© 1988-2002 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, Active Directory, MSDN, SQL Server, Visual Basic, Visual C++, Visual C#, Visual Studio, and Win32 are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.


Introducing SQL Server Notification Services

Microsoft® SQL Server™ Notification Services is a platform for developing and deploying applications that generate and send notifications to users. Notifications are personalized, timely messages that can be sent to a wide variety of devices.

Notifications reflect the preferences of the subscriber. The subscriber enters a subscription to express an interest in information. For example, "notify me when the stock price of ADCP reaches $70.00," or "notify me when the strategy document my team is writing is updated."

A notification can be generated and sent to the user as soon as a triggering event occurs. Or, a notification can be generated and sent on a predetermined schedule specified by the user. The user's subscription specifies when the notification should be generated and sent to the user.

Notifications can be sent to a wide variety of devices. For example, a notification can be sent to a user's cellular phone, personal digital assistant (PDA), Microsoft Windows Messenger, or e-mail account. Because these devices often accompany the user, notifications are ideal for sending high-priority information.

Notification applications are valuable for many reasons, such as the following:

  • Notification applications enable you to send critical information to customers, partners, and employees. The notifications can contain links that enable the recipient to browse to a Web site to retrieve more information or to acknowledge receipt of the information.
  • Notification applications allow you to forge more valuable and longer lasting relationships with your customers by providing more tailored and timely services to them.
  • Notification applications allow you to increase revenue by making it easier for customers to initiate business transactions with you.
  • Notification applications allow you to make you employees more effective by providing them with the information they need, whenever and wherever they need it.
  • Notification applications allow you to empower mobile users over a wide variety of devices.

Notification Services makes it possible to build and deploy a notification application quickly, and to scale the application to support millions of users. Notification Services consists of:

  • A simple yet powerful Notification Services programming framework that enables you to quickly create and deploy notification applications. The programming framework is based on XML and Transact-SQL.
  • A reliable, high-performance, scalable engine that runs notification applications. The engine is built on the Microsoft .NET Framework and Microsoft SQL Server 2000.

The topics that this section covers are described in the following table.

Topic | Description
Business Scenarios | Provides Notification Services application scenarios that illustrate how you can use Notification Services.
What Is Notification Services? | Explains what Notification Services is, how it operates, and what benefits it provides.
Notification Services Architecture | Describes the architecture behind collecting events and subscriptions, generating notifications, and formatting and distributing those notifications.
Notification Services Programming Framework | Provides an overview of the application development process.
Deployment Architecture | Explains how Notification Services applications are deployed and administered.
Security, Reliability, Scalability, and Availability | Explains how Notification Services provides security, reliability, scalability, and availability for notification applications.
Integrating Notification Services | Describes how Notification Services can integrate with other technologies.


Business Scenarios

Notification Services can be used for a wide variety of applications. The following scenarios provide examples of how you can use notification applications.

Consumer Applications

You can use Notification Services to send notifications to customers:

  • A brokerage firm can send stock and fund prices based on customer-defined criteria. The notification can contain a link that enables the customer to buy or sell shares.
  • A financial institution can send bank account balances and overdraft notifications.
  • An airline can send information about flight arrivals and delayed departures.
  • A real estate agent can send listings that match a client's criteria for a new home.
Line of Business Applications

You can use Notification Services to monitor business data:

  • A customer requires immediate attention, as reported by your customer relations management (CRM) system. The text of the customer request is sent to the account manager.
Operational Applications

You can use Notification Services to send notifications about company operations:

  • When a machine on an assembly line needs attention, the assembly line manager receives a notification about which machine is down and what the error is.
  • When a production server's event log receives a critical error, the on-call support technician receives a notification that contains the error message.
Business Intelligence Applications

You can use Notification Services to track critical company data:

  • A database maintains the current inventory of all products. When the inventory of network cards in the South East region goes below 50, an application receives a notification. That notification tells the application to send an order for more network cards.
Employee Communication

You can use Notification Services to ensure employees are informed about their projects:

  • You and a coworker are creating a critical proposal. When the proposal is updated, you receive a notification.
  • You are working on a new product and need to keep informed of product-related research. When a new report is available from the corporate library, you receive an e-mail that contains a link to the report.

See Also

Deployment Architecture

Notification Services Architecture

Notification Services Programming Framework

What Is Notification Services?


What Is Notification Services?

Notification Services is a programming framework for creating applications that generate and send notifications, as well as a platform for hosting those applications. Using the programming framework, you can quickly create applications to generate and send notifications to subscribers. After creating the application, you can deploy the application on the Notification Services platform.

The topics that this section covers are described in the following table.

Topic | Description
What Does Notification Services Do? | Explains, at a high level, how Notification Services uses events and subscriptions to create notifications.
How Does Notification Services Work? | Explains how Notification Services obtains events and subscriptions, generates notifications, and distributes those notifications.
Why Use Notification Services? | Explains the benefits of using Notification Services instead of other notification solutions.


What Does Notification Services Do?

A notification application generates and sends messages to users who have subscribed to the application. To understand notification applications, it is important to define key terms:

  • A subscriber is a person or application that receives notifications.
  • A subscription is an expressed request for specific information, such as a stock price or the scores of a sports team, and the destination for notifications.
  • An event is a piece of information that subscribers are interested in. A stock price at a specific time is an event, as is a sports score, or a product delivery message. Almost any real-world occurrence can be expressed as a Notification Services event.
  • A notification is a message that contains information related to a subscription. A notification might contain a message about a new high value for a specific stock or the final score for a game.

The following illustration shows the basic operation of a Notification Services application.

The application produces notifications as follows:

  1. Subscribers create subscriptions related to the application.
  2. The application collects events.
  3. Notification Services, using Transact-SQL queries, matches subscriptions to events.
  4. When an event and subscription match, Notification Services generates a notification.
  5. Notification Services then formats the notification and sends it to a delivery service.

A good example of a notification application is a stock application. A subscriber could create a subscription to be notified about stock ADCP if the stock price goes above 70, and to receive the notification on a cell phone. The application collects stock data from a stock ticker. Each time a batch of stock prices arrives, Notification Services compares subscriptions to the current set of events. If stock ADCP goes above 70, Notification Services creates a notification, formats it, and sends it to a delivery service that forwards the notification to the subscriber's cell phone.

See Also

How Does Notification Services Work?

Notification Services Architecture

Why Use Notification Services?


How Does Notification Services Work?

A Notification Services application collects events and subscriptions, generates notifications, and then distributes the notifications to external delivery services, such as a Simple Mail Transfer Protocol (SMTP) server. Notification Services accomplishes these tasks as follows:

  1. Notification Services stores subscriber and subscription data in SQL Server databases. Using the subscription management objects, part of the Notification Services API, you can create a custom subscription management application to manage subscriber and subscription data.
  2. Using event providers, Notification Services collects event data and stores the event data in the application's database. For example, the file system watcher event provider monitors a directory for XML event data. Using this event provider, you can drop XML event files in the directory, and the event provider reads the XML events and submits them to the application database.

    Event providers can be run by the event provider host component, or can run independently of Notification Services. For more information, see Event Collection Architecture.

  3. The generator matches subscriptions and events and generates notifications. The generator runs on a regular interval defined for the application, ensuring that subscriptions are evaluated on a regular basis. The application developer writes Transact-SQL queries that determine how subscriptions are evaluated and what information goes into the notifications.
  4. The distributor formats notifications and sends them to subscribers using one or more delivery services. The application developer specifies the transformation from raw data to a formatted notification using a content formatter such as XSLT.

The following illustration shows how Notification Services implements this architecture.

The Notification Services platform uses the NS$instance_name service to run notification applications. This service, the primary component of the Notification Services engine, runs the three internal functions: the event provider, the generator, and the distributor.

See Also

Deployment Architecture

Notification Services Architecture

Why Use Notification Services?


Why Use Notification Services?

Notification Services allows you to develop and deploy a notification application easily and quickly by building on and customizing the Notification Services programming framework. This framework provides a wide range of services for your application, including the following:

  • Support for both event-triggered and scheduled subscriptions. Scheduled subscriptions work for all time zones supported by Microsoft Windows and they automatically handle daylight saving time transitions.
  • Integration with the Microsoft Visual Studio® .NET development environment to make application development easier.
  • Standard event providers that make it easy to submit events to the system.
  • Standard delivery protocols that make it easy to send notifications.
  • Automatic management of the flow of events and notifications through applications.
  • Automatic management of obsolete data, such as expired events and old notifications data. You specify a schedule and Notification Services removes the data.
  • Automatic logging of delivery attempts and retry of delivery failures.
  • Custom formatting of notifications in multiple languages and for multiple devices.
  • Integration with the Microsoft Windows Performance tool.
  • Automatic logging of errors and warnings in the application event log.
Performance and Scalability

Notification Services applications perform extremely well even if your application must support thousands or millions of subscribers because of a set-oriented processing model.

In all applications that send notifications, the basic requirement is to evaluate subscriptions at the right times, either when an event related to the subscription is available, or according to a schedule.

In either case, this requirement can be met for small applications by simply defining each subscription as its own query and running the queries as appropriate. However, for large numbers of subscriptions, running thousands or millions of individual queries does not scale well.

Notification Services avoids this problem by relying on the fact that subscriptions typically share a common structure. Thousands of users might want to know the result of a sporting event. Millions of users might want to get stock price notifications. Because such subscriptions share a common structure, the subscription queries can be parameterized. For example, instead of writing individual queries such as "SELECT Price FROM StockData WHERE StockName=ADCP AND StockValue > 50" for each subscription, you can write a parameterized query such as "SELECT Price FROM StockData WHERE StockName=@StockName AND StockValue=@StockValue". In essence, there are just a few subscription templates, and individual subscribers are simply filling out parameters to customize the template.

The impact of this design is significant. Rather than treating subscriptions as individual queries, Notification Services treats them as parameter data, making evaluation of large numbers of subscriptions a set-oriented data processing problem well suited for database engines. This set-oriented processing is the foundation of the Notification Services programming framework.

In this set-oriented model, subscriptions are evaluated by simply executing a database join between the new events that have arrived and the large set of subscriptions. Notification Services can implement the following broad categories of subscriptions:

  • Simple event-triggered subscriptions that are evaluated as soon as events are available
  • Subscriptions that are evaluated according to their own schedules
  • Subscriptions that use past and present events
  • Subscriptions based on application state
  • Subscriptions that use external databases

Using the set-oriented Notification Services model, application developers can quickly create a robust and scalable notification application. Application development is easy and performance gains are large.

See Also

How Does Notification Services Work?

Notification Services Architecture


Notification Services Architecture

The Notification Services platform provides an interface for collecting subscriber and subscription data, and contains components that collect events and generate, format, and distribute notifications. In addition to the built-in components, Notification Services enables you to create custom components for collecting events and formatting notifications.

This section provides information about what these components are and how they work.

The topics that this section covers are described in the following table.

Topic | Description
Subscription Management Architecture | Describes how subscriptions are submitted to databases and used by Notification Services applications.
Event Collection Architecture | Describes how event providers collect events.
Subscription Processing Architecture | Describes how the notification generator uses events and subscriptions to create notifications.
Notification Formatting and Delivery Architecture | Describes how the notification distributor formats and delivers notifications.


Subscription Management Architecture

To send notifications, a Notification Services application must have information about subscribers, the information that the subscribers are interested in, and information about where to send the information. Subscription management is the process of managing this subscriber, subscription, and subscriber device data.

Subscription management is handled by a custom subscription management application written by an application developer. This application, which can be a Web application or standard Microsoft Windows application, writes the subscriber, subscription, and subscriber device data to the proper databases. The developer uses subscription management objects supplied with Notification Services to simplify the application development process.

The following illustration shows how the subscription management objects are used by a subscription management application to communicate with Notification Services.

Notification Services stores the subscriber and subscriber device data in a central Notification Services database and it stores subscription data in application-specific databases. This storage method allows applications to share the global subscriber data while separately storing subscriptions for each application.

When a Notification Services application is running, the application uses the subscription data to generate notifications and then uses the subscriber data to format and distribute the notification. Subscription and subscriber data is key to Notification Services operation.

See Also

Developing Subscription Management Applications

Event Collection Architecture

Notification Formatting and Delivery Architecture

Subscription Processing Architecture


Event Collection Architecture

Event collection is the process of obtaining event data from one or more sources such as XML files, applications, or databases, and making this information available to a notification application. In Notification Services, event collection is the job of event providers.

Each application uses one or more event providers for gathering events. Each event provider submits data to the application using one of the four event APIs: a managed API, a COM API that uses the managed API, an XML API, and a SQL Server API. A high-level view of how these providers function is shown in the following illustration.

  • The managed API uses the Event and EventCollector objects to submit single events. Using the names of the fields in an event table, an application submits an Event object to the event collector, which then writes the data to the event table.

    The COM API uses COM interop to expose the event classes as COM interfaces.

  • The XML API provides a way to bulk-load XML data. The XML event provider collects an XML document or stream from an event source and submits the data to the XMLLoader, which then writes the events to the event table.
  • The SQL Server API uses stored procedures to load event data from database objects. Two typical ways of using the SQL Server event provider are to invoke the provider using a stored procedure and to run a query according to a schedule. The event provider receives a result set and writes it to the event table using the API stored procedures.
Standard and Custom Event Providers

Application developers can write their own custom event providers using any of the APIs listed above, or they can use one of the standard event providers supplied with Notification Services, such as the Scheduled SQL or file system watcher event providers.

Custom event providers allow the application developer to provide functionality not available from one of the standard event providers. For example, the developer might want to collect data from a comma-delimited file from a stock ticker. Using the Notification Services API, the developer can create an event provider with this functionality. For more information about custom event providers, see Developing a Custom Event Provider.

Hosted and Independent Event Providers

An event provider is either hosted or independent.

Hosted event providers run within Notification Services. Hosted event providers can either run continuously or be invoked according to a schedule defined in the application definition file (ADF). These event providers are run by a Notification Services component called the event provider host. The event provider host runs using the same schedule as the generator component; the schedule is defined in the ADF.

Independent event providers run as external applications and submit events on their own schedule. For example, an event provider hosted by Internet Information Services (IIS) that exposes a Web method for submitting events is an independent event provider. An event provider that is hosted inside a process you write is also an independent event provider.

Batching of Events

Event providers write events in batches. Writing events in batches allows the generator to more efficiently process event data by comparing subscriptions with multiple (maybe thousands) of events at one time. This batch-oriented processing improves application performance.

When the provider commits the event batch, the generator processes the batch. For more information about batching, see Batching in the Notification Services System.

See Also

Notification Formatting and Delivery Architecture

Subscription Management Architecture

Subscription Processing Architecture


Subscription Processing Architecture

After events are collected in an event table, subscriptions can be processed. Evaluating subscriptions against events is the job of the generator.

To generate notifications, the application developer creates one or more rules for the application. These rules are written as Transact-SQL queries that specify how events and subscriptions relate, as well as any other conditions that must be met to generate a notification.

In a simple application, when the generator fires a rule, the application evaluates all available subscriptions against the current batch of events. When a single event matches a single subscription, the notification generator creates a notification. This notification contains data about the event; it also references data about the subscriber, the subscriber device, and other information required for distribution.

The notification is not actually sent at the instant it is created. Instead, the generator writes the notification to an internal notification table. When a batch of notifications is ready, the notifications are formatted and distributed by the distributor.

Notification generation can be more complex than immediately matching an event to a subscription. Notifications can be generated according to a subscription-defined schedule and can use historical data.

If an application supports scheduled subscriptions, when the generator processes the scheduled subscriptions, it sees only subscriptions that are due for evaluation. For example, if the generator runs every 15 minutes, at 8:00 A.M. the generator evaluates all subscriptions that are scheduled between 7:45 A.M. and 8:00 A.M.

If an application uses historical data, the application can store data in a supplemental table called a chronicle. Applying rules written for the application, the application uses data in these tables to store events or generate notifications.

Rule Types

The operation of the generator is controlled by the Transact-SQL rules defined for the application. You can create the following types of rules:

  • Event chronicle rules store or update the history of events in chronicle tables defined by the application developer. Each time the generator runs, it fires this type of rule first.
  • Subscription event rules generate notifications for event-triggered subscriptions. This type of rule runs after the event chronicle rule if an associated batch of events is available. This type of rule can also manage chronicle tables.
  • Subscription scheduled rules generate notifications for scheduled subscriptions. This type of rule runs after the event chronicle rule for any related subscriptions that are due to be processed. This type of rule can also manage chronicle tables.
Quanta

The generator runs according to a schedule defined by the quantum time period in the application definition file (ADF). The quantum determines how often the generator wakes up and fires rules. The quantum period can be as short as a few seconds or as long as you want it to be. A short quantum period causes the generator to run more frequently and consume more system resources. A long quantum interval causes a longer delay between the arrival of events and the generation of notifications.

See Also

Defining the <QuantumDuration> Element

Event Collection Architecture

Notification Formatting and Delivery Architecture

Subscription Management Architecture

Subscription Rules


Notification Formatting and Delivery Architecture

The formatting and distribution of notifications is the job of the distributor. After the generator creates a batch of notifications, the distributor reads the subscriber data in each notification to determine what formatting is required. The distributor then formats the notification and sends it using a delivery channel to a delivery service, such as a Simple Mail Transfer Protocol (SMTP) server.

Message Formatting

Part of creating an application is defining how raw notification data is transformed into readable messages. Using a formatting method such as XSLT, the application developer creates a content formatter for every combination of device and locale. For example, an application that supports the English and French locales and Systems Management Server (SMS) and SMTP devices requires four separate content formatters.

The distributor reads each notification to obtain the subscriber delivery device and locale. The distributor then matches the combination of device and locale to a specific content formatter to generate the formatted message.

The formatted message can contain a combination of the raw notification data, data that is computed at formatting time, and text specified by the content formatter. These options allow for professional and user-friendly notification text and the inclusion of Web links.

Delivery Channels

Notification Services itself does not handle the final delivery of notifications. Instead, Notification Services uses delivery channels, which are like pipes to delivery services such as SMTP servers. Notification Services sends the notifications to one or more delivery channels, which package the notifications into a protocol packet and then send them to the delivery services. The delivery services handle the final delivery on their own.

Notification Services includes the following common protocols, which support a standard set of delivery channels for notification applications. Multiple delivery channels can be configured for each of these protocols:

  • The SMTP protocol for sending notifications to Microsoft Exchange Server or other SMTP servers.
  • The extensible HTTP protocol, which can be used for SOAP, SMS, .NET Alerts, and other HTTP-related protocols.
  • The file protocol for sending notifications to operating system files; used primarily for debugging applications.

The application developer can define additional protocols. For more information about standard and custom protocols, see Standard Delivery Protocols and Developing a Custom Delivery Protocol.

To support delivery retry, performance monitoring, and troubleshooting, Notification Services retains information about the delivery of notifications in the notification table. Delivery channels invoke a delivery channel callback to report delivery successes and failures for individual notifications. The callback updates the notification table to reflect the success or failure of each notification.

You can configure Notification Services to automatically retry failed delivery attempts, how often retry is attempted, and how long to retry delivery before marking a notification as failed.

Delivery Options

In addition to standard message-by-message formatting and delivery, Notification Services offers two options: digest delivery, which groups multiple notifications to an individual subscriber in a single message; and multicast delivery, which sends a single notification to multiple subscribers. For example:

  • If multiple notifications are likely to be sent to individual subscribers, such as price information for multiple stocks, the developer can group notifications using digest delivery. All of the subscriber's notifications within a notification batch can be grouped and sent as a single notification. Digest delivery reduces the formatting and distribution load on the system.
  • If an application produces notifications that are likely to be the same for many subscribers, such as stock prices or weather reports, the developer can choose multicast delivery. This method allows notifications to be formatted once and then sent to multiple subscribers, which improves performance by reducing the formatting load on the system.

See Also

Event Collection Architecture

Subscription Management Architecture

Subscription Processing Architecture


Notification Services Programming Framework

The Notification Services programming framework facilitates quick application development. The primary task for application development is to create the application definition file (ADF). Depending on your application, there might be some additional tasks.

Developing a notification application using the standard components typically requires the following steps:

  1. Define the application in the ADF. This file contains information about events, event providers, subscriptions, notifications, and application settings. Using this file, you define the structure of data, queries used to process data, how notifications are formatted and delivered, and operational parameters for your application.

    There can be a few additional tasks, depending on the entries in the ADF. For example, if you use the file system watcher event provider, you must create an XML Schema definition language (XSD) file that defines the XML event schema. If you choose to format notifications using XSLTs, you must create one or more XSLT files that convert the notification data into a readable message.

  2. Create a subscription management application using the Notification Services API. The Notification Services API provides a number of classes (for managed code) and interfaces (for unmanaged code) to simplify the collection and submission of subscriber and subscription data.

When you are ready to test or deploy the application, do the following:

  1. Configure an instance of Notification Services by creating a configuration file. An instance is a named configuration of Notification Services that hosts one or more applications. The configuration file defines the name of the instance, names the applications hosted by the instance, and configures databases, protocols, and delivery channels for the instance.
  2. Use the NSControl Create command to create the instance and then use NSControl Register to register it. NSControl Create creates the instance and application databases. NSControl Register registers the instance of Notification Services, and optionally creates the NS$instance_name service that runs the Notification Services engine and the performance counters used to monitor the instance.
  3. Activate the subscription management application.

If you use Microsoft Visual Studio® .NET for application development, you can use it to create the ADF, subscription management application, and configuration file. Also, NSControl commands can be run from Visual Studio .NET using batch files.

See Also

Building Notification Services Applications

NSControl Commands

Walkthrough: Creating a Stock Notification Application


Deployment Architecture

A Notification Services system consists of Notification Services, notification applications, databases, and subscription management applications. When you deploy applications, you configure where these items are located and how they operate.

The topics that this section covers are described in the following table.

Topic | Description
System Architecture | Describes the components of a Notification Services system.
Instances and Versions | Describes instances, how they are used by applications, and how system scale-out is accomplished through instance configuration. Also describes how to use multiple versions of Notification Services.
Application Deployment | Describes how applications are deployed using instances.
Administration | Outlines the system administration tasks.


System Architecture

When you deploy a Notification Services application, you must configure and support more than Notification Services. You must also consider the data storage system, the subscription collection and management system, and the delivery systems that are involved.

The SQL Server database engine provides storage for instance and application data. Because the databases are critical to notification applications, the configuration of the database system is a key to application performance. For information about configuring the database engine, see Database Considerations and Defining the Instance Database.

The system where subscription management applications run, such as Internet Information Services (IIS), is also part of the notification application. For information about configuring the subscription management system, see Database Considerations.

The associated delivery systems, such as Simple Mail Transfer Protocol (SMTP) servers, receive notifications from Notification Services and send the notifications to subscribers. For information about configuring delivery options, see Defining Delivery Channels.

A high-level view of the relationships among these components is shown in the following illustration.

See Also

Administration

Application Deployment

Instances and Versions


Instances and Versions

Instances and versions are two important factors when deploying a Notification Services system. Depending on application requirements and optimal configurations, you might run multiple instances and multiple versions on a single system, or you might deploy an instance across multiple servers.

Instances

Notification Services is based on instances. An instance is a single, named configuration of Notification Services that hosts a set of applications. The applications hosted by an instance use the same configuration and can be administered as a group. Instances also provide the following benefits:

  • Each instance has its own registry entries and service, allowing one instance to run separately from other instances.
  • All applications hosted by an instance share the same set of subscriber data. (This can influence which applications you want to group under a single instance.)
  • Instances can be scaled across multiple servers, providing flexible configuration and allowing higher data throughput.

When an administrator deploys Notification Services, a configuration file specifies the name of the instance plus its database system, database settings, applications, protocols, and delivery channels. The administrator then creates the instance using the NSControl administration utility.

Instance deployment scenarios

An instance of Notification Services can be deployed on a single server or on multiple servers. A single-server deployment hosts all processes — event provider host, generator, and distributor — on one server, as shown in the following illustration.

In the single-server scenario, the event provider host, generator, and distributor processes are all hosted by a single server. The event provider collects data, the generator processes subscriptions, and the distributor formats notifications and distributes them to the delivery services.

The administrator configures this system by creating the instance and registering the instance on that server.

A variation of this model uses a remote database server, such as the one shown in the following illustration.

When an instance must be scaled out to support larger applications, the event provider host, generator, and distributor processes can be located on multiple servers. The following illustration shows one sample scale-out configuration.

This system uses three servers to host the Notification Services instance. Server NS1 hosts the event provider and generator processes, while servers NS2 and NS3 host the distributor process, which formats the notifications and distributes them to the delivery services.

The administrator configures this system by creating the instance, registering the instance on each server, and then enabling only the components (event provider host, generator, or distributor) that run on that server.

Version Support

You can install multiple versions of Notification Services on a single system. This arrangement allows multiple instances to each run a different version of Notification Services if required. It also allows a single instance to be easily upgraded or downgraded.

The following illustration shows two instances running different versions of Notification Services on one server.

Instance NS$Inst1 is running version 2.0, and instance NS$Inst2 is running version 2.1. Both are using the same database system and the same set of delivery services.

See Also

Administration

Application Deployment

Configuring and Deploying Instances

System Architecture


Application Deployment

Notification Services applications are deployed using instances. Deploying an application requires you to have all the files that support the instance, such as the application definition file (ADF) and any custom objects. You must also specify application information in the instance configuration file. When you create the instance, the hosted applications are deployed with the instance.

Deployment Tasks

An administrator creates an instance by first creating a configuration file and then using a command prompt utility called NSControl to create and register the instance. The configuration file contains the following information:

  • Instance settings, such as the instance name and the database server name
  • Instance database properties that configure files and filegroups
  • A list of applications hosted by the instance
  • Protocols supported by the instance
  • Delivery channel instances for delivering formatted notifications to delivery services
Sample Deployment

The following illustration shows a set of applications deployed on two instances of Notification Services.

In this configuration, the Stock and Weather instances are on a Notification Services server and all databases are on a database server. The applications are configured as follows:

  • The Funds and Index applications are hosted by the Stock instance. Both applications use the configuration data in the StockNSMain instance database. The Funds application database is StockFunds, and the Index application database is StockIndex.
  • The Europe application is hosted by the Weather instance. The instance database is WeatherNSMain, and the application database is WeatherEurope.

Deploying the applications in this way allows the Funds and Index applications to share subscriber data and delivery configuration with each other, but allows the Weather application to have its own set of subscribers and its own delivery configuration. The two instances also can use different versions of Notification Services.

See Also

Administration

Instances and Versions

System Architecture


Administration

The system administrator is responsible for deploying Notification Services applications. Ensuring that applications operate optimally requires careful planning and installation, configuration, management, and monitoring.

Planning and installation is the process of defining what infrastructure is necessary for applications, planning the system architecture, and then installing system components on each server. For more information, see Installing Notification Services.

Configuration is the process of creating Notification Services instances. Configuration requires version management and careful planning so that system maintenance and upgrades cause minimal service interruptions. Configuration typically consists of the following tasks:

  • Creating a configuration file.
  • Using the NSControl Create command to create the instance and NSControl Register to register it.
  • Loading subscription data or deploying a subscription application.
  • Enabling the instance of Notification Services.
  • Starting the NS$instance_name service or services that run the instance.

For more information, see Configuring and Deploying Instances.

Administration is similar to the administration of SQL Server databases. The following list contains typical management tasks:

  • Data backup. The data maintained by the notification application is critical and needs regular backup. SQL Server supports a number of backup/restore facilities and tools, which you can configure using SQL Server Enterprise Manager.
  • Data vacuuming. Because notification applications collect event data and generate notification data, this data accumulates in the database and must be periodically removed. This process, which is called "vacuuming," is configured per application in the application definition file (ADF).
  • Reacting to problems. Infrequently, an application might exhibit a problem related to a bad event feed, a subscriber that is not valid, or a failing delivery channel. To react to these situations, the Notification Services platform provides control commands to disable specific components of the system or specific subscribers. Once the problems have been identified and solved, the components or subscribers can be enabled again.
  • Instance updates. Infrequently, notification applications must be updated to reflect new functionality created by the application developer. Notification Services provides NSControl Update to update a deployed instance with new application logic, without losing the existing subscription data.

Monitoring is extremely important for proper system operation. When an application is in production, the system administrator must monitor the application to ensure that Notification Services is receiving events and also generating and distributing notifications. Additionally, it is very important to make sure the delivery service is delivering the notifications.

The following objects are available to assist with monitoring:

  • Performance counters
  • Status and historical reports
  • Event log messages

For more information, see Performance Monitoring and Reporting.

See Also

Administering Notification Services

Application Deployment

Instances and Versions

System Architecture


Security, Reliability, Scalability, and Availability

An enterprise system must be secure, reliable, scalable, and available. Notification Services addresses these requirements in the programming framework and in the architecture of the server running Notification Services.

Security

Notification Services, the Microsoft .NET Framework, and SQL Server incorporate design features that allow application developers and administrators to enforce end-to-end security for the applications and the overall deployment:

  • Notification Services uses industry-standard Web security models to communicate across the Internet using wired and wireless devices. It uses standard Microsoft Windows security mechanisms and SQL Server 2000–based security mechanisms to protect the server.
  • Individual Notification Services instances are isolated from each other using SQL Server 2000–based security mechanisms. This ensures that multiple instances can be hosted on the same computers while safeguarding the security of each individual instance.
  • Individual subscribers are isolated from each other because of the programming paradigm that notification applications support. As a result, each subscription is processed as though it were the only subscription in the system.
  • Application developers can extend Notification Services by defining their own event providers. These are run as managed code supported by the .NET Framework, thereby ensuring that they do not compromise the security of the server.
Reliability

SQL Server 2000 has a highly reliable database engine that stores data and processes subscriptions. Notification Services, by using managed code for custom components, ensures that custom components do not compromise the stability of the system. Notification Services benefits in the following ways:

  • The subscription data managed by Notification Services is stored in SQL Server 2000, a highly robust database server that supports write-ahead logging and failover clustering.
  • The processing of events, subscriptions, and notifications in Notification Services is fully transactional, thereby providing additional reliability guarantees. Note that some delivery protocols (for example, Simple Mail Transfer Protocol or SMTP) do not provide guaranteed delivery of messages; however, the Notification Services platform has retry logic that enables an application to resend messages to attempt delivery again.
  • Application developers can build reliable event providers and reliable delivery protocols, for example, based on Message Queuing (also known as MSMQ), thereby achieving complete end-to-end reliability.
Scalability

Notification Services supports high-throughput applications with thousands of incoming events per minute, millions of subscriptions matched, and thousands of notifications delivered per minute on a multiprocessor Windows–based server. Applications can scale in several ways:

  • Subscription logic can be run in parallel, benefiting from scale-up efficiencies in the underlying SQL Server database engine.
  • Notification Services is multithreaded and scales up when run on a multiprocessor computer.
  • The Notification Services service can be deployed on one server and the Notification Services database can be deployed on another server. This configuration is very efficient because notification generation is performed on the database server while notification formatting is performed on the Notification Services server.
  • A single instance can support multiple event providers and multiple distributors. You can distribute the event providers, generator, and distributors across two or more servers. The ability to scale out the distributors is important in deployments where there are large notification volumes with significant formatting and delivery overheads.
  • For further scale-out, you can partition subscriptions across multiple Notification Services instances, each of which operates independently. Because the application model makes the subscriptions independent of each other, such partitioning is natural, which makes notification applications highly scalable. You must implement subscription partitioning in your application. Notification Services does not currently partition subscriptions for you automatically.
Availability

In an instance of Notification Services, all data and state is maintained in the SQL Server database server. Only transient data is maintained in the event provider, generator, and distributor. This is a critical aspect of the design, because it makes system availability solely dependent on the availability of the database server.

SQL Server is a reliable database server with a variety of high-availability technologies, including SQL Server 2000 failover clustering, log shipping, and transactional replication. The database server can be configured to handle hardware failures seamlessly.

See Also

Notification Services Architecture

Why Use Notification Services?


Integration with Other Technologies

Notification Services applications can capture events from multiple sources and send notifications to users and applications.

Notification Services provides several mechanisms for capturing events from external processes and applications. Notification Services includes a set of standard event providers that can capture data from common event sources such as XML files or SQL tables. Developers can write custom event providers using managed APIs, unmanaged APIs, and SQL Server stored procedure APIs to capture events from other event sources.

Notification Services can send notifications using several delivery protocols. Common protocols like Simple Mail Transfer Protocol (SMTP) and a file protocol are included with Notification Services. The product also contains a configurable HTTP protocol, which can be customized to implement a variety of HTTP and SOAP-based delivery protocols.

Use with Other Microsoft Technologies

Notification Services integrates with other key Microsoft technologies to gather notification content and deliver notifications to subscribers. The following examples illustrate how Notification Services can integrate with these other technologies.

.NET Alerts

Notification Services and Microsoft .NET Alerts are complementary technologies. After Notification Services generates notifications, the .NET Alerts Web service can deliver the notifications to subscribers using a variety of devices, such as e-mail, Microsoft Windows Messenger, and mobile phones.

Message Queuing and BizTalk

Messages from a queue can be events to a notification application, and notifications can be sent to Message Queuing queues (also known as MSMQ queues) or to Microsoft BizTalk® through custom delivery channels.

See Also

Developing a Custom Delivery Protocol

Notification Services Architecture


Installing Notification Services

Microsoft® SQL Server™ Notification Services can be installed on one server or many servers. Depending on your system configuration, you must install Notification Services on one or more of the following servers:

  • Any server that hosts a Notification Services instance.
  • The server that hosts the databases used by the instance.
  • Any server that hosts an independent event provider.
  • Any server that hosts a subscription management application.

This section provides information about installing and removing Notification Services, instructions for installing or removing one or more components, and documentation for the Setup pages.

The topics that this section covers are described in the following table.

Topic | Description
Editions of Notification Services | Explains the differences between Notification Services Enterprise Edition and Standard Edition.
Preparing to Install Notification Services | Provides hardware and software requirements, information about multiple version support, installation permissions, and file information.
Installing Components | Describes the process of installing Notification Services and related components.
Running Setup from the Command Line | Explains how to create and use an install script.
Reinstalling Notification Services | Provides instructions for repairing or reinstalling a version of Notification Services.
Removing Notification Services | Provides instructions for removing a version of Notification Services.
Setup Pages | Documents the Setup pages.


Editions of Notification Services

Notification Services is available in two editions: Standard Edition and Enterprise Edition. Standard Edition runs with SQL Server Standard Edition, and Enterprise Edition runs with SQL Server Enterprise Edition.

Notification Services Standard Edition is intended for small to medium applications that run on one server. Some options, including the number of generator threads, distributor threads, notifications per batch, and delivery choices, are limited in Standard Edition.

Notification Services Enterprise Edition is intended for medium to large applications. Instances of Notification Services that run on Enterprise Edition can be scaled across multiple servers. With Enterprise Edition, you can customize the number of generator and distributor threads as well as the size of notification batches. It also supports multicast delivery.

The following table shows the differences between the two editions.

Feature | Standard Edition Support | Enterprise Version Support
Scale-out | Not supported | Supported
Generator threads per instance | 1 | Up to 25
Distributor threads per instance | Up to 3 | Unlimited
Notification batch size | Fixed sizes | Can be adjusted
Multicast delivery | Not supported | Supported

See Also

Hardware Configurations

<MulticastDelivery> Element

<NotificationBatchSize> Element

<ThreadPoolSize> Element (<Distributor>)

<ThreadPoolSize> Element (<Generator>)


Preparing to Install Notification Services

Before you install Notification Services components, you must ensure that the servers meet all hardware and software requirements. When you install components of Notification Services, the account used to perform the installation must have adequate privileges.

This section includes information about hardware and software requirements and the permissions required for installation. It also includes information about the files that are to be installed and how Notification Services supports multiple versions of these files on a single server.

The topics that this section covers are described in the following table.

Topic | Description
Hardware and Software Requirements | Provides hardware requirements for the engine components and software requirements for the engine components, database components, documentation, and samples.
Permissions Required for Installation | Documents the permissions required to install Notification Services components.
Files and File Locations | Lists the files that will be installed and the locations where they are installed.
Multiple Version Support | Explains how multiple version support for Notification Services works.


Hardware and Software Requirements

The minimum hardware and software requirements for installing and running Notification Services are listed in the following tables.

Hardware Requirements

This table shows hardware requirements for installing the Notification Services engine components. For database system hardware requirements, see "Hardware and Software Requirements for Installing SQL Server 2000" in SQL Server Books Online.

Hardware | Requirement
Computer | Pentium 450 megahertz (MHz) minimum; Pentium 733 MHz or higher recommended.
Memory (RAM) | 128 megabytes (MB) minimum; 256 MB or more recommended.
Hard disk space | Notification Services components: 10 MB. If the databases are on the same server as Notification Services, additional disk space is required for your database tables, log files, and temporary database tables.
Software Requirements

Notification Services consists of engine components, client components, database components, samples, and documentation. Each of these components can be installed by itself, or components can be installed together. Some components have software prerequisites; that software must be installed before you can install the component.

The following sections describe the software prerequisites for the Notification Services components.

Notification Services Engine Components

This table shows the software that must be installed before installing the engine components.

Software | Requirement
Operating System | Microsoft Windows® 2000 SP2 (or higher) or Windows XP Professional.
Microsoft Data Access Components (MDAC) | MDAC version 2.6 or higher, required to install the Microsoft .NET Framework; also required by Microsoft SQLXML.
SQL Server 2000 Client Tools | SQL Server 2000 client tools, required by SQLXML.
Microsoft SQLXML | SQLXML version 3.0 or higher. Note Microsoft recommends SQLXML 3.0 SP1 or higher.
Microsoft .NET Framework | Microsoft .NET Framework version 1.0.3705 or higher.

You can find some of the Notification Services prerequisite software at the Microsoft Download Center Web page. Select the name of the prerequisite from the product list, select your operating system, and then click Find It. SQLXML is also available at the SQL Server Downloads Web page.

Install the SQL Server client tools from SQL Server 2000 Setup.

Client Components

The following table shows the software that must be installed before installing the client components.

Software | Requirement
Operating system | Windows 2000 SP2 or Windows XP Professional.
Microsoft Data Access Components (MDAC) | MDAC 2.6 or higher, required to install the .NET Framework.
.NET Framework | .NET Framework version 1.0.3705 or higher.
Bulk Event Submission Subcomponent

The bulk event submission subcomponent, which supports use of the SQLXML bulk loader, is used for submitting events in bulk from XML files. The following table shows the software that must be installed before installing the bulk event submission component.

Software | Requirement
SQL Server client tools | SQL Server 2000 client tools, required by SQLXML.
SQLXML | SQLXML 3.0 or higher. Note Microsoft recommends SQLXML 3.0 SP1 or higher.
Database Components

The following table shows the software that must be installed before installing database components.

Software | Requirement
SQL Server | SQL Server 2000 Standard Edition, SQL Server 2000 Enterprise Edition, or SQL Server 2000 Developer Edition. Note Microsoft recommends the most recent service pack for SQL Server 2000.
Documentation Components

The following table shows the software that must be installed before installing documentation components.

Software | Requirement
Internet software | Microsoft Internet Explorer 5.01 or higher.
Sample Applications

There are no software requirements for installing the sample applications. However, you must install the engine and database components somewhere (either on the same server or on other servers) to be able to use the sample applications.

The sample applications include a Microsoft Visual Studio® .NET solution file that can be used to edit and run the samples. If you have Visual Studio .NET, you can use the solution files.

For more information, see Notification Services Programming Samples.

Setup Requirements

Before Setup can install Notification Services components, Windows Installer version 2.0 must be installed on the computer. Setup checks for Windows Installer 2.0 and installs it if necessary. If Setup installs Windows Installer, you are prompted to reboot after the Notification Services installation is complete.

See Also

Installing Components

Notification Services Programming Samples

Permissions Required for Installation


Permissions Required for Installation

The permissions required to install Notification Services depend on the components you are installing. Engine and client components require local system permissions; database components require both local system and SQL Server permissions. If you are installing all components on a server, you must have the required permissions for every component.

Engine Components

When you are installing Notification Services engine components, the account you are using must have local administrator privileges.

The Notification Services NS$instance_name service is not created during software installation, so the service is not installed using these permissions or any default system permissions. You create the service and define a security account for the service after installation, when you create a new instance of Notification Services. For more information, see Registering and Unregistering an Instance.

Client Components

When you are installing the client components, the account you are using must have local administrator privileges.

Database Components

When you are installing database components, the account you are using must have local administrator privileges as well as be a member of the SQL Server sysadmin server role. Membership in sysadmin is required because installing database components adds a set of extended stored procedures to the master database.

See Also

Preparing to Install Notification Services


Files and File Locations

By default, Notification Services is installed to %PROGRAMFILES%\Program Files\Microsoft SQL Server Notification Services. You can alter this location during setup.

The following folders and files are added when installing Notifications Services:

vN.N.NNNN.N Folder

The root folder uses the Notification Services version number as its name. It contains the Bin, Docs, Samples, and XML Schemas folders. It also contains the Readme.txt file, which contains late-breaking information, and the NSOnWeb.url file, which is a Web link to the Notification Services home page.

Bin Folder

The Bin folder contains all of the binary Notification Services files, such as executables and DLLs, as well as command files. The Bin folder is created when you install the engine components or the client components.

File | Description
EventLogMessages.dll | Resource file that provides information about Notification Services events to the event log.
GrantXpExec.cmd | Command you can use to grant rights to run the Notification Services extended stored procedures to the account used by the NS$instance_name service. For more information, see GrantXPExec Utility.
InstallXPs.cmd | Command you can use to install the Notification Services extended stored procedures to additional instances of SQL Server. For more information, see InstallXPs Utility.
Microsoft.SqlServer.NotificationServices.dll | Notification Services core DLL.
Microsoft.SqlServer.NotificationServices.tlb | Type library used by Notification Services to register types for COM interoperability.
Nscontrol.exe | Executable file that runs the NSControl command prompt utility. Do not run this file. For more information, see NSControl Commands.
Nsservice.exe | Executable file used to run the Notification Services NS$instance_name service. (Installed with engine components only.) Do not run this file from this location. For more information, see Starting and Stopping a Service.
Nsservice.exe.config | Configuration file that controls the logging levels for the Notification Services NS$instance_name service. Edit the values in this file to control logging. For more information, see Configuring Notification Services Event Logging.
RegisterXPs.sql | Transact-SQL script that registers the Notification Services extended stored procedures in SQL Server. This script is run by Setup, so you do not need to run this script manually.
RevokeXpExec.cmd | Command you can use to revoke rights to run the Notification Services extended stored procedures. For more information, see RevokeXPExec Utility.
SetNSVars.cmd | Command used by Notification Services to set general environment variables and open a command prompt window. Instead of running this command, you can open the command prompt window from Start/Program Files/Microsoft SQL Server Notification Services.
SqlXmlBulkLoad.dll | Managed DLL used to facilitate the use of the SQLXML bulk loader.
UninstallXPs.cmd | Command you can use to remove the Notification Services extended stored procedures from an instance of SQL Server. For more information, see UninstallXPs Utility.
UnregisterXPs.sql | Transact-SQL script that removes the Notification Services extended stored procedures from SQL Server. Running this script manually is sometimes necessary. When uninstalling, Setup does not prompt for a SQL Server user name and password and does not prompt for the server name.

The Bin folder also contains language-specific folders, such as de (German), es (Spanish), and fr (French). Each folder contains a DLL that contains language-specific resources for Notification Services.

Docs Folder

The Docs folder contains Notification Services documentation. This folder is installed if you install the documentation components.

The Docs folder contains one folder for each installed language. Each language folder, such as en (English), contains the following files.

File | Description
Sqlntsv.chm | Notification Services HTML Help documentation file. Running this file opens SQL Server Notification Services Books Online.
Sqlntsv.hx* | Documentation files used by Microsoft Visual Studio® .NET. If Visual Studio is installed, you will be able to access the documentation in the Visual Studio .NET Help pane.
Samples Folder

The Samples folder contains all of the files for running the sample applications supplied with Notification Services. This folder is installed if you install the sample applications component during setup.

For more information about the files in the Samples folder, see Notification Services Programming Samples.

XML Schemas Folder

The XML Schemas folder contains the XML schemas for the application definition file (ADF) and the configuration file. These files are required by Notification Services. You can view these files to look at the XML schemas.

File | Description
ApplicationDefinitionFileSchema.xsd | The XML schema definition for the ADF. For more information about the elements described in this file, see the Application Definition File Reference.
ConfigurationFileSchema.xsd | The XML schema definition for the configuration file. For more information about the elements described in this file, see the Configuration File Reference.
SQL Server

When you install the database components, an extended stored procedure DLL is installed in the selected SQL Server Binn folder. The name of this file is Microsoft_SqlServer_NotificationServices_XP_X_X_XXXX_X.dll, where X_X_XXXX_X is the Notification Services version number.


Multiple Version Support

Over time, as successive versions of Notification Services are released, you might want to host applications that require different versions of Notification Services on the same system. Notification Services allows multiple versions of itself to be installed on one system, and allows each instance to use a different version. Also, having multiple versions on one system allows you to upgrade and downgrade instances (and their applications) as needed.

A version is a numbered release of Notification Services. The version number is represented in four parts: <Major>.<Minor>.<Build>.<Revision>. For example, a build number might be 2.0.3520.3.

Each version of Notification Services is installed to a folder with a name that matches the version number, and is registered independently of any other versions. For example, version 2.0.3520.3 is installed (by default) in the following directory:

C:\Program Files\Microsoft Notification Services\v2.0.3520.3

This naming scheme enables individual versions to be installed and uninstalled without affecting other installed versions of Notification Services.

All Notification Services components are labeled with a version number, as are some components created by developers and administrators. Notification Services checks the version number when creating an instance to verify that all components use the same product version.

See Also

Application Definition File Reference

Configuration File Reference

Configuring and Deploying Instances


Installing Components

An instance of Notification Services can run on a variety of system configurations. For example, the instance and the databases can all be on one server, the databases can be on a remote server, and the instance can be scaled across several servers. Additionally, you might have subscription management applications or independent event providers located on a remote server.

Notification Services Setup supports the different system configurations by allowing you to install one or more of the following components on a server:

  • The engine components, which must be installed on the server that runs an instance of Notification Services.
  • The client components, which must be installed on servers that host independent event providers and subscription management applications. These components contain the interfaces used by your independent event providers and subscription management applications. The NSControl commands, which you can use to administer an instance of Notification Services, are also installed.
  • The database components, which must be installed on the SQL Server 2000 database engine system. The database components include extended stored procedures used to generate notifications.
  • The sample applications, which can be installed on a development server. This component is a set of sample applications that you can use to become familiar with Notification Services. You can run the samples from within Microsoft Visual Studio® .NET.
  • The documentation components, which can be installed anywhere you want to have access to the Notification Services documentation.

During installation, you can select one or more components to install. The installation program checks the server for requirements and selects only the components that can be installed.

Note If SQL Server 2000 is installed but not started, installation of the database components fails.

The topics that this section covers are described in the following table.

To Install | See
All components | Installing All Components
Engine components only | Installing Engine Components
Client components only | Installing Client Components
Database components only | Installing Database Components
Database components on additional instances of SQL Server | Installing Database Components on Additional Instances of SQL Server
Documentation only | Installing Documentation
Samples only | Installing Sample Applications

See Also

Notification Services Programming Samples

Preparing to Install Notification Services

Running Setup from the Command Line

Setup Options


Installing All Components

When an instance of Notification Services and the database engine are located on one server, you can install all components on that server. You typically use a single-server configuration for development and for smaller applications.

To install all components

  1. Ensure that all prerequisite software is installed. For more information, see Hardware and Software Requirements.
  2. Run Notification Services Setup.
  3. On the Custom Setup page, make sure that all components are available: engine components, client components, database components, documentation, and sample applications.

    If one of these components is not available, the computer does not meet the minimum requirements for that component.

  4. If you have multiple instances of the database engine installed, select one instance on the Database Components Setup page.
  5. On the SQL Server Login Information page, select the type of authentication used to log in to SQL Server. Enter the user name and password if required.
  6. On the Ready to Install the Program page, click Install.

See Also

Notification Services Programming Samples

Preparing to Install Notification Services

Running Setup from the Command Line

Setup Options


Installing Engine Components

A server that runs an instance of Notification Services must have the engine components installed. If an instance of Notification Services is distributed across multiple servers, each server must have the engine components installed.

To install the engine components

  1. Ensure that engine component prerequisite software is installed. For more information, see Hardware and Software Requirements.
  2. Run Notification Services Setup.
  3. On the Custom Setup page, do the following:
    • Click Engine Components, and then select This feature will be installed on local hard drive.
    • Click each of the other components, and then select This feature will not be available.
  4. On the Ready to Install the Program page, click Install.

See Also

Installing Components

Preparing to Install Notification Services

Running Setup from the Command Line

Setup Options


Installing Client Components

Client components include the Notification Services API and the NSControl commands. These components are required for:

  • Subscription management applications. These applications use the Notification Services API to interact with Notification Services subscriber and subscription data; you must use the NSControl commands to register the instance on the server.
  • Independent event providers use the Notification Services API to submit events to the application databases; you must use the NSControl commands to register the instance on the server.
  • Remote administration servers must have the NSControl commands so you can administer instances and applications.

The bulk event submission subcomponent, which supports use of the Microsoft SQLXML bulk loader, is used for submitting XML data to SQL Server. If your independent event provider or subscription management application submits XML data, you must install this component. However, installing this component requires the SQL Server client tools to be installed. Because the client tools can be used to access databases, it is best not to install them unless necessary.

Note All of the client components are included in the engine components. If you have already installed the engine components on the server, you do not need to install the client components.

To install the client components

  1. Ensure that the client component prerequisite software is installed. For more information, see Hardware and Software Requirements.
  2. Run Notification Services Setup.
  3. On the Custom Setup page, do the following:
    • Click Client Components, and then select This feature will be installed on local hard drive.
    • If an application requires the SQLXML bulk loader component, click Bulk Event Submission, and then select This feature will be installed on local hard drive.
    • Click each of the other components, and then select This feature will not be available.
  4. On the Ready to Install the Program page, click Install.

See Also

Installing Components

Preparing to Install Notification Services

Running Setup from the Command Line

Setup Options


Installing Database Components

The system that hosts the Notification Services databases must have the database components installed. Installing the database components adds the Notification Services extended stored procedures that are used to create and distribute notifications.

To install the database components

  1. Ensure that the SQL Server 2000 database engine is installed and started.

    Setup does not attempt to start SQL Server.

  2. Run Notification Services Setup.
  3. On the Custom Setup page, do the following:
    • Click Database Components, and then select This feature will be installed on local hard drive.
    • Click each of the other components, and then select This feature will not be available.
  4. If you have multiple instances of SQL Server 2000 installed, select one instance on the Database Components Setup page.
  5. On the SQL Server Login Information page, select the type of authentication to use to log in to SQL Server. Enter the user name and password if required.
  6. On the Ready to Install the Program page, click Install.

    Note If you install the database components using SQL Server authentication, extended stored procedures added during setup are not removed after if Notification Services is later uninstalled. For information about removing the database components, see Removing Notification Services.

See Also

Installing Components

Installing Database Components on Additional Instances of SQL Server

Preparing to Install Notification Services

Running Setup from the Command Line

Setup Options


Installing Database Components on Additional Instances of SQL Server

When you install database components using Notification Services Setup, the components are installed on one instance of SQL Server only. You select the instance on the Database Components Setup page. If you want to install the database components on another instance of SQL Server on the same computer, you must use the InstallXPs command prompt utility.

To install database components to another instance

  1. Install the Notification Services engine components on a server.

    You can run the InstallXPs command remotely, so you do not need to install the engine components on a remote database server.

  2. On the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  3. Type the following command to install the database components:
    installxps server_name\sql_instance "sql_binn_path" sql_login password

    The database components are installed on the specified instance of SQL Server.

See Also

Installing Components

Installing Database Components

InstallXPs Utility

UninstallXPs Utility


Installing Documentation

When you install the documentation components, Setup installs an HTML Help file that contains programming, administration, and reference information. Setup will also register the documentation with Microsoft Visual Studio® NET. This enables you to view the documentation in the Visual Studio .NET Help pane.

To install documentation

  1. Run Notification Services Setup.
  2. On the Custom Setup page, do the following:
    • Click Documentation, and then select This feature will be installed on local hard drive.
    • Click each of the other components, and then select This feature will not be available.
  3. On the Ready to Install the Program page, click Install.

See Also

Running Setup from the Command Line

Installing Components

Preparing to Install Notification Services

Setup Options


Installing Sample Applications

Notification Services provides a set of sample applications to help you develop your own applications. The samples require a complete system (engine components, client, and database components) to run, and they also require Microsoft Visual Studio® .NET for full functionality. You can examine sample XML and batch files without any of these other components.

For additional information about the Notification Services samples, see Notification Services Programming Samples.

To install the sample applications

  1. Run Notification Services Setup.
  2. On the Custom Setup page, do the following:
    • Click Sample Applications, and then select This feature will be installed on local hard drive.
    • Click each of the other components, and then select This feature will not be available.
  3. On the Ready to Install the Program page, click Install.

See Also

Running Setup from the Command Line

Installing Components

Preparing to Install Notification Services

Setup Options


Running Setup from the Command Line

Notification Services Setup uses Microsoft Windows® Installer, which supports installation from the command line. Using the command-line syntax, you can create a batch file for unattended installation and removal of Notification Services.

Important If you install or uninstall Notification Services in silent mode from the command line, look in the application log to determine whether the operation was successful.

The downloaded installation file is a self-extracting installation file, MicrosoftSQLServerNotificationServices.exe, that contains a setup bootstrap file (Setup.exe), a Windows Installer database (Microsoft SQL Server Notification Services.msi) and a .cab file (Data1.cab). Running MicrosoftSQLServerNotificationServices.exe automatically runs Setup.exe.

Command-line arguments are passed to Setup.exe or Windows Installer by passing them directly to MicrosoftSQLServerNotificationServices.exe.

Command-Line Arguments for MicrosoftSQLServerNotificationServices.exe

MicrosoftSQLServerNotificationServices.exe accepts the command-line arguments that are presented in the following table.

Argument | Description
-s | Extracts the compressed file in silent mode (no dialog boxes). MicrosoftSQLServerNotificationServices.exe suppresses the progress indicator that is otherwise displayed while its contents are expanded to a temporary location.
-f path | Specifies a location to store Setup.exe, Microsoft SQL Server Notification Services.msi, and Data1.cab when they are expanded.
-e | Extracts the setup files without running Setup. To expand the contents of MicrosoftSQLServerNotificationServices.exe without launching Setup.exe, specify this option without any arguments.
-a setup_arguments | Passes the remaining arguments to Setup.exe.
Command-Line Arguments for Setup.exe

Setup.exe supports the command-line arguments that are presented in the following table. These areguments are passed in from the MicrosoftSQLServerNotificationServices.exe -a argument.

Argument | Description
-s | Runs Setup.exe in silent mode (no dialog boxes).
-v msi_arguments | Passes msi_arguments to Notification Services.msi; do not include a space between -v and msi_arguments. If specifying multiple arguments, enclose msi_arguments in quotation marks.
-x | Uninstalls Notification Services.
Command-Line Arguments for Microsoft SQL Server Notification Services.msi

Microsoft SQL Server Notification Services.msi accepts the following command-line arguments, which are passed in from the Setup.exe -v argument.

Argument | Description
-q[n|b|r|f] | Sets user interface (UI) level: n = no UI b = basic UI (progress only, no prompts) r = reduced UI (dialog at the end of installation) f = full UI
-L | Specifies log file options. To log all messages to log_file_name, use -L*v log_file_name. To log error messages only, use -Le log_file_name.
ADDLOCAL=components| REMOVE=components| REINSTALL=components | Specifies one of these options to install (ADDLOCAL), remove (REMOVE), or reinstall (REINSTALL) one or more components. You can either specify ALL to install or remove all components, or you can use a comma-separated list of components. A list of component names appears below.
INSTALLDIR=path | Installs Notification Services to the location specified by path.
SQLSERVERNAME=sql_server_instance_name | If you install the database components, specify the SQL Server instance name using this argument. Specify a default instance using only the computer name. Specify a named instance using the computer\instance format. If you do not use this argument, the database components are installed to the default instance.
SQLUSERNAME=sysadmin_user_name | To install the database components using SQL Server Authentication, specify the user name of a SQL Server system administrator using this argument.
SQLPASSWORD=sysadmin_password | Specify the password of the user name specified with SQLUSERNAME.
ALLUSERS=1 | To make the Notification Services Start menu items available to all users, use this argument. If you do not use this argument, Notification Services Start menu items are available only for the account that installs Notification Services.

For more information about these and additional command-line options, see Windows Installer Command Line Options in the Microsoft MSDN® Library.

Component Names

Each component that can be installed from Notification Services Setup can also be installed from the command line using the ADDLOCAL argument for Microsoft Windows Installer. To install a component from a command prompt, you must use the correct command-line name. The full name and command-line name for each component is shown in the following table.

Full Name | Command-Line Name
Engine components | EngineComponents
Client components | ClientComponents
Microsoft SQLXML bulk loader components | BulkEvents
Database components | DBComponents
Documentation | Documentation
Sample applications | Samples
All components | ALL (default value)

Note The BulkEvents option, if specified without ClientComponents, installs the client components. ClientComponents, if specified without BulkEvents, installs the SQLXML bulk loader components if the prerequisite software is already installed.

If you specify BulkEvents when the SQLXML and SQL Server client tools are not installed, Setup fails. If you were running Setup in silent mode (no dialogs), Setup writes a message to the application log.

Interaction Between Setup Components

If you run Setup from the command line using MicrosoftSQLServerNotificationServices.exe, you can pass arguments from MicrosoftSQLServerNotificationServices.exe to Microsoft SQL Server Notification Services.msi using Setup.exe. For example, you can run the following command:

MicrosoftSQLServerNotificationServices.exe -s -a -s -v"/qn"

The first -s argument extracts the files without displaying the setup screens. The -a argument passes all following arguments to Setup.exe. The second -s argument runs Setup.exe in silent mode. The last argument, -v, passes the /qn parameter to Microsoft Windows Installer, which runs the .msi package in silent mode.

The following table shows the parameters supplied to MicrosoftSQLServerNotificationServices.exe and the arguments passed to other Setup files.

File | Supplied or Passed Parameters
MicrosoftSQLServerNotificationServices.exe | -s -a -s -v"/qn"
Setup.exe | -s -v"/qn"
Windows Installer | /qn
Examples

The following examples show how to run Setup from the command line.

Extracting files to C:\Temp without running Setup

This example shows how to extract the Setup files, Setup.exe, Microsoft SQL Server Notification Services.msi, and Data1.cab, to C:\Temp without running Setup:

MicrosoftSQLServerNotificationServices.exe –f C:\Temp -e

Installing all components using Windows Authentication

This example shows how to install all components of Notification Services using Windows Authentication to install the database components to the default instance of SQL Server:

MicrosoftSQLServerNotificationServices.exe -s -a -s -v"/qn"

Installing all components using SQL Server Authentication

This example shows how to install all components of Notification Services using SQL Server Authentication to install the database components to the default instance of SQL Server:

MicrosoftSQLServerNotificationServices.exe -s -a -s
   -v"/qn SQLUSERNAME=user_name SQLPASSWORD=password"

Installing all components to a named instance of SQL Server using Windows Authentication

This example shows how to install all components of Notification Services using Windows Authentication to install the database components to a named instance of SQL Server:

MicrosoftSQLServerNotificationServices -s -a -s
   -v"/qn SQLSERVERNAME=computer\sql_instance"

Installing engine components to a specified location and installing database components to a named instance of SQL Server using Windows Authentication

This example shows how to install the engine components to C:\NS\ and the database components to a named instance of SQL Server using Windows Authentication:

MicrosoftSQLServerNotificationServices -s -a -s
   -v"/qn ADDLOCAL=EngineComponents,DBComponents
   SQLSERVERNAME=computer\sql_instance INSTALLDIR=\"c:\NS\""

Removing all installed components using Windows Authentication

This example shows how to remove all installed components:

MicrosoftSQLServerNotificationServices.exe -s -a -x -v"/qn"

Removing database components using Windows Authentication

This example shows how to remove the database components from a named instance of SQL Server using Windows Authentication:

MicrosoftSQLServerNotificationServices.exe -s -a -s
   -v"/qn REMOVE=DBComponents SQLSERVERNAME=computer\sql_instance"

Removing database components using SQL Server Authentication

This example shows how to remove the database components using SQL Server Authentication:

MicrosoftSQLServerNotificationServices.exe -s -a -s
   -v"/qn REMOVE=DBComponents SQLSERVERNAME=computer\sql_instance
    SQLUSERNAME=user_name SQLPASSWORD=password"

See Also

Installing Components

Setup Options


Reinstalling Notification Services

Setup supports reinstalling Notification Services to add or remove components, or to repair files or registry entries. If you attempt to install a version of Notification Services that is already registered on the server, Setup displays the Program Maintenance page, where you can modify, repair, or remove Notification Services.

To reinstall or repair Notification Services

  1. Run Notification Services Setup.
  2. On the Program Maintenance page, do one of the following:
    • If you want to add or remove components, click Modify.
    • If you need to repair a Notification Services installation, click Repair.

      Repair reinstalls and repairs the components you previously installed.

  3. Modify or repair the installation using the instructions provided in Installing Components.

See Also

Removing Notification Services

Program Maintenance Page


Removing Notification Services

Removing Notification Services removes components that were installed by Notification Services Setup.

Setup removes a single version of Notification Services. If multiple versions are installed on the computer, the selected version is uninstalled, and all other versions remain operational.

Setup does not check for applications using the version of Notification Services, nor does it delete configured instances of Notification Services. You must run the NSControl Delete command to remove databases and the NSControl Unregister command to unregister the instance.

Note Uninstalling the database components removes the version-specific extended stored procedures required by Notification Services. Before removing the database components, make sure no other installations of Notification Services use that SQL Server instance and the same version of Notification Services.

To remove Notification Services

  1. To delete any installed samples and their databases, run the RemoveSamplesDB command.

    The RemoveSamplesDB.cmd file is in the Samples folder of the Notification Services installation.

  2. Stop all instances of Notification Services that use the version you are removing.

    For more information, see Starting and Stopping Services.

  3. If you used SQL Server Authentication to install the database components, use the UninstallXPs command to remove the database components.

    Setup does not prompt for a SQL Server user name and password. The UninstallXPs.cmd file is in the Bin folder of the Notification Services installation.

  4. To delete an instance and its databases, do the following:
    1. On the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
    2. Type the following command to delete the instance and application databases:
      nscontrol delete -name instance_name -server database_server_name
    3. Type the following command to unregister the instance and delete the NS$instance_name service and the performance counters (if installed):
      nscontrol unregister -name instance_name
  5. In Control Panel, double-click Add/Remove Programs.
  6. Select Microsoft SQL Server Notification Services, and then click Remove.
  7. Follow the on-screen instructions.

If you unintentionally remove a version of Notification Services, you can simply reinstall that version. For more information, see Installing Components or Reinstalling Notification Services.

To remove database components from an instance of SQL Server

If you installed database components using the InstallXPs command or SQL Server Authentication, you must remove the database components using the UninstallXPs command.

  1. On the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Type the following command to remove the database components:
    uninstallxps computer\instance "sql_server_binn_folder"
   sql_login password

    The SQL login and password arguments are necessary only if you must use SQL Server Authentication to remove the database components.

See Also

RemoveSamplesDB Utility

UninstallXPs Utility

InstallXPs Utility


Setup Pages

Notification Services Setup contains several pages for configuring installation options. The options on these pages control which Notification Services components are installed. This section describes the installation options.

The topics that this section covers are described in the following table.

Topic | Description
Customer Information Page | Documents the Customer Information page.
Custom Setup Page | Documents the Custom Setup page.
Database Components Setup Page | Documents the Database Components Setup page.
SQL Server Login Information Page | Documents the SQL Server Login Information page.
Change Current Destination Folder Page | Documents the Change Current Destination Folder page.
Program Maintenance Page | Documents the Program Maintenance page.

See Also

Installing Components


Customer Information Page

On the Customer Information setup page in Setup, you supply information about who is installing and running Notification Services. This information is required.

Options

User name
Enter your name or the name of the person who will be using this installation of Notification Services.
Organization
Enter the name of the organization that owns this installation, such as your company name.
Install this application for
Specifies who will have access to this installation of Notification Services.

Anyone who uses this computer

Adds the Notification Services items to the Start menu for all users.

Only for me

Adds the Notification Services items to the Start menu of the account that is installing Notification Services.

See Also

Setup Options


Custom Setup Page

On the Custom Setup page in Setup, you select the components to install. The options depend on which prerequisite software, such as the Microsoft .NET Framework and SQL Server 2000, is available on the server.

Options

Engine Components
Specifies the installation option for the Notification Services engine components. The engine components run event collection, notification generation, formatting, and delivery, and also include the interfaces for subscription management applications. These components do not include database components, documentation, or samples.

You can choose to install or not install the engine components. Right-click the icon next to the component name to change the installation option.

This option is available only if the .NET Framework is installed on the server.

Client Components
Specifies the installation option for the Notification Services client components, which are used by subscription management applications and independent event providers that run on a remote server.

You can choose to install or not install the client components. Right-click the icon next to the component name to change the installation option.

This option is available only if the .NET Framework is installed on the server.

Bulk Event Submission
Specifies the installation option for the Microsoft SQLXML bulk loader, which is for submitting event data.

You can choose to install or not install the bulk event submission components. Right-click the icon next to the component name to change the installation option.

This option is available only if the SQL Server client tools are installed on the server.

Database Components
Specifies the installation option for the database components. The database components are the extended stored procedures installed in the SQL Server master database that enable Notification Services processing. This component does not include the engine components, documentation, or samples.

You can choose to install or not install the database components. Right-click the icon next to the component name to change the installation option.

This option is available only if SQL Server 2000 is installed on the server.

Documentation
Specifies the installation option for the documentation. The documentation is an HTML Help file that contains programming, administration, and reference information. If Microsoft Visual Studio® .NET is installed on the computer before the documentation components are installed, Setup registers the documentation with Visual Studio .NET.

You can choose to install or not install the documentation. Right-click the icon next to the component name to change the installation option.

Sample Applications
Specifies the installation option for the sample applications. The samples can be run on computers that host engine components.

You can choose to install or not install the samples. Right-click the icon next to the component name to change the installation option.

Install to
Shows the path where the components will be installed. You can change the location by clicking the Change button.
Change
Displays the Change Current Destination Folder page, where you can select a different installation location.
Help
Displays information about custom installation icons.
Space
Displays information about the combined disk space requirements for the installation option you have selected.

See Also

Setup Options


Database Components Setup Page

On the Database Components Setup page in Setup, you select an instance of SQL Server for installation of the database components. This page appears only if the database server has multiple instances of SQL Server 2000 installed.

Options

SQL Server
Lists the instances of SQL Server 2000 installed on the local computer. You must select the instance of SQL Server where you want to install the database components. You must have sysadmin privileges on the instance where you are installing the components.

The default instance of SQL Server uses the computer name only. Named instances of SQL Server use the computer name followed by the instance name (computer\instance_name).

See Also

Setup Options


SQL Server Login Information Page

On the SQL Server Login Information page in Setup, you choose the authentication mode used to install the database components. The user name and password are used during installation, and are not saved.

Options

Windows Authentication
If Mixed Mode is enabled on the SQL Server instance and your Microsoft Windows account has sysadmin privileges, select this mode. Your Windows account credentials are used to log in to SQL Server and install the database components.
SQL Server Authentication
If Mixed Mode is not enabled on the instance you selected, or if you must use SQL Server Authentication to provide your sysadmin login and password, select this mode.

SQL User Name

Enter your SQL Server login. The login account must have sysadmin privileges, as this account is used to install database components.

SQL Password

Enter the password associated with the SQL Server login.

See Also

Setup Options


Change Current Destination Folder Page

On the Change Current Destination Folder page in Setup, you can change the destination for the Notification Services program and supporting files. This page appears if you click the Change button on the Custom Setup page.

Options

Look in
Click to browse to a destination folder. You also can create new folders using the New Folder button.
Folder name
Type the destination folder for installation.

See Also

Setup Options


Program Maintenance Page

During Setup, the Program Maintenance page appears if you attempt to install a version of Notification Services that is already on the server.

Options

Modify
Allows you to change the components that are installed. You can then add or remove the engine components, database components, or documentation and samples. The components available on the Custom Setup page depend on which prerequisite software, such as Microsoft .NET Framework and SQL Server, is available on the server.
Repair
Repairs Notification Services components by adding missing files and fixing corrupt files, shortcuts, and registry entries.
Remove
Removes Notification Services components from the server.

See Also

Setup Options


Walkthrough: Creating a Stock Notification Application

This walkthrough teaches you how to build and debug a simple Microsoft® SQL Server™ Notification Services application. After installing the walkthrough files, you will start the walkthrough with a very simple Notification Services sample application and add new capabilities to it as you complete each numbered task. At the end of most tasks, you will run the application and verify the functionality that you have added. For example, after one task, you will add functionality to allow the application to capture and store events, and then run the application to see this process in action. As you complete each task, you learn key application development and debugging concepts.

The walkthrough is based on the Stock sample application that is shipped with Notification Services. This sample application is designed to deliver notifications about stock prices to users, based on when the stock price crosses a specified threshold, or at a time specified by the user.

If you complete the full walkthrough you will get the greatest benefit, but it can be used in a modular fashion as well. You can pick it up at any task (after installing the walkthrough files) and complete only that task in order to learn more about that specific item.

The walkthrough describes exactly what you must do at each step. It also describes exactly what source code changes are made during each step, so you can follow along in the code. The most beneficial approach is to update the source code as you go, and run and debug the resulting application at each step.

This walkthrough consists of 14 main tasks:

  1. Design the application. For more information about this task, see Task 1: Designing the Application.
  2. Perform an initial build of the application. For more information about this task, see Task 2: Performing an Initial Build of the Application.
  3. Add the event class. For more information about this task, see Task 3: Adding the Event Class.
  4. Add the event-driven subscription class. For more information about this task, see Task 4: Adding the Event-Driven Subscription Class.
  5. Add a notification generation rule. For more information about this task, see Task 5: Adding a Notification Generation Rule.
  6. Add the notification class. For more information about this task, see Task 6: Adding the Notification Class.
  7. Configure the content formatter. For more information about this task, see Task 7: Configuring the Content Formatter.
  8. Add the file system watcher event provider. For more information about this task, see Task 8: Adding the File System Watcher Event Provider.
  9. Add the standard Simple Mail Transfer Protocol (SMTP) delivery protocol. For more information about this task, see Task 9: Adding the Standard SMTP Delivery Protocol.
  10. Add the custom HttpLogger delivery protocol. For more information about this task, see Task 10: Adding the Custom HttpLogger Delivery Protocol.
  11. Design the scheduled subscription. For more information about this task, see Task 11: Designing the Scheduled Subscription.
  12. Add the event chronicle table. For more information about this task, see Task 12: Adding the Event Chronicle Table.
  13. Add the scheduled subscription class. For more information about this task, see Task 13: Adding the Scheduled Subscription Class.
  14. Review the subscription management application. For more information about this task, see Task 14: Reviewing the Subscription Management Application.

    Important To begin the walkthrough, you must first install the walkthrough files. For detailed information, see Before You Start: Installing the Walkthrough.


Before You Start: Installing the Walkthrough

The walkthrough uses the Stock programming sample that is shipped with Notification Services. Before you begin the walkthrough, you will need to install and import the walkthrough files.

Install the Walkthrough Files

Follow these steps to install the samples to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples directory (InstallLocation is the location where Notification Services has been installed).

  1. Make sure that your computer has all the prerequisites for running the Notification Services samples. For more information about these requirements, see Programming Sample Requirements.
  2. Open a command prompt window, and then navigate to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples directory.
  3. Run the SetupSamples.cmd script, which will set permissions for the programming samples and configure Internet Information Services (IIS) to run the samples.

    For more information about setting up the programming samples, see Setting Up and Removing Programming Samples.

  4. Extract the Walkthrough.zip file to the existing \Samples\Stock subdirectory of the Notification Services installation directory. Use the Extract function of the WinZip program to do this. Make sure the Use Folder Names check box is selected in the Extract dialog box. This action adds files to the existing subdirectories in this location.

    The Walkthrough.zip file contains a series of application definition files (ADFs) and configuration files that you will add to the AppDefinition project in the sample application solution. Each ADF and configuration file name corresponds to the task that takes that file as input. For example, appADF.task2.xml and appConfig.task2.xml are the files used in Task 2 of the walkthrough.

    The Walkthrough.zip file also contains several scripts that add sample subscribers, subscriptions, events, and the like. You will also add these scripts to the AppDefinition project as part of the sample application solution.

Import the Walkthrough Files

Follow these steps to import the walkthrough files to the Microsoft Visual Studio® .NET solution for the Stock sample and prepare it for use.

  1. In Microsoft Windows® Explorer, navigate to the /Samples/Stock subdirectory of the Notification Services installation directory.
  2. Double-click the Stock.sln file to open it in Visual Studio .NET.
  3. If the Solution Explorer pane is not open, click Solution Explorer on the View menu to open it.
  4. In the Solution Explorer pane, right-click AppDefinition, point to Add, and then click Add Existing Item.
  5. In the Add Existing Item dialog box, click All Files (*.*) in the Files of type list.
  6. Navigate to the \Samples\Stock\AppDefinition directory.
  7. Select all of the .sql files, and then click Open to add these files to the Solution Explorer pane.
  8. Select all of the .vbs files, and then click Open to add these files to the Solution Explorer pane.
  9. Select all of the appConfig.taskn.xml files, and then click Open to add these files to the Solution Explorer pane.
  10. Select all of the appADF.taskn.xml files, and then click Open to add these files to the Solution Explorer pane.
  11. Select the PortfolioSummary.xslt file, and then click Open to add this file to the Solution Explorer pane.
  12. In Windows Explorer, right-click the \Samples\Stock\SetProjectVars.cmd file, and then click Edit to open it.
  13. In theSetProjectVars.cmdfile, replace this line:
    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.xml

    with this line:

    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task2.xml
  14. Save and close the file.

Your tutorial configuration is now complete.


Task 1: Designing the Application

In this task you will accomplish the following:

  • Review the components that must be considered when designing a Notification Services application.

    In this task you will focus on conceptual issues. You will make no changes to the solution files.

To design an application in Notification Services, you must determine the structure of the events and subscriptions that your application will accept as input, and the structure of the notifications that it will produce. When designing the subscriptions that produce notifications, you must decide whether to produce notifications on a schedule, notifications based on event arrival, or both. You present the structure of this notification information in a series of schemas. You must then formulate rules for generating the notifications. You must also determine a format for the notifications. Finally, you must document the application. The following sections in task 1 cover these steps.

Determine the Subscription Schemas

First, you decide what kinds of subscriptions you want to provide to your subscribers. The Stock sample provides both scheduled and event-driven subscriptions.

  • The Stock sample can notify a subscriber as soon as a specified stock reaches a specified price. For example, the subscriber can request a notification as soon as Adventure Works Cycles stock reaches sixty dollars. This is called an event-triggered subscription.

    In the Stock sample, this subscription schema requires a stock symbol fieldand a stock trigger price field.

  • The Stock sample can also deliver a notification that lists the highest price reached by a particular stock as of a specified time of day. For example, a subscriber can request a notification containing the highest price reached by Adventure Works Cycles stock as of 15:30 GMT every weekday. This is called a scheduled subscription, because the notification is triggered at a scheduled time.

    In contrast to the event-triggered subscription schema, the only field required for this subscription schema is one to contain the stock symbol to be tracked. (You should not specify a field to contain the schedule, because Notification Services does this for you automatically. Notification Services automatically creates the table that stores the schedule when you define the subscription class in the ADF and include a scheduled rule.)

The Stock sample keeps only subscription data fields in its two subscription schemas. In addition to the subscription data fields, you could choose to keep other information with your subscriptions.

For example, the subscriber device name is commonly included in each subscription. Specifying the target subscriber device would allow subscribers with more than one device to target one subscription at one device and another subscription at another device.

It is also common to keep the subscriber locale — a code that identifies the subscribers' language and country/region — in each subscription. Specifying the locale would allow subscribers to receive notifications in their preferred language. Your application could use this information when formatting notifications. For example, your application could support both French and English notifications for subscribers in Canada.

For more information about defining subscription fields, see Subscription Fields.

Determine the Notification Schemas

After you determine the subscription type and structure, you decide what information you want each notification to contain. Here is the content of the two notification schemas for the Stock sample application:

  • The notification schema for the event-driven subscription contains the stock symbol, the current stock price, and a URL that allows the subscriber to retrieve more information regarding the stock.
  • The notification schema for the scheduled subscription contains the stock symbol, the highest price reached as of the time specified by the subscriber, and a URL that allows the subscriber to retrieve more information regarding the stock.
Determine the Event Source

After you determine the notification structure, you decide where to obtain the event data needed by your application. The Stock sample obtains its event data from an XML sample event data file, and from sample event data that you enter through the application's event submission intranet or Web page.

Note A Notification Services application can use the standard Notification Services event providers to obtain its event data from XML data files or from a SQL Server database. You can obtain event data from virtually any source, if you develop a custom event provider for that source.

Determine the Event Schema

Next, you decide what information you require each event to contain. The Stock sample requires events that contain stock price information. Therefore the event schema must contain fields for the stock symbol and the current stock price.

Determine the Notification Generation Rules

After you determine the event source and event schema, you create the notification generation rules that combine events and subscriptions to produce notifications.

  • The notification generation rule for the event-driven subscriptions compares the stock symbol and price in the event with the stock symbol and trigger price in the subscription. When the event information fulfills subscription requirements, the notification generation rule generates a notification. Notification Services automatically fires this rule each time an event batch of a particular event class (specified in the rule) arrives.
  • The notification generation rule for the scheduled subscriptions compares the stock symbol in the event chronicle table with the stock symbol in the subscription. The event chronicle table contains one record for each stock symbol. This chronicle record contains the highest daily price for the stock. Notification Services automatically fires a stock chronicle rule each time a new batch of stock events arrives. This chronicle rule updates the stock price in the chronicle table whenever the stock reaches a new high price. When the time specified in the scheduled subscription arrives, the scheduled subscription rule locates the chronicle record corresponding to the stock symbol specified in the subscription. It then generates a notification containing the stock price from the chronicle table. The prices in the chronicle table are reset to zero at the end of each day.

Chronicle tables are used to store event or subscription information for later use. You will add an event chronicle table later in the walkthrough, when you are adding a scheduled subscription class.

Determine the Notification Formatting

After you determine the notification generation rules, you decide on the appearance of the notification that you want to send to the subscriber.

The notification produced by the event-driven subscription looks like this:

Thank you for using SQL Server Notification Services.

AWKS is now trading at: $60.00

Click here to see the quote detail: http://moneycentral.msn.com/scripts/webquote.dll?ipage=qd&Symbol=AWKS

The notification produced by the scheduled subscription looks like this:

Thank you for using SQL Server Notification Services.

AWKS highest trade: $60.00

Click here to see the quote detail: http://moneycentral.msn.com/scripts/webquote.dll?ipage=qd&Symbol=AWKS

Document the Application Design

Finally, after you determine the notification formatting, you should write down your application design in a design document. For each event-driven subscription, specify the following schema information. You will add this information to the ADF for the Stock sample over the course of tasks 1 through 9. In task 11, you will define and document the elements required for a scheduled subscription.

Event schema:

StockSymbol nvarchar(6) not null

StockPrice decimal(18,5) null

Event-driven subscription schema:

DeviceName nvarchar(255) not null

SubscriberLocale nvarchar(10) not null

StockSymbol nvarchar(6) not null

StockTriggerValue decimal(18,5) null

Event-driven notification schema:

StockSymbol nvarchar(6) not null

StockPrice decimal(18,5) null

Subscription event notification generation rule:
SELECT e.StockSymbol, e.StockPrice
FROM StockEvents e, StockSubscriptions s
WHERE e.StockSymbol = s.StockSymbol AND
e.StockPrice > s.StockTriggerValue
XSLT file:

This is the content of the Application.xslt file, which you will use in task 7 to produce formatted notifications.

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="notifications">
      <html>
         <body>
            <xsl:apply-templates/>
            <i>
            Thank you for using SQL Server Notification Services.
            </i><br/><br/>
         </body>
      </html>
   </xsl:template>
   <xsl:template match="notification">
      <b><xsl:value-of select="StockSymbol" /></b> is now trading at:       <b>$<xsl:value-of select="StockPrice" /></b><br/>
      Click here to see the quote detail:
      <a>
         <xsl:attribute name="href">
   http://moneycentral.msn.com/scripts/webquote.dll?ipage=qd&amp;Symbol=<xsl:value-of select='StockSymbol'/>
         </xsl:attribute>
   http://moneycentral.msn.com/scripts/webquote.dll?ipage=qd&amp;Symbol=<xsl:value-of select="StockSymbol"/>
      </a>
      <br/><br/>
   </xsl:template>
</xsl:stylesheet>
Task 1 Summary

After completing all the steps in this task, you should now have a basic understanding of the key design elements of a Notification Services application: schemas that determine the structure of events, subscriptions, and notifications in your application; rules that match event and subscription information to produce notifications; and .xslt files that are used with the Notification Services standard XSLT content formatter to produce formatted notifications.


Task 2: Performing an Initial Build of the Application

In this task you will accomplish the following:

  • Review the initial configuration file.
  • Review the initial application definition file (ADF).
  • Review the Notification Services Rebuild command.
  • Build your application for the first time using Microsoft Visual Studio® .NET.
Review the Configuration File

Follow these steps to become familiar with the initial configuration file for the walkthrough.

  1. In the Solution Explorer pane of Visual Studio .NET, expand the AppDefinition project, and then double-click the appConfig.task2.xml file.

    At this point you notice that the configuration file contains just a few elements:

    • An <InstanceName> element that specifies the Notification Services instance name.
    • A <SqlServerSystem> element that specifies the SQL Server instance that will host the Notification Services databases.
    • An <Applications> node that contains the basic application information for the Stock sample.
    • A <DeliveryChannels> node that defines a delivery channel that uses the standard File delivery protocol provided by Notification Services.
  2. When you have finished reviewing the configuration file, close the file.
Review the ADF

Follow these steps to read through the initial application definition file for the walkthrough.

  1. In the Solution Explorer pane, double-click the appADF.task2.xml file to view the ADF.

    At this point you notice that the ADF contains these elements:

    • A <Version> node that you can use to label the ADF with version information. In this node, the <Build> element contains the portion of the version number that indicates the build of the application. The value of the <Build> element should be updated each time you update the ADF.
    • A <History> node that you can use to track when your ADF was originally created and when it was last changed.
    • Empty <SubscriptionClasses> and <NotificationClasses> nodes. You will be filling in these nodes during the walkthrough.
    • <Generator> and <Distributor> nodes, which contain the name of the system where the generator and distributor run. The system name is passed in as a parameter, specified as %ParameterName%.
    • Several basic application execution settings.
  2. When you have finished reviewing the ADF, close the file.
Review the Notification Services Rebuild Command

In an upcoming walkthrough task, you will invoke the Rebuild command to build your Notification Services application in Visual Studio .NET. The Rebuild command deletes the existing instance and application for this programming sample (if they exist), and then creates a new instance and application for the sample.

The Rebuild command is customized, and works by invoking the RunRebuild.cmd script. Follow these steps to review what the RunRebuild.cmd script does and how it works.

  1. In the Solution Explorer pane, expand the BuildScripts directory in the AppDefinition project, and then double-click the RunRebuild.cmd script to open it.

    Reading through the RunRebuild.cmd script, you notice that it does two things:

    • Invokes the NSControl Delete command. In this walkthrough, the command deletes the StockInstanceNSMain and StockInstanceStock databases.
    • Invokes the RunCreate.cmd script to re-create the Stock databases.
  2. When you have finished reviewing the RunRebuild.cmd script, close the file.
  3. In the BuildScripts directory, double-click the RunCreate.cmd script to open it.

    The RunCreate.cmd script does four things:

    • Ensures that the Events and Notification subdirectories of the sample directory exist and are empty.
    • Invokes the NSControl Create command, passing in the name of your configuration file as an argument. The configuration file contains a reference to the ADF. NSControl Create validates the ADF and the configuration file, and creates the StockInstanceNSMain and StockInstanceStock SQL Server databases.
    • Invokes the NSControl Enable command to enable the new instance for the sample.
    • Calls the GrantPermissions.cmd script to grant permissions on the instance and application databases to the Web and service accounts.
  4. When you have finished reviewing the RunCreate.cmd script, close the file.

The output from the Rebuild command is always displayed in the Output pane of Visual Studio .NET. Whenever you invoke the command, always look through the output carefully to verify that the command completed successfully.

Note For more information about the Notification Services commands used in the Visual Studio .NET solutions for the samples, see Programming Sample Structure.

Build the Application
  1. In the Solution Explorer pane, right-click the AppDefinition project, and then click Rebuild.

    A new Stock instance and application are created, overwriting the existing instance and application (if they exist).

  2. In the Output pane, scroll through the results of the Rebuild command to verify that the command succeeded.
  3. In the Server Explorer pane, navigate to the StockInstanceNSMain and StockInstanceStock databases.

    These are the databases generated by NSControl Create.

  4. In the Server Explorer pane, click the Services node, and then locate NS$StockInstance.

    NS$StockInstance is the name of the Notification Services service that was created by the NSControl Register command when you ran the SetupSamples.cmd script.

Task 2 Summary

After completing all the steps in this task, you should now have a basic understanding of the ADF and configuration file structures, as well as an idea of how the Rebuild command works. You should also have your first build of the application.


Task 3: Adding the Event Class

In this task you will accomplish the following:

  • Update the configuration file setting.
  • Add an event class and an event provider, and then rebuild your application.
  • Submit events using a simple Transact-SQL script.
Update the Configuration File Setting
  1. In Microsoft Windows® Explorer, navigate to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock directory.
  2. Right-click the SetProjectVars.cmd file, and then click Edit.
  3. In the SetProjectVars.cmd file, replace this line:
    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task2.xml

    with this line:

    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task3.xml
  4. Save and close the file.
Add the Event Class
  1. In the Solution Explorer pane of Microsoft Visual Studio® .NET, expand the AppDefinition project, and then open the appADF.task3.xml file.
  2. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
       <EventClasses>
      <EventClass>
         <EventClassName>StockEvents</EventClassName>
         <Schema>
            <Field>
               <FieldName>StockSymbol</FieldName>
               <FieldType>nvarchar(6)</FieldType>
               <FieldTypeMods>not null</FieldTypeMods>
            </Field>
            <Field>
               <FieldName>StockPrice</FieldName>
               <FieldType>decimal(18,5) </FieldType>
               <FieldTypeMods>null</FieldTypeMods>
            </Field>
         </Schema>
         <IndexSqlSchema>
            <SqlStatement>CREATE INDEX StockEventsIndex ON StockEvents ( StockSymbol )</SqlStatement>
         </IndexSqlSchema>
      </EventClass>
   </EventClasses>
  3. Place your cursor in the ADF, immediately in front of the <SubscriptionClasses> element.
  4. On the Edit menu, click Paste as HTML to paste the code in the ADF.
  5. Leave the file open.

By adding this node, you have added the StockEvents event class. (The <EventClassName> element specifies the name of the event class.) The event table will be created using the two fields specified in the <Schema> node. The <IndexSqlSchema> node creates an index on the event table to make stock event retrieval more efficient. Indexes are optional, but having the right index can make data retrieval much more efficient. You can omit indexes when you first develop your application and then add them later after all of your match rules are implemented and working. At that point, you can use all the normal SQL Server query optimization tools to decide what indexes are required.

For more information about the <EventClass> elements, see Defining an Event Class.

Add the Event Provider
  1. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
       <Providers>
      <NonHostedProvider>
         <ProviderName>EventCreator</ProviderName>
      </NonHostedProvider>
   </Providers>
  2. Place your cursor in the appADF.task3.xml file, immediately in front of the <Generator> node.
  3. On the Edit menu, click Paste as HTML to paste the code in the ADF.
  4. Save and close the ADF.

Notification Services events can originate from both hosted and independent event providers. Hosted event providers run inside the NS$instance_name service. They are started when the service is started, they run while the service runs, and they are stopped when the service is stopped. Independent event providers, on the other hand, run independently of Notification Services.

You must declare all event providers in the <Providers> section of the ADF. Notification Services requires that every event provider identify itself when submitting events. Self-identification allows Notification Services to tag every event batch with the name of the provider that submitted the batch.

For more information about event providers, see Collecting Events With an Event Provider and Defining an Event Provider.

Rebuild the Application
  1. In the Solution Explorer pane, right-click the AppDefinition project, and then click Rebuild. This drops and recreates the databases, deleting all data that was entered previously.
  2. Scroll through the results displayed in the Output pane to ensure that the Rebuild command succeeded.
Submit Events

Your application is now ready to accept events. You can use the AddEvents.sql script to submit events. The AddEvents.sql script adds events to an event table in the StockInstanceStock database. In a later task you will learn how to submit XML events using the file system watcher event provider.

Review the AddEvents.sql Script
  1. In the Solution Explorer pane, right-click the AddEvents.sql script, click Open With, click Source Code (Text) Editor, and then click Open.

    Reading through the AddEvents.sql script, you notice that it does four things:

    • Invokes the NSEventBeginBatchStockEvents stored procedure to begin a new event batch. This stored procedure returns a bigint output parameter representing the EventBatchId value.
    • Invokes the NSEventWriteStockEvents stored procedure once for each event it submits. Each call to this stored procedure requires the EventBatchId value as an input parameter.
    • Invokes the NSEventFlushBatchStockEvents stored procedure to commit the event batch.
    • Invokes the NSEventBatchDetails stored procedure to return information on the event batch and events, so you can confirm that they were submitted.

    You can use these event collection stored procedures to submit events from a database trigger or stored procedure that you write. The walkthrough introduces this event collection and submission model first because this approach is both useful and simple.

  2. When you have finished reviewing the AddEvents.sql script, close the file.
Associate AddEvents.sql with SQL Query Analyzer
  1. In the Solution Explorer pane, right-click the AddEvents.sql script, and then click Open With.
  2. Click Add.
  3. In the Add Programs dialog box, click Browse and navigate to the InstallLocation\Microsoft SQL \80\Tools\Binn\isqlw.exe file.
  4. Select the isqlw.exe file, and then click Open.
  5. Click OK.
  6. Click Set as Default, and then click Close.
Add Events
  1. In the Solution Explorer pane, double-click the AddEvents.sql script.

    The script launches in SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. In SQL Query Analyzer, review the event and event batch results returned by NSEventBatchDetails.
  4. Close SQL Query Analyzer.
Task 3 Summary

After completing all the steps in this task, you should now have a working event class, and some sample event data entered into your application. Refer to the Related Topics list for more information on the Notification Services event collection stored procedures.

See Also

NSEventBeginBatch<EventClassName>

NSEventFlushBatch<EventClassName>

NSEventSubmitBatch<EventClassName>

NSEventWrite<EventClassName>

Using the Event Collection Stored Procedures


Task 4: Adding the Event-Driven Subscription Class

In this step you will accomplish the following:

  • Update the configuration file setting.
  • Add the subscription class, and then rebuild your application.
  • Add subscribers, subscriber devices, and subscriptions using some simple Microsoft Visual Basic® Scripting Edition (VBScript) scripts.
Update the Configuration File Setting
  1. In Microsoft Windows® Explorer, navigate to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock directory.
  2. Right-click the SetProjectVars.cmd file, and then click Edit.
  3. In the SetProjectVars.cmd file, replace this line:
    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task3.xml

    with this line:

    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task4.xml
  4. Save and close the file.
Add the Subscription Class
  1. In the Solution Explorer pane of Microsoft Visual Studio® .NET, expand the AppDefinition project, and then open the appADF.task4.xml file.
  2. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
          <SubscriptionClass>
         <SubscriptionClassName>StockSubscriptions</SubscriptionClassName>
         <Schema>
            <Field>
               <FieldName>DeviceName</FieldName>
               <FieldType>nvarchar(255)</FieldType>
               <FieldTypeMods>not null</FieldTypeMods>
            </Field>
            <Field>
               <FieldName>SubscriberLocale</FieldName>
               <FieldType>nvarchar(10)</FieldType>
               <FieldTypeMods>not null</FieldTypeMods>
            </Field>
            <Field>
               <FieldName>StockSymbol</FieldName>
               <FieldType>nvarchar(6)</FieldType>
               <FieldTypeMods>not null</FieldTypeMods>
            </Field>
            <Field>
               <FieldName>StockTriggerValue</FieldName>
               <FieldType>decimal(18,5) </FieldType>
               <FieldTypeMods>not null</FieldTypeMods>
            </Field>
         </Schema>
      </SubscriptionClass>
  3. Place your cursor in the ADF between the <SubscriptionClasses> and </SubscriptionClasses> elements.
  4. On the Edit menu, click Paste as HTML to paste the code in the ADF.
  5. Save and close the ADF.

By replacing this node, you have added the StockSubscriptions subscription class. (The <SubscriptionClassName> element specifies the name of the subscription class.) The subscription table will be created using the four fields specified in the <Schema> node.

You have included DeviceName and SubscriberLocale fields in each subscription. DeviceName allows the subscriber to specify which device should receive the notification. For example, one subscriber might want to receive notifications on his cell phone while another wants to receive notifications via e-mail. SubscriberLocale can be used by the content formatter component to format the notification in the subscriber's language.

Note For more information about the <SubscriptionClass> elements, see Defining a Subscription Class. For more information about defining subscription fields, see Subscription Fields.

Notification Services stores each subscription in a subscription table in the StockInstanceStock database. Typically, subscribers enter subscriptions through a subscription management application that you provide. You determine how many subscriptions a subscriber can create.

Notification Services stores one record in the StockInstanceNSMain database for each subscriber. Each subscriber is identified by a unique SubscriberId field. You can assign any value that you want to the SubscriberId field. For example, you might use an e-mail address, an employee number, or a Microsoft .NET Passport user ID to identify a subscriber.

Notification Services stores one record for each device for each subscriber in the StockInstanceNSMain database. If one subscriber has three devices that receive notifications (a phone, an e-mail account, and pager, for example), you will have three subscriber device records for that subscriber. Each subscriber device is identified by the combination of SubscriberId and DeviceName fields. You decide how device names are assigned. You might allow the subscriber to pick his device names, such as "MyPhone" or "Bob'sEmailAccount." Alternatively, you might assign standard device names based upon device type or some other criterion, such as "PhoneDevice," "SMSDevice," or "EmailDevice."

Rebuild the Application
  1. In the Solution Explorer pane, right-click the AppDefinition project, and then click Rebuild. This drops and recreates the databases, deleting all data that was entered previously.
  2. Scroll through the results displayed in the Output pane to ensure that the Rebuild command succeeded.
Add Subscriber, Subscriber Device, and Subscription Information
Review the AddSubscribers.vbs and AddSubscriptions.vbs Scripts

You can use the AddSubscribers.vbs script to add subscribers and subscriber devices. The AddSubscribers.vbs script is written in VBScript. It illustrates how to use the Subscriber, SubscriberDevice, and Subscription classes that Notification Services provides to submit data to the system. It also illustrates how you can call Notification Services interfaces from COM components. Notification Services is written in managed code (C#) and is designed to be accessible from both managed and unmanaged code.

  1. In the Solution Explorer pane, right-click the AddSubscribers.vbs script, click Open With, click Source Code (Text) Editor, and then click Open.

    Reading through the AddSubscribers.vbs script, you notice that it does two things:

    • It adds subscribers to the subscribers table in the StockInstanceNSMain database. It does this by using a Subscriber object. For more information about using a Subscriber object, see Managing Subscribers and Subscriber Class.
    • It adds subscriber devices to the subscriber devices table in the StockInstanceNSMain database. It does this by using a SubscriberDevice object. For more information about using a SubscriberDevice object, see Managing Subscriber Devices and SubscriberDevice Class.
  2. Review and then close the script.
  3. Right-click the AddSubscriptions.vbs script, click Open With, click Source Code (Text) Editor, and then click Open.

    The AddSubscriptions.vbs script adds subscriptions to a subscriptions table in the StockInstanceStock database. It does this by using a Subscription object. For more information about using a Subscription object, see Managing Subscriptions and Subscription Class.

  4. Review and then close the script.
Run the AddSubscribers.vbs and AddSubscriptions.vbs Scripts
  1. In the Solution Explorer pane, right-click AddSubscribers.vbs, and then click Open With.
  2. Select the wscript.exe file, and then click Open to run the script.
  3. Right-click the AddSubscriptions.vbs script, and then click Open With.
  4. Select the wscript.exe file again, and then click Open to run the script.
View Subscriber and Subscriber Device Information
Review the ViewSubscribersAndDevices.sql Script
  1. In the Solution Explorer pane, right-click the ViewSubscribersAndDevices.sql script.
  2. Click Open With, click Source Code (Text) Editor, and then click Open.

    The ViewSubscribersAndDevices.sql script queries the NSSubscriberDeviceView view and returns subscriber and subscriber device information. Notification Services automatically creates this view in each Notification Services instance database.

  3. Review and then close the ViewSubscribersAndDevices.sql script.
Associate ViewSubscribersAndDevices.sql with SQL Query Analyzer
  1. In the Solution Explorer pane, right-click the ViewSubscribersAndDevices.sql script, and then click Open With.
  2. Click Add.
  3. Click Browse, and then navigate to the InstallLocation\Microsoft SQL \80\Tools\Binn\isqlw.exe file.
  4. Select the isqlw.exe file, and then click Open.
  5. Click OK.

    The Add Programs dialog box closes.

  6. Click Set as Default, and then click Close.
Run ViewSubscribersAndDevices.sql
  1. In the Solution Explorer pane, double-click the ViewSubscribersAndDevices.sql script.

    The script launches in SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. Review the subscriber and subscriber device information returned by the query.
  4. Close SQL Query Analyzer.
View Subscription Information
Review the ViewSubscriptions.sql Script
  1. In the Solution Explorer pane, right-click the ViewSubscriptions.sql file, click Open With, click Source Code (Text) Editor, and then click Open.

    The ViewSubscriptions.sql script queries a view and returns subscription information. Notification Services creates one SQL Server view for each subscription class, which can be used to look at current subscription information. Notification Services uses the naming convention NS SubscriptionClassName View, so in this case the view will be NSStockSubscriptionsView.

  2. Review and then close ViewSubscriptions.sql script.
Associate ViewSubscriptions.sql with SQL Query Analyzer
  1. In the Solution Explorer pane, right-click the ViewSubscriptions.sql script, click Open With, and then click Add.
  2. Click Browse, and then navigate to the InstallLocation\Microsoft SQL \80\Tools\Binn\isqlw.exe file.
  3. Select the isqlw.exe file, and then click Open.
  4. Click OK.

    The Add Programs dialog box closes.

  5. Click Set as Default, and then click Close.
Run ViewSubscriptions.sql
  1. Double-click the ViewSubscriptions.sql script.

    The script launches in SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button in the toolbar to run the script.
  3. Review the subscription information returned by the query.
  4. Close SQL Query Analyzer.
Task 4 Summary

After completing all the steps in this task, you should now have a working subscription class, and some sample subscriber, subscriber device, and subscription data entered in your application.


Task 5: Adding a Notification Generation Rule

In this step you will accomplish the following:

  • Update the configuration file setting.
  • Add the notification generation rule, and then rebuild your application.
  • Run your notification generation rule.
Update the Configuration File Setting
  1. In Microsoft Windows® Explorer, navigate to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock directory.
  2. Right-click the SetProjectVars.cmd file, and then click Edit.
  3. In the SetProjectVars.cmd file, replace this line:
    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task4.xml

    with this line:

    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task5.xml
  4. Save and close the file.
Add the Notification Generation Rule
  1. In the Solution Explorer pane of Microsoft Visual Studio® .NET, expand the AppDefinition project, and then open the appADF.task5.xml file.
  2. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
             <EventRules>
            <EventRule>
               <RuleName>StockSubscriptionsEventRule</RuleName>
               <!-- This sample notification generation rule writes
               its results to a temporary table. This is a good
               way to debug your notification generation rule. -->
               <Action>
               IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
               WHERE TABLE_NAME = N&apos;TempResults&apos;)
               DROP TABLE TempResults
               SELECT s.SubscriberId, s.DeviceName, s.SubscriberLocale,
               e.StockSymbol, e.StockPrice
               INTO TempResults
               FROM StockEvents e, StockSubscriptions s
               WHERE e.StockSymbol = s.StockSymbol
               AND e.StockPrice &gt; s.StockTriggerValue
               </Action>
               <EventClassName>StockEvents</EventClassName>
            </EventRule>
         </EventRules>

    Note There are several reserved characters in the Notification Services XML vocabulary (>, <, ', ", &, %). If you want to use these characters in ADF data, you must use entity references to replace them. For more information about using reserved characters, see Reserved Characters.

  3. Place your cursor in the ADF, immediately following the end tag of the /SubscriptionClasses/SubscriptionClass/Schema section.
  4. On the Edit menu, click Paste as HTML to paste the code in the ADF.
  5. Save and close the ADF.

The notification generation rule is critical to the Notification Services application. The rule matches events and subscriptions to produce notifications. It can be specified in an <EventRule> node, as shown above, or in a <ScheduledRule> node, which you will see when adding the scheduled subscription class in Task 13.

The notification generation rule is a Transact-SQL SELECT statement. It can include data from chronicle tables (covered in a later task of in this walkthrough), and any other tables you want. These tables can be located in the Notification Services databases or in other SQL Server databases. You can also make use of all of the facilities of SQL Server, including calling stored procedures or extended stored procedures.

When the Notification Services service is running, the notification generation rule for the event-driven subscription class fires when the generator detects that a new event batch that is associated with the event class has arrived. You associate an event-driven notification generation rule with its event class by specifying the <EventClassName> element in the <EventRule> node.

The generator function is replaced in this task of the walkthrough by the NSPrepareRuleFiring and NSExecuteRuleFiring stored procedures. These stored procedures are useful when testing rules. NSPrepareRuleFiring prepares the Notification Services application database for a rule firing by scheduling each interval, called a quantum, for generator firing, and otherwise setting up the system to execute a rule. NSExecuteRuleFiring prepares and runs Notification Services application rules. For more information about setting quantum intervals, see Defining the Application Execution Settings. For more information about NSPrepareRuleFiring, see NSPrepareRuleFiring. For more information about NSExecuteRuleFiring, see NSExecuteRuleFiring.

Rebuild the Application
  1. In the Solution Explorer pane, right-click AppDefinition, and then click Rebuild. This drops and recreates the databases, deleting all data that was entered previously.
  2. Scroll through the results displayed in the Output pane to ensure that the Rebuild command succeeded.
Add Subscriber, Subscriber Device, and Subscription Data
  1. In the Solution Explorer pane, right-click the AddSubscribers.vbs script, and then click Open With.
  2. Select the wscript.exe file, and then click Open to run the script.
  3. Right-click the AddSubscriptions.vbs script, and then click Open With.
  4. Select the wscript.exe file again, and then click Open to run the script.
Run the Notification Generation Rule

Follow these steps to run the notification generation rule.

Disable the Generator

First, disable the generator function, so that the rule-firing stored procedures will execute properly.

  1. Open a command prompt window, and then navigate to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Bin directory.
  2. Type the following command:
    nscontrol disable -name StockInstance -generator

    Notification generation is disabled.

Submit Events
  1. In the Solution Explorer pane, double-click the AddEvents.sql script.

    The script launches in SQL Query Analyzer.

    Note If you skipped Task 3, please refer to the Submit Events section of that task for instructions on associating the AddEvents.sql script with SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. In SQL Query Analyzer, review the event and event batch results returned by NSEventBatchDetails.

    Note the value in the EndCollectionTime column in the third result set.

Fire the Rule
  1. In SQL Query Analyzer, open a new Query window.
  2. From this online Help topic, copy the following Transact-SQL statement, and then paste it in the Query window:
    EXEC NSSetQuantumClockDate 'EndCollectionTime'
  3. Replace the EndCollectionTime argument with the EndCollectionTime value you noted in the previous step, "Submit Events." This must be a datetime value in UTC format, like '2002-06-12 00:00:00'.
  4. Run the query.

    The quantum clock is set so that the quantum prepared by NSPrepareRuleFiring in the next step will be the quantum in which your events were submitted. This ensures that the events you just submitted are used for comparison with your subscription data when the rule is fired in the next step.

  5. From this online Help topic, copy the following Transact-SQL statement, and then paste it into the Query window:
    EXEC NSPrepareRuleFiring 0, 0
EXEC NSExecuteRuleFiring 0, 0

    When the generator is invoked by running these stored procedures, it determines whether any event batches fall in the current quantum. The generator discovers the event batch you submitted in the previous step, determines its event class name, and determines that the StockSubscriptionsEventRule must be fired for this event class.

    The generator then constructs the StockEvents view over the NSStockEventsEvents table. This view contains only those events that belong to the selected event batch for this quantum.

    The generator finally invokes the StockSubscriptionsEventRule. The event rule matches the events in the StockEvents view with the subscriptions in the StockSubscriptions table and writes the resulting notifications to the TempResults table.

  6. Run the query and review the result sets.
  7. Close SQL Query Analyzer.
View the Rule Firing Results
Review the RuleFiringResults.sql Script
  1. In the Solution Explorer pane, right-click the RuleFiringResults.sql script.
  2. Click Open With, click Source Code (Text) Editor, and click Open.

    The script opens.

    Reading through the RuleFiringResults.sql script, you notice that it does three things:

    • It displays the contents of the StockEvents view. This view is always created during rule firing, and contains just the events to be processed (instead of the entire contents of the NSStockEventsEvents table).
    • It displays the contents of the NSStockSubscriptionsView view.
    • It displays the contents of the TempResults table.
  3. Review and close the RuleFiringResults.sql script.
Associate RuleFiringResults.sql with SQL Query Analyzer
  1. In the Solution Explorer pane, right-click the RuleFiringResults.sql script, and then click Open With.
  2. Click Add.
  3. Click Browse and navigate to the InstallLocation\Microsoft SQL \80\Tools\Binn\isqlw.exe file.
  4. Select the isqlw.exe file, and then click Open.
  5. Click OK.

    The Add Programs dialog box closes.

  6. Click Set as Default, and click Close.
Run RuleFiringResults.sql
  1. In the Solution Explorer pane, double-click the RuleFiringResults.sql script.

    The script launches in SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. Review the event, subscription, and rule processing results returned by the queries.
  4. Close SQL Query Analyzer.
Task 5 Summary

After completing all the steps in this task, you should now have an idea of how Notification Services rules work, and be familiar with the type of information that is generated each time a rule is fired.


Task 6: Adding the Notification Class

In this step you will accomplish the following:

  • Update the configuration file setting.
  • Add the notification class, update the notification generation rule to call the notification function, and then rebuild your application.
  • Generate notifications, format them using the default NoOp.xslt file and standard Notification Services XSLT content formatter, and view the resulting notifications.
Update the Configuration File Setting
  1. In Microsoft Windows® Explorer, navigate to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock directory.
  2. Right-click the SetProjectVars.cmd file, and then click Edit.
  3. In the SetProjectVars.cmd file, replace this line:
    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task5.xml

    with this line:

    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task6.xml
  4. Save and close the file.
Add the Notification Class
  1. In the Solution Explorer pane of Microsoft Visual Studio® .NET, expand the AppDefinition project, and then open the appADF.task6.xml file.
  2. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
          <NotificationClass>
         <NotificationClassName>StockNotifications</NotificationClassName>
         <Schema>
            <Fields>
               <Field>
                  <FieldName>StockSymbol</FieldName>
                  <FieldType>nvarchar(6)</FieldType>
               </Field>
               <Field>
                  <FieldName>StockPrice</FieldName>
                  <FieldType>decimal(18,5) </FieldType>
               </Field>
            </Fields>
         </Schema>
         <ContentFormatter>
            <ClassName>XsltFormatter</ClassName>
            <Arguments>
               <Argument>
                  <Name>XsltBaseDirectoryPath</Name>
                  <Value>%_BaseDirectoryPath_%\AppDefinition</Value>
               </Argument>
               <Argument>
                  <Name>XsltFileName</Name>
                  <Value>NoOp.xslt</Value>
               </Argument>
            </Arguments>
         </ContentFormatter>
         <Protocols>
            <Protocol>
               <ProtocolName>File</ProtocolName>
            </Protocol>
         </Protocols>
         <ExpirationAge>PT2H</ExpirationAge>
      </NotificationClass>
  3. Place your cursor in the ADF, between the <NotificationClasses> and </NotificationClasses> elements.
  4. On the Edit menu, click Paste as HTML to paste the code in the ADF.
  5. Leave the ADF open.

By replacing this node, you have added the StockNotifications notification class.

The <NotificationClassName> element specifies the name of the notification class.

The notification table is created using the fields specified in the /NotificationClasses/NotificationClass/Schema/Fields section.

The <ContentFormatter> node specifies the information necessary to format notifications of this notification class, including the content formatter component to be used, and the arguments that the content formatter requires.

The <Protocols> node specifies the protocols (such as SMTP or HTTP) used to deliver notifications of this class, and provides any field values that might be needed to create a notification message using the specified protocol.

For more information about the <NotificationClass> elements, see Defining a Notification Class.

Update the Subscription Event Rule
  1. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
                   <Action>
               SELECT dbo.StockNotificationsNotify(
               s.SubscriberId, s.DeviceName,
               s.SubscriberLocale, e.StockSymbol, e.StockPrice)
               FROM StockEvents e, StockSubscriptions s
               WHERE e.StockSymbol = s.StockSymbol
               AND e.StockPrice &gt; s.StockTriggerValue
               </Action>
  2. Highlight the existing /SubscriptionClasses/SubscriptionClass/EventRules/EventRule/Action element in the ADF.
  3. On the Edit menu, click Paste as HTML to replace the ADF code with the copied code.
  4. Save and close the ADF.

A notification generation rule generates notifications by calling the NotificationClassNameNotify function, in this case StockNotificationsNotify. Notification Services automatically creates a notification function for each notification class, based on the defined notification schema. For more information about the notification function, see Using Notification Functions.

Rebuild the Application
  1. In the Solution Explorer pane, right-click the AppDefinition project, and then click Rebuild. This drops and recreates the databases, deleting all data that was entered previously.
  2. Scroll through the results displayed in the Output pane to ensure that the Rebuild command succeeded.
Add Subscriber, Subscriber Device, and Subscription Data
  1. In the Solution Explorer pane, right-click the AddSubscribers.vbs script, and then click Open With.
  2. Select the wscript.exe file, and then click Open to run the script.
  3. Right-click the AddSubscriptions.vbs script, and then click Open With.
  4. Select the wscript.exe file again, and then click Open to run the script.
Run the Notification Generation Rule

Follow these steps to run the notification generation rule.

Disable the Generator

First, disable the generator function, so that the rule-firing stored procedures execute properly.

  1. Open a command prompt window, and then navigate to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Bin directory.
  2. Type the following command:
    nscontrol disable -name StockInstance -generator

    The generator function is disabled.

Submit Events
  1. In the Solution Explorer pane, double-click the AddEvents.sql script.

    The script launches in SQL Query Analyzer.

    Note If you skipped Task 3, please refer to the Submit Events section of that task for instructions on associating the AddEvents.sql script with SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. In SQL Query Analyzer, review the event and event batch results returned by NSEventBatchDetails.

    Note the value in the EndCollectionTime column in the third result set.

Fire the Rule
  1. In SQL Query Analyzer, open a new Query window, and then select StockInstanceStock in the database list on the toolbar.
  2. From this online Help topic, copy the following Transact-SQL statement, and then paste it in the Query window:
    EXEC NSSetQuantumClockDate 'EndCollectionTime'
  3. Replace EndCollectionTime with the EndCollectionTime value you noted in the previous step, "Submit Events." This must be a datetime value in UTC format, such as '2002-06-12 00:00:00'.
  4. Run the query.

    The quantum clock is set so that the quantum prepared by NSPrepareRuleFiring in the next few steps is the quantum in which your events were submitted. This ensures that the events you just submitted are used for comparison with your subscription data when the rule is fired in the next step.

  5. From this online Help topic, copy the following Transact-SQL statement, and then paste it in the Query window:
    EXEC NSPrepareRuleFiring 0, 0
EXEC NSExecuteRuleFiring 0, 0
  6. Run the query.
  7. Review the result sets.

    Note the QuantumId value returned for the row in the third result set that lists StockSubscriptionsEventRule as the RuleName value.

View the Quantum Information
  1. In the Query window, delete the Transact-SQL statement you added in the previous step, "Fire the Rule."
  2. From this online Help topic, copy the following Transact-SQL statement, and then paste it in the Query window:
    EXEC NSQuantumDetails QuantumId
  3. Replace the QuantumId argument with the QuantumId value you noted in the rule firing results.
  4. Run the query.
  5. Review the result sets to see the details of the quantum that was processed by the rule firing.

    In the fifth result set, note the NotificationBatchId value returned for the row that lists StockNotifications as the NotificationClassName value.

View the Notification Information
  1. In the Query window, delete the Transact-SQL statement you added in the previous step, "View the Quantum Information".
  2. From this online Help topic, copy the following Transact-SQL statement, and then paste it in the Query window:
    EXEC NSNotificationBatchDetails N'StockNotifications', NotificationBatchId
  3. Replace the NotificationBatchId argument with the NotificationBatchID value you noted in the NSQuantumDetails results.
  4. Run the query.
  5. Look at the result sets to review notification details.
  6. Close SQL Query Analyzer.
Task 6 Summary

After completing all the steps in this task, you should now have a working notification class entered into your application, and be able to produce and view notification data.


Task 7: Configuring the Content Formatter

In this step you will accomplish the following:

  • Update the configuration file setting.
  • Generate and view unformatted notifications produced with the NoOp.xslt file. This will allow you to see the notifications as they are produced by the system, with no additional formatting.
  • Replace the NoOp.xslt file with the Application.xslt file, and then rebuild your application.
  • Generate and view the formatted notifications produced with the Application.xslt file. This will allow you to see the notifications formatted with supporting text.
Update the Configuration File Setting
  1. In Microsoft Windows® Explorer, navigate to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock directory.
  2. Right-click the SetProjectVars.cmd file, and then click Edit.
  3. In the SetProjectVars.cmd file, replace this line:
    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task6.xml

    with this line:

    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task7.xml
  4. Save and close the file.
Rebuild the Application
  1. In the Solution Explorer pane of Microsoft Visual Studio® .NET, right-click the AppDefinition project, and then click Rebuild. This drops and recreates the databases, deleting all data that was entered previously.
  2. Scroll through the results displayed in the Output pane to ensure that the Rebuild command succeeded.
Generate Unformatted Notifications
Start the NS$StockInstance Service
  1. In the Server Explorer pane, click the Services node.
  2. Right-click NS$StockInstance, and then click Start.
Add Subscriber, Subscriber Device, and Subscription Data
  1. In the Server Explorer pane, right-click the AddSubscribers.vbs script, and then click Open With.
  2. Select the wscript.exe file, and then click Open to run the script.
  3. Right-click the AddSubscriptions.vbs script, and then click Open With.
  4. Select the wscript.exe file again, and then click Open to run the script.
Submit Events
  1. In the Server Explorer pane, double-click the AddEvents.sql script.

    The script launches in SQL Query Analyzer.

    Note If you skipped Task 3, please refer to the Submit Events section of that task for instructions on associating the AddEvents.sql script with SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. In SQL Query Analyzer, review the event and event batch results returned by NSEventBatchDetails.
  4. Close SQL Query Analyzer.
Stop the NS$StockInstance Service
  1. Allow the service to run for about 60 seconds in order to generate notifications.
  2. Return to the Server Explorer pane, right-click NS$StockInstance, and then click Stop.
View the Unformatted Notifications
Review the ViewNotifications.sql script
  1. In the Solution Explorer pane, expand the AppDefinition project, right-click the ViewNotifications.sql script, click Open With, click Source Code (Text) Editor, and then click Open.

    The ViewNotifications.sql script runs the NSNotificationBatchDetails stored procedure to return notification information.

  2. Review and close the script.
Associate ViewNotifications.sql with SQL Query Analyzer
  1. In the Solution Explorer pane, right-click the ViewNotifications.sql script, and then click Open With.
  2. Click Add.
  3. Click Browse and navigate to the InstallLocation\Microsoft SQL \80\Tools\Binn\isqlw.exe file.
  4. Select the isqlw.exe file, and then click Open.
  5. Click OK.

    The Add Programs dialog box closes.

  6. Click Set as Default, and then click Close.
Run ViewNotifications.sql

This script allows you to view the notification data in the database.

  1. In the Solution Explorer pane, double-click the ViewNotifications.sql script.

    The script launches in SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. Review the notification information returned by the query.
  4. Close SQL Query Analyzer.
View the Unformatted Notifications

This step allows you to view the unformatted notifications after they are written to a file.

  1. Using Microsoft Notepad, open the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock\Test\Test1\Notifications\StockNotification.txt file.

    You will see one unformatted notification for each subscriber.

  2. Review the data, and then close and delete the file.
Modify the Content Formatter
  1. In the Solution Explorer pane, expand the AppDefinition project, and then open the appADF.task7.xml file .
  2. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
                   <Argument>
                  <Name>XsltFileName</Name>
                  <Value>Application.xslt</Value>
               </Argument>
  3. Place your cursor in the ADF, and select the existing XsltFileName argument in the /NotificationClasses/NotificationClass/ContentFormatter/Arguments section.
  4. On the Edit menu, click Paste as HTML to replace the ADF code with the copied code.
  5. Save and close the ADF.
View the Application.xslt File

The Application.xslt file provides formatting for stock notifications.

  1. In the Solution Explorer pane, locate the Application.xslt file, and then double-click it to open it.

    Notice that the formatting file inserts the StockSymbol value into the formatted notification by referring to <xsl:value-of select="StockSymbol" />. It inserts the StockPrice value into the formatted notification by referring to <xsl:value-of select="StockPrice" />. These values map to the /NotificationClasses/NotificationClass/Schema/Fields elements in the ADF.

  2. Close the file.
Rebuild the Application
  1. In the Solution Explorer pane, right-click the AppDefinition project, and then click Rebuild. This drops and recreates the databases, deleting all data that was entered previously.
  2. Scroll through the results displayed in the Output pane to verify that the Rebuild command succeeded.
Generate Formatted Notifications
Start the NS$StockInstance Service
  1. In the Server Explorer pane, click the Services node.
  2. Right-click NS$StockInstance, and then click Start.
Add Subscriber, Subscriber Device, and Subscription Data
  1. In the Server Explorer pane, right-click the AddSubscribers.vbs script, and then click Open With.
  2. Select the wscript.exe file, and then click Open to run the script.
  3. Right-click the AddSubscriptions.vbs script, and then click Open With.
  4. Select the wscript.exe file again, and then click Open to run the script.
Submit Events
  1. In the Server Explorer pane, double-click the AddEvents.sql script.

    The script launches in SQL Query Analyzer.

    Note If you skipped Task 3, please refer to the Submit Events section of that task for instructions on associating the AddEvents.sql script with SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. In SQL Query Analyzer, review the event and event batch results returned by NSEventBatchDetails.
  4. Close SQL Query Analyzer.
Stop the NS$StockInstance Service
  1. Allow the service to run for about 60 seconds in order to generate notifications.
  2. In the Server Explorer pane, right-click NS$StockInstance, and then click Stop.
View the Formatted Notifications
Run ViewNotifications.sql

This script allows you to view the notification data in the database.

  1. In the Solution Explorer pane, double-click the ViewNotifications.sql script.

    The script launches in SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. Review the notification information returned by the query.
  4. Close SQL Query Analyzer.
View the Formatted Notifications

This step allows you to view the formatted notifications after they are written to a file.

  1. Using Microsoft Notepad, open the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock\Test\Test1\Notifications\StockNotification.txt file.

    You will see one formatted notification for each subscriber.

  2. Review the data, and then close and delete the file.
Task 7 Summary

After completing all the steps in this task, you should be able to configure a content formatter and produce formatted notifications.


Summary: Tasks 1 - 7

You have now completed a notification application that provides event-driven subscriptions. In the process you carried out the following tasks:

  • Designed the application by specifying the event, subscription, and notification schemas; the notification generation rule; and the appearance of the formatted notification.
  • Got the core of the application working by entering events, subscribers, subscriber devices, and subscriptions using simple scripts.
  • Implemented and tested your notification generation rules.
  • Formatted your notifications and delivered them using the file delivery channel.

After you have your basic application working, complete the application by implementing your subscription management application, and then configuring or implementing any additional event providers, content formatters, and delivery protocols your application will use.

This approach is recommended for Notification Services application development generally.

Looking Forward

You now have an application that produces formatted notifications. The next tasks will show you how to extend the functionality of the application by automating event input and providing additional options for notification delivery. You will learn how to configure the file system watcher event provider to enter XML events, as well as how to use standard SMTP and custom HttpLogger delivery to deliver notifications.


Task 8: Adding the File System Watcher Event Provider

In this step you will accomplish the following:

  • Update the configuration file setting.
  • Configure the file system watcher event provider to enter events into the system, and then rebuild your application.
  • Test the file system watcher event provider.
Update the Configuration File Setting
  1. In Microsoft Windows® Explorer, navigate to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock directory.
  2. Right-click the SetProjectVars.cmd file, and then click Edit.
  3. In the SetProjectVars.cmd file, replace this line:
    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task7.xml

    with this line:

    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task8.xml
  4. Save and close the file.
Configure the File System Watcher Event Provider
  1. In the Solution Explorer pane of Microsoft Visual Studio® .NET, expand the AppDefinition project, and then open the appADF.task8.xml file.
  2. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
          <HostedProvider>
         <ProviderName>StockEP</ProviderName>
         <ClassName>FileSystemWatcherProvider</ClassName>
         <SystemName>%_NSSystem_%</SystemName>
         <Arguments>
            <Argument>
               <Name>WatchDirectory</Name>
               <Value>%_EventsDir_%</Value>
            </Argument>
            <Argument>
               <Name>SchemaFile</Name>
               <Value>%_BaseDirectoryPath_%\AppDefinition\EventsSchema.xsd</Value>
            </Argument>
            <Argument>
               <Name>EventClassName</Name>
               <Value>StockEvents</Value>
            </Argument>
         </Arguments>
      </HostedProvider>
  3. Place your cursor in the ADF, immediately in front of the <NonHostedProviders> start tag.
  4. On the Edit menu, click Paste as HTML to paste the code in the ADF.
  5. Save and close the ADF.
Rebuild the Application
  1. Right-click the AppDefinition project, and then click Rebuild. This drops and recreates the databases, deleting all data that was entered previously.
  2. Scroll through the results displayed in the Output pane to ensure that the Rebuild command succeeded.
Review the XSD Event Schema
  1. In the Solution Explorer pane, locate the EventsSchema.xsd file, and then double-click it to open it.

    This file contains the XSD schema for the StockEvents event class. The file system watcher event provider uses this schema when loading stock events. The XSD event schema must match the /EventClasses/EventClass/Schema section of the ADF defined for the StockEvents event class.

  2. Review and close the file.
Review the Sample Event Data
  1. In the Solution Explorer pane, locate the EventsData.xml file in the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock\Test directory, and then double-click it.

    The EventsData.xml file contains the sample event data, which must match the event schema defined in the /EventClasses/EventClass/Schema section of the ADF and in the EventsSchema.xsd file.

  2. Review the sample event data, and then close EventsData.xml.
Submit Events
Start the NS$StockInstance Service
  1. In the Server Explorer pane, click the Services node.
  2. Right-click NS$StockInstance, and then click Start.
Add Subscriber, Subscriber Device, and Subscription Data
  1. In the Server Explorer pane, right-click the AddSubscribers.vbs script, and then click Open With.
  2. Select the wscript.exe file, and then click Open to run the script.
  3. Right-click the AddSubscriptions.vbs script, and then click Open With.
  4. Select the wscript.exe file again, and then click Open.
Add the Event File to the File Watcher Directory
  1. In Windows Explorer, navigate to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock\Test directory.
  2. Copy the EventData.xml file from that directory to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock\Test\Events subdirectory.

    The file system watcher event provider detects the arrival of the event file. It loads the event data from the file into the event table, and renames the event file with the suffix yyyymmdd-hhmmss.mmm.done to indicate that the event file has been processed successfully.

Stop the NS$StockInstance Service
  1. Allow the service to run for about 60 seconds in order to process the event file.
  2. In the Server Explorer pane, right-click NS$StockInstance, and then click Stop.
View the Quantum Information
Review the ViewQuantum.sql script
  1. In the Server Explorer pane, expand the AppDefinition project.
  2. Right-click the ViewQuantum.sql script, click Open With, click Source Code (Text) Editor, and then click Open.

    The ViewQuantum.sql script runs the NSQuantumList stored procedure to return quantum information.

  3. Review and close the script.
Associate ViewQuantum.sql with SQL Query Analyzer
  1. In the Server Explorer pane, right-click the ViewQuantum.sql script, and then click Open With.
  2. Click Add.
  3. Click Browse, and then navigate to the InstallLocation\Microsoft SQL \80\Tools\Binn\isqlw.exe file.
  4. Select the isqlw.exe file, and then click Open.
  5. Click OK.

    The Add Programs dialog box closes.

  6. Click Set as Default, and then click Close.
Run ViewQuantum.sql

This script allows you to view the quantum information.

  1. In the Server Explorer pane, double-click the ViewQuantum.sql script.

    The script launches in SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. Review the quantum information returned by the query.

    In the result sets, note the value in the QuantumId column for the row that has a value greater than 0 in the EventNotificationsGenerated column.

  4. Open a new query window in SQL Query Analyzer.
  5. From this online Help topic, copy the following Transact-SQL statement, and then paste it in the Query window:
    EXEC NSQuantumDetails QuantumId
  6. Replace the QuantumId argument with the QuantumId value you noted in the NSQuantumList results.
  7. Run the query.
  8. Review the result sets.

    In the third result set, note the value of the EventBatchId column returned for the row that lists StockEvents as the EventClassName value.

View the Events
  1. In the Query window, delete the Transact-SQL statement you added in the previous step, "Run ViewQuantum.sql".
  2. From this online Help topic, copy and paste the following Transact-SQL statement into the Query window:
    EXEC NSEventBatchDetails N'StockEvents', EventBatchId
  3. Replace the EventBatchId argument with the EventBatchId value you noted in the NSQuantumDetails results.
  4. Run the query.
  5. Review event details in the result set.
  6. Close SQL Query Analyzer.
Task 8 Summary

After completing all the steps in this task, you should be able to configure the file system watcher event provider and use it to add events to the system.


Task 9: Adding the Standard SMTP Delivery Protocol

In this step you will accomplish the following:

  • Update the configuration file setting.
  • Configure the Simple Mail Transfer Protocol (SMTP) standard delivery protocol to deliver notifications via e-mail, and then rebuild your application.
  • Test SMTP notification delivery.
Update the Configuration File Setting
  1. In Microsoft Windows® Explorer, navigate to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock directory.
  2. Right-click the SetProjectVars.cmd file, and then click Edit.
  3. In the SetProjectVars.cmd file, replace this line:
    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task8.xml

    with this line:

    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task9.xml
  4. Save and close the file.
Add the SMTP Delivery Channel
  1. In the Solution Explorer pane of Microsoft Visual Studio® .NET, expand the AppDefinition project, and then open the appConfig.task9.xml file.
  2. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
          <DeliveryChannel>
         <DeliveryChannelName>EmailChannel</DeliveryChannelName>
         <ProtocolName>SMTP</ProtocolName>
      </DeliveryChannel>
  3. Place your cursor in the appConfig.task9.xml file, immediately following the end tag of the existing FileChannel delivery channel in the <DeliveryChannels> node.
  4. On the Edit menu, click Paste as HTML to paste the code in the configuration file.
  5. Save and close the configuration file.
Add the SMTP Protocol to the Notification Class
  1. In the Solution Explorer pane, expand the AppDefinition project, and then open the appADF.task9.xml file.
  2. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
                <Protocol>
               <ProtocolName>SMTP</ProtocolName>
               <Fields>
                  <Field>
                     <FieldName>Subject</FieldName>
                     <SqlExpression>&apos;Stock notification: &apos;+CONVERT (NVARCHAR(30), GETDATE())</SqlExpression>
                  </Field>
                  <Field>
                     <FieldName>BodyFormat</FieldName>
                     <SqlExpression>&apos;html&apos;</SqlExpression>
                  </Field>
                  <Field>
                     <FieldName>From</FieldName>
                     <SqlExpression>&apos;sender@adventure-works.com&apos;</SqlExpression>
                  </Field>
                  <Field>
                     <FieldName>Priority</FieldName>
                     <SqlExpression>&apos;Normal&apos;</SqlExpression>
                  </Field>
                  <Field>
                     <FieldName>To</FieldName>
                     <SqlExpression>DeviceAddress</SqlExpression>
                  </Field>
               </Fields>
            </Protocol>
  3. Place your cursor in the ADF, immediately following the end tag of the existing File protocol in the /NotificationClasses/NotificationClass/Protocols section.
  4. On the Edit menu, click Paste as HTML to paste the code in the ADF.
  5. Save and close the ADF.

The application formats the notification content (called the body). The delivery protocol formats the notification message (called the envelope) that encloses the body. The delivery protocol might need information from you in order to format the envelope. This information is specified in the /NotificationClasses/NotificationClass/Protocols/Protocol/Fields section of the ADF. For example, you might need to provide the Subject and Priority values when sending an e-mail message. For more information about setting the SMTP protocol arguments, see SMTP Delivery Protocol.

Rebuild the Application
  1. In the Solution Explorer pane, right-click the AppDefinition project, and then click Rebuild. This drops and recreates the databases, deleting all data that was entered previously.
  2. Scroll through the results displayed in the Output pane to verify that the Rebuild command succeeded.
Stop the Simple Mail Transfer Protocol (SMTP) Service

By stopping the service, you prevent the e-mail message from being sent, ensuring that you can find the formatted e-mail file in the Inetpub\mailroot\Pickup directory.

  1. In Windows 2000, go to Control Panel, open Administrative Tools, and then click Services.

    –or–

    In Windows XP, go to Control Panel, open Performance and Maintenance, open Administrative Tools, and then click Services.

  2. Right-click Simple Mail Transfer Protocol (SMTP), and then click Properties.
  3. In the Startup Type box, select Manual.
  4. Click OK.
  5. Right-click Simple Mail Transfer Protocol (SMTP), and then click Stop.
Generate Notifications for SMTP Delivery
Start the NS$StockInstance Service
  1. In the Server Explorer pane, click the Services node.
  2. Right-click NS$StockInstance, and then click Start.
Add Subscriber, Subscriber Device, and Subscription Data
  1. In the Server Explorer pane, right-click the AddSubscribers.vbs script, and then click Open With.
  2. Select the wscript.exe file, and then click Open to run the script.
  3. Right-click the AddEmailSubscriptions.vbs script, and then click Open With.
  4. Select the wscript.exe file again, and then click Open to run the script.
Submit Events
  1. In the Server Explorer pane, double-click the AddEvents.sql script.

    The script launches in SQL Query Analyzer.

    Note If you skipped Task 3, please refer to the Submit Events section of that task for instructions on associating the AddEvents.sql script with SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. In SQL Query Analyzer, review the event and event batch results returned by NSEventBatchDetails.
  4. Close SQL Query Analyzer.
Stop the NS$StockInstance Service
  1. Allow the service to run for about 2 minutes in order to generate and distribute the notifications.
  2. In the Server Explorer pane, right-click NS$StockInstance, and then click Stop.
View the Notifications
  1. In Windows Explorer, navigate to the Inetpub\mailroot\Pickup directory.

    This directory contains one .eml file for each notification.

  2. Double-click any of the e-mail files.

    The notification opens in Outlook Express.

  3. Review the e-mail notifications.
  4. Delete the .eml files after viewing them.
Task 9 Summary

After completing all the steps in this task, you should be able to configure a delivery channel and a notification class to use the SMTP protocol to deliver notifications.


Task 10: Adding the Custom HttpLogger Delivery Protocol

The HttpLogger task shows you how to configure a custom delivery protocol. For additional information about developing a custom HTTP-based delivery protocol, see Developing a Custom Delivery Protocol.

In this step you will accomplish the following:

  • Update the configuration file setting.
  • Configure the HttpLogger custom delivery protocol to deliver notifications via HTTP, and then rebuild your application.
  • Test HTTP notification delivery.
Update the Configuration File Setting
  1. In Microsoft Windows® Explorer, navigate to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock directory.
  2. Right-click the SetProjectVars.cmd file, and then click Edit.
  3. In the SetProjectVars.cmd file, replace this line:
    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task9.xml

    with this line:

    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task10.xml
  4. Save and close the file.
Add the HTTPLogger Protocol
  1. In the Solution Explorer pane of Microsoft Visual Studio® .NET, expand the AppDefinition project, and then open the appConfig.task10.xml file.
  2. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
       <Protocols>
      <Protocol>
         <ProtocolName>HttpLogger</ProtocolName>
         <ClassName>HttpExtension</ClassName>
      </Protocol>
   </Protocols>
  3. Place your cursor in the configuration file, immediately following the end tag of the <Applications> node.
  4. On the Edit menu, click Paste as HTML to paste the code in the configuration file.
  5. Leave the configuration file open.
Add the HTTPLoggerChannel Delivery Channel
  1. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
       <DeliveryChannel>
         <DeliveryChannelName>HttpLoggerChannel</DeliveryChannelName>
         <ProtocolName>HttpLogger</ProtocolName>
         <Arguments>
            <Argument>
               <Name>ProtocolProviderClassName</Name>
               <Value>NSSamples.HttpLoggerDeliveryProtocol</Value>
            </Argument>
            <Argument>
            <!-- The ProtocolProviderAssemblyName value points
            to the custom provider assembly, which must be created
            before the application is run.  This can be done from
            within Visual Studio by loading the Stock solution,
            right clicking the CustomDeliveryProtocol project
            and choosing Build. -->
            <Name>ProtocolProviderAssemblyName</Name>
            <Value>%BaseDirectoryPath%\CustomDeliveryProtocol\bin\HttpLoggerDeliveryProtocol.dll</Value>
            </Argument>
            <Argument>
               <Name>PostURL</Name>
               <Value>http://localhost/NSSamples/Stock/HttpLogger.aspx</Value>
            </Argument>
            <Argument>
               <Name>UserName</Name>
               <Value>UserThatHasPermissionsToPost</Value>
            </Argument>
            <Argument>
               <Name>Password</Name>
               <Value>Password</Value>
            </Argument>
            <Argument>
               <Name>Encoding</Name>
               <Value>ISO-8859-1</Value>
            </Argument>
            <Argument>
               <Name>ContentType</Name>
               <Value>text/html</Value>
            </Argument>
         </Arguments>
      </DeliveryChannel>
  2. Place your cursor in the configuration file, immediately following the end tag of the existing EmailChannel delivery channel in the <DeliveryChannels> node.
  3. Click Paste as HTML on the Edit menu to paste in the code.
  4. Save and close the configuration file.
Add the HttpLogger Protocol to the Notification Class
  1. In the Solution Explorer pane, expand the AppDefinition project, and then open the appADF.task10.xml file.
  2. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
                <Protocol>
               <ProtocolName>HttpLogger</ProtocolName>
               <Fields>
                  <Field>
                     <FieldName>escaping</FieldName>
                     <SqlExpression>&apos;yes&apos;</SqlExpression>
                  </Field>
                  <Field>
                     <FieldName>Subject</FieldName>
                     <SqlExpression>&apos;Stock notification:&apos;+CONVERT (NVARCHAR(30), GETDATE())</SqlExpression>
                  </Field>
                  <Field>
                     <FieldName>SubscriberId</FieldName>
                     <SqlExpression>DeviceAddress</SqlExpression>
                  </Field>
            </Fields>
            </Protocol>
  3. Place your cursor in the ADF, immediately following the end tag of the existing SMTP protocol in the /NotificationClasses/NotificationClass/Protocols section.
  4. On the Edit menu, click Paste as HTML to paste the code in the ADF.
  5. Save and close the ADF.

The application formats the notification content (the body). The delivery protocol formats the notification message (the envelope) that encloses the body. The delivery protocol might need information from you in order to format the envelope. This information is specified in the /NotificationClasses/NotificationClass/Protocols/Protocol/Fields section of the ADF.

Rebuild the Application
  1. In the Solution Explorer pane, right-click the AppDefinition project, and then click Rebuild. This drops and recreates the databases, deleting all data that was entered previously.
  2. Scroll through the results displayed in the Output pane to ensure that the Rebuild command succeeded.
Rebuild the Subscription Management Application
  1. In the Solution Explorer pane, right-click the Subscribe project, and then click Rebuild.
  2. Scroll through the results displayed in the Output pane to ensure that the Rebuild command succeeded.
Generate Notifications for HTTP Delivery
Start the NS$StockInstance Service
  1. In the Server Explorer pane, click the Services node.
  2. Right-click NS$StockInstance, and then click Start.
Add Subscriber, Subscriber Device, and Subscription Data
  1. In the Server Explorer pane, right-click the AddSubscribers.vbs script, and then click Open With.
  2. Select the wscript.exe file, and then click Open to run the script.
  3. Right-click the AddHttpSubscriptions.vbs script, and then click Open With.
  4. Select the wscript.exe file again, and then click Open to run the script.
Submit Events
  1. In the Server Explorer pane, double-click the AddEvents.sql script.

    The script launches in SQL Query Analyzer.

    Note If you skipped Task 3, please refer to the Submit Events section of that task for instructions on associating the AddEvents.sql script with SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. In SQL Query Analyzer, review the event and event batch results returned by NSEventBatchDetails.
  4. Close SQL Query Analyzer.
Stop the NS$StockInstance Service
  1. Allow the service to run for about 2 minutes in order to generate and distribute the notifications.
  2. In the Server Explorer pane, right-click NS$StockInstance, and then click Stop.
View the Notifications
  1. When the build has completed, open a Web browser, and go to http://localhost/NSSamples/Stock/HttpLogger.aspx.

    Note If you are using Microsoft Internet Explorer, you must configure it to bypass the proxy server for local addresses in order to access this page.

  2. On the Web page, click Test Post .

    The response to the post will report "Successfully saved posted data to DirectoryLocation".

Task 10 Summary

After completing all the steps in this task, you should be able to configure a delivery channel and notification class to use a custom delivery protocol for delivering notifications.


Task 11: Designing the Scheduled Subscription

In this task you will accomplish the following:

  • Review the components that must be added to support scheduled subscriptions.

    In this task you will focus on conceptual issues. You will make no changes to the solution files.

The Stock sample can support scheduled subscriptions, which deliver notifications at the times specified by the subscribers. In the Stock sample, a scheduled subscription notification contains the highest price reached by a specified stock at the time the notification was generated. For example, a subscriber can request a notification at 3:30 P.M. each day containing the highest price reached by Adventure Works Cycles.

For each scheduled subscription, you must specify:

  • The event schema. Both subscription classes use the same events, so you already specified the event schema for the application in Task 2.
  • The scheduled subscription schema.
  • The event chronicle table schema. The event chronicle table stores event data so that it is available at the time that the scheduled subscription comes due.
  • The scheduled notification schema.
  • The event chronicle rule, which updates the event chronicle table each time new events are submitted.
  • The notification generation rule for combining events with scheduled subscriptions to produce notifications. This rule is defined in a /SubscriptionClasses/SubscriptionClass/ScheduledRules/ScheduledRule section of the ADF, because it creates notifications for a scheduled subscription.
  • The XSLT file that determines the appearance of the formatted notification.

You should write down your application design in a design document. For each scheduled subscription, specify the following information. In this task, you will define and document the elements required for a scheduled subscription.

Scheduled subscription schema:

DeviceName nvarchar(255) not null

SubscriberLocale nvarchar(10) not null

StockSymbol nvarchar(6) not null

The DeviceName and SubscriberLocale fields are often kept in the subscription table. They contain subscriber information that must be passed to the notification function when notifications are created.

The StockSymbol field identifies the stock that the subscriber wants to monitor.

There are no fields defined to track the subscription's schedule. Notification Services keeps the schedule information in a separate system table that it creates and manages for you.

For more information about defining subscription fields, see Subscription Fields.

Event chronicle schema:

StockSymbol nvarchar(6) not null

StockPrice decimal(18,5) null

The event chronicle table contains one record for each StockSymbol value. This record contains the highest StockPrice value reached by that stock. When the time specified in the scheduled subscription arrives, the subscription scheduled rule extracts the StockPrice value for the appropriate StockSymbol value from the event chronicle table, and generates a notification containing this price.

Scheduled notification schema:

StockSymbol nvarchar(6) not null

StockPrice decimal(18,5) null

The notification fields for this notification schema are identical to those of the notification schema related to the event-driven subscription. The difference between these schemas is in the XSLT file used for formatting.

Event chronicle rule:

The event chronicle rule updates the event chronicle when a new StockSymbol value appears or a stock price reaches a new high.

/*Insert symbol if not already in the chronicle.*/
INSERT INTO StockEventsChron (StockSymbol, StockPrice)
SELECT e.StockSymbol, e.StockPrice
FROM StockEvents e
WHERE e.StockSymbol NOT IN (SELECT StockSymbol from StockEventsChron)
/*Update value in the chronicle if the event price is greater than the value in the chronicle.*/
UPDATE StockEventsChron
SET StockPrice = e.StockPrice
FROM StockEvents e, StockEventsChron c
WHERE e.StockSymbol = c.StockSymbol AND e.StockPrice > c.StockPrice
Subscription scheduled notification generation rule:

Select the stock price from the event chronicle table based on matching the subscription and event chronicle stock symbols.

SELECT e.StockSymbol, e.StockPrice
FROM StockEventsChron e, PortfolioSubscriptions s
WHERE e.StockSymbol = s.StockSymbol
XSLT file:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="notifications">
      <html>
         <body>
            <xsl:apply-templates/>
            <i>
            Thank you for using SQL Server Notification Services.
            </i><br/><br/>
         </body>
      </html>
   </xsl:template>
   <xsl:template match="notification">
      <b><xsl:value-of select="StockSymbol" /></b> highest trade:       <b>$<xsl:value-of select="StockPrice" /></b><br/>
      Click here to see the quote detail:
      <a>
         <xsl:attribute name="href">
   http://moneycentral.msn.com/scripts/webquote.dll?ipage=qd&amp;Symbol=<xsl:value-of select='StockSymbol'/>
         </xsl:attribute>
   http://moneycentral.msn.com/scripts/webquote.dll?ipage=qd&amp;Symbol=<xsl:value-of select="StockSymbol"/>
      </a>
      <br/><br/>
   </xsl:template>
</xsl:stylesheet>
Task 11 Summary

After completing all the steps in this task, you should understand the basic concepts used in designing a scheduled subscription class.


Task 12: Adding the Event Chronicle Table

In this step you will accomplish the following:

  • Update the configuration file setting.
  • Add an event chronicle table and an event chronicle rule to the application definition file (ADF), and then rebuild your application.
  • Submit events using simple test scripts, and then verify that the event chronicle table is being updated.
Update the Configuration File Setting
  1. In Microsoft Windows® Explorer, navigate to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock directory.
  2. Right-click the SetProjectVars.cmd file, and then click Edit.
  3. In the SetProjectVars.cmd file, replace this line:
    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task10.xml

    with this line:

    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task12.xml
  4. Save and close the file.
Add the Event Chronicle Table and Rule
  1. In the Solution Explorer pane of Microsoft Visual Studio® .NET, expand the AppDefinition project, and then open the appADF.task12.xml file.
  2. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
             <ChronicleRule>
            <RuleName>StockEventsChronRule</RuleName>
            <Action>
            INSERT INTO StockEventsChron (StockSymbol, StockPrice)
            SELECT e.StockSymbol, e.StockPrice
            FROM StockEvents e
            WHERE   e.StockSymbol
            NOT IN (SELECT StockSymbol from StockEventsChron)
            UPDATE StockEventsChron
            SET StockPrice = e.StockPrice
            FROM StockEvents e, StockEventsChron c
            WHERE   e.StockSymbol = c.StockSymbol
            AND e.StockPrice &gt; c.StockPrice
            </Action>
            <ActionTimeout>P0DT0H10M10S</ActionTimeout>
         </ChronicleRule>
         <Chronicles>
            <Chronicle>
               <ChronicleName>StockEventsChronRule</ChronicleName>
               <SqlSchema>
                  <SqlStatement>
                  IF EXISTS(
                  SELECT name
                  FROM dbo.sysobjects
                  WHERE name = &apos;StockEventsChron&apos;)
                  DROP TABLE dbo.StockEventsChron
                  CREATE TABLE StockEventsChron
                  (
                     [StockSymbol] nvarchar(6),
                     [StockPrice] decimal(18,5)
                  )
                  </SqlStatement>
               </SqlSchema>
            </Chronicle>
         </Chronicles>
  3. Place your cursor in the ADF, immediately following the end tag of the existing EventClasses/EventClass/IndexSqlSchema section.
  4. On the Edit menu, click Paste as HTML to paste the code in the file.
  5. Save and close the ADF.
Rebuild the Application
  1. In the Solution Explorer pane, right-click the AppDefinition project, and then click Rebuild. This drops and recreates the databases, deleting all data that was entered previously.
  2. Scroll through the results displayed in the Output pane to ensure that the Rebuild command succeeded.
Submit Initial Events and Review the Chronicle Data
Start the NS$StockInstance Service
  1. In the Server Explorer pane, click the Services node.
  2. Right-click NS$StockInstance, and then click Start.
Submit Events
  1. In the Server Explorer pane, double-click the AddEvents.sql script.

    The script launches in SQL Query Analyzer.

    Note If you skipped Task 3, please refer to the Submit Events section of that task for instructions on associating the AddEvents.sql script with SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. In SQL Query Analyzer, review the event and event batch results returned by NSEventBatchDetails.
  4. Close SQL Query Analyzer.
Review the Event Chronicle Table Data
  1. Wait about 60 seconds.
  2. In the Server Explorer pane, navigate to the StockInstanceStock database.
  3. Right-click Tables, and then click Refresh.
  4. Right-click the StockEventsChron table, and then click Retrieve Data from Table.

    Review the data in the table; it should contain the following values:

    StockSymbol | StockPrice
    AWKS | 67.68
    ADCP | 90
    ASHK | 19
  5. Close the table when you are finished.
Submit Additional Events and Review the Chronicle Data
Submit Events
  1. In the Server Explorer pane, double-click the AddMoreEvents.sql script.

    The script launches in SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. Close SQL Query Analyzer when the script finishes.
Review the Updated Event Chronicle Table Data
  1. Wait for about 60 seconds.
  2. In the Server Explorer pane, navigate to the StockInstanceStock database.
  3. Right-click Tables, and then click Refresh.
  4. Right-click the StockEventsChron table, and then click Retrieve Data from Table.

    Review the data in the table; it should contain the following values:

    StockSymbol | StockPrice
    AWKS | 70
    ADCP | 90
    ASHK | 19

    Only the price of AWKS has changed.

  5. Close the table when you are finished.
Stop the Notification Services service
  • In the Server Explorer pane, right-click NS$StockInstance, and then click Stop.
Task 12 Summary

After completing all the steps in this task, you should have an understanding of how to use chronicle tables to save event information for use with scheduled subscriptions.


Task 13: Adding the Scheduled Subscription Class

In this step you will accomplish the following:

  • Update the configuration file setting.
  • Add a scheduled subscription class, a scheduled notification generation rule, and a scheduled notification class to the ADF, and then rebuild your application.
  • Add scheduled subscriptions using a simple test script.
Update the Configuration File Setting
  1. In Microsoft Windows® Explorer, navigate to the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock directory.
  2. Right-click the SetProjectVars.cmd file, and then click Edit.
  3. In the SetProjectVars.cmd file, replace this line:
    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task12.xml

    with this line:

    set NSConfigFile=%BaseDirectoryPath%\AppDefinition\appConfig.task13.xml
  4. Save and close the file.
Add the Scheduled Subscription Class
  1. In the Solution Explorer pane of Microsoft Visual Studio® .NET, expand the AppDefinition project, and then open the appADF.task13.xml file.
  2. From this online Help topic, select the following code lines, right-click in the selection, and then click Copy.
          <SubscriptionClass>
         <SubscriptionClassName>
         PortfolioSubscriptions
         </SubscriptionClassName>
         <Schema>
            <Field>
               <FieldName>DeviceName</FieldName>
               <FieldType>nvarchar(255)</FieldType>
               <FieldTypeMods>not null</FieldTypeMods>
            </Field>
            <Field>
               <FieldName>SubscriberLocale</FieldName>
               <FieldType>nvarchar(10)</FieldType>
               <FieldTypeMods>not null</FieldTypeMods>
            </Field>
            <Field>
               <FieldName>StockSymbol</FieldName>
               <FieldType>nvarchar(6)</FieldType>
               <FieldTypeMods>not null</FieldTypeMods>
            </Field>
         </Schema>
         <IndexSqlSchema>
            <SqlStatement>
            CREATE INDEX PortfolioSubscriptionsIndex
            ON PortfolioSubscriptions ( StockSymbol )
            </SqlStatement>
         </IndexSqlSchema>
         <ScheduledRules>
            <ScheduledRule>
               <RuleName>PortFolioSubscriptionsRule</RuleName>
               <Action>
               SELECT dbo.StockNotificationsNotify(
               s.SubscriberId, s.DeviceName, s.SubscriberLocale,
               e.StockSymbol, e.StockPrice)
               FROM StockEventsChron e, PortfolioSubscriptions s
               WHERE e.StockSymbol = s.StockSymbol
               </Action>
            </ScheduledRule>
         </ScheduledRules>
      </SubscriptionClass>
  3. Place your cursor in the ADF, immediately following the end tag of the existing SubscriptionClasses/SubscriptionClass section.
  4. On the Edit menu, click Paste as HTML to paste the code in the file.
  5. Leave the ADF open.
Add the Scheduled Notification Class
  1. Copy the following code.
          <NotificationClass>
         <NotificationClassName>
         PortfolioNotifications
         </NotificationClassName>
         <Schema>
            <Fields>
               <Field>
                  <FieldName>StockSymbol</FieldName>
                  <FieldType>nvarchar(6)</FieldType>
               </Field>
               <Field>
                  <FieldName>StockPrice</FieldName>
                  <FieldType>decimal(18,5) </FieldType>
               </Field>
            </Fields>
         </Schema>
         <ContentFormatter>
            <ClassName>XsltFormatter</ClassName>
            <Arguments>
               <Argument>
                  <Name>XsltBaseDirectoryPath</Name>
                  <Value>%_BaseDirectoryPath_%\AppDefinition</Value>
               </Argument>
               <Argument>
                  <Name>XsltFileName</Name>
                  <Value>PortfolioSummary.xslt</Value>
               </Argument>
            </Arguments>
         </ContentFormatter>
         <DigestDelivery>true</DigestDelivery>
         <MulticastDelivery>false</MulticastDelivery>
         <Protocols>
            <Protocol>
               <ProtocolName>File</ProtocolName>
            </Protocol>
            <Protocol>
               <ProtocolName>SMTP</ProtocolName>
               <Fields>
                  <Field>
                     <FieldName>Subject</FieldName>
                     <SqlExpression>&apos;Portfolio notification: &apos;+CONVERT (NVARCHAR(30), GETDATE())</SqlExpression>
                  </Field>
                  <Field>
                     <FieldName>BodyFormat</FieldName>
                     <SqlExpression>&apos;html&apos;</SqlExpression>
                  </Field>
                  <Field>
                     <FieldName>From</FieldName>
                     <SqlExpression>&apos;sender@adventure-works.com&apos;</SqlExpression>
                  </Field>
                  <Field>
                     <FieldName>Priority</FieldName>
                     <SqlExpression>&apos;Normal&apos;</SqlExpression>
                  </Field>
                  <Field>
                     <FieldName>To</FieldName>
                     <SqlExpression>DeviceAddress</SqlExpression>
                  </Field>
               </Fields>
            </Protocol>
         </Protocols>
         <ExpirationAge>PT2H</ExpirationAge>
      </NotificationClass>
  2. Place your cursor in the ADF, immediately following the end tag of the existing NotificationClasses/NotificationClass section.
  3. On the Edit menu, click Paste as HTML to paste the code in the file.
  4. Save and close the ADF.
Rebuild the application
  1. In the Solution Explorer pane, right-click the AppDefinition project, and then click Rebuild. This drops and recreates the databases, deleting all data that was entered previously.
  2. Scroll through the results displayed in the Output pane to verify that the Rebuild command succeeded.
Add Subscriber, Subscriber Device, and Scheduled Subscription Data
  1. In the Solution Explorer pane, right-click the AddSubscribers.vbs script, and then click Open With.
  2. Select the wscript.exe file, and then click Open to run the script.
  3. Right-click the AddScheduledSubscriptions.vbs script, and then click Open With.
  4. Select the wscript.exe file again, and then click Open to run the script.

    The script runs for about a minute. It adds one subscription for every minute of the day, for a total of 1440 scheduled subscriptions. By adding all these subscriptions, you ensure that the application will generate a scheduled notification within one minute, regardless of when you run it.

View the Scheduled Subscription Information
  1. Open SQL Query Analyzer, and select StockInstanceStock from the list on the toolbar.
  2. From this online Help topic, copy the following Transact-SQL statement, and then paste it in the Query window:
    EXECUTE NSScheduledSubscriptionDetails N'PortfolioSubscriptions', 'StartTime', 'EndTime'
  3. Replace the StartTime and EndTime arguments with time values spanning the current day, for example '2002-06-12 00:00:00' and '2002-06-12 23:59:'59'.
  4. Run the query.
  5. Look at the result set to review the subscription information.

    Note the subscriber ID for one of the rows returned.

  6. Delete the Transact-SQL statement.
  7. From this online Help topic, copy the following Transact-SQL statement, and then paste it in the Query window:
    EXEC NSScheduledSubscriptionList N'subscriberId', 'StartTime', 'EndTime'
  8. Replace the subscriberId argument with the subscriber ID you noted in step 5; replace StartTime and EndTime with time values spanning the current day, for example, '2002-06-12 00:00:00' and '2002-06-12 23:59:'59'.
  9. Run the query.
  10. Look at the result set to review the detailed subscription information for one subscriber.
  11. Close SQL Query Analyzer.
Start the NS$StockInstance Service
  1. In the Server Explorer pane, click the Services node.
  2. Right-click NS$StockInstance, and then click Start.
Generate Scheduled Notifications
Submit Events
  1. In the Server Explorer pane, double-click the AddEvents.sql script.

    The script launches in SQL Query Analyzer.

    Note If you skipped Task 3, please refer to the Submit Events section of that task for instructions on associating the AddEvents.sql script with SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. Review the event and event batch results returned by NSEventBatchDetails.
  4. Close SQL Query Analyzer.
Stop the NS$StockInstance Service
  1. Allow the service to run for about 2 minutes in order to generate and distribute the notifications.
  2. In the Server Explorer pane, right-click NS$StockInstance, and then click Stop.
View the Scheduled Notifications
  1. Using Microsoft Notepad, open the InstallLocation\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock\Test\Test1\Notifications\StockNotification.txt file.
  2. Review the StockNotification.txt contents.
  3. Close and delete the file.
Task 13 Summary

After completing all the steps in this task, you should have a working scheduled subscription class in your application, and have the system populated with data from associated subscribers, subscriber devices, and subscriptions.


Task 14: Reviewing the Subscription Management Application

In this task you will accomplish the following:

  • Review the sample subscription management application code.
  • Test the subscription management application.
Review the Code
  1. In the Solution Explorer pane of Microsoft Visual Studio® .NET, expand the AppDefinition project, and then double-click the Default.aspx file.

    The file opens. This file implements the sample subscription management application.

  2. On the View menu, click Code.

    The Default.aspx.cs file opens.

  3. Review the subscription management application code.
  4. Close the Default.aspx.cs and Default.aspx files.
Rebuild the Subscription Management Application
  1. In the Solution Explorer pane of Microsoft Visual Studio, right-click Subscribe, and then click Rebuild.
  2. Scroll through the results displayed in the Output pane to verify that the Rebuild command succeeded.
Test the Subscription Management Application
  1. Open a Web browser, and go to http://localhost/nssamples/stock.

    The application displays the Stock Alerts Sample Web page in Internet Explorer.

  2. In the Stock symbol field, enter ADCP.
  3. In the Alert me when the price goes above field, enter 50.
  4. Click Alerts SignUp.
  5. Close the Web browser.
View Subscriber and Subscriber Device Information
  1. In the Solution Explorer pane, double-click the ViewSubscribersAndDevices.sql script.

    The script launches in SQL Query Analyzer.

    Note If you skipped Task 4, please refer to the View Subscriber and Subscriber Device Information section of that task for instructions on associating the ViewSubscribersAndDevices.sql script with SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. Review the subscriber and subscriber device information returned by the query.
  4. Close SQL Query Analyzer.
View the Subscriptions
  1. In the Server Explorer pane, double-click the ViewSubscriptions.sql script.

    The script launches in SQL Query Analyzer.

    Note If you skipped Task 4, please refer to the View Subscription Information section of that task for instructions on associating the ViewSubscriptions.sql script with SQL Query Analyzer.

  2. Connect to SQL Server in SQL Query Analyzer, and then click the green arrow button on the toolbar to run the script.
  3. Review the subscription information returned by the query.
  4. Close SQL Query Analyzer.
Task 14 Summary

After completing all the steps in this task, you should be able to input subscriber and subscription information through the subscription management application.


Walkthrough Summary

You have completed the Notification Services walkthrough - congratulations! You should now have a working Stock application that performs all the following actions:

  • Accepts events from a file system watcher event provider.
  • Accepts subscriber, subscriber device, and subscription data from a Web application.
  • Produces both event-driven and scheduled subscriptions.
  • Outputs formatted notifications.
  • Uses both the standard SMTP delivery protocol and a custom HttpLogger delivery protocol to create notification messages and hand them off to external delivery systems for delivery.


Building Notification Services Applications

The Building Notification Services Applications section provides information about defining and developing the components needed to create an application in Microsoft® SQL Server™ Notification Services.

The topics that this section covers are described in the following table.

Topic | Description
Introducing Notification Services Programming | Reviews aspects of system workflow that affect development. Also discusses developer responsibilities and development planning.
Application Settings | Discusses the available application settings, and how to define them in the application definition file (ADF).
Events | Discusses how to define an event class, and how event providers are used to provide event data to the system. Reviews the standard event providers that are ship with Notification Services.
Subscriptions | Discusses how to define a subscription class.
Notifications | Discusses how to define a notification class. Also discusses how content formatters are used to format notification data, and how delivery channels make use of delivery protocols to route notification messages for delivery. Reviews the standard content formatter and delivery protocols that are shipped with Notification Services.
Instance and Application APIs | Provides examples of how to use the Notification Services classes that provide access to Notification Services instances and applications.
Developing Subscription Management Applications | Provides examples of how to use the Notification Services classes that permit creation and maintenance of subscription-related data.
Developing Custom Notification Services Components | Provides examples of how to use the Notification Services classes and interfaces to develop custom event providers, content formatters, and delivery protocols.
Notification Services Programming Samples | Provides information about the sample applications provided with Notification Services.


Introducing Notification Services Programming

Notification services are key to getting important information to users when they want it, wherever they are. There is a wide variety of possible notification applications. One organization might use them to increase traffic at an e-commerce site by notifying customers of sale items. Another might use them to push corporate information, like meeting reminders or sales information, out to its employees.

Notification Services allows you to create and deploy notification applications quickly and easily. The Notification Services APIs streamline the input of event, subscriber, and subscription data. The Notification Services engine provides functions to seamlessly generate, format, and route notifications to external delivery systems based on this information.

Notification Services is designed to integrate with existing notification delivery services. Notification Services hands notification messages to these services for transport to the subscriber's target device. SMS phone delivery is a good example of an external delivery service, although this service is not required for a Notification Services application.

Some of the benefits of programming with the Notification Services framework are:

  • Speed of development: An application can be prototyped in days rather than months.
  • Cost of development: Most of the underlying application requirements are provided by the Notification Services infrastructure, so you can concentrate on the details of your applications.
  • Ability to leverage existing knowledge: Notification Services uses popular technologies like Transact-SQL, XML, and the Microsoft .NET Framework to implement its components. You do not have to learn a proprietary language to create Notification Services applications.
  • Programmability: Event providers, subscription management applications, and notification formatting and delivery mechanisms can be tailored to your business needs. The Notification Services APIs can be used to capture data from any new or existing application that you create.

The topics that the Introducing Notification Services Programming section covers are described in the following table.

Topic | Description
Notification Services System | Reviews the components that make up a Notification Services system, and discusses the basic workflow.
Developer Responsibilities | Discusses the Notification Services components that the application developer must provide.


Notification Services System

The Notification Services system provides a standardized way to collect event and subscription data, and then produce notifications based on this information.

  1. Information about subscribers, subscriber devices, and subscriptions comes into the system through a subscription management application, which uses the Notification Services APIs to submit this information to the system.
  2. Events are submitted to the system in batches by an event provider, which is optionally hosted by the Notification Services provider host component.
  3. The Notification Services generator uses rules to match events with subscriptions. Each firing of a notification generation rule produces a batch of notifications.
  4. The Notification Services distributor then passes the raw notification data to a content formatter to be formatted, and then passes the formatted notification data to a delivery protocol to be packaged into messages. Finally the messages are handed off to one or more external delivery systems for delivery to subscriber devices.

For more information about how the Notification Services architecture works, see Notification Services Architecture.


Notification Services Components

A Notification Services application runs on a platform based on the Notification Services engine and SQL Server. Many applications also use Internet Information Services (IIS) to host their subscription management application or custom event providers, although this is not required, and is not provided as part of Notification Services.

A Notification Services application is composed of six primary components:

  • The Notification Services platform, consisting of the Notification Services engine (which contains the provider host, generator, and distributor components) and the Notification Services SQL Server databases. The platform stores system data and provides functions for notification generation and distribution.
  • Two metadata files: the configuration file, which describes the configuration information for a Notification Services instance, and the application definition file (ADF), which defines the data and structure of a Notification Services application. When NSControl Create is run, it uses these files to set up the Notification Services instance and applications, including the SQL Server tables and other objects.
  • The subscription management application, which manages subscriber and subscription information and adds, updates, and deletes it in Notification Services.
  • One or more event providers, which gather event data and submit it to Notification Services.
  • One or more content formatters, which take raw notification data after it has been generated and format it appropriately for display on the target device.
  • One or more delivery protocols, which create a notification message and then route the message to the external delivery service that delivers the message to the target device.


Notification Generation Process

Notification Services uses database processing to manage large volumes of data, subscriptions, events, and notifications. The purpose of a Notification Services application is to generate notifications for delivery to subscribers. The notification generation process flows as follows.

Event information comes into the system through one or more event providers, which might operate in conjunction with the provider hosting function of the Notification Services engine. This information can come in randomly, as events occur that meet particular criteria, or it can be inserted on a scheduled basis. Older event data that has already been used to generate notifications can be cleaned out of the system using the vacuumer.

Subscriber and subscription information comes into the system through a subscription management application that the developer provides. This information is entered as end users choose to subscribe to a notification service, rather than on any sort of scheduled basis.

The generator function of the Notification Services engine matches the event and subscription data by using a notification generation rule. Firing this rule produces new batches of notification data based on the results. The generator is run on a scheduled basis, which is determined by the developer or system administrator and specified in the application definition file (ADF).

The distributor function of the Notification Services engine formats the notification data, and then distributes the resulting notifications. The distributor is run on a scheduled basis, as determined by the system administrator. Older notification data that has already been used to generate notifications can be cleaned out of the system using the vacuumer.

See Also

Generating Notifications

Using Notification Generation Rules


Batching in the Notification Services System

Wherever possible, Notification Services data is handled in batches for the sake of efficiency. Event data and notification data are both batched.

When a single event is written to the system and there is not an event batch open, then one is created automatically. The initial event and subsequent events are associated with this batch. The event provider that is providing these events must be programmed to close the current event batch periodically. When this batch of events is closed, the associated events are submitted for use in notification generation. A new event batch is created with the next new event submission, and the cycle starts again.

When events are written to the system as a group, each group is automatically assigned an event batch. When the writing process is completed, the event batch is closed and becomes available for notification generation.

Notification batches are automatically generated and closed by the generator function. No API access is provided to notification batches. However, if you use Notification Services Enterprise Edition, you can configure the size of notification batches to meet your application requirements.

Each time the notification generation process is started, a new notification batch record is created. Each notification record generated from that point in time until the process has finished will be associated with this batch. When processing is complete, the current notification batch is closed. This makes the notifications in this batch available for processing by the distributor. A new notification batch record is then created the next time the notification generation process is started, and the cycle starts again.


Developer Responsibilities

The application developer is responsible for designing the Notification Services application, and then creating those elements that require programming. The system administrator is responsible for installing, configuring, and managing Notification Services. The individuals serving in these roles must work together when planning the system, to ensure that the system is written and configured to be optimal for their particular environment and business purposes.

Developer Responsibilities

You are responsible for the following activities in the order presented:

  1. Plan for the application. This includes making decisions about the application design, as well as working with the system administrator to make sure the hardware and networking resources allocated for the application are sufficient. For more information about application planning, see Planning for Notification Services Development. For more information about planning for the system, including database resources, see Planning for Notification Services System.
  2. Create the application. You do this by creating an application definition file (ADF) that defines the application. You can construct a new file, or copy an ADF from the Notification Services sample applications to use as a template. There should also be a configuration file that defines the Notification Services instance, which the system administrator is responsible for developing. For more information about the ADF, see Application Definition File Reference. For more information about the configuration file, see Configuration File Reference.
  3. Run the NSControl utility, which takes the information supplied in the ADF and the configuration file and creates the instance and application databases. These databases are created containing all of the objects (tables, stored procedures, etc.) needed to store application data and encapsulate application logic. For more information about using NSControl, see NSControl Commands.
  4. Write a subscription management application that allows users to sign up to receive notifications. Many subscription management applications are Web based. The subscription management application accepts and validates information about the subscribers; the target devices that subscribers are using for notification delivery; and subscriptions, which specify the information that the subscribers want to receive. For more information, see Developing Subscription Management Applications.
  5. Perform the development needed to produce any custom event providers, content formatters, or delivery protocols that are required by your system. For more information, see Developing Custom Notification Services Components.
  6. Install Notification Services on the servers allocated to host the application. Deploy a test version of your application, and then deploy a production version once testing is complete. For more information about deployment, see Deployment Architecture.

    Note Notification Services provides a number of stored procedures to assist you in testing and troubleshooting your application. For more information, see Stored Procedure Reference.

See Also

Deploying and Administering Notification Services

System Architecture


Planning for Notification Services Development

Metrics concerning the expected type and volume of input and output from your application are important to consider before you begin the implementation of your Notification Services application. Careful review of these metrics in combination with a thorough analysis of requirements for your proposed application will allow you to develop a system that successfully meets your business goals.

Planning Checklist

Use the following questions as a guide when you plan your application.

What are the schemas of the events and subscriptions you want your application to accept, and the notifications you want it to produce? What are the schemas of any chronicle tables you want to use?

Getting all the schemas right can prevent you from having to make updates to your application later. In a production environment, making application updates can involve inconvenient manual data migration between the old and the rebuilt tables.

Also consider how your event, subscription, and chronicle schemas affect your application rules. These schemas are used to create the event, subscription, and chronicle tables you reference in your Transact-SQL rules. Make sure that your rules can be expressed with as few joins and as short a WHERE clause as is possible with your data. Good table design leads to optimized rules, which in turn provide better application performance. Also, knowing the structure of your rules early on can help you make good decisions regarding whether and how to index any of these tables.

What is the configuration of the SQL Server instance that you want to use to host the Notification Services application database?

Work with your database administrator to learn how the SQL Server instance is deployed and configured. Use this information in the application definition file (ADF) to specify values in the <Database> node that will provide the best performance and reliability for your application.

What technologies do you plan to use to implement your subscription management application?

You can implement your subscription management application in managed code using the Microsoft .NET Framework and any of the languages it supports. A managed code application can directly access the Notification Services classes. You can also implement it in unmanaged code like Microsoft ASP pages, Microsoft Visual Basic®, or Microsoft C++®, using .NET COM wrappers to access the Notification Services APIs. Determining which implementation to use helps you determine what technologies you must install on each server, and can help you plan better for scaling and failover.

How much data do you expect to have in the system, both initially and after the application has been deployed for a while?

Estimate the number of records expected in each of the Notification Services tables. Knowing this can help you to appropriately plan for optimizing execution times for rule queries, creating SQL Server indexes and filegroups for your tables, and setting values for the generator and distributor functions.

Knowing the expected size of the event, chronicle, and notification tables can also help you plan an appropriate vacuuming schedule for removing obsolete data from your system to improve performance.

Do you want to offer scheduled notifications, event-driven notifications, or both?

The two types of notifications have some differences in implementation. Knowing which types you want to offer helps you plan a realistic development schedule.

What size in kilobytes do you expect an average notification record to be?

Knowing the size range of notification records and resultant notification messages can help you determine realistic delivery times based on the delivery protocols you choose to implement.

What volume of notifications do you expect to deliver, for both base times and peak times?

Volume information can help you gauge expected application performance. For instance, you will want to verify that the delivery mechanism you decide on is capable of processing that volume of notifications in a timely manner. It can also help you determine the optimal values for the application execution settings in the application definition file (ADF).

Do you want to use standard Notification Services components, or do you plan to implement custom components?

Custom components can provide very specific and powerful functionality for your application, but they take additional resources to design, develop, and test.

Do you need to integrate the Notification Services application with external databases or third-party applications?

Integration requirements can affect many aspects of the Notification Services application, such as system performance, data formatting options, and notification delivery.


Common System Configurations

Considering the common configurations can be helpful when planning for your notification application. While there are many possible configurations for a Notification Services system, four configurations are particularly common. Each of these configurations has its strengths, and is recommended for particular business scenarios.

Single Server

In a single-server configuration, all components run on one server, which is typically a 2-CPU or 4-CPU server. This includes SQL Server, and all the Notification Services engine components (the provider host, generator, and distributor). This server also acts as the Web server for the subscription management application.

This configuration is recommended for smaller Notification Services applications that operate within an intranet. It is not recommended for Internet applications, due to the security issues raised by having the Web server and the database on the same server.

Application Server/Web Server

In an application server/Web server configuration, all components are divided across two servers. The SQL Server database and all Notification Services engine components (the provider host, generator, and distributor) run on one server, which is typically a 2-CPU or 4-CPU server. The other server acts as the Web server for the subscription management application.

This configuration is recommended for small Internet applications, which are likely to require that their subscription management applications reside on a Web server located outside the company firewall. It is also recommended for medium-sized intranet applications, where the resources needed for the application would be too much for a single server.

Database Server/Application Server/Web Servers

In this configuration, all components are divided among three or more servers. SQL Server runs on one server, and all the Notification Services engine components (the provider host, generator, and distributor) run on another server. These servers are typically 4-CPU servers. One or more additional servers act as Web servers for the subscription management application.

This is the most common configuration for large intranet applications and medium-to-large Internet applications.

Database Server/Application Server/Web Servers plus Failover

Customers who are especially concerned about availability can use SQL Server failover clustering. This allows several servers to be associated, so that the database can failover from one server to another if an error occurs. The Notification Services engine components (the provider host, generator, and distributor) can run on a separate server, with an additional backup server available for failover of these application functions. One or more additional servers act as Web servers for the subscription management application. The servers used in this configuration are typically 4-CPU servers, at least for the database and application components.

This configuration is recommended for large intranet applications and medium–to-large Internet applications that require high availability.

See Also

For more information about SQL Server clustering, see "Failover Clustering" in SQL Server Books Online.


Application Creation

The typical course of development for a Notification Services application is as follows:

  1. Design the application by creating an application definition file (ADF) that defines the application.
    1. Specify one or more event classes in the ADF. Each event class corresponds to one particular kind of event accepted by the application. For more information, see Defining an Event Class.
    2. Specify one or more notification classes in the ADF. Each notification class corresponds to one particular kind of notification generated by the application. For more information, see Defining a Notification Class.
    3. Specify one or more subscription classes in the ADF. Each subscription class corresponds to one particular kind of subscription accepted by the application. Specifying a subscription class includes writing rules, which are Transact-SQL statements that either generate notifications or update chronicle tables. Rules are invoked when an event provider submits a new batch of events, or on a scheduled basis, depending on the rule type. For more information, see Defining a Subscription Class.
    4. Create one or more notification generation rules (in a subscription class in an ADF) that will match your event data with your subscription data to produce notifications. For more information, see Subscription Rules.
  2. Make sure that a configuration file exists for the Notification Services instance that will host your application. Creating the configuration file is usually the task of the system administrator. For more information about creating the configuration file, see Creating a Configuration File.
  3. Build the application using the NSControl utility. This utility takes all of the information specified in the ADF, and sets up the SQL Server database and tables needed for the application. For example, an event table is created for each event class you define, and a subscription table is created for each subscription class you define. For more information, see NSControl Commands.
  4. Write some simple scripts, for example in Transact-SQL or Microsoft Visual Basic®, to enter sample subscriber, subscriber device, subscription, and event data that conforms to the requirements of your application.
  5. Run this basic version of your application to test your notification generation rules and make sure they are producing notifications as expected. For this step, use the NoOp.xslt file (available in the programming sample applications provided with Notification Services) with the standard XSLT content formatter, and the standard File delivery protocol, to make the notifications very easy to produce.
  6. Create or modify a subscription management application to submit information about subscribers, subscriber devices, and subscriptions to the system with the Notification Services APIs. For more information, see Developing Subscription Management Applications.
  7. Define an event provider that monitors an external entity and generates an event each time something noteworthy happens. You can configure one of the standard event providers included with Notification Services, or develop a custom event provider tailored to your specific business needs. For more information about deploying a standard event provider, see Standard Event Providers. For details about creating a custom event provider, see Developing a Custom Event Provider.
  8. Optionally, create one or more XSLT files for use by the standard XSLT content formatter. These XSL transforms are used to format the raw notification data appropriately for display, based on the language, locale, and device type of the recipient. Alternatively, you can develop a custom content formatter tailored to your specific business needs. For more information about using the standard XSLT content formatter, see XSLT Content Formatter. For details about creating a custom content formatter, see Developing a Custom Content Formatter.
  9. Complete the application settings in the ADF, to optimize application performance and manage system resource consumption. For more information, see Application Settings.
  10. Optionally, develop a custom delivery protocol tailored to your specific business needs. For details about creating a custom delivery protocol, see Developing a Custom Delivery Protocol.
  11. Test and then deploy your application. For more information about deployment, see Deployment Architecture.

    Note Notification Services provides a number of stored procedures to assist you in testing and troubleshooting your application. For more information, see Stored Procedure Reference.


Notification Services Programming Interfaces

Notification Services components use several programming interfaces. Here is an overview of the technologies necessary for developing each component:

Application definition files (ADFs)

XML

ADFs are developed and maintained as XML documents. Configuration files are also developed and maintained using XML.

Transact-SQL

Transact-SQL queries are used to create application rules, which govern notification generation as well as maintenance of application data within a Notification Services instance. Transact-SQL statements can also be used in the definitions of indexes and chronicle tables in the ADF.

Subscription management application

Notification Services APIs

Managed code classes that allow you to add, update, and delete subscribers, subscriber devices, and subscriptions. These APIs can be used from managed code, and through COM interop from unmanaged code.

File system watcher event provider (optional)

XML

Events submitted to the file system watcher event provider must be in XML format.

XSD

The file system watcher event provider requires the developer to provide a SQL-annotated XML schema file that describes the structure of the events contained in the XML files it processes.

SQL Server event provider (optional)

Transact-SQL

Transact-SQL event collection stored procedures are automatically created for each Notification Services application that is created. The standard SQL Server event provider uses these stored procedures along with Transact-SQL queries that you provide to submit SQL Server data as events.

XSLT content formatter (optional)

XSLT

The standard XSLT content formatter requires one or more XSLT files to apply to the raw notification data in order to produce formatted content. Applications that use custom content formatters are not required to use XSLT.

Custom event providers, content formatters, and delivery protocols

Notification Services APIs

Managed code classes and interfaces allow you to create custom components that interoperate with Notification Services. They can be used from managed code, and through COM interop from unmanaged code.

Transact-SQL

Transact-SQL event collection stored procedures are automatically created for each Notification Services application that is created. You can use these stored procedures along with any Transact-SQL queries you provide to create custom event providers that submit SQL Server data as events.


COM Interop with Notification Services

All Notification Services APIs are developed in managed code. However, the majority of Notification Services classes have been developed to be used from unmanaged code as well, through COM interop. If you are integrating notification services into an existing unmanaged application, then you will probably need to continue to use unmanaged code for your subscription management application. The COM interop solution is provided for this purpose.

If you have installed multiple versions of Notification Services, and are using COM interop, your code uses the APIs from the most recently installed version of Notification Services. This is not necessarily the highest version number of Notification Services. Such a discrepancy can occur because the Program ID (under HKEY_CLASSES_ROOT) is of the form "Microsoft.SqlServer.NotificationServices.NSInstance", and always points to the most recently installed version.

To enable COM interop with Notification Services classes, you must add the Microsoft.NotificationServer.ComInterop.tlb file to your Microsoft Visual Basic® or Microsoft Visual C++® project.

The following Notification Services classes implement interfaces to be used in COM interop:

  • ApplicationEnumeration
  • DeliveryChannel
  • DeliveryChannelEnumeration
  • Event
  • EventClass
  • EventClassEnumeration
  • EventCollector
  • InstanceEnumeration
  • NSApplication
  • NSInstance
  • NSInstanceDescription
  • Subscriber
  • SubscriberDevice
  • SubscriberDeviceEnumeration
  • SubscriberEnumeration
  • SubscriberLocale
  • SubscriberLocaleEnumeration
  • Subscription
  • SubscriptionClass
  • SubscriptionClassEnumeration
  • SubscriptionEnumeration
  • TimeZone
  • TimeZoneEnumeration

These classes provide a parameter-less constructor and an Initialize method for creating and initializing an object in unmanaged code. For overloaded methods in these classes, the most extensive overload is provided to the COM caller, and method parameters are made optional in order to provide equivalent functionality.

For more information about using COM interop, refer to COM Interoperability in Visual Basic and Visual C# in the Microsoft MSDN® Library.


Application Settings

You can define application settings in several sections of the application definition file (ADF). (For more information about the ADF, see Application Definition File Reference.) These settings specify such things as the computers that host Notification Services, and execution schedules for Notification Services functions. They also document metadata about the ADF itself, such as modification history.

The Application Settings section is divided into the following topics:

Topic | Description
Defining Application Parameters | Describes how to use the <ParameterDefaults> node of the ADF to maintain information about application parameters.
Maintaining Version Information | Describes how to use the <Version> node of the ADF to maintain application version information.
Maintaining History Information | Shows how to use the <History> node of the ADF to maintain ADF modification history.
Defining Application Database Information | Describes how to use the <Database> node of the ADF to maintain information about the SQL Server database that this application uses.
Specifying Generator Settings | Discusses how different settings for the <Generator> elements can affect system operation. Walks through the population of the <Generator> node with information about the generator that this application uses.
Specifying Distributor Settings | Discusses how different settings for the <Distributor> elements can affect system operation. Walks through the population of the <Distributors> node with information about the distributors that this application uses.
Defining the Application Execution Settings | Discusses how different settings for the <ApplicationExecutionSettings> elements can affect system operation. Walks through the population of the <ApplicationExecutionSettings> node with information relating to application execution, such as how frequently the generator fires.


Defining Application Parameters

To ensure consistent values for elements that are used in several different nodes in your application definition file (ADF), you can use a <ParameterDefaults> node to define application parameters. You can specify parameters in the ADF, the configuration file, or both. The files where the parameters are specified will determine their precedence of use; parameters inherited from the configuration file take precedence over those defined in the ADF.

Note Microsoft recommends that you use parameters to pass in any sensitive information that your application requires, rather than hardcoding this information in clear text in the ADF. A good example of where you might want to use parameters is if you need to supply user name or password information for use as an argument value.

See Also

Defining Parameters in Both the ADF and the Configuration File

Defining Parameters in the ADF

Inheriting Configuration File Parameters


Defining Parameters in the ADF

One way to specify the parameters you want to use in your application is by creating a <ParameterDefaults> node in your application definition file (ADF). Within the <ParameterDefaults> node, you must create a <Parameter> node for each parameter that you require. The <Parameter> node has two required child elements: <Name> and <Value>.

Note You must exclude the <ParameterDefaults> node from the ADF if you do not specify any application parameters.

Once you define a parameter in your <ParameterDefaults> node, you use a variable to specify the value of that parameter in other elements in the ADF. The variable name is always the parameter name with a percent sign (%) before and after it (for example %RetryInterval%.)

<ParameterDefaults> Example

The following example shows how to create a <ParameterDefaults> node. This example creates a parameter for the retry interval, which is then used in the protocol execution settings in the notification class:

<ParameterDefaults>
   <Parameter>
      <Name>SysName</Name>
      <Value>SERVER01</Value>
   </Parameter>
   <Parameter>
      <Name>RetryInterval</Name>
      <Value>P0DT00H15M00S</Value>
   </Parameter>
</ParameterDefaults>
...
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         <Protocol>
            ...
            <ProtocolExecutionSettings>
               <RetrySchedule>
                  <RetryDelay>%RetryInterval%</RetryDelay>
               </RetrySchedule>
            </ProtocolExecutionSettings>
         </Protocol>
      </Protocols>
   </NotificationClass>
</NotificationClasses>

See Also

<Name> Element (<Parameter>)

<Parameter> Node

<ParameterDefaults> Node

<Value> Element (<Parameter>)


Inheriting Configuration File Parameters

An alternative to defining parameters in your application definition file (ADF) is to inherit parameters that are defined in the /Applications/Application/Parameters section of the configuration file. If you choose this method, you must make certain that the configuration file supplies the parameters — otherwise the applications will fail to be created.

Configuration File Parameters Example

The following example shows how to set a parameter in the configuration file that will then be used in the ADF. A parameter that represents the name of the server that hosts Notification Services is set in the configuration file, and then inherited in the ADF:

<!--Configuration File-->
...
<Applications>
   <Application>
      ...
      <Parameters>
         <Parameter>
            <Name>NSSysName</Name>
            <Value>SLEIPNIR</Value>
         </Parameter>
      </Parameters>
   </Application>
</Applications>

<!--ADF-->
...
<!--No parameter defaults are specified.-->
...
<Distributors>
   <Distributor>
      <!--The value of SystemName will be SLEIPNIR. -->
      <SystemName>%NSSysName%</SystemName>
      <ThreadPoolSize>3</ThreadPoolSize>
   </Distributor>
</Distributors>


Defining Parameters in Both the ADF and the Configuration File

Including the same parameter in both the configuration file and the application definition file (ADF) provides a backup parameter value for your application in the ADF. That way, if the parameter is accidentally removed from the configuration file, your application has a fallback value. When you specify it in both places, the value you specify in the configuration file always overrides the value you specify in the ADF.

ADF and Configuration File Parameters Example

The following example shows how parameter precedence works when a parameter is set in both the configuration file and the ADF. A parameter that represents the name of the server that hosts Notification Services is set in both the configuration file and the ADF; the configuration file setting will override the ADF setting:

<!--Configuration File-->
...
<Applications>
   <Application>
      ...
      <Parameters>
         <Parameter>
            <Name>NSSysName</Name>
            <Value>SLEIPNIR</Value>
         </Parameter>
      </Parameters>
   </Application>
</Applications>

<!--ADF-->
...
<ParameterDefaults>
   <Parameter>
      <ParameterName>NSSysName</ParameterName>
      <ParameterValue>GRANE</ParameterValue>
   </Parameter>
</ParameterDefaults>
...
<Distributors>
   <Distributor>
      <!--The value of the system name will be SLEIPNIR. -->
      <SystemName>%NSSysName%</SystemName>
      <ThreadPoolSize>3</ThreadPoolSize>
   </Distributor>
</Distributors>


Maintaining Version Information

You can associate version numbers with an application definition file (ADF) to track changes made to the ADF. You can document this information by creating a <Version> node in the ADF. Notification Services does not verify the version information that appears in the ADF, so this action is not required; however, maintaining version information is a recommended practice.

Note If you choose not to document version information, you must exclude the <Version> node from the ADF.

The <Version> node consists of four required child elements:

  • <Major>
  • <Minor>
  • <Build>
  • <Revision>
<Version> Example

The following example shows how to create a <Version> node. It sets a version number of 1.0.24.8 for the application:

<Version>
   <Major>1</Major>
   <Minor>0</Minor>
   <Build>24</Build>
   <Revision>8</Revision>
</Version>

See Also

<Build> Element

<Major> Element

<Minor> Element

<Revision> Element

<Version Node>


Maintaining History Information

To see when the application definition file (ADF) was created and when it was last modified, you can create a <History> node in your ADF. This history information is for your own use, and is not referenced or validated in any way by Notification Services.

Note If you choose not to document history information, you must exclude the <History> node from the ADF.

The <History> node has four required child elements:

  • <CreationDate>
  • <LastModifiedDate>
  • <CreationTime>
  • <LastModifiedTime>
<History> Example

The following example shows how to create a <History> node. It records the application creation time as 10:30 GMT on 9/22/2001, and the application last update time as 22:30 GMT on 10/25/2001:

<History>
   <CreationDate>2001-09-22</CreationDate>
   <CreationTime>10:30:00</CreationTime>
   <LastModifiedDate>2001-10-25</LastModifiedDate>
   <LastModifiedTime>22:30:00</LastModifiedTime>
</History>

See Also

<CreationDate> Element

<CreationTime> Element

<History> Node

<LastModifiedDate> Element

<LastModifiedTime> Element


Defining Application Database Information

If you want to create your application database using other than SQL Server defaults, you can specify the database information in the <Database> node of your application definition file (ADF). In the absence of this information, SQL Server defaults are used when creating the application database.

Note If you choose not to specify application database information, you must exclude the <Database> node from the ADF.

The <Database> node has four optional child elements:

  • <NamedFileGroup>
  • <LogFile>
  • <DefaultFileGroup>
  • <CollationName>

Each of these elements is summarized in the following sections.

For further general information about SQL Server databases and physical files, see "CREATE DATABASE" and "Physical Database Files and Filegroups" in SQL Server Books Online.

<Database> Example

The following example shows how to create a <Database> node for an application that has two named filegroups, Primary and Secondary, and a log file named StockLog. It uses the Secondary filegroup as its default filegroup, and uses the SQL_Latin1_General_Cp437_BIN collation:

<Database>
   <NamedFileGroup>
      <FileGroupName>Primary</FileGroupName>
      <FileSpec>
         <LogicalName>StockPrimary</LogicalName>
         <FileName>C:\SQLData\StockPrimary.mdf</FileName>
         <Size>2GB</Size>
         <MaxSize>5GB</MaxSize>
         <GrowthIncrement>500MB</GrowthIncrement>
      </FileSpec>
   </NamedFileGroup>
   <NamedFileGroup>
      <FileGroupName>Secondary</FileGroupName>
      <FileSpec>
         <LogicalName>StockSecondary1</LogicalName>
         <FileName>D:\Data\StockSecondary1.ndf</FileName>
         <Size>1000MB</Size>
         <MaxSize>5000MB</MaxSize>
         <GrowthIncrement>25%</GrowthIncrement>
      </FileSpec>
      <FileSpec>
         <LogicalName>StockSecondary2</LogicalName>
         <FileName>D:\Data\StockSecondary2.ndf</FileName>
      </FileSpec>
   </NamedFileGroup>
   <LogFile>
      <LogicalName>StockLog</LogicalName>
      <FileName>E:\Logs\StockLog.ldf</FileName>
   </LogFile>
   <DefaultFileGroup>Secondary</DefaultFileGroup>
   <CollationName>SQL_Latin1_General_Cp437_BIN</CollationName>
</Database>

See Also

<CollationName> Element

<Database> Node

<DefaultFileGroup> Element

<LogFile> Node

<NamedFileGroup> Node


Defining a <NamedFileGroup> Node

A <NamedFileGroup> node contains information about the application database data files in a particular SQL Server filegroup. SQL Server provides filegroups to simplify database administration, as well as to allow for optimal allocation of system data across multiple physical disks. For more information about SQL Server filegroups, see "Files and Filegroups" in SQL Server Books Online.

You can optionally specify one or more <NamedFileGroup> nodes in the <Database> node. If you create any <NamedFileGroup> nodes, then one of the nodes must represent the primary filegroup for your application, and must be named Primary. The primary filegroup is used as the default for your application database files if no <DefaultFileGroup> element is specified.

The <NamedFileGroup> node contains two required child elements: <FileGroupName> and the <FileSpec> node. These elements are summarized in the following sections.

<FileGroupName> Element

The <FileGroupName> element must contain the name of the SQL Server filegroup that the associated <NamedFileGroup> node describes.

<FileSpec> Node

The <FileSpec> node contains information about a data file that resides on the filegroup specified in the <FileGroupName> element. You can specify one or more <FileSpec> nodes in the <NamedFileGroup> node.

The <FileSpec> node contains five child elements:

  • <LogicalName> (required)
  • <FileName> (required)
  • <Size> (optional)
  • <MaxSize> (optional)
  • <GrowthIncrement> (optional)

    Note If you choose not to specify one or more of the optional child elements <Size>, <MaxSize>, or <GrowthIncrement>, you must exclude those nodes from the ADF.

<NamedFileGroup> Example

The following example shows how to create <NamedFileGroup> nodes for two named filegroups, Primary and Secondary. The Secondary filegroup uses two <FileSpec> nodes to specify multiple physical files in which to place the data:

<Database>
   <NamedFileGroup>
      <FileGroupName>Primary</FileGroupName>
      <FileSpec>
         <LogicalName>StockPrimary</LogicalName>
         <FileName>C:\SQLData\StockPrimary.mdf</FileName>
         <Size>2GB</Size>
         <MaxSize>5GB</MaxSize>
         <GrowthIncrement>500MB</GrowthIncrement>
      </FileSpec>
   </NamedFileGroup>
   <NamedFileGroup>
      <FileGroupName>Secondary</FileGroupName>
      <FileSpec>
         <LogicalName>StockSecondary1</LogicalName>
         <FileName>D:\Data\StockSecondary1.ndf</FileName>
         <Size>1000MB</Size>
         <MaxSize>5000MB</MaxSize>
         <GrowthIncrement>25%</GrowthIncrement>
      </FileSpec>
      <FileSpec>
         <LogicalName>StockSecondary2</LogicalName>
         <FileName>D:\Data\StockSecondary2.ndf</FileName>
      </FileSpec>
   </NamedFileGroup>
   ...
</Database>

See Also

<FileGroupName> Element

<FileName> Element (<FileSpec>)

<FileSpec> Node

<GrowthIncrement> Element (<FileSpec>)

<LogicalName> Element (<FileSpec>)

<MaxSize> Element (<FileSpec>)

<NamedFileGroup> Node

<Size> Element (<FileSpec>)


Defining a <LogFile> Node

A <LogFile> node contains information about an application database log file. You can optionally specify one or more <LogFile> nodes in the <Database> node.

The <LogFile> node contains five child elements:

  • <LogicalName> (required)
  • <FileName> (required)
  • <Size> (optional)
  • <MaxSize> (optional)
  • <GrowthIncrement> (optional)

    Note If you choose not to specify one or more of the optional child elements <Size>, <MaxSize>, or <GrowthIncrement>, you must exclude those nodes from the application definition file (ADF).

<LogFile> Example

The following example shows how to create a <LogFile> node for the application log file:

<Database>
   ...
   <LogFile>
      <LogicalName>StockLog</LogicalName>
      <FileName>E:\Logs\StockLog.ldf</FileName>
      <Size>750MB</Size>
      <MaxSize>2GB</MaxSize>
      <GrowthIncrement>250MB</GrowthIncrement>
   </LogFile>
   ...
</Database>

See Also

<FileName> Element (<LogFile>)

<GrowthIncrement> Element (<LogFile>)

<LogFile> Node

<LogicalName> Element (<LogFile>)

<MaxSize> Element (<LogFile>)

<Size> Element (<LogFile>)


Defining a <DefaultFileGroup> Element

You can specify the name of the default SQL Server filegroup in the <DefaultFileGroup> element. This filegroup must be one of those specified in a <NamedFileGroup> node.

Note You must exclude the <DefaultFileGroup> element from the <Database> node if you choose not to use it.

<DefaultFileGroup> Example

The following example shows how to create a <DefaultFileGroup> element, which defines the Secondary filegroup as the default for this application:

<Database>
   ...
   <DefaultFileGroup>Secondary</DefaultFileGroup>
   ...
</Database>

See Also

<DefaultFileGroup> Element


Defining a <CollationName> Element

You specify the name of the default collation in the <CollationName> element. This determines the character set and sort order used by the application database. Its value must be the full collation name of either a Microsoft Windows or a SQL Server collation. If you do not provide a <CollationName> value, the application database collation is the same as the default collation of the SQL Server instance that hosts the database.

Note You must exclude the <CollationName> element from the <Database> node if you choose not to use it.

The <CollationName> value of all application databases in a SQL Server Notification Services instance must match that of the instance's NSMain database.

For more information about how SQL Server uses collations, see "COLLATE" in SQL Server Books Online.

<CollationName> Example

The following example shows how to create a <CollationName> element, which sets the collation used by this application:

<Database>
   ...
   <CollationName>SQL_Latin1_General_Cp437_BIN</CollationName>
</Database>

See Also

<CollationName> Element


Specifying Generator Settings

The generator function governs the rule processing for a notification application. Settings for the generator are specified in the <Generator> node. These settings determine which server hosts the generator, and how many threads the generator can use when processing application rules. The values you specify for the generator settings should be considered in terms of a trade-off between improving application speed and monopolizing system resources.

See Also

Generator Settings Considerations

Populating the <Generator> Node


Generator Settings Considerations

The <ThreadPoolSize> element is the only <Generator> node setting that has any performance implications. In Notification Services Enterprise Edition, you can use the <ThreadPoolSize> element in the <Generator> node to provide a balance between improving application speed and monopolizing system resources. In Notification Services Standard Edition, <ThreadPoolSize> must be omitted or set to 1. Any other value generates an error when NSControl is run to create or update the application.

The Notification Services generator attempts to fire all event chronicle rules in parallel, followed by all subscription rules (both event rules and scheduled rules). The generator attempts to utilize all threads available within the thread pool while executing rules.

The event chronicle rules maintain event chronicle table data. Because subscription rules might reference the event chronicle tables, these tables must be updated before subscription rules are processed. Therefore the generator never processes event chronicle rules in parallel with subscription rules.

The <ThreadPoolSize> value determines how many operating system threads the generator can use in this parallel processing. In a Standard Edition system, the <ThreadPoolSize> value is always 1. If the <ThreadPoolSize> element is not defined in an Enterprise Edition system, the system allocates up to 25 threads per processor for parallel rule execution. The actual number of threads allocated is determined by an optimization algorithm.

The default thread allocation attempts to provide a dedicated thread for each rule that is processed, thereby ensuring maximum throughput. If you specify a higher value for <ThreadPoolSize>, this might burden the system with thread-switching overhead without improving application performance.

However, you can provide a lower value for <ThreadPoolSize> if the consumption of processor time is a concern on your system. If you lower the thread pool size, the speed of the generator processing decreases, thereby decreasing the generator's demand on system resources.


Populating the <Generator> Node

Each instance of Notification Services provides one generator function. You must maintain information about the computer that hosts the generator. This information is stored in the <Generator> node of the application definition file (ADF). You are required to define this node.

The <Generator> node has two child elements:

  • <SystemName> (required)
  • <ThreadPoolSize> (optional)

The <SystemName> element specifies the computer name of the server that hosts the Notification Services instance that provides your generator function.

The <ThreadPoolSize> element specifies the number of threads on which the generator can process. The value of the <ThreadPoolSize> element determines the amount of work that the generator can perform in parallel, and affects the overall speed of the Notification Services system. In the case of Notification Services Standard Edition, the only valid <ThreadPoolSize> value is 1.

Note You must exclude the <ThreadPoolSize> element from the <Generator> node if you do not use it; in this case the generated default value is used. This default value is 1 in the case of Notification Services Standard Edition, or some number determined by an optimization algorithm in the case of Notification Services Enterprise Edition.

<Generator> Example

The following example shows how to create a <Generator> node. The generator for this instance runs on a server named SIF, and will process application rules on one thread:

<Generator>
   <SystemName>SIF</SystemName>
   <ThreadPoolSize>1</ThreadPoolSize>
</Generator>

See Also

<Generator> Node

<SystemName> Element (<Generator>)

<ThreadPoolSize> Element (<Generator>)


Specifying Distributor Settings

The distributor function governs notification formatting and delivery for a notification application. Each Notification Services instance can have one or more distributors. Settings for a distributor can be specified in the <Distributors> node. These settings determine which server hosts a distributor, how frequently it runs, and how many threads it can use when processing work items. The values you specify for the distributor settings should be considered in terms of a trade-off between improving application speed and monopolizing system resources.


Distributor Settings Performance Considerations

The <QuantumDuration> and <ThreadPoolSize> elements both have implications for system performance.

<QuantumDuration> Element

A quantum is a block of time used by Notification Services to determine how frequently to trigger system functions. You can use the <QuantumDuration> element to trade off between application speed and resource consumption, based on the specifics of your system.

The <QuantumDuration> element determines how frequently the distributor checks for available work items. (For more detail about work items, see Distributing Notifications.) You can use the <QuantumDuration> value to optimize distributor performance relative to the workload on the server. Smaller quantum durations cause more frequent firing of the distributor, which means faster notification formatting and delivery for the application. Smaller quantum durations also mean that the distributor takes up more processor time overall, and therefore requires more resources on the server.

<ThreadPoolSize> Element

In Notification Services Enterprise Edition, you can use the <ThreadPoolSize> element in the <Distributor> node to provide a balance between improving application speed and monopolizing system resources. In Notification Services Standard Edition, the <ThreadPoolSize> value must be between 1 and 3. Any other value generates an error when NSControl is run to create or update the application. In Notification Services Enterprise Edition, the <ThreadPoolSize> value is unlimited.

Each Notification Services distributor attempts to process available work items as quickly as possible. The distributor attempts to perform parallel processing and utilize all threads available within the thread pool while processing work items.

The <ThreadPoolSize> value determines how many operating system threads the distributor can use in this parallel processing. In a Standard Edition system, this is between 1 and 3 threads, with 3 threads being used if no <ThreadPoolSize> element is defined. In an Enterprise Edition system, the system imposes no limit on the number of threads used in parallel work item processing. It uses as many as are available if no <ThreadPoolSize> element is defined.

You can provide a lower value for <ThreadPoolSize> if the consumption of processor time is a concern on your system. If you lower the thread pool size, the speed of the distributor processing decreases, thereby decreasing the distributor's demand on system resources.


Populating a <Distributor> Node

You must maintain information about the distributors your Notification Services application uses. This information is stored in the <Distributors> node of the application definition file (ADF). You are required to define this node.

Within the <Distributors> node, you must create a <Distributor> node for each distributor that services your application. The <Distributor> node has three child elements:

  • <SystemName> (required)
  • <ThreadPoolSize> (optional)
  • <QuantumDuration> (optional)

The <SystemName> element specifies the computer name of the server that hosts the NS$instance_name service that provides the distributor function.

The <ThreadPoolSize> element specifies the number of threads on which the distributor can process. The value of the <ThreadPoolSize> element determines the amount of work that the distributor can perform in parallel, and affects the overall speed of the Notification Services system.

Note You must exclude the <ThreadPoolSize> element from the <Distributor> node if you do not use it. In the case of Notification Services Standard Edition, the <ThreadPoolSize> value default of 3 is used. In the case of Notification Services Enterprise Edition, the system uses as many threads as are available to process current work items.

The <QuantumDuration> element specifies the duration of a distributor quantum. The quantum determines how frequently the distributor fires.

Note You must exclude the <QuantumDuration>element from the <Distributor> node if you do not use it. The system default of a 1-minute quantum duration is used in this case.

<Distributor> Example

The following example shows how to create a <Distributors> node. One distributor runs on the server THORFINN, using a distributor quantum period of 30 seconds and a thread pool size of 1. The other distributor runs on the server BIFROST, using a distributor quantum period of 15 seconds and a thread pool size of 3:

<Distributors>
   <Distributor>
      <SystemName>THORFINN</SystemName>
      <ThreadPoolSize>1</ThreadPoolSize>
      <QuantumDuration>P0DT00H00M30S</QuantumDuration>
   </Distributor>
   <Distributor>
      <SystemName>BIFROST</SystemName>
      <ThreadPoolSize>3</ThreadPoolSize>
      <QuantumDuration>P0DT00H00M15S</QuantumDuration>
   </Distributor>
</Distributors>

See Also

<Distributor> Node

<QuantumDuration> Element (<Distributor>)

<SystemName> Element (<Distributor>)

<ThreadPoolSize> Element(<Distributor>)


Defining Application Execution Settings

To maintain execution information about your application, you can create an <ApplicationExecutionSettings> node in your application definition file (ADF).

Note You must exclude the <ApplicationExecutionSettings> node from the ADF if you choose not to specify application settings. System defaults are used in that case.

The <ApplicationExecutionSettings> node has ten optional child elements:

  • <QuantumDuration>
  • <ChronicleQuantumLimit>
  • <SubscriptionQuantumLimit>
  • <ProcessEventsInOrder>
  • <PerformanceQueryInterval>
  • <EventThrottle>
  • <SubscriptionThrottle>
  • <NotificationThrottle>
  • <DistributorLogging>
  • <Vacuum>
<ApplicationExecutionSettings> Example

The following example shows how to create an <ApplicationExecutionSettings> node. It sets a generator quantum period of 5 minutes, with a chronicle quantum limit of 25 quanta (125 minutes, or just over 2 hours), and a subscription quantum limit of 12 quanta (60 minutes, or 1 hour). It uses sub-quantum sequencing, and runs the performance query once every hour. The event and notification throttles both allow 5,000 records to be processed per quantum, while the subscription throttle allows 3,000 records to be processed per quantum. The distributor logs notification pre-delivery information and notification delivery status, but not the notification text. Vacuuming runs from 3:00 A.M. to 5:00 A.M. and from 11:00 P.M. to 1:00 A.M. every day, removing data older than 3 days:

<ApplicationExecutionSettings>
   <QuantumDuration>P0DT00H05M00S</QuantumDuration>
   <ChronicleQuantumLimit>25</ChronicleQuantumLimit>
   <SubscriptionQuantumLimit>12</SubscriptionQuantumLimit>
   <ProcessEventsInOrder>true</ProcessEventsInOrder>
   <PerformanceQueryInterval>P0DT01H00M00S</PerformanceQueryInterval>
   <EventThrottle>5000</EventThrottle>
   <SubscriptionThrottle>3000</SubscriptionThrottle>
   <NotificationThrottle>5000</NotificationThrottle>
   <DistributorLogging>
      <LogBeforeDeliveryAttempts>true</LogBeforeDeliveryAttempts>
      <LogStatusInfo>true</LogStatusInfo>
      <LogNotificationText>false</LogNotificationText>
   </DistributorLogging>
   <Vacuum>
      <RetentionAge>P3DT00H00M00S</RetentionAge>
      <VacuumSchedule>
         <Schedule>
            <StartTime>23:00:00</StartTime>
            <Duration>P0DT02H00M00S</Duration>
         </Schedule>
         <Schedule>
            <StartTime>03:00:00</StartTime>
            <Duration>P0DT02H00M00S</Duration>
         </Schedule>
      </VacuumSchedule>
   </Vacuum>
</ApplicationExecutionSettings>

See Also

<ApplicationExecutionSettings> Node

Defining the <ChronicleQuantumLimit> Element

Defining the <DistributorLogging> Node

Defining the <EventThrottle> Element

Defining the <NotificationThrottle> Element

Defining the <PerformanceQueryInterval> Element

Defining the <ProcessEventsInOrder> Element

Defining the <QuantumDuration> Element

Defining the <SubscriptionQuantumLimit> Element

Defining the <SubscriptionThrottle> Element

Defining the <Vacuum> Node


Defining the <QuantumDuration> Element

A quantum is a block of time used by Notification Services to determine how frequently to trigger system functions. You can use the <QuantumDuration> element to trade off between application speed and resource consumption, based on the specifics of your system.

The <QuantumDuration> element determines how frequently the generator fires to process the application rules. You can use the <QuantumDuration> setting to optimize generator performance relative to the workload on the server. Smaller quantum durations cause more frequent firing of the generator, which means more frequent rule processing and greater application speed. Smaller quantum durations also mean that the generator takes up more processor time overall, and therefore requires more resources on the server.

The <QuantumDuration> element is optional. If it is not specified, the generator default of a 1-minute quantum duration is used.

<QuantumDuration> Example

The following example shows how to create a <QuantumDuration> element. It sets the quantum duration period to 5 minutes.

<ApplicationExecutionSettings>
   <QuantumDuration>P0DT00H05M00S</QuantumDuration>
   ...
</ApplicationExecutionSettings>

See Also

<QuantumDuration> Element


Defining the <ChronicleQuantumLimit> Element

The Notification Services system sometimes finds it necessary to skip the work that is due to be processed within a particular quantum, because the system is overloaded or down altogether. The <ChronicleQuantumLimit> element in the <ApplicationExecutionSettings> node is used to determine the number of quanta prior to the current quantum in which event chronicle rules must be processed. If the generator falls behind, then work in quanta earlier than those specified by <ChronicleQuantumLimit> is skipped so that the generator can catch up.

The <ChronicleQuantumLimit> value can be used to optimize generator performance relative to the workload on the server. Smaller quantum limits permit the generator to do less work when falling behind, and therefore it can catch up more easily. With smaller quantum limits, more event chronicle rules can go unprocessed, which will affect the event data that goes into the system and the notification data that it generates.

You can use the <ChronicleQuantumLimit> value to trade off between application speed and data correctness, based on the specifics of your system. You must specify the <ChronicleQuantumLimit> value as a non-negative integer.

<ChronicleQuantumLimit> is optional. If it is not specified, the chronicle quantum limit default of 1,440 quanta is used (1 day if the default <QuantumDuration> of 1 minute is used).

You can specify a value of 0 for the <ChronicleQuantumLimit> element to indicate that all chronicle rules for all quanta should always be processed.

Note You must exclude the <ChronicleQuantumLimit> element from the <ApplicationExecutionSettings> node if you do not specify a value for it. The system default is used in this case.

<ChronicleQuantumLimit> Example

The following example shows how to create a <ChronicleQuantumLimit> element. It sets the chronicle quantum limit to 25 quanta.

<ApplicationExecutionSettings>
   ...
   <ChronicleQuantumLimit>25</ChronicleQuantumLimit>
   ...
</ApplicationExecutionSettings>

See Also

<ChronicleQuantumLimit> Element


Chronicle Quantum Limit Illustration

In the following illustration, the Notification Services system has not been able to process quantum 1 through quantum 8, and <ChronicleQuantumLimit> is set to 4.

The generator processes the event chronicle rules for the event batches (E9 – E12) that arrived in quanta 5 through 8, which are the last four quanta. If the <SubscriptionQuantumLimit> value has not been exceeded, the subscription event rules for event batches E1 - E8 (which arrived prior to quantum 5), are also processed, but their event chronicle rules are not applied.

See Also

Defining the <SubscriptionQuantumLimit> Element


Defining the <SubscriptionQuantumLimit> Element

The Notification Services system sometimes finds it necessary to skip the work that is due to be processed within a particular quantum, because the system is overloaded or down altogether. The <SubscriptionQuantumLimit> element in the <ApplicationExecutionSettings> node is used to determine the number of quanta prior to the current quantum in which subscription rules (both event and scheduled) must be processed. If the generator falls behind, then work in quanta earlier than those specified by <SubscriptionQuantumLimit> is skipped so that the generator can catch up.

The <SubscriptionQuantumLimit> value can be used to optimize generator performance relative to the workload on the server. Smaller quantum limits permit the generator to do less work when falling behind, and therefore it can catch up more easily. With smaller quantum limits, more subscription rules can go unprocessed, which might cause some notifications not to be generated that otherwise would have been.

You can use the <SubscriptionQuantumLimit> value to trade off between application speed and data correctness, based on the specifics of your system. You must specify the <SubscriptionQuantumLimit> value as a non-negative integer.

<SubscriptionQuantumLimit> is optional. If it is not specified, the subscription quantum limit default of 30 quanta is used (30 minutes if the default <QuantumDuration> of 1 minute is used).

You can specify a value of 0 for the <SubscriptionQuantumLimit> element to indicate that all subscription rules for all quanta should always be processed.

Note You must exclude the <SubscriptionQuantumLimit> element from the <ApplicationExecutionSettings> node if you do not specify a value for it. The system default is used in this case.

<SubscriptionQuantumLimit> Example

The following example shows how to create a <SubscriptionQuantumLimit> element. It sets the chronicle quantum limit to 12 quanta.

<ApplicationExecutionSettings>
   ...
   <SubscriptionQuantumLimit>12</SubscriptionQuantumLimit>
   ...
</ApplicationExecutionSettings>

See Also

<SubscriptionQuantumLimit> Element


Subscription Quantum Limit Illustration

In the following illustration, the Notification Services system has not been able to process quantum 1 through quantum 8, and <SubscriptionQuantumLimit> is set to 2.

The generator processes the subscription rules for all subscriptions that come up for processing in quanta 7 and 8, which are the last two quanta. For any subscriptions that should have been processed prior to quantum 7, the subscription rules are skipped and notifications are not generated.


Defining the <ProcessEventsInOrder> Element

Notification Services provides two options for determining how application rules are processed. You can specify whether event and subscription rules are fired for each event batch arrival time (known as sub-quantum sequencing), or whether they are fired once per quantum period, regardless of event batch arrival time (known as quantum sequencing). These two modes provide you with fine control in balancing data correctness against generator performance in your application.

Sub-quantum sequencing processes event batches in order of arrival. All event batches are processed one at a time in chronological order. The system guarantees that each event batch is processed first by the event chronicle rule, and then by any subscription event rules. Scheduled subscriptions are also processed chronologically, so they never contain events arriving in the system after their scheduled processing times.

Quantum sequencing processes event batches in quantum order. Some systems do not require the strict in-order guarantee provided by sub-quantum sequencing, and can take advantage of the performance benefit of not having to provide such a guarantee. All event batches received within the quantum are processed together for efficiency as if the arrival time occurred just after the last quantum duration expired. The generator processes all timed subscriptions as scheduled for the last moment of the quantum period. Therefore the only ordering guarantee for rule firings within a quantum using quantum sequencing is the following:

  1. Event chronicle rules
  2. Subscription event rules
  3. Subscription scheduled rules

The <ProcessEventsInOrder> element of the <ApplicationExecutionSettings> node documents this information. You must specify a Boolean value for this element, with true indicating that sub-quantum sequencing has been selected and false indicating that quantum sequencing has been selected.

Note You must exclude the <ProcessEventsInOrder> element from the <ApplicationExecutionSettings> node if you do not specify a value for it. Quantum sequencing is used in this case.

<ProcessEventsInOrder> Example

The following example shows how to create a <ProcessEventsInOrder> element. It specifies that sub-quantum sequencing is used by this application.

<ApplicationExecutionSettings>
   ...
   <ProcessEventsInOrder>true</ProcessEventsInOrder>
   ...
</ApplicationExecutionSettings>

See Also

<ProcessEventsInOrder> Element

Quantum Sequencing Illustration

Sub-Quantum Sequencing Illustration


Quantum Sequencing Illustration

Quantum sequencing of eight quanta is shown in the following illustration.

Processing of these quanta results in the following rule firing schedule:

Quantum | Event batch and timed subscription processing
Process quantum 1 | Event batches E1, E2, and E3 are processed together. No timed subscriptions to process.
Process quantum 2 | Event batches E4 and E5 are processed together. Timed subscription T1 is processed.
Process quantum 3 | Event batches E6 and E7 are processed together. Timed subscription T2 is processed.
Process quantum 4 | Event batch E8 is processed. Timed subscriptions T3 and T4 are processed together.
Process quantum 5 | Event batches E9 and E10 are processed together. Timed subscription T5 is processed.
Process quantum 6 | Event batch E11 is processed. Timed subscriptions T6 and T7 are processed together.
Process quantum 7 | Event batch E12 is processed. Timed subscriptions T8 and T9 are processed together.
Process quantum 8 | No event batches to process. Timed subscriptions T10, T11, and T12 are processed together.


Sub-Quantum Sequencing Illustration

Sub-quantum sequencing of eight quanta is shown in the following illustration.

Processing of these quanta results in the following rule firing schedule:

Quantum | Event batch and timed subscription processing
Process quantum 1 | Event batches E1, E2, and E3 are processed sequentially. No timed subscriptions to process.
Process quantum 2 | Event batches E4 and E5 are processed sequentially. Timed subscription T1 is processed.
Process quantum 3 | Event batch E6 is processed. Timed subscription T2 is processed. Event batch E7 is processed.
Process quantum 4 | Event batch E8 is processed. Timed subscriptions T3 and T4 are processed together.
Process quantum 5 | Timed subscription T5 is processed. Event batches E9 and E10 are processed sequentially.
Process quantum 6 | Timed subscription T6 is processed. Event batch E11 is processed. Timed subscription T7 is processed.
Process quantum 7 | Timed subscriptions T8 and T9 are processed together. Event batch E12 is processed.
Process quantum 8 | Timed subscriptions T10, T11, and T12 are processed together. No event batches to process.


Defining the <PerformanceQueryInterval> Element

Some Notification Services performance counters are updated at periodic intervals rather than continuously. The <PerformanceQueryInterval> element of the <ApplicationExecutionSettings> node specifies the intervals at which these counters are updated.

Calculating the performance counters requires an amount of processing overhead that might affect system performance. You can use the <PerformanceQueryInterval> setting to trade off between the frequency of counter updates and the performance of the system.

Note You must exclude the <PerformanceQueryInterval> element from the <ApplicationExecutionSettings> node if you do not specify a value for it. The default value of 1 minute is used in this case.

The following performance counters are affected by the <PerformanceQueryInterval> value:

  • Event Batches Awaiting Generation
  • Event Batches in Collection
  • Event Batches Submitted
  • Total Events
  • Subscribers Added
  • Subscribers Enabled
  • Subscribers Disabled
  • Subscriptions Added
  • Subscriptions Added per Minute
  • Subscriptions Enabled
  • Subscriptions Disabled
  • Batches in Generation
  • Batches Awaiting Distribution
  • Notifications Awaiting Distribution
  • Batches Successfully Delivered
  • Notifications Successfully Delivered
  • Batches Failed Delivery
  • Notifications Failed Delivery
  • Batches in Retry
  • Notifications in Retry
  • Batches Expired
  • Notifications Expired

These counters are updated only on the server that hosts the generator, and only when the application is enabled.

The remaining counters do not require as much overhead to calculate, and so are not affected by the <PerformanceQueryInterval> setting.

<PerformanceQueryInterval> Example

The following example shows how to create a <PerformanceQueryInterval> element. It specifies that the affected performance counters are updated once per hour.

<ApplicationExecutionSettings>
   ...
   <PerformanceQueryInterval>P0DT01H00M00S</PerformanceQueryInterval>
   ...
</ApplicationExecutionSettings>

See Also

<PerformanceQueryInterval> Element


Defining the <EventThrottle> Element

The <EventThrottle> element in the <ApplicationExecutionSettings> node is used to determine the number of events per event class that can be processed by the generator within a quantum period.

This setting is meant to provide a way to limit the number of events coming in to the system, in order to prevent malicious users from generating very large numbers of events as part of a denial-of-service attack. If the <EventThrottle> value is exceeded, an error is thrown in order to alert the system administrator to the potential problem. Notification Services aborts a quantum when the <EventThrottle> value is exceeded.

<EventThrottle> is optional. If it is not specified, the event throttle default of 1,000 is used.

You can specify a value of 0 for the <EventThrottle> element to allow an unlimited number of events per event class to be processed.

Note You must exclude the <EventThrottle> element from the <ApplicationExecutionSettings> node if you do not specify a value for it. The system default is used in this case.

<EventThrottle> Example

The following example shows how to create an <EventThrottle> element. It specifies that 5000 events per event class can be processed per quantum.

<ApplicationExecutionSettings>
   ...
   <EventThrottle>5000</EventThrottle>
   ...
</ApplicationExecutionSettings>

See Also

<EventThrottle> Element


Defining the <SubscriptionThrottle> Element

The <SubscriptionThrottle> element in the <ApplicationExecutionSettings> node is used to determine, per rule firing, the number of subscriptions of each subscription class that can be processed by the generator within a quantum period. This setting is only used with subscription scheduled rules.

This setting is meant to provide a way to limit the number of subscriptions processed by the system, in order to prevent malicious users from generating very large numbers of subscriptions as part of a denial-of-service attack. If the <SubscriptionThrottle> value is exceeded, an error is thrown in order to alert the system administrator to the potential problem. Notification Services aborts a quantum when the <SubscriptionThrottle> value is exceeded.

<SubscriptionThrottle> is optional. If it is not specified, the subscription throttle default of 1,000 is used.

You can specify a value of 0 for the <SubscriptionThrottle> element to allow an unlimited number of subscriptions per subscription class to be processed.

Note You must exclude the <SubscriptionThrottle> element from the <ApplicationExecutionSettings> node if you do not specify a value for it. The system default is used in this case.

<SubscriptionThrottle> Example

The following example shows how to create a <SubscriptionThrottle> element. It specifies that 3000 subscriptions per subscription class can be processed per quantum.

<ApplicationExecutionSettings>
   ...
   <SubscriptionThrottle>3000</SubscriptionThrottle>
   ...
</ApplicationExecutionSettings>

See Also

<SubscriptionThrottle> Element


Defining the <NotificationThrottle> Element

The <NotificationThrottle> element in the <ApplicationExecutionSettings> node is used to determine, per rule firing, the number of notifications of each notification class that can be processed by the generator within a quantum period.

This setting is meant to provide a way to limit the number of notifications generated by the system, in order to prevent malicious users from generating very large numbers of notifications as part of a denial-of-service attack. If the <NotificationThrottle> value is exceeded, an error is thrown in order to alert the system administrator to the potential problem. Notification Services causes the subscription rules associated with notification generation to fail when the <NotificationThrottle> value is exceeded. Other rules within the quantum and all future quantum processing proceed normally.

<NotificationThrottle> is optional. If it is not specified, the notification throttle default of 1,000 is used.

You can specify a value of 0 for the <NotificationThrottle> element to allow an unlimited number of notifications per notification class to be processed.

Note You must exclude the <NotificationThrottle> element from the <ApplicationExecutionSettings> node if you do not specify a value for it. The system default is used in this case.

<NotificationThrottle> Example

The following example shows how to create a <NotificationThrottle> element. It specifies that 5000 notifications per notification class can be processed per quantum.

<ApplicationExecutionSettings>
   ...
   <NotificationThrottle>5000</NotificationThrottle>
   ...
</ApplicationExecutionSettings>

See Also

<NotificationThrottle> Element


Defining the <DistributorLogging> Node

The distributor can maintain various levels of logging to keep track of notification delivery information. This information is important when troubleshooting notification delivery issues, or in applications where notification delivery must be guaranteed and audited. You can use the settings in the <DistributorLogging> node to configure the appropriate logging level for your application. The Notification Services default of using the highest level of logging is used, which also uses more system resources and might affect application speed.

Note You must exclude the <DistributorLogging> node from the <ApplicationExecutionSettings> node if you do not specify a value for it.

The <LogBeforeDeliveryAttempt> element contains a Boolean value that indicates whether the distributor makes an entry in the distributor log before sending out a notification message. The default of this element is true.

The <LogStatusInfo> element contains a Boolean value that indicates whether the distributor logs the delivery status information for each notification message it has attempted to send. The default of this element is true.

The <LogNotificationText> element contains a Boolean value that indicates whether or not the distributor logs the full text of any notification delivery information returned from the delivery protocol. Notification Services will always log information for a failed delivery. Setting this option to true logs this information for successful deliveries as well. The default of this element is true.

Note Setting <LogNotificationText> to true is useful when getting your application up and running, but it can have an adverse effect on performance in a production environment. Once you have your application deployed, you should consider setting the <LogNotificationText> value to false if you do not specifically require the information that it provides.

Note All the <DistributorLogging> child elements are optional. If you do not specify a value for any one of them, you must exclude it from the <DistributorLogging> node.

<DistributorLogging> Example

The following example shows how to create a <DistributorLogging> node. It specifies that the distributor logs all notification pre-delivery information and notification delivery status, but does not log the notification text itself.

<ApplicationExecutionSettings>
   ...
   <DistributorLogging>
      <LogBeforeDeliveryAttempts>true</LogBeforeDeliveryAttempts>
      <LogStatusInfo>true</LogStatusInfo>
      <LogNotificationText>false</LogNotificationText>
   </DistributorLogging>
   ...
</ApplicationExecutionSettings>

See Also

<DistributorLogging> Node

<LogBeforeDeliveryAttempts> Element

<LogNotificationText> Element

<LogStatusInfo> Element


Defining the <Vacuum> Node

The Notification Services vacuumer function deletes obsolete event, notification, and batch header data from the system. It operates automatically, according to the information specified in the <Vacuum> element of the <ApplicationExecutionSettings> node. It runs based on the intervals specified in the <Schedule> element, and uses the <RetentionAge> value to determine what data is expired and available for deletion.

Vacuuming is essential because it reclaims disk space. By keeping the number of records in the system to a minimum, it also improves the speed with which SQL Server can search the application tables.

The following tables are vacuumed:

  • NSQuantum1
  • NSRuleFirings1
  • NSEventClassNameEventBatches
  • NSEventClassNameEvents
  • NSNotificationClassNameNotificationBatches
  • NSNotificationClassNameNotifications
  • NSDistributorWorkItems
  • NSDistributionLog

There is one vacuumer per application.

In general, it is best to schedule the vacuumer to operate at low usage times for your application. You can tune the vacuuming intervals to suit the needs of your application. Less frequent or shorter vacuuming intervals decrease the vacuumer's use of system resources, but also lead to an increase in disk space requirements to accommodate the expired but unremoved data. Lack of vacuuming can also degrade application performance, as table sizes increase and extend the length of time needed to perform database operations on them.

The default <RetentionAge> value is P7DT0H or 1 week.

All /VacuumSchedule/Schedule/StartTime values must be specified in UTC format.

The default /VacuumSchedule/Schedule/Duration value is 6 hours, or until the next schedule start time, whichever comes first. For more information about setting the vacuumer schedule, see Running the Vacuumer.

<Vacuum> Example

The following example shows how to create a <Vacuum> node. It specifies that vacuuming runs from 3:00 A.M. to 5:00 A.M. and from 11:00 P.M. to 1:00 A.M. every day, removing data older than 3 days.

<ApplicationExecutionSettings>
   ...
   <Vacuum>
      <RetentionAge>P3DT00H00M00S</RetentionAge>
      <VacuumSchedule>
         <Schedule>
            <StartTime>23:00:00</StartTime>
            <Duration>P0DT02H00M00S</Duration>
         </Schedule>
         <Schedule>
            <StartTime>03:00:00</StartTime>
            <Duration>P0DT02H00M00S</Duration>
         </Schedule>
      </VacuumSchedule>
   </Vacuum>
</ApplicationExecutionSettings>

See Also

<RetentionAge> Element

<Vacuum> Node

<VacuumSchedule> Node


Running the Vacuumer

The vacuumer runs based on the information defined in the <Vacuum> element of the <ApplicationExecutionSettings> node. The vacuumer cannot be enabled or disabled individually; it can only be enabled or disabled along with the entire application. Notification Services restarts the vacuumer automatically if it terminates abnormally.

When the vacuumer starts, it reads the system clock on the database server. It then identifies all expired data by comparing the current time with the interval specified in the <RetentionAge> element.

For example, assume the following is true:

  • The current time is 22:00:00 on January 28.
  • The retention age is set to three days.
  • There is event data that is time-stamped at 19:00:00 on January 25.

Given these facts, the event data expired at 19:00:00 on January 28, so the vacuumer identifies and deletes it.

Note The vacuumer checks once per minute to see if it should run. This can lead to a variation of up to a minute between the actual duration of the vacuuming interval and the interval specified by the user. In cases where the vacuumer starts after the specified start time, but before a minute has elapsed, the duration of the vacuuming period will be shorter by that time difference.

The vacuumer limits the number of records it deletes in one unit of work, based on a maximum number of records per table, thereby limiting the duration of each unit of work. This allows the vacuumer to function without overtaxing system resources and application processing time.

Each time the vacuumer completes a unit of work, it checks the system clock to see if it has exceeded the value of the /ApplicationExecutionSettings/Vacuum/VacuumSchedule/Schedule/Duration element, if one is specified. It also checks the database to see if its associated application has been disabled. If either of these events occurs, then the vacuumer stops, logs a message in the event log, and sleeps until the next scheduled vacuuming interval.

Vacuuming intervals are not permitted to overlap. Notification Services determines when they would overlap, and stops the earlier interval when the later one starts. For example, these intervals:

  • <StartTime>: 13:00 <Duration>: 2 hours
  • <StartTime>: 14:00 <Duration>: 2 hours

are converted to:

  • <StartTime>: 13:00 <Duration>: 1 hour
  • <StartTime>: 14:00 <Duration>: 2 hours

The vacuumer creates entries in the event log to report notable actions or errors.


Events

In Notification Services, you must define each event that your application will accept. You document these event definitions as event classes in your application definition file (ADF). When the notification application is set up using NSControl Create, the event class information is used to implement SQL Server objects (like tables and indexes) that will manage the data for this event class.

Components called event providers collect event data and write it to Notification Services. You must document in the ADF any event providers that your application uses.

The topics that the Events section covers are described in the following table.

Topic | Description
Collecting Events with an Event Provider | Describes how event providers collect and submit events to the system.
Event Chronicles | Discusses how event chronicle tables and event chronicle rules can be used to provide event data to scheduled subscriptions, and to prevent redundant notifications for event-driven subscriptions.
Defining an Event Class | Discusses how to define an event class in your ADF.
Defining an Event Provider | Discusses how to define an event provider in your ADF.
Standard Event Providers | Describes the standard event providers that come with Notification Services, and discusses how to implement them.


Collecting Events with an Event Provider

An event provider collects event data and transmits it to Notification Services. Each collected event is persisted as a single row in the event table of the application database.

Event providers can monitor and gather data in a number of ways, such as:

  • Watching directories for file additions, and then creating events based on the content of the added files.
  • Checking system and application log files for certain types of entries.
  • Trapping alerts from applications.
  • Monitoring Web pages.
  • Tracking changes in database tables.
  • Gathering data from Web services.

An event provider can gather data from any resource you want to use, provided that you can write an application that retrieves events from this resource.


Implementing Event Providers

Event providers use three means to write data to the application database:

  • Event and EventCollector classes: An Event object is created that encapsulates the data of a single event. This Event object is handed off to an EventCollector object, which writes the event to the event table.
  • EventLoader class: An EventLoader object is created that takes an XML document or a Stream object as a source of events. It writes the events to the event table.
  • Event collection stored procedures: SQL Server stored procedures are called to write data from another database table or query to the event table.

Event providers are implemented as assemblies that monitor event sources and gather information. An event provider can be hosted by Notification Services, or it can operate as an independent non-hosted event provider.

To be hosted by Notification Services, the event provider must implement one of two interfaces. Continuous event providers implement the IEventProvider interface, while scheduled event providers implement the IScheduledEventProvider interface. These interfaces allow Notification Services to make calls to initialize, run, and stop an event provider.

Event providers can also be implemented to run independently of Notification Services. These independent event providers do not implement the IEventProvider or IScheduledEventProvider interfaces. They interact with Notification Services only to introduce events. These independent event providers are either standalone assemblies or they are hosted by another application platform such as Internet Information Services (IIS).

Document all event providers used by your application, both hosted and independent, in the <Providers> node of the application definition file (ADF). This allows Notification Services to tag every event batch with the name of the event provider that submitted it, which can be helpful information when you are troubleshooting or generating system statistics.

Standard Event Providers

To help you get a Notification Services application developed and deployed quickly, Notification Services comes with two standard event providers. In addition, you can develop custom event providers that are tailored to your environment and event sources.

You can use the standard event providers in your application by specifying predefined values in the <Provider> node in the ADF. You customize event providers for use in your application by providing the values for their initialization arguments. For more information about using these event providers, see Standard Event Providers.

The Notification Services API provides the IEventProvider and IScheduledEventProvider interfaces; the Event, EventLoader, and EventCollector classes; and some SQL Server stored procedures to assist you in creating custom event providers. For more information about this topic, see Developing a Custom Event Provider.


Event Collection Models

Two sets of event collection models are used by Notification Services event providers. One set, the data gathering models, determines how the event provider collects events. The other set, the data submission models, determines how the event collector submits events to the application. Most event providers implement one model from each of the two sets.

Data Gathering Models

Your event provider can retrieve new information in one of two ways: pushing or pulling.

Push Model

The event provider can wait for information to be pushed, or sent to it, when an event occurs. For example, a customer enters a request using a form on your Web site. When she confirms the request through your user interface, you can include code that calls the event provider dynamic-link library (DLL) and passes the information to it. In this case the event provider never looks for new data. It always uses data pushed from the event source.

Pull Model

Alternatively, the event provider can pull information from a source by checking that source every so often and gathering any new or updated data it finds. (The pull task of periodically checking for and retrieving updated data is also referred to as polling.)

For example, suppose you want to be notified every time the headline story on your favorite news page changes. You can implement an event provider that monitors that page and looks for changes to the headline text. When the text does change, the event provider gathers the new headline data for input into the Notification Services system. The event provider in this case is responsible for pulling the data it needs. Data is never sent to the event provider from the event source.

Data Submission Models

Your event provider submits new data to your application based on one of two models: either on a schedule, or on the occurrence of an event that meets predefined criteria.

Scheduled Model

A scheduled event provider runs periodically, based on the settings implemented by the application developer in the application definition file (ADF). It starts running, retrieves and submits any new event data, and then shuts down until the next scheduled trigger time.

For example, suppose you want your event provider to periodically provide new stock price data. You can implement a scheduled event provider that runs every five minutes and calls a Web service to get the latest stock price information. The event provider here runs only on the schedule determined by the settings in the /Providers/HostedProvider/Schedule section of the ADF.

Event-Driven Model

An event-driven event provider typically runs continuously, monitoring an event source. Only when data is made available that meets its criteria for collection does it create and submit an event. Alternatively, an event-driven event provider can also run in response to a callback function or some other external stimulus. This external function is what determines that there is valid event data to collect, and it uses the event provider as the means of collecting that data.

For example, imagine that you want to provide notifications composed of aggregated financial data to members of your accounting department. You create a file with this data, and then add the file to an operating system directory that you are monitoring with an event provider. The addition of this file triggers the event provider, which reads the contents of the new file, and writes an event containing the relevant information to Notification Services. In this case, the event provider creates events only in response to file additions to a particular directory. If there are no changes to that directory, then the event provider does not create and submit any events.


Event Chronicles

In Notification Services, events are always processed in batches. An event batch consists of one or more events. An event batch is processed by the notification generation routine only once (except for limited circumstances involving system failures or restarts), and event-driven notifications are produced at this time. After notification generation is complete, the event data in that batch is treated as expired, and is later removed from the system.

However, you might still need to use this event data to produce notifications for scheduled subscriptions, or for other application requirements such as data warehousing. You can use event chronicle tables and rules to store and maintain event data from processed event batches. Event chronicle rules maintain current event information in event chronicle tables.

For more information about event chronicles, see Event Chronicle Tables and Event Chronicle Rules.


Event Chronicle Tables

An event chronicle table is the mechanism for maintaining current event information within Notification Services. Two common reasons for using event chronicle tables are to provide data for scheduled subscriptions, by updating the table with current event data each time an event batch is processed, and to store information about the ranges or history of the event data, for use in preventing duplicate notifications. You can define multiple event chronicle tables if your application requires saving event information for these or other purposes.

Document event chronicle table information in the /EventClasses/EventClass/Chronicles section of your application definition file (ADF).


Event Chronicle Rules

If you choose to use event chronicle tables in your application, you must define the event chronicle rules that maintain their data. You define Transact-SQL queries within the rule to insert, update, or delete data in the chronicle tables, in order to keep it in a usable state for your application. For instance, each time a new event batch is processed, you might want to delete all existing data in an event chronicle table and then insert the fresh event data.

Event chronicle rules can be defined in the <ChronicleRule> node of an event class, or in the <EventRules> node of a subscription class. If you want the event chronicle rule to affect chronicle data before notifications are generated, you should define it in the <ChronicleRule> node of an event class. If you want the event chronicle rule to affect chronicle data after notifications are generated, you should define it in the <EventRules> node of a subscription class.

If the event chronicle rule is specified in the event class <ChronicleRule> node, it is run each time the generator processes an event batch that contains events of that event class. If it is specified in the subscription class <EventRules> node, it is run each time event-driven notifications are generated for that subscription class.

In addition to event chronicle rules, notification generation rules and subscription chronicle rules are also defined as part of subscription classes. The execution of the event class rules and subscription class rules depends on the arrival of event batches for the event class. The rules specified in the event class <ChronicleRule> node run first, followed by any rules specified in the subscription class <EventRules> node. If any of the <ChronicleRule> rules fail to execute, all <EventRules> rules associated with the same event class are also marked as failed for the remainder of the current generator quantum. Any rules specified in the subscription class <ScheduledRules> node execute when any scheduled subscription of that subscription class comes due, so the success or failure of <ChronicleRule> or <EventRules> rules has no impact on their execution schedule.

See Also

Subscription Chronicles

Subscription Rules


Example: Providing Data to Scheduled Subscriptions

The following example shows the use of an event chronicle table to provide event data for scheduled subscriptions. In this example, a weather update application notifies users about the forecast for their area each day.

Every hour on the hour, weather information is updated in the application database. Your scheduled subscription is defined to give you a weather update notification at 08:15 GMT every weekday.

At 08:00 GMT, a new batch of events arrives with the latest weather information. This information is used to generate any event-driven subscriptions, and then is used to refresh the information in the WeatherEventChron event chronicle table, as shown in the following Transact-SQL code:

<EventClasses>
   <EventClass>
      ...
      <ChronicleRule>
         <RuleName>WeatherChronUpdate</RuleName>
         <!-- Delete all current WeatherEventChron records, and then
         insert the latest forecast records into WeatherEventChron -->
         <Action>
         DELETE WeatherEventChron
         INSERT WeatherEventChron
         (EventId, Location, Forecast)
         SELECT EventId, Location, Forecast
         FROM WeatherEvents
         </Action>
      </ChronicleRule>
      ...
   </EventClass>
</EventClasses>

The notification generation rule defined in a subscription scheduled rule for this application uses the event chronicle table to provide event data for its scheduled subscriptions. Using an event chronicle table allows it to provide this information quickly, from internal database tables, instead of retrieving this information from an event provider each time a scheduled subscription is due:

<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <ScheduledRule>
         <RuleName>WeatherScheduledSubs</RuleName>
         <!-- Provide data from WeatherEventChron
         based on a location match. -->
         <Action>
         SELECT dbo.WeatherNotificationNotify(S.SubscriberId,
         S.SubscriberDeviceName, S.SubscriberLocale,
         C.Location, C.Forecast)
         FROM WeatherSubscriptions S JOIN WeatherEventChron C
         ON S.Location = C.Location
         </Action>
      </ScheduledRule>
      ...
   </SubscriptionClass>
</SubscriptionClasses>


Example: Comparing Event Data to Prevent Duplicate Notifications

The following example shows the use of an event chronicle table to avoid redundant notifications based on previously received event data — only new, unique data is sent out to subscribers. In this example, a news update application notifies users about the new headlines on a particular news Web site.

Your event-driven subscription is defined to notify you any time a new headline is posted to the news Web site. The news Web site provides no way for the event provider to know when the headline changes, so the event provider collects the contents of the headline element every 15 minutes. The data for the morning is shown in the following table.

Time in | News headline
09:00 GMT | Political Gridlock in Olympia
09:15 GMT | Political Gridlock in Olympia
09:30 GMT | Wildfire in the Cascades

You receive a notification based on the 09:00 GMT data, containing the current headline, "Political Gridlock in Olympia." After the event batch is processed and your notification is generated, a row for the current headline is inserted in the event chronicle table by an event chronicle rule that is defined for this application.

The notification generation rule defined in the subscription rules for this application uses the event chronicle table to prevent duplicate notifications. It does this by excluding any events whose headline value already exists in the event chronicle table:

<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <EventRules>
         <EventRule>
            <RuleName>GenerateNewsNotifications</RuleName>
            <!-- Provide Headline data that does not
            already exist in NewsEventChron. -->
            <Action>
            SELECT dbo.NewsNotificationNotify(S.SubscriberId,
               S.SubscriberDeviceName, S.SubscriberLocale,
               E.Headline, E.BrowseBackURL)
            FROM NewsSubscriptions S, NewsEvents E
            WHERE E.Headline
            NOT IN (SELECT Headline from NewsEventChron)
            INSERT NewsEventChron(Headline)
            SELECT NewsEvents.Headline
            FROM NewsEvents
            WHERE NewsEvents.Headline
            NOT IN (SELECT Headline FROM NewsEventChron)
            </Action>
         </EventRule>
      </EventRules>
      ...
   </SubscriptionClass>
</SubscriptionClasses>

Based on this example, the notification process proceeds as follows:

  • The first headline, "Political Gridlock in Olympia," is not in the chronicle table, and is sent to you as a notification. The chronicle table is then updated with this headline.
  • The second headline, "Political Gridlock in Olympia," is identical to an existing record (from the first headline) in the chronicle table. It is not sent to you, and the chronicle table is not updated.
  • The third headline, "Wildfire in the Cascades," is not in the chronicle table, and is sent to you as a notification. The chronicle table is then updated with this headline.


Example: Using Event Data High Values to Prevent Duplicate Notifications

The following example shows the use of an event chronicle table to prevent redundant notifications based on the highest values for event data during a specified time period. In this example, a stock notification application provides users with notifications when their selected stocks cross predefined thresholds.

The application gets new stock event data every 20 minutes from a Web service. The data for the morning is shown in the following table.

Time in | Event data stock symbol | Event data stock price ($USD)
09:00 GMT | AWKS | 69.98
09:20 GMT | AWKS | 70.35
09:40 GMT | AWKS | 70.87
10:00 GMT | AWKS | 71.55
10:20 GMT | AWKS | 72.00

Your own event-driven subscription is for a notification when AWKS stock reaches a value of $71.00 (US dollars) or greater. You therefore receive a notification based on the 10:00 GMT data. After the event batch is processed and your notification is generated, the high value for the day so far, $71.55, is entered or updated in the event chronicle table by an event chronicle rule that is defined for this application.

The 10:20 GMT event data arrives for processing. The notification generation rule defined in the subscription rules for this application uses the event chronicle table to prevent duplicate notifications. It does this by excluding any subscriptions whose trigger price has already been passed today, based on the value in the event chronicle table:

<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <EventRules>
         <EventRule>
            <RuleName>GenerateStockNotifications</RuleName>
            <!--  Provide notifications to subscriptions
            whose trigger price is between the new price
            and the last high price. -->
            <Action>
            SELECT dbo.StockNotificationNotify(S.SubscriberId,
               S.SubscriberDeviceName, S.SubscriberLocale,
               E.StockSymbol, E.StockPrice)
            FROM StockSubscriptions S JOIN StockEvents E
            ON S.StockSymbol = E.StockSymbol
            JOIN StockEventChron C
            ON S.StockSymbol = C.StockSymbol
            WHERE S.StockTriggerPrice &lt;= E.StockPrice
            AND S.StockTriggerPrice &gt; C.StockHighPrice
            INSERT StockEventChron(StockSymbol, StockHighPrice)
            SELECT StockEvents.StockSymbol, StockEvents.StockPrice
            FROM StockEvents
            WHERE StockEvents.StockSymbol
            NOT IN (SELECT StockSymbol FROM StockEventChron)
            UPDATE StockEventChron
            SET StockEventChron.StockHighPrice = StockEvents.StockPrice
            FROM StockEvents JOIN StockEventChron
            ON StockEvents.StockSymbol = StockEventChron.StockSymbol
            WHERE StockEvents.StockPrice &gt;
               StockEventChron.StockHighPrice
            </Action>
         </EventRule>
      </EventRules>
      ...
   </SubscriptionClass>
</SubscriptionClasses>

Note The greater-than sign (>) and the less-than sign (<) are reserved characters in XML. If you need to use these characters in Transact-SQL statements, you must use the entity references &gt; and &lt; to replace them. For more information about using reserved characters in the application definition file (ADF), see Reserved Characters.

Any subscription with a trigger price of $71.55 or lower has already received a notification, and does not receive another. Any subscription that has a trigger price greater than the stored high price of $71.55, but less than or equal to the new high price of $72.00, receives a notification. After notifications are generated, the event chronicle rule again updates the event chronicle table with the latest data.


Defining an Event Class

You define an event that you want to gather for your Notification Services application by creating an event class in your application definition file (ADF). You can define one or more event classes for each application you develop.

Event class information is stored in the /EventClasses/EventClass section of the ADF. You must create one <EventClass> node for each event class that you require.

Follow these steps to define an event class:

  1. Name your event class. For more information, see Naming the Event Class.
  2. Define the fields in your event class. Event providers that gather events of this class use these field definitions to validate their event data. These fields are used to provide the schema for the event table in SQL Server that stores the event data. For more information, see Defining the Event Fields.
  3. Optionally, designate the SQL Server filegroup on which the event table should be created. If you do not specify a filegroup, the event table is automatically created on the default filegroup for the application database. For more information, see Designating the Filegroup.
  4. If you want to index your event table, provide Transact-SQL statements to create one or more indexes on your event table. For more information, see Creating the Indexing Statement.
  5. If you use event chronicle tables in your application, define a chronicle rule associated with this event class. The chronicle rule defines queries that manipulate data in one or more event chronicle tables. For more information, see Defining Chronicle Rules.
  6. If you use event chronicle tables in your application, also define one or more event chronicle tables associated with this event class. For more information, see Defining Chronicle Tables.

For more information about the <EventClass> node, see <EventClass> Node.

Note The Notification Services stored procedure NSDiagnosticEventClass can be used to gather information about an event class. For more information about this stored procedure, see NSDiagnosticEventClass.

Example: Defining an Event Class

The following example shows how to create an <EventClass> node. It defines an event class that provides stock information to a notification application:

<EventClasses>
   <!--Example definition of a stock event class. -->
   <EventClass>
      <!--Name of the event class. -->
      <EventClassName>StockEvents</EventClassName>
      <!--Event fields are defined in the Schema section. -->
         <Schema>
         <!--Define the stock symbol field. -->
         <Field>
            <FieldName>StockSymbol</FieldName>
            <FieldType>char(10)</FieldType>
            <FieldTypeMods>not null</FieldTypeMods>
         </Field>
         <!--Define the stock price field. -->
         <Field>
            <FieldName>StockPrice</FieldName>
            <FieldType>money</FieldType>
            <FieldTypeMods>not null</FieldTypeMods>
         </Field>
      </Schema>
      <!--Name of the SQL Server filegroup
      on which the event table will be created. -->
      <FileGroup>Primary</FileGroup>
      <!--The Transact-SQL statement that creates
      an index on the event table. -->
      <IndexSqlSchema>
         <SqlStatement>
         CREATE CLUSTERED INDEX StockIndex
         ON StockEvents (StockSymbol)
         </SqlStatement>
      </IndexSqlSchema>
      <!--The rules that determine the state of the data
      in the event chronicle table. -->
      <ChronicleRule>
         <RuleName>StockEventChronRule</RuleName>
         <Action>
         INSERT StockEventChron
         (StockSymbol, StockHighPrice)
         SELECT StockEvents.StockSymbol, StockEvents.StockPrice
         FROM StockEvents
         WHERE StockEvents.StockSymbol
         NOT IN (SELECT StockSymbol FROM StockEventChron)
         UPDATE StockEventChron
         SET StockEventChron.StockHighPrice = StockEvents.StockPrice
         FROM StockEvents JOIN StockEventChron
         ON StockEvents.StockSymbol = StockEventChron.StockSymbol
         WHERE StockEvents.StockPrice &gt; StockEventChron.StockHighPrice
         </Action>
         <ActionTimeout>P0DT00H05M00S</ActionTimeout>
      </ChronicleRule>
      <Chronicles>
         <!--The Transact-SQL statement that determines the
         structure of the event chronicle table. -->
         <Chronicle>
            <ChronicleName>StockEventChron</ChronicleName>
            <SqlSchema>
               <SqlStatement>
               IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
               WHERE TABLE_NAME = &apos;StockEventChron&apos;)
               DROP TABLE StockEventChron
               </SqlStatement>
               <SqlStatement>
               CREATE TABLE StockEventChron
               (
               StockSymbol char(10),
               StockHighPrice money
               PRIMARY KEY (StockSymbol)
               )
               </SqlStatement>
            </SqlSchema>
         </Chronicle>
      </Chronicles>
   </EventClass>
</EventClasses>


Naming the Event Class

Document the event class name in the <EventClassName> element of the application definition file (ADF).

For more information, see <EventClassName> Element (<EventClass>).

Example

The following example shows how to create an <EventClassName> element. It specifies the name StockEvents for the event class:

<EventClassName>StockEvents</EventClassName>


Defining the Event Fields

Determine the fields you need for storing your event data. Document the event fields in the <Schema> section of the <EventClass> node of the application definition file (ADF). Create one <Field> node in the <Schema> section for each field you define.

The <Field> node has three child elements:

  • <FieldName> (required)
  • <FieldType> (required)
  • <FieldTypeMods> (optional)

For more information about the <Field> node, see <Field> Node (/EventClass/Schema).

<FieldName> Element

Document the field name in the required <FieldName> element.

For more information, see <FieldName> Element (/EventClass/Schema/Field).

<FieldType> Element

Document the field data type in the required <FieldType> element. The field data types must conform to SQL Server data types.

Important You cannot specify an event data field as an Identity column in SQL Server. Notification Services already uses the Identity property to specify a system-generated EventId field.

For more information, see <FieldType> Element (/EventClass/Schema/Field).

<FieldTypeMods> Element

Document null and default settings in the optional <FieldTypeMods> element. These settings must conform to SQL Server Transact-SQL syntax conventions.

Note You must exclude the <FieldTypeMods> element from the <Field> node if you do not use it.

For more information, see <FieldTypeMods> Element (/EventClass/Schema/Field).

Example

The following example shows how to create a <Schema> node. Two event fields are defined: a 10-character stock symbol field, and a stock price field that accepts monetary data:

<Schema>
   <Field>
      <FieldName>StockSymbol</FieldName>
      <FieldType>char(10)</FieldType>
      <FieldTypeMods>NOT NULL</FieldTypeMods>
   </Field>
   <Field>
      <FieldName>StockPrice</FieldName>
      <FieldType>money</FieldType>
      <FieldTypeMods>NOT NULL DEFAULT 10</FieldTypeMods>
   </Field>
</Schema>


Designating the Filegroup

SQL Server provides filegroups to simplify database administration and allow optimal allocation of system data across multiple physical disks. Optimized data allocation can be critical to the performance of high-volume Notification Services applications.

For more information about SQL Server filegroups, see "Files and Filegroups" in SQL Server Books Online.

Specify the name of the filegroup on which you want the event table created in the <FileGroup> element of the <EventClass> node. The filegroup that you name must be one of the filegroups defined as a <NamedFileGroup> in the <Database> node.

Note You must exclude the <FileGroup> element from the <EventClass> node if you do not use it. Your event table will be created on the default filegroup for the application database in this case.

For more information, see <FileGroup> Element (<EventClass>).

Example

The following example shows how to create a <FileGroup> element. The Primary filegroup is selected as the filegroup for the event table:

<Database>
   <NamedFileGroup>
      <FileGroupName>Primary</FileGroupName>
      ...
   </NamedFileGroup>
   <NamedFileGroup>
      <FileGroupName>Secondary</FileGroupName>
      ...
   </NamedFileGroup>
   ...
</Database>
...
<EventClasses>
   <EventClass>
      ...
      <FileGroup>Primary</FileGroup>
      ...
   </EventClass>
</EventClasses>


Creating the Indexing Statement

You can significantly enhance the performance of a Notification Services application by creating appropriate indexes. Indexes speed the location of particular records based on the data in a specified field. Indexes are automatically used when processing a Transact-SQL query, provided that using the indexes improves query performance. (SQL Server makes this determination.)

For more information about SQL Server indexes, see "Table Indexes" in SQL Server Books Online. Microsoft strongly encourages you to review this documentation to better understand how the performance of your application can be enhanced by this feature.

Note Indexes defined in the <IndexSqlSchema> node of an <EventClass> node are created against a SQL Server view that bears an identical name to the event table. This view contains only the most recent events, instead of the full set of all of the events in the system. Using this subset of events in a view significantly improves rule processing time by reducing the number of records involved.

The <IndexSqlSchema> node has one required child element, <SqlStatement>. For more information, see <IndexSqlSchema> Node (<EventClass>).

In an <IndexSqlSchema> node, use Transact-SQL CREATE INDEX statements in <SqlStatement> elements to define any indexes you want. Use the event class name (for example, StockEvents) for the event table name. For more information, see <SqlStatement> Element (/EventClass/IndexSqlSchema).

Note There are several reserved characters in the Notification Services XML vocabulary (>, <, ', ", &, %). If you need to use these characters in your Transact-SQL statements, you must use entity references to replace them. For more information about using reserved characters in the application definition file (ADF), see Reserved Characters.

Note You must exclude the <IndexSqlSchema> node from the <EventClass> node if you do not use it.

Example

The following example shows how to create an <IndexSqlSchema> node. It creates an index named StockIndex on the StockSymbol field of the StockEvents table in the application database:

<IndexSqlSchema>
   <SqlStatement>
   CREATE INDEX StockIndex
   ON StockEvents (StockSymbol)
   </SqlStatement>
</IndexSqlSchema>


Defining Chronicle Rules

If you are using event chronicle tables, you must define a chronicle rule. The chronicle rule contains the Transact-SQL queries that manipulate the data in the event chronicle tables.

Document chronicle rule information in the <ChronicleRule> node of the <EventClass> node. Define the Transact-SQL queries that determine the actions of the rule in the <Action> element.

Note You must exclude the <ChronicleRule> node from the <EventClass> node if you do not use it.

The <ChronicleRule> node has three child elements:

  • <RuleName> (required)
  • <Action> (required)
  • <ActionTimeout> (optional)

For more information, see <ChronicleRule> Node.

<RuleName> Element

Document the rule name in the <RuleName> element of the <ChronicleRule> node. For more information, see <RuleName> Element (<ChronicleRule>).

<Action> Element

Define one or more Transact-SQL statements in the <Action> element, specifying the actions that this rule should take. You can either define a Transact-SQL query directly, or call a stored procedure (of the format EXEC storedProcedureName) that provides the same functionality. For more information about creating Transact-SQL queries, see "Query Fundamentals" in SQL Server Books Online.

Use the event class name (for example, StockEvents) for the event table name.

All statements that you define in the <Action> element are part of the same transaction, so either they will all complete successfully or they all will be rolled back. If the event chronicle rule fails, an error is written to the system log. Also, any event subscription rules that are associated with events of this class are not fired.

Note There are several reserved characters in the Notification Services XML vocabulary (>, <, ', ", &, %). If you need to use these characters in your Transact-SQL statements, you must use entity references to replace them. For more information about using reserved characters in the application definition file (ADF), see Reserved Characters.

For more information, see <Action> Element (<ChronicleRule>).

<ActionTimeout> Element

The <ActionTimeout> element specifies the permitted length of time for statements in the <Action> element to complete. If they are not completed during this time, the transaction containing them is rolled back, and an error is written to the system log.

Note You must exclude the <ActionTimeout> element from the <ChronicleRule> node if you do not use it.

For more information, see <ActionTimeout> Element (<ChronicleRule>).

Example

The following example shows how to create a <ChronicleRule> node. It creates the event chronicle rule StockEventChronRule, which first inserts new stock data into the chronicle table, and then updates existing stock records in the chronicle table. This rule is permitted five minutes to complete successfully:

<ChronicleRule>
   <RuleName>StockEventChronRule</RuleName>
   <Action>
   INSERT StockEventChron
   (StockSymbol, StockHighPrice)
   SELECT StockEvents.StockSymbol, StockEvents.StockPrice
   FROM StockEvents
   WHERE StockEvents.StockSymbol
   NOT IN (SELECT StockSymbol FROM StockEventChron)
   UPDATE StockEventChron
   SET StockEventChron.StockHighPrice = StockEvents.StockPrice
   FROM StockEvents JOIN StockEventChron
   ON StockEvents.StockSymbol = StockEventChron.StockSymbol
   WHERE StockEvents.StockPrice &gt; StockEventChron.StockHighPrice
   </Action>
   <ActionTimeout>P0DT00H05M00S</ActionTimeout>
</ChronicleRule>

For more information about event chronicle rules, see Event Chronicles.


Defining Chronicle Tables

Event chronicle tables can store event data for use by scheduled subscriptions, or for any other purpose that you devise for your application. You can define one or more event chronicle tables.

Document chronicle table information in the /EventClasses/EventClass/Chronicles section of your application definition file (ADF). Create one <Chronicle> node in the <Chronicles> section for each event chronicle table you want.

Note You must exclude the <Chronicles> node from the <EventClass> node if you do not use it.

The <Chronicle> node has two required child elements:

  • <ChronicleName>
  • <SqlSchema>

For more information, see <Chronicle> Node (/EventClass/Chronicles).

<ChronicleName> Element

Document the chronicle name in the <ChronicleName> element. For consistency, the chronicle name you define here and the name of the chronicle table you create in the <SqlSchema> element should be the same. For more information, see <ChronicleName> Element (/EventClass/Chronicles/Chronicle).

<SqlSchema> Node

Document the schemas for creating your event chronicle tables in the <SqlSchema> node. The <SqlSchema> node has one required child element, <SqlStatement>. For more information, see <SqlSchema> Node (/EventClass/Chronicles/Chronicle).

At the top of the <SqlSchema> node, include a <SqlStatement> element with a Transact-SQL statement to check for any chronicle tables you are about to create, and drop them if they exist. Then use Transact-SQL CREATE TABLE statements in additional <SqlStatement> elements to define any chronicle tables you want. Define one Transact-SQL CREATE TABLE statement for each chronicle table that you want; this statement must include the table name, and the field names and their data types. It can also include arguments for constraints, and any other optional CREATE TABLE parameters. You can also include a CREATE INDEX statement to create an index on your event chronicle table.

You can develop the schema with any text editor, although SQL Query Analyzer, which is installed with SQL Server, is recommended for ease of use. This tool provides templates for creating tables and other objects on the Templates tab of its Object Browser.

Note There are several reserved characters in the Notification Services XML vocabulary (>, <, ', ", &, %). If you need to use these characters in your Transact-SQL statements, you must use entity references to replace them. For more information about using reserved characters in the ADF, see Reserved Characters.

For more information about creating SQL Server tables, see "CREATE TABLE" in SQL Server Books Online.

Example

The following example shows how to create a <Chronicles> node. It creates the event chronicle table StockEventChron, which consists of the StockSymbol and StockPrice fields:

<Chronicles>
   <!--The Transact-SQL statement that determines the
   structure of the event chronicle table. -->
   <Chronicle>
      <ChronicleName>StockEventChron</ChronicleName>
      <SqlSchema>
         <SqlStatement>
         IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
         WHERE TABLE_NAME = &apos;StockEventChron&apos;)
         DROP TABLE StockEventChron
         </SqlStatement>
         <SqlStatement>
         CREATE TABLE StockEventChron
         (
         StockSymbol char(10),
         StockHighPrice money
         PRIMARY KEY (StockSymbol)
         )
         </SqlStatement>
      </SqlSchema>
   </Chronicle>
</Chronicles>

For more information about event chronicle tables, see Event Chronicles.


Defining an Event Provider

You document the event providers that your Notification Services application uses in your application definition file (ADF). You can use one or more event providers to provide event data to your application.

You specify hosted event provider information in the /Providers/HostedProvider section of the ADF, and independent event provider information in the /Providers/NonHostedProvider section of the ADF. You create one <HostedProvider> or <NonHostedProvider> node for each event provider that you have defined.

Follow these steps to define an event provider:

  1. Name your event provider. For more information, see Naming the Event Provider.
  2. If you are defining a hosted event provider (either standard or custom), document the class name of your event provider. This step is not required for independent event providers. For more information, see Documenting the Event Provider Class Name.
  3. If you are defining a custom hosted event provider, document the assembly name of your event provider. This step is not required for independent event providers or standard event providers. For more information, see Documenting the Event Provider Assembly Name.
  4. If you are defining a hosted event provider, identify the server that runs the provider function of Notification Services. This step is not required for independent event providers. For more information, see Identifying the Notification Services System Computer.
  5. If you are defining a scheduled event provider, define the schedule for your event provider. This step is required only for scheduled hosted event providers. This step is not required for event-driven or independent event providers. For more information, see Defining the Event Provider Schedule.
  6. If you are defining a hosted event provider that requires arguments, define the arguments that should be passed to your event provider each time it is initialized. This step is unnecessary for event providers that do not require any arguments, or for independent event providers. For more information, see Defining the Event Provider Arguments.

For more information about the <HostedProvider> node, see <HostedProvider> Node. For more information about the <NonHostedProvider> node, see <NonHostedProvider> Node.

Note The Notification Services stored procedures NSDiagnosticEventProvider and NSEventBatchDetails can be used to gather information about an event provider and submitted events. For more information about these stored procedures, see NSDiagnosticEventProvider and NSEventBatchDetails.

Example: A Hosted Event Provider Definition

This example shows how to document a custom hosted event provider named StockEP:

<Providers>
   <!-- Example definition of a hosted event provider. -->
   <HostedProvider>
      <!-- Name of the event provider. -->
      <ProviderName>StockEP</ProviderName>
      <!-- Name of the event provider's class. -->
      <ClassName>StockData.StockProvider</ClassName>
      <!-- Name of the event provider's assembly. -->
      <AssemblyName>C:\EventProviders\CustomProviders\StockProvider.dll</AssemblyName>
      <SystemName>%SYSNAME%</SystemName>
      <!-- Schedule that determines the run
      times of the event provider. -->
      <Schedule>
         <StartTime>22:00:00</StartTime>
         <Interval>P0DT00H05M00S</Interval>
      </Schedule>
      <!-- Arguments required to initialize the event provider. -->
      <Arguments>
         <Argument>
            <Name>URL</Name>
            <Value>www.microsoft.com/stockvalues</Value>
         </Argument>
      </Arguments>
   </HostedProvider>
</Providers>
Example: An Independent Event Provider Definition

This example shows how to document a custom independent event provider named EventWatcher:

<Providers>
   <!-- Example definition of an independent event provider. -->
   <NonHostedProvider>
      <!-- Name of the event provider. -->
      <ProviderName>EventWatcher</ProviderName>
   </NonHostedProvider>
</Providers>


Naming the Event Provider

Define the event provider name in the <ProviderName> element.

For more information about the <ProviderName> element, see <ProviderName> Element (<HostedProvider>) or <ProviderName> Element (<NonHostedProvider>).

Example

The following example shows how to create a <ProviderName> element. It specifies the name StockEP for the event provider:

<ProviderName>StockEP</ProviderName>


Documenting the Event Provider Class Name

You must document the class name of the class that implements any hosted event provider. For custom hosted event providers, the class name must conform to the Microsoft .NET Framework naming convention of namespace.className. For more information about namespace naming conventions, see Namespace Naming Guidelines in the Microsoft MSDN® Library.

For standard Notification Services event providers, the class name should be provided without the namespace, simply as className. For more information about implementing the standard Notification Services event providers, see Standard Event Providers.

Enter the class name in the <ClassName> element. For more information, see <ClassName> Element (<HostedProvider>).

Example

The following example shows how to create a <ClassName> element. It specifies that the event provider is implemented by the StockProvider class in the StockData namespace:

<ClassName>StockData.StockProvider</ClassName>


Documenting the Event Provider Assembly Name

You must specify the location of the assembly that contains the hosted event provider class in the <AssemblyName> element. This must be done for any custom hosted event providers that you create. Standard Notification Services event providers do not require this information.

You must provide the full path and the assembly file name as the value for the <AssemblyName> element.

Note If you are documenting a standard Notification Services event provider, you must exclude the <AssemblyName> element from the <HostedProvider> node.

For more information, see <AssemblyName> Element (<HostedProvider>).

Example

The following example shows how to create an <AssemblyName> element. It specifies that the StockProvider.dll assembly contains the event provider implementation class:

<AssemblyName>C:\EventProviders\CustomProviders\StockProvider.dll</AssemblyName>


Identifying the Notification Services System Computer

You must identify the name of the server that runs the provider host function provided by the Notification Services engine. Document this information in the <SystemName> element.

You will rarely define this value at development time. Most often, an application parameter is used to pass this information in from a setting in the configuration file or from the command line. For more information about using application parameters, see Defining Application Parameters.

For more information, see <SystemName> Element (<HostedProvider>).

Example

The following example shows how to create a <SystemName> element. It specifies that the provider host runs on the server represented by the %SYSNAME% parameter:

<SystemName>%SYSNAME%</SystemName>


Defining the Event Provider Schedule

The event provider schedule (optional) determines when a scheduled hosted event provider is started for the first time, and how frequently it runs thereafter. Define the schedule in the <Schedule> node of the <HostedProvider> node.

Note You must exclude the <Schedule> node from the <HostedProvider> node if you do not use it.

The <Schedule> node contains two child elements:

  • <StartTime> (optional)
  • <Interval> (required)

For more information, see <Schedule> Node (<HostedProvider>).

<StartTime> Element

You can use the <StartTime> element to determine how the schedule intervals fall within a 24-hour period. The time value itself is not used, but rather the general time period it specifies. For example:

Your <StartTime> element has a value of 10:00:00, and your <Interval> element is set for 5 minutes. When your application starts, it waits until the first even five-minute interval that occurs, and then runs every 5 minutes thereafter. So, if your application was started at 14:38 GMT, your event provider waits until the first interval that is divisible by 5 (14:40 GMT), then runs at 14:40 GMT, 14:45 GMT, and so on.

You must specify the <StartTime> element value in coordinated universal time (UTC) notation.

Note You must exclude the <StartTime> element from the <HostedProvider> node if you do not use it. If you do not specify a start time, the event provider starts when your application starts, and then runs at intervals based on when the system came on line. For example, if you have an interval of 5 minutes, and you start your application at 11:22 GMT, your event provider runs at 11:22 GMT, 11:27 GMT, 11:32 GMT, and so on.

For more information, see <StartTime> Element (/HostedProvider/Schedule).

<Interval> Element

Use the <Interval> element to specify how often the event provider should be triggered. For more information, see <Interval> Element.

Example

The following example shows how to create a <Schedule> node. It specifies that the event provider runs at the first five-minute interval after it is started, and then every five minutes thereafter:

<Schedule>
   <StartTime>22:00:00</StartTime>
   <Interval>P0DT00H05M00S</Interval>
</Schedule>


Defining the Event Provider Arguments

Define any arguments that your hosted event provider requires, and provide the requisite argument values.

If you are using a Notification Services standard event provider, you document the predefined arguments that are required, and you then specify the application-specific values you want to provide for them. For a custom event provider, define any arguments you choose to use, and also provide values for them.

Document event provider arguments in the <Arguments> section of the <HostedProvider> node. Create one <Argument> node within the <Arguments> section for each argument you define.

Note You must exclude the <Arguments> node from the <HostedProvider> node if you do not use it.

Each <Argument> node has two required child elements:

  • <Name>
  • <Value>

For more information, see <Argument> Node (/HostedProvider/Arguments).

You specify the argument name in the <Name> element. For more information about the <Name> element, see <Name> Element (/HostedProvider/Arguments/Argument).

You specify the argument value in the <Value> element. For more information about the <Value> element, see <Value> Element (/HostedProvider/Arguments/Argument).

Example

The following example shows how to create an <Argument> node. The defined argument supplies the URL that the event provider uses to locate new stock price information:

<Arguments>
   <Argument>
      <Name>URL</Name>
      <Value>www.microsoft.com/stockvalues</Value>
   </Argument>
</Arguments>


Standard Event Providers

Notification Services provides two standard event providers to assist you in getting a Notification Services application developed and deployed quickly:

  • File System Watcher Event Provider: This event provider monitors an operating system directory, and is triggered when an XML file is added to the directory. It reads the file contents into memory, and then uses an EventLoader object to write the event information to the event table.
  • SQL Server Event Provider: This event provider uses a developer-defined Transact-SQL query to poll a database table for changes or additions to its data. It then uses Notification Services–provided stored procedures to create events based on this new or updated data, and to write these events to the event table.


File System Watcher Event Provider

The file system watcher event provider is a standard event provider implemented within Microsoft.SqlServer.NotificationServices.dll. It is a standard component of Notification Services.

The file system watcher event provider uses the FileSystemWatcher class defined in the Microsoft .NET Framework class library to monitor .xml file additions to a given directory. When a new file with a .xml extension is dropped into the designated directory, the file system watcher event provider loads the file into memory, and then uses an EventLoader object provided by Notification Services to write the event information into the event table.

Important The XML source file should be created and populated in a different directory than the one being monitored by the file system watcher event provider. This is to prevent the event provider from attempting to pick up the source file immediately after it has been created, possibly while you are still writing events to it.

When the event batch has been written to the database, the XML source file is renamed to indicate that it has been processed. The new file name is the original file name, to which is appended the date and time of its processing, a counter value to differentiate files processed at the same time, and a .done extension.

For example, if a file named Alerts.xml were processed on September 9, 2001 at 10:34:22, it would be renamed to Alerts.xml.20010922-103422.countervalue.done.

Files that are being added to the monitored directory must be in XML format. You must provide a run-time argument to this event provider specifying the path and name of a SQL-annotated XML schema file that transforms the XML data into the event data format.

The file system watcher event provider can only process properly formatted XML files. Proper formatting consists of being able to be transformed by the specified SQL-annotated XML schema file. If an invalid XML file is added to the monitored directory, and the file system event provider cannot successfully process it, the event provider logs an error in the event log and then renames the suspect file so that it is not picked up for processing again. If a non-XML file is added to the monitored directory, it is ignored.

The file system watcher event provider processes all valid files that are already present in the directory when the event provider is started. After that, it processes new files as they are added. Updates to existing files in the directory are not processed, because these changes do not cause the event provider to fire.

If you need functionality beyond that of reading event data from new files, you can create a custom event provider. More information about this can be found in Developing a Custom Event Provider.

Example: SQL-Annotated XML Schema File

The following schema defines the structure for the StockEvents event class.

You must provide the sql:relation annotation for the event element. Its value is modified at run time to be the name of the event table associated with the specified event class:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
   <xsd:element name="event" sql:relation="StockEvents">
      <xsd:complexType>
         <xsd:sequence>
            <xsd:element name="StockSymbol" type="xsd:string" />
            <xsd:element name="StockPrice" type="xsd:float" />
         </xsd:sequence>
      </xsd:complexType>
   </xsd:element>
</xsd:schema>

For more information about creating a SQL-annotated XML schema file, see SQLXML and XML Mapping Technologies in the Microsoft MSDN® Library.


Defining the FileSystemWatcher Event Provider

 SQL Server Notification Services Books Online

Defining the File System Watcher Event Provider

The file system watcher event provider must be defined in the /Service/Providers/HostedProvider section of the application definition file (ADF). The following list reviews the elements in this section and provides the required values for each of them:

<ProviderName> (required)

This value must be a unique name within your application.

<ClassName> (required)

This value must be "FileSystemWatcherProvider".

<AssemblyName> (not used)

This element is not used. Notification Services looks at the Microsoft.SqlServer.NotificationServices.dll assembly for standard event provider information.

<SystemName> (required)

This value must be the name of the computer that runs the provider host function of Notification Services.

<Schedule> and child elements (not used)

This node is not used with this event provider. The file system watcher event provider is a continuous provider, and so does not need defined scheduling information.

<Arguments> and child elements

The file system watcher event provider requires three named arguments as initialization parameters. You can specify them in any order:

  • WatchDirectory specifies the full path and name of the directory that the event provider monitors as its value. Both standard and Universal Naming Convention (UNC) naming conventions can be used.
  • EventClassName specifies the name of the event class that defines the events that the event provider gathers. You must provide the event class name as documented in the /EventClasses/EventClass/EventClassName section of the ADF as the argument value.
  • SchemaFile specifies the full path to a file containing the SQL-annotated XML schema used to transform the XML file data into the appropriate event format.

    Note The SQL-annotated XML schema provided in the SchemaFile argument must handle all of the fields defined in the event class. If an event field is missing from the schema file, the file system watcher event provider fails with an "80004005: the statement has been terminated" error, and an .err file is created in the watch directory.

For more information about defining an event provider, see Defining an Event Provider.

File System Watcher Event Provider Definition

The following code example shows how to document an implementation of the file system watcher event provider named StockWatcher:

<Providers>
   <HostedProvider>
      <ProviderName>StockWatcher</ProviderName>
      <ClassName>FileSystemWatcherProvider</ClassName>
      <SystemName>NSSERVER01</SystemName>
      <Arguments>
         <Argument>
            <Name>WatchDirectory</Name>
            <Value>C:\StockInfo\NewEvents</Value>
         </Argument>
         <Argument>
            <Name>EventClassName</Name>
            <Value>StockEvents</Value>
         </Argument>
         <Argument>
            <Name>SchemaFile</Name>
            <Value>C:\Schemas\StockEventSchema.xsd</Value>
         </Argument>
      </Arguments>
   </HostedProvider>
</Providers>


SQL Server Event Provider

The event provider in Notification Services is a standard event provider implemented within Microsoft.SqlServer.NotificationServices.dll. It is a standard component of Notification Services. It uses a developer-defined Transact-SQL query to identify and query a database table for event data. The SQL Server event provider uses SQL Server stored procedures to collect new event data and submit the data directly to the event table. Additional Transact-SQL queries can also be specified to do processing before and after gathering the event data. All of these queries are passed as arguments to the SQL Server event provider when it is initialized.

If you want to use SQL Server data to create your events, but need functionality beyond that of querying a table, develop a custom event provider. For more information, see Developing a Custom Event Provider.


Defining the SQL Server Event Provider

The SQL Server event provider must be defined in the /Providers/HostedProvider section of the application definition file (ADF). The following list reviews the elements in this section and provides their required values:

<ProviderName> (required)

This value must be a unique name within your application.

<ClassName> (required)

This value must be "SQLProvider".

<AssemblyName> (not used)

This element is not used. Notification Services looks at the Microsoft.SqlServer.NotificationServices.dll assembly for standard event provider information.

<SystemName> (required)

This value must be the name of the computer that runs the provider host function of Notification Services.

<Schedule> and child elements (required)

These values follow the same conventions specified in Defining an Event Provider.

<Arguments> and child elements

The SQL Server event provider can take three named arguments to act as initialization parameters. You can specify them in any order:

  • EventsQuery (required) gathers event data as its value. The only restriction on this query is that it must return columns that map to the event fields specified in the /EventClasses/EventClass/Schema section of the ADF. Values for all of the event fields must be returned.

    The SQL Server event provider runs against the local SQL Server instance. If you want to use a table on a remote server in your EventsQuery query, create a linked server. This allows you to use four-part names (server.db.owner.object) to access objects on the remote server. For more information, see "Configuring Linked Servers" in SQL Server Books Online.

  • PostQuery (optional) does any processing that is required after event data is gathered as its value.
  • EventClassName (required) specifies the name of the event class for which this event provider is configured to submit events.

For more information about defining an event provider, see Defining an Event Provider.

SQL Server Event Provider Definition

The following code example shows how to document an implementation of the SQL Server event provider named SQLStock:

<Providers>
   <HostedProvider>
      <ProviderName>SQLStock</ProviderName>
      <ClassName>SQLProvider</ClassName>
      <SystemName>SLEIPNIR</SystemName>
      <Schedule>
         <Interval>P0DT00H00M60S</Interval>
      </Schedule>
      <Arguments>
         <Argument>
            <Name>EventsQuery</Name>
            <Value>SELECT StockSymbol, StockPrice FROM StockTable</Value>
         </Argument>
         <Argument>
            <Name>EventClassName</Name>
            <Value>StockEvents</Value>
         </Argument>
      </Arguments>
   </HostedProvider>
</Providers>


Subscriptions

Subscriptions determine what notifications subscribers receive. A service that offers daily weather updates, for example, typically allows subscribers to request weather information for specific cities, rather than sending everyone the same nationwide forecast.

Subscriptions also determine when subscribers receive notifications. Subscriptions can be scheduled for specific times. A subscriber to a service that offers traffic updates, for example, can schedule her subscription to provide traffic notifications at 16:45 Greenwich Mean Time (GMT) every weekday. Other subscriptions can permit notifications to be sent at any time, depending on what event information comes into the system.

Additionally, subscriptions can store information about the target devices for the notifications. For instance, a subscriber can have news alerts sent to his instant messaging service during the day, and have traffic alerts sent to his cell phone during commuting hours.

The topics that the Subscriptions section covers are described in the following table.

Topic | Description
Collecting Subscription-Related Information | Describes how subscription-related information is submitted to the Notification Services system.
Subscription Models | Describes the notification delivery models that subscriptions can implement.
Subscription Fields | Discusses required and optional subscription fields that the developer specifies in the application definition file (ADF).
Subscription Rules | Discusses how to use notification generation queries to produce notifications. Includes usage of the notification function and recommendations for creating an efficient query.
Subscription Chronicles | Discusses how subscription chronicle tables and subscription chronicle rules can be used to select notification data based on the content of a prior notification.
Defining a Subscription Class | Discusses how to define a subscription class in the ADF.


Collecting Subscription-Related Information

You develop a subscription management application as a component of your Notification Services system to collect subscriber, subscription, and subscriber device information. Many subscription management applications are Web-based, using Microsoft ASP or ASP.NET technology.

You must use the subscription-related classes provided by the Notification Services API to write data to or retrieve data from the Notification Services databases. These classes can be used natively in managed code or via COM interop in unmanaged code.

See Also

Managing Subscriber Devices

Managing Subscribers

Managing Subscriptions

Subscriber Class

SubscriberDevice Class

Subscription Class


Subscription Models

Subscriptions are either scheduled or event-driven. Scheduled subscriptions provide notifications at a user-defined time, while event-driven subscriptions provide notifications based on when events occur.

Scheduled Subscriptions

Scheduled subscriptions deliver their related notifications at times specified when the subscription is created or updated. The delivery time can be based on frequency, time of day, or specific days or dates. Some possibilities are:

  • Every day at 09:00 GMT
  • Mondays and Fridays at noon
  • 17:00 GMT on the first and fifteenth of every month
  • Yearly at 15:00 GMT on March 7

Scheduled subscriptions often pull data from the event chronicle table. An event chronicle table can be used as a storage system for event information. It is updated each time a new batch of events comes into the Notification Services system, so that it always has the most recent data. That way, when the time for the scheduled notification arrives, the system can save time by simply getting the latest data from an internal table, instead of having to go through the event provider to get the same data from the event source.

Scheduled subscriptions are appropriate for any application in which you want the subscriber to be able to define the times at which they receive notifications. Scheduled subscriptions work particularly well for predictable events about relatively static data. Weather and traffic updates are good examples of this type of data.

Event-Driven Subscriptions

In contrast with scheduled subscriptions, event-driven subscriptions deliver their notifications immediately after processing the related event (although you might want to specify blackout periods during which no notifications are delivered). This type of subscription pulls its data directly from the event table.

Randomly occurring events about time-sensitive data are good candidates for event-driven subscriptions. Auction updates or breaking news alerts are good examples of this type of data.


Subscription Fields

In Notification Services, each subscription is stored as a row in a subscription table. The subscription table is created with the assumption that every subscription record requires certain fields. Other fields are optional, as they are specific to the application. Optional fields are defined in the application definition file (ADF).

  • The SubscriptionId and SubscriberId fields are included in the subscription table automatically, and do not need to be defined in the ADF. SubscriptionId is a bigint identity column, while SubscriberId is an nvarchar(255) column.
  • The Enabled field is included automatically in every subscription record. Setting this Boolean field to false suspends notification generation for this subscription, without removing the record from the database. The Enabled field default is true.
  • The data fields that define your subscription class must be specified by you in the /SubscriptionClasses/SubscriptionClass/Schema section of the ADF. These fields are optional, depending on the specifics of the application. For more information about defining application-specific subscription fields, see Defining Subscription Fields.
  • The subscriber device name and subscriber locale fields are required by the notification function, which matches subscription and event information to produce notifications. They are usually specified in the /SubscriptionClasses/SubscriptionClass/Schema section of the ADF as well. Alternatively, you can provide this information from user profile preference information or from some other source in more complex application scenarios.

    Although including the subscriber device name in every subscription is common, it is not required. For example, there is no need to keep a device name in your subscriptions if your application always delivers notifications by e-mail and you use the subscriber's e-mail address as the subscriber ID. In this case you can simply pass a constant device name, such as "email device", when you generate a notification. Alternatively, you might decide not to include the subscriber's device name in the subscription because you always select the device name dynamically when you generate the notification. For example, your application might select the device based on time of day. During business hours you could send all notifications to a subscriber's business e-mail account; during off-hours you might send critical notifications to the subscriber's phone and all other notifications to the subscriber's home e-mail account.

    Wherever this information resides, it must be provided to Notification Services by specifying these fields as parameters to the notification function. For more information about the notification function, see Using Notification Functions.

The subscriber device name, in conjunction with the subscriber ID, is used to identify the subscriber device record that is associated with this subscription. The subscriber device record contains the information about the recipient device, such as its type and address. This information is used to format the notification data appropriately for display, and to route the notification message for delivery.

The subscriber locale is used to identify the language and country/region of the recipient. This information is used to format the notification data appropriately for display.

If you choose to define the subscriber device name and subscriber locale fields in your ADF, you must specify them as follows:

<Field>
   <FieldName>SubscriberDeviceName</FieldName>
   <FieldType>nvarchar(255)</FieldType>
   <FieldTypeMods>NOT NULL</FieldTypeMods>
</Field>
<Field>
   <FieldName>SubscriberLocale</FieldName>
   <FieldType>nvarchar(10)</FieldType>
   <FieldTypeMods>NOT NULL</FieldTypeMods>
</Field>

For more information about the field elements and what they represent, see Defining a Subscription Class.


Subscription Rules

Notification Services subscriptions have two types of rules associated with them, subscription event rules and subscription scheduled rules.

  • Subscription event rules can contain notification generation rules to generate notifications for event-driven subscriptions, and event chronicle rules to maintain information in event chronicle tables. Subscription event rules are defined as part of a subscription class, and reference a specific event class. Every subscription class can have multiple subscription event rules defined.

    An event chronicle rule should be defined as a subscription event rule if you want the event chronicle rule to affect chronicle data after notifications are generated. If you want the event chronicle rule to affect chronicle data before notifications are generated, you should define it in the <ChronicleRule> node of an event class.

  • Subscription scheduled rules can contain notification generation rules to generate notifications for scheduled subscriptions, and subscription chronicle rules to maintain information in subscription chronicle tables. Subscription chronicle tables maintain information about notification data previously sent to fulfill a subscription. This information can be used to select the data for future notifications based on data that has already been sent. Subscription scheduled rules are defined as part of a specific subscription class, and a single subscription class can have multiple subscription scheduled rules.

A subscription class can include multiple rules of both event and scheduled rule types. There is no guarantee of order regarding the firing of rules of the same type. For example, you might have two subscription scheduled rules (each defined in a separate <ScheduledRule> node), one that generates notifications, and one that updates a subscription chronicle table. There should be no application logic that depends on one rule firing before the other; Notification Services can fire them in any order.

The execution of the event class and subscription class rules depends on the arrival of event batches for the event class. The event chronicle rule executes first, followed by any subscription event rules. If the event chronicle rule fails to execute, all subscription event rules associated with the same event class are also marked as failed for the remainder of the current generator quantum. Subscription scheduled rules execute when scheduled subscriptions of that subscription class come due, so the success or failure of an event chronicle or subscription event rule has no impact on the execution schedule of a subscription scheduled rule.

Note The Notification Services stored procedures NSPrepareRuleFiring and NSExecuteRuleFiring can be helpful in testing and troubleshooting rules. For more information about these stored procedures, see NSPrepareRuleFiring and NSExecuteRuleFiring.

Do not use rules to update the event or subscription tables. The subscription and event tables of a Notification Services system are likely to be among the largest in terms of number of records. Transact-SQL statements operating directly on these tables will of necessity take longer and require more system resources to process, and therefore should not be used in rule statements.

For more information about event chronicle rules, see Event Chronicle Rules.


Using Notification Generation Rules

In order to generate notifications, you must specify at least one notification generation rule in your subscription class. This rule invokes a notification function to create notifications.

Notification generation rules can be defined in either an <EventRule> node or a <ScheduledRule> node of the <SubscriptionClass> node. You can also define notification generation rules in both nodes. In an <EventRule> node, a notification generation rule provides notifications for event-driven subscriptions, and typically matches the most recent batch of events from the events table with the subscription information to produce notifications. In a <ScheduledRule> node, a notification generation rule provides notifications for scheduled subscriptions, and typically matches data in an event chronicle table (which is updated with each batch of events processed) to subscription information to produce notifications. Rules can also use data from other sources (non–Notification Services tables or stored procedures, for example) to produce notifications.

Note Notifications might not be distributed in the same order in which they are generated. The Notification Services distributor has internal logic that determines the order in which notifications are passed to the content formatter. Thus if you write a notification generation rule using a SELECT statement and use an ORDER BY clause to specify notification order, this order will not necessarily be honored by the distributor.

Note A good way to test a notification generation rule is to write the SELECT results to a temporary table, before incorporating the use of the notification function. This allows you to check the results and ensure that the rule is returning the data you expect.


Using Notification Functions

Notification functions are created when the system administrator runs NSControl Create or NSControl Update to create or modify a notification application. During the setup process, Notification Services reads the application definition file (ADF) for the application and creates a SQL Server user-defined function for each notification class. The fields used in this notification function are drawn from the notification schema specified in the /NotificationClasses/NotificationClass/Schema/Fields section of the ADF. The notification function name is the concatenation of the notification class name and the word "Notify".

The following code example shows the notification generation query for a notification class called NewsNotification:

/* This statement would be part of a subscription rule,
and would appear in either an
<EventRule> or a <ScheduledRule> node
in a <SubscriptionClass> node in the ADF. */
SELECT NewsNotificationNotify(S.SubscriberId, S.SubscriberDeviceName,
S.SubscriberLocale, E.Headline, E.BrowseBackURL)
FROM NewsSubscribers S JOIN NewsEvents E
ON S.SiteName = E.SiteName

As illustrated in the example, in the call to the notification function you must specify these fields in the following order:

  • SubscriberID
  • SubscriberDeviceName
  • SubscriberLocale
  • All the notification fields you defined in the /NotificationClasses/NotificationClass/Schema/Fields section of the ADF

You cannot specify any computed fields in the notification function.

The Notification Services distributor function later uses the subscriber device name and subscriber locale information to format and deliver the notification.

When you use a notification function, a row of raw notification data is written to the notification table. Using the notification function is the only valid way to create a notification in the Notification Services system.

Notification functions also participate in the creation of notification batches. The first time a notification function is called for each firing of a rule, the system creates a new notification batch record. All notifications produced by the processing statement of this rule are included in this new notification batch. When the notification generation is complete, the Notification Services generator function closes this batch so that the new notifications can be distributed.


Writing Efficient Notification Generation Queries

It is very important that the Transact-SQL statements you use in application rules are optimized for rapid execution. Rule performance is key to the overall speed of the Notification Services system. The faster the rules execute, the less time it takes to maintain application information and generate notification data. This is especially true of the notification generation rule. To ensure that you make the notification generation rule as efficient as possible, keep the following guidelines in mind when you are developing it:

  • In a notification generation rule, the WHERE clause specifies the conditions that define a match between subscription and event records. It is important that you keep the WHERE clause as brief as possible, and avoid lengthy arguments.
  • If you have many OR operators in your WHERE clause, the additional table reads increase the processing time for the statement and slow down the Notification Services system as a result. For instance, in the following statement, the database engine must read through the event table three times, once for each of the LIKE comparisons:
    SELECT NewsNotificationNotify(S.SubscriberId, S.SubscriberDeviceId, S.LocaleId,
E.Headline, E.BrowseBackURL)
FROM NewsSubscribers S JOIN NewsEvents E
ON S.SiteName = E.SiteName
WHERE (E.Headline LIKE &apos;&#37;president&#37;&apos;
OR E.Headline LIKE &apos;&#37;government&#37;&apos;
OR E.Headline LIKE &apos;&#37;congress&#37;&apos;)

    Note There are several reserved characters in the Notification Services XML vocabulary (>, <, ', ", &, %). If you want to use these characters in your Transact-SQL statements, you must use entity references to replace them. For more information about using reserved characters in the application definition file (ADF), see Reserved Characters.

  • SQL Server provides several tools and many guidelines for optimizing query performance. You are encouraged to take advantage of these resources to design efficient notification generation queries. For more information, see "Query Tuning" in SQL Server Books Online.

    Note Specifying indexes on your event, subscription, and chronicle tables can improve rule performance. You can use the <IndexSqlSchema> element when defining an event or subscription class to specify one or more indexes on an event or subscription table. You may use an <SqlStatement> element when defining a chronicle to specify an index on a chronicle table.


Subscription Chronicles

A common use of subscription chronicle tables is to store notification data so it can be used by your application after that notification has been sent. You can define one or more subscription chronicle tables in the /SubscriptionClasses/SubscriptionClass/Chronicles section of your application definition file (ADF).

You can define one or more rules to manipulate subscription chronicle table data. These rules contain named sets of Transact-SQL queries that insert, update, and delete data in the chronicle tables, in order to keep it in an appropriate state for use by your application. You document these rules in the /SubscriptionClasses/SubscriptionClass/ScheduledRules or the /SubscriptionClasses/SubscriptionClass/EventRules section of your ADF. These nodes are also used to document notification generation rules. For more information about subscription rules, see Subscription Rules.

The most common use of subscription chronicle tables is for storing data about sent notifications, so that this information can be used to determine the appropriate data for the next notification. To provide time-conditional data, your application needs to either determine when you last received a notification or compare sent notification data against current event data to determine what information is new.

A good example of when to use a subscription chronicle table is in the case of a subscription that provides news updates. It should provide you with only the news information that has been added since your last notification. If the news event data has no date or time information, you must use the story headers to provide a basis for comparison. By storing the story headers that were included in previous notifications, and comparing them to the new event data, you can exclude duplicate story headers from the next notification.


Example: Using a Subscription Chronicle Table

The following code example shows the use of a subscription chronicle table to determine appropriate data for a new notification based on non-timestamp data in prior notifications sent to the subscriber. In this example, a news update application notifies users about the headlines on a particular news site.

Your scheduled subscription is defined to provide you with notifications every day at 12:00 GMT, containing any new headlines that have arrived since your last notification.

The headline data for the last few days is shown in the following table.

Day | News headlines
Monday | Political Gridlock in Olympia Wildfire in Eastern Washington Fugitive Jaywalker Arrested
Tuesday | Political Gridlock in Olympia Wildfire in Eastern Washington Mt. Rainier Shows Activity

You receive notifications at 12:00 GMT based on the Monday data.

After your notification is generated, rows are written to the subscription chronicle table by the subscription scheduled rule that is defined for this application, identifying your subscription ID and each headline you received.

At 12:00 GMT on Tuesday, your scheduled subscription is due again. The notification generation rule defined in the subscription scheduled rule for this application checks the subscription chronicle table as part of processing notifications. It compares each incoming headline to those you have already received, based on the values in the subscription chronicle table. If the headline in the new event batch and the headline in the subscription chronicle table do not match, then a notification with the new headline is generated and sent out to you.

<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <ScheduledRules>
         <ScheduledRule>
            <RuleName>MyScheduledRule</RuleName>
            <Action>
            SELECT dbo.NewsNotificationNotify(S.SubscriberId,
            S.SubscriberDeviceName, S.SubscriberLocale, E.Headline,
            E.BrowseBackURL)
            FROM NewsSubscriptions S, NewsEvents E
            WHERE NOT EXISTS (SELECT C.SubscriptionId, C.Headline
            FROM NewsEventChron C
            WHERE C.SubscriptionId = S.SubscriptionId
            AND C.Headline = E.Headline)
            INSERT INTO NewsEventChron
            (SubscriptionId, Headline)
            SELECT DISTINCT SubscriptionId, Headline
            FROM NewsSubscriptions, NewsEvents
            WHERE NewsEvents.Headline NOT IN
            (SELECT Headline FROM NewsEventChron)
            </Action>
         </ScheduledRule>
      </ScheduledRules>
      ...
   </SubscriptionClass>
</SubscriptionClasses>


Defining a Subscription Class

You define the types of subscriptions your Notification Services application will accept by creating subscription classes in your application definition file (ADF). You can define one or more subscription classes for each Notification Services application you develop.

Follow these steps to define a subscription class:

  1. Name your subscription class. For more information, see Naming the Subscription Class.
  2. Define the fields that make up your subscription class. The field definitions validate any subscription data supplied by a subscription management application. They are also used by Notification Services to create the SQL Server subscription table, which stores the subscription data. SQL Server table creation occurs when the application is added to Notification Services by the system administrator, using the NSControl Create or NSControl Update command. For more information, see Defining Subscription Fields.
  3. Optionally, designate the SQL Server filegroup for the subscription table. If you do not specify a filegroup, the subscription table is automatically created on the same filegroup as the application database. For more information, see Designating the Filegroup.
  4. If you want to index your subscription table, provide Transact-SQL statements to create one or more indexes on your subscription table. For more information, see Creating the Indexing Statement.
  5. You might have an <EventRules> node if you define the event rules associated with this subscription class. You must have at least one notification generation rule defined in either the <EventRules> or the <ScheduledRules> node if you want to generate notifications. Event rules are named sets of one or more Transact-SQL queries that either create notifications or manipulate the data in a subscription chronicle table. Event rules are processed each time a new event batch is processed. For more information about defining event rules, see Defining Event Rules.
  6. You might have a <ScheduledRules> node if you define the scheduled rules associated with this subscription class. You must have at least one notification generation rule defined in either the <EventRules> or the <ScheduledRules> node if you want to generate notifications. Scheduled rules are named sets of one or more Transact-SQL queries that create notifications or manipulate the data in a subscription chronicle table. Scheduled rules are processed whenever a scheduled subscription of this class comes due. For more information, see Defining Scheduled Rules.
  7. If you need subscription chronicle tables in your application, define one or more subscription chronicle tables associated with this subscription class. The subscription chronicle tables store subscription data for use in your application. For instance, you might use a subscription chronicle table to store information about the last notification delivered to a subscriber, and generate the next notification based only on data that has come in during the intervening time. For more information, see Defining Chronicle Tables.

All of this information is stored in the /SubscriptionClasses/SubscriptionClass section of the ADF for the application that uses this subscription class. You create one <SubscriptionClass> node for each subscription class that you have defined.

Note The Notification Services stored procedure NSDiagnosticSubscriptionClass can be used to gather information about a subscription class. For more information about this stored procedure, see NSDiagnosticSubscriptionClass.

Example: Defining a Subscription Class

The following code example shows the definition for the Stock subscription class.

<SubscriptionClasses>
   <SubscriptionClass>
      <SubscriptionClassName>StockSubscriptions</SubscriptionClassName>
      <Schema>
         <Field>
            <FieldName>SubscriberDeviceName</FieldName>
            <FieldType>nvarchar(255)</FieldType>
            <FieldTypeMods>NOT NULL</FieldTypeMods>
         </Field>
         <Field>
            <FieldName>SubscriberLocale</FieldName>
            <FieldType>nvarchar(10)</FieldType>
            <FieldTypeMods>NOT NULL</FieldTypeMods>
         </Field>
         <Field>
            <FieldName>StockSymbol</FieldName>
            <FieldType>char(10)</FieldType>
            <FieldTypeMods>NOT NULL</FieldTypeMods>
         </Field>
         <Field>
            <FieldName>StockTriggerPrice</FieldName>
            <FieldType>money</FieldType>
            <FieldTypeMods>NOT NULL DEFAULT 10</FieldTypeMods>
         </Field>
      </Schema>
      <FileGroup>Secondary</FileGroup>
      <IndexSqlSchema>
         <SqlStatement>
         CREATE INDEX StockSubIndex
         ON StockSubscriptions (SubscriberId)
         </SqlStatement>
      </IndexSqlSchema>
      <EventRules>
         <EventRule>
            <RuleName>StockSubscriptionNotifyRule</RuleName>
            <Action>
            SELECT dbo.EventNotificationsNotify(S.SubscriberId,
            S.SubscriberDeviceName, S.SubscriberLocale,
            E.StockSymbol, E.StockPrice)
            FROM StockSubscriptions S JOIN StockEvents E
            ON S.StockSymbol = E.StockSymbol
            JOIN StockEventChron C
            ON S.StockSymbol = C.StockSymbol
            WHERE S.StockTriggerPrice &lt;= E.StockPrice
            AND S.StockTriggerPrice &gt; C.StockHighPrice
            INSERT StockSubscriptionChron
            (SubscriberId, StockSymbol, StockPrice)
            SELECT S.SubscriberId, S.StockSymbol, E.StockPrice
            FROM StockSubscriptions S JOIN StockEvents E
            ON S.StockSymbol = E.StockSymbol
            </Action>
            <ActionTimeout>P0DT00H01M00S</ActionTimeout>
            <EventClassName>StockEvents</EventClassName>
         </EventRule>
      </EventRules>
      <ScheduledRules>
         <ScheduledRule>
            <RuleName>StockSubScheduledRule</RuleName>
            <Action>
            SELECT dbo.ScheduledNotificationsNotify
            (S.SubscriberId, S.SubscriberDeviceName, S.SubscriberLocale,
            C.StockSymbol, C.StockPrice)
            FROM StockSubscriptions S JOIN StockEventChron C
            ON S.StockSymbol = C.StockSymbol
            WHERE S.StockTriggerPrice &lt;= C.StockHighPrice
            GROUP BY S.StockSymbol, C.StockHighPrice
            INSERT StockSubscriptionChron
            (SubscriberId, StockSymbol, StockPrice)
            SELECT S.SubscriberId, S.StockSymbol, C.StockHighPrice
            FROM StockSubscriptions S JOIN StockEventChron C
            ON S.StockSymbol = C.StockSymbol
            </Action>
            <ActionTimeout>P0DT00H00M45S</ActionTimeout>
         </ScheduledRule>
      </ScheduledRules>
      <Chronicles>
         <Chronicle>
            <ChronicleName>StockSubscriptionChron</ChronicleName>
            <SqlSchema>
               <SqlStatement>
               IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
               WHERE TABLE_NAME = &apos;StockSubscriptionChron&apos;)
               DROP TABLE StockSubscriptionChron
               </SqlStatement>
               <SqlStatement>
               CREATE TABLE StockSubscriptionChron
               (
               SubscriberId  bigint,
               StockSymbol   char(10),
               StockPrice    money
               PRIMARY KEY   (SubscriberId)
               );
               </SqlStatement>
            </SqlSchema>
         </Chronicle>
      </Chronicles>
   </SubscriptionClass>
</SubscriptionClasses>


Naming the Subscription Class

Document the subscription class name in the <SubscriptionClassName> element of the application definition file (ADF).

For more information, see <SubscriptionClassName> Element.

Example

The following example creates a subscription class with the name StockSubscriptions in the ADF:

<SubscriptionClassName>StockSubscriptions</SubscriptionClassName>


Defining the Subscription Fields

Determine the fields you need for storing your subscription data. Document the subscription fields in the <Schema> section of the <SubscriptionClass> node of the application definition file (ADF). Create one <Field> node in the <Schema> section for each field you define.

The <Field> node has three child elements:

  • <FieldName> (required)
  • <FieldType> (required)
  • <FieldTypeMods> (optional)

These elements are summarized later in this topic. For more information, see <Field> Node (</SubscriptionClass/Schema>).

<FieldName> Element

Document the field name in the required <FieldName> element.

For more information, see <FieldName> Element (/SubscriptionClass/Schema/Field).

<FieldType> Element

Document the field data type in the required <FieldType> element. The field data types must conform to SQL Server data types.

Important You cannot specify a subscription data field as a SQL Server Identity column. Notification Services already uses the Identity property to specify a system-generated SubscriptionId field.

For more information, see <FieldType> Element (/SubscriptionClass/Schema/Field).

<FieldTypeMods> Element

Document null and default settings in the optional <FieldTypeMods> element. These settings must conform to SQL Server Transact-SQL syntax conventions.

Note You must exclude the <FieldTypeMods> element from the <Field> node if you do not use it.

For more information, see <FieldTypeMods> Element (/SubscriptionClass/Schema/Field).

Example

In this example, two subscription fields are defined: a 10-character stock symbol field and a stock trigger price field that accepts monetary data. A 255-character subscriber device name field and a 10-character subscriber locale field are also specified, to store subscriber information in the subscription:

<Schema>
   <Field>
      <FieldName>SubscriberDeviceName</FieldName>
      <FieldType>nvarchar(255)</FieldType>
      <FieldTypeMods>NOT NULL</FieldTypeMods>
   </Field>
   <Field>
      <FieldName>SubscriberLocale</FieldName>
      <FieldType>nvarchar(10)</FieldType>
      <FieldTypeMods>NOT NULL</FieldTypeMods>
   </Field>
   <Field>
      <FieldName>StockSymbol</FieldName>
      <FieldType>char(10)</FieldType>
      <FieldTypeMods>NOT NULL</FieldTypeMods>
   </Field>
   <Field>
      <FieldName>StockTriggerPrice</FieldName>
      <FieldType>money</FieldType>
      <FieldTypeMods>NOT NULL DEFAULT 10</FieldTypeMods>
   </Field>
</Schema>


Designating the Filegroup

SQL Server provides filegroups to simplify database administration and allow optimal allocation of system data across multiple physical disks. Optimized data allocation can be critical to the performance of high-volume Notification Services applications.

For more information about SQL Server filegroups, see "Files and Filegroups" in SQL Server Books Online.

Specify the name of the filegroup on which you want the subscription table created in the <FileGroup> element of the <SubscriptionClass> node. The filegroup named must be one of the filegroups defined in the <NamedFileGroup> node of the <Database> node.

Note You must exclude the <FileGroup> element from the <SubscriptionClass> node if you do not use it. Your subscription table will be created on the default filegroup for the application database in this case.

For more information, see <FileGroup> Element (<SubscriptionClass>).

Example

In the following code example, the Secondary filegroup is selected as the filegroup for the subscription table:

<Database>
   <NamedFileGroup>
      <FileGroupName>Primary</FileGroupName>
      ...
   </NamedFileGroup>
   <NamedFileGroup>
      <FileGroupName>Secondary</FileGroupName>
      ...
   </NamedFileGroup>
   ...
</Database>
...
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <FileGroup>Secondary</FileGroup>
      ...
   </SubscriptionClass>
</SubscriptionClasses>


Creating the Indexing Statement

You can significantly enhance the performance of a Notification Services application by creating appropriate indexes. Indexes speed the location of particular records based on the data in a specified field. Indexes are automatically used when processing a Transact-SQL query, provided that using the indexes improves query performance (SQL Server makes this determination).

For more information about SQL Server indexes, see "Table Indexes" in SQL Server Books Online. You are strongly encouraged to review this documentation to better understand how the performance of your application can be enhanced by this feature.

The <IndexSqlSchema> node has one required child element, <SqlStatement>. In an <IndexSqlSchema> node, use Transact-SQL CREATE INDEX statements in <SqlStatement> elements to define any indexes you want. Use the subscription class name (for example, StockSubscriptions) for the subscription table name.

For more information, see <SqlStatement> Element (/SubscriptionClass/IndexSqlSchema).

Note There are several reserved characters in the Notification Services XML vocabulary (>, <, ', ", &, %). If you want to use these characters in your Transact-SQL statements, you must use entity references to replace them. For more information about using reserved characters in the application definition file (ADF), see Reserved Characters.

Note You must exclude the <IndexSqlSchema> node from the <SubscriptionClass> node if you do not use it.

For more information, see <IndexSqlSchema> Element (<SubscriptionClass>).

Example

This example specifies that an index named StockSubIndex will be created on the SubscriberID field of the StockSubscriptions table in the application database:

<IndexSqlSchema>
   <SqlStatement>
   CREATE INDEX StockSubIndex
   ON StockSubscriptions (SubscriberId)
   </SqlStatement>
</IndexSqlSchema>


Defining Event Rules

If you are providing event-driven subscriptions, you must define one or more event rules. These event rules must contain the notification generation rules that create the notifications for event-driven subscriptions. The event rules are executed each time a new event batch is processed. The notification generation rule matches event data from the event table with the subscription information, and uses a notification function to generate a notification based on this match.

For more information about notification generation rules and notification functions, see Using Notification Generation Rules and Using Notification Functions.

Document event rule information in the <EventRules> section of your application definition file (ADF). Create one <EventRule> node for each event rule you define.

The <EventRule> node has four child elements:

  • <RuleName> (required)
  • <Action> (required)
  • <ActionTimeout> (optional)
  • <EventClassName> (required)

These elements are summarized later in this topic. For more information, see <EventRule> Node.

<RuleName> Element

Document the name of the rule in the <RuleName> element of the <EventRule> node.

For more information, see <RuleName> Element (<EventRule>).

<Action> Element

Define one or more Transact-SQL statements in the <Action> element, specifying the actions that this rule should take. You can either define a Transact-SQL query directly, or call a stored procedure (of the format EXEC storedProcedureName) that provides the same functionality.

Use the subscription and event class names (for example, StockSubscriptions and StockEvents) for the subscription and event table names.

All statements that you define in the <Action> element are part of the same transaction, so either they all will complete successfully or they all will be rolled back. If the subscription event rule fails, an error is written to the system log.

Note There are several reserved characters in the Notification Services XML vocabulary (>, <, ', ", &, %). If you want to use these characters in your Transact-SQL statements, you must use entity references to replace them. For more information about using reserved characters in the ADF, see Reserved Characters.

For more information about creating Transact-SQL queries, see "Query Fundamentals" in SQL Server Books Online.

For more information, see <Action> Element (<EventRule>).

<ActionTimeout> Element

The <ActionTimeout> element specifies the permitted length of time for statements in the <Action> element to complete. If they are not completed during this time, the transaction containing them is rolled back, and an error is written to the system log.

Note You must exclude the <ActionTimeout> element from the <EventRule> node if you do not use it.

For more information, see <ActionTimeout> Element (<EventRule>).

<EventClassName> Element

Document the event class associated with the execution of the subscription event rule in the <EventClassName> element. Only the processing of event batches of the specified event class causes execution of the associated rule.

For more information, see <EventClassName> Element (<EventRule>).

Example

The following code example creates the subscription event rule StockSubscriptionEventRule. This rule creates event-driven notifications, and also loads notification data into the StockSubscriptionChron table, for use in data mining on subscription trends. It is executed whenever an event batch containing events of the StockEvents class is processed. This rule is permitted one minute to complete successfully:

<EventRules>
   <EventRule>
      <RuleName>StockSubscriptionEventRule</RuleName>
      <Action>
      SELECT dbo.EventNotificationsNotify(S.SubscriberId,
      S.SubscriberDeviceName, S.SubscriberLocale,
      E.StockSymbol, E.StockPrice)
      FROM StockSubscriptions S JOIN StockEvents E
      ON S.StockSymbol = E.StockSymbol
      JOIN StockEventChron C
      ON S.StockSymbol = C.StockSymbol
      WHERE S.StockTriggerPrice &lt;= E.StockPrice
      AND S.StockTriggerPrice &gt; C.StockHighPrice
      INSERT StockSubscriptionChron
      (SubscriberId, StockSymbol, StockPrice)
      SELECT S.SubscriberId, S.StockSymbol, E.StockPrice
      FROM StockSubscriptions S JOIN StockEvents E
      ON S.StockSymbol = E.StockSymbol
      </Action>
      <ActionTimeout>P0DT00H01M00S</ActionTimeout>
      <EventClassName>StockEvents</EventClassName>
   </EventRule>
</EventRules>


Defining Scheduled Rules

If you are providing scheduled subscriptions, you must define one or more scheduled rules. These scheduled rules must contain the notification generation rules that create the notifications for scheduled subscriptions. The scheduled rules are executed each time a scheduled subscription of the subscription class comes due. The notification generation rule matches event data from an event chronicle table with the subscription information, and uses a notification function to generate a notification based on this match.

For more information about notification generation rules and notification functions, see Using Notification Generation Rules and Using Notification Functions.

Document scheduled rule information in the <ScheduledRules> section of your application definition file (ADF). Create one <ScheduledRule> node for each scheduled rule you define.

The <ScheduledRule> node has three child elements:

  • <RuleName> (required)
  • <Action> (required)
  • <ActionTimeout> (optional)

These elements are summarized later in this topic. For more information, see <ScheduledRule> Node.

<RuleName> Element

Document the name of the rule in the <RuleName> element of the <ScheduledRule> node.

For more information, see <RuleName> Element (<ScheduledRule>).

<Action> Element

Define one or more Transact-SQL statements in the <Action> element, specifying the actions that this rule should take. You can either define a Transact-SQL query directly or call a stored procedure (of the format EXEC storedProcedureName) that provides the same functionality.

Use the subscription and event class names (for example, StockSubscriptions and StockEvents) for the subscription and event table names.

All statements that you define in the <Action> element are part of the same transaction, so either they will all complete successfully or they all will be rolled back. If the subscription scheduled rule fails, an error is written to the system log.

Note There are several reserved characters in the Notification Services XML vocabulary (>, <, ', ", &, %). If you want to use these characters in your Transact-SQL statements, you must use entity references to replace them. For more information about using reserved characters in the ADF, see Reserved Characters.

For more information about creating Transact-SQL queries, see "Query Fundamentals" in SQL Server Books Online. For more information about this element, see <Action> Element (<ScheduledRule>).

<ActionTimeout> Element

The <ActionTimeout> element specifies the permitted length of time for statements in the <Action> element to complete. If they are not completed during this time, the transaction containing them is rolled back and an error is written to the system log.

Note You must exclude the <ActionTimeout> element from the <ScheduledRule> node if you do not use it.

For more information, see <ActionTimeout> Element (<ScheduledRule>).

Example

This example creates the subscription schedule rule StockSubScheduledRule. This rule creates scheduled notifications, and also loads notification data into the StockSubscriptionChron table, for use in data mining on subscription trends. It is executed whenever a scheduled subscription of the subscription class comes due. This rule is permitted 45 seconds to complete successfully:

<ScheduledRules>
   <ScheduledRule>
      <RuleName>StockSubScheduledRule</RuleName>
      <Action>
      SELECT dbo.ScheduledNotificationsNotify
      (S.SubscriberId, S.SubscriberDeviceName, S.SubscriberLocale,
      C.StockSymbol, C.StockPrice)
      FROM StockSubscriptions S JOIN StockEventChron C
      ON S.StockSymbol = C.StockSymbol
      WHERE S.StockTriggerPrice &lt;= C.StockHighPrice
      GROUP BY S.StockSymbol, C.StockHighPrice
      INSERT StockSubscriptionChron
      (SubscriberId, StockSymbol, StockPrice)
      SELECT S.SubscriberId, S.StockSymbol, C.StockHighPrice
      FROM StockSubscriptions S JOIN StockEventChron C
      ON S.StockSymbol = C.StockSymbol
      </Action>
      <ActionTimeout>P0DT00H00M45S</ActionTimeout>
   </ScheduledRule>
</ScheduledRules>


Defining Chronicle Tables

Subscription chronicle tables can store previously sent notification data, which can be used to help determine data that should be sent in future notifications. You can define one or more subscription chronicle tables.

Document chronicle table information in the /SubscriptionClasses/SubscriptionClass/Chronicles section of your application definition file (ADF). Create one <Chronicle> node in the <Chronicles> section for each subscription chronicle table you want.

Note You must exclude the <Chronicles> node from the <SubscriptionClass> node if you do not use it.

The <Chronicle> node has two required child elements:

  • <ChronicleName>
  • <SqlSchema>

These elements are summarized later in this topic. For more information, see <Chronicle> Node (/SubscriptionClass/Chronicles).

<ChronicleName> Element

Document the chronicle name in the <ChronicleName> element. For consistency, the chronicle name you define here and the name of the chronicle table you create in the <SqlSchema> element should be the same.

For more information, see <ChronicleName> Element (/SubscriptionClass/Chronicles/Chronicle).

<SqlSchema> Node

Document the schemas for creating your subscription chronicle tables in the <SqlSchema> node. The <SqlSchema> node has one required child element, <SqlStatement>.

For more information, <SqlSchema> Node (/SubscriptionClass/Chronicles/Chronicle).

At the top of the <SqlSchema> node, include a <SqlStatement> element with a Transact-SQL statement to check for any chronicle tables you are about to create, and drop them if they exist. Then use Transact-SQL CREATE TABLE statements in additional <SqlStatement> elements to define any chronicle tables you want. Define one Transact-SQL CREATE TABLE statement for each chronicle table that you want; this statement must include the table name, and the field names and their data types. It can also include arguments for constraints, and any other optional CREATE TABLE parameters. You can also include a CREATE INDEX statement to create an index on your subscription chronicle table.

You can develop the schema with any text editor, although SQL Query Analyzer, which is installed with SQL Server, is recommended for ease of use. This tool provides templates for creating tables and other objects. Find it on the Templates tab of the SQL Object Browser.

Note There are several reserved characters in the Notification Services XML vocabulary (>, <, ', ", &, %). If you want to use these characters in your Transact-SQL statements, you must use entity references to replace them. For more information about using reserved characters in the ADF, see Reserved Characters.

For more information about creating SQL Server tables, see "CREATE TABLE" in SQL Server Books Online.

Example

The following code example creates the subscription chronicle table StockSubscriptionChron, which consists of the SubscriberID, StockSymbol, and StockPrice fields. This chronicle table stores information about the notification content sent to subscribers, so that it can be used in data mining procedures:

<Chronicles>
   <Chronicle>
      <ChronicleName>StockSubscriptionChron</ChronicleName>
      <SqlSchema>
         <SqlStatement>
         IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
         WHERE TABLE_NAME = &apos;StockSubscriptionChron&apos;)
         DROP TABLE StockSubscriptionChron
         </SqlStatement>
         <SqlStatement>
         CREATE TABLE StockSubscriptionChron
         (
         SubscriberId  bigint,
         StockSymbol   char(10),
         StockPrice    money
         PRIMARY KEY  (SubscriberId)
         );
         </SqlStatement>
      </SqlSchema>
   </Chronicle>
</Chronicles>


Notifications

A notification is a set of data that is produced as a result of matching an event with a subscription that has been set up with a Notification Services application. The notification data consists of the event information that meets the subscription requirements, as well as any additional information the developer wishes to include. The notification is packaged as a message (if appropriate for the delivery protocol) and handed off to an external delivery system for delivery to the subscriber's device.

For example, consider a stock notification application that alerts subscribers to changes in stock prices based on a trigger price that the subscribers specify. A particular subscription is for Adventure Works Cycles stock (represented by the symbol AWKS) passing the price of $71.00 (US). The subscriber speaks French, and wants to receive her notifications on her cellular phone.

The application defines the type of data sent in the notification, in this case information about changes in stock price. The subscription defines what stock data is provided, in this case information about the price of Adventure Works Cycles stock crossing a specific threshold. The subscription information is also likely to determine how the notification is formatted, and when it is generated. This subscriber needs to have her notification formatted with French text, and packaged so that it can be delivered to her cell phone.

Note The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious. No association with any real company, organization, product, domain name, e-mail address, logo, person, places, or events is intended or should be inferred.

The topics that the Notifications section covers are described in the following table.

Topic | Description
Generating Notifications | Describes the components and workflow of the notification generation process.
Formatting Notifications | Describes the components and workflow of the notification formatting process.
Distributing Notifications | Describes the components and workflow of the notification distribution process.
Defining a Notification Class | Discusses how to define a notification class in your application definition file.
XSLT Content Formatter | Describes the standard XSLT content formatter installed with Notification Services, and discusses how to implement it.
Standard Delivery Protocols | Describes the standard delivery protocols installed with Notification Services, and discusses how to implement delivery channels that use them.


Generating Notifications

Notification Services generates notifications based on the subscriptions and events that are entered into the system. It does this by using a notification generation rule, which matches subscription information to event data. When the event data fulfills the subscription requirements, a notification is created and added to the current notification batch. This batch is closed when all of the new events are processed, which makes the notifications it contains available to the distributor for formatting and distribution. You can specify a notification generation rule in either the event rules or the scheduled rules for a subscription class, or both.

A subscription class can provide both event-driven and scheduled subscriptions. You must create rules to handle either or both of these types of subscriptions, depending on your application, when you create your subscription class. Whether a particular subscription is event-driven or scheduled determines when notifications for that subscription are generated and subsequently delivered, and what table is used to provide the event data used in the notification generation rule.

Generating Notifications from Event-Driven Subscriptions

An event-driven subscription has a notification generated for it whenever an incoming event matches the subscription information. For example, an event-driven subscription to a stock update application might specify that a notification be generated when Adventure Works Cycles stock reaches a particular price. You specify a notification generation rule in the /SubscriptionClasses/SubscriptionClass/EventRules section of the application definition file (ADF) that matches the subscription information with the event data in the event table to produce a notification. In the preceding example, the subscription and event data would be matched based on having the same stock symbol, and having the stock price of the event data be equal to or greater than the trigger stock price specified in the subscription data.

Generating Notifications from Scheduled Subscriptions

A scheduled subscription has a notification generated for it at specific times, provided there is matching event information to provide the notification content. For example, a scheduled subscription to a weather update application might specify that a notification containing the forecast for the local area be generated every weekday morning at 08:00 GMT. To produce a notification, you specify a notification generation rule in the /SubscriptionClasses/SubscriptionClass/ScheduledRules section of the ADF that matches the subscription information with the event data in a chronicle table (which is used to store event data state; for more information see Event Chronicles). In the preceding example, the subscription and event data would be matched based on having the same local area ID.

The Generator

The generator function of the Notification Services engine handles notification generation. It fires according to a time period you define in the /ApplicationExecutionSettings/QuantumDuration section of the ADF.

Each time the generator fires, it executes the event chronicle rules, the event subscription rules, and the scheduled subscription rules defined for your application. It applies these rules to all unprocessed event batches that have arrived before or during the current quantum, and to all scheduled subscriptions whose schedule intervals fall within the current quantum.

The output from each firing of the generator is raw notification data, which is stored in batches in the notification table. The generator usually produces one batch per rule firing, except if a notification batch size value is specified. In that case, it breaks up the batch into smaller batches to ensure that the batch size requirements are met. The notification batch size value is defined in the /NotificationClasses/NotificationClass/NotificationBatchSize section of the ADF. In Notification Services Standard Edition, the <NotificationBatchSize> value must be 0. In Notification Services Enterprise Edition, the <NotificationBatchSize> value is configurable.

Note The Notification Services stored procedures NSDiagnosticNotificationClass and NSNotificationBatchDetails can be used to gather information about generated notifications. For more information about these stored procedures, see NSDiagnosticNotificationClass and NSNotificationBatchDetails.

For more information about the details of generator functioning and how this affects system performance, see Specifying Generator Settings. For more information about rule actions and firing order, see Subscription Rules.


Formatting Notifications

In Notification Services, notification generation populates the notification table with batches of raw notification data. After a set of notification batches is completed by the generator function, the batches are made available for formatting by the distributor function. Notification formatting aggregates the notification data, which is composed of notification fields and recipient information, and then formats this data appropriately for its destination device and specified locale.

The work item is the unit on which notification formatting is performed. Each completed notification batch is partitioned into work items by the distributor, which allows the system to take advantage of parallel processing. A work item consists of all the notifications in a batch that are to be distributed through the same delivery channel. The number of work items created per notification batch is based on the number of delivery channels configured for this application, so that there is optimal distribution of the workload.

Aggregating Notification Data

The first step in the formatting process involves aggregating the notification data. The notification fields are selected from the notification table, and the computed field values are generated. The data from these two sources is then gathered together into a single dataset. After it is aggregated, the notification data is then passed to a content formatter.

Aggregation of the data into digest and multicast notifications is also handled at this time, as appropriate. Digest delivery is a way of combining several notifications for the same subscriber into a single notification. Multicast delivery is a way of formatting shared notification data only once and then sending it to multiple subscribers. Multicast delivery is available only in Notification Services Enterprise Edition. Both of these distribution options affect how notification data is grouped and formatted.

The subscriber device name field and the subscriber locale field are considered "built-in" notification fields. They are never explicitly declared in the /NotificationClasses/NotificationClass/Schema section of the application definition file (ADF). Instead, these fields are provided as parameters to the notification function, which is used in a subscription rule to generate notifications. Recipient information, such as the delivery channel, and the subscriber's language as indicated by the locale, is looked up from the Notification Services databases.

Formatting Notification Data

Using the aggregated dataset, the content formatter formats the notification fields for display, by using the recipient information to determine the appropriate formatting.

Formatting takes into account such information as the subscriber locale and the device type, in order to provide notification text in an appropriate language, and to format the content to be displayed correctly on the target device.

When formatting is complete, the content formatter creates a string containing the formatted notification data. The distributor passes this string along to the delivery protocol, which is the Notification Services component that creates the notification message and hands it off to an external delivery system to be delivered to the recipient.

Formatting with the Distributor

The distributor function of the Notification Services engine handles notification formatting and distribution. It creates work items, shepherds them through the formatting and distribution processes as provided by the content formatter and delivery protocol components, and then handles delivery retries if necessary. A distributor runs continuously, requesting work items whenever it has processing cycles available. You might have several distributors servicing your application, with each processing a separate work item from the same batch. Distributors might also process several work items in parallel. These options allow for sharing of the processing load for formatting and distribution, and can affect the speed of your application.

For more information about the details of distributor functioning and how this affects system performance, see Specifying Distributor Settings.


Formatting Digest Notifications

It is often useful to group several individual notifications into one larger notification within one notification batch, if they are all destined for the same subscriber. For example, think of a subscriber who subscribes to traffic update notifications for several potential routes to her office. Rather than send these notifications separately, you can group them into a single notification, which aggregates their content.

Aggregating several notifications into one is called digest delivery. A notification that consists of an aggregation of several other notifications is referred to as a digest notification. The first notification in the set that forms the digest notification is called the digest head notification and the remaining notifications are called digest trailer notifications. The message body is composed of the aggregated information from all the notifications. The <DigestDelivery> element in the /NotificationClasses/NotificationClass section of the application definition file (ADF) enables digest delivery for a notification class. If the value of this element is true, then the notifications of this class in a notification batch are grouped together if they contain common SubscriberId, DeviceName, and SubscriberLocale values.

In a Notification Services Enterprise Edition system, do not specify digest delivery if you have already specified multicast delivery for a notification class. These options are mutually exclusive. If you do specify both options, the NSControl command fails.

Using <DigestGrouping> to Group Notifications

Notifications can also use match fields to narrow grouping criteria. The <DigestGrouping> element, located in both the /NotificationClasses/NotificationClass/Schema/Fields/Field and /NotificationClasses/NotificationClass/Schema/ComputedFields/ComputedField sections of the ADF, indicates whether a field should be used when grouping notifications. The <DigestGrouping> element is available for both regular and computed notification fields. If <DigestGrouping> is true, then the value of the given field is used in selecting notifications to be grouped. Notifications are grouped together only if they have the same subscriber ID, the same device name, and the same value in the given field.

You can use as many match fields as you want in grouping criteria. The more match fields you use, the smaller and more specific your digest notifications will be. However, using more match fields also imposes greater processing requirements, so you should balance use of these fields with application performance considerations.

Processing Digest Delivery Notifications

Each time a distributor processes a work item, it looks for notification data that satisfies the digest grouping criteria and then groups it together. Digesting never occurs across work item or batch boundaries. Notification data in different notification batches or different work items is never digested together.

If digest delivery is being used, then the distributor creates what amounts to an array of datasets for each digest notification. Each element in the array contains the data from one of the originating notifications. This array of datasets is passed to the content formatter, which is responsible for resolving these datasets into a single formatted notification.

See Also

Digest Delivery


Formatting Multicast Notifications

In many cases, the same notification data is sent to multiple subscribers. For example, all subscribers who have subscriptions to the weather forecast for Tokyo, receive the same weather data in their notifications. In these cases, it is not necessary to format the notification data for each subscriber. Formatting can simply be applied to the data once, and this formatted output can then be sent to each subscriber. A notification that contains an aggregation of several subscribers that receive identical data is referred to as a multicast notification.

Formatting the data once and then sending it to multiple subscribers is referred to as multicast delivery. The <MulticastDelivery> element in the /NotificationClasses/NotificationClass section of the application definition file (ADF) enables multicast delivery for a notification class. If the value of this element is true, notifications of this class that contain identical notification data are formatted only once, and then routed to the appropriate list of subscribers. Multicast delivery is available only in Notification Services Enterprise Edition.

In an Enterprise Edition system, do not specify multicast delivery if you have already specified digest delivery for a notification class. These two options are mutually exclusive. If you do specify both options, the NSControl command fails.

Note Multicast notifications and delivery can increase the performance of your application, by reducing the processing load on the distributor. Microsoft recommends that you take advantage of this feature if you have the Enterprise Edition and if it is appropriate for your application.

Processing Multicast Notifications

For notification classes in which multicast delivery is enabled, the distributor takes these actions to format multicast notifications:

It groups the rows in the notifications table by the values for the device type field, subscriber locale field, notification data fields, and computed fields. It sends one set of notification data to the content formatter for each group, and then caches the formatted data that is produced.

It builds a list of subscribers to whom the formatted content should be sent: the subscriber in the first row is added to the list, and then the subscribers in each subsequent row, where the values for the notification and computed fields are the same. The duplicate data contained in these subsequent rows is not sent to the content formatter.

As soon as a row is encountered with different notification and computed field values, the current formatted content and the current subscriber list are handed off to the delivery protocol. Then the process repeats: the data for this next group of notifications is formatted and cached, and a new subscriber list is created.

Multicast Notification Requirements

For multicast delivery to work properly, multicast notifications must not contain any subscriber-specific information , because the same formatted output is being sent to many subscribers. The distributor does not pass any recipient information to the content formatter when multicast delivery is specified. If the content formatter is programmed to use recipient information for formatting, it fails.

Important Notification Services does not prevent incorporation of subscriber-specific information from sources outside of Notification Services, such as external tables, into the notification data during the formatting process.

It is the responsibility of the developer to ensure that any external information that the content formatter adds to the notification data is non-recipient-specific if it is to be used in multicast notifications.

Also, content formatting is often device specific and locale specific. Therefore, multicast delivery is not possible for notifications that have different device type or subscriber locale information. If you have a notification batch in which all the other notification data is the same but the locale or device type varies, then there will be one formatting pass for each group of notifications that share the same subscriber locale and device type. This means that the recipient groups for each multicast notification are smaller, and more multicast notifications are generated.

Note Multicast delivery in Notification Services can be used even if the delivery protocol does not support true multicast delivery in the networking sense. Selecting multicast delivery in Notification Services allows the system to aggregate identical notifications, so that formatting is done just once, which improves performance. One set of formatted data and a list of subscribers are handed off to the delivery protocol. The delivery protocol then delivers these notifications using multicast delivery if it has the capability, or one at a time if it does not.

Limiting Multicast Recipients

For reliability or performance reasons, you might want to consider limiting the number of subscribers that receive a single multicast notification. You can set the limit in the <MulticastRecipientLimit> element, in the /NotificationClasses/NotificationClass/Protocols/Protocol/ProtocolExecutionSettings section of the ADF. Fewer recipients for each multicast notification means that more notifications must be generated. This can affect the speed and resource consumption of your application.

See Also

Multicast Delivery


Content Formatting

Content formatting is handled by the content formatter component of the distributor, after the notification data has been aggregated. This component is implemented as a class in a managed code assembly.

Each notification class uses one content formatter to handle the formatting of its data. The selected content formatter is specified in the /NotificationClasses/NotificationClass/ContentFormatter section of the application definition file (ADF).

A content formatter takes notification data as input, packaged into an array. For standard delivery, there is only one element in the array, which contains the information for a single notification record. For digest delivery, there are multiple elements in the array, each of which contains the data from one of the component notifications.

The content formatter then formats the notification fields for display, using the recipient information included in the notification data to determine the appropriate formatting. If digest delivery is enabled, the content formatter is also responsible for appropriately combining the component notification information. When the content formatter is finished with its task, it creates a string containing the formatted data. The distributor passes this string, along with some notification header information that it generates, to the delivery protocol.

Internally, a content formatter can use any technique to format the notification fields. It can be as simple as using basic string manipulation, or it can be more complex, using XSL transforms or Microsoft ASP.NET rendering.

Notification Services provides an XSLT content formatter to assist you in quickly developing an application. It can be used in your application after you specify some basic information about it in your ADF. For more information about the standard content formatter, see XSLT Content Formatter.

You can also develop a custom content formatter. The Notification Services API provides an interface to assist you with this. For more information about creating a custom content formatter, see Developing a Custom Content Formatter.


Distributing Notifications

In Notification Services, formatted notifications are distributed through delivery channels and handed off to external delivery services. A delivery channel represents a delivery pipe to a particular endpoint. A delivery channel has two elements: a delivery protocol, and the configuration/addressing information required to identify the endpoint.

  • The delivery protocol creates the notification message and routes it to an external delivery system, based on the string of formatted data it receives from the content formatter as well as distributor-generated headers that contain recipient data and protocol-specific information. It is implemented as a class in a managed code assembly. A delivery protocol implements a well-known protocol, such as Simple Mail Transfer Protocol (SMTP), making it accessible to the Notification Services instance. Custom delivery protocols are specified in the <Protocols> section of the configuration file. (Notification Services is already aware of the standard delivery protocols it provides, so developers are not required to document them.)
  • The configuration/addressing information permits the Notification Services instance to interact with the delivery channel. It includes all non-application-specific information needed to deliver notifications. It can include such information as the name of the delivery protocol assembly, the server name for the delivery service gateway, and authentication information — depending on what external delivery service is being used. Instance configuration information is specified in the <DeliveryChannels> section of the configuration file.

Additionally, notification-specific information is needed by the delivery protocol in order to create and route notification messages. This information can include such information as the device address, the notification subject line, and the notification message priority, depending on the protocol being used. Notification-specific protocol information is specified in the /NotificationClasses/NotificationClass/Protocols/Protocol section of the application definition file (ADF).

Several delivery channels might use the same delivery protocol to communicate with different external delivery systems.

For instance, you might send mail by several different mail gateways, all using the SMTP delivery protocol. Each gateway would have a different delivery channel entry in the configuration file, because each would require different information about accessing a mail server. These are considered different delivery channel instances, yet because they all use the same protocol, they are of the same delivery channel type.

The distributor determines which delivery channel should handle a particular notification by looking at the subscriber device specified as the target for this notification. It then determines which delivery channel is associated with this device by reading this information from the subscriber device record.

Notification Services provides several standard delivery protocols to assist you in defining delivery channels for your applications. For more information, see Standard Delivery Protocols.

You can also develop a custom delivery protocol. Notification Services provides the IDeliveryProtocol interface to assist you with this. For more information, see Developing a Custom Delivery Protocol.

The distributor function of the Notification Services engine handles notification formatting and distribution. For more information about the details of distributor functioning and how this affects system performance, see Specifying Distributor Settings.


Specifying Protocol Information

You specify delivery protocol information in the Notification Services system by following these steps:

  1. If you have any custom delivery protocols, declare them in the <Protocols> node of the configuration file. (Notification Services is aware of all standard delivery protocols it provides, so they do not need to be declared here.)
  2. Define each delivery channel (including its delivery protocol) in the <DeliveryChannels> node of the configuration file.
  3. For each notification class, declare all delivery protocols that the notification class supports in the /NotificationClasses/NotificationClass/Protocols section of your application definition file (ADF). Multiple delivery protocols can be specified for each notification class. Header fields that are required for notification delivery are defined in the <Fields> node of this section. These header fields are provided to the delivery protocol that creates and routes the notification message.
  4. Design your subscription management application to specify the delivery channel that each subscriber device record uses. This can be hard-coded or you can allow the user to select a value. The delivery channel specified must be one of the delivery channels defined in the <DeliveryChannels> node of your configuration file. The delivery channel determines which delivery protocol creates the notification messages that are used to fulfill this subscription.
  5. Pass the subscriber ID, subscriber device name, and subscriber locale fields to the notification function in the notification generation rule. This information is saved with the other raw notification data. The subscriber device name and subscriber locale are usually contained in the subscription information, but alternatively can be retrieved from other locations. This information identifies the subscriber device record from which to retrieve the delivery channel information. This in turn determines the delivery protocol used to create and route the notification message, and the external delivery system used for message delivery.


Example: Stock Update Application

The following example shows a stock update application that allows subscribers to receive notifications in several ways. Subscriber X wants his notifications to be delivered as e-mail to his cellular phone. To have the notification successfully delivered, the system administrator, the application developer, and subscriber X take the following steps:

  1. In the configuration file, the system administrator defines the Mail1 delivery channel, which uses the Simple Mail Transfer Protocol (SMTP) delivery protocol and enables e-mail notifications using the MS01 mail server:
    <DeliveryChannels>
   <DeliveryChannel>
      <DeliveryChannelName>Mail1</DeliveryChannelName>
      <ProtocolName>SMTP<ProtocolName>
      <Arguments>
         <Argument>
            <Name>SmtpServer</Name>
            <Value>MS01</Value>
         </Argument>
         <Argument>
            <Name>BodyEncoding</Name>
            <Value>utf-16</Value>
         </Argument>
      </Arguments>
   </DeliveryChannel>
</DeliveryChannels>
  2. In the application definition file (ADF), the application developer creates the StockNotifications notification class, which provides stock notification delivery via SMTP:
    <NotificationClasses>
   <NotificationClasses>
      <NotificationClassName>StockNotifications</NotificationClassName>
      ...
      <Protocols>
         <Protocol>
            <ProtocolName>SMTP</ProtocolName>
            <Fields>
               <Field>
                  <FieldName>Subject</FieldName>
                  <SqlExpression>
                  &apos;The price of &apos; + StockSymbol
                  + &apos; is now &apos; + StockPrice
                  </SqlExpression>
               </Field>
               <Field>
                  <FieldName>From</FieldName>
                  <SqlExpression>
                  &apos;stockquotes@microsoft.com&apos;
                  </SqlExpression>
               </Field>
               <Field>
                  <FieldName>To</FieldName>
                  <SqlExpression>DeviceAddress</SqlExpression>
               </Field>
               <Field>
                  <FieldName>Priority</FieldName>
                  <SqlExpression>&apos;Normal&apos;</SqlExpression>
               </Field>
               <Field>
                  <FieldName>BodyFormat</FieldName>
                  <SqlExpression>&apos;html&apos;</SqlExpression>
               </Field>
            </Fields>
            <ProtocolExecutionSettings>
            ...
            </ProtocolExecutionSettings>
         </Protocol>
      </Protocols>
   </NotificationClass>
</NotificationClasses>
  3. In the ADF, the application developer creates the StockSubscriptions subscription class, which consumes stock events to produce notifications of the StockNotifications notification class:
    <SubscriptionClasses>
   <SubscriptionClass>
      <SubscriptionClassName>StockSubscriptions</SubscriptionClassName>
      ...
      <EventRule>
         <RuleName>CreateEmailNotifications</RuleName>
         <Action>
         SELECT dbo.StockNotificationsNotify(
         S.SubscriberId, S.SubscriberDeviceName,
         S.SubscriberLocale, E.StockSymbol, E.StockPrice)
         FROM StockSubscriptions S JOIN StockEvents E
         ON S.StockSymbol = E.StockSymbol
         WHERE S.StockTriggerValue &lt;= E.StockPrice
         </Action>
         <ActionTimeout>P0DT00H01M00S</ActionTimeout>
         <EventClassName>StockEvents</EventClassName>
      </EventRule>
      ...
   </SubscriptionClass>
</SubscriptionClasses>
  4. Subscriber X enters the subscriber device information for his cellular phone in a subscription management application. He selects a delivery channel as part of creating the subscriber device record. In this case, subscriber X selects the Mail1 delivery channel.

    (The subscription management application developer must ensure that subscribers are restricted to valid delivery channels for the device type they enter.)

  5. Subscriber X now enters a subscription to the stock update service, specifying the subscriber device record that represents his cellular phone as the target device. In this case, subscriber X creates a subscription of the StockSubscriptions class.

When a stock event comes in, the following actions occur:

  1. StockSubscriptions subscriptions are matched to the incoming event, and StockNotifications notifications are generated.
  2. The notification data for subscriber X is passed to the content formatter, formatted, and output as a string.
  3. The distributor generates a notification header for subscriber X's notification. This notification header includes delivery information like device address and delivery channel, and the values of the protocol fields defined in the StockNotifications notification class.
  4. The distributor passes the notification header and the string containing the formatted notification data to the Simple Mail Transfer Protocol (SMTP) delivery protocol, which is selected based on the delivery channel information retrieved from subscriber X's subscriber device record.
  5. The SMTP delivery protocol constructs an SMTP message based on this information. The body contains the formatted notification data, and the header uses the notification header information.
  6. The message is handed off to the SMTP transport for delivery to the external MS01 mail server, which ultimately delivers the message to the subscriber's device.

    Note The SMTP delivery protocol is provided as a standard part of Notification Services. It makes the SMTP mail delivery protocol available to Notification Services instances. No configuration file entry is needed, because SMTP is a Notification Services standard delivery protocol.


Digest Delivery

One option for notification delivery is digest delivery: grouping several individual notifications for one subscriber into one larger notification, called a digest notification. For example, a subscriber can subscribe to traffic update notifications for several potential routes to her office. Rather than being sent separately, these notifications are grouped into a single digest delivery.

Digest delivery is disabled by default. If both digest delivery and multicast delivery are specified, the NSControl command fails. Digest notifications are delivered in exactly the same manner as standard notifications.

The collection and aggregation of the notification data is performed when the distributor processes the work item that contains the notifications. For more information, see Formatting Digest Notifications.


Multicast Delivery

Multiple subscribers often receive identical notification data, such as the weather forecast for Tokyo. In these cases, it is possible to format that notification data once, and then send it to each subscriber. Formatting the data once and then sending it to multiple subscribers is referred to as multicast delivery. Multicast delivery is available only in Notification Services Enterprise Edition.

Multicast delivery is disabled by default. If both digest delivery and multicast delivery are specified, the NSControl command fails.

The notification data is cached and the subscriber list is created when the distributor processes the work item that contains the notifications. Once the formatted notification data and subscriber list are handed off to the delivery protocol, the delivery protocol determines whether it is appropriate to send a single message to all the subscribers, or to send one message to each, based on the protocol being implemented.

For more information about the formatting process for multicast notifications, see Formatting Multicast Notifications.


Handling Delivery Failures

The distributor provides several mechanisms for handling notification delivery failures. As the developer, you must specify the parameters that determine how your application uses these mechanisms.

All the delivery failure parameters except for expiration age are specified for each delivery protocol for each notification class. For a given notification class, all notifications that are delivered using the specified delivery protocol have the same delivery failure handling, even if they are delivered using different delivery channels.

The expiration age is specified for the whole notification class. All notifications for the given notification class have the same expiration age, regardless of the delivery protocols or delivery channels they use.

Note The Notification Services stored procedures NSDiagnosticDeliveryChannel and NSDiagnosticFailedNotifications can be helpful in troubleshooting delivery failures. For more information about these stored procedures, see NSDiagnosticDeliveryChannel and NSDiagnosticFailedNotifications.

Important Notification Services receives limited error feedback from the external delivery systems. Most failures result in a generic "delivery failure" error in the event log. If you receive consistent delivery failures, it might indicate a configuration issue. Check the delivery channel settings in the configuration file, and the protocol field values for the notification classes in the application definition file (ADF) in such a circumstance.


Retry Logic

The distributor can re-attempt the delivery of notifications when a prior delivery attempt has failed. It does this on a per-protocol basis, using the /NotificationClasses/NotificationClass/Protocols/Protocol/ProtocolExecutionSettings/RetrySchedule value to determine how many retries are attempted and when they occur. If you do not want any retries, you can exclude the <RetrySchedule> node from the application definition file (ADF).

The retry logic is applied at the distributor work item level. If any notifications in a work item cannot be delivered, then the distributor work item itself is considered to have failed. The distributor can re-attempt delivery of the distributor work item at a later time, according to the information specified in the <RetrySchedule> node. When this happens, only the notifications that could not be delivered during the previous delivery attempt are included in the retry. Notifications that were successfully delivered during a previous delivery attempt are ignored during a retry. There is one exception: if a delivery failure occurs and the delivery status of a notification cannot be determined, retries are attempted that might result in the subscriber receiving duplicate notifications.

The <RetrySchedule> node contains a list of <RetryDelay> elements, each of which specifies a time duration value. After the initial failure of a distributor work item, the distributor waits the amount of time specified in the first <RetryDelay> element before re-attempting delivery of the work item. If this attempt also fails, the distributor waits the amount of time specified in the next <RetryDelay> element, and then makes another attempt. This process continues until the intervals specified by all <RetryDelay> elements have been exhausted, or until the undelivered notifications expire, whichever comes first.

Retry delays are relative to each other, not relative to the original failure time. The distributor waits the full time specified in the next <RetryDelay> element before attempting delivery again.

For example, suppose you have three retry delays specified: the first for 15 minutes, the second for 30 minutes, and the third for one hour. Assuming the initial delivery failure occurred at 13:00 GMT, the first retry occurs at 13:15 GMT, the second at 13:45 GMT, and the third at 14:45 GMT.

The <RetryDelay> values do not affect the firing schedule of the distributor. These values represent minimum delays; the actual delay between attempts might be longer. Each time the distributor fires, it determines which <RetryDelay> intervals have passed, and then re-attempts the distributor work items to which they apply.

If your server experiences prolonged downtime, more than one retry delay interval might pass without the distributor attempting a retry. If this occurs, the distributor immediately performs one retry attempt on those distributor work items that have not expired when the server comes back online. It then resumes the retry delay schedule, and waits the amount of time specified in the second missed delay interval before trying again.

For example, suppose you have four retry delays specified: the first for 15 minutes, the second for 30 minutes, the third for 45 minutes, and the fourth for one hour. The initial delivery failure occurs at 13:00 GMT, and the first retry occurs at 13:15 GMT. The server then goes down until 16:00 GMT. When the server comes back online, a retry occurs immediately, replacing the first retry delay that was missed (in this case the delay interval of 30 minutes). If this retry fails, then the next retry occurs at 16:45 GMT per the third specified retry delay interval.

Expiration Age

You can specify an expiration age for notifications with time-sensitive data. If the notifications are not delivered within the time period specified, then the distributor ceases trying to deliver them, even if there are retry delay intervals remaining. For instance, suppose you set an expiration age of two hours. If your 14:00 GMT notification batch cannot send successfully by 16:00 GMT, then those notifications expire and no further delivery attempts are made.

You specify an expiration age for notifications by using the <ExpirationAge> element in the notification class definition. If you choose not to use this element, you must exclude it from the <NotificationClass> node. In that case, notifications never expire. The distributor continues to attempt delivery of them until the retry schedule is exhausted.


Managing Event Log Entries

The distributor writes entries to the event log to document notification delivery failures. It uses the <FailuresBeforeLoggingEvent> and the <FailureEventLogInterval> elements defined in the notification class to determine when to do this.

The <FailuresBeforeLoggingEvent> element specifies the number of failures that must occur before the distributor writes an entry to the event log. The <FailureEventLogInterval> element specifies the minimum amount of time that must pass between writes to the event log, regardless of how many failures occur. This allows you to control the number of writes to the event log, so multiple errors do not cause hundreds of duplicate event log entries.

For example, suppose the <FailuresBeforeLoggingEvent> value is set to 5 and the <FailureEventLogInterval> value is set to ten minutes. The first time five failures occur, an event log entry is written. After that, regardless of how many failures occur, no further entries are written to the event log until after ten minutes has passed. After ten minutes, the <FailuresBeforeLoggingEvent> count begins again. If five failures occur, another event log entry is written.

These two parameters together allow you to configure the error logging to fit the needs of your application, based on known information about the reliability of the network and on the quality of service you want.

Note Developers might want to leave the values of the <FailuresBeforeLoggingEvent> and <FailureEventLogInterval> elements at their default settings while developing an application. These settings cause all errors to be logged, which simplifies testing.


Handling Prolonged Failure

In cases where delivery failure occurs because of a prolonged network outage, rather than transient network conditions, the distributor aborts delivery attempts in order to avoid flooding the network. The behavior of the distributor in this situation is controlled by the <FailuresBeforeAbort> element.

The <FailuresBeforeAbort> element specifies the number of consecutive delivery failures that must occur before the distributor aborts the delivery of a work item. If this specified number of consecutive failures occurs, the distributor writes an error message to the event log and then halts processing.

There are also several settings available to control distributor logging levels for the application as a whole. These settings can be configured to provide the optimal amount of log information for troubleshooting your application. For more information about these settings, see Defining the <DistributorLogging> Node.


Defining a Notification Class

You define the notifications your Notification Services application will provide by creating notification classes in your application definition file (ADF). You can define one or more notification classes for each Notification Services application you develop.

Follow these steps to define a notification class:

  1. Name your notification class. See Naming the Notification Class for more information.
  2. Define the fields in your notification class. These fields provide the data that can be sent to your subscribers. They are also used to create the SQL Server notification table, which stores the notification data, and the notification function, which is used in subscription rules to create notifications. For more information, see Defining the Notification Fields.
  3. Optionally, designate the SQL Server filegroup for the notification table. If you do not specify a filegroup, the notification table is automatically created on the same filegroup as the application database. For more information, see Designating the Filegroup.
  4. Declare the content formatter that this notification class is to use. The content formatter takes the raw notification data and formats it appropriately for display. For more information, see Documenting the Content Formatter.
  5. Indicate whether this notification class uses digest delivery. Digest delivery means that all notifications for the same subscriber that are generated by one execution of the notification generation rule are grouped and handled as a single notification. For more information, see Setting the Digest Delivery Option.
  6. If you are using Notification Services Enterprise Edition, indicate whether this notification class uses multicast delivery. Multicast delivery means that all notifications that share identical data and are in the same distributor work item are formatted just once, and then this formatted data is sent out to all subscribers. For more information, see Setting the Multicast Delivery Option.
  7. If you are using Notification Services Enterprise Edition, specify a notification batch size for notifications of this class. For more information, see Specifying a Notification Batch Size.
  8. Specify one or more delivery protocols that this notification class is to use for notification delivery. This consists of specifying header or other notification-specific information required for messages created by this delivery protocol. For more information, see Documenting the Delivery Protocols.
  9. Specify an expiration age for notifications of this class. For more information, see Specifying the Notification Expiration Age.

All of this information is stored in the /NotificationClasses/NotificationClass section of the ADF. You create one <NotificationClass> node for each notification class that you define.

Example: Defining a Notification Class

The following code example shows the definition for the StockNotifications notification class:

<NotificationClasses>
   <NotificationClass>
      <NotificationClassName>StockNotifications</NotificationClassName>
      <Schema>
         <Fields>
            <Field>
               <FieldName>StockSymbol</FieldName>
               <FieldType>char(10)</FieldType>
            </Field>
            <Field>
               <FieldName>StockPrice</FieldName>
               <FieldType>money</FieldType>
            </Field>
         </Fields>
      </Schema>
      <FileGroup>Secondary</FileGroup>
      <ContentFormatter>
         <ClassName>Stock.StockFormatter</ClassName>
         <AssemblyName>C:\CustomCFs\StockFormatter.dll</AssemblyName>
         <Arguments>
            <Argument>
               <Name>OutputHTML</Name>
               <Value>true</Value>
            </Argument>
         </Arguments>
      </ContentFormatter>
      <DigestDelivery>true</DigestDelivery>
      <NotificationBatchSize>100</NotificationBatchSize>
      <Protocols>
         <Protocol>
            <ProtocolName>SMTP</ProtocolName>
            <Fields>
               <Field>
                  <FieldName>Subject</FieldName>
                  <SqlExpression>%SubjectLine%</SqlExpression>
               </Field>
               <Field>
                  <FieldName>From</FieldName>
                  <SqlExpression>%fromAddress%</SqlExpression>
               </Field>
               <Field>
                  <FieldName>To</FieldName>
                  <FieldReference>DeviceAddress</FieldReference>
               </Field>
               <Field>
                  <FieldName>Priority</FieldName>
                  <SqlExpression>%mailPriority%</SqlExpression>
               </Field>
               <Field>
                  <FieldName>BodyFormat</FieldName>
                  <SqlExpression>&quot;html&quot;</SqlExpression>
               </Field>
            </Fields>
            <ProtocolExecutionSettings>
               <RetrySchedule>
                  <RetryDelay>P0DT00H15M00S</RetryDelay>
                  <RetryDelay>P0DT00H30M00S</RetryDelay>
                  <RetryDelay>P0DT01H00M00S</RetryDelay>
               </RetrySchedule>
               <FailuresBeforeAbort>20</FailuresBeforeAbort>
               <MulticastRecipientLimit>10</MulticastRecipientLimit>
               <WorkItemTimeout>P0DT00H30M00S</WorkItemTimeout>
            </ProtocolExecutionSettings>
         </Protocol>
      </Protocols>
      <ExpirationAge>P0DT02H30M00S</ExpirationAge>
   </NotificationClass>
</NotificationClasses>


Naming the Notification Class

Document the notification class name in the <NotificationClassName> element of the application definition file (ADF). For more information, see <NotificationClassName> Element.

Example

The following example creates a notification class with the name StockNotifications:

<NotificationClassName>StockNotifications</NotificationClassName>


Defining the Notification Fields

Define the fields that make up the notification in the <Schema> section of the <NotificationClass> node of the application definition file (ADF).

The <Schema> node has two child nodes:

  • <Fields> (required)
  • <ComputedFields> (optional)

Fields that store data within a database table are defined in the <Fields> node. Fields whose data should be computed at notification distribution time are defined in the <ComputedFields> node.

Note You must exclude the <ComputedFields> node from the <Schema> node if you do not use it.

The <Fields> and <ComputedFields> nodes in turn have <Field> and <ComputedField> nodes, each of which defines a single field for this notification class.

<Field> Node

The <Field> node has three child elements:

  • <FieldName> (required)
  • <FieldType> (required)
  • <DigestGrouping> (optional)

For more information, see <Field> Node (/Schema/Fields).

<FieldName> Element

Document the field name in the required <FieldName> element.

For more information, see <FieldName> Element (/NotificationClass/Schema/Fields/Field).

<FieldType> Element

Document the field data type in the required <FieldType> element. The field data types must conform to SQL Server data types.

Important You cannot specify a notification data field as a SQL Server Identity column. Notification Services already uses the Identity property to specify a system-generated NotificationId field.

For more information, see <FieldType> Element (/NotificationClass/Schema/Fields/Field).

<DigestGrouping> Element

Document the field to be used for matching when grouping notifications. Notifications with the same SubscriberId, SubscriberLocale, and DeviceName values that also have matching values in any <DigestGrouping> fields are grouped into one notification.

Note You must exclude the <DigestGrouping> element from the <Field> node if you do not use it.

For more information, see <DigestGrouping> Element (<Field>).

<ComputedField> Node

The <ComputedField> node has three child elements:

  • <FieldName> (required)
  • <SqlExpression> (required)
  • <DigestGrouping> (optional)

For more information, see <ComputedField> Node.

<FieldName> Element

Document the field name in the required <FieldName> element.

For more information, see <FieldName> Element (/NotificationClass/Schema/ComputedFields/ComputedField).

<SqlExpression> Element

This element contains the Transact-SQL expression that computes the data for this field. Any Transact-SQL expression that can be evaluated as part of a SELECT query in the application database can be referenced in an <SqlExpression> element. This includes use of arbitrary constants, making SQL function calls, and referring to data in chronicle tables. If you use a string constant as a <SqlExpression> value, it must be enclosed in apostrophes (expressed as the entity reference &apos; in the ADF).

Note There are several reserved characters in the Notification Services XML vocabulary (>, <, ', ", &, %). If you need to use these characters in your expressions, you must use entity references to replace them. For more information about using reserved characters in the ADF, see Reserved Characters.

For more information, see <SqlExpression> Element (<ComputedField>).

<DigestGrouping> Element

Document the field to be used for matching when grouping notifications. Notifications with the same SubscriberID and DeviceName values that also have matching values in any <DigestGrouping> fields are grouped into one notification.

Note You must exclude the <DigestGrouping> element from the <ComputedField> node if you do not use it.

For more information, see <DigestGrouping> Element (<ComputedField>).

Example

In the following code example, two notification fields are defined: a 10-character stock symbol field, and a stock value field that accepts monetary data. Additionally, a computed field is defined that determines how much the stock price has changed:

<Schema>
   <Fields>
      <Field>
         <FieldName>StockSymbol</FieldName>
         <FieldType>char(10)</FieldType>
         <DigestGrouping>true<DigestGrouping>
      </Field>
      <Field>
         <FieldName>StockPrice</FieldName>
         <FieldType>money</FieldType>
      </Field>
   </Fields>
   <ComputedFields>
      <ComputedField>
         <FieldName>StockPriceChange</FieldName>
         <!--The event table name is the combination
         of the event class name ("Stock") and the word "Events".-->
         <!--The event chronicle name is the name you gave the
         chronicle table when you created it in the event class
         definition in the ADF.-->
         <SqlExpression>
         (StockEvents.StockPrice – StockEventChron.StockLastValue)
         </SqlExpression>
      </ComputedField>
   </ComputedFields>
</Schema>


Designating the Filegroup

SQL Server provides filegroups to simplify database administration and allow optimal allocation of system data across multiple physical disks. Optimized data allocation can be critical to the performance of high-volume Notification Services applications.

For more information about SQL Server filegroups, see "Files and Filegroups" in SQL Server Books Online.

Specify the name of the filegroup on which you want the notification table created in the <FileGroup> element of the <NotificationClass> node. The filegroup named must be one of the filegroups defined as a <NamedFileGroup> in the <Database> node.

Note You must exclude the <FileGroup> element from the <NotificationClass> node if you do not use it. Your notification table is created on the default filegroup for the application database in this case.

For more information, see <FileGroup> Element (<NotificationClass>).

Example

In the following example, the Primary filegroup is selected as the default filegroup for the notification table:

<Database>
   <NamedFileGroup>
      <FileGroupName>Primary</FileGroupName>
      ...
   </NamedFileGroup>
   <NamedFileGroup>
      <FileGroupName>Secondary</FileGroupName>
      ...
   </NamedFileGroup>
   ...
</Database>
...
<NotificationClasses>
   <NotificationClass>
      ...
      <FileGroup>Primary</FileGroup>
      ...
   </NotificationClass>
</NotificationClasses>


Documenting the Content Formatter

The <ContentFormatter> node contains information about the class that provides content formatting functionality to this notification class. This class is part of a managed code assembly, and contains all the functions necessary to format your raw notification data appropriately for the locales, languages, and devices you support for subscriptions to this application.

The <ContentFormatter> node has three child elements:

  • <ClassName> (required)
  • <AssemblyName> (required for custom content formatters)
  • <Arguments> (optional)

For more information about the <ContentFormatter> node, see <ContentFormatter> Node.

<ClassName> Element

You must document the class name of the class that implements the content formatter. For custom content formatters, the class name must be fully qualified, including any namespace prefix.

For more information about namespace naming conventions, see Namespace Naming Guidelines in the Microsoft MSDN® Library.

For the standard XSLT content formatter that is installed with Notification Services, the class name should be provided without the namespace, simply as XsltFormatter. For more information about implementing the XSLT content formatter, see XSLT Content Formatter.

Enter the class name in the <ClassName> element.

For more information about the <ClassName> element, see <ClassName> Element (<ContentFormatter>).

<AssemblyName> Element

You must specify the location of the assembly that contains the content formatter class in the <AssemblyName> element. This must be done for any custom content formatters that you create. The standard Notification Services XSLT content formatter does not require this information.

You must provide the full path and the assembly file name as the value for the <AssemblyName> element.

Note If you are declaring the standard Notification Services XSLT content formatter, you must exclude the <AssemblyName> element from the <ContentFormatter> node.

For more information, see <AssemblyName> Element (<ContentFormatter>).

<Arguments> Node

Document arguments in the <Arguments> section of the <ContentFormatter> node. These are the arguments that must be passed to the content formatter when it is initialized. Create one <Argument> node for each argument in the <Arguments> section.

Note You must exclude the <Arguments> node from the <ContentFormatter> node if you do not use it.

Each <Argument> node has two required child elements:

  • <Name>
  • <Value>

For more information, see <Argument> Node (/ContentFormatter/Arguments).

You specify the argument name in the <Name> element. You specify the argument value in the <Value> element.

For more information about the <Name> element, see <Name> Element (/ContentFormatter/Arguments/Argument). For more information about the <Value> element, see <Value> Element (/ContentFormatter/Arguments/Argument).

Example

In the following code example, the Stock.StockFormatter class provides the content formatting functionality, and is implemented in the StockFormat.dll file. It takes a single argument that tells it to display the content in an HTML format:

<ContentFormatter>
   <ClassName>Stock.StockFormatter</ClassName>
   <AssemblyName>C:\CustomCFs\StockFormat.dll<AssemblyName>
   <Arguments>
      <Argument>
         <Name>OutputHTML</Name>
         <Value>true</Value>
      </Argument>
   </Arguments>
</ContentFormatter>


Setting the Digest Delivery Option

The <DigestDelivery> element indicates whether notifications of this class are digested. Specify true as the value to enable digest delivery. Specifying false, or excluding this element from the <NotificationClass> node, disables digest delivery.

Note You must exclude the <MulticastDelivery> element from the <NotificationClass> node if you have Notification Services Standard Edition, or if you have Notification Services Enterprise Edition and you do not use this element.

For more information about the <DigestDelivery> element, see <DigestDelivery> Element. For more information about the implications of using this option, see Formatting Digest Notifications.

Example

This example enables digest delivery for a notification class on an Enterprise Edition system:

<DigestDelivery>true</DigestDelivery>


Setting the Multicast Delivery Option

The <MulticastDelivery> element indicates whether notifications of this class are multicasted. Specify true as the value to enable multicast delivery. Specifying false, or excluding this element from the <NotificationClass> node, disables multicast delivery.

Note You must exclude the <NotificationBatchSize> element from the <NotificationClass> node if you have Notification Services Standard Edition, or if you have Notification Services Enterprise Edition and you do not use this element. If it is excluded in an Enterprise Edition system, there is no limit to the number of notifications that can be included in a single batch.

For more information about the <MulticastDelivery> element, see <MulticastDelivery> Element. For more information about the implications of using this option, see Formatting Multicast Notifications.

Example

This example enables multicast delivery for a notification class on an Enterprise Edition system:

<MulticastDelivery>true</MulticastDelivery>


Specifying a Notification Batch Size

The <NotificationBatchSize> element documents the maximum number of notifications that can be included in a batch for a given notification class.

The generator usually produces one batch per rule firing, unless a notification batch size value is specified. If you do specify this value, the generator breaks up the batch into smaller batches to ensure that the batch size requirements are met.

Note You must exclude the <NotificationBatchSize> element from the <NotificationClass> node if you do not use it. In this case, there is no limit to the number of notifications that can be included in a single batch.

For more information, see <NotificationBatchSize> Element.

Example

This example sets the notification batch size for a notification class to 100:

<NotificationBatchSize>100</NotificationBatchSize>


Documenting the Delivery Protocols

The <Protocols> node documents the delivery protocols that are supported by a given notification class. Each delivery protocol has a <Protocol> child node in the <Protocols> node.

Each <Protocol> node has three child elements:

  • <ProtocolName> (required)
  • <Fields> (required)
  • <ProtocolExecutionSettings> (optional)

For more information, see <Protocol> Node.

Note You must exclude the <ProtocolExecutionSettings> node from the <Protocol> node if you do not use it.

Important You must document every delivery protocol that a notification class uses, even if the delivery protocol requires no header field information (for example, the File delivery protocol). Notification Services uses this protocol information to determine what protocols are valid for delivering notifications of this class.

<ProtocolName> Element

Determine the name of the delivery protocol: either a well-known protocol like Simple Mail Transfer Protocol (SMTP), or the name of a custom delivery protocol that you have documented in the <Protocols> node of the configuration file. Document this name in the <ProtocolName> element. The configuration file entry provides the mapping between an application developer-assigned delivery protocol name and the class name of its implementation.

For more information, see <ProtocolName> Element.

<Fields> Node

The <Fields> node documents all the header fields that are required for a message that is to be created and routed by this delivery protocol. For each of the header fields, create a <Field> child node in the <Fields> node. These fields are provided to the DeliverNotification method of the class that implements the delivery protocol as a set of name/value pairs. The values are computed at notification delivery time.

A <Field> node consists of two required child elements:

  • <FieldName>
  • either <FieldReference> or <SqlExpression>

For more information, see <Field> Node (/Protocol/Fields).

<FieldName> Element

Document the name of the header field in the required <FieldName> element.

For more information, see <FieldName> Element (/Protocol/Fields/Field).

<FieldReference> or <SqlExpression> Element

If the header field value already exists in one of the notification fields or computed fields, use the <FieldReference> element. The <FieldReference> element specifies the name of the notification field whose value should be used in this header field. Both regular and computed notification fields can be used to provide this value.

For more information, see <FieldReference> Element.

If the header field value does not yet exist in a notification field, use the <SqlExpression> element. The <SqlExpression> element contains the Transact-SQL expression that computes the data for this field. Any Transact-SQL expression that can be evaluated as part of a SELECT query in the application database can be referenced in a <SqlExpression> element. This includes expressions such as arbitrary constants and making SQL function calls. If you use a string constant as a <SqlExpression> value, it must be enclosed in apostrophes, which in turn must be expressed as the entity reference &apos; in the application definition file (ADF).

An <SqlExpression> element can also take an application parameter as a value. Application parameters are defined in the <ParameterDefaults> node of the ADF. For more information about using application parameters, see Defining Application Parameters and <SqlExpression> Element (/Protocol/Fields/Field).

Note There are several reserved characters in the Notification Services XML vocabulary (>, <, ', ", &, %). If you need to use these characters in your Transact-SQL expressions, you must use entity references to replace them. For more information about using reserved characters in the ADF, see Reserved Characters.

<ProtocolExecutionSettings> Node

The <ProtocolExecutionSettings> node has six optional child elements:

  • <RetrySchedule>
  • <FailuresBeforeLoggingEvent>
  • <FailureEventLogInterval>
  • <FailuresBeforeAbort>
  • <MulticastRecipientLimit>
  • <WorkItemTimeout>

    Note Any child element that is not used must be excluded from the <ProtocolExecutionSettings> node.

For more information, see <ProtocolExecutionSettings> Node.

<RetrySchedule> Node

The <RetrySchedule> node consists of one or more <RetryDelay> elements. Each <RetryDelay> element defines a period of time after a failed notification delivery attempt that a retry should be attempted. If the retry attempted at the time specified by the first <RetryDelay> element fails, then another retry attempt is made at the time specified by the second <RetryDelay> element, and so forth.

For more information, see <RetrySchedule> Node.

<FailuresBeforeLoggingEvent> Element

The <FailuresBeforeLoggingEvent> element defines the number of failures that are to occur before a system event log entry is created to document the failure.

For more information, see <FailuresBeforeLoggingEvent> Element.

<FailureEventLogInterval> Element

The <FailureEventLogInterval> element specifies the minimum amount of time that must pass before consecutive failure events are logged.

For more information, see <FailureEventLogInterval> Element.

<FailuresBeforeAbort> Element

The <FailuresBeforeAbort> element defines the number of retry attempts that are permissible before aborting any further attempts.

For more information, see <FailuresBeforeAbort> Element.

<MulticastRecipientLimit> Element

The <MulticastRecipientLimit> element limits the number of recipients allowed for each multicast notification. This element is available only in Notification Services Enterprise Edition.

Note You must exclude the <MulticastRecipientLimit> element from the <ProtocolExecutionSettings> node if you have Notification Services Standard Edition.

For more information, see <MulticastRecipientLimit> Element.

<WorkItemTimeout> Element

The <WorkItemTimeout> element specifies the amount of time a distributor thread can take in order to complete a work item assigned to it. If the <WorkItemTimeout> value is exceeded, the work item is canceled for that thread. The work item is then returned to the pool of available work items, so that it can be picked up by another thread and processed. This prevents a work item from being lost, which can occur when a work item is assigned to a thread for processing, but is not actually completed because of some error.

For more information, see <WorkItemTimeout> Element.

Example

The following code example specifies Simple Mail Transfer Protocol (SMTP) as a valid delivery protocol for creating and routing notifications of this class, and provides values for the fields required to create an SMTP message. Notifications sent using this protocol have three redelivery attempts if initially unsuccessful: the first at 15 minutes after the initial attempt, the second 30 minutes after that, and the final attempt one hour later. If you are using multicast delivery, it limits each multicast notification to 10 recipients. Work items time out after 10 minutes. This example assumes an Enterprise Edition system:

<Protocols>
   <Protocol>
      <ProtocolName>SMTP</ProtocolName>
      <Fields>
         <Field>
            <FieldName>Subject</FieldName>
            <SqlExpression>%SubjectLine%</SqlExpression>
         </Field>
         <Field>
            <FieldName>From</FieldName>
            <SqlExpression>%fromAddress%</SqlExpression>
         </Field>
         <Field>
            <FieldName>To</FieldName>
            <FieldReference>DeviceAddress</FieldReference>
         </Field>
         <Field>
            <FieldName>Priority</FieldName>
            <SqlExpression>%mailPriority%</SqlExpression>
         </Field>
         <Field>
            <FieldName>BodyFormat</FieldName>
            <SqlExpression>&quot;html&quot;</SqlExpression>
         </Field>
      </Fields>
      <ProtocolExecutionSettings>
         <RetrySchedule>
            <RetryDelay>P0DT00H15M00S</RetryDelay>
            <RetryDelay>P0DT00H30M00S</RetryDelay>
            <RetryDelay>P0DT01H00M00S</RetryDelay>
         </RetrySchedule>
         <FailuresBeforeAbort>20</FailuresBeforeAbort>
         <MulticastRecipientLimit>10</MulticastRecipientLimit>
         <WorkItemTimeout>P0DT00H10M00S</WorkItemTimeout>
      </ProtocolExecutionSettings>
   </Protocol>
</Protocols>


Specifying the Notification Expiration Age

The <ExpirationAge> element allows you to specify the length of time permitted for notification re-sends before the notification data is determined to be out of date. If Notification Services cannot successfully deliver a notification before it expires, it abandons the notification without delivering it. If you do not specify an expiration age, notifications never expire.

Note You must exclude the <ExpirationAge> element from the <NotificationClass> node if you do not use it.

For more information, see <ExpirationAge> Element.

Example

This example sets the expiration age of this notification class to 1 hour, 45 minutes, and 30 seconds:

<ExpirationAge>PT01H45M30S</ExpirationAge>


XSLT Content Formatter

Notification Services provides a standard XSLT content formatter to assist you in getting a Notification Services application developed and deployed quickly. This content formatter allows you to specify an XSL transform to be applied to the raw notification data. This XSL transform makes all the formatting changes that are required to prepare the notification data for display.

For each notification it formats, the XSLT content formatter reads an XSL transform from a directory, and creates an intermediate XML document in memory, which contains the notification data. It then applies the XSL transform to this intermediate XML document, which results in the final formatted content. A string containing the formatted content is then passed to a delivery protocol.

You must supply one or more identically named XSLT files, one for each subscriber locale and device type name combination you support. Place each XSLT file in a separate directory. Notification Services selects the appropriate file at run time, based on the device type and subscriber locale specified in the notification data. You also need to document the XSLT file name and the base directory in the application definition file (ADF).

Note You can debug an XSLT file by loading the unformatted XML notifications into a document object model (DOM), applying the NoOp.xslt file that comes with the Notification Services sample applications, and examining the resulting formatted notifications. This is easier than debugging the XSLT file inside Notification Services.

If you need functionality that cannot be addressed by applying XSL transforms to your notification data, you can create a custom content formatter. For more information, see Developing a Custom Content Formatter.


Creating the XSLT File

You must create your XSLT file to transform XML data of the following form:

<Notifications>
   <Notification>
      <Field_Name>field_value</Field_Name>
   </Notification>
</Notifications>

All values in the intermediate XML will be strings.

If the notifications have been aggregated for digest delivery, there will be many <Notification> elements in the XML document. Otherwise, there will only be a single <Notification> element. Each <Notification> element will contain one or more elements that contain the notification data. The names of these elements will reflect the names of the notification fields, and their values will be the values of the notification fields. The notification data will consist of notification fields from the notification table as well as computed notification fields.

Note Consider adding a "for more information" URL to the formatted notification as part of the transform process. Using a URL reduces the amount of notification data to be delivered, yet makes it easy for subscribers to retrieve more information if they choose.

Example

In the following example, a notification record with the two fields StockSymbol (value of AWKS) and StockPrice (value of 55.02) has the following intermediate XML:

<notifications>
   <notification>
      <StockSymbol>AWKS</StockSymbol>
      <StockPrice>55.02</StockPrice>
   </notification>
</notifications>

There is no guarantee about the order of the elements in the intermediate XML.

Any field value in the intermediate XML that represents a date or a number will be in the form appropriate for the locale of the notification. For example, a date for an English-United States locale will be in the MM/DD/YYYY format, while a date for a Japanese-Japan locale will be in the YYYY/MM/DD format. It is up to the application developer to do any additional translation or formatting transformations on the notification contents.


XSLT File Location

Information about the subscriber locale and device type of the recipient is supplied to the content formatter as part of the notification data. The subscriber locale is identified using the set of locale strings that are shipped with Notification Services. The device type is identified using the set of devices supported by the application, as specified by the developer.

These values are not directly available to you to use in the XSLT file. Notification Services uses them to select from among the XSLT files that you provide, based on the XSLT file location.

The base directory that you specify in the application definition file (ADF) is the root directory under which your XSLT files are found. The XSLT file can reside in a subdirectory of the base directory, to allow for specific transforms based on locale and device type.

Notification Services expects to find one subdirectory under the base directory for each combination of locale and device type that is to have a specific transformation. These directories should follow this format:

XSLTBaseDirectory\SubscriberLocale\DeviceType

The subscriber locale and device type elements are optional.

Example

In the following example, you want to provide transformations for the combinations shown in the following table.

Recipient information | XSLT path
French, Canada, all device types | BaseDirectory\fr-CA\transform.xsl
English, Canada, all device types | BaseDirectory\en-CA\transform.xsl
English, United States, cellular phones | BaseDirectory\en-US\CellularPhoneDeviceTypeName\transform.xsl
English, United States, all other device types | BaseDirectory\en-US\transform.xsl

The content formatter searches for an XSLT file that matches the locale and device type information of the notification it is processing, going from the most specific match to the least specific match. The search process looks for matching directories in the following order:

  • XSLTBaseDirectory\SubscriberLocale\DeviceType
  • XSLTBaseDirectory\SubscriberLocale
  • XSLTBaseDirectory\DeviceType
  • XSLTBaseDirectory


Defining the XSLT Content Formatter

Define the XSLT content formatter in the /NotificationClasses/NotificationClass/ContentFormatter section of the application definition file (ADF). The following list reviews the elements in this section and provides their required values:

<ClassName> (required)
This value must be XsltFormatter.
<AssemblyName> (not used)
This element is not used with the XSLT content formatter.
<Arguments> and child elements
The XSLT content formatter takes three named arguments as initialization parameters. You can specify them in any order:
  • XsltBaseDirectory (required) specifies the directory that serves as the root location of all of your XSLT files.
  • XsltFileName (required) specifies the name of the XSLT file used to transform the raw notification data into the appropriate format for display.
  • DisableEscaping (optional) provides a Boolean value that indicates that the event data contains xml or html data, and prevents further transformation of the data. If this argument is not specified the default is false.
XSLT Content Formatter Definition
<ContentFormatter>
   <ClassName>XsltFormatter</ClassName>
   <Arguments>
      <Argument>
         <Name>XsltBaseDirectory</Name>
         <Value>C:\TransformDirectory</Value>
      <Argument>
      <Argument>
         <Name>XsltFileName</Name>
         <Value>StockTransform.xsl</Value>
      <Argument>
   </Arguments>
</ContentFormatter>


Standard Delivery Protocols

Notification Services provides several standard delivery protocols to assist you in defining delivery channels for a Notification Services instance.

The following standard delivery protocols are shipped with Notification Services:

  • File Delivery Protocol: Creates an ASCII text file containing the notification data.
  • SMTP Delivery Protocol: Creates and routes the notification message for delivery by Microsoft Exchange or other Simple Mail Transfer Protocol (SMTP) mail systems.


File Delivery Protocol

The File delivery protocol writes notification data to a text file, using the name you specify for the file in the application definition file (ADF).

Defining a Delivery Channel Using the File Delivery Protocol

Define the delivery channel in the /DeliveryChannels/DeliveryChannel section of the configuration file. The following list reviews the elements in this section and provides their required values:

<DeliveryChannelName> (required)
This value can be any string that conforms to XML naming conventions. It must be unique within the Notification Services instance.
<ProtocolName> (required)
This value must be File.
<Arguments> and child elements
The File delivery protocol requires two named arguments as initialization parameters.
  • FileName (required) specifies the full path and name of the text file that you want the delivery protocol to create.
  • Encoding (optional) specifies the encoding that will be used by the file that is produced. All encoding formats returned by the GetEncoding method of the Encoding class in the Microsoft .NET Framework are acceptable values. If this argument is not specified, the encoding default of utf-8 is used.
File Delivery Channel Configuration File Definition
<DeliveryChannels>
   <DeliveryChannel>
      <DeliveryChannelName>FileChannel1</DeliveryChannelName>
      <!-- "File" is a well-known protocol name. It does not
      require a corresponding entry in the Protocols section
      of the configuration file. -->
      <ProtocolName>File</ProtocolName>
      <Arguments>
         <Argument>
            <Name>FileName</Name>
            <Value>C:\Results\StockNotification.txt</Value>
         </Argument>
      </Arguments>
   </DeliveryChannel>
</DeliveryChannels>
Defining File Delivery Protocol Information in the ADF

Define the notification-specific File delivery protocol information in the NotificationClasses/NotificationClass/Protocols/Protocol section of the ADF. The following list reviews the elements in this section and provides their required values:

<ProtocolName> (required)
This value must be File.
<Fields> and child elements (not used)
This node is not used with the File delivery protocol.

Important You must document the File delivery protocol in the ADF for every notification class that uses it, despite the fact that this delivery protocol requires no protocol header field information. Notification Services uses this protocol information to determine what protocols are valid for delivering notifications of that class.

File Delivery Protocol ADF Definition
<Protocols>
   <Protocol>
      <ProtocolName>File</ProtocolName>
      <ProtocolExecutionSettings>
      ...
      </ProtocolExecutionSettings>
   </Protocol>
<Protocols>


SMTP Delivery Protocol

The Simple Mail Transfer Protocol (SMTP) delivery protocol creates and routes notification messages for delivery by Microsoft Exchange or other SMTP mail systems.

Defining a Delivery Channel Using the SMTP Delivery Protocol

Define the delivery channel in the /DeliveryChannels/DeliveryChannel section of the configuration file. The following list reviews the elements in this section and provides the values required by the SMTP delivery protocol:

<DeliveryChannelName> (required)
This value can be any string that conforms to XML naming conventions. It must be unique within your application.
<ProtocolName> (required)
This value must be SMTP.
<Arguments> and child elements
The SMTP delivery protocol takes two named arguments as initialization parameters.
  • SmtpServer specifies a server to which all e-mail notifications are delivered. If this property is not set, mail is queued on the local system by default, ensuring that the calling program does not block network traffic.

    If the SmtpServer property is set to a single forwarding server, then local e-mail queuing on the Notification Services server can be avoided.

  • BodyEncoding specifies the string format required by the SMTP server. All encoding formats returned by the GetEncoding method of the Encoding class in the Microsoft .NET Framework are acceptable values. Not all platforms support all encodings; if an encoding is not supported by the deployed platform, a NotSupportedException is thrown.

    Note You cannot specify connection information (like name and password) for the SMTP server as part of the delivery channel configuration. Establishment of a connection to the configured SMTP server is handled by the operating system.

SMTP Delivery Protocol Configuration File Definition
<DeliveryChannels>
   <DeliveryChannel>
      <DeliveryChannelName>SMTPServer1</DeliveryChannelName>
      <!-- "SMTP" is a well-known protocol name. It does not
      require a corresponding entry in the Protocols section
      of the configuration file. -->
      <ProtocolName>SMTP</ProtocolName>
      <Arguments>
         <Argument>
            <Name>SmtpServer</Name>
            <Value>MJOLLNIR</Value>
         </Argument>
         <Argument>
            <Name>BodyEncoding</Name>
            <Value>utf-16</Value>
         </Argument>
      </Arguments>
   </DeliveryChannel>
</DeliveryChannels>
Defining SMTP Delivery Protocol Information in the ADF

Define the notification-specific SMTP delivery protocol information in the /NotificationClasses/NotificationClass/Protocols/Protocol section of the application definition file (ADF). The following list reviews the elements in this section and provides their required values:

<ProtocolName> (required)
This value must be SMTP.
<Fields> and child elements
The SMTP delivery protocol allows five fields to be specified for use in the header of the notification message, in the order presented. If you use a string constant as a <SqlExpression> value in any of these fields, it must be enclosed in apostrophes (expressed as the entity reference &apos; in the ADF).
  • Subject (required) specifies the expression that represents the subject line to be displayed in the e-mail.
  • From (required) specifies the sending e-mail address to be displayed in the e-mail.
  • To (required) must specify the address of the target device for standard notifications. This field must be blank for a notification class that is providing multicast notifications.
  • Priority (optional) specifies the priority with which the notification e-mail is to be sent, using the values appropriate for the mail subsystem that will be delivering the message. For example, with Microsoft Exchange you would specify Low, Normal, or High. The notification priority default is Normal if no other value is specified.
  • BodyFormat (optional) takes either Text or Html as its value, depending on what the intended format is for the notification data provided by the content formatter. The notification format default is Text if no value is specified.
SMTP Delivery Protocol ADF Definition
<Protocols>
   <Protocol>
      <ProtocolName>SMTP</ProtocolName>
      <Fields>
         <Field>
            <FieldName>Subject</FieldName>
            <SqlExpression>
            &apos;The price of &apos; + StockSymbol
            + &apos; is now &apos; + StockPrice
            </SqlExpression>
         </Field>
         <Field>
            <FieldName>From</FieldName>
            <SqlExpression>
            &apos;stockquotes@microsoft.com&apos;
            </SqlExpression>
         </Field>
         <Field>
            <FieldName>To</FieldName>
            <SqlExpression>DeviceAddress</SqlExpression>
         </Field>
         <Field>
            <FieldName>Priority</FieldName>
            <SqlExpression>&apos;Normal&apos;</SqlExpression>
         </Field>
         <Field>
            <FieldName>BodyFormat</FieldName>
            <SqlExpression>&apos;html&apos;</SqlExpression>
         </Field>
      </Fields>
      <ProtocolExecutionSettings>
      ...
      </ProtocolExecutionSettings>
   </Protocol>
</Protocols>


Instance and Application APIs

Notification Services provides several classes for accessing Notification Services instance and application information.

These classes provide limited administrative access to your Notification Services instances and applications. Objects of these classes are required for the initialization of most other Notification Services classes.

The topics that this section covers are described in the following table.

Topic | Description
Notification Services Instance Classes | Reviews the classes that provide information about or references to Notification Services instances.
Notification Services Application Classes | Reviews the classes that provide information about or references to Notification Services applications.


Notification Services Instance Classes

The InstanceEnumeration, NSInstanceDescription, and NSInstance classes provide access to Notification Services instances and their properties. These classes are provided by the Notification Services API, and can be found in the Microsoft.SqlServer.NotificationServices namespace.

InstanceEnumeration Class

The InstanceEnumeration class is primarily used to iterate through the available Notification Services instances on the local computer. You can also return an NSInstanceDescription object by supplying an instance name to an InstanceEnumeration object's indexer.

NSInstanceDescription Class

The NSInstanceDescription class provides descriptive information about a specified Notification Services instance. You can use the Item property of an InstanceEnumeration object to return an NSInstanceDescription object. The NSInstanceDescription class is often used for administrative purposes, to programmatically discover information about the Notification Services instances on a server. This information can then be used to create an NSInstance object. The NSInstanceDescription class provides properties to get the following values for the instance:

InstanceName
Gets the name of the instance.
DBServerName
Gets the machine name of the server that hosts the SQL Server instance that contains the Notification Services instance database.
Version
Gets the Notification Services version of the instance.
NSInstance Class

The NSInstance class acts as a programmatically accessible reference to a specified Notification Services instance. It is often used to initialize other Notification Services classes. The NSInstance class provides properties to get or set the following values for the instance:

InstanceName
Gets the name of the instance.
SqlPassword
Sets the SQL Server password for the account used to access the instance database. This property is required only in environments where mixed security (SQL Server and Windows Authentication) rather than integrated security (only Windows Authentication) is being used with SQL Server.
SqlUser
Sets the SQL Server user name for the account used to access the instance database. This property is required only in environments where mixed security (SQL Server and Windows Authentication) rather than integrated security (only Windows Authentication) is being used with SQL Server.
Version
Gets the Notification Services version of the instance. A single server can host multiple instances of Notification Services, and each of these instances can be a different version.

See Also

InstanceEnumeration Class

NSInstance Class

NSInstanceDescription Class


Obtaining a Reference to a Notification Services Instance

You will often need to obtain a reference to a particular Notification Services instance. This reference is used to initialize other Notification Services classes that represent instance-specific data. Use an object of the NSInstance class to obtain this reference.

The following classes require an NSInstance object for initialization:

  • Subscriber, SubscriberEnumeration
  • SubscriberDevice, SubscriberDeviceEnumeration
  • DeliveryChannelEnumeration
  • SubscriberLocaleEnumeration
  • TimeZoneEnumeration
  • NSApplication, ApplicationEnumeration
Managed Code Example

You can create and initialize the NSInstance object in managed code by using the parameterized constructor to pass in the name of the desired Notification Services instance. The NSInstance object will be usable immediately.

string instanceName = "MyInstanceName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);
COM Interop Example

You can create and initialize the NSInstance object via COM interop by using the parameter-less constructor to create the object, and then calling the Initialize method to initialize it.

Dim myInstance

const instanceName = "MyInstanceName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

See Also

NSInstance Constructor

NSInstance.Initialize Method


Verifying Instance Properties

You might want to verify an NSInstance object before using it. Calling Verify tests the connection to the instance database, to verify that it is reachable. This allows you to force any connection-related errors for the NSInstance object at one place in your application, before you use it to initialize other objects.

Use the Verify method of the NSInstance object to perform verification.

Managed Code Example
string instanceName = "MyInstanceName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Verify the NSInstance object.
myInstance.Verify();
COM Interop Example
Dim myInstance

const instanceName = "MyInstanceName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Verify the NSInstance object.
myInstance.Verify

See Also

NSInstance.Verify Method


Getting and Setting Instance Information

You can retrieve descriptive information about a Notification Services instance from an NSInstanceDescription or NSInstance object. In general, use the NSInstanceDescription object to retrieve information in order to create an NSInstance object, in cases where you must discover this information at run time.

The primary use of an NSInstance object is to gain access to other instance objects, like subscribers. However, you can also retrieve instance information from an NSInstance object.

Both NSInstance and NSInstanceDescription objects provide instance name and version information. NSInstanceDescription additionally provides the name of the server that hosts the SQL Server instance containing the Notification Services instance database. NSInstance additionally provides properties to set SQL Server login information for the Notification Services instance database, if you use SQL Server Authentication rather than Windows Authentication as your SQL Server security mode.

Important Microsoft strongly recommends that you use Windows Authentication rather than SQL Server Authentication. Windows Authentication provides better security features, such as secure validation and encryption of passwords, auditing, password expiration, minimum password length, and account lockout after multiple invalid login requests.

Managed Code Example: Using an NSInstance Object to Get Instance Information
string instanceName = "MyInstanceName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Verify the NSInstance object.
myInstance.Verify();

//Display the instance information.
txtInstanceName.Text = myInstance.InstanceName;
txtVersion.Text = myInstance.Version;
Managed Code Example: Using an NSInstanceDescription Object to Get Instance Information
string instanceName = "MyInstanceName";

//Create the InstanceEnumeration object.
Microsoft.SqlServer.NotificationServices.InstanceEnumeration myInstanceEnumeration = new Microsoft.SqlServer.NotificationServices.InstanceEnumeration();

//Use the InstanceEnumeration object to step through
//the collection of NSInstanceDescription objects.
foreach (Microsoft.SqlServer.NotificationServices.NSInstanceDescription nsi in myInstanceEnumeration)
{
   //Display the instance information.
   Console.Writeline("Instance Name is " + nsi.InstanceName);
   Console.Writeline("Version is " + nsi.Version);
   Console.Writeline("Database Server is " + nsi.DBServerName);
}
COM Interop Example: Using an NSInstance Object to Get Instance Information
Dim myInstance

const instanceName = "MyInstanceName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Verify the NSInstance object.
myInstance.Verify

'Display the instance information.
Wscript.Echo "InstanceName", myInstance.InstanceName
Wscript.Echo "Version", myInstance.Version
Wscript.Echo
COM Interop Example: Using an NSInstanceDescription Object to Get Instance Information
Dim myInstanceEnumeration

set myInstanceEnumeration = Wscript.CreateObject("Microsoft.SqlServer.NotificationServices.InstanceEnumeration")

for each nsInstanceDescription in myInstanceEnumeration
   Wscript.Echo "InstanceName", nsInstanceDescription.InstanceName
   Wscript.Echo "DBServerName", nsInstanceDescription.DBServerName
   Wscript.Echo "Version", nsInstanceDescription.Version
   Wscript.Echo
next

See Also

InstanceEnumeration Class

NSInstance Class

NSInstanceDescription Class


Notification Services Application Classes

The NSApplication and ApplicationEnumeration classes provide access to Notification Services applications and their properties. These classes are provided by the Notification Services API, and can be found in the Microsoft.SqlServer.NotificationServices namespace.

ApplicationEnumeration Class

The ApplicationEnumeration class is used primarily to iterate through the applications within a specified Notification Services instance. You can also select a specific application by supplying its application name to an ApplicationEnumeration object's indexer.

NSApplication Class

The NSApplication class acts as a programmatically accessible reference to a specified application within a specified Notification Services instance. It is often used to initialize other Notification Services classes. The NSApplication class provides properties to get the following values for the application:

ApplicationName
Gets the name of the application.
Version
Gets the version number of the application, as specified in the application definition file (ADF).

See Also

ApplicationEnumeration Class

NSApplication Class


Obtaining a Reference to a Notification Services Application

You will often need to obtain a reference to a particular Notification Services application. This reference initializes other Notification Services classes that represent application-specific data. Use an object of the NSApplication class to do this.

The following classes require an NSApplication object for initialization:

  • Subscription, SubscriptionEnumeration
  • SubscriptionClassEnumeration
  • Event
  • EventCollector
  • EventLoader
  • EventClassEnumeration
Managed Code Example

The following code example shows that you can create and initialize the NSApplication object by using the parameterized constructor to pass in the name of the application and an NSInstance object representing the Notification Services instance that hosts it. NSApplication will be usable immediately.

string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Verify the NSInstance object.
myInstance.Verify();

//Create the NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);
COM Interop Example

The following code example shows that you can create and initialize the NSApplication object via COM interop by using the parameter-less constructor to create the object, and then calling the Initialize method to initialize it.

Dim myInstance, myApplication

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Verify the NSInstance object.
myInstance.Verify

'Create the NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

See Also

NSApplication Constructor

NSApplication.Initialize Method


Verifying Application Properties

You might want to verify an NSApplication object before using it. Calling Verify tests the connection to the application database, to verify that it is reachable. This allows you force any connection-related errors for the NSApplication object at one place in your application, before you use it to initialize other objects.

Use of the NSApplication Verify method also invokes the Verify method on the NSInstance object used to initialize the NSApplication object. You can use a single Verify call to validate both objects in this way.

Use the Verify method of the NSApplication object to perform verification.

Managed Code Example
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Verify the NSInstance object.
myInstance.Verify();

//Create the NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Verify the NSApplication object.
myApplication.Verify();
COM Interop Example
Dim myInstance, myApplication

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Verify the NSInstance object.
myInstance.Verify

'Create the NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Verify the NSApplication object.
myApplication.Verify

See Also

NSApplication.Verify Method


Getting Application Information

The primary use of an NSApplication object is to gain access to other application objects, like events and subscriptions. However, you can also retrieve application information, like application name and version, from an NSApplication object.

Managed Code Example
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Verify the NSInstance object.
myInstance.Verify();

//Create the NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Verify the NSApplication object.
myApplication.Verify();

//Display the application information.
txtAppName.Text = myApplication.ApplicationName;
txtAppVersion.Text = myApplication.Version;
COM Interop Example
Dim myInstance, myApplication

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Verify the NSInstance object.
myInstance.Verify

'Create the NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Verify the NSApplication object.
myApplication.Verify

'Display the application information.
Wscript.Echo "ApplicationName", myApplication.ApplicationName
Wscript.Echo "Version", myApplication.Version
Wscript.Echo

See Also

NSApplication Class


Developing Subscription Management Applications

Subscriber and subscription information is entered into the Notification Services system by a subscription management application. This is often a Web application based on Microsoft Active Server Page (ASP page) or ASP.NET technologies. You are required to develop this application, but the Notification Services API provides a number of classes to simplify the collection and submission of subscriber and subscription data. It also supplies several enumeration classes, to make it easy to select values for user options such as device types, time zones, and subscriber locales.

For more information about using ASP and ASP.NET, see Active Server Pages and ASP.NET in the Microsoft MSDN® Library.

The topics that this section covers are described in the following table.

Topic | Description
Subscription Management Application Security | Discusses the options available when setting up the accounts that the subscription management application is to use.
Managing Subscribers | Describes how to use the Notification Services Subscriber and SubscriberEnumeration classes to enter and maintain subscriber information.
Managing Subscriber Devices | Describes how to use the Notification Services SubscriberDevice and SubscriberDeviceEnumeration classes to enter and maintain subscriber device information. Discusses how to use the DeliveryChannel class, along with its related enumeration class, to provide information from a standard Notification Services table to your user interface.
Managing Subscriptions | Describes how to use the Notification Services Subscription and SubscriptionEnumeration classes to enter and maintain subscription information. Discusses how to use the SubscriberLocale and TimeZone classes, along with their related enumeration classes, to provide information from standard Notification Services tables to your user interface.


Subscription Management Application Security

The subscription management application must use accounts when accessing the Notification Services databases. You have several options for setting up these accounts: you can use a local account, a domain account, or SQL Server Authentication.

Using a Local Account

The subscription management application can use a local account only when it runs on the same server as the SQL Server instance that hosts the Notification Services databases. A convenient account to use in this situation is the ASPNET account, which is created automatically when the Microsoft .NET Framework is installed. The Notification Services sample applications use this account when deployed in a single-server configuration.

Using A Domain Account

The subscription management application can use a domain account in two situations: when it runs on the same server as the SQL Server instance that hosts the Notification Services databases; and when it accesses a SQL Server instance on another computer.

Using a domain account allows you to use Windows Authentication, which provides better security features than SQL Server Authentication, such as secure validation and encryption of passwords, auditing, password expiration, minimum password length, and account lockout after multiple invalid login requests.

Using SQL Server Authentication

The subscription management application can use SQL Server Authentication in the same situations as for using a domain account: both when it runs on the same server as the SQL Server instance that hosts the Notification Services databases, and when it accesses a SQL Server instance on another computer.

Important Microsoft strongly recommends that you specify a domain account for use by the subscription management application rather than using SQL Server Authentication.

For more information about adding login accounts and database users, see "sp_grantlogin" and "sp_grantdbaccess" in SQL Server Books Online.

See Also

Notification Services Database Roles


Managing Subscribers

The Subscriber and SubscriberEnumeration classes provide a way to enter, update, and delete subscriber information. These classes are provided by the Notification Services API, and can be found in the Microsoft.SqlServer.NotificationServices namespace.

Subscriber Class

The Subscriber class provides the following properties for the subscriber:

Enabled
Indicates whether the subscriber is currently enabled to receive notifications. The default value is true.
SubscriberId
Indicates a particular subscriber record. Notification Services does not generate this value; it must be generated by your application or specified by the end user.

The Subscriber class contains subscriber data, which is usually passed to it through the subscription management application user interface. A Subscriber object creates or updates a single subscriber record at a time. You must use a Subscriber object to update subscriber information once the information has been entered into the Notification Services system.

SubscriberEnumeration Class

The SubscriberEnumeration class represents the set of subscribers in a Notification Services instance. You select a specific subscriber record by supplying its subscriber ID to the indexer of a SubscriberEnumeration object, or you can step through all the subscribers in a Notification Services instance one at a time.

See Also

Subscriber Class

SubscriberEnumeration Class


Creating a Subscriber Object

You must create a Subscriber object to add, delete, or update subscriber information in the Notification Services system.

Managed Code Example

The following code example shows how to create and initialize the Subscriber object by using the parameterized constructor to pass in the name of the desired Notification Services instance. The Subscriber object is usable immediately:

string instanceName = "MyInstanceName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);
COM Interop Example

The following code example shows how to create and initialize the Subscriber object via COM interop, by using the parameter-less constructor to create the object and then calling the Initialize method to initialize it:

Dim myInstance, mySubscriber

const instanceName = "MyInstanceName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the Subscriber object.
set mySubscriber = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscriber")
mySubscriber.Initialize myInstance

See Also

Subscriber Constructor

Subscriber.Initialize Method


Adding a Subscriber Record

The Subscriber object exposes properties that allow you to set the SubscriberId value and indicate whether the subscriber is enabled to receive notifications. The Add method of this object writes that data to the Notification Services database.

Managed Code Example

The following code example shows how to use a Subscriber object in managed code to add a subscriber:

string instanceName = "MyInstanceName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the properties that describe the subscriber record.
mySubscriber.Enabled = chkEnabled.Checked;
mySubscriber.SubscriberId = txtID.Text;

//Add the subscriber record to the database.
mySubscriber.Add();
COM Interop Example

The following code example shows how to use a Subscriber object in unmanaged code to add a subscriber:

Dim myInstance, mySubscriber

const instanceName = "MyInstanceName"
const subscriberId = "TestSubscriber"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

set mySubscriber = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscriber")
mySubscriber.Initialize myInstance

'Set the properties that describe the subscriber record.
mySubscriber.SubscriberId = subscriberId
mySubscriber.Enabled = true

'Add the subscriber record to the database.
mySubscriber.Add

See Also

Subscriber.Add Method


Updating a Subscriber Record

You must use the Update method of the Subscriber class to modify existing subscriber data in the Notification Services database.

Managed Code Example

The following code example shows how to use a Subscriber object in managed code to update a subscriber:

string instanceName = "MyInstanceName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the subscriber ID so that the correct subscriber
//record is updated.
mySubscriber.SubscriberId = txtSubscriberId.Text;

//Change subscriber data, then update the database.
mySubscriber.Enabled = true;
mySubscriber.Update();
COM Interop Example

The following code example shows how to use a Subscriber object in unmanaged code to update a subscriber:

Dim myInstance, mySubscriber

const instanceName = "MyInstanceName"
const subscriberId = "TestSubscriber"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the Subscriber object.
set mySubscriber = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscriber")
mySubscriber.Initialize myInstance

'Set the subscriber ID so that the correct subscriber
'record is updated.
mySubscriber.SubscriberId = subscriberId

'Change subscriber data, then update the database.
mySubscriber.Enabled = false
mySubscriber.Update

See Also

Subscriber.Update Method


Deleting a Subscriber Record

The Delete method of the Subscriber class deletes an existing subscriber record in the Notification Services database. In enabled Notification Services applications, deleting a subscriber record automatically deletes all subscriber devices and subscriptions associated with that subscriber ID. In disabled Notification Services applications, deleting a subscriber record causes associated subscriptions to be orphaned.

Managed Code Example

The following code example shows how to use a Subscriber object in managed code to delete a subscriber:

string instanceName = "MyInstanceName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the subscriber ID so that the correct subscriber
//record is deleted.
mySubscriber.SubscriberId = txtSubscriberId.Text;

//Delete the subscriber.
mySubscriber.Delete();
COM Interop Example

The following code example shows how to use a Subscriber object in unmanaged code to delete a subscriber:

Dim myInstance, mySubscriber

const instanceName = "MyInstanceName"
const subscriberId = "TestSubscriber"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the Subscriber object.
set mySubscriber = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscriber")
mySubscriber.Initialize myInstance

'Set the subscriber ID so that the correct subscriber
'record is deleted.
mySubscriber.SubscriberId = subscriberId

'Delete the subscriber.
mySubscriber.Delete

See Also

Subscriber.Delete Method


Deleting Related Subscription Information

The DeleteSubscriptions method of the Subscriber class deletes existing subscription records for a given subscriber. You can delete all related subscriptions, just the subscriptions for one application, or just the subscriptions for one subscription class in one application.

Managed Code Example: Delete All Subscriptions

The following code example shows how to use a Subscriber object in managed code to delete all subscriptions belonging to a single subscriber:

string instanceName = "MyInstanceName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the subscriber ID so that the correct
//records are affected.
mySubscriber.SubscriberId = txtSubscriberId.Text;

//Delete all subscriptions of all subscription classes
//in all applications for this subscriber.
mySubscriber.DeleteSubscriptions();
Managed Code Example: Delete Subscriptions for One Application

The following code example shows how to use a Subscriber object in managed code to delete all subscriptions to one application belonging to a single subscriber:

string instanceName = "MyInstanceName";
string applicationName= "MyApplicationName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the subscriber ID so that the correct
//records are affected.
mySubscriber.SubscriberId = txtSubscriberId.Text;

//Create the NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Delete the subscriptions for the given application.
mySubscriber.DeleteSubscriptions(myApplication);
Managed Code Example: Delete Subscriptions of One Subscription Class in One Application

The following code example shows how to use a Subscriber object in managed code to delete all subscriptions of one subscription class in one application belonging to a single subscriber:

string instanceName = "MyInstanceName";
string applicationName= "MyApplicationName";
string subscriptionClassName= "MySubscriptionClassName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the subscriber ID so that the correct
//records are affected.
mySubscriber.SubscriberId = txtSubscriberId.Text;

//Create the NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Delete the subscriptions for the given
//subscription class in the given application.
mySubscriber.DeleteSubscriptions(myApplication,subscriptionClassName);
COM Interop Example: Delete All Subscriptions

The following code example shows how to use a Subscriber object in unmanaged code to delete all subscriptions belonging to a single subscriber:

Dim myInstance, mySubscriber

const instanceName = "MyInstanceName"
const subscriberId = "TestSubscriber"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the Subscriber object.
set mySubscriber = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscriber")
mySubscriber.Initialize myInstance

'Set the subscriber ID so that the correct
'records are affected.
mySubscriber.SubscriberId = subscriberId

'Delete all subscriptions of all subscription classes
'in all applications for this subscriber.
mySubscriber.DeleteSubscriptions Nothing, ""
COM Interop Example: Delete Subscriptions of One Subscription Class in One Application

The following code example shows how to use a Subscriber object in unmanaged code to delete all subscriptions of one subscription class in one application belonging to a single subscriber:

Dim myInstance, mySubscriber, myApplication

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const subscriptionClassName = "MySubscriptionClassName"
const subscriberId = "TestSubscriber"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the Subscriber object.
set mySubscriber = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscriber")
mySubscriber.Initialize myInstance

'Create the NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Set the subscriber ID so that the correct
'records are affected.
mySubscriber.SubscriberId = subscriberId

'Delete the subscriptions for the given
'subscription class in the given application.
mySubscriber.DeleteSubscriptions myApplication, subscriptionClassName

See Also

Subscriber.DeleteSubscriptions Method


Getting a Subscriber's Devices and Subscriptions

The Subscriber class provides the GetSubscriptions and GetDevices methods, to give access to subscriber device and subscription records related to a specified subscriber.

You use the GetSubscriptions method of the Subscriber class to return a SubscriptionEnumeration object that represents the collection of all the subscriptions of one subscription class in one application for the specified subscriber.

You use the GetDevices method of the Subscriber class to return a SubscriberDeviceEnumeration object that represents the collection of all the devices for the specified subscriber.

Managed Code Example: Return Subscriptions

The following code example shows how to use a Subscriber object in managed code to return all subscriptions belonging to a single subscriber:

string instanceName = "MyInstanceName";
string applicationName= "MyApplicationName";
string subscriptionClassName= "MySubscriptionClassName";
string subscriptionFieldName = "MySubscriptionFieldName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the subscriber ID so that the correct
//records are retrieved.
mySubscriber.SubscriberId = txtSubscriberId.Text;

//Create the NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Retrieve the subscriber's subscriptions.
Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration mySubscriptionEnumeration =
mySubscriber.GetSubscriptions(myApplication, subscriptionClassName);

foreach(Microsoft.SqlServer.NotificationServices.Subscription subscription in mySubscriptionEnumeration)
{
   myList.Items.Add(subscription[subscriptionFieldName].ToString());
}
Managed Code Example: Return Devices

The following code example shows how to use a Subscriber object in managed code to return all devices belonging to a single subscriber:

string instanceName = "MyInstanceName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the subscriber ID so that the correct
//records are retrieved.
mySubscriber.SubscriberId = txtSubscriberId.Text;

//Retrieve the subscriber's devices.
Microsoft.SqlServer.NotificationServices.SubscriberDeviceEnumeration mySubscriberDeviceEnumeration = mySubscriber.GetDevices();

foreach(Microsoft.SqlServer.NotificationServices.SubscriberDevice subscriberDevice in mySubscriberDeviceEnumeration)
{
   myList.Items.Add(subscriberDevice.DeviceName);
}
COM Interop Example: Return Subscriptions

The following code example shows how to use a Subscriber object in unmanaged code to return all subscriptions belonging to a single subscriber:

Dim myInstance, mySubscriber, myApplication, mySubscriptionEnumeration

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const subscriptionClassName = "MySubscriptionClassName"
const subscriptionFieldName = "MySubscriptionFieldName"
const subscriberId = "TestSubscriber"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the Subscriber object.
set mySubscriber = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscriber")
mySubscriber.Initialize myInstance

'Create the NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Retrieve the subscriber's subscriptions.
set mySubscriptionEnumeration = mySubscriber.GetSubscriptions(myApplication, subscriptionClassName)

for each subscription in mySubscriptionEnumeration
   if subscription.SubscriberId = subscriberId then
      Wscript.Echo "Field Value", subscription.GetFieldValue(subscriptionFieldName)
      WScript.Echo
   end if
next
COM Interop Example: Return Devices

The following code example shows how to use a Subscriber object in unmanaged code to return all devices belonging to a single subscriber:

Dim myInstance, mySubscriber, mySubscriberDeviceEnumeration

const instanceName = "MyInstanceName"
const subscriberId = "TestSubscriber"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the Subscriber object.
set mySubscriber = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscriber")
mySubscriber.Initialize myInstance

'Set the subscriber ID so that the correct
'records are retrieved.
mySubscriber.SubscriberId = subscriberId

'Retrieve the subscriber's devices.
set mySubscriberDeviceEnumeration = mySubscriber.GetDevices

for each subscriberDevice in mySubscriberDeviceEnumeration
   Wscript.Echo "Device Name", subscriberDevice.DeviceName
   WScript.Echo
next

See Also

Subscriber.GetDevices Method

Subscriber.GetSubscriptions Method


Managing Subscriber Devices

The SubscriberDevice and SubscriberDeviceEnumeration classes provide a way to enter, update, and delete the target devices that subscribers use to receive notifications. These classes are provided by the Notification Services API, and can be found in the Microsoft.SqlServer.NotificationServices namespace.

SubscriberDevice Class

The SubscriberDevice class provides the following properties for the subscriber device:

DeviceAddress
Provides the address for this device. For example, a telephone number might be the address for a system management software (SMS) device.
DeliveryChannelName
Provides the delivery channel for this device. This value must be selected from the delivery channels defined for the Notification Services instance. The delivery channel determines how the notification is sent to this device, including the networking protocol that must be used to deliver the notification message packet.
DeviceName
Provides a user-defined value that identifies this subscriber device record.
DeviceTypeName
Identifies what kind of device this is, for instance a cell phone or a pager. You must determine the list of devices your application can support.
SubscriberId
Identifies the subscriber to whom this device belongs. A subscriber record with this subscriber ID must already exist in the Notification Services database.

The SubscriberDevice class represents subscriber device data, which is usually passed to it by the subscription management application user interface. A SubscriberDevice object creates or updates a single subscriber device record at a time. You must use a SubscriberDevice object to update subscriber device information once it has been entered into the Notification Services system.

You decide how many devices each subscriber can have, and how the DeviceName value is assigned. If you allow subscribers to have more than one device, you might want to let them pick their own device names. If you allow subscribers to have only one device, you might want to assign standard device names, based on the device type or some other criterion.

Although including the subscriber device name in every subscription is common, it is not required. For example, there is no need to keep a device name in your subscriptions if your application always delivers notifications via e-mail and you use the subscriber's e-mail address as their subscriber ID. In this case you can simply pass a constant device name, such as "email device", when you generate a notification. Alternatively, you might decide not to include the subscriber's device name in the subscription because you always select the device name dynamically when you generate the notification. For example, your application might select the device based on time of day. During business hours you could send all notifications to a subscriber's business e-mail account; during off-hours you might send critical notifications to the subscriber's phone and all other notifications to the subscriber's home e-mail account.

SubscriberDeviceEnumeration Class

The SubscriberDeviceEnumeration class represents the set of subscriber devices for a given subscriber in a Notification Services instance. You can select a specific subscriber device by supplying its device name to the indexer of a SubscriberDeviceEnumeration object.

See Also

SubscriberDevice Class

SubscriberDeviceEnumeration Class


Creating a SubscriberDevice Object

You must create an object of the SubscriberDevice class to add, delete, and update subscriber device information in the Notification Services system.

Managed Code Example

The following code example shows how to create and initialize the SubscriberDevice object by using the parameterized constructor to pass in the name of the desired Notification Services instance. The SubscriberDevice object is usable immediately:

string instanceName = "MyInstanceName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the SubscriberDevice object.
Microsoft.SqlServer.NotificationServices.SubscriberDevice mySubscriberDevice = new Microsoft.SqlServer.NotificationServices.SubscriberDevice(myInstance);
COM Interop Example

The following code example shows how to create and initialize the SubscriberDevice object via COM interop, by using the parameter-less constructor to create the object and then calling the Initialize method to initialize it:

Dim myInstance, mySubscriberDevice

const instanceName = "MyInstanceName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the SubscriberDevice object.
set mySubscriberDevice = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriberDevice")
mySubscriberDevice.Initialize myInstance

See Also

SubscriberDevice Constructor

SubscriberDevice.Initialize Method


Adding a Subscriber Device

The SubscriberDevice object exposes properties that allow you to set information about what type of device this is, what subscriber it belongs to, and how to deliver notifications to it. The Add method of this object writes that data to the Notification Services database.

Managed Code Example

The following code example shows how to use a SubscriberDevice object in managed code to add a subscriber device:

string instanceName = "MyInstanceName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the SubscriberDevice object.
Microsoft.SqlServer.NotificationServices.SubscriberDevice mySubscriberDevice = new Microsoft.SqlServer.NotificationServices.SubscriberDevice(myInstance);

//Set the properties that describe the subscriber device record.
mySubscriberDevice.SubscriberId = txtSubscriberId.Text;
mySubscriberDevice.DeviceAddress = txtAddress.Text;
mySubscriberDevice.DeliveryChannelName = ddChannels.SelectedItem.Value;
mySubscriberDevice.DeviceTypeName = ddTypes.SelectedItem.Value;
mySubscriberDevice.DeviceName = txtDeviceName.Text;

//Add the subscriber record to the database.
mySubscriberDevice.Add();
COM Interop Example

The following code example shows how to use a SubscriberDevice object in unmanaged code to add a subscriber device:

Dim myInstance, mySubscriberDevice

const instanceName = "MyInstanceName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the SubscriberDevice object.
set mySubscriberDevice = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriberDevice")
mySubscriberDevice.Initialize myInstance

mySubscriberDevice.SubscriberId = Request.Form("SubscriberId")
mySubscriberDevice.DeviceAddress = Request.Form("DeviceAddress")
mySubscriberDevice.DeliveryChannelName = Request.Form("DeliveryChannel")
mySubscriberDevice.DeviceTypeName = Request.Form("DeviceType")
mySubscriberDevice.DeviceName = Request.Form("DeviceName")
mySubscriberDevice.Add

See Also

SubscriberDevice.Add Method


Updating a Subscriber Device

Use the Update method of the SubscriberDevice class to modify existing subscriber device data in the Notification Services database.

Managed Code Example

The following code example shows how to use a SubscriberDevice object in managed code to update a subscriber device:

string instanceName = "MyInstanceName";
string deviceName = txtDeviceName.Text;

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the SubscriberDevice object.
Microsoft.SqlServer.NotificationServices.SubscriberDevice mySubscriberDevice = new Microsoft.SqlServer.NotificationServices.SubscriberDevice(myInstance);

//Set the subscriber ID and device name
//so that the correct record is updated.
mySubscriberDevice.SubscriberId = txtSubscriberId.Text;
mySubscriberDevice.DeviceName = deviceName;

//Modify the subscriber device properties
//and update the record.
mySubscriberDevice.DeviceAddress = txtAddress.Text;
mySubscriberDevice.DeliveryChannelName = ddChannels.SelectedItem.Value;
mySubscriberDevice.DeviceTypeName = ddTypes.SelectedItem.Value;
mySubscriberDevice.Update();
COM Interop Example

The following code example shows how to use a SubscriberDevice object in unmanaged code to update a subscriber device:

Dim myInstance, mySubscriberDevice

const instanceName = "MyInstanceName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the SubscriberDevice object.
set mySubscriberDevice = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriberDevice")
mySubscriberDevice.Initialize myInstance

'Set the subscriber ID and device name
'so that the correct record is updated.
mySubscriberDevice.SubscriberId = Request.Form("SubscriberId")
mySubscriberDevice.DeviceName = Request.Form("DeviceName")

'Change a subscriber device property
'and update the record.
mySubscriberDevice.DeviceAddress = Request.Form("DeviceAddress")
mySubscriberDevice.DeliveryChannelName = Request.Form("DeliveryChannel")
mySubscriberDevice.DeviceTypeName = Request.Form("DeviceType")
mySubscriberDevice.Update

See Also

SubscriberDevice.Update Method


Deleting a Subscriber Device

The Delete method of the SubscriberDevice class deletes an existing subscriber device record in the Notification Services database.

Managed Code Example

The following code example shows how to use a SubscriberDevice object in managed code to delete a subscriber device:

string instanceName = "MyInstanceName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the SubscriberDevice object.
Microsoft.SqlServer.NotificationServices.SubscriberDevice mySubscriberDevice = new Microsoft.SqlServer.NotificationServices.SubscriberDevice(myInstance);

//Set the subscriber ID and device name
//so that the correct record is deleted.
mySubscriberDevice.SubscriberId = txtSubscriberId.Text;
mySubscriberDevice.DeviceName = txtDeviceName.Text;

//Delete the subscriber device.
mySubscriberDevice.Delete();
COM Interop Example

The following code example shows how to use a SubscriberDevice object in unmanaged code to delete a subscriber device:

Dim myInstance, mySubscriberDevice

const instanceName = "MyInstanceName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the SubscriberDevice object.
set mySubscriberDevice = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriberDevice")
mySubscriberDevice.Initialize myInstance

'Set the subscriber ID and device name
'so that the correct record is deleted.
mySubscriberDevice.SubscriberId = Request.Form("SubscriberId")
mySubscriberDevice.DeviceName = Request.Form("DeviceName")

'Delete the subscriber device.
mySubscriberDevice.Delete

See Also

SubscriberDevice.Delete Method


Populating a Delivery Channel List

You might want to provide a drop-down list of delivery channels in your application user interface, so that users can select valid delivery channels for their subscriber devices. The DeliveryChannel and DeliveryChannelEnumeration classes can be used to provide this information.

It is possible that not all of the delivery channels offered in a Notification Services instance are appropriate for all of your applications. It is up to you to ensure that your user interface offers only those delivery channels that are valid for the application that is being subscribed to.

Managed Code Example
The following code example shows how to use a DeliveryChannelEnumeration object in managed code to populate a dropdown list in your subscription management application:using Microsoft.SqlServer.NotificationServices;
public class AppSubscriberDevices
{
   void Page_Load(Object sender, System.EventArgs e)
   {
      string instanceName = "MyInstanceName";

      //Create the NSInstance object.
      NSInstance myInstance = new NSInstance(instanceName);

      if(!IsPostBack)
      {
         //Create the DeliveryChannelEnumeration object.
         DeliveryChannelEnumeration myDeliveryChannelEnumeration = new
         DeliveryChannelEnumeration(myInstance);

         //Step through the enumeration, populating
         //the drop-down list as you go.
         foreach(DeliveryChannel deliveryChannel in myDeliveryChannelEnumeration)
            {
               if (deliveryChannel.ProtocolName == "SMTP")
               {
                  ddDeliveryChannel.Items.Add(deliveryChannel.DeliveryChannelName);
               }
            }
      }
   }
}
COM Interop Example

The following code example shows how to use a DeliveryChannelEnumeration object in unmanaged code to populate a drop-down list in your subscription management application:

<%

Dim myInstance, myDeliveryChannelEnumeration

const instanceName = "MyInstanceName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the DeliveryChannelEnumeration object.
set myDeliveryChannelEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.DeliveryChannelEnumeration")
myDeliveryChannelEnumeration.Initialize myInstance

'Step through the enumeration, populating
'the drop-down list as you go.
for each deliveryChannel in myDeliveryChannelEnumeration
   if deliveryChannel.ProtocolName = "SMTP" then
      populateSelect = populateSelect & "<OPTION>"
      populateSelect = populateSelect & deliveryChannel.DeliveryChannelName
      populateSelect = populateSelect & "</OPTION>"
   end if
next
%>
<SELECT NAME="Delivery Channels" SIZE="1">
<%=populateSelect%>
</SELECT>

See Also

DeliveryChannel Class

DeliveryChannelEnumeration Class


Managing Subscriptions

The Subscription and SubscriptionEnumeration classes provide a way to enter, update, and delete subscriptions. These classes are provided by the Notification Services API, and can be found in the Microsoft.SqlServer.NotificationServices namespace.

Subscription Class

The Subscription class provides the following properties for the subscription:

Enabled
Indicates whether the subscription is currently enabled to generate notifications. This default value is true.
FieldCount
Returns the number of developer-defined data fields in this subscription record.
HasTimedRule
Returns true if the subscription class that this subscription implements has one or more scheduled subscription rules defined for it.
Item
Gets or sets the value of a data field in the subscription. This property serves as the class indexer in C#.
ScheduleRecurrence
Sets the recurrence information for a scheduled subscription. This property must be used in conjunction with the ScheduleStart property.
ScheduleStart
Sets the start date and time for a scheduled subscription. This property must be used in conjunction with the ScheduleRecurrence property.
SubscriberId
Is the application-defined identifier of the subscriber who receives this subscription.
SubscriptionId
Is generated and used internally by Notification Services to identify this subscription.

The Subscription class represents subscription data, which is usually passed to it by the subscription management application user interface. A Subscription object creates or updates a single subscription record at a time. You must use a Subscription object to update subscription information once it has been entered into Notification Services.

SubscriptionEnumeration Class

The SubscriptionEnumeration class represents the set of subscriptions for a given subscriber in a Notification Services application. You can select a specific subscription record by supplying its subscription ID to the indexer of a SubscriptionEnumeration object.

See Also

Subscription Class

SubscriptionEnumeration Class


Creating a Subscription Object

You must create an object of the Subscription class to add, delete, and update subscription information in a Notification Services application.

Managed Code Example

The following code example shows how to create and initialize the Subscription object, by using the parameterized constructor to pass in the name of the desired Notification Services application and the name of the subscription class that this subscription implements. The Subscription object is usable immediately:

string instanceName = "MyInstanceName";
string applicationName= "MyApplicationName";
string subscriptionClassName= "MySubscriptionClassName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create the Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = new Microsoft.SqlServer.NotificationServices.Subscription(myApplication,
subscriptionClassName);
COM Interop Example

The following code example shows how to create and initialize the Subscription object via COM interop, by using the parameter-less constructor to create the object and then calling the Initialize method to initialize it:

Dim myInstance, myApplication, mySubscription

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const subscriptionClassName = "MySubscriptionClassName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create the Subscription object.
set mySubscription = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscription")
mySubscription.Initialize myApplication, subscriptionClassName

See Also

Subscriber.Initialize Method

Subscription Constructor


Adding a Subscription

The Subscription object exposes properties that allow you to set subscription information such as the subscriber ID, the fields that define the subscription data, and whether the subscription is enabled to generate notifications.

The Add method of this object writes that data to the application database, and returns the system-generated SubscriptionId for the subscription. The SubscriptionId is stored as a 64-bit integer in the database, but is returned to the application as a string.

Note The values for the ScheduleStart and ScheduleRecurrence properties of the Subscription class must conform to the Notification Services subset of the ICalendar interface specification. For more information about constructing valid values for these properties, see Subscription.ScheduleRecurrence Property and Subscription.ScheduleStart Property.

Managed Code Example

The following code example shows how to use the Item method of the Subscription class to set the value of the application-specific subscription fields:

using Microsoft.SqlServer.NotificationServices;
using System.Text;

public class AppSubscriptions
{
   private string AddSubscription(string instanceName, string
   applicationName, string subscriptionClassName, string subscriberId)
   {
      //Create the NSInstance object.
      NSInstance myInstance = new NSInstance(instanceName);

      //Create the NSApplication object.
      NSApplication myApplication = new NSApplication(myInstance, applicationName);

      //Create the Subscription object.
      Subscription mySubscription = new Subscription(myApplication,
      subscriptionClassName);

      //Set the properties that describe the subscription record.
      mySubscription.Enabled = true;
      mySubscription.SubscriberId = subscriberId;

      //Set the subscription data fields (as defined in the ADF),
      //using the indexer to set fields by field name.
      mySubscription["DeviceName"] = txtDeviceName.Text;
      mySubscription["SubscriberLocale"] = ddLocales.SelectedItem.Value;
      mySubscription["StockSymbol"] = txtStockSymbol.Text;
      mySubscription["StockTriggerValue"] = txtStockValue.Text;

      //Set the recurrence of the subscription.
      //This property is only used with scheduled subscriptions.
      //You can provide a list from which the user
      //can choose recurrence frequencies that comply with
      //the subset of the ICalendar specification that is
      //used by Notification Services.
      mySubscription.ScheduleRecurrence = ddRecur.SelectedItem.Value;

      //Set the start date and time of the subscription.
      //This property is used only with scheduled subscriptions.
      //You must provide lists from which the user
      //can choose time zone, date, and time components in order
      //to build a start date/time string that complies with
      //the subset of the ICalendar specification that is
      //used by Notification Services.
      StringBuilder sb = new StringBuilder();
      sb.AppendFormat(
         "TZID={0}:{1}{2}{3}T{4}{5}{6}",
         ddTimeZones.SelectedItem.ToString().Trim(),
         DateTime.Now.Year.ToString("D4"),
         DateTime.Now.Month.ToString("D2"),
         DateTime.Now.Day.ToString("D2"),
         ddHours.SelectedItem.ToString().Trim(),
         ddMinutes.SelectedItem.ToString().Trim(),
         ddSeconds.SelectedItem.ToString().Trim());
      mySubscription.ScheduleStart = sb.ToString();

      //Add the subscription to the database.
      string subscriptionId = mySubscription.Add();
      return subscriptionId;
   }
}
COM Interop Example

The following code example shows how to use the SetFieldValue method of the Subscription class to set the value of the application-specific subscription fields:

Sub AddSubscription(subscriptionClassName, subscriberId)

Dim myInstance, myApplication, mySubscription, subscriptionId

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create the Subscriptionobject.
set mySubscription = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscription")
mySubscription.Initialize myApplication, subscriptionClassName

'Set the properties that describe the subscription record.
mySubscription.SubscriberId = Request.Form("SubscriberId")
mySubscription.Enabled = true

'Set the subscription data fields
'(as defined in the ADF).
mySubscription.SetFieldValue "DeviceName", Request.Form("DeviceName")
mySubscription.SetFieldValue "SubscriberLocale", Request.Form("Locale")
mySubscription.SetFieldValue "StockSymbol", Request.Form("Symbol")
mySubscription.SetFieldValue "StockTriggerValue", Request.Form("Price")

'Set the recurrence of the subscription.
'This property is used only with scheduled subscriptions.
'You must provide a list from which the user
'can choose recurrence frequencies that comply with
'the subset of the ICalendar specification that is
'used by Notification Services.
mySubscription.ScheduleRecurrence = Request.Form("Schedule")

'Set the start date and time of the subscription.
'This property is used only with scheduled subscriptions.
'You must provide lists from which the user
'can choose time zone, date, and time components in order
'to build a start date/time string that complies with
'the subset of the ICalendar specification that is
'used by Notification Services.
start = "TZID" & Request.Form("TimeZones")
start = start & Request.Form("Year")
start = start & Request.Form("Month")
start = start & Request.Form("Day")
start = start & Request.Form("Hours")
start = start & Request.Form("Minutes")
start = start & Request.Form("Seconds")
mySubscription.ScheduleStart = start

'Add the subscription to the database.
subscriptionId = mySubscription.Add

See Also

Subscriber.Add Method

Subscriber.Item Property

Subscriber.SetFieldValue Method


Updating a Subscription

You must use the Update method of the Subscription class to modify existing subscription data in the Notification Services database.

Managed Code Example

The following code example shows how to use the Item method of the Subscription class to set the value of the application-specific subscription fields:

string instanceName = "MyInstanceName";
string applicationName= "MyApplicationName";
string subscriptionClassName= "MySubscriptionClassName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create the Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = new Microsoft.SqlServer.NotificationServices.Subscription(myApplication,
subscriptionClassName);

//Set the subscription ID so that
//the correct record is updated.
mySubscription.SubscriptionId = txtSubscriptionId.Text;

//Update the subscription record.
      mySubscription["DeviceName"] = txtDeviceName.Text;
      mySubscription["SubscriberLocale"] = ddLocales.SelectedItem.Value;
      mySubscription["StockSymbol"] = txtStockSymbol.Text;
mySubscription["StockTriggerValue"] = txtStockValue.Text;
mySubscription.Update();
COM Interop Example

The following code example shows how to use the SetFieldValue method of the Subscription class to set the value of the application-specific subscription fields:

Dim myInstance, myApplication, mySubscription

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const subscriptionClassName = "MySubscriptionClassName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create the Subscription object.
set mySubscription = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscription")
mySubscription.Initialize myApplication, subscriptionClassName

'Set the subscription ID so that
'the correct record is updated.
mySubscription.SubscriptionId = Request.Form("SubscriptionId")

'Update the subscription record.
mySubscription.SetFieldValue "DeviceName", Request.Form("DeviceName")
mySubscription.SetFieldValue "SubscriberLocale", Request.Form("Locale")
mySubscription.SetFieldValue "StockSymbol", Request.Form("Symbol")
mySubscription.SetFieldValue "StockTriggerValue", Request.Form("Price")
mySubscription.Update

See Also

Subscriber.Item Property

Subscriber.SetFieldValue Method

Subscriber.Update Method


Deleting a Subscription

The Delete method of the Subscription class deletes an existing subscription record in the Notification Services database.

Managed Code Example

The following code example shows how to use the Item method of the Subscription class to get the value of the application-specific subscription fields:

using Microsoft.SqlServer.NotificationServices;
public class AppSubscriptions
{
   private void DeleteSubscription(string instanceName, string
   applicationName, string subscriptionClassName, string
   subscriberId, string deleteSymbol)
   {
      //Create the NSInstance object.
      NSInstance myInstance = new NSInstance(instanceName);

      //Create the NSApplication object.
      NSApplication myApplication = new NSApplication(myInstance, applicationName);

      //Create the SubscriptionEnumeration object.
      //This constructor returns the subscriptions for
      //the specified application, subscription class, and subscriber.
      SubscriptionEnumeration mySubEnum = new SubscriptionEnumeration
      (myApplication, subscriptionClassName, subscriberId);

      //Step through the subscriptions, locate the one
      //that should be removed, and delete it.
      foreach(Subscription mySubscription in mySubEnum)
      {
         if ((string)mySubscription["StockSymbol"] == deleteSymbol)
         {
            mySubscription.Delete();
         }
      }
   }
}
COM Interop Example

Tthe following code example shows how to use the GetFieldValue method of the Subscription class to get the value of the application-specific subscription fields:

Dim myInstance, myApplication, mySubscriptionEnumeration

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const subscriptionClassName = "MySubscriptionClassName"

subscriberId = Request.Form("SubscriberId")
deleteSymbol = Request.Form("Remove")

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create the SubscriptionEnumeration object.
'This constructor returns the subscriptions for
'the specified application, subscription class, and subscriber.
set mySubscriptionEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration")
mySubscriptionEnumeration.Initialize myApplication, subscriptionClassName, subscriberId

'Step through the subscriptions, locate the one
'that should be removed, and delete it.
for each subscription in mySubscriptionEnumeration
   if subscription.GetFieldValue("StockSymbol") = deleteSymbol then
      subscription.Delete
   end if
next

See Also

Subscriber.Delete Method

Subscriber.GetFieldValue Method

Subscriber.Item Property


Getting Subscription Field Information

The Subscription class provides the GetFieldName and GetFieldOrdinal methods to give access to subscription field information.

The GetFieldName method of the Subscription class returns the name of a field by providing its ordinal number. The GetFieldOrdinal method of the Subscription class returns the ordinal of a field by providing its name.

Managed Code Example: Getting a Field Name

The following code example shows how to use a Subscription object in managed code to return subscription field name information:

string instanceName = "MyInstanceName";
string applicationName= "MyApplicationName";
string subscriptionClassName= "MySubscriptionClassName";
int ordinal = 2;

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create the Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = new Microsoft.SqlServer.NotificationServices.Subscription(myApplication,
subscriptionClassName);

//Return the name for a field identified by ordinal.
string fieldName = mySubscription.GetFieldName(ordinal);
Managed Code Example: Getting a Field Ordinal

The following code example shows how to use a Subscription object in managed code to return subscription field ordinal information:

string instanceName = "MyInstanceName";
string applicationName= "MyApplicationName";
string subscriptionClassName= "MySubscriptionClassName";
string fieldName = "MySubscriptionFieldName";

//Create the NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create the NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create the Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = new Microsoft.SqlServer.NotificationServices.Subscription(myApplication,
subscriptionClassName);

//Return the ordinal for a field identified by name.
int ordinal = mySubscription.GetFieldOrdinal(fieldName);
COM Interop Example: Getting a Field Name

The following code example shows how to use a Subscription object in unmanaged code to return subscription field name information:

Dim myInstance, myApplication, mySubscription, ordinal, fieldName

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const subscriptionClassName = "MySubscriptionClassName"

ordinal = 2

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create the Subscription object.
set mySubscription = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscription")
mySubscription.Initialize nsApplication, subscriptionClassName

'Get the name for a field identified by ordinal.
fieldName = mySubscription.GetFieldName(ordinal)
Wcript.Echo "Subscription Field ", fieldName
COM Interop Example: Getting a Field Ordinal

The following code example shows how to use a Subscription object in unmanaged code to return subscription field ordinal information:

Dim myInstance, myApplication, mySubscription, ordinal, fieldName

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const subscriptionClassName = "MySubscriptionClassName"

fieldName = "MySubscriptionFieldName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create the Subscription object.
set mySubscription = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscription")
mySubscription.Initialize nsApplication, subscriptionClassName

'Get the name for a field identified by ordinal.
ordinal = mySubscription.GetFieldOrdinal(fieldName)
Wcript.Echo "Subscription Ordinal ", ordinal

See Also

Subscriber.GetFieldName Method

Subscriber.GetFieldOrdinal Method


Populating a Subscriber Locale List

You can provide a drop-down list of subscriber locales in your application user interface, so that users can select valid subscriber locales for their subscriptions. You are not required to include subscriber locale information in the subscription record, and can collect it from another source. However, providing it as part of the subscription information is common.

The SubscriberLocale and SubscriberLocaleEnumeration classes can be used to provide this information.

Managed Code Example

The following code example shows how to use a SubscriberLocaleEnumeration object in managed code to populate a drop-down list in your subscription management application:

using Microsoft.SqlServer.NotificationServices;
public class AppSubscribers
{
   void Page_Load(Object sender, System.EventArgs e)
   {
      string instanceName = "MyInstanceName";

      //Create the NSInstance object.
      NSInstance myInstance = new NSInstance(instanceName);

      if(!IsPostBack)
      {
         //Create the SubscriberLocaleEnumeration object.
         SubscriberLocaleEnumeration mySubscriberLocaleEnumeration = new
         SubscriberLocaleEnumeration(myInstance);

         //Step through the enumeration, populating
         //the drop-down list as you go.
         foreach(SubscriberLocale subscriberLocale in mySubscriberLocaleEnumeration)
            {
               ddSubscriberLocale.Items.Add(subscriberLocale.Locale);
            }
      }
   }
}
COM Interop Example

The following code example shows how to use a SubscriberLocaleEnumeration object in unmanaged code to populate a drop-down list in your subscription management application:

<%
Dim myInstance, mySubscriberLocaleEnumeration

const instanceName = "MyInstanceName"

'Create the NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create the SubscriptionLocaleEnumeration object.
set mySubscriberLocaleEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriberLocaleEnumeration")
mySubscriberLocaleEnumeration.Initialize myInstance

'Step through the enumeration, populating
'the drop-down list as you go.
for each subscriberLocale in mySubscriberLocaleEnumeration
   populateSelect = populateSelect & "<OPTION>"
   populateSelect = populateSelect & subscriberLocale.Locale
   populateSelect = populateSelect & "</OPTION>"
next
%>
<SELECT NAME="Locales" SIZE="1">
<%=populateSelect%>
</SELECT>

See Also

SubscriberLocale Class

SubscriberLocaleEnumeration Class


Populating a Time Zone List

You can provide a drop-down list of time zones in your application user interface, so that users can select valid time zones for the schedule information of their scheduled subscriptions.

The TimeZone and TimeZoneEnumeration classes can be used to provide this information.

Managed Code Example

The following code example shows how to use a TimeZoneEnumeration object in managed code to populate a drop-down list in your subscription management application:

using Microsoft.SqlServer.NotificationServices;
public class AppSubscribers
{
   void Page_Load(Object sender, System.EventArgs e)
   {
      string instanceName = "MyInstanceName";
      string language = "en";

      //Create the NSInstance object.
      NSInstance myInstance = new NSInstance(instanceName);

      if(!IsPostBack)
      {
         //Create the TimeZoneEnumeration.
         TimeZoneEnumeration myTimeZoneEnumeration = new TimeZoneEnumeration(myInstance,
         language);

         //Step through the enumeration, populating
         //the drop-down list as you go. Note that the TimeZone
         //reference must include the namespace, because there is
         //an identically named class in the System namespace.
         foreach(Microsoft.SqlServer.NotificationServices.TimeZone
         timeZone in myTimeZoneEnumeration)
            {
               ddTimeZone.Items.Add(timeZone.TimeZoneName);
            }
      }
   }
}
COM Interop Example

The following code example shows how to use a TimeZoneEnumeration object in unmanaged code to populate a drop-down list in your subscription management application:

<%
Dim myInstance, myTimeZoneEnumeration

const instanceName = "MyInstanceName"

set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

set myTimeZoneEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.timeZoneEnumeration")
myTimeZoneEnumeration.Initialize myInstance

for each timeZone in myTimeZoneEnumeration
   if timeZone.TimeZoneId >=2 and timeZone.TimeZoneId <=40 then
      populateSelect = populateSelect & "<OPTION>"
      populateSelect = populateSelect & timeZone.TimeZoneName
      populateSelect = populateSelect & "</OPTION>"
   end if
next
%>
<SELECT NAME="Time Zones" SIZE="1">
<%=populateSelect%>
</SELECT>

See Also

TimeZone Class

TimeZoneEnumeration Class


Developing Custom Notification Services Components

You can create a complete notification application using Notification Services standard components. However, Notification Services also provides APIs for developing custom versions of these components, so that you can tailor them to your requirements. You can create custom event providers and content formatters for use within your notification applications, and custom delivery protocols for use within your Notification Services instances.

Note For added security, you can use the Caspol.exe utility provided by Microsoft Visual Studio® .NET in order to set appropriate code access permissions on the assemblies containing event providers, content formatters, and delivery protocols. Notification Services assemblies require the FullTrust permission set. You must determine the appropriate permissions for any custom assemblies you create or purchase.

The topics that this section covers are described in the following table.

Developing a Custom Event Provider | Discusses how to use Notification Services–provided classes, interfaces, and stored procedures to create custom event providers.
Developing a Custom Content Formatter | Discusses how to use Notification Services–provided classes and interfaces to create custom content formatters.
Developing a Custom Delivery Protocol | Discusses how to use Notification Services–provided classes and interfaces to create custom delivery protocols.
Debugging a Custom Component | Discusses how to debug a custom component that is hosted by Notification Services.


Developing a Custom Event Provider

Notification Services provides two standard event providers to assist you in rapid application development. However, you might want to gather event data from data sources that the standard event providers are not designed to monitor, or you might need to tailor the event data to meet particular application requirements. If this is the case, you must develop a custom event provider.

Custom event providers can be hosted or independent. Hosted event providers are run by the Notification Services provider host component. Hosted event providers are easier to develop, because some of their processes (like loading and scheduling) can be handled by Notification Services. Hosted event providers can also be enabled and disabled like other Notification Services components.

Independent event providers operate outside of the Notification Services system. Independent event providers are useful if you have existing infrastructure that you want to use to submit events.

There are three possible ways that a custom event provider can submit event information to a Notification Services application:

  • Using data from an XML source: You create an EventLoader object to write one or more events from an XML data source to the application database.
  • Using data from SQL Server tables: You use predefined event collection stored procedures to write one or more events from a SQL Server data source to the application database. One set of these stored procedures is created for each event class that is defined. This method is also useful when you can take advantage of business logic that is defined within SQL Server stored procedures.
  • Using any other data sources: You create an Event object for each event, and then use an EventCollector object to collect one or more events into a batch and submit it to the application database.

You must document the event provider information in the application definition file (ADF).

When implementing a custom event provider, you must use one of the event collection APIs to submit events to the system. The Event, EventCollector, and EventLoader classes are available in the Microsoft.SqlServer.NotificationServices namespace. The event collection stored procedures are available in the application database.

All the event submission methods support a similar model of event submission. Events are submitted to the database in batches. They become visible to the application only when the event batch is committed, which is a step in the event submission process.

You implement your custom event provider as a class in either a managed or an unmanaged component. The component can reside anywhere. You must document the full path to the event provider assembly or DLL file in the ADF. You can include the business logic within the coded component, or by calling Transact-SQL stored procedures.


Independent Event Providers

Independent event providers operate externally to the Notification Services system, interacting with it only to provide event data. They do not implement the IEventProvider or IScheduledEventProvider interfaces that are provided by Notification Services.

An independent event provider can be hosted by a different service, such as Internet Information Services (IIS). As an example, a Microsoft ASP.NET page can act as an independent event provider. Every time a user fills out a form from an ASP.NET page and submits it, one or more new events can be generated, based on the contents of the form.

Although they are not hosted by Notification Services, independent event providers must still use one of the Notification Services event collection APIs to write events to the application database.

Accessing Notification Services with an Independent Event Provider

An independent event provider must be able to identify the Notification Services instance and application to which it provides data. As the developer of the event provider, you are responsible for establishing the relationship between your custom independent event provider and the correct Notification Services instance and application. There are two ways to do this:

  • Using the InstanceEnumeration and ApplicationEnumeration classes that are included in the Notification Services API to programmatically select the appropriate instance and application names at run time. For more information about using an InstanceEnumeration object, see Notification Services Instance Classes. For more information about using an ApplicationEnumeration object, see Notification Services Application Classes. Microsoft recommends this approach if your application accesses more than one Notification Services application.
  • Providing the instance and application names as initialization parameters to the independent event provider. Microsoft recommends this approach if your application accesses only one Notification Services application.

However they are determined, the instance and application names are necessary in order to use any of the event collection APIs.


Hosted Event Providers

Hosted event providers rely on the provider host component of the Notification Services engine to initialize, run, and terminate them. There are two kinds of hosted event providers:

  • Scheduled event providers, which are invoked by the provider host on a predefined schedule and submit events during the scheduled intervals.
  • Continuous event providers, which are invoked by the provider host once when the application starts, and then run continuously and submit events as they come in.

For details about how these models differ, see Event Collection Models.

Your hosted event provider must implement either the IEventProvider interface or the IScheduledEventProvider interface. These interfaces are accessible in the Microsoft.SqlServer.NotificationServices namespace.

The IEventProvider and IScheduledEventProvider interfaces are identical in their public members. However, Notification Services explicitly distinguishes between the two, based on the way they are invoked by the provider host.

A scheduled event provider must implement the IScheduledEventProvider interface, and must have an associated schedule and optionally a start time defined in the application definition file (ADF). An exception is thrown if a schedule is not provided for an event provider that implements the IScheduledEventProvider interface.

A continuous event provider must implement the IEventProvider interface, and must not have a schedule or start time defined in the ADF. An exception is thrown if a schedule is defined for an event provider that implements the IEventProvider interface.


Using the IEventProvider and IScheduledEventProvider Interfaces

The IEventProvider and IScheduledEventProvider interfaces provide the following methods:

  • Initialize allows the provider host to inform the event provider to initialize itself prior to running.
  • Run allows the provider host to ask the event provider to start collecting events.
  • Terminate allows the provider host to ask the event provider to stop collecting events, and release any resources it is holding.

To create a custom hosted event provider, you must create a class that implements IEventProvider or IScheduledEventProvider, and then implement the methods inherited from the interface within this class. Finally you code the functionality for these methods that is appropriate for your application.

The provider host calls Initialize when the system starts. This method passes required parameters to the event provider so that it can prepare to start running. The provider host calls the Terminate method for the provider if the Initialize call doesn't return within five minutes.

For a continuous event provider, the provider host calls Run after the call to Initialize returns successfully. For a scheduled event provider, the provider host calls Run on every scheduled interval after the call to Initialize returns successfully. The event provider must return from the Run method immediately. If collecting and submitting events is likely to take the event provider more than a couple of minutes, you must program the event provider to gather and submit events on a separate thread. This is more likely to be the case when using a continuous event provider. If you choose to have multiple threads running in parallel, and if event order is important to your application, make sure to synchronize the threads so that they submit events to the database in the same order in which they were created. The provider host calls the Terminate method and stops the event provider if the event provider does not return from the Run call within five minutes.

Note When using a scheduled event provider to poll a data source for new information, Microsoft recommends that you persist "watermark" information that can be used to determine what event data is new. For instance, you might want to save the date and time of the last event batch submission in a database. That way, you will have the data available to refer to in case of system outages for which you must restart the event provider.

The provider host calls the Terminate method to tell the event provider to stop collecting events. This happens if the service is stopping, if the provider appears to be not responding (for example, if it doesn't return from the Run or Initialize calls within the specified time-out), or if the provider requests to be stopped.

Example: Event Provider

In the following code example, the event provider reads a log file and creates events for any entries with the type Error:

using System;
using System.Collections.Specialized;
using Microsoft.SqlServer.NotificationServices;
using System.Diagnostics;

namespace EventProviderNamespace
{
   public class MyEventProvider : IScheduledEventProvider
   {
      NSApplication myApplication;
      EventCollector myEventCollector;
      string eventProviderName;
      StringDictionary arguments;
      string logName;
      DateTime eventDate;
      string eventClassName;

      public MyEventProvider()
      {
         //Add constructor logic here if required.
      }

      //Implement the IScheduledEventProvider.Initialize method.
      public void Initialize(
         NSApplication application,
         string providerName,
         StringDictionary args,
         StopHandler stopDelegate )
      {
         this.eventProviderName = providerName;
         this.arguments = args;
         this.myApplication = application;

         //This event provider requires three arguments:
         //the event log to check, the date used
         //to filter the events returned, and the
         //name of the event class.
         if (3 == arguments.Count)
         {
            this.logName = arguments["logName"];
            this.eventDate = System.Convert.ToDateTime(arguments["eventDate"]);
            this.eventClassName = arguments["eventClass"];
         }

         //Add code to validate the values
         //of the arguments here.

         //Create the event collector.
         this.myEventCollector = new EventCollector(myApplication, eventProviderName);
      }

      //Implement the IScheduledEventProvider.Run method.
      public bool Run()
      {
         bool returnValue = true;

         try
         {
            //Open the event log & review the latest entries.
            EventLog myLog = new EventLog();
            myLog.Log = logName;
            Event myEvent = new Event();
            myEvent.Initialize(myApplication, eventClassName);
            foreach(EventLogEntry entry in myLog.Entries)
            {
               if(entry.TimeWritten >= eventDate)
                  if(entry.EntryType == EventLogEntryType.Error)
                  {
                     //Create an event to convey the event log data.
                     myEvent["LogName"] = logName;
                     myEvent["Message"] = entry.Message;
                     myEvent["Source"] = entry.Source;
                     myEventCollector.Write(myEvent);
                  }
            }

            //Commit the event batch.
            int eventsSubmitted = myEventCollector.Commit();
            myEvent = null;
         }
         catch (Exception e)
         {
            //Provide error handling here.
         }
         return returnValue;
      }

      //Implement the IScheduledEventProvider.Terminate method.
      public void Terminate()
      {
         myEventCollector.Dispose();
      }
   }
}

See Also

IEventProvider Interface

IScheduledEventProvider Interface


Implementing the Initialize Method

The Initialize method requires four arguments:

application
A reference to an NSApplication object that represents the application to which this event provider writes event data. For more information, see NSApplication Class.
providerName
A string specifying the event provider name, as specified in the /Providers/HostedProvider/ProviderName section of the application definition file (ADF).
args
A reference to a StringDictionary object containing the argument names and values for this event provider. The argument information is retrieved from the /Providers/HostedProvider/Arguments section of the ADF.
stopDelegate
A reference to a StopHandler delegate, which can be used by the event provider to contact the provider host and request termination. This delegate is supplied as part of the Notification Services API.

The Initialize method does not have a return value.

The Initialize method has a five-minute time-out window. If initialization has not completed within that time, an event is logged and the event provider's Terminate method is called.

You use the values provided in the args argument to set class variables and prepare the event provider to run. This often involves setting information about the event source that the event provider monitors, and the event class that defines the events that the event provider creates.

The Initialize method is called when the provider host starts running. The event provider performs initialization and returns as soon as initialization is complete. The provider host always calls Initialize before calling the Run or Terminate method.

Example: Initialize
//Implement the IScheduledEventProvider.Initialize method.
public void Initialize(
   Microsoft.SqlServer.NotificationServices.NSApplication application,
   string providerName,
   System.Collections.Specialized.StringDictionary args,
   Microsoft.SqlServer.NotificationServices.StopHandler stopDelegate)
{
   this.eventProviderName = providerName;
   this.arguments = args;
   this.myApplication = application;

   //This event provider requires three arguments:
   //the event log to check, the date used
   //to filter the events returned, and the
   //name of the event class.
   if (3 == arguments.Count)
   {
      this.logName = arguments["logName"];
      this.eventDate = System.Convert.ToDateTime(arguments["eventDate"]);
      this.eventClassName = arguments["eventClass"];
   }

   //Validate the values of the arguments here.

   //Create the event collector.
   this.myEventCollector = new Microsoft.SqlServer.NotificationServices.EventCollector(myApplication, eventProviderName);
}

To refer to the full code for the event provider, look at the example in Using the IEventProvider and IScheduledEventProvider Interfaces.

For more information, see IEventProvider.Initialize Method or IScheduledEventProvider.Initialize Method.


Implementing the Run Method

The Run method does not require any arguments. It returns a Boolean value that indicates whether the provider is running successfully (true) or whether the provider host must call its Terminate method (false).

The Run method has a five-minute time-out window. If it does not return within that time period, an event is logged and the event provider's Terminate method is called.

Hosted event providers are expected to catch and handle their own exceptions. If the exceptions are not handled, the provider host logs the unhandled error, and then invokes the Terminate method on the event provider.

Implementing the Run Method in Continuous Event Providers

Continuous event providers are started when the notification application is started, and they run continuously while the application is active. When the system administrator starts the application, the provider host calls the Initialize and Run methods on the continuous event provider just once. The Run method must return within the five-minute time-out period. Once started, a continuous event provider runs and submits events until its Terminate method is called.

An event provider must return false from the Run method to let the provider host know something is wrong and that it is not going to continue to run. A scheduled event provider gets this opportunity at each interval. However, a non-scheduled event provider gets invoked only once and therefore it has no way to notify the provider host that something has gone wrong. In this situation you can use the StopHandler delegate. This is passed to the event provider as an argument to the Initialize method, so that the event provider can invoke it if it needs to be terminated.

Implementing the Run Method in Scheduled Event Providers

Scheduled event providers are initialized once and are then called on a periodic basis. You control the frequency with which the event provider is called by specifying a schedule in the /Providers/HostedProvider/Schedule section of the application definition file (ADF). When the system administrator starts the notification application, the provider host calls the Initialize method on the scheduled event provider. The provider host reads the schedule information for this event provider, and then calls the event provider's Run method as indicated by the schedule.

All event providers can collect and submit events from within the Run method. However, a scheduled event provider must return from the Run call before the next scheduled interval. If the event provider has not returned when the next scheduled interval arrives, the provider host waits until the next interval to call Run again.

To avoid missing calls, a scheduled event provider must always return from the Run method call on time. Make sure that you set the schedule of the event provider so that it can complete its tasks and return in a timely fashion.

Example: Run
//Implement the IScheduledEventProvider.Run method.
public bool Run()
{
   bool returnValue = true;

   try
   {
      //Open the event log and review the latest entries.
      System.Diagnostics.EventLog myLog = new System.Diagnostics.EventLog();
      myLog.Log = logName;
      Microsoft.SqlServer.NotificationServices.Event myEvent = new Microsoft.SqlServer.NotificationServices.Event();
      myEvent.Initialize(myApplication, eventClassName);
      foreach(System.Diagnostics.EventLogEntry entry in myLog.Entries)
      {
         if(entry.TimeWritten >= eventDate)
            if(entry.EntryType == System.Diagnostics.EventLogEntryType.Error)
            {
               //Create an event to convey the event log data.
               myEvent["LogName"] = logName;
               myEvent["Message"] = entry.Message;
               myEvent["Source"] = entry.Source;
               myEventCollector.Write(myEvent);
            }
         }

      //Commit the event batch.
      int eventsSubmitted = myEventCollector.Commit();
      myEvent = null;
   }
   catch (System.Exception e)
   {
      //Provide error handling here.
   }
   return returnValue;
}

To refer to the full code for the event provider, look at the example in Using the IEventProvider and IScheduledEventProvider Interfaces.

For more information, see IEventProvider.Run Method or IScheduledEventProvider.Run Method.


Implementing the Terminate Method

The Terminate method does not require any arguments, and does not have a return value.

When the provider host calls the Terminate method, the event provider must stop collecting new events, write any pending events to the application database, release any resources it is holding, and return from the Terminate method call. If the event provider does not return from the Terminate method call within one minute, the provider host stops the event provider unconditionally.

If the Terminate method fails to handle an exception, the provider host logs the unhandled error, and the event provider is terminated.

Example: Terminate
//Implement the IScheduledEventProvider.Terminate method.
public void Terminate()
{
   myEventCollector.Dispose();
}

To refer to the full code for the event provider, look at the example in Using the IEventProvider and IScheduledEventProvider Interfaces.

For more information, see IEventProvider.Terminate Method or IScheduledEventProvider.Terminate Method.


Implementing an Event Provider Using the Event and EventCollector Classes

You can use the Event and EventCollector classes in an event provider when working with any event source that can provide events as individual units. These classes can be found in the Microsoft.SqlServer.NotificationServices namespace.

You use an object of the Event class to encapsulate the data for a single event. Which data fields are provided by the Event object depends on the schema of the event class that is used to initialize the Event object.

The Event class provides properties to set the following values for an event:

FieldCount
Returns the number of data fields in the event record.
Item
Gets or sets the value of a data field for an event. This property serves as the indexer in C#.

Once you have created an Event object and populated it with event data, you submit it to an EventCollector object, using the EventCollector.Write method. You create, populate, and submit one Event object for each event record that you want to create. You can reuse the Event object after each call to EventCollector.Write. The EventCollector object gathers the events written to it into a batch, and then adds the event batch to the application database when you call the EventCollector.Commit method. Following a Commit call, the EventCollector object is cleared and ready to create a new event batch.

The EventCollector object also provides an Abort method. Call this method if you want to discard the current event batch.

See Also

Event Class

EventCollector Class


Creating an Event Object

You can create and initialize the Event object by using the parameterized constructor to pass in an NSApplication object that represents the desired Notification Services application, and the name of the event class that defines the events that are to be created. The Event object is usable at once.

Example
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";

//Get the Notification Services instance.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Get the Notification Services application.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create the Event object.
Microsoft.SqlServer.NotificationServices.Event myEvent = new Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName);

See Also

Event Class


Creating a Disconnected Event Object

It is possible to create an Event object without calling its Initialize method. Doing this allows you to create a "disconnected" Event object that does not have a reference to a Notification Services application, and is not on the same system as any running NS$instance_name service. This technique can be useful for such things as serializing an arbitrary event in a Message Queueing message (also known as an MSMQ message). In order to use this technique, you must know the event class name and the event field names at development time.

Example
//Initialize the Event object.
Event myEvent = new Event();
myEvent.EventClassName = "StockEvents";

myEvent.FieldNames.Add("StockSymbol");
myEvent.FieldValues.Add(String.Empty);

myEvent.FieldNames.Add("StockPrice");
myEvent.FieldValues.Add(String.Empty);

//Use the Event object.
myEvent["StockSymbol"] = "AWKS";
myEvent["StockPrice"] = "58.35";

//Add code to send the Event object.


Creating an EventCollector Object

You can create and initialize the EventCollector object by using the parameterized constructor to pass in an NSApplication object that represents the desired Notification Services application, and the name of the event provider that hosts the EventCollector. The EventCollector object is usable at once.

Example
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";

//Get the Notification Services instance.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Get the Notification Services application.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create the EventCollector object.
Microsoft.SqlServer.NotificationServices.EventCollector myEventCollector = new Microsoft.SqlServer.NotificationServices.EventCollector(myApplication, eventClassName);

See Also

EventCollector Class


Using Event and EventCollector Objects to Add Events

Once your Event and EventCollector objects are created, you use them to capture event data, collect it into batches, and write it to the application database.

You use the Write method of EventCollector to add event records to a batch, and then the Commit method of EventCollector to submit the event batch to the Notification Service system. An event batch can consist of one or more event records; you must determine the event batch size for your application, by calling the Commit method of the EventCollector when appropriate.

In a hosted event provider, the Write and Commit methods are called in the Run method, or in a custom method called by the Run method.

If you need to discard an event batch due to an error, you use the EventCollector.Abort method. This method is called in a catch block in the Run method, or in a custom method called by the Run method.

Example

In this managed code example, the Item method of the Event class is used to set the value of the developer-defined event fields. In unmanaged (native) code, this would be done using the Event.SetFieldValue method:

public bool Run()
{
   //These variables would normally be defined for
   //the class. They would be set based on the values
   //provided by the args argument of the Initialize method.
   string instanceName = "MyInstanceName";
   string applicationName = "MyApplicationName";
   string eventClassName = "MyEventClassName";

   bool returnValue = true;

   try
   {
      //Get the Notification Services instance.
      Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

      //Get the Notification Services application.
      Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

      //Create the Event object.
      Microsoft.SqlServer.NotificationServices.Event myEvent = new Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName);

      //Create the EventCollector object.
      Microsoft.SqlServer.NotificationServices.EventCollector myEventCollector = new Microsoft.SqlServer.NotificationServices.EventCollector(myApplication, eventClassName);

      //Create and initialize a proxy class for a weather Web service.
      MyWeatherService.Method weatherMethod = new MyWeatherService.Method();

      //Create an array for the areas for which you want forecasts.
      string[] areas = {"Bellevue", "Issaquah", "Redmond", "Seattle"};

      //Step through the array and select event information.
      for(int i = 0; i < areas.Length; i++)
      {
         //Set the event fields in the MyEvent object.
         myEvent["Area"] = areas[i];
         myEvent["Forecast"] = weatherMethod.Forecast(areas[i]);

         //Write the event to the EventCollector.
         myEventCollector.Write(myEvent);
      }

      //Submit the event batch to the
      //Notification Services application database.
      int eventsSubmitted = myEventCollector.Commit();
      myEvent = null;
   }
   catch(System.Exception e)
   {
      //Handle errors by using myEventCollector.Abort() to
      //discard the current event batch if necessary.
   }
   return returnValue;
}

See Also

Event Class

EventCollector Class


Getting Event Field Information

The Event class provides the GetFieldName and GetFieldOrdinal methods to give access to event field information.

You use the GetFieldName method of the Event class to return the name of a field by providing its ordinal.

You use the GetFieldOrdinal method of the Event class to return the ordinal of a field by providing its name.

Example: Getting a Field Name
//Return the name for a field identified by ordinal.
int ordinal = 2;
string fieldName = myEvent.GetFieldName(ordinal);
Example: Getting a Field Ordinal
//Return the ordinal for a field identified by name.
string fieldName = "StockSymbol";
int ordinal = myEvent.GetFieldOrdinal(fieldName);

See Also

Event Class


Using the EventLoader Class

You can use the EventLoader class when working with an XML document or stream object to create one or more event records.

You use the EventLoader.LoadXML method to write the events provided by an XML data source into the Notification Services application database as an event batch.

The EventLoader class has an EventSchema property. This property is used to set the name of the SQL-annotated XML schema file that maps the data from the XML document structure to the event class structure.

For more information about authoring an SQL-annotated XML schema file, see Authoring and Using Custom Schemas Backgrounder in the Microsoft MSDN® Library.

See Also

EventLoader Class


Creating an EventLoader Object

You can create and initialize the EventLoader object by using the parameterized constructor to pass in an NSApplication object that represents the desired Notification Services application, the name of the event provider that is to host the EventLoader, the name of the event class that defines the events that are to be created, and the name of the SQL-annotated XML schema file that maps the data from the XML document structure to the event class structure. The EventLoader object is usable at once.

Example
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";
string eventProviderName = "MyEventProviderName";
string eventSchema = "MyEventSchemaPathAndName";

//Get the Notification Services instance.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Get the Notification Services application.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create the EventLoader object.
Microsoft.SqlServer.NotificationServices.EventLoader myEventLoader = new Microsoft.SqlServer.NotificationServices.EventLoader(myApplication, eventProviderName, eventClassName, eventSchema);

See Also

EventLoader Class


Using an EventLoader Object to Add Events

Once your EventLoader object is created, you can use it to write an event batch of one or more records from an XML data source to the Notification Services application database. You use the LoadXml method to accomplish this.

Example
public bool Run()
{
   //These variables would normally be defined for
   //the class. They would be set based on the values
   //provided by the args argument of the Initialize method.
   string instanceName = "MyInstanceName";
   string applicationName = "MyApplicationName";
   string eventClassName = "MyEventClassName";
   string eventProviderName = "MyEventProviderName";
   string eventSchema = "MyEventSchemaPathAndName";
   string xmlDoc = "MyXMLDocPathAndName";

   bool returnValue = true;
   System.DateTime dt = System.DateTime.Now;

   try
   {
      //Get the Notification Services instance.
      Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

      //Get the Notification Services application.
      Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance,       applicationName);

      //Create the EventLoader object.
      Microsoft.SqlServer.NotificationServices.EventLoader myEventLoader = new Microsoft.SqlServer.NotificationServices.EventLoader(myApplication,    eventProviderName, eventClassName, eventSchema);

      //Write the event records from the XML data
      //source to the application database.
      int eventsSubmitted = myEventLoader.LoadXml(xmlDoc);
   }
   catch(System.Exception e)
   {
      //Add code to handle errors here.
   }
   return returnValue;
}

See Also

EventLoader Class


Using the Event Collection Stored Procedures

You can use the standard event collection stored procedures when working with a SQL Server event source, or when you want to take advantage of business logic that you can have already defined in other SQL Server stored procedures.

One set of standard event collection stored procedures is automatically generated for each event class that you create. These stored procedures allow an event provider to submit events directly to the event table from a SQL Server–based event source. The event collection stored procedures reside in the application database. The name of the stored procedure is a concatenation of the stored procedure name and the name of the event class to which it belongs.

The standard event collection stored procedures are as follows:

  • NSEventBeginBatchEventClassName provides the event batch ID to be used for the events that are being created. It takes the name of the event provider that is submitting the event data as an input parameter, and returns the batch ID of the new event batch.
  • NSEventWriteEventClassName inserts a single event record into the event table. It takes the event batch ID to which this event belongs as an input parameter, as well as a list of values for the event data fields. It does not have a return value.
  • NSEventFlushBatchEventClassName either commits or discards the event batch. It takes the event batch ID of the event batch that it acts on as an input parameter, as well as a flag to indicate whether to discard or to commit the batch. It does not have a return value.
  • NSEventSubmitBatchEventClassName encapsulates the functionality of the three previously described stored procedures. It first creates a new event batch by calling NSEventBeginBatchEventClassName. Then it associates one or more event records with the new event batch, and writes them to the event table. NSEventSubmitBatchEventClassName does not use the NSEventWriteEventClassName stored procedure to do this, because that procedure is designed to submit a single event record. It instead provides similar functionality for one or more event records, by executing the query you provide to select a set of rows and submit them as events. Finally, NSEventSubmitBatchEventClassName commits the event batch by calling NSEventFlushBatchEventClassName.

    NSEventSubmitBatchEventClassName takes the following input parameters:

    • The name of the event provider that is submitting the events.
    • The text of the Transact-SQL query that is to be used to select the records that are to be submitted as events. The schema of the records generated by the query must match the schema of the event table to which they are being submitted.
    • The text of the Transact-SQL query that is to be used to do any post-processing cleanup or state maintenance, like updating tables or deleting any temporary objects.

Use the NSEventBeginBatchEventClassName, NSEventFlushBatchEventClassName, and NSEventWriteEventClassName stored procedures in combination to write single events to the application database. Use the NSEventSubmitBatchEventClassName stored procedure to write multiple events to the application database.

See Also

NSEventBeginBatch<EventClassName>

NSEventFlushBatch<EventClassName>

NSEventSubmitBatch<EventClassName>

NSEventWrite<EventClassName>


Using the Event Collection Stored Procedures to Add Events

You can run the event collection stored procedures from within both managed and unmanaged code, using any appropriate mechanism available in the language with which you are working.

A common way to execute a stored procedure from within managed code is to use a SqlCommand object. You can specify a stored procedure and its arguments in the SqlCommand object, and then execute the procedure using its ExecuteNonQuery method.

Example: Adding a Single Event
public bool Run()
{
   //These variables would normally be defined for
   //the class. They would be set based on the values
   //provided by the args argument of the Initialize method.
   string instanceName = "MyInstanceName";
   string applicationName = "MyApplicationName";
   string eventClassName = "MyEventClassName";
   string eventProviderName = "MyEventProviderName";

   bool returnValue = true;
   System.Data.SqlClient.SqlConnection conn = null;

   try
   {
      //Set the connection to SQL Server.
      conn = new System.Data.SqlClient.SqlConnection();
      conn.ConnectionString = string.Format("Integrated Security=SSPI; Data Source=MySQLServer;Initial Catalog=MyApplicationDatabaseName");
      conn.Open();

      //Use NSEventBeginBatchEventClassName
      //to create a new event batch and return the ID.
      System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(string.Format("\"NSEventBeginBatch{0}\"", eventClassName));
      cmd.Connection = conn;
      cmd.CommandType = System.Data.CommandType.StoredProcedure;
      cmd.Parameters.Add("@ProviderName", eventProviderName);
      System.Data.SqlClient.SqlParameter param = cmd.Parameters.Add("@EventBatchId", System.Data.SqlDbType.BigInt);
      param.Direction = System.Data.ParameterDirection.Output;
      cmd.ExecuteNonQuery();
      long eventBatchId = (long)cmd.Parameters["@EventBatchId"].Value;

      //Use NSEventWriteEventClassName
      //to write the event to the database.
      cmd.Parameters.Clear();
      cmd.CommandText = string.Format("\"NSEventWrite{0}\"", eventClassName);
      cmd.Parameters.Add("@EventBatchId", eventBatchId);
      cmd.Parameters.Add("@City", "Redmond");
      cmd.Parameters.Add("@Date", "3/12/02");
      cmd.Parameters.Add("@Low", 50.0);
      cmd.Parameters.Add("@High", 55.5);
      cmd.Parameters.Add("@Forecast", "Partly cloudy");
      cmd.ExecuteNonQuery();

      //Use NSEventFlushBatchEventClassName
      //to commit the event batch.
      cmd.Parameters.Clear();
      cmd.CommandText = string.Format("\"NSEventFlushBatch{0}\"", eventClassName);
      cmd.Parameters.Add("@EventBatchId", eventBatchId);
      long eventsSubmitted = (long)cmd.ExecuteScalar();
   }
   catch(System.Data.SqlClient.SqlException ex)
   {
      //Add code to handle the exception here.
   }
   finally
   {
      if (null != conn)
      {
      conn.Close();
      conn = null;
      }
   }
   return true;
}
Example: Adding Multiple Events
public bool Run()
{
   //These variables would normally be defined for
   //the class. They would be set based on the values
   //provided by the args argument of the Initialize method.
   string instanceName = "MyInstanceName";
   string applicationName = "MyApplicationName";
   string eventClassName = "MyEventClassName";
   string eventProviderName = "MyEventProviderName";
   string eventsQuery = Transact-SQL statement to return records to be used as events;
   string postQuery = Transact-SQL statement to do any post-processing cleanup;

   bool returnValue = true;
   System.Data.SqlClient.SqlConnection conn = null;

   try
   {
      //Set the connection to SQL Server.
      conn = new System.Data.SqlClient.SqlConnection();
      conn.ConnectionString = string.Format("Integrated Security=SSPI; Data Source=MySQLServer;Initial Catalog=MyApplicationDatabaseName");
      conn.Open();

      //Use NSEventSubmitBatchEventClassName
      //to create and submit a batch of events.
      System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(string.Format("\"NSEventSubmitBatch{0}\"", eventClassName));
      cmd.Connection = conn;
      cmd.CommandType = System.Data.CommandType.StoredProcedure;
      cmd.Parameters.Add("@ProviderName", eventProviderName);
      cmd.Parameters.Add("@EventsQuery", eventsQuery);
      cmd.Parameters.Add("@PostQuery", postQuery);
      long eventsInBatch = (long)cmd.ExecuteScalar();
   }
   catch(System.Data.SqlClient.SqlException ex)
   {
      //Add code to handle the exception here.
   }
   finally
   {
      if (null != conn)
      {
         conn.Close();
         conn = null;
      }
   }
return true;
}


Developing a Custom Content Formatter

Notification Services provides a standard XSLT content formatter to assist you in rapid application development. However, you might want to format your notification data to meet particular application requirements in a way that is not provided by this content formatter. If this is the case, you must develop a custom content formatter.

You must implement the IContentFormatter interface that is provided by Notification Services within your custom content formatter, in order for it to interoperate with the Notification Services distributor. The IContentFormatter interface is available in the Microsoft.SqlServer.NotificationServices namespace.

Each notification class has information specified about the content formatter it uses in the /NotificationClasses/NotificationClass/ContentFormatter section of the application definition file (ADF). If you create a custom content formatter, you must declare it and specify the values for any arguments that it requires in each notification class that uses it.

Your custom content formatter must be implemented as a class in a managed code assembly. This assembly can reside anywhere, with the full path to the assembly provided in the ADF when the content formatter is declared.

Important Your custom content formatter runs with the same privileges as the NS$instance_name service. This gives the content formatter significant permissions on the system, such as adding and deleting files. It is up to you as the developer to ensure that your custom content formatter is robustly coded, and does not adversely affect system data or performance.


Using the IContentFormatter Interface

The IContentProvider interface provides the following methods:

  • Initialize allows the distributor to initialize the content formatter and prepare it to start running.
  • FormatContent allows the distributor to pass notification data to the content formatter, so that it can be formatted and then output for use by a delivery protocol. This method processes regular or multicast notifications one at a time, and digest notifications as a group.
  • Close allows the distributor to tell the content formatter to shut down.

The sequence of calls begins with Initialize, followed by a series of FormatContent calls, one for each notification to be formatted. Close is the last method in the sequence to be called. After Close has returned, FormatContent is not called again, unless the calling sequence is started over, with a new call to Initialize.

To create a custom content formatter that implements this interface, you must create a class that implements IContentFormatter, and then implement the methods inherited from the interface within this class. You then code the functionality for these methods that is appropriate for your application. For example, if your application provides both regular and digest notifications, your content formatter must be able to correctly format both types of notification.

Content Formatter Example

In the following code example, the content formatter concatenates notification text blocks with localized notification values to produce formatted notification content:

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using Microsoft.SqlServer.NotificationServices;

namespace TestFormatter
{
   public class MyContentFormatter : IContentFormatter
   {
      private bool digest = false;
      string introText = null;
      string midText = null;
      string endText = null;
      string browseBackUrl = null;

      public MyContentFormatter()
      {
         //Add constructor logic here if required.
      }

      //Implement the IContentFormatter.Initialize method.
      public void Initialize(
         StringDictionary arguments,
         bool digest)
      {
         this.digest = digest;

         //This content formatter requires four arguments:
         //the three text blocks to insert as notification
         //text, and the browse-back URL to display.
         if (4 == arguments.Count)
         {
            this.introText = arguments["introText"];
            this.midText = arguments["midText"];
            this.endText = arguments["endText"];
            this.browseBackUrl = arguments["URL"];
         }
         //Validate the values of the arguments here.
      }

      //Format the notification content.
      public string FormatContent(
         string subscriberLocale,
         string deviceTypeName,
         RecipientInfo recipientInfo,
         Hashtable[] rawContent)
      {
         StringBuilder contentString = new StringBuilder();

         try
         {
            StringWriter myWriter = new StringWriter(contentString);
            CultureInfo recipientCulture = GetCulture(subscriberLocale);

            foreach (Hashtable notification in rawContent)
            {
               myWriter.Write(introText);
               myWriter.Write(LocalizeNotificationData(notification["StockSymbol"], recipientCulture));
               myWriter.Write(midText);
               myWriter.Write(LocalizeNotificationData(notification["StockPrice"], recipientCulture));
               myWriter.Write(endText);
               myWriter.Write(browseBackUrl);
            }
            myWriter.Close();
         }
         catch (Exception e)
         {
            //Add code to handle errors here.
         }
      return contentString.ToString();
      }

      //Gets the culture information for the recipient.
      private CultureInfo GetCulture(string subscriberLocale)
      {
         CultureInfo culture = null;
         culture = CultureInfo.CreateSpecificCulture(subscriberLocale);
         return culture;
      }

      //Localizes the notification data.
      private string LocalizeNotificationData(object notificationField, CultureInfo recipientCulture)
      {
         string localizedString;
         IFormattable formattable = notificationField as IFormattable;
         if (formattable != null)
         {
            const string DEFAULT_FORMAT = null;
            localizedString = formattable.ToString(DEFAULT_FORMAT, recipientCulture);
         }
         else
         {
            localizedString = notificationField.ToString();
         }
         return localizedString;
      }

      //Implement the IContentFormatter.Close method.
      public void Close()
      {
         //Release any system resources here.
      }
   }
}

See Also

IContentFormatter Interface


Implementing the Initialize Method

The Initialize method requires two arguments:

arguments
A reference to a StringDictionary object that contains the named arguments for the content formatter. These arguments are defined in the NotificationClasses/NotificationClass/ContentFormatter/Arguments section of the application definition file (ADF).
digest
A Boolean value indicating whether the notification class for which the formatter is being used has digest delivery enabled.

The Initialize method does not have a return value.

Initialize Example
//Implement the IContentFormatter.Initialize method.
public void Initialize(
   System.Collections.Specialized.StringDictionary arguments,
   bool digest)
{
   this.digest = digest;

   //This content formatter requires four arguments:
   //the three text blocks to insert as notification
   //text, and the browse-back URL to display.
   if (4 == arguments.Count)
   {
      this.introText = arguments["introText"];
      this.midText = arguments["midText"];
      this.endText = arguments["endText"];
      this.browseBackUrl = arguments["URL"];
   }
   //Validate the values of the arguments here.
}

To refer to the full code for the content formatter, look at the example in Using the IContentFormatter Interface.

For more information, see IContentFormatter.Initialize Method.


Implementing the FormatContent Method

The FormatContent method requires four arguments:

subscriberLocale
A string providing the locale information, which can be used to determine how the notification is formatted with regards to language, date/time/currency formatting, and so on. For more information about these codes, see Subscriber Locale Codes.
deviceTypeName
A string providing the name that identifies the type of target device for this notification. The value of this string is specified in the subscriber device record of the target device for the notification. You can make use of this information in your content formatter processing, to format the notification to display appropriately on the recipient device.
recipientInfo
A reference to a RecipientInfo object containing information about the subscriber who is to receive the notification. This information is composed of a subscriber ID and a device address. The RecipientInfo class is provided as part of the Notification Services API.
rawContent
A reference to an array of Hashtable objects containing the raw notification data. Each hash table represents a single notification, with entries for each notification and computed field. The array contains only one Hashtable object, unless digest delivery is used. If that is the case, there is one Hashtable object for each notification in the digest group.

FormatContent returns a string that is the formatted notification data.

Your custom content formatter can internally use any technique to produce the formatted string. A simple approach might use basic string manipulation; more complex approaches might use XSL transforms or Microsoft ASP.NET rendering.

The FormatContent method provides a good place to implement filtering or encoding of notification content for security purposes. For example, as a security precaution, you might want to limit the total size of the notification content string produced.

Example: FormatContent
//Format the notification content.
public string FormatContent(
   string subscriberLocale,
   string deviceTypeName,
   Microsoft.SqlServer.NotificationServices.RecipientInfo recipientInfo,
   System.Collections.Hashtable[] rawContent)
{
   System.Text.StringBuilder contentString = new System.Text.StringBuilder();

   try
   {
      System.IO.StringWriter myWriter = new System.IO.StringWriter(contentString);
      System.Globalization.CultureInfo recipientCulture = GetCulture(subscriberLocale);

      foreach (System.Collections.Hashtable notification in rawContent)
      {
         myWriter.Write(introText);
         myWriter.Write(LocalizeNotificationData(notification["StockSymbol"], recipientCulture));
         myWriter.Write(midText);
         myWriter.Write(LocalizeNotificationData(notification["StockPrice"], recipientCulture));
         myWriter.Write(endText);
         myWriter.Write(browseBackUrl);
      }
      myWriter.Close();
   }
   catch (System.Exception e)
   {
      //Add code to handle errors here.
   }
   return contentString.ToString();
}

//Get the culture info for the recipient.
private System.Globalization.CultureInfo GetCulture(subscriberLocale)
{
   System.Globalization.CultureInfo culture = null;
   culture = System.Globalization.CultureInfo.CreateSpecificCulture(subscriberLocale);
   return culture;
}

//Localizes the notification data.
private string LocalizeNotificationData(object notificationField, System.Globalization.CultureInfo recipientCulture)
{
   string localizedString;
   System.IFormattable formattable = notificationField as System.IFormattable;

   if (formattable != null)
   {
      const string DEFAULT_FORMAT = null;
      localizedString = formattable.ToString(DEFAULT_FORMAT, recipientCulture);
   }
   else
   {
      localizedString = notificationField.ToString();
   }
   return localizedString;
}

To refer to the full code for the content formatter, look at the example in Using the IContentFormatter Interface.

For more information, see IContentFormatter.FormatContent Method.


Implementing the Close Method

The Close method does not accept any parameters, and has no return value.

The distributor calls Close to make the content formatter shut down.

Example: Close
//Implement the IContentFormatter.Close method.
public void Close()
{
   //Release any system resources here.
}

To refer to the full code for the content formatter, look at the example in Using the IContentFormatter Interface.

For more information about the IContentFormatter.Close method, see IContentFormatter.Close Method.


Developing a Custom Delivery Protocol

Notification Services provides several standard delivery protocols to assist you in creating delivery channels. However, you might want to deliver notifications using a different protocol than those provided by the standard components. If this is the case, you must develop a custom delivery protocol. The delivery protocol component implements the message creation and transport requirements of a protocol, thereby making it accessible within the Notification Services system.

You must implement one of two interfaces that are provided by Notification Services within your custom delivery protocol, in order for it to interoperate with the Notification Services distributor.

The IHttpProtocolProvider interface is provided to make it easy to develop a custom HTTP-based delivery protocol. It simplifies custom delivery protocol development in the case of HTTP-based protocols by providing all of the HTTP-related functionality, so that you need to provide code only to format the envelope and process the response.

The IDeliveryProtocol interface is to be used for custom delivery protocols that implement other protocols, or for HTTP-based delivery protocols that require more flexibility than IHttpProtocolProvider provides.

Both of these interfaces are available in the Microsoft.SqlServer.NotificationServices namespace.

You must declare each custom delivery protocol you develop in the <Protocols> node of the configuration file. You must then define a delivery channel that uses the custom delivery protocol in the <DeliveryChannels> node of the configuration file.

Finally, you must document the notification-specific information required by that delivery protocol in the /NotificationClasses/NotificationClass/Protocols section of the application definition file (ADF).

The following fields are used internally by Notification Services. You must not create protocol fields (specified in the /NotificationClasses/NotificationClass/Protocols/Protocol/Fields section of the ADF) with these names:

  • DeliveryChannelName
  • DeliveryStatusCode
  • DeviceAddress
  • DeviceName
  • DeviceTypeName
  • DistributorWorkItemId
  • ExpirationTime
  • LinkNotificationId
  • NotificationId
  • NotificationBatchId
  • SentTime
  • SubscriberId
  • SubscriberLocale

The NotificationId, SubscriberId, DeviceName, DeviceTypeName, DeviceAddress, and SubscriberLocale fields are exposed by Notification Services, and can be used in the SQL expressions for protocol fields.

Your custom delivery protocol must be implemented as a class in a managed code assembly. This assembly can reside anywhere, with the full path to the assembly provided in the configuration file when the delivery protocol is documented.


Using the IDeliveryProtocol Interface

The IDeliveryProtocol interface provides the following methods:

  • Initialize allows the delivery protocol to be initialized by the distributor prior to running.
  • DeliverNotification allows the distributor to pass formatted notification data to the delivery protocol, so that it can create the notification message, and route it to the external delivery system. This method is called once for each notification message that must be created and delivered.
  • Flush allows the distributor to make the delivery protocol complete any pending deliveries.
  • Close allows the distributor to make the delivery protocol release any resources it is using, and prepare it for shutdown.

The sequence of calls begins with Initialize, followed by a series of DeliverNotification calls, one for each message to be sent. Flush can be called before or after any of the DeliverNotification calls (but never in parallel with a DeliverNotification call). Close is the last method in the sequence to be called. After Close has returned, DeliverNotification and Flush is not called again, unless the calling sequence is started over, with a new call to Initialize.

The methods on a single delivery protocol instance are called only by a single thread, so accesses to instance data do not need to be thread-safe. Multiple protocol instances might possibly be called on multiple threads, so accesses to shared class-wide data must be thread safe.

Important The distributor does not enforce any time-outs on the IDeliveryProtocol methods. The delivery protocol classes are considered to be trusted, tested code. If any of the methods stop responding, then the distributor thread that calls them stops responding. If this happens on enough threads, distributor operation might halt.

To create a custom delivery protocol that implements this interface, you must create a class that implements IDeliveryProtocol and then implement the methods inherited from the interface within this class. Finally, you must code the functionality for these methods that is appropriate for your application.

Example: Delivery Protocol

In the following code example, the delivery channel sends notifications to a stored procedure in a SQL Server database:

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Text;
using Microsoft.SqlServer.NotificationServices;

namespace TestProtocol
{
   public class myDeliveryProtocol : IDeliveryProtocol
   {
      private bool multicast = false;
      private NotificationStatusCallback notificationStatusCallback = null;
      private string server = null;
      private string database = null;
      private string sproc = null;
      private string appName = null;
      private int commandTimeout = 0;
      private string connectionString = null;

      public myDeliveryProtocol()
      {
            //Add constructor logic here if required.
      }

      //Implement the IDeliveryProtocol.Initialize method.
      public void Initialize(
         StringDictionary channelArgs,
         bool multicast,
         NotificationStatusCallback notificationStatusCallback )
      {
         this.multicast = multicast;
         this.notificationStatusCallback = notificationStatusCallback;

         //This delivery protocol requires five arguments:
         //-the SQL Server instance to connect to.
         //-the SQL Server database to use.
         //-the SQL Server stored procedure to receive notifications.
         //-the name of the application making the connection.
         //-the time-out period for the command.
         if (5 == arguments.Count)
         {
            this.server = channelArgs["Server"];
            this.database = channelArgs["Database"];
            this.sproc = channelArgs["SProc"];
            this.appName = channelArgs["AppName"];
            this.commandTimeout = Int32.Parse(channelArgs["CommandTimeout"]);
         }

         //Validate the values of the arguments here.

         //Build the connection string.
         StringBuilder connectionStringBuilder = new StringBuilder();
         connectionStringBuilder.AppendFormat("Data Source={0}; Initial Catalog={1}; Integrated Security=true; App={2}",server,database,appName);

         connectionString = connectionStringBuilder.ToString();
      }

      //Implement the IDeliveryProtocol.DeliverNotification method.
      public void DeliverNotification(
         NotificationHeaders[] notificationHeaders,
         string body )
      {
         bool successfulDelivery = false;
         Exception failureException = null;

         try
         {
            //Get a connection to SQL Server.
            using (SqlConnection myConnection = new SqlConnection(connectionString))
            {
               //Prepare the SqlCommand object.
               SqlCommand myCommand = myConnection.CreateCommand();
               myCommand.CommandTimeout = commandTimeout;
               myCommand.CommandType = CommandType.StoredProcedure;
               myCommand.CommandText = sproc;

               //Call the stored procedure for each recipient.
               foreach(NotificationHeaders notificationHeader in notificationHeaders)
               {
                  //Reset the parameters.
                  myCommand.Parameters.Clear();

                  //Set the procedure parameters.
                  if (null != notificationHeader.ProtocolFields)
                  {
                     foreach (string protocolField in notificationHeader.ProtocolFields.Keys)
                     {
                        myCommand.Parameters.Add(String.Format("@{0}", protocolField), notificationHeader.ProtocolFields[protocolField]);
                     }
                  }
                  //Execute the command.
                  myCommand.ExecuteNonQuery();
                  successfulDelivery = true;
               }
            }
         }
         catch (Exception ex)
         {
            failureException = ex;
            //Handle any exceptions here; for instance,
            //write exception information to the event log.
         }
         finally
         {
            SendStatus(notificationHeaders, successfulDelivery, body, failureException);
         }
      }

      //Builds up a statusInfo message, creates a
      //NotificationStatus object, and calls
      //the notificationStatusCallback delegate.
      private void SendStatus(
         NotificationHeaders[] notificationHeaders,
         bool successfulDelivery,
         string body,
         Exception failureException)
      {
         if (null != notificationStatusCallback)
         {
            ArrayList statusList = new ArrayList(notificationHeaders.Length);
            string statusInfo;

            //Set some notification status parameters
            //based on delivery success or failure.
            string notificationText;
            if (null == failureException)
            {
               statusInfo = "";
               notificationText = "";
            }
            else
            {
               statusInfo = failureException.Message;
               notificationText = body;
            }

            object timeStamp = DateTime.UtcNow;

            //Create a NotificationStatus object for
            //each notification and add it to an array.
            for (int i = 0; i < notificationHeaders.Length; i++)
            {
               NotificationHeaders notificationHeader = notificationHeaders[i];
               statusList.Add(new NotificationStatus(notificationHeader.NotificationState, successfulDelivery, statusInfo, notificationText, timeStamp));
            }

            //Pass the array of NotificationStatus objects
            //to the NotificationStatusCallback delegate.
            notificationStatusCallback((NotificationStatus[])statusList.ToArray(typeof(NotificationStatus)));
         }
      }

      //Implement the IDeliveryProtocol.Flush method.
      public void Flush()
      {
         //Notification delivery by this protocol
         //is synchronous and completes in the
         //DeliverNotification call, so there
         //is nothing for Flush to do.
      }

      //Implement the IDeliveryProtocol.Close method.
      public void Close()
      {
         //No resources are held beyond the
         //sychronous call to DeliverNotification
         //so there are no resources for Close to release.
      }
   }
}

See Also

IDeliveryProtocol Interface


Implementing the Initialize Method

The Initialize method accepts three arguments:

channelArgs
A reference to a StringDictionary object containing the named arguments for this delivery protocol.
multicast
A Boolean value indicating whether multicast delivery is being used.
nsc
A NotificationStatusCallback delegate. This delegate is provided as part of the Notification Services API. The delegate is used to report notification delivery status to the distributor.

The arguments passed in the channelArgs argument are retrieved from the /DeliveryChannels/DeliveryChannel/Arguments section of the configuration file for the delivery channel in which the protocol is being used. They are defined by the developer, based on the information that the custom delivery protocol requires in order to initialize successfully.

The Initialize method does not have a return value.

Example: Initialize
public void Initialize(
   System.Collections.Specialized.StringDictionary channelArgs,
   bool multicast,
   Microsoft.SqlServer.NotificationServices.NotificationStatusCallback notificationStatusCallback )
{
   this.multicast = multicast;
   this.notificationStatusCallback = notificationStatusCallback;

   //This delivery protocol requires five arguments:
   //-the SQL Server instance to connect to.
   //-the SQL Server database to use.
   //-the SQL Server stored procedure to receive notifications.
   //-the name of the application making the connection.
   //-the time-out period for the command.
   if (5 == arguments.Count)
   {
      this.server = channelArgs["Server"];
      this.database = channelArgs["Database"];
      this.sproc = channelArgs["SProc"];
      this.appName = channelArgs["AppName"];
      this.commandTimeout = System.Int32.Parse(channelArgs["CommandTimeout"]);
   }

   //Validate the values of the arguments here.

   //Build the connection string.
   System.Text.StringBuilder connectionStringBuilder = new System.Text.StringBuilder();
   connectionStringBuilder.AppendFormat("Data Source={0}; Initial Catalog={1}; Integrated Security=true; App={2}",server,database,appName);

   connectionString = connectionStringBuilder.ToString();
}

To refer to the full code for the delivery protocol, look at the example in Using the IDeliveryProtocol Interface.

For more information, see IDeliveryProtocol.Initialize Method.


Implementing the DeliverNotification Method

The DeliverNotification method accepts two arguments:

headersList
A reference to an array of NotificationHeaders objects containing the information needed to create the notification message and route it to the external delivery system. Each NotificationHeaders object contains an opaque NotificationState object, which is a RecipientInfo object that provides information about the recipient, and a StringDictionary object containing the values of the protocol fields specified in the /NotificationClasses/NotificationClass/Protocols/Protocol section of the application definition file (ADF). The array contains only one NotificationHeaders object, unless multicast delivery is used. If that is the case, there is one NotificationHeaders object for each notification recipient. The NotificationHeaders, NotificationState, and RecipientInfo classes are provided as part of the Notification Services API.
body
A string containing the formatted notification data that was produced by the content formatter.

The DeliverNotification method does not have a return value.

The distributor calls a delivery protocol's DeliverNotification method once for each message to be delivered. In the case of multicast delivery, each call to DeliverNotification can contain data from more than one notification. The delivery protocol creates the notification message from this information, and routes the message for delivery. The message routing to the external delivery system can be accomplished in any way that is available to the developer and valid for the target delivery system. Often, this involves using transport mechanisms provided by the operating system.

The delivery protocol must use the notification status callback (whose delegate was passed to the Initialize method in the nsc argument) to pass a NotificationStatus object to the distributor for each notification passed as a NotificationHeaders object to the DeliverNotification method. The NotificationStatus object provides details on the outcome of each notification delivery attempt. Each NotificationStatus object contains the following fields:

  • NotificationState: An object used to convey notification information to the delivery protocol. The NotificationState object is passed to the delivery protocol for the express purpose of being passed back again as part of the notification delivery status information in a NotificationStatus object. The information contained in the NotificationState object is not used within the delivery protocol.
  • succeeded: A Boolean value indicating whether the notification message was handed off to the external delivery system successfully.
  • statusInfo: Additional delivery status information, such as an error message, or a text description of a status code. The value of statusInfo can be null if it is not needed by the delivery protocol.
  • notificationText: The content of the notification message. The value of notificationText can be null if it is not needed by the delivery protocol.
  • timeStamp: The time of the delivery attempt. The value of timeStamp can be null if it is not needed by the delivery protocol. If it is used, the time must be specified as a Universal Time Coordinate (UTC) time.

If multiple notifications are passed in a single call to DeliverNotification (that is, if the headersList array contains multiple NotificationHeaders objects), a NotificationStatus object must be provided to the distributor for each notification. This can be accomplished either by calling the notification status callback multiple times, or by passing multiple NotificationStatus objects to the notification status callback in a single call.

Determine when your implementation should invoke the notification status callback by balancing your requirement for application performance with your requirement for accuracy.

Each call to the notification status callback results in a round-trip to the database server. Sending multiple NotificationStatus objects in a single call improves performance by reducing the round-trips to the server. This requires the protocol implementation to cache the individual notification status values in memory until a sufficient number of them are collected. This situation leaves open the possibility of sending duplicate notifications if a server failure occurs and causes that in-memory cache to be lost before the status for those notifications is reported. You can mitigate this possibility by reporting the status of each notification individually immediately after it is sent, but this strategy results in more round-trips and some performance impact.

Important If DeliverNotification throws an exception, you must not invoke the status callback for any of the notification headers passed in that call to DeliverNotification. Any exception thrown in this method is treated as a delivery failure. The notification delivery status is automatically set to Failed, thereby eliminating the need to set the status by using the callback.

DeliverNotification Example
//Implement the IDeliveryProtocol.DeliverNotification method.
public void DeliverNotification(
   Microsoft.SqlServer.NotificationServices.NotificationHeaders[] notificationHeaders,
   string body )
{
   bool successfulDelivery = false;
   System.Exception failureException = null;

   try
   {
      //Get a connection to SQL Server.
      using (System.Data.SqlClient.SqlConnection myConnection = new System.Data.SqlClient.SqlConnection(connectionString))
      {
         //Prepare the SqlCommand object.
         System.Data.SqlClient.SqlCommand myCommand = myConnection.CreateCommand();
         myCommand.CommandTimeout = commandTimeout;
         myCommand.CommandType = System.Data.CommandType.StoredProcedure;
         myCommand.CommandText = sproc;

         //Call the stored procedure for each recipient.
         foreach(Microsoft.SqlServer.NotificationServices.NotificationHeaders notificationHeader in notificationHeaders)
         {
            //Reset the parameters.
            myCommand.Parameters.Clear();

            //Set the procedure parameters.
            if (null != notificationHeader.ProtocolFields)
            {
               foreach (string protocolField in notificationHeader.ProtocolFields.Keys)
               {
                  myCommand.Parameters.Add(string.Format("@{0}", protocolField), notificationHeader.ProtocolFields[protocolField]);
               }
            }
            //Execute the command.
            myCommand.ExecuteNonQuery();
            successfulDelivery = true;
         }
      }
   }
   catch (System.Exception ex)
   {
      failureException = ex;
      //Handle exception; for instance, write
      //exception information to the event log.
   }
   finally
   {
      SendStatus(notificationHeaders, successfulDelivery, body, failureException);
   }
}

//Builds up a statusInfo message, creates a
//NotificationStatus object, and calls
//the notificationStatusCallback delegate.
private void SendStatus(
   Microsoft.SqlServer.NotificationServices.NotificationHeaders[] notificationHeaders,
   bool successfulDelivery,
   string body,
   System.Exception failureException)
{
   if (null != notificationStatusCallback)
   {
      System.Collections.ArrayList statusList = new System.Collections.ArrayList(notificationHeaders.Length);
      string statusInfo;

      //Set some notification status parameters
      //based on delivery success or failure.
      string notificationText;
      if (null == failureException)
      {
         statusInfo = "";
         notificationText = "";
      }
      else
      {
         statusInfo = failureException.Message;
         notificationText = body;
      }

      object timeStamp = System.DateTime.UtcNow;

      //Create a NotificationStatus object for
      //each notification and add it to an array.
      for (int i = 0; i < notificationHeaders.Length; i++)
      {
         Microsoft.SqlServer.NotificationServices.NotificationHeaders notificationHeader = notificationHeaders[i];
         statusList.Add(new Microsoft.SqlServer.NotificationServices.NotificationStatus(notificationHeader.NotificationState, successfulDelivery, statusInfo, notificationText, timeStamp));
      }

      //Pass the array of NotificationStatus objects
      //to the NotificationStatusCallback delegate.
      notificationStatusCallback((Microsoft.SqlServer.NotificationServices.NotificationStatus[])
      statusList.ToArray(typeof(Microsoft.SqlServer.NotificationServices.NotificationStatus)));
   }
}

To refer to the full code for the delivery protocol, look at the example in Using the IDeliveryProtocol Interface.

For more information, see IDeliveryProtocol.DeliverNotification Method.


Implementing the Flush Method

The Flush method does not accept any parameters, and does not have a return value.

The Flush method is called by the distributor when it wants the delivery protocol to complete any notifications that are pending for message creation or for routing to the external delivery system.

Flush must either complete or abort any pending operations before returning. The Flush method can impose a time-out on pending operations (the value of which can be specified as a parameter or a hard-coded argument in the /NotificationClasses/NotificationClass/Protocols/Protocol section of the application definition file (ADF) or the /DeliveryChannels/DeliveryChannel/Arguments section of the configuration file), but this is implementation-specific, and is not enforced by the distributor.

You can use calls to the Flush method to do such things as either wait for or terminate an outstanding transaction. If it makes sense for your application, you can also use Flush to submit all outstanding status callbacks as a batch, thereby making a single round-trip to the server.

Important When creating a custom delivery protocol, you must ensure that status callbacks for all notifications that have not yet had their delivery status recorded are sent before the Flush method finishes. Status callbacks return status to the distributor by using the NotificationStatusCallback delegate. Failure to return status for any outstanding notifications can result in distribution errors. This is due to the fact that no callbacks are allowed after the Flush method finishes, and notification delivery status information might therefore be incomplete.

Example
//Implement the IDeliveryProtocol.Flush method.
public void Flush()
{
   //Notification delivery by this protocol
   //is synchronous and completes in the
   //DeliverNotification call, so there
   //is nothing for Flush to do.
}

To refer to the full code for the delivery protocol, look at the example in Using the IDeliveryProtocol Interface.

For more information, see IDeliveryProtocol.Flush Method.


Implementing the Close Method

The Close method does not accept any parameters, and does not have a return value.

The distributor calls the Close method to cause the delivery protocol to shut down, at which time it releases all resources. If the delivery protocol implements asynchronous delivery, and there are outstanding requests at the time Close is called, these requests must be either completed or aborted before Close returns.

Example
//Implement the IDeliveryProtocol.Close method.
public void Close()
{
   //No resources are held beyond the
   //sychronous call to DeliverNotification
   //so there are no resources for Close to release.
}

To refer to the full code for the delivery protocol, look at the example in Using the IDeliveryProtocol Interface.

For more information, see IDeliveryProtocol.Close Method.


Using the IHttpProtocolProvider Interface

The IHttpProtocolProvider interface provides the following methods:

  • Initialize allows the delivery protocol to be initialized by the distributor prior to running.
  • FormatEnvelope allows the distributor to pass formatted notification data to the delivery protocol, which then uses this information to create the HTTP envelope.
  • ProcessResponse allows the delivery protocol to receive and process the HTTP response from the server.
  • Close allows the distributor to make the delivery protocol release any resources it is using, and prepares it for shutdown.

The sequence of calls begins with Initialize, followed by a pair of FormatEnvelope and ProcessResponse calls, one pair for each message to be sent. Close is the last method in the sequence to be called. After Close has returned, FormatEnvelope and ProcessResponse are not called again, unless the calling sequence is started over, with a new call to Initialize.

The IHttpProtocolProvider interface works in conjunction with the internal HttpExtension class provided by Notification Services. This class wraps most of the basic functionality required when implementing an HTTP-based delivery protocol, including issuing requests and receiving responses from an HTTP server. The developer only needs to create the message envelope and process the HTTP response, using the methods that the IHttpProtocolProvider interface provides.

The distributor does not enforce any time-outs on the IHttpProtocolProvider methods. The delivery protocol classes that provide the implementations are considered to be trusted, tested code. If any of the methods stop responding, then the distributor thread that calls them stops responding. If this happens on enough threads, distributor operation might halt.

To create a custom delivery protocol that implements this interface, you must create a class that implements IHttpProtocolProvider and then create the methods inherited from the interface within this class. Finally, you must code the functionality for these methods that is appropriate for your application.

HTTP Delivery Protocol Example

In the following code example, the HTTP delivery protocol uses an XSLT file in combination with the protocol fields to build an envelope:

using System;
using System.Collections.Specialized;
using System.Text;
using System.Net;
using System.Xml;
using System.IO;
using Microsoft.SqlServer.NotificationServices;

namespace HttpProtocol
{
   public class MyHttpDeliveryProtocol: IHttpProtocolProvider
   {

      public MyHttpDeliveryProtocol()
      {
         //Add constructor logic here if required.
      }

      //Implement the IHttpProviderProtocol.Initialize method.
      public void Initialize(StringDictionary channelArguments)
      {
         //Process initialization parameters
         //if any are necessary.
      }

      //Implement the IHttpProviderProtocol.FormatEnvelope method.
      public string FormatEnvelope(
         StringDictionary protocolFields,
         string requestBody)
      {
         //Use a StringBuilder, a StringWriter, and
         //an XmlTextWriter to create the XML string.
         StringBuilder myStringBuilder = new StringBuilder();
         StringWriter myStringWriter = new StringWriter(myStringBuilder);
         XmlTextWriter myWriter = new XmlTextWriter(myStringWriter);
         //Create the envelope.
         myWriter.WriteStartElement("soap:envelope");
         //Create the header.
         myWriter.WriteStartElement("soap:header");
         myWriter.WriteStartElement("username");
         myWriter.WriteString(protocolFields["userName"]);
         myWriter.WriteEndElement();
         myWriter.WriteStartElement("password");
         myWriter.WriteString(protocolFields["password"]);
         myWriter.WriteEndElement();
         myWriter.WriteEndElement();
         //Create the body.
         myWriter.WriteStartElement("soap:body");
         myWriter.WriteString(requestBody);
         myWriter.WriteEndElement();
         //Close the envelope.
         myWriter.WriteEndElement();

         string envelope = myStringBuilder.ToString();

         myWriter.Close();

         return envelope;
      }

      //Implement the IHttpProviderProtocol.ProcessResponse method.
      public bool ProcessResponse(
         HttpStatusCode   statusCode,
         String responseBody,
         bool postSuccess)
      {
         if(postSuccess)
         {
            return postSuccess;
         }
         else
         {
            return(false);
            //You could log the responseBody info here.
         }
      }

      //Implement the IHttpProviderProtocol.Close method.
      public void Close()
      {
         //Release any system resources here.
      }
   }
}

See Also

IHttpProtocolProvider


IHttpProtocolProvider Delivery Protocol Configuration File Settings

Your custom IHttpProtocolProvider delivery protocol must be declared in a <Protocol> node within the <Protocols> section of the configuration file. Then, in a <DeliveryChannel> node within the <DeliveryChannels> section of the configuration file, you must declare one or more delivery channels that use the custom IHttpProtocolProvider delivery protocol. Each of the elements for these two nodes is described in the following sections.

<Protocol> Elements

The following list reviews the elements that are required in the <Protocol> declaration for the custom IHttpProtocolProvider delivery protocol:

<ProtocolName>
A string that conforms to XML naming conventions. It must be unique within your application.
<ClassName>
You must specify the value "HttpExtension" for this element.
IHttpProtocolProvider Protocol Example
<Protocols>
   <Protocol>
      <ProtocolName>SMSDeliveryProtocol</ProtocolName>
      <ClassName>HttpExtension</ClassName>
   </Protocol>
</Protocols>
<DeliveryChannel> Elements

The following list reviews the elements that are required in the <DeliveryChannel> declaration for the custom IHttpProtocolProvider delivery protocol:

<DeliveryChannelName>
A string that conforms to XML naming conventions. It must be unique within your application.
<ProtocolName>
The same value that you specified for the <ProtocolName> element in the <Protocol> declaration.
<Arguments> and child elements
Initialization parameters for a custom IHttpProtocolProvider delivery protocol. It can accept some or all of the following arguments. (Required arguments are noted.)
  • ProtocolProviderClassName (required) provides the name of the class you have created that implements the IHttpProtocolProvider interface.
  • ProtocolProviderAssemblyName (required) provides the name of the assembly containing the class that implements the IHttpProtocolProvider interface.
  • PostUrl (required) provides the URL to be used to connect to the service to which the notification is to be delivered.
  • UserName provides the user name required for authentication.
  • Password provides the password required for authentication.
  • Domain provides the Windows domain that the IIS server uses for digest authentication.
  • Group provides a user name or other unique string that the HTTP server can use to group requests.
  • ConnectionLimit provides the maximum number of connections to the service that one distributor can create. If no value is specified, the default is 2.
  • AsyncPosts provides the number of outstanding requests (requests that have not been responded to) that one distributor can have with a service. If no value is specified, the default is 16.
  • MaxShutdown provides the amount of time in seconds that the distributor can wait for an HTTP request to complete. If no value is specified, the default is 180.
  • ProxyServer provides the name of the proxy server that this delivery channel uses to access service beyond the local network.
  • ProxyPort provides the port number that this delivery channel uses for communication. If no value is specified, the default is 80.
  • Encoding specifies the string format required by the HTTP server. All encoding formats returned by the GetEncoding method of the Encoding class in the Microsoft .NET Framework are acceptable values. Not all platforms support all encodings; if an encoding is not supported by the deployed platform, a NotSupportedException is thrown.
  • ContentType specifies the HTTP content type of the request.
  • SoapAction specifies the intent of the SOAP HTTP request. The permissible values for this argument are dependent upon the SOAP server that is being used.
IHttpProtocolProvider Delivery Channel Example
<DeliveryChannels>
   <DeliveryChannel>
      <ChannelName>SMSChannel</ChannelName>
      <ProtocolName>SMSDeliveryProtocol</ProtocolName>
      <Arguments>
         <Argument>
            <Name>ProtocolProviderClassName</Name>
            <Value>MyHttpDeliveryProtocol</Value>
         </Argument>
         <Argument>
            <Name>ProtocolProviderAssemblyName</Name>
            <Value>%AppPath%\SMSProtocol.dll</Value>
         </Argument>
         <Argument>
            <Name>PostURL</Name>
            <Value>%URL%</Value>
         </Argument>
         <!-- Additional arguments specific to the HTTP-based
         protocol being implemented. -->
      </Arguments>
   </DeliveryChannel>
</DeliveryChannels>


Implementing the Initialize Method

The Initialize method is called in order to prepare the delivery protocol to run. The Initialize method accepts one argument, channelArguments. This provides a reference to a StringDictionary object containing the names and values of the arguments for this delivery protocol.

The arguments passed in the channelArguments argument are retrieved from the /DeliveryChannels/DeliveryChannel/Arguments section of the configuration file. They are defined by the developer, based on the information that the custom delivery protocol requires in order to initialize successfully.

The Initialize method does not have a return value.

Initialize Example
//Implement the IHttpProviderProtocol.Initialize method.
public void Initialize(System.Collections.Specialized.StringDictionary channelArguments)
{
   //Process initialization parameters
   //if any are necessary.
}

To refer to the full code for the delivery protocol, look at the example in Using the IHttpProtocolProvider Interface.

For more information, see IHttpProtocolProvider.Initialize Method.


Implementing the FormatEnvelope Method

The FormatEnvelope method returns a string containing the appropriately formatted envelope. The FormatEnvelope method accepts two arguments:

protocolFields
A StringDictionary object containing the names and values of the protocol fields specified in the /NotificationClasses/NotificationClass/Protocols/Protocol section of the application definition file (ADF).
requestBody
A string containing the formatted notification data that was produced by the content formatter. This becomes the body of the HTTP request.
FormatEnvelope Example
//Implement the IHttpProviderProtocol.FormatEnvelope method.
public string FormatEnvelope(
   System.Collections.Specialized.StringDictionary protocolFields,
   string requestBody)
{
   //Use a StringBuilder, a StringWriter, and
   //an XmlTextWriter to create the XML string.
   System.Text.StringBuilder myStringBuilder = new System.Text.StringBuilder();
   System.IO.StringWriter myStringWriter = new System.IO.StringWriter(myStringBuilder);
   System.Xml.XmlTextWriter myWriter = new System.Xml.XmlTextWriter(myStringWriter);
   //Create the envelope.
   myWriter.WriteStartElement("soap:envelope");
   //Create the header.
   myWriter.WriteStartElement("soap:header");
   myWriter.WriteStartElement("username");
   myWriter.WriteString(protocolFields["userName"]);
   myWriter.WriteEndElement();
   myWriter.WriteStartElement("password");
   myWriter.WriteString(protocolFields["password"]);
   myWriter.WriteEndElement();
   myWriter.WriteEndElement();
   //Create the body.
   myWriter.WriteStartElement("soap:body");
   myWriter.WriteString(requestBody);
   myWriter.WriteEndElement();
   //Close the envelope.
   myWriter.WriteEndElement();

   string envelope = myStringBuilder.ToString();

   myWriter.Close();

   return envelope;
}

To refer to the full code for the delivery protocol, look at the example in Using the IHttpProtocolProvider Interface.

For more information, see IHttpProtocolProvider.FormatEnvelope Method.


Implementing the ProcessResponse Method

The ProcessResponse method returns a Boolean value indicating whether the post was successful. The ProcessResponse method accepts three arguments:

httpResponseCode
A reference to an HttpStatusCode object that contains the HTTP response code.
responseBody
A string containing the body of the HTTP response.
postSuccess
A Boolean value indicating whether Notification Services thinks the post was successful.

The postSuccess argument indicates whether the protocol thinks the delivery succeeded. This post status can conflict with the actual delivery status. For instance, the post might have succeeded at the HTTP level, but the delivery itself might have failed. This additional status information is supplied in the responseBody argument. You must evaluate this response body to determine the actual delivery status, and then set the return value to indicate success or failure.

Example
//Implement the IHttpProviderProtocol.ProcessResponse method.
public bool ProcessResponse(
   System.Net.HttpStatusCode statusCode,
   string responseBody,
   bool postSuccess)
{
   if(postSuccess)
   {
      return postSuccess;
   }
   else
   {
      return(false);
      //You could log the responseBody info here.
   }
}

To refer to the full code for the delivery protocol, look at the example in Using the IHttpProtocolProvider Interface.

For more information, see IHttpProtocolProvider.ProcessResponse Method.


Implementing the Close Method

The distributor calls the Close method to cause the delivery protocol to shut down, at which time it releases all resources. If the delivery protocol implements asynchronous delivery, and there are outstanding requests at the time Close is called, these requests are either completed or abandoned before Close returns.

The Close method does not accept any arguments, and does not have a return value.

Example
//Implement the IHttpProviderProtocol.Close method.
public void Close()
{
   //Release any system resources here.
}

To refer to the full code for the delivery protocol, look at the example in Using the IHttpProtocolProvider Interface.

For more information, see IHttpProtocolProvider.Close Method.


Debugging a Custom Component

To call a custom component that is hosted by Notification Services, you must build and run a Notification Services application that calls the component. You cannot use this method to debug an independent event provider, because the thread of execution for such an event provider is not provided by nsservice.exe.

If Notification Services is running as the NS$instance_name service, you can start the service and attach a debugger to the running process.

Alternatively, you can run nsservice.exe as a console application to debug application components in Microsoft Visual Studio .NET. To do this, follow these steps:

  1. In Visual Studio .NET, right-click the project containing the custom component, click on Properties, select Configuration Properties in the left pane, and then select Debugging.
  2. In the Start Action section, set the Debug Mode field to "Program", and then set the Start Application field to the fully qualified path to nsservice.exe.
  3. In the Start Options section, set the Command Line Arguments field to "instance_name -a", where instance_name is the name of the instance you want to debug.
  4. Place a breakpoint in the custom component code wherever you want the debugger to stop.
  5. Start the solution.
  6. Drop events into the system in whatever way the application requires, so that the application starts processing.


Notification Services Programming Samples

Notification Services includes a set of programming samples to illustrate application development in a variety of scenarios. The samples are installed by default to C:\Program Files\Microsoft Notification Services\VersionNumber\Samples.

This section covers each of these samples, as well as more general information on sample structure, deployment, and security. The topics are described in the following table.

Topic | Description
Programming Sample Structure | Provides information about the projects and files used in the samples.
Programming Sample Requirements | Provides information about the software and configuration settings needed to run the samples.
Setting Up and Removing Programming Samples | Provides information on installing and removing the samples.
Changing Sample Reference Paths | Discusses the manual changes you must make to the samples if you have installed Notification Services to a non-default location.
Configuring the Subscribe Project for Debugging | Describes how to configure the subscription management application project in a sample for debugging in Microsoft Visual Studio® .NET.
Resolving Common Issues | Provides troubleshooting information for commonly encountered problems.
Stock Sample | Provides information about the Stock sample, which is developed in Microsoft C#™, and provides event-driven and scheduled subscriptions.
Flight Sample | Provides information about the Flight sample, which is developed in Microsoft Visual Basic® .NET, and provides event-driven subscriptions.
Weather Sample | Provides information about the Weather sample, which is developed in C#, and provides scheduled subscriptions.
Realtor Sample | Provides information about the Realtor sample, which is developed in C#, and provides event-driven subscriptions.


Programming Sample Structure

Each programming sample included with Notification Services is implemented as a Microsoft Visual Studio .NET solution. A solution serves as a container for storing information about one or more projects and associated items. The solutions use several standard projects to identify and separate application components. These projects in turn contain standard files, which perform such tasks as defining the application metadata, providing build scripts, and implementing the subscription management application. You will use these projects and files to build and run the samples.

All samples build to a Debug configuration. If you use the CopySample.cmd script to copy a sample application for use as a development template, don't forget to change the configuration setting in the solution properties from Debug to Release before you deploy your application.

Important Visual Studio .NET creates files in the directory Samples\SampleName\Subscribe\obj\Debug. The files in this directory can be read by anyone. This poses a security threat if the sample is deployed in an environment where a hostile user might access that computer. Once the sample is built, this folder is no longer required and can be safely deleted. However, it is re-created each time the sample is built.

The solution for each sample contains the AppDefinition and Subscribe projects. The Stock sample also includes a CustomDeliveryProtocol project. Each of these projects is described in this section.

AppDefinition Project

The AppDefinition project contains the files that describe the application metadata, and the scripts used to create and update the application.

Application metadata files
appADF.xml
The application definition file (ADF) for the sample.
appConfig.xml
The configuration file for the sample.
Application.xslt
An XSL transform file that you can use with the Notification Services standard XSLT content formatter to format notification data for this application. This XSL transform file provides simple formatted data in a sample-specific manner. In the Realtor sample this file is named RealtorInfo.xslt.
NoOp.xslt
An XSL transform file that you can use with the Notification Services standard XSLT content formatter to format notification data for this application. The NoOp.xslt file writes the notification information in exactly the same format that it receives it, without any additional processing. This XSL transform is useful for debugging, and is used by default in the Flight programming sample and for one of the two notification classes in the Stock sample.
EventSchema.xsd
The XML schema that defines the structure of the event class used in this application.
ApplicationDefinitionFileSchema.xsd
The XML schema that defines the structure of a Notification Services ADF. It is provided for reference information and also to enable IntelliSense when working in the ADF.
ConfigurationFileSchema.xsd
The XML schema that defines the structure of a Notification Services configuration file. It is provided for reference information and also to enable IntelliSense when working in the configuration file.
Application build scripts
BuildScripts
The BuildScripts subfolder contains the following scripts, which are used to create and update the application.
RunBuild.cmd
Builds the application. For a new application, this script runs the RunCreate.cmd script; for an existing application it runs the NSControl Disable command and then the NSControl Update command. This script is run when you select the Build action, which you access by right-clicking the project name in the Solution Explorer pane of Visual Studio .NET.

Note If you build the samples by using direct NSControl commands instead of the sample script files, you must manually copy the required Microsoft.SqlServer.NotificationServices.dll and Subscribe.dll files to the Samples\SampleName\Subscribe\bin directory. Otherwise, the sample subscription pages return an error about the DLLs not being found.

RunClean.cmd
Removes the application and deletes the sample databases using NSControl Delete. This script is run when you select the Clean action, which you access by right-clicking the project in the Solution Explorer pane of Visual Studio .NET.
RunCreate.cmd
Creates the sample instance and application using NSControl Create, and enables the instance using NSControl Enable. It calls the GrantPermissions.cmd script to add the ASPNET Windows account (which is created when you install the Microsoft.NET Framework) and the NS$instance_name service account as SQL Server login accounts. It then adds the accounts to appropriate roles in the instance database. In the Realtor programming sample, RunCreate.cmd also calls CreateRealtorDB.cmd to create the Realtor database.
RunRebuild.cmd
Rebuilds the application. Deletes the sample databases using NSControl Delete, and then runs the RunCreate.cmd script. This script is run when you select the Rebuild action accessed by right-clicking the AppDefinition project.
RunService.cmd
Runs the NS$instance_name service as a command-line application.
GrantPermissions.cmd
Sets up the required SQL Server login accounts and permissions. Adds the ASPNET SQL Server login account to appropriate roles in the instance database. If the NS$instance_name service uses SQL Server Authentication to access the databases, then that login account is also given appropriate permissions to the instance database if you specify the password for that account as a parameter to GrantPermissions.cmd.
Subscribe Project

The Subscribe project contains the files associated with the subscription management application for this application. If this application accepts event data through a Web page, those files will appear here as well.

Default.aspx
The subscription management page. The code behind this file is in Default.aspx.cs (or Default.aspx.vb in the Flight sample application).
EventSubmission.aspx
The event submission page. This file appears only in the Stock sample application. The code behind this file is in EventSubmission.aspx.cs.
CustomDeliveryProtocol Project

The CustomDeliveryProtocol project is used only in the Stock sample application. It contains the files for a custom delivery protocol that the Stock sample application uses. The code for this project is in HttpLoggerDeliveryProtocol.cs, the class file that defines the custom delivery protocol.


Programming Sample Requirements

All the programming samples included with Notification Services create Notification Services instances and databases, so Microsoft strongly recommends that you run the samples only on a development or testing server, not on a production server.

To run correctly, the Notification Services sample applications require the environment shown in the following table.

Operating System Microsoft Windows® 2000 Server (SP2 or later).

Microsoft Windows XP.
Applications Microsoft SQL Server Notification Services.

Microsoft Visual Studio .NET (with Microsoft Visual C#™, Microsoft Visual C++®, and Microsoft Visual Basic® components installed).

SQL Server 2000 (Standard, Developer, or Enterprise Edition).

Microsoft SQLXML 3.0

Note If you install Visual Studio .NET before installing SQL Server, you must manually add the SQL Server client utilities location to the C++ path. For details, see Configuring Visual Studio .NET
Running Services Simple Mail Transfer Protocol (SMTP).

IIS Admin.

World Wide Web Publishing Service.

Note To send e-mail notifications, you must configure the Windows SMTP service to relay messages and start running. For more information, see "Configuring the SMTP Service" later in this topic.
Accounts Accounts under which the subscription management application, the NS$instance_name service, and the Visual Studio .NET Build commands (based on calls to the NSControl utility) will run.

Valid Windows accounts and SQL Server login accounts for any users who will be working with the samples.

For more information about these accounts and their required permissions, see Required Accounts and Permissions.
Installing Software for Samples Deployment

All Notification Services sample applications require SQL Server, Notification Services, Visual Studio .NET, and Internet Information Services (IIS). Microsoft recommends that you install all this software on a single server to make it easy to deploy the samples.

If you choose to deploy the samples in a multi-server environment instead, you must install the required software as follows.

The server running the samples must have:

  • The Notification Services engine components, client components, sample applications, and documentation.
  • Visual Studio .NET (with Visual C#, Visual C++, and Visual Basic components installed).
  • All services that are noted in the "Running Services" row of the preceding table.
  • The SQL Server 2000 client utilities.

The server running the databases must have:

  • The Notification Services database components.
  • SQL Server 2000 (Standard, Developer, or Enterprise Edition).
Configuring the SMTP Service

To send e-mail notifications, you must configure the Simple Mail Transport Protocol (SMTP) service to relay messages and start running. If the SMTP service is not configured to relay messages or is not running, the notifications generated by the sample applications are delivered to the \inetpub\mailroot\queue directory. Depending on the configuration of your SMTP service, the messages might appear in a different \inetpub\mailroot folder, such as \pickup or \badmail. For more information about configuring SMTP, see Using SMTP for Outgoing Messages in the Microsoft MSDN® Library.


Required Accounts and Permissions

As part of setting up the Notification Services programming samples, you must provide the Windows accounts under which the following components will run: the subscription management application, the NS$instance_name service, and the Microsoft Visual Studio .NET Build commands (based on calls to the NSControl utility). These Windows accounts must also have SQL Server login accounts in order to create, access, and modify the Notification Services databases. Notification Services does not create SQL Server login accounts, so you must ensure that all accounts that require access to the databases have SQL Server login accounts before using the samples. (When you run the SetupSamples.cmd script, Notification Services automatically grants database permissions to these accounts.)

You must also have valid Windows accounts and SQL Server login accounts for all users who access the samples.

For more information about adding login accounts and database users, see "sp_addlogin", "sp_grantlogin", and "sp_grantdbaccess" in SQL Server Books Online.

See Also

Subscription Management Application Account

NS$instance_name Service Account

Visual Studio .NET Build Command (NSControl Utility) Account

User Accounts


Subscription Management Application Account

In Notification Services, the subscription management application uses the ASPNET Windows account by default to access the Notification Services databases. The ASPNET account is created automatically when the Microsoft .NET Framework is installed.

To check for the ASPNET account on the computer where you have your programming samples, open the User Accounts directory in Control Panel. If the ASPNET account was not created during your installation of Microsoft Visual Studio .NET, run windows_directory\Microsoft.NET\Framework\v1.0.3705\aspnet_regiis.exe to create it.

Because ASPNET is a local account, it cannot be granted access to a remote SQL Server instance. Therefore, when using the ASPNET account, you must install SQL Server on the server where the samples are installed.

Accessing a Remote SQL Server Instance

To access a SQL Server instance on another computer, you can configure the subscription management application to use a domain account instead of the default ASPNET account. Using a domain account allows you to use Windows Authentication, which provides better security features than SQL Server Authentication, such as secure validation and encryption of passwords, auditing, password expiration, minimum password length, and account lockout after multiple invalid login requests. Alternatively, if you cannot use Windows authentication, you can use SQL Server Authentication.

To use a domain account to access a remote instance

  1. In Microsoft Windows Explorer, expand the Notification Services installation directory, and navigate to the Samples directory.
  2. Right-click the SetGlobalVars.cmd script, and then click Edit.
  3. Replace this line:
    set SubscriptionApplicationAccount=%NSHost%\ASPNET

    with this line:

    set SubscriptionApplicationAccount=DOMAIN\User
  4. Ensure that the domain account you specify has been given a SQL Server login account (by using the sp_grantlogin stored procedure), and has been added as a user to the instance and application databases.

    When you run the SetupSamples.cmd script, this account is granted the necessary database permissions.

To use SQL Server Authentication to access a remote instance

Important Microsoft strongly recommends that you specify a domain account for use by the subscription management application rather than using SQL Server Authentication.

  1. Define a SQL Server login name and password for your subscription management application to use.
  2. Grant the login account user access to the instance and application databases.
  3. Add the user to the NSSubscriberAdmin role in those databases.
  4. Record the SQL Server authorization information in a secure location, like a registry key with appropriate access control entries (ACEs) in its access control list (ACL).
  5. In the Solution Explorer pane of Visual Studio .NET, expand the Subscribe project, right-click the Default.aspx file, and then click View Code.
  6. In the Page_Load method, remove the comment delimiters from the following two lines, and replace the "sqluser" and "sqlpassword" values with code that retrieves the appropriate authorization information from the secure location:
    // instance.SqlUser = "sqluser";
// instance.SqlPassword = "sqlpassword";
  7. In the Solution Explorer pane, right-click the \Samples\Common\NSUtility.cs file, click View Code, and make the same changes in the NSUtility constructor that you did in step 6.
  8. Right-click the Subscribe project, and then click Rebuild.

When you run the SetupSamples.cmd script, this account will be granted the necessary database permissions.

Note If you want to allow Web applications to submit event data, add the SQL Server login account of the subscription management application to the NSEventProvider database role.

For more information about adding login accounts and database users, see "sp_addlogin," "sp_grantlogin," and "sp_grantdbaccess" in SQL Server Books Online.

See Also

Notification Services Database Roles


NS$instance_name Service Account

In Notification Services, the NS$instance_name service requires an account in order to access local and network resources, to send messages with Simple Mail Transfer Protocol (SMTP), and to access the SQL Server databases in environments where SQL Server Authentication is used.

The SetupSamples.cmd script creates the NS$instance_name service. When you run this script, you must specify the account under which the NS$instance_name service runs. Specify one of the following types of accounts:

  • A domain user account. Microsoft strongly recommends running the NS$instance_name service under a domain account (domain\username). You can either obtain a custom domain account from your domain administrator (recommended), or use your own domain account. Using a domain account, you can more easily control access to network resources and to local or remote SQL Server databases. Additionally, if you use a custom domain account, you can limit the permissions granted to only those required by the service.
  • A local user account. You can run the NS$instance_name service under a local user account (computer\username) if the databases are located on the same system as the NS$instance_name service, or if you use SQL Server Authentication to access the databases (regardless of database locations).
  • The NetworkService account. This account is available only on Microsoft Windows XP. Using this account makes it difficult to control which services have access to network resources, including remote SQL Server databases. All services running under the NetworkService account are mapped to the domain\remotecomputername$ domain account when accessing network resources.

    The NetworkService account cannot send notifications using the SMTP delivery protocol because the account is not a member of the local Administrators group. Because the Stock sample provided with Notification Services does not use SMTP, you can run the NS$StockInstance service under the NetworkService account.

  • The LocalSystem account. Microsoft strongly discourages using the LocalSystem account, because this account has unrestricted access to all local resources. Also, with this account it is impossible to control which services have access to network resources, including remote SQL Server databases. All services running under the LocalSystem account are mapped to the domain\remotecomputername$ domain account when accessing network resources.

The account under which the NS$instance_name service runs must have the following permissions and characteristics:

  • Read and write permissions for the Notification Services directory (InstallLocation\Microsoft SQL Server Notification Services\VersionNumber).
  • The ability to log on as a service.
  • The ability to read and write registry keys in HKEY_LOCAL_MACHINE\Software\Microsoft\NotificationServices, HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services, and their subkeys.
  • Modify permission in the folder from which the event provider reads events, if the sample uses the standard FileSystemWatcher event provider (as do the Stock, Flight, and Weather sample applications provided with Notification Services).
  • Modify permission in the folder to which the delivery protocol writes notifications, if the sample uses the File delivery protocol (as do the Stock, Flight, and Weather sample applications).
  • Membership in the local Administrators group, if the sample uses the SMTP delivery protocol (as do the Flight, Weather, and Realtor sample applications).

If you must use SQL Server Authentication to connect to the Notification Services databases, provide a SQL Server user name and password for the NS$instance_name service when you run SetupSamples.cmd. The SQL Server user name and password are encrypted and stored in the registry. The SQL Server login account specified must be a user in the master database, so that the service has the access necessary to run extended stored procedures.

Important Microsoft strongly recommends that you specify a domain account for use by the NS$instance_name service instead of using SQL Server Authentication. Using a domain account allows you to use Windows Authentication, which provides better security features, such as secure validation and encryption of passwords, auditing, password expiration, minimum password length, and account lockout after multiple invalid login requests.

See Also

Notification Services Database Roles


Visual Studio .NET Build Command (NSControl Utility ) Account

 SQL Server Notification Services Books Online

Visual Studio .NET Build Command (NSControl Utility) Account

In Notification Services, the Microsoft Visual Studio .NET Build commands require an account to access the NSControl utility. They use NSControl to create the NS$instance_name service on the server, and to create and update the Notification Services databases.

This account must have permissions to create services and write to the registry, and so must be a member of the local Administrators group. In addition, you must ensure either that this account is a SQL Server login account, or that a separate SQL Server login account is also provided for its use. The SQL Server login account must be assigned to the sysadmin fixed server role.

See Also

Notification Services Database Roles


User Accounts

For any users who will be working with the programming samples provided as part of Notification Services, valid Windows accounts and SQL Server login accounts must be provided.

The user who runs SetupSamples.cmd to set up the samples must have a SQL Server login account that is a member of the SQL Server sysadmin fixed server role, or must be able to supply the user name and password of a login account that is a member of the SQL Server sysadmin fixed server role. The sysadmin permissions are required to add new database users to SQL Server, to add users to database roles, and to create and delete SQL Server databases.

Note The end user who runs the installation procedures for the Notification Services samples is set by SQL Server as the database owner (dbo) for each of the sample SQL Server databases that are created. The login name for the dbo user corresponds to the SQL Server login account for the end user.

See Also

Notification Services Database Roles


Configuring Visual Studio .NET

The programming samples provided as part of Notification Services make use of SQL Server client utilities, such as the osql utility. These utilities must be available on the local computer.

If you installed Microsoft Visual Studio .NET before installing SQL Server, the SQL Server utilities did not get registered with Visual Studio .NET. If this is the case, you must add the SQL Server client utilities location to the C++ path.

To register SQL Server client utilities

  1. In Visual Studio .NET, click the Tools menu, and then click Options.
  2. In the Options dialog box, expand Projects in the left pane, and then click VC++ Directories.
  3. In the Show directories for box, select Executable Files.
  4. In the Executable Directories pane, look for Install_location\Microsoft SQL Server\80\Tools\BINN.

    If this directory is not present, click the folder icon to add a new line to the list of directories, and then click the ellipsis button (...) at the end of the new line to browse to this directory.

  5. Click OK.


Setting Up and Removing Programming Samples

Setting up the sample applications provided as part of Notification Services involves assigning appropriate permissions in SQL Server to the required sample accounts, setting some system variables, and creating an Internet Information Services (IIS) virtual directory for the samples.

Note Before setting up the programming samples, verify that your system has the required software installed and the required accounts created. For more information, see Programming Sample Requirements.

Setting Up the Samples

You can accomplish all three setup tasks at once by running the SetupSamples.cmd script, which is located in the Samples directory (InstallPath\Microsoft SQL Server Notification Services\VersionNumber\Samples). You must run SetupSamples.cmd to configure the system for running the samples, even if you plan to use only one of the samples.

The SetupSamples.cmd script is available from the command line. To use it, open a command prompt window and navigate to the Samples directory. For more information about the SetupSamples.cmd script, see SetupSamples.cmd.

Removing the Samples

You can remove all the Notification Services samples at once by running the RemoveSamplesDB.cmd script, which is located in the Samples directory of the Notification Services installation directory.

The RemoveSamplesDB.cmd script is available from the command line. To use it, open a command prompt window and navigate to the Samples directory. For more information about this utility, see RemoveSamplesDB.cmd.


Changing Sample Reference Paths

If you have installed Notification Services to a non-default location, you must set the reference path to the Microsoft.SqlServer.NotificationServices.dll file in all projects except the AppDefinition project.

To set the sample reference paths manually

  1. In the Solution Explorer pane of Microsoft Visual Studio .NET, expand the project, expand the References folder, right-click Microsoft.SqlServer.NotificationServices, and then click Remove.
  2. Right-click the References folder again, and then click Add Reference.
  3. Click the ellipsis button (...), and then navigate to the InstallPath\Microsoft SQL Server Notification Services\VersionNumber\bin directory.
  4. Double-click Microsoft.SqlServer.NotificationServices.dll, and then click OK.


Configuring the Subscribe Project for Debugging

The Subscribe project can be configured so that your Web page code can be debugged in Microsoft Visual Studio .NET.

To configure the subscription management application project for debugging

  1. In the Solution Explorer pane of Visual Studio .NET, right-click the Subscribe project, and then click Properties.
  2. In the left pane, click Configuration Properties, and then select Debugging.
  3. In the right pane, do the following:
    • Under Debuggers, change Enable ASP.NET Debugging to True.
    • Under Start Action, change Debug Mode to URL.
    • Under Start Action, type http://localhost/nssamples/samplename/default.aspx for the Start URL value.
  4. Click OK.
  5. Right-click the Subscribe project, click Debug, and then select Start new instance to start the debugger.


Resolving Common Issues

The following table lists common errors that occur in the programming samples included with Notification Services, and presents recommended resolutions.

Error message | Action
InstallPath\Microsoft SQL Server Notification Services\VersionNumber\Samples\SampleApplication\Subscribe\Default.aspx.cs(19): The type or namespace name 'SqlServer' does not exist in the class or namespace 'Microsoft' (are you missing an assembly reference?). | Add the missing reference to Microsoft.SqlServer.NotificationServices.dll. For more information, see Changing Sample Reference Paths.
Error trying to run project: Unable to start debugging on the web server. The project is not configured to be debugged. | Click No when asked whether you want to disable debugging for Microsoft ASP.NET pages for this project. Open a command prompt window, and navigate to the Subscribe project directory for the given sample application. Run SetupSample.cmd to re-create the Internet Information Services (IIS) virtual directories.
Running the project requires setting an initial web page. | Right-click the Default.aspx file, and then click Set As Start Page.


Stock Sample

The Stock programming sample that is shipped with Notification Services provides both event-driven and scheduled subscriptions based on stock information. The scheduled subscription generates a digest notification containing portfolio information on a selected stock. This notification is delivered at a predefined time every day. The event-driven subscription generates a notification whenever a selected stock crosses a predefined threshold value.

Language

Microsoft ASP.NET and Microsoft C#

Notification Services Features
Event Class Features | Event chronicle table and rule.
Subscription Class Features | Multiple subscription classes, providing scheduled and event-driven subscriptions.
Notification Class Features | Multiple notification classes. One notification class uses digest delivery.
Event Providers | Notification Services file system watcher event provider. Independent WebEventCreator event provider.
Content Formatters | Notification Services XSLT content formatter.
Delivery Protocols | File delivery protocol. Custom HttpLogger delivery protocol, which uses the IHttpProtocolProvider interface.
Building the Sample

You can use the following steps to build the Stock application.

To build the Stock sample application

  1. In Microsoft Windows® Explorer, navigate to the Stock directory, and then open the Stock.sln solution file in Microsoft Visual Studio .NET.
  2. Right-click the AppDefinition project, and then click Build.

    This action creates the NS$StockInstance service and sets up the StockInstanceNSMain and StockInstanceStock databases.

  3. Right-click the Subscribe project, and then click Build.

    This creates the subscription management and event submission applications.

  4. Right-click the CustomDeliveryProtocol project, and then click Build.

    This creates the custom delivery protocol DLL.

  5. In Windows 2000, go to Control Panel, double-click Administrative Tools, double-click Services, right-click NS$StockInstance, and then click Start.

    –or–

    In Windows XP, go to Control Panel, double-click Performance and Maintenance, double-click Administrative Tools, double-click Services, right-click NS$StockInstance, and then click Start.

    –or–

    Open a command prompt window, and then type net start NS$StockInstance.

Sample Workflow

The following steps outline the way information is entered into and processed by the Stock sample application in order to create notifications.

  1. On the subscription management page, enter a stock symbol to be tracked. Clear the Include this stock in a daily summary check box, specify a trigger price for the stock, and then click Alerts Signup.

    This will create an event-driven subscription.

  2. Select the Include this stock in a daily summary check box, specify a time zone and time, and then click Alerts Signup.

    This will create a scheduled subscription.

  3. On the event submission page, submit stock price data for the stock you have entered.

    This page uses the WebEventCreator event provider to write the event data to the application database.

  4. The event chronicle rule adds and updates stock values in the chronicle table, so that each stock's highest value for the day is recorded
  5. For the event-driven notifications, the Notification Services generator processes the subscription event rule, which joins the event chronicle data with subscription data, based on the following conditions:
    • The stock price in the event chronicle table is greater than or equal to the stock price in the subscriptions table.
    • The stock symbol in the event chronicle table is equal to the stock symbol in the subscriptions table.
  6. For the scheduled notifications, the Notification Services generator processes the subscription scheduled rule at the time specified for the scheduled subscription. Subscription and event chronicle data is matched based on the stock symbol in the chronicle table matching the stock symbol in the subscription table. The sum of each stock value is generated to provide the notification information.
  7. A notification is created for each match found.
  8. The Notification Services distributor formats notifications using the Notification Services XSLT content formatter and the Application.xslt file.
  9. By default, the Notification Services distributor sends all notifications using the HttpLoggerChannel delivery channel, which uses the custom HttpLogger delivery protocol.

    HttpLogger posts the notification data to the URL specified in the HttpLoggerChannel delivery channel definition in the appConfig.xml file. The default URL is http://localhost/NSSamples/Stock/HttpLogger.aspx. The code for this page is available in Samples\Stock\Subscribe\HttpLogger.aspx.cs.

    Note You can test the HttpLogger.aspx page by loading it in your browser and clicking Test Post.

    You can change the subscriptions to use the File delivery protocol by editing the imgbtnAlertsSignup_Click method in Default.aspx.cs. If the File delivery protocol is used, the notifications are written to InstallPath\Microsoft Notification Services\VersionNumber\Samples\Stock\Test\Notifications\FileNotifications.txt.

    The sample code does not provide a method to update a subscriber's delivery information. Once a subscriber has been entered in the database you must remove that subscriber to update her delivery preference. The update functionality could be added to the user interface for a production application.

Testing the Sample

You can generate sample notifications by using the test data and the RunSample.cmd script. To do this, you can open a command prompt window, navigate to the specific sample subdirectory (InstallPath\Microsoft SQL Server Notification Services\VersionNumber\Samples\Stock), and then run the script. This action loads subscriber, subscription, and event data into the system; generates notifications based on it; and then formats the notifications and writes them to a text file. Some notifications are written to the HttpLogger.aspx page, and some are written to InstallPath\Microsoft Notification Services\VersionNumber\Samples\Stock\Test\FileNotifications.txt. The delivery of notifications using the HttpLogger fails if the CustomDeliveryProtocol project has not been built.

Removing the Sample

To remove the databases associated with the Stock application, open the Stock solution in Visual Studio .NET, right-click the AppDefinition project, and then click Clean.

To fully remove the instance, including the databases, IIS virtual directory, and service registration, you can use the RemoveSample.cmd script. For more information, see Setting Up and Removing Programming Samples.


Flight Sample

The Flight sample application that is shipped with Notification Services provides event-driven subscriptions. It sends a notification e-mail message to the end user when an airline flight between two specified locations is offered at or below the target price the user has indicated.

Language

Microsoft ASP.NET and Microsoft Visual Basic .NET

Notification Services Features
Event Class Features | Basic event class.
Subscription Class Features | Subscription class providing event-driven subscriptions.
Notification Class Features | Notification class uses digest delivery.
Event Providers | Notification Services FileSystemWatcher event provider.
Content Formatters | Notification Services XSLT content formatter.
Delivery Protocols | File delivery protocol. Simple Mail Transfer Protocol (SMTP) delivery protocol.
Building the Sample

You can use the following steps to build the Flight application.

To build the Flight sample application

  1. In Microsoft Windows® Explorer, navigate to the Flight directory, and then open the Flight.sln solution file in Microsoft Visual Studio .NET.
  2. Right-click the AppDefinition project, and then click Build.

    This action creates the NS$FlightInstance service and sets up the FlightInstanceNSMain and FlightInstanceFlight databases.

  3. Right-click the Subscribe project, and then click Build.

    This action creates the subscription management application.

  4. In Windows 2000, go to Control Panel, double-click Administrative Tools, double-click Services, right-click NS$FlightInstance, and then click Start.

    –or–

    In Windows XP, go to Control Panel, double-click Performance and Maintenance, double-click Administrative Tools, double-click Services, right-click NS$FlightInstance, and then click Start.

    –or–

    Open a command prompt window, and then type net start NS$FlightInstance.

Sample Workflow

The following steps outline the way information is entered into and processed by the Flight sample application in order to create notifications.

  1. Use the subscription management page to specify flight origin and destination information, a ticket price, and optionally an airline, following the directions provided on the page.

    This information will determine when a digest notification for the event-driven subscription will be generated.

  2. Copy EventData.xml from the Flight\Test directory to the Events subdirectory, which is monitored by a file system watcher event provider.
  3. The contents of the event file are read by the event provider and submitted to the sample application database.
  4. The Notification Services generator processes the subscription event rule, which joins the event data with subscription data, and creates notifications if the following conditions are met:
    • The event ticket price is less than the subscription ticket price.
    • The event departure airport equals the subscription departure airport.
    • The event arrival airport equals the subscription arrival airport.
    • The event airline equals the subscription airline (if specified).
  5. A notification is created for each match found.
  6. The Notification Services distributor formats notifications using the Notification Services XSLT content formatter and the Application.xslt file.
  7. The Notification Services distributor sends the notifications using the EmailChannel delivery channel, which uses the SMTP delivery protocol.

    In order to send email notifications, the Windows SMTP service must be configured to relay messages and it must be running. If the Windows SMTP service is not running or is not configured to relay messages, the notifications generated by the sample applications will be delivered to the \inetpub\mailroot\queue directory. Depending on the configuration of your SMTP service, the messages may appear in another folder under \inetpub\mailroot, such as \pickup or \badmail. For more information on configuring SMTP, please see Using SMTP for Outgoing Messages in the Microsoft MSDN® Library.

Testing the Sample

You can generate sample notifications by using the test data and the RunSample.cmd script. To do this, you can open a command prompt window, navigate to the specific sample subdirectory (InstallPath\Microsoft SQL Server Notification Services\VersionNumber\Samples\Flight), and then run the script. This action loads subscriber, subscription, and event data into the system; generates notifications based on it; and then formats the notifications and writes them to a text file. Because this sample uses both the File and SMTP delivery protocols, some of the notifications are sent to your SMTP service, and some are written to the InstallPath\Microsoft Notification Services\VersionNumber\Samples\Flight\Test\FileNotifications.txt file.

Removing the Sample

To remove the databases associated with the Flight application, open the Flight solution in Visual Studio .NET, right-click the AppDefinition project, and then click Clean.

To fully remove the instance, including the databases, IIS virtual directory, and service registration, you can use the RemoveSample.cmd script. For more information, see Setting Up and Removing Programming Samples.


Weather Sample

The Weather sample application that is shipped with Notification Services provides scheduled subscriptions. It sends a notification e-mail message containing the weather forecast to the subscriber at a specific time every morning.

Language

Microsoft ASP.NET and Microsoft C#

Notification Services Features
Event Class Features | Event chronicle table and rule.
Subscription Class Features | Subscription class providing scheduled subscriptions.
Notification Class Features | Notification class uses digest delivery.
Event Providers | Notification Services FileSystemWatcher event provider.
Content Formatters | Notification Services XSLT content formatter.
Delivery Protocols | File delivery protocol. Simple Mail Transfer Protocol (SMTP) delivery protocol.
Building the Sample

To build the Weather sample application, follow these steps:

To build the Weather sample application

  1. In Microsoft Windows® Explorer, navigate to the Weather directory, and then open the Weather.sln solution file in Microsoft Visual Studio .NET.
  2. Right-click the AppDefinition project, and then click Build.

    This action creates the NS$WeatherInstance service and sets up the WeatherInstanceNSMain and WeatherInstanceWeather databases.

  3. Right-click the Subscribe project and select Build.

    This action creates the subscription management application.

  4. In Windows 2000, go to Control Panel, double-click Administrative Tools, double-click Services, right-click NS$WeatherInstance, and then click Start.

    –or–

    In Windows XP, go to Control Panel, double-click Performance and Maintenance, double-click Administrative Tools, double-click Services, right-click NS$WeatherInstance, and then click Start.

    –or–

    Open a command prompt window, and then type net start NS$WeatherInstance.

Sample Workflow

The following steps outline the way information is entered into and processed by the Weather sample application in order to create notifications.

  1. Use the subscription management page to specify the city for which you want to receive a forecast, following the directions provided on the page. Specify delivery time and frequency.

    This information will determine when a digest notification for the scheduled subscription will be generated.

  2. Copy EventData.xml from the Weather\Test directory into the Events subdirectory.
  3. The contents of the event file are read by the event provider and submitted to the sample application database.
  4. The event chronicle rule adds new forecast information to the event chronicle table.
  5. When the time for the scheduled subscription arrives, the Notification Services generator processes the subscription scheduled rule. Subscription and event chronicle data is matched based on the city information.
  6. A notification is created for each match found.
  7. The Notification Services distributor formats notifications using the XSLT content formatter and the Application.xslt file.
  8. The Notification Services distributor sends the notifications using the EmailChannel delivery channel, which uses the SMTP delivery protocol.

    In order to send email notifications, the Windows SMTP service must be configured to relay messages and it must be running. If the Windows SMTP service is not running or is not configured to relay messages, the notifications generated by the sample applications will be delivered to the \inetpub\mailroot\queue directory. Depending on the configuration of your SMTP service, the messages may appear in another folder under \inetpub\mailroot, such as \pickup or \badmail. For more information on configuring SMTP, please see Using SMTP for Outgoing Messages in the Microsoft MSDN® Library.

Testing the Sample

You can generate sample notifications by using the test data and the RunSample.cmd script. To do this, you can open a command prompt window, navigate to the specific sample subdirectory (InstallPath\Microsoft SQL Server Notification Services\VersionNumber\Samples\Weather), and then run the script. This action loads subscriber, subscription, and event data into the system; generates notifications based on it; and then formats the notifications. Because this sample uses both the File and SMTP delivery protocols, some of the notifications are sent to your SMTP service, and some are written to the InstallPath\Microsoft Notification Services\VersionNumber\Samples\Weather\Test\FileNotifications.txt file.

Removing the Sample

To remove the databases associated with the Weather application, open the Weather solution in Visual Studio .NET, right-click the AppDefinition project, and then select Clean.

To fully remove the instance, including the databases, IIS virtual directory, and service registration, you can use the RemoveSample.cmd script. For more information, see Setting Up and Removing Programming Samples.


Realtor Sample

The Realtor sample application that is shipped with Notification Services provides event-driven subscriptions. It sends a notification e-mail message when a house goes on the market that has specified features and falls within the target price range.

Language

Microsoft ASP.NET and Microsoft C#

Notification Services Features
Event Class Features | Basic event class.
Subscription Class Features | Subscription class providing event-driven subscriptions.
Notification Class Features | Notification class uses multicast delivery. (Multicast is available only in Notification Services Enterprise Edition.)
Event Providers | Event stored procedures run by SQL trigger in an external database.
Content Formatters | Notification Services XSLT content formatter.
Delivery Protocols | Simple Mail Transfer Protocol (SMTP) delivery protocol.
Building the Sample

To build the Realtor sample application, follow these steps:

To build the Realtor sample application

  1. In Microsoft Windows Explorer, navigate to the Realtor directory and open the Realtor.sln solution file in Microsoft Visual Studio .NET.
  2. Right-click the AppDefinition project, and then click Build.

    This action creates the NS$RealtorInstance service and sets up the RealtorInstanceNSMain and RealtorInstanceRealtor databases.

  3. Right-click the Subscribe project, and then click Build.

    This action creates the subscription management and event submission applications.

  4. In Windows 2000, go to Control Panel, double-click Administrative Tools, double-click Services, right-click NS$RealtorInstance, and then click Start.

    –or–

    In Windows XP, go to Control Panel, double-click Performance and Maintenance, double-click Administrative Tools, double-click Services, right-click NS$RealtorInstance, and then click Start.

    –or–

    Open a command prompt window, and then type net start NS$RealtorInstance.

Sample Workflow

The following steps outline the way information is entered into and processed by the Realtor sample application in order to create notifications.

  1. Use the subscription management page to enter information about the house features that interest you, following the directions provided on the page.

    This information will determine when a notification for the event-driven subscription will be generated.

  2. Open SQL Query Analyzer, type in this Transact-SQL statement, and run it:
    INSERT INTO RealtorDB..Listings values (N'2828 28th Ave SE',
N'BusyKids', 4, 3, 350000, N'A cute house with a great view. Contact
Jamie Reding or attend the open house on Sunday.')

    Running this query will insert sample data into the database that matches the subscription you have entered per the directions on the subscription management application page.

  3. The Notification Services generator processes the subscription event rule, which joins the event data with subscription data, and creates notifications if the following conditions are met:
    • The house price is equal to or less than the subscription specified price.
    • The event listing ID is equal to the subscription listing ID.
    • The event school district is equal to the subscription school district.
    • The event number of bedrooms is equal to the subscription number of bedrooms.
    • The event number of bathrooms is equal to the subscription number of bathrooms.
  4. A notification is created for each match found.
  5. The Notification Services distributor formats notifications using the Notification Services XSLT content formatter and the RealtorInfo.xslt file.
  6. The Notification Services distributor sends the notifications using the EmailChannel delivery channel, which uses the SMTP delivery protocol.

    In order to send email notifications, the Windows SMTP service must be configured to relay messages and it must be running. If the Windows SMTP service is not running or is not configured to relay messages, the notifications generated by the sample applications will be delivered to the \inetpub\mailroot\queue directory. Depending on the configuration of your SMTP service, the messages may appear in another folder under \inetpub\mailroot, such as \pickup or \badmail. For more information on configuring SMTP, please see Using SMTP for Outgoing Messages in the Microsoft MSDN® Library.

Testing the Sample

You can generate sample notifications by using the test data and the RunSample.cmd script. To do this, you can open a command prompt window, navigate to the specific sample subdirectory (InstallPath\Microsoft SQL Server Notification Services\VersionNumber\Samples\Realtor), and then run the script. This action loads subscriber, subscription, and event data into the system; generates notifications based on it; and then formats the notifications and writes them to a text file. The notifications are sent to the SMTP service.

The Realtor sample application uses a trigger on an external database to enter events into the application database. That trigger is fired when you perform an insert using the osql utility. If you are not using Windows Authentication to access SQL Server (that is, if you specified an account for SqlServerAdminName when running the SetupSamples.cmd script), you will be prompted for the SqlServerAdminName account password while RunSample.cmd is running.

Removing the Sample

To remove the databases associated with the Realtor application, open the Realtor solution in Visual Studio .NET, right-click the AppDefinition project, and then click Clean.

To fully remove the instance, including the databases, IIS virtual directory, and service registration, you can use the RemoveSample.cmd script. For more information, see Setting Up and Removing Programming Samples.


Deploying and Administering Notification Services

A Microsoft® SQL Server™ Notification Services administrator performs tasks related to running notification applications in a production environment. These tasks include the following:

  • Plan the system configuration for the instances of Notification Services, the databases, and any subscription management applications. This typically requires you to answer questions like "Will Notifications Services be located on the same server as the SQL Server database engine?" and "What availability configuration will the instances of Notification Services use?"
  • Install Notification Services on all servers that will host the Notification Services applications and databases, and on any server that will host a subscription management application.
  • Deploy Notification Services applications by configuring instances that host the applications. For each instance, you will create an XML configuration file and use the NSControl command prompt utility to create, register, and enable the instance.

    Depending on the application, you might also need to load subscription data into the instance and application databases.

    After the instance is configured, start the NS$instance_name service for the instance to start the application.

  • After the applications are deployed, you must monitor the transition of data through the system, from events coming into the system, to notification generation, to notification delivery. Notification Services provides stored procedures, performance counters, and event log messages for monitoring system activity.
  • You also must manage the data in the instance and application databases. This requires you to back up the instance and application databases, ensure that vacuuming is effectively removing stale data, and update instances and applications as necessary.

The topics that the Administering Notification Services section covers are described in the following table.

Topic | Description
Planning a Notification Services System | Describes the tasks involved in planning a Notification Services system and shows possible hardware configurations for scaling out an application.
Configuring and Deploying Instances | Describes how to configure and deploy an instance of Notification Services.
Managing Instances and Applications | Describes the day-to-day tasks for administering instances and applications, including backup and restore tasks, vacuuming, and methods for managing availability.
Managing Services | Describes how to configure, start, and stop the NS$instance_name service that runs an instance of Notifications Services.
Managing Security | Discusses system security and security requirements.
Monitoring Performance and Activity | Documents the performance counters and reports.


Planning a Notification Services System

To plan a deployment of Notification Services, you must determine the availability requirements of the applications hosted by the instance, and the hardware required to support the applications. This section contains information about typical deployment hardware configurations and other considerations for the system that supports your notification applications.

The topics that this section covers are described in the following table.

Topic | Description
Hardware Configurations | Illustrates common hardware configurations, and discusses the benefits of each scenario.
Notification Services Considerations | Provides information to help you plan your Notification Services applications.
Database Considerations | Provides information to help you plan your database system.
Database Resource Planning | Provides advice to help you estimate database sizes.
Subscription Management Application Considerations | Provides information to help you plan subscription management applications.


Hardware Configurations

Hardware configuration depends on three factors: how much processing power is required, how much delivery throughput is needed, and where your servers are located. If you have a small notification application that is completely located behind a firewall, you might host Notification Services, databases, and subscription management on one server. However most medium to large applications benefit from multiple servers. Very large applications can be scaled out across several servers, and applications that require very high availability can use failover clustering.

Sample Configurations

Because Notification Services can be deployed in several ways, it helps to look at some sample hardware configurations. This section illustrates several hardware configurations: single server, remote database server, scale out, and clustering for high availability.

The topics that this section covers are described in the following table.

Topic | Description
Single-Server Configurations | Shows the simplest configuration for a Notification Services system.
Remote Database Server Configuration | Shows a common configuration that has Notification Services on one server and the databases on a second server.
Scale-Out Configurations | Shows how an application can be scaled out to provide more processing power for receiving events, generating notifications, and formatting and delivering notifications.
High-Availability Configurations | Shows how availability can be managed for databases and for the Notification Services engine.


Single-Server Configurations

For development systems and for small to medium applications that do not require the availability provided by clustering, you can collocate Notification Services and the database engine on a single server. If you are not placing the subscription management applications on the Internet, the subscription management applications also can be installed on this server.

Single-server installations are simple to configure; however, Microsoft does not recommend hosting Notification Services, the database engine, and potentially a Web server on a single server for critical systems or for systems expected to support high volumes of notifications.

The recommended number of CPUs and amount of disk space depend on the processing and storage requirements of the system. A development system might have only one CPU and enough disk space for testing; a production server should have two to four CPUs and enough disk space to store event, notification, subscription, and subscriber data at peak periods. Additionally, in production, the database files, log files, and tempdb database should all be located on separate physical disks.

It is critical to monitor the CPU, memory and disk usage of production servers hosting Notification Services or SQL Server to watch for bottlenecks or contention problems. If the single server cannot support processing requirements, consider using the remote database server configuration. For more information, see Remote Database Server Configuration.

See Also

Database Considerations

Database Resource Planning

Hardware Configurations

Notification Services Considerations

Single-Server Deployment (SQL Server Authentication)

Single-Server Deployment (Windows Authentication)


Remote Database Server Configuration

A typical configuration for medium to large Notification Services applications uses one server to host the Notification Services engine and another server to host the Notification Services instance and application databases. The following illustration shows an example of a remote database server configuration.

The servers that host the databases and Notification Services engine each do a part of the processing work. The server that hosts the Notification Services engine collects events and formats and distributes notifications; the database server generates notifications. The two servers require about the same amount of processing power. However, the server that hosts the database engine needs much more disk space because this server contains event, subscriber, subscription, and notification data.

The number of CPUs and amount of disk space depend on the processing and storage requirements of the system. Each Notification Services server and the database server should have two to four CPUs. The database server should have enough disk space to store event, notification, subscription, and subscriber data at peak periods. Additionally, the database files, log files, and tempdb database should all be located on separate physical disks.

See Also

Database Considerations

Database Resource Planning

Hardware Configurations

Notification Services Considerations

Remote Database Server Deployment (Windows Authentication)

Remote Database Server (SQL Server Authentication)


Scale-Out Configurations

If a single server cannot handle the number of notifications produced by an instance of Notification Services, you can scale out the Notification Services engine. The following illustration shows a system that uses three servers for the Notification Services engine: one server hosts the generator and event collection components, and two other servers host the distributor components.

Note that the generator is located with the event provider host. This is because generator process does not entail significant CPU or disk overhead; most of the generator work is performed on the database server. The generator can be hosted on another server if event collection requires its own server.

Note The generator for each application can be hosted on its own server, but each application uses only a single generator.

The recommended number of CPUs and the amount of disk space depend on the processing and storage requirements of the system. Each Notification Services server and the database server should have two to four CPUs. The database server should have enough disk space to store event, notification, subscription, and subscriber data during peak periods. Additionally, the database files, log files, and tempdb database should be located on separate physical disks.

Distributor Scale-Out

The distributor of an application that sends many notifications can fall behind because formatting notifications is processor intensive, and notification distribution requires adequate bandwidth to the systems that deliver notifications. To minimize this problem you can scale the distributor across multiple servers by defining multiple distributors in the application definition file (ADF). The distributors automatically pick up available distribution work items as notification batches become available.

Event Provider Host Scale Out

Depending on the number of events your applications collect, you may need to run the event provider host on more than one server. Event collection scale-out is not as common as distributor scale out.

See Also

Database Considerations

Database Resource Planning

Hardware Configurations

Notification Services Considerations

Scale-Out Deployment (SQL Server Authentication)

Scale-Out Deployment (Windows Authentication)


High-Availability Configurations

High-availability configurations are similar to other configurations of Notification Services, except that they use clustering.

A failover cluster is a group of independent servers running Microsoft Cluster Service and working collectively as a single system. The purpose of a failover cluster is to keep applications running during server failures and planned outages. If one of the servers in the cluster becomes unavailable, resources and applications move to another available cluster node.

For an effective Notification Services clustering solution, you must cluster the SQL Server database engine and the Notification Services engine.

The first failover clustering example shows the clustered version of a single-server configuration. Notification Services and the databases are on the same server. If one server fails, the other server picks up all processing. External applications, such as subscription management applications, connect to a virtual server name that represents the cluster.

The second failover clustering example shows the clustered version of the remote database configuration. In this example, the SQL Server data engine uses a two-server failover cluster, and Notification Services also uses a two-server failover cluster. External applications, such as subscription management applications, connect to SQL Server using the virtual name for the SQL Server failover cluster.

See Also

Database Considerations

Database Resource Planning

Hardware Configurations

Notification Services Considerations


Notification Services Considerations

The hardware needed for the each system at peak load periods is critical in planning the system that hosts the Notification Services engine. The processing and disk requirements of each part of the system are also important.

Peak Load Periods

Plan your hardware configuration based on peak load periods. For example, if a traffic reporting application supports scheduled subscriptions, and most users want traffic updates between 7:00 A.M. and 9:00 A.M. and between 4:00 P.M. and 6:00 P.M., you need to plan the system based on these periods, including peaks within these periods, not 24-hour averages.

Hardware Usage Patterns

When planning the servers that host your notification applications and databases, consider the following:

  • Notification generation is disk intensive, requiring heavy use of tempdb. Because generation occurs on the database server, the disk subsystem of the server that hosts the databases typically limits how many notifications an application can generate.

    Therefore, you can improve the performance of SQL Server by using fast disk drives served by high-performance controllers. Adding more storage capacity may increase notification generation capacity, but using fast drives with fast controllers will significantly improve performance.

  • Notification delivery is usually limited by processing power and delivery bandwidth. Formatting notifications requires ample processing power, and delivering notifications requires adequate bandwidth to the systems that deliver notifications.

See Also

Application Settings

Planning a Notification Services System


Database Considerations

Notification Services databases are created when you deploy an instance of Notification Services. Other than defining database parameters in the configuration file and the application definition file (ADF), you do not configure databases; however, you must configure SQL Server properly for optimal performance. Use the following guidelines when configuring SQL Server.

Database Recommendations

For optimal performance, security, and recoverability, Microsoft makes the following recommendations for Notification Services databases.

Log Files

Processing events and notifications creates high activity in log files. This activity can decrease read and write times for other operations, potentially hurting the performance of the entire system. To optimize performance, put log files on a dedicated physical disk using the <LogFile> element in the configuration file and ADFs.

tempdb

Notification Services makes extensive use of the tempdb database. For example, every time events are matched to subscriptions, SQL Server creates temporary tables. Because tempdb is critical and is heavily used, it is important to minimize resizing by defining this database with an adequate initial size and to reduce resource contention by placing it on a separate physical disk.

The tempdb database is re-created at its initial size each time SQL Server starts. If tempdb has an initial size that is too small and the database is set to autogrow, the autogrow process will use more system resources than during normal operation, which can impair system performance. You can avoid this overhead by using ALTER DATABASE to increase the initial size of tempdb and to increase the autogrow percentage.

For more information, see "Optimizing tempdb Performance" in SQL Server Books Online.

Indexes

Indexes are critical for optimal Notification Services performance. First, indexes can greatly improve the performance of joins. Second, once an event and subscription match occurs, data must be retrieved from other tables to generate the actual notification with delivery instructions. Indexes can help SQL Server retrieve this data faster.

When Notification Services databases are created, indexes should be defined in the ADF for most tables. However, additional indexes may enhance the performance of those queries.

To define additional indexes, you can examine the Transact-SQL code defined in the application ADFs, and either create your own indexes or use the SQL Server Index Tuning Wizard, which suggests indexes.

For more information, see "Designing an Index" in SQL Server Books Online.

Database Recovery Model

To ensure that data is not lost, back up all Notification Services databases frequently using the Full Recovery model. This allows you to create a complete database backup periodically, and then create differential and transaction log backups as required.

To ensure that the transaction log does not fill, back up the database and log files on a frequent, regular schedule. For more information about database backups, see Backing Up and Recovering Notification Services.

You can also monitor database and transaction log files using System Monitor, a part of the Microsoft Windows Performance tool. For example, the SQL Server: Databases performance object contains the Percent Log Used performance counter to monitor how full the transaction log is. For more information on SQL Server performance objects, see "Using SQL Server Objects" in SQL Server Books Online.

User Connections

Connections are a critical resource. Application data is stored in SQL Server databases, and the processing of events requires the applications to request and receive data from SQL Server; if there are not enough connections available, errors can occur.

Microsoft recommends setting the Maximum Concurrent User Connections value to zero, meaning that the number of connections is limited only by the SQL Server maximum. For more information, see "user connections Option" in SQL Server Books Online.

Database Authentication

Notification Services supports Windows Authentication as well as SQL Server Authentication; it does not require SQL Server Authentication for any functionality. Windows Authentication has certain benefits that make it superior to SQL Server Authentication in most applications, such as secure Authentication, encryption of passwords, auditing, password expiration, minimum password length, and account lockout after multiple invalid login requests.

For these reasons, Microsoft strongly recommends that you use Windows Authentication. For more information about security configuration, see Managing Security.

If you must use SQL Server Authentication, you must specify a SQL Server user name and password to be used by the NS$instance_name service when you register the instance of Notification Services. For more information, see Registering and Unregistering an Instance.

See Also

Database Resource Planning

Defining Application Database Information

Defining the Instance Database

Planning a Notification Services System


Database Resource Planning

When you initially create your instance and application databases, you should define the databases with adequate file sizes in the configuration file and application definition files (ADFs). Generous initial file sizes and adequate disk space reduce the chance that the databases will run out of space, which causes databases to resize (temporarily degrading performance) and which can even cause an application to stop processing data.

The adequate file sizes for your databases depend on the estimated number of subscribers, subscriptions, events, and notifications that the instance and application will support. Use the following guidelines to plan database sizes.

Application Database Sizes

Each application database stores subscriptions, events, notifications, application status information, possibly historical data in the form of chronicles, and metadata about the application.

Event and notification data is removed according to the schedule defined by the <Vacuum> node of the ADF. In this node, the developer also specifies a retention age for data. Use the combination of retention age and vacuuming schedule to estimate how much event and notification data will collect in the application database.

Once you determine how much event and notification data will accumulate in the database before the vacuuming process removes the data, you can use the SQL Server database sizing methods to estimate the size of the application database.

To plan the database size for an application, gather the following information:

  • The estimated number of events that will be collected during peak periods before the events are removed by the vacuuming process, and the size of each event row as determined by the event class fields in the ADF.
  • The estimated total number of subscriptions that you expect for the application, and the size of each subscription row as determined by the subscription class fields in the ADF.
  • The estimated number of notifications generated before the notifications are removed by the vacuuming process. If using distributor logging, double the number of notifications. Use the notification class fields in the ADF to determine the size of each notification row.
  • The amount of metadata. Application databases typically contain 5 to 10 MB of metadata.
  • Chronicle tables and indexes. These objects add to the size of the database.

Application database size estimates can be difficult to determine because of indexes and application settings. For more information on estimating database sizes, see "Estimating the Size of a Database" in SQL Server Books Online.

Instance Database Size

The data in an instance database is much more stable than data in application databases. If you can estimate the number of subscribers and the number of subscriber devices, you should be able to estimate the instance database size. To estimate the size, gather the following information:

  • The total number of expected subscribers for all applications hosted by the instance.
  • The size of each subscriber row.
  • The total number of expected subscriber devices.
  • Metadata. Estimate the amount of metadata for your instance at 2 MB.

The following equation can be used to estimate the instance database size:

instance database size =
2 * ((number_of_subscribers * subscriber_row_size (in bytes))
+ (number_of_subscriber_devices * 200 bytes)
+ 2 MB metadata )

Log File Sizes

The application database is typically a very active database, with many transactions. This activity can cause the transaction log to grow quickly. You should therefore start with a log file size equal to 25 percent of the initial application database size. You can use the same estimate for the instance database log file. If the log is truncated during log file backups or during a checkpoint, the log maintains a reasonable size. For more information, see "Truncating the Transaction Log" in SQL Server Books Online.

See Also

Database Considerations

Defining Application Database Information

Defining the Instance Database

Planning a Notification Services System


Subscription Management Application Considerations

Subscription management applications are external to Notification Services but use the Notification Services subscription management objects to create and modify subscriber and subscription data. A subscription management application can be a Web application or a Microsoft Windows application. The only requirement is that it must use the subscription management objects provided with Notification Services.

Not all notification applications use subscription management applications. For example, some enterprise applications contain a relatively unchanging set of subscribers and subscriptions, making a separate application unnecessary.

The sample applications provided with Notification Services, as well as the deployment scenarios, show the use of Microsoft ASP.NET-based subscription management applications.

Location

A subscription management application can be located on the database server or on a separate server. The configuration of the application varies according to the location. If your subscription management application is for internal use only, such as an intranet-based Web page, locating the application on the database server might be an adequate solution. However, do not put the subscription management application on the database server if the application is publicly available: you should never put your databases on Internet servers.

Security

The subscription management application must have access to the instance and application databases in order to read and write subscriber and subscription data. To connect to SQL Server, the application can use Windows Authentication or SQL Server Authentication. Microsoft recommends Windows Authentication because it is more secure and easier to manage.

The optimal security configuration for the subscription management application depends on the location of the application and the security model. For more information, see Subscription Management Application Deployment Scenarios.

See Also

Developing Subscription Management Applications

Planning a Notification Services System


Configuring and Deploying Instances

To deploy one or more Notification Services applications, you must first configure an instance of Notification Services to host the application, and then deploy the instance. This section describes how to configure and deploy instances.

The topics that this section covers are described in the following table.

Topic | Description
Creating a Configuration File | Explains the purpose of a configuration file and helps you create one.
Deploying an Instance | Provides the basic steps for deploying an instance of Notification Services.
Notification Services Deployment Scenarios | Contains step-by-step instructions for deploying Notification Services instances using different system configurations and security models.
Subscription Management Application Deployment Scenarios | Contains step-by-step instructions for deploying Microsoft ASP.NET-based subscription management applications locally or remotely using Microsoft Windows® Authentication or SQL Server Authentication.
Providing Access to the Notification Services Assembly and Localized Resource Files | Explains how to provide access to the Notification Services assembly and localized resource files for an Microsoft ASP.NET-based application.


Creating a Configuration File

Each instance of Notification Services is defined by a configuration file. This file contains information about the instance, general information about the instance's applications with pointers to the application definitions, and information about delivery channels and protocols. When you deploy the instance, the data in the configuration file is used to create an instance database.

The topics that this section covers are described in the following table.

Topic | Description
Specifying File Version and History | Explains how to use the <Version> and <History> nodes of the configuration file.
Specifying the Instance Name | Explains how to use the <InstanceName> element of the configuration file to provide a name for the instance.
Specifying the Database System Name | Explains how to use the <SqlServerSystem> element of the configuration file to specify which instance of SQL Server hosts the Notification Services instance and application databases.
Defining the Instance Database | Explains how to use the <Database> node of the configuration file to configure the instance database.
Configuring Applications | Explains how to use the <Applications> node of the configuration file to define the applications hosted by the instance.
Configuring Protocols | Explains how to use the <Protocols> node of the configuration file to define custom protocols used by delivery channels.
Configuring Delivery Channels | Explains how to use the <DeliveryChannels> node of the configuration file to define one or more delivery channels used to deliver notifications
Configuring Argument Encryption | Explains how to use the <EncryptArguments> node to encrypt event provider and delivery channel arguments that are stored in databases.
Configuration File Parameters | Explains how to use the <ParameterDefaults> node of the configuration file to specify values for configuration file parameters.

See Also

Application Definition File Reference

Configuration File Reference

Configuration File Samples


Specifying File Version and History

Each instance of Notification Services has a configuration file. This file contains information about the instance, general information about the instance's applications, and information about delivery channels and protocols.

The configuration file contains a <Version> node for specifying the configuration file version number and a <History> node for keeping a history of your configuration file. The <Version> and <History> nodes of the configuration file are not required.

Keep the following in mind for these nodes:

  • When you create or update an instance, Notification Services adds a row to the NSVersionInfo table that contains the version number from the <Version> node of the configuration file. If the version number is missing, Notification Services uses the last version number from the database. If no version is available in the database, Notification Services enters 0.0.0.0.
  • History information is not added to the database and is not used by Notification Services. You can use the history information for your own purposes, or you can omit the <History> node.

For more information and examples, see <Version> Node and <History> Node.

See Also

Configuration File Samples

Creating a Configuration File


Specifying the Instance Name

Each instance of Notification Services has a configuration file. This file contains information about the instance, general information about the instance's applications, and information about delivery channels and protocols.

Within the configuration file, you must specify a unique name for the instance using the <InstanceName> element. This name is used for the following objects:

  • The instance database is named instance_name NSMain.
  • The application database names are a concatenation of instance_name and application_name. (The application name is defined in the <Application> node.)
  • The Windows service that runs the instance of Notification Services is named NS$instance_name.

Because the instance name is used by these objects, it must follow naming conventions for all of them:

  • A service name cannot contain quotation marks (double quotes).
  • SQL Server object names are limited to 128 characters.
  • SQL Server object names must follow the naming rules for regular identifiers. For more information, see "Using Identifiers" in SQL Server Books Online.

    Important Do not use case to make an instance name unique; Notification Services instance names are not case sensitive. For example, Notification Services does not distinguish between MyInstance and myinstance.

For more information and examples, see <InstanceName> Element.

Naming Recommendations

Since the instance name is used for several objects, and the database names are a concatenation of the instance name and "NSMain" or the application name, it is best to keep the instance name short, and to name the instance based on unchanging entities. For example, you might want to name the instance according to a target audience, a functional unit of your company, or a product.

It is best to avoid using the names of organization units (which can change frequently), an application, or the server on which the instance is running.

A good instance name is something short and self-explanatory like Broker or Internet01. You can then give each application a short and self-explanatory name, and use meaningful names for databases and objects. If you name your instance Broker and your application Stocks, for example, your instance database is named BrokerNSMain, and your application database is named BrokerStocks. If you add an application named Bonds, the application database name is BrokerBonds.

See Also

Configuration File Samples

Creating a Configuration File


Specifying the Database System Name

Each instance of Notification Services has a configuration file. This file contains information about the instance, general information about the instance's applications, and information about delivery channels and protocols.

Within the configuration file, you must use the <SqlServerSystem> element to specify which instance of SQL Server 2000 stores instance and application data.

For a default instance of SQL Server, the <SqlServerSystem> value is simply the name of the computer that hosts the SQL Server 2000 databases. For a named instance of SQL Server, the <SqlServerSystem> value must be in the form computer\instance_name.

For small to medium notification applications, Notification Services and the database engine might be located on the same computer. For larger applications, the database engine is typically on a remote server.

For more information and examples, see <SqlServerSystem> Element.

See Also

Configuration File Samples

Creating a Configuration File

Deployment Scenarios

Hardware Configurations


Defining the Instance Database

Each instance of Notification Services has a configuration file. This file contains information about the instance, general information about the instance's applications, and information about delivery channels and protocols.

Within the configuration file, you can define properties of the instance database and log files using the <Database> node.

The <Database> node is optional. However, if you do not specify database properties, the database engine creates the instance database using the model database as a template. Unless you have customized the model database, these database settings might not provide the best performance for your particular situation.

The <Database> node uses the following structure:

<Database>
   <NamedFileGroup>
      <FileGroupName>
      <FileSpec>
         <LogicalName>
         <FileName>
         <Size>
         <MaxSize>
         <GrowthIncrement>
   <LogFile>
      <LogicalName>
      <FileName>
      <Size>
      <MaxSize>
      <GrowthIncrement>
   <DefaultFileGroup>
   <CollationName>

The nodes and elements of the <Database> node are discussed in the following sections.

Filegroups and Database Files

In the <NamedFileGroup> node of the <Database> node you can define one or more filegroups for the instance database files and then specify the properties of one or more database files per filegroup.

It is best to locate the instance database (and application databases) on a separate physical disk from the tempdb database and the log files. Use the <FileName> element to specify the location of the instance database file. For more database recommendations, see Database Considerations.

For more information about this node, see <NamedFileGroup> Node. For more information about using database files and filegroups, see "Files and Filegroups" in SQL Server Books Online.

Log Files

In the <LogFile> node of the <Database> node you can define one or more log files for the instance transaction log. The transaction log is a serial record of all modifications that have occurred in the database as well as the transaction that performed each modification.

The transaction log is critical to database operation and recovery. For optimal performance, place the transaction log on a separate physical disk from the database files and the tempdb database. Use the <FileName> element to specify the location of the transaction log file. For more recommendations, see Database Considerations.

Default File Group

At any time, exactly one filegroup is designated as the default filegroup. When objects are created in the database without an assigned filegroup, they are assigned to this filegroup. Initially, the PRIMARY filegroup is the default filegroup.

You can use the <DefaultFileGroup> element to specify one of the <FileGroupName> values as the default filegroup.

For more information, see "Default Filegroups" in SQL Server Books Online.

Collation Name

If your instance and application databases must use a different collation from the default collation for the instance of SQL Server, specify the collation name using the <CollationName> element. The instance database and the databases for all applications hosted by that instance must use the same collation.

For more information, see <CollationName> Element.

See Also

ADF <Database> Node

Configuration File <Database> Node

Configuration File Samples

Creating a Configuration File


Configuring Applications

Each instance of Notification Services has a configuration file. This file contains information about the instance, general information about the instance's applications, and information about delivery channels and protocols.

In the <Applications> section of the configuration file, specify which notification applications are hosted by the instance. You can specify one or more applications.

The <Applications> node is a container for all <Application> nodes. Each <Application> element has a set of child elements that define application settings, such as the application name, a base directory path that points to application files, and application parameters that are passed into the application definition file.

For more information and examples, see <Applications> Node and <Application> Node.

See Also

Configuration File Samples

Creating a Configuration File


Configuring Protocols

Each instance of Notification Services has a configuration file. This file contains information about the instance, general information about the instance's applications, and information about delivery channels and protocols.

Within the configuration file, you can use the <Protocols> node to specify custom protocols supported by the instance. A protocol is a set of rules that endpoints use to communicate with each other. Notification Services supplies two standard protocols: SMTP and File. If applications use these protocols, you do not need to define the protocols in the <Protocols> section of the configuration file.

If an application uses one or more custom protocols, you must include information about each protocol in the <Protocols> node. If you do not know whether the application uses custom protocols, look at the <Protocols> elements in the application definition file.

Each custom protocol should have a name, a class name, and an assembly name.

For more information, see <Protocols> Node and <Protocol> Node.

Note To use the Internet Information Services (IIS) SMTP delivery protocol, which is used in the Flight, Weather, and Realtor sample applications, the account that the NS$instance_name service runs under must be a member of the local Administrators group. For more information, see <Protocol> Node.

See Also

Configuration File Samples

Creating a Configuration File

Developing a Custom Delivery Protocol


Configuring Delivery Channels

Each instance of Notification Services has a configuration file. This file contains information about the instance, general information about the instance's applications, and information about delivery channels and protocols.

Within the configuration file, you must use the <DeliveryChannels> node to specify one or more delivery channels. A delivery channel is an instance of a delivery protocol. The <DeliveryChannel> node that defines a single delivery channel can provide information used to deliver notifications, such as server names, user names, and passwords.

The structure of the <DeliveryChannels> node looks like this:

<DeliveryChannels>
   <DeliveryChannel>
      <DeliveryChannelName>
      <ProtocolName>
      <Arguments>

Important Because of the SMTP implementation used by the Microsoft .NET Framework, you can define only one SMTP delivery channel per instance. If you define two SMTP delivery channels, notifications might go to the wrong SMTP servers.

Note The .NET Framework implementation of SMTP does not support user names and passwords.

When a subscriber creates a subscription, the subscription is associated with a delivery channel. When a notification is delivered, the notification is sent via the selected delivery channel using the protocol specified for that delivery channel.

For example, the subscription management application might use a subscriber device named "E-mail." When the subscriber selects "E-mail" from a dialog box and enters an e-mail address, the subscription management application assigns delivery channel Email01 to the subscription and then writes the information about the subscriber device (e-mail), address, and delivery channel to the instance database.

The definition of the Email01 delivery channel, using the IIS SMTP protocol, looks like this:

<DeliveryChannels>
   <DeliveryChannel>
      <DeliveryChannelName>Email01</DeliveryChannelName>
      <ProtocolName>SMTP</ProtocolName>
   </DeliveryChannel>
</DeliveryChannels>

For more information, see <DeliveryChannels> Node and <DeliveryChannel> Node.

See Also

Configuration File Samples

Creating a Configuration File

Developing a Custom Delivery Protocol

Standard Delivery Protocols


Configuring Argument Encryption

Each instance of Notification Services has a configuration file. This file contains information about the instance, general information about the instance's applications, and information about delivery channels and protocols.

Within the configuration file, you can use the <EncryptArguments> element to encrypt arguments for delivery channels and event providers that are stored in the instance database and application databases.

Delivery channel arguments and event provider arguments may contain sensitive data, such as a password for a delivery channel. Encryption makes it difficult for any user with access to the databases to view this data.

You can turn argument encryption on by setting the value in the <EncryptArguments> element to true. (By default, the value is false.) If you turn on argument encryption, you must provide an encryption key when you run NSControl Create to create the databases and when you run NSControl Register to register the instance.

The database columns that store the delivery channel and event provider arguments are encrypted, and the NS$instance_name service uses the key to read the arguments when necessary.

Important Argument encryption protects the data in the databases, but does not do so for the data in the configuration files and ADFs. To protect this data, you can use command-line arguments to pass values into the configuration file and ADFs. If that is not a reasonable solution for your applications, secure the configuration file and ADFs if they contain sensitive information.

For more information, see <EncryptArguments> Element.

See Also

Configuration File Samples

Creating a Configuration File

Using Parameters in the Configuration File


Using Parameters in the Configuration File

Each instance of Notification Services has a configuration file. This file contains information about the instance, general information about the instance's applications, and information about delivery channels and protocols.

You can hard code configuration file values for each element of the configuration file, or you can use parameters. If you use parameters in the configuration file, you can define default values for the parameters in the <ParameterDefaults> node.

For example, if the instance hosts two applications, and the files for the two applications are located in similar locations, you can use the same parameter in the <BaseDirectoryPath> values for the applications. The parameterized values look like this:

<BaseDirectoryPath>%BaseDirPath%\Stock</BaseDirectoryPath>
...
<BaseDirectoryPath>%BaseDirPath%\Weather</BaseDirectoryPath>

You can then supply the value for %BaseDirPath% in the <ParameterDefaults> node, like this:

<ParameterDefaults>
   <Parameter>
      <Name>BaseDirPath</Name>
      <Value>C:\Notification Services\Applications</Value>
   </Parameter>
</ParameterDefaults>

When you run the NSControl Create or NSControl Update command, "C:\Notification Services\Applications" is substituted for %BaseDirPath% where it appears in the configuration file.

The values in the <ParameterDefaults> node are default values. You can override these values on the command line when you run NSControl Create or NSControl Update.

You should specify values on the command line when you do not want to store values in the configuration file (such as passwords) or when you do not want to use the values in the <ParameterDefaults> node.

For more information about specifying parameter values on the command line, see NSControl Commands.

See Also

<Parameter> Node (<ParameterDefaults>)


Deploying an Instance

When you deploy an instance, you create the NS$instance_name service that runs the instance, create the instance and application databases, define security, and then enable and start the instance. This section provides instructions for completing these tasks.

The process of deploying an instance depends on the system configuration. For information about creating a configuration file for an instance, see Creating a Configuration File. For step-by-step instructions for a variety of configurations, see Notification Services Deployment Scenarios.

The topics that this section covers are described in the following table.

Topic | Description
Deployment Overview | Describes the basic steps for deploying an instance of Notification Services.
Creating a Deployment Directory Structure | Lists the instance and application files needed for deployment, and provides recommendations for the directory structure.
Registering and Unregistering an Instance | Describes registration and provides instructions for registering and unregistering an instance on different types of servers.
Creating Instance and Application Databases | Explains how to create databases based on the configuration file and application definition files (ADFs).
Configuring Security for an Instance | Provides a high-level description of Notification Services security requirements.
Enabling and Disabling an Instance | Explains how to turn components of a Notification Services instance on and off.
Starting and Stopping an Instance | Provides information about starting and stopping the NS$instance_name service.

See Also

Subscription Management Application Deployment Scenarios


Deployment Overview

Notification Services uses instances to deploy applications. Each instance hosts one or more notification applications.

An instance is configured through an XML configuration file, which contains pointers to application definition files (ADFs). Each ADF defines a single application. When you deploy an instance, Notification Services uses the configuration file to create an instance database, and then uses each referenced ADF to create an application database.

Deploying an instance also creates the NS$instance_name service that runs the instance and its applications.

The Deployment Process

To deploy an instance of Notification Services, follow these steps:

  1. Plan the instance and gather information.
    • Determine the system configuration for the instance, such as which server hosts the database, which servers host the instance, and where the subscription management application is hosted. For more information, see Hardware Configurations.
    • Determine the security model that the instance will use. The NS$instance_name service can use either Windows Authentication or SQL Server Authentication to connect to SQL Server. Microsoft recommends Windows Authentication.
    • Determine the account that the NS$instance_name service will run under. The account can be a domain account, a local account, or a built-in account. For more information, see NS$instance_name Service Account Security.
    • Obtain the ADF and operational files, such as XSLT files and custom components, for all applications hosted by the instance. These files are required to create an instance. For more information, see Creating a Deployment Directory Structure.
    • Create a configuration file for each instance, if an application developer has not provided one.
  2. Install Notification Services.
  3. Grant access to SQL Server for the account used by NS$instance_name. The NS$instance_name service requires access to the instance, application, and master databases, so it must have access to SQL Server.
  4. Grant permission to run the Notification Services extended stored procedures for the account used by NS$instance_name. The service runs these extended stored procedures to generate notifications and perform other key tasks. For more information about granting these permissions, see SQL Server Permissions for NS$instance_name .
  5. Register the instance of Notification Services.

    Registration adds information about the instance to the registry and optionally creates the NS$instance_name service. You must register the instance on each server that hosts the instance as well as on servers that host subscription management applications and independent event providers. For more information, see Registering and Unregistering an Instance.

  6. Create the instance and application databases.

    The NSControl Create command reads the instance data from the configuration file and creates the instance database; it then reads the application data from each associated ADF and creates application databases. For more information, see Creating Instance and Application Databases.

    Note You can create the instance databases before registering the instance if you prefer.

  7. Grant access to the instance and application databases for the SQL Server login account used by the service, and then add the account to the NSRunService database role in each database.
  8. Enable the instance.

    The NSControl Enable command activates components of Notification Services. For more information, see Enabling and Disabling an Instance.

  9. Start the instance.

    Start the instance by starting the NS$instance_name service. At this point, Notification Services starts its event collection, notification generation, and distribution functions for all enabled components. For more information, see Starting and Stopping an Instance.

You can now test the applications. You may need to bulk load subscriber and subscription data at this time. Without subscriber, subscriber device, subscription, and event data, the applications cannot generate notifications.

Deployment Options

Notification Services supports several deployment configurations:

  • You can deploy the Notification Services instance and the databases on one server.
  • You can deploy the Notification Services instance and the databases on separate servers. This configuration requires you to separately install the database components on the database server.
  • The Notification Services instance can be deployed across multiple servers, providing scale-out options for large applications. You must install Notification Services on each server that runs the Notification Services instance and subscription management applications, and then register the instance. You must also install Notification Services on the server that hosts the instance and application databases.

For detailed instructions about deploying Notification Services in these configurations, see Notification Services Deployment Scenarios.


Creating a Deployment Directory Structure

Each application for Notification Services should have its own folder for application files. For example, if you have a stock quote application and a weather reporting application, create one application directory for the stock application and another application directory for the weather application.

For each application, the path to this folder is specified in the configuration file. Notification Services uses this path to find the application files.

An application directory typically contains the following files:

  • Any XML schemas describing event schemas
  • Any XSLT files used to format notifications
  • DLLs for any custom event providers specific to the application
  • DLLs for any custom content formatters specific to the application
  • DLLs for any custom delivery protocols specific to the application

These files are referred to as operational files because they are used while the application is running.

Because the configuration file and application definition files (ADFs) are used only when deploying the instance or when updating the application, you should consider storing these files in another directory. By storing these files separately, you can provide a higher level of security for them. The following section provides recommendations for a creating a directory structure that separates operational files from deployment files.

Deployment Directory Recommendations

Microsoft recommends using two file shares for instance and application files: NSSourceFiles and NSDataFiles. Create NSSourceFiles to contain the configuration file and ADFs and create NSDataFiles to contain the operational files.

NSSourceFiles

The NSSourceFiles share contains only the files necessary to create and update the instance of Notification Services. This includes the configuration file and the ADFs.

The NSSourceFiles share uses a simple structure. Each instance has one directory under NSSourceFiles, and this directory contains all files used when creating and updating the instance. The following list shows a sample directory structure:

NSSourceFiles

Instance01

Instance02

You should control security at the instance-directory level. By controlling security this way, you can grant Full Control to the Everyone group for the NSSourceFiles share and then set permissions for each instance directory. (Make sure to clear the Inherit from parent check box for the directories within the NSSourceFiles share.) Setting security at the instance-directory level makes it clear who has permissions in each directory, and makes it easier to debug security issues.

Grant the following permissions to the NSSourceFiles directory:

  • Grant Full Control permissions to the computer\Administrators group.
  • Grant Modify permissions to the account used to deploy the instance.
NSDataFiles

The NSDataFiles share contains operational files used when the instance and its applications are running.

The NSDataFiles directory uses a structure that mimics the instances and their applications. Each instance has one directory within NSDataFiles. The instance directory contains a directory named Common that contains custom objects that can be used by all applications, and one directory for each application hosted by the instance. The application directory might contain directory for event drops, event schemas, and content formatters. The following list shows a sample directory structure:

NSDataFiles

Instance01

Common

CustomContentFormatters

CustomDeliveryProtocols

CustomEventProviders

wwwroot

Application01

XSDs

ContentFormatters

en

Email

File

SMS

fr

Email

File

SMS

Instance02

...

You should control security at the instance-directory level. By controlling security this way, you can grant the Everyone group Full Control for the NSDataFiles share and then set permissions for each instance directory. (Make sure to clear the Inherit from parent check box for the directories within the NSDataFiles share.) Setting security at the instance-directory level makes it clear who has permissions in each directory, and makes it easier to debug security issues.

Grant the following permissions to the NSDataFiles directory:

  • Grant Full Control permissions to the computer\Administrators group.
  • Grant Modify permissions to the accounts used to deploy and monitory the instance.
  • Grant Modify permissions to the account used by the NS$instance_name service.
Mapping Network Drives

If your NSDataFiles and NSSourceFiles directories are located on a network share, you can map network drives to these directories to simplify access to the shares. Mapping a network drive enables you to assign a drive letter, such as T, to a UNC path, such as \\Server1\NotificationServicesFiles\NSSourceFiles.

The benefit of mapping network drives is illustrated by the following NSControl Create examples.

  • UNC Path
    NSControl Create –in \\Server1\NotificationServicesFiles\NSSourceFiles\Instance01\Instance01Config.xml
  • Mapped Network Drive Path
    NSControl Create –in S:\Instance01\Instance01Config.xml

If you use mapped network drives in your configuration file or ADFs, each server that runs the NS$instance_name service must map the same drive letters to the NSDataFiles share.

For more information about mapping network drives, see your Windows documentation.

See Also

File and Folder Security


Registering and Unregistering an Instance

Registering an instance of Notification Services creates the NS$instance_name service, creates performance counters on the local server, and adds information to the registry. You must register the instance on the following servers:

  • Each server that runs the NS$instance_name service. The service runs the event provider host, generator, and distributor components. For scaled-out configurations, the service runs on multiple servers.
  • Each server that runs a subscription management application. If the subscription management application runs on its own server, do not create the NS$instance_name service when registering the instance.
  • Each server that runs an independent event provider. If the independent event provider runs on its own server or the database server, do not create the NS$instance_name service when registering the instance.

If the database server does not also run the Notification Services instance or the client components, do not register the instance on this server.

To register an instance of Notification Services and create the NS$instance_name service

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Type the following command to register the instance:
    nscontrol register -name instance_name -service
   -serviceusername "service_username"
   -servicepassword "service_password"

    If using SQL Server Authentication to connect to SQL Server, you must also use the -sqlusername and -sqlpassword arguments.

To register an instance of Notification Services without creating the service

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Type the following command to register the instance:
    nscontrol register -name instance_name

To remove an instance from a server, you must delete the instance and also unregister it. Unregistering an instance removes registry entries, removes the NS$instance_name service (if present), and deletes the performance counters for the service.

To unregister an instance of Notification Services
  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Type the following command to register the instance:
    nscontrol unregister -name instance_name

See Also

Deploying an Instance

NSControl Register

NSControl Unregister


Creating Instance and Application Databases

When you deploy an instance of Notification Services, you must create an instance database and application databases. These databases are defined by the configuration file and the application definition files (ADFs). These databases store information used when the instance and applications are running, including subscriber, subscription, event, and notification data.

To create the databases, use the NSControl Create command.

To create an instance of Notification Services

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Type the following command to create the databases:
    nscontrol create -in configuration_filename

    If the configuration file or ADFs use parameters, your NSControl Create command might contain additional arguments. For more information, see NSControl Create.

If you need to update existing instance and application databases, use the NSControl Update command. If you need to delete the databases, use the NSControl Delete command. For more information about managing instances and applications after deployment, see Managing Instances and Applications.

See Also

Deploying an Instance

NSControl Delete

NSControl Update


Configuring Security for an Instance

Deploying an instance of Notification Services requires defining security for the application and for those who administer and monitor the application. The following list describes the accounts used by an instance:

  • The NS$instance_name Windows service runs under a local, domain, or built-in Windows account. The service uses this account to access local and network resources, and possibly to access databases.
  • If you cannot grant database permissions to the account the service runs under, the service uses a SQL Server login account to access databases.
  • The NSControl commands, used to deploy and administer instances, are run in the context of the user. Each command requires specific permissions, so you might use one or more user accounts to run these commands.
  • A subscription management application uses an account to execute stored procedures that read and write data in the instance and application databases.
  • Custom event providers require connections to SQL Server to execute stored procedures that write data to an application database.

The NS$instance_name service requires permissions in the instance and application databases. The service must be a member of the NSRunService role in each database, and must be granted permission to run the Notification Services extended stored procedures using the GrantXPExec utility.

For more information about the security requirements of Notification Services instances and applications, see Managing Security. For step-by-step instructions, see Notification Services Deployment Scenarios.

See Also

GrantXPExec Utility


Enabling and Disabling an Instance

When you create the NS$instance_name service by registering an instance of Notification Services, all components of the instance are initially disabled. Before starting the instance, you must enable them.

Enabling an instance sets flags in the database. The NS$instance_name services that run the instance check these flags to see if the instance, application, and components are enabled. For example, if only the distributor component is running on a server, the NS$instance_name service checks the instance, application, and distributor flags. If any of these flags are disabled, the distributor thread for the instance or application does not run.

When you deploy an instance of Notification Services, you will probably enable all components. You typically disable components only when you update an instance, or when you need to test or troubleshoot the instance.

Component | Effect
Events | If enabled, runs the event provider host component, which collects events. You can control event provider host operation at the instance, application, and server level.
Generator | If enabled, runs the generator component, which creates notifications.
Distributor | If enabled, runs the distributor, which formats and distributes notifications. You can control distributor operation at the instance, application, and server level.
Subscriptions | If enabled, allows subscriptions to be added, deleted, and modified. Subscriptions are enabled or disabled at the instance level. They cannot be controlled at the application level.
Subscribers | If enabled, allows subscriber data to be added, deleted, and modified. Subscribers are enabled or disabled at the instance level. They cannot be controlled at the application level.
Application application_name | Allows you to enable or disable an application, or one or more components for a single application.
Instance instance_name | Allows you to enable or disable the instance as a whole, or one or more components for all applications hosted by the instance.

To enable all components of an instance

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Type the following command to enable the instance:
    nscontrol enable -name instance_name

To enable a single component that was previously disabled

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Type the following command to enable a component:
    nscontrol enable -name instance_name –component

    For more information, see NSControl Enable.

To disable all components of an instance

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Type the following command to disable the instance:
    nscontrol disable -name instance_name

To disable a single component of an instance

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Type the following command to disable a component:
    nscontrol disable -name instance_name -component

    For more information, see NSControl Enable.

To view the status of an instance, application, or component

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Type the following command to view the status of the instance:
    nscontrol status -name instance_name

See Also

NSControl Disable

NSControl Enable


Starting and Stopping an Instance

An instance of Notification Services is run by a Windows service named NS$instance_name. Each instance has one service on each server the instance runs on. When the service is started, all enabled components start processing available data.

To start or stop an instance of Notification Services

Starting and Stopping Services

To configure automatic startup and restart

Configuring Services


Notification Services Deployment Scenarios

Deploying an instance of Notification Services requires several steps. These steps vary depending on the system configuration. For example, if Notification Services and the databases are located on one server, you perform all deployment steps on that server. However, if the databases are located on a remote server, you must install the database components on the database server.

This section contains several deployment scenarios, and provides step-by-step instructions for deploying an instance of Notification Services for each scenario.

The topics that this section covers are described in the following table.

Topic | Description
Windows Authentication Deployment Scenarios | Provides deployment instructions for scenarios that use Windows Authentication to connect to SQL Server.
SQL Server Authentication Deployment Scenarios | Provides deployment instructions for scenarios that use SQL Server Authentication to connect to SQL Server.

See Also

Subscription Management Application Deployment Scenarios


Windows Authentication Deployment Scenarios

An instance of Notification Services must be able to access its instance and application databases. To access them, the NS$instance_name service that runs the instance must be able to connect to SQL Server. These connections use Windows Authentication or SQL Server Authentication.

This section contains instructions for deploying an instance of Notification Services that uses Windows Authentication to connect to SQL Server. Microsoft recommends Windows Authentication because it uses Windows credentials instead of using credentials stored in a SQL Server database.

The topics that this section covers are described in the following table.

Topic | Description
Single-Server Deployment (Windows Authentication) | Provides step-by-step instructions for deploying an instance of Notification Services that uses Windows Authentication to connect to a local database server.
Remote Database Server Deployment (Windows Authentication) | Provides step-by-step instructions for deploying an instance of Notification Services that uses Windows Authentication to connect to a remote database server.
Scale-Out Deployment (Windows Authentication) | Provides step-by-step instructions for deploying an instance of Notification Services on multiple servers if the instance uses Windows Authentication to connect to SQL Server.

See Also

SQL Server Authentication Deployment Scenarios


Single-Server Deployment (Windows Authentication)

This scenario shows how to deploy an instance of Notification Services on a server that also hosts the databases (and possibly the subscription management system) using Windows Authentication. Typically, you would use a single-server deployment for small to medium applications.

The following picture shows the hardware configuration for this deployment scenario. The server, named NS1, has multiple disk drives to improve the performance of the databases and notification applications.

The disk layout depicts an optimal configuration. You can use other disk configurations. For more information, see Database Considerations.

Prerequisites
  • You have previously installed the operating system and SQL Server 2000 on NS1 and have applied all applicable service packs and updates. For more information, see Hardware and Software Requirements.
  • You are running these procedures under an account that has administrative permissions on the server and is a member of the sysadmin fixed server role in SQL Server 2000.
  • You or your domain administrator have created two domain accounts: domain\NSService (used by the NS$instance_name service) and domain\Ops (used by anyone who monitors performance and runs reports).
  • You have created file shares for source files and data files, and have granted the necessary permissions to your account, the domain\NSService account, and the domain\Ops account. For more information, see Creating a Deployment Directory Structure.

    Note If you print this topic, the steps contained within each task will automatically appear in the printout.

Tasks

Install Notification Services.

  • Install the Notification Services engine and database components on NS1. You can install additional components, such as documentation, but other components are not required for deployment. Do not install the sample applications on production servers.

    For more information about installing components, see Installing Notification Services.

Map network drives. (Optional)

Mapping network drives can simplify access to source files (files you use when you deploy an instance) and data files (files used while the instance is running).

  • To learn how to map network drives, see Creating a Deployment Directory Structure. For more information about mapping network drives, see your Windows documentation.

Grant local Windows permissions to the domain accounts.

This scenario uses two domain accounts: domain\NSService and domain\Ops.

  • Add the domain\NSService and domain\Ops accounts to the local Users group.

    These domain accounts require few privileges on NS1; the Users group provides the basic privileges. You grant additional privileges during the deployment process. For more information on adding accounts to a local group, see your Windows documentation.

Grant the domain accounts access to SQL Server.

The domain\NSService and domain\Ops accounts must be able to access the Notification Services databases. Additionally, the domain\NSService account requires permissions in the master database. Before you can grant database permissions to these accounts, you must grant access to SQL Server by creating login IDs.

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Set any necessary environment variables. This deployment scenario uses the following four environment variables:
    Set InstanceName=instance_name
Set SQLServer=database_server_name
Set NSSourceFilesRoot=instance_source_file_root
Set ConfigFileName=%NSSourceFilesRoot%\%InstanceName%\config_file_name.xml

    When you run these commands, the environment variables are active as long as the command prompt window is open.

    Your instance and applications may require additional environment variables. To reduce typing, you can create a batch file that contains all environment variables for your instance, and then run this batch file after you open the command prompt window.

  3. Type the following command to create a SQL Server login ID for the domain\NSService account:
    osql -E -S %SQLServer% -Q "EXEC sp_grantlogin 'domain\NSService'"
  4. Type the following command to create a SQL Server login ID for the domain\Ops account:
    osql -E -S %SQLServer% -Q "EXEC sp_grantlogin 'domain\Ops'"
  5. Leave the command prompt window open for the next procedure.

Grant the domain\NSService account permission to run extended stored procedures.

To generate and send notifications, the NS$instance_name service must be able to run the Notification Services extended stored procedures. Follow these steps to grant the account access to the master database, and then grant the necessary permissions.

  1. In the open command prompt window, type the following command to grant the domain\NSService account access to the master database:
    osql -E -S %SQLServer% -Q "USE master
   EXEC sp_grantdbaccess 'domain\NSService'"
  2. Type the following command to grant the domain\NSService account permission to run the Notification Services extended stored procedures.
    GrantXpExec "domain\NSService"
  3. Leave the command prompt window open for the next procedure.

Create the NS$instance_name service.

Now that the account used by the NS$instance_name service is available, you can create the service.

  1. In the open command prompt window, type the following command:
    nscontrol register -name %InstanceName% -server %SQLServer%
   -serviceusername domain\NSService
   -servicepassword "[password]" -service

    The NSControl Register command creates the service; it also creates performance counters used to monitor the instance and creates registry entries for the instance.

  2. Leave the command prompt window open for the next procedure.

Create the databases and grant database permissions.

NSControl Create uses data from the configuration file and ADFs to create the instance and application databases. After you create the databases, you can grant database permissions to the domain\NSService account. This is also a good time to grant database permissions to the domain\Ops account.

  1. In the open command prompt window, type the following command to create the instance and application databases:
    nscontrol create -in "%ConfigFileName%"
  2. Type the following command to grant the domain\NSService account access to the instance database and to add the account to the NSRunService database role:
    osql -E -S %SQLServer% -Q "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'domain\NSService'
   EXEC sp_addrolemember 'NSRunService', 'domain\NSService'"
  3. Type the following command to grant the domain\NSService account access to the application database and to add the account to the NSRunService database role:
    osql -E -S %SQLServer% -Q "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'domain\NSService'
   EXEC sp_addrolemember 'NSRunService', 'domain\NSService'"

    If the instance hosts multiple applications, repeat this step for each application database.

  4. Type the following command to grant the domain\Ops account access to the instance database and to add the account to the NSMonitor and NSAnalysis database roles.
    osql -E -S %SQLServer% -Q "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'domain\Ops'
   EXEC sp_addrolemember 'NSMonitor', 'domain\Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'domain\Ops'"
  5. Type the following command to grant the domain\Ops account access to the application database and to add the account to the NSMonitor and NSAnalysis database roles.
    osql -E -S %SQLServer% -Q "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'domain\Ops'
   EXEC sp_addrolemember 'NSMonitor', 'domain\Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'domain\Ops'"

    If the instance hosts multiple applications, repeat this step for each application database.

Enable all components and then start the instance.

After you have created the databases and have granted the necessary permissions, you can enable the instance and then start the instance by starting the NS$instance_name service.

Important Without event, subscriber, subscriber device, and subscription data, Notification Services will not generate notifications. If you have not configured an event source and deployed your subscription management application, complete those tasks before performing the following steps.

  1. Type the following command to enable the instance:
    nscontrol enable -name %InstanceName%

    Enabling the instance in this way allows all components, including the event provider host, the generator, and the distributor, to run when you start the service.

  2. Type the following command to start the instance:
    net start NS$%InstanceName%
  3. Close the command prompt window.

You have now deployed the instance of Notification Services.

See Also

NSControl Create

NSControl Enable

NSControl Register

SQL Server Authentication Deployment Scenarios

Subscription Management Application Deployment Scenarios

Windows Authentication Deployment Scenarios


Remote Database Server Deployment (Windows Authentication)

This scenario shows how to deploy an instance of Notification Services when the databases are located on a remote server and you can use Windows Authentication to connect to SQL Server. This deployment is more scalable than the single-server deployment, and is a good solution for medium to large applications.

The following picture shows the hardware configuration for this deployment scenario. The scenario uses two servers: NS1 and SQL1. NS1 hosts the instance of Notification Services, and SQL1 hosts the instance and application databases. NS1 can use one or two disk drives; the number of drives is not critical on this server. However, SQL1 has multiple disk drives to improve the performance of the databases.

The disk layout shown in this picture depicts an optimal configuration. You can use other disk configurations. For more information, see Database Considerations.

Prerequisites
  • You have previously installed the operating system on NS1 and have applied all applicable service packs and updates. For more information, see Hardware and Software Requirements.
  • You have previously installed the operating system and SQL Server 2000 on SQL1 and have applied all applicable service packs and updates.
  • You are running these procedures under an account that has administrative permissions on the server and is a member of the sysadmin fixed server role in SQL Server 2000.
  • You or your domain administrator have created two domain accounts: domain\NSService (used by the NS$instance_name service) and domain\Ops (used by anyone who monitors performance and runs reports).
  • You have created file shares for source files and data files, and have granted the necessary permissions to your account, the domain\NSService account, and the domain\Ops account. For more information, see Creating a Deployment Directory Structure.

    Note If you print this topic, the steps within each procedure will appear in the printout.

NS1 Tasks

Install Notification Services.

  • Install the Notification Services engine and database components on NS1. You can install additional components, such as documentation, but other components are not required for deployment. Do not install the sample applications on production servers.

    For more information about installing components, see Installing Notification Services.

Map network drives. (Optional)

Mapping network drives can simplify access to source files (files you use when you deploy an instance) and data files (files used while the instance is running).

  • To learn how to map network drives, see Creating a Deployment Directory Structure. For more information about mapping network drives, see your Windows documentation.

Grant local Windows permissions to the domain accounts.

This scenario uses two domain accounts: domain\NSService and domain\Ops.

  • Add the domain\NSService and domain\Ops accounts to the local Users group.

    These domain accounts require few privileges on NS1; the Users group provides the basic privileges. You grant additional privileges during the deployment process. For more information on adding accounts to a local group, see your Windows documentation.

Grant the domain\NSService account permission to run extended stored procedures.

To generate and send notifications, the NS$instance_name service must be able to run the Notification Services extended stored procedures. The following steps grant the account access to the master database, and then grant the necessary permissions.

  1. In the open command prompt window, type the following command to grant the domain\NSService account access to the master database:
    osql -E -S %SQLServer% -Q "USE master
   EXEC sp_grantdbaccess 'domain\NSService'"
  2. Type the following command to grant the domain\NSService account permission to run the Notification Services extended stored procedures:
    GrantXpExec "domain\NSService" -E -S %SQLServer%
  3. Leave the command prompt window open for the next procedure.

Create the NS$instance_name service.

Now that the account used by the NS$instance_name service is available, you can create the service.

  1. In the open command prompt window, type the following command:
    nscontrol register -name %InstanceName% -server %SQLServer%
   -serviceusername domain\NSService
   -servicepassword "[password]" -service

    The NSControl Register command creates the service; it also creates performance counters used to monitor the instance and creates registry entries for the instance.

  2. Leave the command prompt window open for the next procedure.

Create the databases and grant database permissions.

NSControl Create uses data from the configuration file and ADFs to create the instance and application databases. After you create the databases, you can grant database permissions to the domain\NSService account. This is also a good time to grant database permissions to the domain\Ops account.

  1. In the open command prompt window, type the following command to create the instance and application databases:
    nscontrol create -in "%ConfigFileName%"
  2. Type the following command to grant the domain\NSService account access to the instance database and to add the account to the NSRunService database role:
    osql -E -S %SQLServer% -Q "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'domain\NSService'
   EXEC sp_addrolemember 'NSRunService', 'domain\NSService'"
  3. Type the following command to grant the domain\NSService account access to the application database and to add the account to the NSRunService database role:
    osql -E -S %SQLServer% -Q "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'domain\NSService'
   EXEC sp_addrolemember 'NSRunService', 'domain\NSService'"

    If the instance hosts multiple applications, repeat this step for each application database.

  4. Type the following command to grant the domain\Ops account access to the instance database and to add the account to the NSMonitor and NSAnalysis database roles.
    osql -E -S %SQLServer% -Q "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'domain\Ops'
   EXEC sp_addrolemember 'NSMonitor', 'domain\Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'domain\Ops'"
  5. Type the following command to grant the domain\Ops account access to the application database and to add the account to the NSMonitor and NSAnalysis database roles.
    osql -E -S %SQLServer% -Q "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'domain\Ops'
   EXEC sp_addrolemember 'NSMonitor', 'domain\Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'domain\Ops'"

    If the instance hosts multiple applications, repeat this step for each application database.

Enable all components and then start the instance.

After you have created the databases and have granted the necessary permissions, you can enable and then start the instance by starting the NS$instance_name service.

Important Without event, subscriber, subscriber device, and subscription data, Notification Services will not generate notifications. If you have not configured an event source and deployed your subscription management application, complete those tasks before performing the following steps.

  1. Type the following command to enable the instance:
    nscontrol enable -name %InstanceName%

    Enabling the instance in this way allows all components, including the event provider host, the generator, and the distributor, to run when you start the service.

  2. Type the following command to start the instance:
    net start NS$%InstanceName%
  3. Close the command prompt window.
SQL1 Tasks

Install Notification Services database components.

Because this scenario uses a remote database server, the SQL1 server does not run the NS$instance_name service, and is not used to administer the instance using the NSControl commands. For this reason, install only the database components on SQL1.

For more information, see Installing Database Components.

Grant the domain accounts access to SQL Server.

The domain\NSService and domain\Ops accounts must be able to access the Notification Services databases. Additionally, the domain\NSService account requires permissions in the master database. Before you can grant database permissions to these accounts, you must grant access to SQL Server by creating login IDs.

Note Because this procedure does not require the Notification Services client tools, you can run this procedure wherever the SQL Server client tools are installed. The SQL Server client tools must be installed on server NS1, so you can run this procedure on NS1 if you prefer.

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Set any necessary environment variables. On SQL1, this deployment scenario uses one environment variable:
    Set SQLServer=database_server_name

    When you run this command, the environment variable is active as long as the command prompt window is open.

  3. Type the following command to create a SQL Server login ID for the domain\NSService account:
    osql -E -S %SQLServer% -Q "EXEC sp_grantlogin 'domain\NSService'"
  4. Type the following command to create a SQL Server login ID for the domain\Ops account:
    osql -E -S %SQLServer% -Q "EXEC sp_grantlogin 'domain\Ops'"
  5. Close the command prompt window.

You have now deployed the instance of Notification Services.

See Also

NSControl Create

NSControl Enable

NSControl Register

SQL Server Authentication Deployment Scenarios

Subscription Management Application Deployment Scenarios

Windows Authentication Deployment Scenarios


Scale-Out Deployment (Windows Authentication)

This scenario shows how to deploy an instance of Notification Services on multiple servers; in this scenario the databases are located on a remote server and you use Windows Authentication to connect to SQL Server. This deployment scenario is for large applications that need multiple servers for formatting and distributing notifications.

The following picture shows the hardware configuration for this deployment scenario. The scenario uses four servers: NS1, NS2, NS3 and SQL1. NS1 hosts the event provider host and generator for an instance of Notification Services. NS2 and NS3 host distributor components for an instance of Notification Services. SQL1 hosts the instance and application databases. NS1, NS2, and NS3 can use one or two disk drives, because the number of drives is not critical on this server. However, SQL1 has multiple disk drives to improve the performance of the databases.

The disk layout shown in this picture depicts an optimal configuration. You can use other disk configurations. For more information, see Database Considerations.

Prerequisites
  • You have previously installed the operating system on NS1, NS2, and NS3 and have applied all applicable service packs and updates. For more information, see Hardware and Software Requirements.
  • You have previously installed the operating system and SQL Server 2000 on SQL1 and have applied all applicable service packs and updates.
  • You are running these procedures under an account that has administrative permissions on the server and is a member of the sysadmin fixed server role in SQL Server 2000.
  • You or your domain administrator have created two domain accounts: domain\NSService (used by the NS$instance_name service) and domain\Ops (used by anyone who monitors performance and runs reports).
  • You have created file shares for source files and data files, and have granted the necessary permissions to your account, the domain\NSService account, and the domain\Ops account. For more information, see Creating a Deployment Directory Structure.

    Note If you print this topic, the steps within each procedure will appear in the printout.

SQL1 Tasks

Install Notification Services database components.

Because this scenario uses a remote database server, the SQL1 server does not run the NS$instance_name service, and is not used to administer the instance using the NSControl commands. For this reason, install only the database components on SQL1. For more information, see Installing Database Components.

Grant the domain accounts access to SQL Server.

The domain\NSService and domain\Ops accounts must be able to access the Notification Services databases. Additionally, the domain\NSService account requires permissions in the master database. Before you can grant database permissions to these accounts, you must grant access to SQL Server by creating login IDs.

Note Because this procedure does not require the Notification Services client tools, you can run this procedure wherever the SQL Server client tools are installed. The SQL Server client tools must be installed on server NS1, so you can run this procedure on NS1, NS2, or NS3 if you prefer.

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Set any necessary environment variables. On SQL1, this deployment scenario uses one environment variable:
    Set SQLServer=database_server_name

    When you run this command, the environment variable is active as long as the command prompt window is open.

  3. Type the following command to create a SQL Server login ID for the domain\NSService account:
    osql -E -S %SQLServer% -Q "EXEC sp_grantlogin 'domain\NSService'"
  4. Type the following command to create a SQL Server login ID for the domain\Ops account:
    osql -E -S %SQLServer% -Q "EXEC sp_grantlogin 'domain\Ops'"
  5. Close the command prompt window.
NS1 Tasks

In this scale-out scenario, NS1 is used as the administrative server. This means that the databases are created from this server, not from NS2 and NS3, and permissions to run the extended stored procedures are granted from this server, not from NS2 or NS3.

Install Notification Services.

  • Install the Notification Services engine and database components on NS1. You can install additional components such as documentation, but other components are not required for deployment. Do not install the sample applications on production servers.

    For more information about installing components, see Installing Notification Services.

Map network drives. (Optional)

Mapping network drives can simplify access to source files (files you use when you deploy an instance) and data files (files used while the instance is running).

  • To learn how to map network drives, see Creating a Deployment Directory Structure. For more information about mapping network drives, see your Windows documentation.

Grant local Windows permissions to the domain accounts.

This scenario uses two domain accounts: domain\NSService and domain\Ops.

  • Add the domain\NSService and domain\Ops accounts to the local Users group.

    These domain accounts require few privileges on NS1; the Users group provides the basic privileges. You grant additional privileges during the deployment process. For more information on adding accounts to a local group, see your Windows documentation.

Grant the domain\NSService account permission to run extended stored procedures.

To generate and send notifications, the NS$instance_name service must be able to run the Notification Services extended stored procedures. The following steps grant the domain\NSService account access to the master database and then grant the necessary permissions.

  1. In the open command prompt window, type the following command to grant the domain\NSService account access to the master database:
    osql -E -S %SQLServer% -Q "USE master
   EXEC sp_grantdbaccess 'domain\NSService'"
  2. Type the following command to grant the domain\NSService account permission to run the Notification Services extended stored procedures.
    GrantXpExec "domain\NSService" -E -S %SQLServer%
  3. Leave the command prompt window open for the next procedure.

Create the NS$instance_name service.

Now that the account used by the NS$instance_name service is available, you can create the service.

  1. In the open command prompt window, type the following command:
    nscontrol register -name %InstanceName% -server %SQLServer%
   -serviceusername domain\NSService
   -servicepassword "[password]" -service

    The NSControl Register command creates the service; it also creates performance counters used to monitor the instance and creates registry entries for the instance.

  2. Leave the command prompt window open for the next procedure.

Create the databases and grant database permissions.

NSControl Create uses data from the configuration file and ADFs to create the instance and application databases. After you create the databases, you can grant database permissions to the domain\NSService account. This is also a good time to grant database permissions to the domain\Ops account.

  1. In the open command prompt window, type the following command to create the instance and application databases:
    nscontrol create -in "%ConfigFileName%"
  2. Type the following command to grant the domain\NSService account access to the instance database and to add the account to the NSRunService database role:
    osql -E -S %SQLServer% -Q "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'domain\NSService'
   EXEC sp_addrolemember 'NSRunService', 'domain\NSService'"
  3. Type the following command to grant the domain\NSService account access to the application database and to add the account to the NSRunService database role:
    osql -E -S %SQLServer% -Q "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'domain\NSService'
   EXEC sp_addrolemember 'NSRunService', 'domain\NSService'"

    If the instance hosts multiple applications, repeat this step for each application database.

  4. Type the following command to grant the domain\Ops account access to the instance database and to add the account to the NSMonitor and NSAnalysis database roles.
    osql -E -S %SQLServer% -Q "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'domain\Ops'
   EXEC sp_addrolemember 'NSMonitor', 'domain\Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'domain\Ops'"
  5. Type the following command to grant the domain\Ops account access to the application database and to add the account to the NSMonitor and NSAnalysis database roles.
    osql -E -S %SQLServer% -Q "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'domain\Ops'
   EXEC sp_addrolemember 'NSMonitor', 'domain\Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'domain\Ops'"

    If the instance hosts multiple applications, repeat this step for each application database.

Enable the event and generator components and then start the instance.

After you have created the databases and have granted the necessary permissions, you can enable the instance and then start it by starting the NS$instance_name service.

Important Without event, subscriber, subscriber device, and subscription data, Notification Services will not generate notifications. If you have not configured an event source and deployed your subscription management application, complete those tasks before performing the following steps.

  1. Type the following command to enable the instance:
    nscontrol enable -name %InstanceName% -events -generator

    Enabling the instance in this way allows all components, including the event provider host, the generator, and the distributor, to run when you start the service.

  2. Type the following command to start the instance:
    net start NS$%InstanceName%
  3. Close the command prompt window.
NS2 and NS3 Tasks

NS2 and NS3 run the distributors in this scale-out scenario.

Install Notification Services.

  • Install the Notification Services engine and database components on NS1. You can install additional components such as documentation, but other components are not required for deployment. Do not install the sample applications on production servers.

    For more information about installing components, see Installing Notification Services.

Map network drives. (Optional)

Mapping network drives can simplify access to source files (files you use when you deploy an instance) and data files (files used while the instance is running).

  • To learn how to map network drives, see Creating a Deployment Directory Structure. For more information about mapping network drives, see your Windows documentation.

Grant local Windows permissions to the domain accounts.

This scenario uses two domain accounts: domain\NSService and domain\Ops.

  • Add the domain\NSService and domain\Ops accounts to the local Users group.

    These domain accounts require few privileges on NS1; the Users group provides the basic privileges. You grant additional privileges during the deployment process. For more information on adding accounts to a local group, see your Windows documentation.

Create the NS$instance_name service.

Now that the account used by the NS$instance_name service is available, you can create the service.

  1. In the open command prompt window, type the following command:
    nscontrol register -name %InstanceName% -server %SQLServer%
   -serviceusername domain\NSService
   -servicepassword "[password]" -service

    The NSControl Register command creates the service; it also creates performance counters used to monitor the instance and creates registry entries for the instance.

  2. Leave the command prompt window open for the next procedure.

Enable the distributor component and then start the instance.

After you have created the databases and have granted the necessary permissions, you can enable the distributor component of the instance and then start the component by starting the NS$instance_name service.

  1. Type the following command to enable the instance:
    nscontrol enable -name %InstanceName% -distributor

    Enabling the instance in this way allows all components, including the event provider host, the generator, and the distributor, to run when you start the service.

  2. Type the following command to start the instance:
    net start NS$%InstanceName%
  3. Close the command prompt window.

You have now deployed the instance of Notification Services.

See Also

NSControl Create

NSControl Enable

NSControl Register

SQL Server Authentication Deployment Scenarios

Subscription Management Application Deployment Scenarios

Windows Authentication Deployment Scenarios


Clustered Single Server Deployment (Windows Authentication)

This scenario shows how to deploy an instance of Notification Services on a failover cluster using Windows Authentication; this configuration is similar to the single-server deployment scenario, but provides the availability offered by clustering. Typically, you would use this scenario for small to medium applications that require very high availability.

The following picture shows the hardware configuration for this deployment scenario. The servers, named NS1 and NS2, each have Notification Services and SQL Server 2000 installed. The NS$instance_name service is configured as a "Generic Service," allowing it to fail over to another server when necessary.

This configuration uses shared drives for the cluster quorum resource, all database files, and all operational files. Sharing drives allows the cluster to access the drives independent of which server in the cluster is active.

The disk layout shown in this picture depicts an optimal configuration. You can use other disk configurations. For more information, see Database Considerations.

Prerequisites
  • You have installed Windows 2000 Advanced Server or Datacenter on NS1 and NS2 and have applied all applicable service packs and updates. For more information, see Hardware and Software Requirements.
  • Windows Cluster Service is installed and running on NS1 and NS2. For more information, see the Step-by-Step Guide to Installing Cluster Service Web page.
  • You have added a cluster group resource named NSGroup to the cluster. This scenario assumes that the group contains the following resources:
    NSGroup resources | Description
    Cluster Name: NSCluster | Network name of server cluster
    SQL Server: SQLVS1 | Network name of SQL Server virtual node
    F, G, H, I, K | Shared disk drives available to the cluster
    SQLData | File share to the H drive, which is the location of the database files
    SQLLogs | File share to the I drive, which is the location of the database log files
    SQLTempDB | File share to the J drive, which is the location of the SQL Server tempdb database
  • You have installed an instance of SQL Server on both nodes of the cluster, creating a virtual SQL Server. For more information, see "Creating a Failover Cluster" in SQL Server Books Online.
  • You are running these procedures under an account that has administrative permissions on the server and is a member of the sysadmin fixed server role in SQL Server 2000.
  • You or your domain administrator have created two domain accounts: domain\NSService (used by the NS$instance_name service) and domain\Ops (used by anyone who monitors performance and runs reports).
  • You have created the NSDataFiles and NSSourceFiles directories, and have granted the necessary permissions to your account, the domain\NSService account, and the domain\Ops account. For more information, see Creating a Deployment Directory Structure. You create a cluster file share resource for each of these directories during deployment.

    Note If you print this topic, all tasks and their step-by-step instructions will appear in the printout.

NS1 Tasks

Move the cluster group to node NS1.

Node NS1 must own the cluster group NSGroup to complete these procedures. If NSGroup is not on NS1, you must use Cluster Administrator to move it to NS1.

  1. In Control Panel, open Administrative Tools, and then open Cluster Administrator.
  2. In the left pane, expand Groups.
  3. Select NSGroup, and then look at the Owner column in the right pane.
  4. If the Owner column indicates that NS2 owns the cluster group, right-click NSGroup, and then click Move.

NSGroup is now available to NS1.

Install Notification Services.

  • Install the Notification Services engine and database components on NS1. You can install additional components such as documentation, but other components are not required for deployment. Do not install the sample applications on production servers.

    For more information about installing components, see Installing Notification Services.

Make available the NSDataFiles and NSSourceFiles shares.

The network shares for the NSDataFiles and NSSouceFiles directories must be available to the cluster. To, you must add them to the cluster resource group and then map network drives.

  1. Create the NSDataFiles and NSSourceFiles directories on drive K. For more information, see Creating a Deployment Directory Structure.
  2. Create the NSDataFiles share in the cluster group.
    1. In Control Panel, open Administrative Tools, and then open Cluster Administrator.
    2. In the left pane, expand Groups.
    3. Right-click NSGroup, point to New, and then select Resource.
    4. On the New Resource page, enter the following information:

      Name: NSDataFiles

      Resource type: File Share

      Group: NSGroup

    5. On the Possible Owners page, select NS1 and NS2 in the Available nodes list, and then click Add to move them to the Possible owners list.
    6. On the Dependencies page, select K: in the Available resources list, and then click Add to move it to the Resource dependencies list.
    7. On the File Share Parameters page, verify that the following information is entered:

      Share name: NSDataFiles

      Path: K:\NSDataFiles

      User limit: Maximum allowed

    8. Click Finish to add the share to the cluster group.
  3. In the right pane of Cluster Administrator, right-click NSDataFiles, and then click Bring Online.
  4. Map the NSDataFiles share to drive S. For more information about mapping network drives, see your Windows documentation.
  5. Create the NSSourceFiles share in the cluster group.
    1. In Control Panel, open Administrative Tools, and then open Cluster Administrator.
    2. In the left pane, expand Groups.
    3. Right-click NSGroup, point to New, and then click Resource.
    4. On the New Resource page, enter the following information:

      Name: NSSourceFiles

      Resource type: File Share

      Group: NSGroup

    5. On the Possible Owners page, select NS1 and NS2 in the Available nodes list, and then click Add to move them to the Possible owners list.
    6. On the Dependencies page, select K: in the Available resources list, and then click Add to move them to the Resource dependencies list.
    7. On the File Share Parameters page, verify that the following information is entered:

      Share name: NSSourceFiles

      Path: K:\NSSourceFiles

      User limit: Maximum allowed

    8. Click Finish to add the share to the cluster group.
    9. Right-click NSSourceFiles, and then click Bring Online.
  6. Map the NSSourceFiles share to drive T. For more information about mapping network drives, see your Windows documentation.
  7. Secure the folders. For more information, see Creating a Deployment Directory Structure.
  8. Copy source files and operational files to the proper NSSourceFiles and NSDataFiles directories.

Grant local Windows permissions to the domain accounts.

This scenario uses two domain accounts: domain\NSService and domain\Ops.

  • Add the domain\NSService and domain\Ops accounts to the local Users group.

    These domain accounts require few privileges; the Users group provides the basic privileges. You grant additional privileges during the deployment process. For more information on adding accounts to a local group, see your Windows documentation.

Grant the domain accounts access to SQL Server.

The domain\NSService and domain\Ops accounts must be able to access the Notification Services databases. Additionally, the domain\NSService account requires permissions in the master database. Before you can grant database permissions to these accounts, you must grant access to SQL Server by creating login IDs.

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Set any necessary environment variables. This deployment scenario uses the following four environment variables:
    Set InstanceName=instance_name
Set SQLServer=database_server_name
Set NSSourceFilesRoot=path_to_NSSourceFiles
Set ConfigFileName=%NSSourceFilesRoot%\%InstanceName%\config_file_name.xml

    When you run these commands, the environment variables are active as long as the command prompt window is open.

    Your instance and applications may require additional environment variables. To reduce typing, you can create a batch file that contains all environment variables for your instance, and then run this batch file after you open the command prompt window.

  3. Type the following command to create a SQL Server login ID for the domain\NSService account:
    osql -E -S %SQLServer% -Q "EXEC sp_grantlogin 'domain\NSService'"
  4. Type the following command to create a SQL Server login ID for the domain\Ops account:
    osql -E -S %SQLServer% -Q "EXEC sp_grantlogin 'domain\Ops'"
  5. Leave the command prompt window open for the next procedure.

Grant the domain\NSService account permission to run extended stored procedures.

To generate and send notifications, the NS$instance_name service must be able to run the Notification Services extended stored procedures. Follow these steps to grant the account access to the master database, and then grant the necessary permissions.

  1. In the open command prompt window, type the following command to grant the domain\NSService account access to the master database:
    osql -E -S %SQLServer% -Q "USE master
   EXEC sp_grantdbaccess 'domain\NSService'"
  2. Type the following command to grant the domain\NSService account permission to run the Notification Services extended stored procedures.
    GrantXpExec "domain\NSService" -E -S %SQLServer%
  3. Leave the command prompt window open for the next procedure.

Register the instance of Notification Services.

Registering the instance creates the NS$instance_name service, which runs the instance of Notification Services.

  1. In the open command prompt window, type the following command:
    nscontrol register -name %InstanceName% -server %SQLServer%
   -serviceusername domain\NSService
   -servicepassword service_password -service

    The NSControl Register command creates the service; it also creates performance counters used to monitor the instance and creates registry entries for the instance.

  2. Leave the command prompt window open for the next procedure.

Create a Generic Service resource for NS$instance_name.

Generic Service resources enable Windows services, such as NS$instance_name, to be used as cluster resources. If node NS1 fails, the cluster resource group fails over to NS2, and the NS$instance_name service starts on NS2.

  1. In Control Panel, open Administrative Tools, and then open Cluster Administrator.
  2. Open Groups.
  3. Right-click NSGroup, point to New, and then click Resource.
  4. On the New Resource page, enter the following information:

    Name: instance_name

    Resource type: Generic Service

    Group: NSGroup.

  5. On the Possible Owners page, select NS1 and NS2 in the Available nodes list, and then click Add to move them to the Possible owners list.
  6. On the Dependencies page, select SQL Server in the Available resources list, and then click Add to move it to the Resource dependencies list.
  7. On the Generic Service Parameters page, type the following information:

    Service name: NS$instance_name

  8. On the Registry Replication page, click Finish.

Create the databases and grant database permissions.

NSControl Create uses data from the configuration file and ADFs to create the instance and application databases. After you create the databases, you can grant database permissions to the domain\NSService account. This is also a good time to grant database permissions to the domain\Ops account.

  1. In the open command prompt window, type the following command to create the instance and application databases:
    nscontrol create -in "%ConfigFileName%"
  2. Type the following command to grant the domain\NSService account access to the instance database and to add the account to the NSRunService database role:
    osql -E -S %SQLServer% -Q "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'domain\NSService'
   EXEC sp_addrolemember 'NSRunService', 'domain\NSService'"
  3. Type the following command to grant the domain\NSService account access to the application database and to add the account to the NSRunService database role:
    osql -E -S %SQLServer% -Q "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'domain\NSService'
   EXEC sp_addrolemember 'NSRunService', 'domain\NSService'"

    If the instance hosts multiple applications, repeat this step for each application database.

  4. Type the following command to grant the domain\Ops account access to the instance database and to add the account to the NSMonitor and NSAnalysis database roles:
    osql -E -S %SQLServer% -Q "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'domain\Ops'
   EXEC sp_addrolemember 'NSMonitor', 'domain\Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'domain\Ops'"
  5. Type the following command to grant the domain\Ops account access to the application database and to add the account to the NSMonitor and NSAnalysis database roles:
    osql -E -S %SQLServer% -Q "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'domain\Ops'
   EXEC sp_addrolemember 'NSMonitor', 'domain\Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'domain\Ops'"

    If the instance hosts multiple applications, repeat this step for each application database.

Enable all components.

After you have created the databases and have granted the necessary permissions, you can enable the instance and then start it by starting the NS$instance_name service.

Note Without event, subscriber, subscriber device, and subscription data, Notification Services will not generate notifications. If you have not configured an event source and deployed your subscription management application, you might want to complete those tasks before performing the following steps.

  1. Type the following command to enable the instance:
    nscontrol enable -name %InstanceName%

    Enabling the instance in this way allows all components, including the event provider host, the generator, and the distributor, to run when you start the service.

  2. Close the command prompt window.

Important Do not bring the Generic Service online at this time; bring the Generic Service online after configuring NS2.

NS2 Tasks

Move the cluster group to node NS2.

Node NS2 must own the cluster group NSGroup to complete these procedures. If NSGroup is not on NS2, you must use Cluster Administrator to move it to NS2.

  1. In Control Panel, open Administrative Tools, and then open Cluster Administrator.
  2. In the left pane, expand Groups.
  3. Select NSGroup, and then look at the Owner column in the right pane.
  4. If the Owner column indicates that NS1 owns the cluster group, right-click NSGroup, and then click Move.

NSGroup should now be available to NS2.

Install Notification Services.

  • Install the Notification Services engine on NS2. You can install additional components such as documentation, but other components are not required for deployment. Do not install the sample applications on production servers. For more information about installing components, see Installing Notification Services.

Map network drives.

  • To match the mappings on NS1, map the NSSourceFiles share to drive S and the NSDataFiles share to drive T. For more information about mapping network drives, see your Windows documentation.

Grant local Windows permissions to the domain accounts.

This scenario uses two domain accounts: domain\NSService and domain\Ops.

  • Add the domain\NSService and domain\Ops accounts to the local Users group.

    These domain accounts require few privileges on NS2; the Users group provides the basic privileges. You grant additional privileges during the deployment process. For more information on adding accounts to a local group, see your Windows documentation.

Register the instance of Notification Services.

Registering the instance creates the NS$instance_name service, which runs the instance of Notification Services. The service must be registered on NS2 in case of a failover.

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Set any necessary environment variables. This deployment scenario uses the following environment variables:
    Set InstanceName=instance_name
Set SQLServer=database_server_name

    When you run these commands, the environment variables are active as long as the command prompt window is open.

    Your instance and applications may require additional environment variables. To reduce typing, you can create a batch file that contains all environment variables for your instance, and then run this batch file after you open the command prompt window.

  3. In the open command prompt window, type the following command:
    nscontrol register -name %InstanceName% -server %SQLServer%
   -serviceusername domain\NSService
   -servicepassword service_password -service

    The NSControl Register command creates the service; it also creates performance counters used to monitor the instance and creates registry entries for the instance.

  4. Close the command prompt window.

Bring the Generic Service online.

To start the instance of Notification Services, bring the Generic Service online. If you want to start the service on NS1, move the cluster group to NS1 before performing these steps.

  1. In Control Panel, open Administrative Tools, and then open Cluster Administrator.
  2. In the left pane, expand Groups.
  3. Select NSGroup.
  4. In the right pane, right-click Generic Service, and click Bring Online.

You have now deployed the instance of Notification Services on a two-node cluster.

See Also

NSControl Create

NSControl Enable

NSControl Register

SQL Server Authentication Deployment Scenarios

Subscription Management Application Deployment Scenarios

Windows Authentication Deployment Scenarios


SQL Server Authentication Deployment Scenarios

An instance of Notification Services must be able to access its instance and application databases. To access these databases, the NS$instance_name service that runs the instance must be able to connect to SQL Server. These connections can use Windows Authentication or SQL Server Authentication.

This section contains instructions for deploying an instance of Notification Services that uses SQL Server Authentication to connect to SQL Server.

Important Microsoft recommends Windows Authentication because it uses the more secure Windows credentials instead of using credentials stored in a SQL Server database.

The topics that this section covers are described in the following table.

Topic | Description
Single-Server Deployment (SQL Server Authentication) | Provides step-by-step instructions for deploying an instance of Notification Services that uses SQL Server Authentication to connect to a local database server.
Remote Database Server (SQL Server Authentication) | Provides step-by-step instructions for deploying an instance of Notification Services that uses SQL Server Authentication to connect to a local database server.
Scale-Out Deployment (SQL Server Authentication) | Provides step-by-step instructions for deploying an instance of Notification Services on multiple servers if the instance uses SQL Server Authentication to connect to SQL Server.


Single-Server Deployment (SQL Server Authentication)

This scenario shows how to deploy an instance of Notification Services on a server that also hosts the databases and you use SQL Server Authentication to connect to SQL Server. Typically, you would use a single-server deployment for small to medium applications.

The following picture shows the hardware configuration for this deployment scenario. The server, named NS1, has multiple disk drives to improve the performance of the databases and the notification applications.

The disk layout shown in this picture depicts an optimal configuration. You can use other disk configurations. For more information, see Database Considerations.

Note If you print this topic, the steps within each procedure will appear in the printout.

Prerequisites
  • You have previously installed the operating system and SQL Server 2000 on NS1 and have applied all applicable service packs and updates. For more information, see Hardware and Software Requirements.
  • You are running these procedures under an account that has administrative permissions on the server and is a member of the sysadmin fixed server role in SQL Server 2000.
  • You or your domain administrator have created two domain accounts: domain\NSService (used by the NS$instance_name service) and domain\Ops (used by anyone who monitors performance and runs reports).
  • You have created file shares for source files and data files, and have granted the necessary permissions to your account, the domain\NSService account, and the domain\Ops account. For more information, see Creating a Deployment Directory Structure.
Tasks

Install Notification Services.

  • Install the Notification Services engine and database components on NS1. You can install additional components, such as documentation, but other components are not required for deployment. Do not install the sample applications on production servers.

    For more information about installing components, see Installing Notification Services.

Map network drives. (Optional)

Mapping network drives can simplify access to source files (files you use when you deploy an instance) and data files (files used while the instance is running).

  • To learn how to map network drives, see Creating a Deployment Directory Structure. For more information about mapping network drives, see your Windows documentation.

Grant local Windows permissions to the domain accounts.

This scenario uses two domain accounts: domain\NSService and domain\Ops.

  • Add the domain\NSService and domain\Ops accounts to the local Users group.

    These domain accounts require few privileges on NS1; the Users group provides the basic privileges. You grant additional privileges during the deployment process. For more information on adding accounts to a local group, see your Windows documentation.

Create SQL Server login accounts for the domain accounts.

The domain\NSService and domain\Ops accounts must be able to access the Notification Services databases. Additionally, the domain\NSService account requires permissions in the master database. Because you are using SQL Server Authentication, you cannot grant SQL Server access directly to the domain accounts. Instead you must create SQL Server login accounts that the NS$instance_name service and the people who monitor the instance can use.

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Set any necessary environment variables. This deployment scenario uses the following four environment variables:
    Set InstanceName=instance_name
Set SQLServer=database_server_name
Set NSSourceFilesRoot=instance_source_file_root
Set ConfigFileName=%NSSourceFilesRoot%\%InstanceName%\config_file_name.xml

    When you run these commands, the environment variables are active as long as the command prompt window is open.

    Your instance and applications may require additional environment variables. To reduce typing, you can create a batch file that contains all environment variables for your instance, and then run this batch file after you open the command prompt window.

  3. Type the following command to create a SQL Server login for the domain\NSService account:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "EXEC sp_addlogin 'NSService', 'sql_password'"
  4. Type the following command to create a SQL Server login for the domain\Ops account:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "EXEC sp_addlogin 'Ops', 'sql_password'"
  5. Leave the command prompt window open for the next procedure.

Grant the NSService login permission to run extended stored procedures.

To generate and send notifications, the NS$instance_name service must be able to run the Notification Services extended stored procedures. The following steps grant the login account used by the service access to the master database, and then grant the necessary permissions.

  1. In the open command prompt window, type the following command to grant the NSService login account access to the master database:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE master EXEC sp_grantdbaccess 'NSService'"
  2. Type the following command to grant the NSService login account permission to run the Notification Services extended stored procedures.
    GrantXpExec "NSService" -U dba_user_name -P dba_password
   -S %SQLServer%
  3. Leave the command prompt window open for the next procedure.

Create the NS$instance_name service.

Now that the account used by the NS$instance_name service is available, you can create the service.

  1. In the open command prompt window, type the following command:
    nscontrol register -name %InstanceName% -server %SQLServer%
   -serviceusername domain\NSService -servicepassword "service_password"
   -sqlusername NSService -sqlpassword sql_password -service

    The NSControl Register command creates the service; it also creates performance counters used to monitor the instance, creates registry entries for the instance, and provides a SQL Server ID and password that the service uses to connect to SQL Server.

  2. Leave the command prompt window open for the next procedure.

Create the databases and grant database permissions.

NSControl Create uses data from the configuration file and ADFs to create the instance and application databases. After you create the databases, you can grant database permissions to the NSService login account. This is also a good time to grant database permissions to the Ops login account.

  1. In the open command prompt window, type the following command to create the instance and application databases:
    nscontrol create -in "%ConfigFileName%"
  2. Type the following command to grant the NSService login account access to the instance database and to add the account to the NSRunService database role:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'NSService'
   EXEC sp_addrolemember 'NSRunService', 'NSService'"
  3. Type the following command to grant the NSService login account access to the application database and to add the account to the NSRunService database role:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'NSService'
   EXEC sp_addrolemember 'NSRunService', 'NSService'"

    If the instance hosts multiple applications, repeat this step for each application database.

  4. Type the following command to grant the Ops login account access to the instance database and to add the account to the NSMonitor and NSAnalysis database roles.
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'Ops'
   EXEC sp_addrolemember 'NSMonitor', 'Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'Ops'"
  5. Type the following command to grant the Ops login account access to the application database and to add the account to the NSMonitor and NSAnalysis database roles.
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'Ops'
   EXEC sp_addrolemember 'NSMonitor', 'Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'Ops'"

    If the instance hosts multiple applications, repeat this step for each application database.

Enable all components and then start the instance.

After you have created the databases and have granted the necessary permissions, you can enable the instance and then start the instance by starting the NS$instance_name service.

Important Without event, subscriber, subscriber device, and subscription data, Notification Services will not generate notifications. If you have not configured an event source and deployed your subscription management application, complete those tasks before performing the following steps.

  1. Type the following command to enable the instance:
    nscontrol enable -name %InstanceName%

    Enabling the instance in this way allows all components, including the event provider host, the generator, and the distributor, to run when you start the service.

  2. Type the following command to start the instance:
    net start NS$%InstanceName%
  3. Close the command prompt window.

You have now deployed the instance of Notification Services.

See Also

NSControl Create

NSControl Enable

NSControl Register

SQL Server Authentication Deployment Scenarios

Subscription Management Application Deployment Scenarios

Windows Authentication Deployment Scenarios


Remote Database Server Deployment (SQL Server Authentication)

This scenario shows how to deploy an instance of Notification Services when the databases are located on a remote server and you must use SQL Server Authentication to connect to SQL Server. This deployment is more scalable than the single-server deployment, and is a good solution for medium to large applications.

The following picture shows the hardware configuration for this deployment scenario. The scenario uses two servers: NS1 and SQL1. NS1 hosts the instance of Notification Services, and SQL1 hosts the instance and application databases. NS1 can use one or two disk drives; the number of drives is not critical on this server. However, SQL1 has multiple disk drives to improve the performance of the databases.

The disk layout shown in this picture depicts an optimal configuration. You can use other disk configurations. For more information, see Database Considerations.

Prerequisites
  • You have previously installed the operating system on NS1 and have applied all applicable service packs and updates. For more information, see Hardware and Software Requirements.
  • You have previously installed the operating system and SQL Server 2000 on SQL1 and have applied all applicable service packs and updates.
  • You are running these procedures under an account that has administrative permissions on the server and is a member of the sysadmin fixed server role in SQL Server 2000.
  • You or your domain administrator have created two domain accounts: domain\NSService (used by the NS$instance_name service) and domain\Ops (used by anyone who monitors performance and runs reports).
  • You have created file shares for source files and data files, and have granted the necessary permissions to your account, the domain\NSService account, and the domain\Ops account. For more information, see Creating a Deployment Directory Structure.

    Note If you print this topic, the steps within each procedure will appear in the printout.

NS1 Tasks

Install Notification Services.

  • Install the Notification Services engine and database components on NS1. You can install additional components, such as documentation, but other components are not required for deployment. Do not install the sample applications on production servers.

    For more information about installing components, see Installing Notification Services.

Map network drives. (Optional)

Mapping network drives can simplify access to source files (files you use when you deploy an instance) and data files (files used while the instance is running).

  • To learn how to map network drives, see Creating a Deployment Directory Structure. For more information about mapping network drives, see your Windows documentation.

Grant local Windows permissions to the domain accounts.

This scenario uses two domain accounts: domain\NSService and domain\Ops.

  • Add the domain\NSService and domain\Ops accounts to the local Users group.

    These domain accounts require few privileges on NS1; the Users group provides the basic privileges. You grant additional privileges during the deployment process. For more information on adding accounts to a local group, see your Windows documentation.

Grant the NSService login account permission to run extended stored procedures.

To generate and send notifications, the NS$instance_name service must be able to run the Notification Services extended stored procedures. The following steps grant the login account used by the service access to the master database, and then grant the necessary permissions.

  1. In the open command prompt window, type the following command to grant the NSService login account access to the master database:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE master EXEC sp_grantdbaccess 'NSService'"
  2. Type the following command to grant the NSService login account permission to run the Notification Services extended stored procedures.
    GrantXpExec "NSService" -U dba_user_name -P dba_password
   -S %SQLServer%
  3. Leave the command prompt window open for the next procedure.

Create the NS$instance_name service.

Now that the account used by the NS$instance_name service is available, you can create the service.

  1. In the open command prompt window, type the following command:
    nscontrol register -name %InstanceName% -server %SQLServer%
   -serviceusername domain\NSService -servicepassword "service_password"
   -sqlusername NSService -sqlpassword sql_password -service

    The NSControl Register command creates the service; it also creates performance counters used to monitor the instance, creates registry entries for the instance, and provides a SQL Server ID and password that the service uses to connect to SQL Server.

  2. Leave the command prompt window open for the next procedure.

Create the databases and grant database permissions.

NSControl Create uses data from the configuration file and the ADFs to create the instance and application databases. After you create the databases, you can grant database permissions to the NSService login account. This is also a good time to grant database permissions to the Ops login account.

  1. In the open command prompt window, type the following command to create the instance and application databases:
    nscontrol create -in "%ConfigFileName%"
  2. Type the following command to grant the NSService login account access to the instance database and to add the account to the NSRunService database role:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'NSService'
   EXEC sp_addrolemember 'NSRunService', 'NSService'"
  3. Type the following command to grant the NSService login account access to the application database and to add the account to the NSRunService database role:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'NSService'
   EXEC sp_addrolemember 'NSRunService', 'NSService'"

    If the instance hosts multiple applications, repeat this step for each application database.

  4. Type the following command to grant the Ops login account access to the instance database and to add the account to the NSMonitor and NSAnalysis database roles.
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'Ops'
   EXEC sp_addrolemember 'NSMonitor', 'Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'Ops'"
  5. Type the following command to grant the Ops login account access to the application database and to add the account to the NSMonitor and NSAnalysis database roles.
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'Ops'
   EXEC sp_addrolemember 'NSMonitor', 'Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'Ops'"

    If the instance hosts multiple applications, repeat this step for each application database.

Enable all components and then start the instance.

After you have created the databases and have granted the necessary permissions, you can enable the instance and then start the instance by starting the NS$instance_name service.

Important Without event, subscriber, subscriber device, and subscription data, Notification Services will not generate notifications. If you have not configured an event source and deployed your subscription management application, complete those tasks before performing the following steps.

  1. Type the following command to enable the instance:
    nscontrol enable -name %InstanceName%

    Enabling the instance in this way allows all components, including the event provider host, the generator, and the distributor, to run when you start the service.

  2. Type the following command to start the instance:
    net start NS$%InstanceName%
  3. Close the command prompt window.
SQL1 Tasks

Install Notification Services database components.

Because this scenario uses a remote database server, the SQL1 server does not run the NS$instance_name service, and is not used to administer the instance using the NSControl commands. For this reason, install only the database components on SQL1.

For more information, see Installing Database Components.

Create SQL Server login accounts for the domain accounts.

The domain\NSService and domain\Ops accounts must be able to access the Notification Services databases. Additionally, the domain\NSService account requires permissions in the master database. Because you are using SQL Server Authentication, you cannot grant SQL Server access directly to the domain accounts. Instead you must create SQL Server login accounts that can be used by the NS$instance_name service and the people who monitor the instance.

Note Because this procedure does not require the Notification Services client tools, you can run this procedure wherever the SQL Server client tools are installed. The SQL Server client tools must be installed on server NS1, so you can run this procedure on NS1 if you prefer.

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Set any necessary environment variables. On SQL1, this deployment scenario uses one environment variable:
    Set SQLServer=database_server_name

    When you run this command, the environment variable is active as long as the command prompt window is open.

  3. Type the following command to create a SQL Server login account for the domain\NSService account:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "EXEC sp_addlogin 'NSService', 'sql_password'"
  4. Type the following command to create a SQL Server login account for the domain\Ops account:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "EXEC sp_addlogin 'Ops', 'sql_password'"
  5. Close the command prompt window.

You have now deployed the instance of Notification Services.

See Also

NSControl Create

NSControl Enable

NSControl Register

SQL Server Authentication Deployment Scenarios

Subscription Management Application Deployment Scenarios

Windows Authentication Deployment Scenarios


Scale-Out Deployment (SQL Server Authentication)

This scenario shows how to deploy an instance of Notification Services on multiple servers; in this scenario the databases are located on a remote server, and you use SQL Server Authentication to connect to SQL Server. This deployment scenario is for large applications that need multiple servers for formatting and distributing notifications.

The following picture shows the hardware configuration for this deployment scenario. The scenario uses four servers: NS1, NS2, NS3, and SQL1. NS1 hosts the event provider host and generator for instance of Notification Services. NS2 and NS3 host distributor components for an instance of Notification Services. SQL1 hosts the instance and application databases. NS1, NS2, and NS3 can use one or two disk drives; the number of drives is not critical on this server. However, SQL1 has multiple disk drives to improve the performance of the databases.

The disk layout shown in this picture depicts an optimal configuration. You can use other disk configurations. For more information, see Database Considerations.

Prerequisites
  • You have previously installed the operating system on NS1, NS2, and NS3 and have applied all applicable service packs and updates. For more information, see Hardware and Software Requirements.
  • You have previously installed the operating system and SQL Server 2000 on SQL1 and have applied all applicable service packs and updates.
  • You are running these procedures under an account that has administrative permissions on the server and is a member of the sysadmin fixed server role in SQL Server 2000.
  • You or your domain administrator have created two domain accounts: domain\NSService (used by the NS$instance_name service) and domain\Ops (used by anyone who monitors performance and runs reports).
  • You have created file shares for source files and data files, and have granted the necessary permissions to your account, the domain\NSService account, and the domain\Ops account. For more information, see Creating a Deployment Directory Structure.

    Note If you print this topic, the steps within each procedure will appear in the printout.

SQL1 Tasks

Install Notification Services database components.

Since this scenario uses a remote database server, the SQL1 server does not run the NS$instance_name service, and is not used to administer the instance using the NSControl commands. For this reason, install only the database components on SQL1.

For more information, see Installing Database Components.

Create SQL Server login accounts for the domain accounts.

The domain\NSService and domain\Ops accounts must be able to access the Notification Services databases. Additionally, the domain\NSService account requires permissions in the master database. Because you are using SQL Server Authentication, you cannot grant SQL Server access directly to the domain accounts. Instead you must create SQL Server login accounts that the NS$instance_name service and the people who monitor the instance can use.

Note Because this procedure does not require the Notification Services client tools, you can run this procedure wherever the SQL Server client tools are installed. The SQL Server client tools must be installed on server NS1, so you can run this procedure on NS1 if you prefer.

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Set any necessary environment variables. On SQL1, this deployment scenario uses one environment variable:
    Set SQLServer=database_server_name

    When you run this command, the environment variable is active as long as the command prompt window is open.

  3. Type the following command to create a SQL Server login account for the domain\NSService account:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "EXEC sp_addlogin 'NSService', 'sql_password'"
  4. Type the following command to create a SQL Server login account for the domain\Ops account:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "EXEC sp_addlogin 'Ops', 'sql_password'"
  5. Close the command prompt window.
NS1 Tasks

Install Notification Services.

  • Install the Notification Services engine and database components on NS1. You can install additional components, such as documentation, but other components are not required for deployment. Do not install the sample applications on production servers.

    For more information about installing components, see Installing Notification Services.

Map network drives. (Optional)

Mapping network drives can simplify access to source files (files you use when you deploy an instance) and data files (files used while the instance is running).

  • To learn how to map network drives, see Creating a Deployment Directory Structure. For more information about mapping network drives, see your Windows documentation.

Grant local Windows permissions to the domain accounts.

This scenario uses two domain accounts: domain\NSService and domain\Ops.

  • Add the domain\NSService and domain\Ops accounts to the local Users group.

    These domain accounts require few privileges on NS1; the Users group provides the basic privileges. You grant additional privileges during the deployment process. For more information on adding accounts to a local group, see your Windows documentation.

Grant the NSService login account permission to run extended stored procedures.

To generate and send notifications, the NS$instance_name service must be able to run the Notification Services extended stored procedures. The following steps grant the login account used by the service access to the master database, and then grant the necessary permissions.

  1. In the open command prompt window, type the following command to grant the NSService login account access to the master database:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE master EXEC sp_grantdbaccess 'NSService'"
  2. Type the following command to grant the NSService login account permission to run the Notification Services extended stored procedures.
    GrantXpExec "NSService" -U dba_user_name -P dba_password
   -S %SQLServer%
  3. Leave the command prompt window open for the next procedure.

Create the NS$instance_name service.

Now that the account used by the NS$instance_name service is available, you can create the service.

  1. In the open command prompt window, type the following command:
    nscontrol register -name %InstanceName% -server %SQLServer%
   -serviceusername domain\NSService -servicepassword "service_password"
   -sqlusername NSService -sqlpassword sql_password -service

    The NSControl Register command creates the service; it also creates performance counters used to monitor the instance, creates registry entries for the instance, and provides a SQL Server ID and password that the service uses to connect to SQL Server.

  2. Leave the command prompt window open for the next procedure.

Create the databases and grant database permissions.

NSControl Create uses data from the configuration file and the ADFs to create the instance and application databases. After you create the databases, you can grant database permissions to the NSService login account. This is also a good time to grant database permissions to the Ops login account.

  1. In the open command prompt window, type the following command to create the instance and application databases:
    nscontrol create -in "%ConfigFileName%"
  2. Type the following command to grant the NSService login account access to the instance database and to add the account to the NSRunService database role:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'NSService'
   EXEC sp_addrolemember 'NSRunService', 'NSService'"
  3. Type the following command to grant the NSService login account access to the application database and to add the account to the NSRunService database role:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'NSService'
   EXEC sp_addrolemember 'NSRunService', 'NSService'"

    If the instance hosts multiple applications, repeat this step for each application database.

  4. Type the following command to grant the Ops login account access to the instance database and to add the account to the NSMonitor and NSAnalysis database roles.
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'Ops'
   EXEC sp_addrolemember 'NSMonitor', 'Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'Ops'"
  5. Type the following command to grant the Ops login account access to the application database and to add the account to the NSMonitor and NSAnalysis database roles.
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'Ops'
   EXEC sp_addrolemember 'NSMonitor', 'Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'Ops'"

    If the instance hosts multiple applications, repeat this step for each application database.

Enable the generator and events components and then start the instance.

After you have created the databases and have granted the necessary permissions, you can enable the instance and then start the instance by starting the NS$instance_name service.

Important Without event, subscriber, subscriber device, and subscription data, Notification Services will not generate notifications. If you have not configured an event source and deployed your subscription management application, complete those tasks before performing the following steps.

  1. Type the following command to enable the generator and event provider host:
    nscontrol enable -name %InstanceName% -generator -events

    Enabling the instance in this way runs only the generator and event provider host on NS1 when you start the service.

  2. Type the following command to start the instance:
    net start NS$%InstanceName%
  3. Close the command prompt window.
NS2 and NS3 Tasks

Install Notification Services.

  • Install the Notification Services engine and database components on NS1. You can install additional components, such as documentation, but other components are not required for deployment. Do not install the sample applications on production servers.

    For more information about installing components, see Installing Notification Services.

Map network drives. (Optional)

Mapping network drives can simplify access to source files (files you use when you deploy an instance) and data files (files used while the instance is running).

  • To learn how to map network drives, see Creating a Deployment Directory Structure. For more information about mapping network drives, see your Windows documentation.

Grant local Windows permissions to the domain accounts.

This scenario uses two domain accounts: domain\NSService and domain\Ops.

  • Add the domain\NSService and domain\Ops accounts to the local Users group.

    These domain accounts require few privileges on NS1; the Users group provides the basic privileges. You will grant additional privileges during the deployment process. For more information on adding accounts to a local group, see your Windows documentation.

Create the NS$instance_name service.

Now that the account used by the NS$instance_name service is available, you can create the service.

  1. In the open command prompt window, type the following command:
    nscontrol register -name %InstanceName% -server %SQLServer%
   -serviceusername domain\NSService -servicepassword "service_password"
   -sqlusername NSService -sqlpassword sql_password -service

    The NSControl Register command creates the service; it also creates performance counters used to monitor the instance, creates registry entries for the instance, and provides a SQL Server ID and password that the service uses to connect to SQL Server.

  2. Leave the command prompt window open for the next procedure.

Enable the distributor component and then start the instance.

After you have created the databases and have granted the necessary permissions, you can enable the instance and then start the instance by starting the NS$instance_name service.

  1. Type the following command to enable the distributor component:
    nscontrol enable -name %InstanceName% -distributor

    Enabling the instance in this way runs only the distributor when you start the service.

  2. Type the following command to start the instance:
    net start NS$%InstanceName%
  3. Close the command prompt window.

You have now deployed the instance of Notification Services.

See Also

NSControl Create

NSControl Enable

NSControl Register

SQL Server Authentication Deployment Scenarios

Subscription Management Application Deployment Scenarios

Windows Authentication Deployment Scenarios


Clustered Single Server (SQL Server Authentication)

This scenario shows how to deploy an instance of Notification Services on a cluster using SQL Server Authentication; this configuration is similar to the single-server deployment scenario, but provides the availability offered by clustering. Typically, you would use this scenario for small to medium applications that require very high availability.

The following picture shows the hardware configuration for this deployment scenario. The servers, named NS1 and NS2, both have Notification Services and SQL Server 2000 installed. The NS$instance_name service is configured as a "Generic Service", allowing it to fail over to another server when necessary.

The configuration uses shared drives for the cluster quorum resource, all database files, and all operation files for the instance of Notification Services. Sharing drives allows the cluster to access the drives independent of which server in the cluster is active.

The cluster quorum resource, required for every cluster, maintains the configuration data necessary for recovery of the cluster. This data, in the form of recovery logs, contains details of all of the changes that have been applied to the cluster database. This provides node-independent storage for cluster configuration and state data.

The disk layout shown in this picture depicts an optimal configuration. You can use other disk configurations. For more information, see Database Considerations.

Prerequisites
  • You have installed Windows 2000 Advanced Server or Datacenter on NS1 and NS2.and have applied all applicable service packs and updates. For more information, see Hardware and Software Requirements.
  • Windows Cluster Service is installed and running on NS1 and NS2. For more information, see the Step-by-Step Guide to Installing Cluster Service Web page.
  • You have added a cluster group resource, named NSGroup, to the cluster. This scenario assumes that the group contains the following resources:
    NSGroup resources | Description
    Cluster Name: NSCluster | Network name of server cluster
    SQL Server: SQLVS1 | Network name of SQL Server virtual node
    F, G, H, I, K | Shared disk drives available to the cluster
    SQLData | File share to the H drive, which is the location of the database files
    SQLLogs | File share to the I drive, which is the location of the database log files
    SQLTempDB | File share to the J drive, which is the location of the SQL Server tempdb database
  • You have installed SQL Server on both nodes of the cluster, creating a virtual SQL Server instance. For more information, see "Creating a Failover Cluster" in SQL Server Books Online. (All references to SQL Server are to the virtual server name.)
  • You are running these procedures under an account that has administrative permissions on the server, and you are using a SQL Server login account that is a member of the sysadmin fixed server role.
  • You or your domain administrator have created two domain accounts: domain\NSService (used by the NS$instance_name service) and domain\Ops (used by anyone who monitors performance and runs reports).
  • You have created the NSDataFiles and NSSourceFiles directories, and have granted the necessary permissions to your account, the domain\NSService account, and the domain\Ops account. For more information, see Creating a Deployment Directory Structure. You create a cluster file share resource for each of these directories during deployment.

    Note If you print this topic, all tasks and their step-by-step instructions will appear in the printout.

NS1 Tasks

Move the cluster group to node NS1

Node NS1 must own the cluster group NSGroup to complete these procedures. If NSGroup is not on NS1, you must use Cluster Administrator to move it to NS1.

  1. In Control Panel, open Administrative Tools, and then open Cluster Administrator.
  2. In the left pane, expand Groups.
  3. Select NSGroup, and then look at the Owner column in the right pane.
  4. If the Owner column indicates that NS2 owns the cluster group, right-click NSGroup, and then click Move.

NSGroup should now be available to NS1.

Install Notification Services.

  • Install the Notification Services engine and database components on NS1. You can install additional components, such as documentation, but other components are not required for deployment. Do not install the sample applications on production servers.

    For more information about installing components, see Installing Notification Services.

Add the NSDataFiles and NSSourceFiles shares to the cluster resource group and then map network drives.

The network shares for the NSDataFiles and NSSouceFiles directories must be available to the cluster. To make these shares available, you must add them to the cluster group.

  1. Create the NSDataFiles and NSSourceFiles directories on drive K. For more information, see Creating a Deployment Directory Structure.
  2. Create the NSDataFiles share in the cluster group.
    1. In Control Panel, open Administrative Tools, and then open Cluster Administrator.
    2. In the left pane, expand Groups.
    3. Right-click NSGroup, point to New, and then click Resource.
    4. On the New Resource page, enter the following information:

      Name: NSDataFiles

      Resource type: File Share

      Group: NSGroup

    5. On the Possible Owners page, select NS1 and NS2 in the Available nodes list, then click Add to move them to the Possible owners list.
    6. On the Dependencies page, select K: in the Available resources list, then click Add to move it to the Resource dependencies list.
    7. On the File Share Parameters page, verify that the following information is entered:

      Share name: NSDataFiles

      Path: K:\NSDataFiles

      User limit: Maximum allowed

    8. Click Finish to add the share to the cluster group.
  3. In the right pane of Cluster Administrator, right-click NSDataFiles, and then click Bring Online.
  4. Map the NSDataFiles share to drive S. For more information about mapping network drives, see your Windows documentation.
  5. Create the NSSourceFiles share in the cluster group.
    1. In Control Panel, open Administrative Tools, and then open Cluster Administrator.
    2. In the left pane, expand Groups.
    3. Right-click NSGroup, point to New, and then select Resource.
    4. On the New Resource page, enter the following information:

      Name: NSSourceFiles

      Resource type: File Share

      Group: NSGroup

    5. On the Possible Owners page, select NS1 and NS2 in the Available nodes list, and then click Add to move them to the Possible owners list.
    6. On the Dependencies page, select K: in Available resources list, and then click Add to move them to Resource dependencies list.
    7. On the File Share Parameters page, verify that the following information is entered:

      Share name: NSSourceFiles

      Path: K:\NSSourceFiles

      User limit: Maximum allowed

    8. Click Finish to add the share to the cluster group.
    9. Right-click NSSourceFiles, and then click Bring Online.
  6. Map the NSSourceFiles share to drive T. For more information about mapping network drives, see your Windows documentation.
  7. Secure the folders. For more information, see Creating a Deployment Directory Structure.
  8. Copy source files and operational files to the proper NSSourceFiles and NSDataFiles directories.

Grant local Windows permissions to the domain accounts.

This scenario uses two domain accounts: domain\NSService and domain\Ops.

  • Add the domain\NSService and domain\Ops accounts to the local Users group.

    These domain accounts require few privileges; the Users group provides the basic privileges. You grant additional privileges during the deployment process. For more information on adding accounts to a local group, see your Windows documentation.

Create SQL Server login accounts for the domain accounts.

The domain\NSService and domain\Ops accounts must be able to access the Notification Services databases. Additionally, the domain\NSService account requires permissions in the master database. Because you are using SQL Server Authentication, you cannot grant SQL Server access directly to the domain accounts. Instead, you must create SQL Server login accounts that can be used by the NS$instance_name service and the people who monitor the instance.

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Set any necessary environment variables. This deployment scenario uses the following four environment variables:
    Set InstanceName=instance_name
Set SQLServer=database_server_name
Set NSSourceFilesRoot=instance_source_file_root
Set ConfigFileName=%NSSourceFilesRoot%\%InstanceName%\config_file_name.xml

    When you run these commands, the environment variables are active as long as the command prompt window is open.

    Your instance and applications may require additional environment variables. To reduce typing, you can create a batch file that contains all environment variables for your instance, and then run this batch file after you open the command prompt window.

  3. Type the following command to create a SQL Server login account for the domain\NSService account:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "EXEC sp_addlogin 'NSService', 'sql_password'"
  4. Type the following command to create a SQL Server login account for the domain\Ops account:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "EXEC sp_addlogin 'Ops', 'sql_password'"
  5. Leave the command prompt window open for the next procedure.

Grant the NSService login account permission to run extended stored procedures.

To generate and send notifications, the NS$instance_name service must be able to run the Notification Services extended stored procedures. The following steps grant the login account used by the service access to the master database, and then grant the necessary permissions.

  1. In the open command prompt window, type the following command to grant the NSService login account access to the master database:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE master EXEC sp_grantdbaccess 'NSService'"
  2. Type the following command to grant the NSService login account permission to run the Notification Services extended stored procedures.
    GrantXpExec "NSService" -U dba_user_name -P dba_password
   -S %SQLServer%
  3. Leave the command prompt window open for the next procedure.

Register the instance of Notification Services.

Now that the account used by the NS$instance_name service is available, you can create the service.

  1. In the open command prompt window, type the following command:
    nscontrol register -name %InstanceName% -server %SQLServer%
   -serviceusername domain\NSService
   -servicepassword service_password
   -sqlusername NSService -sqlpassword sql_password -service

    The NSControl Register command creates the service; it also creates performance counters used to monitor the instance, creates registry entries for the instance, and provides a SQL Server ID and password that the service uses to connect to SQL Server.

  2. Leave the command prompt window open for additional procedures.

Create a Generic Service resource for NS$instance_name.

Generic Service resources enable Windows services, such as NS$instance_name, to be used as cluster resources. If node NS1 fails, the cluster resource group fails over to NS2, and the NS$instance_name service starts on NS2.

  1. In Control Panel, open Administrative Tools, and then open Cluster Administrator.
  2. Open Groups.
  3. Right-click NSGroup, point to New, and then click Resource.
  4. On the New Resource page, enter the following information:

    Name: instance_name

    Resource type: Generic Service

    Group: NSGroup

  5. On the Possible Owners page, select NS1 and NS2 in the Available nodes list, and then click Add to move them to Possible owners list.
  6. On the Dependencies page, select SQL Server in the Available resources list, and then click Add to move it to Resource dependencies list.
  7. On the Generic Service Parameters page, type the following information:

    Service name: NS$instance_name

  8. On the Registry Replication page, click Finish.

Create the databases and grant database permissions.

NSControl Create uses data from the configuration file and the ADFs to create the instance and application databases. After you create the databases, you can grant database permissions to the domain\NSService account. This is also a good time to grant database permissions to the domain\Ops account.

  1. In the open command prompt window, type the following command to create the instance and application databases:
    nscontrol create -in "%ConfigFileName%"
   -sqlusername dba_user_name -sqlpassword dba_password
  2. Type the following command to grant the NSService login account access to the instance database and to add the account to the NSRunService database role:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'NSService'
   EXEC sp_addrolemember 'NSRunService', 'NSService'"
  3. Type the following command to grant the NSService login account access to the application database and to add the account to the NSRunService database role:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'NSService'
   EXEC sp_addrolemember 'NSRunService', 'NSService'"

    If the instance hosts multiple applications, repeat this step for each application database.

  4. Type the following command to grant the Ops login account access to the instance database and to add the account to the NSMonitor and NSAnalysis database roles.
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'Ops'
   EXEC sp_addrolemember 'NSMonitor', 'Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'Ops'"
  5. Type the following command to grant the Ops login account access to the application database and to add the account to the NSMonitor and NSAnalysis database roles.
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'Ops'
   EXEC sp_addrolemember 'NSMonitor', 'Ops'
   EXEC sp_addrolemember 'NSAnalysis', 'Ops'"

    If the instance hosts multiple applications, repeat this step for each application database.

Enable all components and then start the instance.

After you have created the databases and have granted the necessary permissions, you can enable the instance and then start the instance by bringing the Generic Service online.

Note Without event, subscriber, subscriber device, and subscription data, Notification Services will not generate notifications. If you have not configured an event source and deployed your subscription management application, you might want to complete those tasks before performing the following steps.

  1. Type the following command to enable the instance:
    nscontrol enable -name %InstanceName%
   -sqlusername dba_user_name -sqlpassword dba_password

    Enabling the instance in this way allows all components, including the event provider host, the generator, and the distributor, to run when you start the service.

  2. Close the command prompt window.
NS2 Tasks

Move the cluster group to node NS2.

Node NS2 must own the cluster group NSGroup to complete these procedures. If NSGroup is not on NS2, you must use Cluster Administrator to move it to NS2.

  1. In Control Panel, open Administrative Tools, and then open Cluster Administrator.
  2. In the left pane, expand Groups.
  3. Select NSGroup, and then look at the Owner column in the right pane.
  4. If the Owner column indicates that NS1 owns the cluster group, right-click NSGroup, and then click Move.

NSGroup should now be available to NS2.

Install Notification Services.

  • Install the Notification Services engine on NS2. You can install additional components, such as documentation, but other components are not required for deployment. Do not install the sample applications on production servers.

    For more information about installing components, see Installing Notification Services.

Map network drives.

To match the mappings on NS1, map the NSSourceFiles share to drive S and the NSDataFiles share to T. For more information about mapping network drives, see your Windows documentation.

Grant local Windows permissions to the domain accounts.

This scenario uses two domain accounts: domain\NSService and domain\Ops.

  • Add the domain\NSService and domain\Ops accounts to the local Users group.

    These domain accounts require few privileges on NS2; the Users group provides the basic privileges. You grant additional privileges during the deployment process. For more information on adding accounts to a local group, see your Windows documentation.

Register the instance of Notification Services.

Registering the instance creates the NS$instance_name service, which runs the instance of Notification Services. The service must be registered on NS2 in case of a failover.

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Set any necessary environment variables. This deployment scenario uses the following environment variables:
    Set InstanceName=instance_name
Set SQLServer=database_server_name

    When you run these commands, the environment variables are active as long as the command prompt window is open.

    Your instance and applications may require additional environment variables. To reduce typing, you can create a batch file that contains all environment variables for your instance, and then run this batch file after you open the command prompt window.

  3. In the open command prompt window, type the following command:
    nscontrol register -name %InstanceName% -server %SQLServer%
   -serviceusername domain\NSService
   -servicepassword service_password
   -sqlusername NSService -sqlpassword sql_password -service

    The NSControl Register command creates the service; it also creates performance counters used to monitor the instance and creates registry entries for the instance.

  4. Close the command prompt window.

Bring the Generic Service online.

To start the instance of Notification Services, bring the Generic Service online. If you want to start the service on NS1, move the cluster group to NS1 before performing these steps.

  1. In Control Panel, open Administrative Tools, and then open Cluster Administrator.
  2. In the left pane, expand Groups.
  3. Select NSGroup.
  4. In the right pane, right-click Generic Service, and then click Bring Online.

You have now deployed the instance of Notification Services on a two-node cluster.

See Also

NSControl Create

NSControl Enable

NSControl Register

SQL Server Authentication Deployment Scenarios

Subscription Management Application Deployment Scenarios

Windows Authentication Deployment Scenarios


Subscription Management Application Deployment Scenarios

Subscription management applications are typically Web-based applications that subscribers can use to create and manage subscriptions. The steps for deploying a subscription management application depend on whether the application is deployed on the database server or on a remote server, and whether the application uses Windows Authentication or SQL Server Authentication to connect to SQL Server.

This section contains several deployment scenarios for ASP.NET-based subscription management applications. Each scenario provides step-by-step instructions for deploying the subscription management application.

Scenario Steps

Follow these steps to deploy a subscription management application:

  1. Determine whether the application will be located on the database server or on a remote server. Only intranet-based applications should be deployed on the database server. Most Internet-based applications are deployed on an existing Web server.
  2. Determine the security model used by the application. If possible, use Windows Authentication, since it is more secure and easier to manage.
  3. If the subscription management application is located on a server that does not host the Notification Services instance, install the Notification Services client components and register the instance.
  4. Grant database permissions to the account used by the subscription management application to connect to SQL Server.

The topics that this section covers are described in the following table.

Topic | Description
Deploying a Subscription Management Application on the Database Server (Windows Authentication) | Provides step-by-step instructions for deploying a subscription management application on the database server, using Windows Authentication.
Deploying a Subscription Management Application on a Remote Server (Windows Authentication) | Provides step-by-step instructions for deploying a subscription management application on a server that does not host the databases, using Windows Authentication.
Deploying a Subscription Management Application on the Database Server (SQL Server Authentication) | Provides step-by-step instructions for deploying a subscription management application on the database server, using SQL Server Authentication.
Deploying a Subscription Management Application on a Remote Server (SQL Server Authentication) | Provides step-by-step instructions for deploying a subscription management application on a server that does not host the databases, using SQL Server Authentication.

See Also

Notification Services Deployment Scenarios


Deploying a Subscription Management Application on the Database Server (Windows Authentication)

For intranet-based notification applications, your subscription management application might be on the same server as the instance and application databases. Having your application and databases together simplifies deployment because you do not need to create a domain account that the subscription management application uses to connect to SQL Server.

This scenario shows how to deploy a Microsoft ASP.NET-based subscription management application using Windows Authentication. ASP.NET-based applications can use a built-in account named ASPNET. If the application is an ASP-based application (not ASP.NET), you must create define a different account for the application.

Prerequisites
  • The ASPNET account exists on the database server. The Microsoft .NET Framework Setup program creates this account. If the ASPNET account does not exist, you can create the account by running the following command (for version 1.0.3705):
    %windir%\Microsoft.NET\Framework\v1.0.3705\ASPNET_REGIIS.exe –I
  • You have added the application to Internet Information Services (IIS), but have not yet configured security for the application.

    Note If you print this topic, the steps within each procedure will appear in the printout.

Tasks

Install Notification Services client components, if necessary.

  • Install the Notification Services client components on the database server. If you have already installed the engine components on this server, you do not need to install the client components.

    For more information about installing components, see Installing Notification Services.

Register the instance, if necessary.

The subscription management application requires the instance of Notification Services to be registered so it can locate the databases. If the database server hosts only the database components (not the engine components), the instance was not previously registered. Register the instance using NSControl Register.

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Set any necessary environment variables. This deployment scenario uses the following environment variables:
    Set SQLServer=database_server_name
Set InstanceName=instance_name
Set AppName=application_name

    When you run this command, the environment variables are active as long as the command prompt window is open.

  3. Type the following command to register the instance:
    nscontrol register -name %InstanceName% -server %SQLServer%

    This registers the instance on SQL1. The –service option is omitted to avoid installing the NS$instance_name service.

  4. Leave the command prompt window open for the next procedure.

Grant the computer\ASPNET account access to SQL Server.

The computer\ASPNET account must be able to access the Notification Services databases. Before you can grant database permissions to this account, you must grant access to SQL Server by creating a login ID.

  1. In the open command prompt window, type the following command to create a SQL Server login ID for the computer\ASPNET account:
    osql -E -S %SQLServer% -Q "EXEC sp_grantlogin 'computer\ASPNET'"
  2. Leave the command prompt window open for the next procedure.

Grant database access and permissions to the SQL Server login account.

After creating the login account for computer\ASPNET, grant permissions in the instance and application databases. The subscription management application manages subscriber data in the instance database and subscription data in the application databases.

  1. In the open command prompt window, type the following command to grant the computer\ASPNET account access to the instance database and add it to the NSSubscriberAdmin database role:
    osql -E -S %SQLServer% -Q "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess ' computer\ASPNET'
   EXEC sp_addrolemember 'NSSubscriberAdmin', 'computer\ASPNET'"
  2. Type the following command to grant the computer\ASPNET account access to an application database and add it to the NSSubscriberAdmin database role:
    osql -E -S %SQLServer% -Q "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'computer\ASPNET'
   EXEC sp_addrolemember 'NSSubscriberAdmin', 'computer\ASPNET'"

    If the subscription management application manages subscriptions for multiple applications, repeat this step for each application database.

  3. Ensure that the subscription management application has access to the Notification Services assembly and any necessary localized resource files. For more information, see Providing Access to the Notification Services Assembly and Localized Resource Files.

You can now use the subscription management application to manage subscribers and subscriptions for the instance of Notification Services.

See Also

Notification Services Deployment Scenarios

Subscription Management Application Deployment Scenarios


Deploying a Subscription Management Application on a Remote Server (Windows Authentication)

For Internet-based notification applications, your subscription management application is typically deployed on an existing Internet Information Services (IIS) Web server.

This scenario shows how to deploy a Microsoft ASP.NET-based subscription management application on a remote IIS server using Windows Authentication. This scenario requires a domain account that your subscription management application uses to connect to SQL Server. The procedures in this topic show you how to create this login account and grant the necessary permissions.

Prerequisites
  • You (or your domain administrator) have created a domain account used by the ASP.NET-based application. This is required to allow an application on a remote server to connect to SQL Server using Windows Authentication.
  • You have added the application to Internet Information Services (IIS), but have not yet configured security for the application.
  • You have already deployed the instance of Notification Services, which created the instance and application databases on the database server.

    Note If you print this topic, the steps within each procedure will appear in the printout.

IIS Server Tasks

Install the client components.

  • Install the Notification Services client components on the IIS server. The client components include the Notification Services subscription management objects and the NSControl utility. The client components do not require a Notification Services license.

    For more information about installing components, see Installing Notification Services.

Register the instance.

The subscription management application requires the instance of Notification Services to be registered so it can locate the databases. Register the instance using NSControl Register.

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Set any necessary environment variables. This deployment scenario uses the following environment variables:
    Set SQLServer=database_server_name
Set InstanceName=instance_name

    When you run these commands, the environment variables are active as long as the command prompt window is open.

  3. In the open command prompt window, type the following command to register the instance without creating the NS$instance_name service:
    nscontrol register -name %InstanceName% -server %SQLServer%
  4. Ensure that the subscription management application has access to the Notification Services assembly and any necessary localized resource files. For more information, see Providing Access to the Notification Services Assembly and Localized Resource Files.
  5. Close the command prompt window.

Configure security for ASP.NET-based applications.

Important The following procedure changes the account used by all ASP.NET-based applications on the IIS server to run under the domain\ASPNET account. This may not be compatible with existing ASP.NET-based applications.

  1. Using Notepad, open the Machine.config file.

    This file should be located at %windir%\Microsoft.NET\Framework\v1.0.3705\CONFIG.

  2. Locate the <processModel> element. This element has several attributes, including userName and password.
  3. Set the userName value to domain\ASPNET and the password value to the password for the domain ASPNET account. The element should look like this:
    <processModel
   ...
   userName="domain\ASPNET"
   password="aspnet_password"
   ...
/>
  4. Save the Machine.config file.
  5. Grant the domain\ASPNET account Full Control to the %windir%Microsoft.NET\Framework\v1.0.3705\Temporary ASP.NET Files folder.

    For more information on granting permissions to folders, see your Windows documentation.

  6. Restart IIS to apply the changes.
Database Server Tasks

Grant the domain\ASPNET account access to SQL Server.

The domain\ASPNET account must be able to access the Notification Services databases. Before you can grant database permissions to this account, you must grant access to SQL Server.

  1. In the open command prompt window, type the following command to grant SQL Server access to the domain\ASPNET account:
    osql -E -S %SQLServer% -Q "EXEC sp_grantlogin 'domain\ASPNET'"
  2. Leave the command prompt window open for the next procedure.

Grant database access and permissions to the SQL Server login account.

After granting SQL Server access to domain\ASPNET, grant permissions in the instance and application databases. The subscription management application manages subscriber data in the instance database and subscription data in the application databases.

  1. In the open command prompt window, type the following command to grant the domain\ASPNET account access to the instance database and add it to the NSSubscriberAdmin database role:
    osql -E -S %SQLServer% -Q "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'domain\ASPNET'
   EXEC sp_addrolemember 'NSSubscriberAdmin', 'domain\ASPNET'"
  2. Type the following command to grant the domain\ASPNET account access to an application database and add it to the NSSubscriberAdmin database role:
    osql -E -S %SQLServer% -Q "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'domain\ASPNET'
   EXEC sp_addrolemember 'NSSubscriberAdmin', 'domain\ASPNET'"

    If the subscription management application manages subscriptions for multiple applications, repeat this step for each application database.

You can now use the subscription management application to manage subscribers and subscriptions for the instance of Notification Services.

See Also

Notification Services Deployment Scenarios

Subscription Management Application Deployment Scenarios


Deploying a Subscription Management Application on the Database Server (SQL Server Authentication)

For intranet-based notification applications, your subscription management application might be on the same server as the instance and application databases. Keeping your application and databases together simplifies deployment because you do not need to create a domain account that the subscription management application uses to connect to SQL Server.

This scenario shows how to deploy a Microsoft ASP.NET-based subscription management application using SQL Server Authentication for connections to the databases. You must define a SQL Server login account that your subscription management application uses to connect to SQL Server. The procedures in this topic show you how to create this login account and grant the necessary permissions.

Prerequisites
  • The subscription management application was developed to use a SQL Server login account for connections to SQL Server. For the purpose of this scenario, the account is called SMA.
  • You have added the application to Internet Information Services (IIS), but have not yet configured security for the application.

    Note If you print this topic, the steps within each procedure will appear in the printout.

Tasks

Install Notification Services client components, if necessary.

  • Install the Notification Services client components on the database server. If you have already installed the engine components on this server, you do not need to install the client components.

    For more information about installing components, see Installing Notification Services.

Register the instance, if necessary.

The subscription management application requires the instance of Notification Services to be registered so that it can locate the databases. If the database server hosts only the database components (not the engine components), the instance was not previously registered. Register the instance using the NSControl Register command.

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Set any necessary environment variables. This deployment scenario uses one environment variable:
    Set SQLServer=database_server_name
Set InstanceName=instance_name
Set AppName=application_name

    When you run this command, the environment variable is active as long as the command prompt window is open.

  3. In the open command prompt window, type the following command to register the instance without creating the NS$instance_name service:
    nscontrol register -name %InstanceName% -server %SQLServer%
  4. Leave the command prompt window open for the next procedure.

Create the SMA SQL Server login account.

The subscription management application uses the SMA SQL Server login account to connect to SQL Server. You must create the login account and assign a password.

  1. In the open command prompt window, type the following command to create the SMA login account and define a password:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "EXEC sp_addlogin 'SMA', 'sql_password'"
  2. Leave the command prompt window open for the next procedure.

Grant database access and permissions to the SMA login account.

After creating the SMA login account, grant permissions in the instance and application databases. The subscription management application manages subscriber data in the instance database and subscription data in the application databases.

  1. In the open command prompt window, type the following command to grant the SMA login account access to the instance database and add it to the NSSubscriberAdmin database role:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'SMA'
   EXEC sp_addrolemember 'NSSubscriberAdmin', 'SMA'"
  2. Type the following command to grant the SMA login account access to an application database and add it to the NSSubscriberAdmin database role:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'SMA'
   EXEC sp_addrolemember 'NSSubscriberAdmin', 'SMA'"

    If the subscription management application manages subscriptions for multiple applications, repeat this step for each application database.

  3. Ensure that the subscription management application has access to the Notification Services assembly and any necessary localized resource files. For more information, see Providing Access to the Notification Services Assembly and Localized Resource Files.

You can now use the subscription management application to manage subscribers and subscriptions for the instance of Notification Services.

See Also

Notification Services Deployment Scenarios

Subscription Management Application Deployment Scenarios


Deploying a Subscription Management Application on a Remote Server (SQL Server Authentication)

For Internet-based notification applications, your subscription management application is typically deployed on an existing Internet Information Services (IIS) Web server.

This scenario shows how to deploy a Microsoft ASP.NET-based subscription management application on a remote IIS server using SQL Server Authentication to connect to the databases. You must define a SQL Server login account that your subscription management application uses to connect to SQL Server. The procedures in this topic show you how to create this login account and grant the necessary permissions.

Prerequisites
  • The subscription management application was developed to use a SQL Server login account for connections to SQL Server. For the purpose of this scenario, the account is called SMA.
  • You have added the application to Internet Information Services (IIS), but have not yet configured security for the application.
  • You have already deployed the instance of Notification Services, which created the instance and application databases on the database server.

    Note If you print this topic, the steps within each procedure will appear in the printout.

IIS Server Tasks

Install the client components.

  • Install the Notification Services client components on the IIS server. The client components include the Notification Services subscription management objects and the NSControl utility. The client components do not require a Notification Services license.

    For more information about installing components, see Installing Notification Services.

Register the instance.

The subscription management application requires the instance of Notification Services to be registered so that it can locate the databases. Register the instance using NSControl Register.

  1. On the Start menu, point to Programs\Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Set any necessary environment variables. This deployment scenario uses the following environment variables:
    Set SQLServer=database_server_name
Set InstanceName=instance_name

    When you run these commands, the environment variables are active as long as the command prompt window is open.

  3. In the open command prompt window, type the following command to register the instance without creating the NS$instance_name service:
    nscontrol register -name %InstanceName% -server %SQLServer%
  4. Ensure that the subscription management application has access to the Notification Services assembly and any necessary localized resource files. For more information, see Providing Access to the Notification Services Assembly and Localized Resource Files.
  5. Close the command prompt window.
Database Server Tasks

Create the SMA SQL Server login account.

The subscription management application uses the SMA SQL Server login account to connect to SQL Server. You must create the login account and assign a password.

  1. Set any necessary environment variables. The procedures on the database server use the following environment variables:
    Set SQLServer=database_server_name
Set InstanceName=instance_name
Set AppName=application_name

    When you run these commands, the environment variables are active as long as the command prompt window is open.

  2. In the open command prompt window, type the following command to create the SMA login account and define a password:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "EXEC sp_addlogin 'SMA', 'sql_password'"
  3. Leave the command prompt window open for the next procedure.

Grant database access and permissions to the SMA login account.

After creating the SMA login account, grant permissions in the instance and application databases. The subscription management application manages subscriber data in the instance database and subscription data in the application databases.

  1. In the open command prompt window, type the following command to grant the SMA login account access to the instance database and add it to the NSSubscriberAdmin database role:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%NSMain
   EXEC sp_grantdbaccess 'SMA'
   EXEC sp_addrolemember 'NSSubscriberAdmin', 'SMA'"
  2. Type the following command to grant the SMA login account access to an application database and add it to the NSSubscriberAdmin database role:
    osql -U dba_user_name -P dba_password -S %SQLServer% -Q
   "USE %InstanceName%%AppName%
   EXEC sp_grantdbaccess 'SMA'
   EXEC sp_addrolemember 'NSSubscriberAdmin', 'SMA'"

    If the subscription management application manages subscriptions for multiple applications, repeat this step for each application database.

You can now use the subscription management application to manage subscribers and subscriptions for the instance of Notification Services.

See Also

Notification Services Deployment Scenarios

Subscription Management Application Deployment Scenarios


Providing Access to the Notification Services Assembly and Localized Resource Files

When deploying a subscription management application, a non-hosted event provider, or another application that interacts with the Notification Services API, you must provide a way for the application to locate the Notification Services assembly (which contains the Notification Services API classes) and localized resource files. Applications use these files to interact with Notification Services and to write event messages to the local application log.

You can provide access to the files for all applications running on the server, or you can provide access for a single application. To provide access for applications, register the assembly and localized resource files with the global assembly cache. To provide access for a single application, copy the assembly to the Bin folder of the application, and copy the localized resource files to the Bin\language_code folders of the application.

The primary reason to provide access for a single application instead of all applications is security. If you do not want all applications to be able to interact with Notification Services, do not register the assembly or resource files with the global assembly cache.

The following procedures assume you have already installed the Notification Services client components on the server that hosts the subscription management applications.

To register files in the global assembly cache for use by all applications

  1. Open a command prompt window.
  2. Go to the Microsoft .NET Framework directory, where the Gacutil.exe file is located. For the .NET Framework version 1.0.3705, type the following:
    CD %windir%\Microsoft.NET\Framework\v1.0.3705
  3. Type the following command to register the assembly and the English resources in the global assembly cache:
    GACUTIL /i "%ProgramFiles%\Microsoft SQL Server Notification
   Services\vx.x.xxxx.x\Bin\
   Microsoft.SqlServer.NotificationServices.dll"
  4. To register resources for a language other than English, type the following command:
    GACUTIL /i "%ProgramFiles%\Microsoft SQL Server Notification
   Services\vx.x.xxxx.x\Bin\language_code\
   Microsoft.SqlServer.NotificationServices.resources.dll"

    Repeat this step for each non-English language any subscription management applications support.

To provide access to the files for a single application

  1. Open a command prompt window.
  2. Copy the assembly to the Bin directory of the application. For example, for an ASP.NET-based subscription management application located at \\Webserver\Wwwroot\SMAroot\Bin, type the following:
    Copy "%ProgramFiles%\Microsoft SQL Server Notification Services
   \vx.x.xxxx.x\Bin\Microsoft.SqlServer.NotificationServices.dll"
   \\webserver\wwwroot\smaroot\bin
  3. Copy the localized resource files to the proper Bin\language_code folders. For example, for an ASP.NET-based subscription management application located at \\Webserver\Wwwroot\SMAroot\Bin, type the following:
    Copy "%ProgramFiles%\Microsoft SQL Server Notification Services
   \vx.x.xxxx.x\Bin\language_code\
   Microsoft.SqlServer.NotificationServices.resources.dll"
   \\WebServer\wwwroot\smaroot\bin\language_code

    Repeat this step for each non-English language any subscription management applications support.

See Also

Subscription Management Application Deployment Scenarios


Managing Instances and Applications

After you deploy an instance of Notification Services, you might need to update the instance and its applications. Notification Services supports updating instances and applications with the NSControl command prompt utility.

In addition to maintaining the instance and application configurations, you must ensure that the built-in data removal process, called vacuuming, is running. This removes obsolete data from an application database, which improves performance and saves disk space.

Another management task is backing up databases and other instance and application files on a regular schedule, and periodically testing the restore process in preparation for possible hardware failures or data loss.

The topics that this section covers are described in the following table.

Topic | Description
Updating Instances and Applications | Provides information and instructions for updating or deleting an instance that is deployed.
Removing Obsolete Data | Provides information and instructions for removing obsolete data in Notification Services application databases.
Backing Up and Recovering Notification Services | Provides information and instructions for backing up and restoring Notification Services databases, configuration data, and operational data.

See Also

Event Messages

Managing Security

Managing Services

Performance Monitoring and Reporting

Troubleshooting


Updating Instances and Applications

After you deploy an instance of Notification Services, you might need to update the operational parameters of the instance, such as delivery channels. You also can add and delete applications from the instance and modify existing applications.

In Notification Services you update an instance by updating its configuration file. You update applications hosted by the instance by editing the application definition files (ADFs), updating the configuration file as necessary for the application updates. You then apply the changes using the NSControl utility.

You also might need to remove an application from an instance, or delete an instance completely. These actions also are supported by NSControl.

The topics that this section covers are described in the following table.

Topic | Description
Updating Instance Properties | Explains how to use NSControl Update to update changes to the configuration file.
Adding an Application to an Instance | Provides instructions for adding an application to a deployed instance of Notification Services.
Updating an Application | Provides instructions for updating a single application while other applications remain operational.
Removing an Application from an Instance | Provides instructions for removing an application from a deployed instance of Notification Services.
Enabling and Disabling an Instance, Application, or Component | Explains how to enable or disable an instance, one or more instance components, or one or more of its hosted applications.
Re-Registering an Instance | Explains how to re-register an instance using NSControl Register.
Starting and Stopping a Deployed Instance | Explains how to start or stop an instance by starting or stopping its NS$instance_name service.
Deleting an Instance | Explains how to delete an instance using NSControl commands.

See Also

Configuring and Deploying Instances

Managing Security

Managing Services

Performance Monitoring and Reporting


Updating Instance Properties

After creating an instance of Notification Services, you might need to update properties of the instance, such as the available delivery channels. You update instance properties by updating the configuration file, temporarily disabling the instance, applying the changes using NSControl Update, and then enabling the instance.

During the update process, NSControl Update reads your updated configuration file and compares it with the metadata in the existing instance database to determine which changes were made.

You can add or delete applications, delivery protocols, and delivery channels in the configuration file. You can change the database system name, but doing so will not move the instance to a new server. You cannot update the instance name or database properties; to change these properties, you must create a new instance. For complete information about which configuration file elements can be updated, see the Configuration File Reference.

Note NSControl Update also reads each application definition file (ADF) and compares the information in those files to the metadata in the application databases. If there are differences in the ADFs, NSControl Update updates the applications also. For more information, see Updating an Application.

To update instance properties

  1. Using an XML editor, update the configuration file.
  2. Back up the instance and application databases. For more information, see Backing Up Databases and Other Files.
  3. On the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  4. Type the following command to disable the instance:
    nscontrol disable -name instance_name
  5. Type the following command to stop the NS$instance_name service:
    net stop NS$instance_name
  6. Type the following command to apply the changes made in the configuration file:
    nscontrol update -in configuration_filename

    If the instance or application uses command-line parameters, your NSControl Update command will contain additional arguments. For more information, see NSControl Update.

  7. To update performance counters, stop the NS$instance_name service and re-register the instance using NSControl Register. If you do not use the performance counters or do not need them to be updated, do not perform this step.
  8. Type the following command to enable the instance:
    nscontrol enable -name instance_name
  9. Type the following command to start the NS$instance_name service:
    net start NS$instance_name

See Also

Adding an Application to an Instance

Deleting an Instance

NSControl Disable

NSControl Enable

NSControl Update

Removing an Application from an Instance

Re-Registering an Instance


Adding an Application to an Instance

A Notification Services instance can host multiple applications. Two important benefits of using one instance for multiple applications are that the applications share the same set of subscribers, and the applications can be administered as a group.

You can add applications after you deploy an instance. To add an application, you gather application files, add the information about the application to the configuration file, and then update the instance using NSControl Update.

Note Before adding an application, gather the application definition file (ADF) and all operational files, such as XML Schema definition language (XSD), XSLT, or custom component files.

To add an application to a deployed instance

  1. Create or obtain the ADF for the new application.
  2. In the configuration file, do the following:
    • Add an <Application> node to define the application.
    • Add any custom protocols to the <Protocols> node and any additional delivery channels to the <DeliveryChannels> node.
    • If necessary for the new application, add default parameter values using the <ParameterDefaults> node.
  3. Back up the instance and application databases. For more information, see Backing Up Databases and Other Files.
  4. On the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  5. Type the following command to disable the instance:
    nscontrol disable -name instance_name
  6. Type the following command to apply the changes made in the configuration file:
    nscontrol update -in configuration_filename

    If the instance or application uses command-line parameters, your NSControl Update command will contain additional arguments. For more information, see NSControl Update.

  7. To update performance counters, stop the NS$instance_name service and re-register the instance using NSControl Register.

    This step updates performance counters, user names, and passwords. If you do not use the performance counters or do not need them to be updated, do not perform this step.

  8. Type the following command to enable the instance:
    nscontrol enable -name instance_name

See Also

Configuration File Reference

Removing an Application from an Instance

Updating Instances and Applications


Updating an Application

After you deploy a Notification Services instance, you can update individual applications hosted by the instance. You update an application by updating the application definition file (ADF), modifying any of the operational files (such as by adding or deleting XSLT files or custom components), and then using the NSControl Update command to apply the changes.

To update a single application, you do not need to stop or disable the entire instance. You can leave other applications hosted by the instance running while you update a single application. However, if you also change values in the configuration file, you must disable the entire instance before applying the update.

When you update an application, consider the following:

  • If you change a subscription class in the ADF, NSControl Update usually must create a new subscriptions table. NSControl Update backs up the existing table. For more information, see NSControl Update.
  • Updating an application typically deletes event and notification data. Plan to resubmit any batches of events that have not been processed before the update, or any batches of events that would have been processed while the application is being updated.

    Important You can rename the application in the configuration file. However, this is considered a change to the instance properties, so it requires you to disable the instance. When you apply the name change, Notification Services creates a new application database, but does not delete the old database.

To update one application with no configuration changes

  1. Update the elements in the ADF and any operational files, such as XSLT files and DLLs for custom components.
  2. Back up the instance and application databases. For more information, see Backing Up Databases and Other Files.
  3. On the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  4. Type the following command to disable the application:
    nscontrol disable -name instance_name -application application_name
  5. Type the following command to apply the changes made in the ADF:
    nscontrol update -in configuration_filename

    If the instance or application uses command-line parameters, your NSControl Update command will contain additional arguments. For more information, see NSControl Update.

  6. To update performance counters, stop the NS$instance_name service and re-register the instance using NSControl Register.

    This updates performance counters, user names, and passwords. If you do not use the performance counters or do not need to update them, do not perform this step.

  7. From a command prompt, type the following command to enable the application:
    nscontrol enable -name instance_name -application application_name

See Also

Adding an Application to an Instance

Removing an Application from an Instance

Updating Instances and Applications


Removing an Application from an Instance

After you deploy a Notification Services instance, you might determine that you need to remove an application. For example, you might want to permanently delete an obsolete application or move the application to another instance.

When you remove an application from an instance, Notification Services simply disassociates the application from the instance. Notification Services does not delete the application database or any of the application files from the server. You can manually delete the databases by using Transact-SQL or SQL Server Enterprise Manager.

Important Do not use the NSControl Delete command to remove applications from an instance. NSControl Delete deletes the instance database and the application databases for all applications hosted by the instance.

To remove an application from a deployed instance

  1. In the configuration file, do the following:
    • Remove the <Application> node that represents the application.
    • Remove any application-specific custom protocols from the <Protocols> node.
    • Remove any application-specific delivery channels from the <DeliveryChannels> node.
    • Remove any application-specific default parameter values from the <ParameterDefaults> node.
  2. Back up the instance and application databases. For more information, see Backing Up Databases and Other Files.
  3. On the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  4. Type the following command to disable the instance:
    nscontrol disable -name instance_name
  5. Type the following command to apply the changes made in the configuration file:
    nscontrol update -in configuration_filename

    If the instance or application uses command-line parameters, your NSControl Update command will contain additional arguments. For more information, see NSControl Update.

  6. To update performance counters, stop the NS$instance_name service and re-register the instance using NSControl Register.

    This updates performance counters, user names, and passwords. If you do not use the performance counters or do not need them to be updated, do not perform this step.

  7. Type the following command to enable the instance:
    nscontrol enable -name instance_name

See Also

Adding an Application to an Instance

Configuration File Reference

NSControl Disable

NSControl Enable

NSControl Register

NSControl Update


Enabling and Disabling an Instance, Application, or Component

After you deploy an instance, you might need to temporarily stop the instance, a single application hosted by the instance, or a component of an instance or application for maintenance or troubleshooting reasons. You stop an instance, application, or component using the NSControl Disable command. You can later enable the component using NSControl Enable.

Note If you disable the generator component (or if you disable an instance or application) the clock that controls quantum processing stops. When you enable the generator, the generator attempts to catch up to the current real-time clock. This might have some impact on how quickly new notifications are generated, depending on the level of activity in the application. The application definition file (ADF) defines the limit for how many previous quantum periods the generator attempts to process using the <SubscriptionQuantumLimit> and <ChronicleQuantumLimit> values.

To enable an instance, application, or component

  1. On the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Run the NSControl Enable command to enable the instance. For more information, see NSControl Enable.

To disable an instance, application, or component

  1. On the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Run the NSControl Disable command to disable the instance. For more information, see NSControl Disable.

To view the status of an instance, application, or component

  1. On the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Run the NSControl Status command to view the status. For more information, see NSControl Status.

See Also

Starting and Stopping an Instance


Re-Registering an Instance

After you create a Notification Services instance, you register the instance on each server where the instance runs using NSControl Register. Registering the instance creates the NS$instance_name service, registers the service with Microsoft Windows®, updates user names and passwords for the service, and creates performance counters.

There are times when you need to re-register the instance to update this information:

  • If you add or remove an application, re-registering the application updates the performance counters.
  • If the NS$instance_name service uses SQL Server Authentication to connect to SQL Server, you must re-register the instance to update the SQL Server user name and password.
  • You can change the user name and password of the account the service runs under by re-registering the instance.
  • If performance counters become corrupted, re-registering the instance might fix the problem.

To register or re-register an instance of Notification Services

  1. If the NS$instance_name service is running, stop the service. For more information, see Starting and Stopping a Service.
  2. On the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  3. Type the following command to unregister the instance:
    nscontrol unregister -name instance_name
  4. Run the NSControl Register command. The arguments you use will vary depending on your system configuration. For more information, see NSControl Register.

See Also

Configuring an NS$instance_name Service

Managing Security

Registering and Unregistering an Instance


Stopping and Restarting a Deployed Instance

On each server that hosts a Notification Services instance, the instance is run by a Windows service named NS$instance_name. Stopping the service stops the Notification Services instance on the local server. If the instance runs on that server only, the instance is completely stopped. If the instance is scaled out across multiple servers, stopping the NS$instance_name service on that server stops the processing only on that server.

When possible, use the NSControl Disable command to stop components of an instance without stopping the entire instance.

Stopping a deployed instance of Notification Services has varying effects, depending on which components are run by the service you are stopping:

Generator component: Notification Services stops collecting event data and stops generating notifications. However, the clock that controls quantum processing stops. When you restart the service that runs the generator, the generator attempts to catch up to the current clock time, and past-due processing takes priority. When you re-start the instance, this can have a minor or major impact on how quickly new notifications are generated (depending on the activity level of the application). The application definition file (ADF) defines the limit for how many previous quantum periods the generator attempts to process using the <SubscriptionQuantumLimit> and <ChronicleQuantumLimit> values.

Event provider component: Events cannot be collected. You might need to resubmit any event batches that was submitted while the event provider component is disabled.

Distributor component: Notifications cannot be delivered. When you restart the service, there might be a backlog of notifications to deliver.

You can use the NSSnapshotApplications stored procedure to determine how far behind all the applications hosted by an instance have fallen (based on the number of quantum periods the generator is running behind), both when the instance is stopped and when it is running. This can help you determine whether quanta will be skipped when you restart an instance.

To stop an instance of Notification Services

  • From a command prompt, type:
    net stop NS$instance_name

To restart an instance of Notification Services

  • From a command prompt, type:
    net start NS$instance_name

See Also

NSControl Disable

Starting and Stopping a Service


Deleting an Instance

Deleting a Notification Services instance deletes the instance and application databases. After deleting the instance, you must unregister the instance to remove performance counters, the NS$instance_name service, and registry entries.

Important Deleting an instance is an irreversible action. If you have not backed up your databases, all data in those databases is permanently lost. However, if you remove an application from an instance, databases are not deleted. For more information, see Removing an Application from an Instance.

Before deleting a deployed instance, develop a plan for migrating any subscriber and subscription data to new instances if necessary. Data Transformation Services and the bcp utility are two SQL Server tools you can use for transferring data from a database to a destination.

When you delete an instance, the Notification Services extended stored procedures in the master database are not removed because the instance cannot detect whether other instances are using the extended stored procedures.

To delete a Notification Services instance

  1. Back up the instance and application databases. For more information, see Backing Up Databases and Other Files.
  2. From the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  3. Type the following command to delete the instance:
    nscontrol delete -name instance_name -server database_server_name
  4. Type the following command to unregister the instance:
    nscontrol unregister -name instance_name

See Also

Backing Up and Recovering Notification Services

NSControl Delete

NSControl Unregister

Removing Notification Services

UninstallXPs Utility


Removing Obsolete Data

If too much data accumulates in your Notification Services application database, it can affect performance in two ways. First, large tables affect query performance, because there is excess data for SQL Server to search. Second, when data files become large, SQL Server might automatically increase the file size; this operation consumes system resources.

Notification Services uses a process called vacuuming to remove obsolete data from application databases. Vacuuming is a process that runs automatically for each application according to a schedule defined for the application.

When a developer creates an application, the developer can define a custom retention age for data. This is the minimum age for events, notifications, and other data before the vacuuming process can remove the data. The developer can also define a custom vacuuming schedule. This schedule determines when the vacuuming process begins and how long it runs. If the developer does not define a custom retention age and schedule, the application uses the default settings. For more information, see the reference topics for the <Vacuum> Node.

When applications are running, you must ensure that the vacuuming process is running. If vacuuming is running, but the application requires a different vacuuming configuration, you can update vacuuming by updating the application definition file (ADF). If necessary, you can run vacuuming manually.

The topics that this section covers are described in the following table.

Topic | Description
Verifying Vacuuming | Provides methods for confirming that the vacuumer process is running as scheduled.
Modifying the Vacuuming Schedule | Provides instructions for updating the vacuuming schedule in the ADF and then applying these changes to the application.
Running Vacuuming Manually | Provides instructions for running the vacuumer process using a stored procedure.

See Also

Defining the <Vacuum> Node

<Vacuum> Node


Verifying Vacuuming

For every application, you should periodically check to ensure that vacuuming is running as scheduled. If large amounts of data accumulate in the application database, application performance might decline, and the database might run out of disk space. Notification Services provides stored procedures and performance counters for monitoring applications, which you can use to monitor vacuuming.

The NSSnapshotApplications stored procedure returns five vacuuming values for each application:

  • VacuumerSystemName: The name of the computer system running the vacuumer.
  • LastTimeVacuumingOccurred: The date and time the last vacuuming period started.
  • SecondsSinceLastVacuum: The elapsed time, in seconds, since the vacuumer last ran.
  • LastTimeVacuumEventCount: The number of events removed when the vacuumer last ran.
  • LastTimeVacuumNotificationsCount: The number of notifications removed when the vacuumer last ran.

The NS$instance_name: Vacuumer performance object provides performance counters relevant to vacuumer processing. You monitor the counters provided by this object to determine whether the vacuumer component is timing out and how many quanta have been vacuumed or are ready to be vacuumed.

Vacuuming removes notifications only if they have been delivered or if they have expired. Vacuuming removes events only if they have been processed. Vacuuming removes quanta only if the notifications and events associated with them have been removed. If data that you expect to be removed is not yet removed, then there is likely a dependent piece of data that cannot yet be removed.

See Also

Modifying the Vacuuming Schedule

NS$instance_name: Vacuumer Object

NSSnapshotApplications


Modifying the Vacuuming Schedule

To adjust the vacuuming schedule for a Notification Services application, you must update the application definition file (ADF) and then update the application.

The ADF contains a section named <ApplicationExecutionSettings>; within this section is a <Vacuum> node. This node defines the retention age of data and the schedule used to run the vacuumer. For more information about defining a vacuuming schedule, see Defining the <Vacuum> Node.

If you modify the vacuuming schedule, configure the schedule so that vacuuming runs at times of low system activity. Vacuuming consumes system resources and might cause lower application performance while the vacuumer is running.

To modify the vacuuming schedule and apply the changes

  1. Open the ADF for the application you want to update.
  2. Add or edit the <Vacuum> node in the <ApplicationExecutionSettings> node by doing the following:
    • To change the minimum age for data that should be removed, change the <RetentionAge> value. For more information, see <RetentionAge> Element.
    • To change the schedule, modify the <VacuumSchedule> node. For more information, see <VacuumSchedule> Node.
  3. Back up the instance and application databases. For more information, see Backing Up Databases and Other Files.
  4. From the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  5. Type the following command to disable the application:
    nscontrol disable -name instance_name -application application_name
  6. Type the following command to update the application:
    nscontrol update -in configuration_filename

    If the instance or application uses command-line parameters, your NSControl Update command will contain additional arguments. For more information, see NSControl Update.

  7. To update performance counters, stop the NS$instance_name service and re-register the instance using NSControl Register.

    This updates performance counters, user names, and passwords. If you do not use the performance counters or do not need them to be updated, do not perform this step.

  8. Type the following command to enable the application:
    nscontrol enable -name instance_name -application application_name

See Also

Application Definition File Reference

NSControl Disable

NSControl Enable

NSControl Register

NSControl Update

Removing Obsolete Data


Running Vacuuming Manually

The best way to remove obsolete data from an application database is to let the vacuumer run as scheduled. If the vacuuming schedule is not optimal, change the schedule in the application definition file (ADF) and then update the application. You should run vacuuming manually only if you determine that vacuuming has not run as scheduled and there is an urgent need to remove obsolete data.

Important Do not run the vacuumer manually when the vacuumer is running or is scheduled to run. Application errors might occur, resulting in no data being removed. Look at the ADF to determine the vacuuming schedule. If the ADF does not contain a <Vacuum> node, the application uses the default vacuuming schedule. For more information, see Defining the <Vacuum> Node.

Use the NSVacuum stored procedure, located in the application database, to run vacuuming manually. For more information, see NSVacuum.

See Also

Removing Obsolete Data


Backing Up and Recovering Notification Services

Backing up instances of Notification Services should be a regular maintenance task. Without backups of the instance and application database files, operational files, configuration file, and application definition files (ADFs), you cannot recover applications to a point in time.

When you recover an instance, Notification Services determines the last completed quantum from the application database and resumes processing from that point, possibly skipping quanta according to settings in the ADF. Because of this, and because subscriber and subscription data is located in the instance and application databases, frequent backups are important for optimal application recovery.

The topics that this section covers are described in the following table.

Topic | Description
Planning for Recovery | Provides lists of the software and information you need when recovering Notification Services instances, and provides recommendations for creating your own recovery plan.
Backing Up Databases and Other Files | Explains what files need to be backed up so you can recover an instance of Notification Services.
Recovering Notification Services | Provides step-by-step instructions for recovering an instance of Notification Services.


Planning for Recovery

Use the following lists to get started with planning for the recovery of Notification Services applications.

Even though these lists can help you plan for recovery, it is important to develop your own recovery lists and instructions for your applications because each application and deployment is unique.

Software

Ensure that the following software is available for recovery:

  • Operating system media
  • SQL Server 2000 media
  • Notification Services Setup program
  • Notification Services prerequisite software
  • Any service packs or patches applied to the operating system, SQL Server, or Notification Services
  • Any operational files used by Notification Services applications, such as custom components, XML Schema definition language (XSD) files, and XSLT files
  • Configuration files and application definition files (used only for instance and application updates)
  • Subscription management applications
Security Information

Ensure that the following security information is available to those who will restore the instance:

  • User names and passwords that the NS$instance_name services run under.
  • If using SQL Server Authentication, the SQL Server user name and password used by the NS$instance_name service to connect to SQL Server.
  • User names and passwords used by subscription management applications.
  • The local or domain user account used to install software and run NSControl commands.
  • The SQL Server administrator account used to run NSControl commands.

See Also

Backing Up Databases and Other Files

Recovering Notification Services


Backing Up Databases and Other Files

To back up an instance of Notification Services, you must back up database and operational files (such as XSLT files used to format notifications), and the files used to configure the instance and applications.

Backing Up Database Files

Each instance has one instance database and one or more application databases. The instance database contains information about the Notification Services instance, including subscriber and subscriber device data. The application databases contain all application-specific information, including the events, subscriptions, notifications, and information about the state of the application.

For Notification Services, the best recovery model is Full. Using the database, differential, and transaction log backups provided by the Full recovery model enables you to restore the instance and application databases to a point in time. An example schedule for backups could be full database backups each night, differential backups every 3 hours, and transaction log backups every 30 minutes. Using this model, even if the hard drive that stores the transaction log is damaged, you should be able to restore the instance to within 30 minutes of the failure.

For more information about SQL Server recovery models, see "Using Recovery Models" in SQL Server Books Online.

Important Back up the instance and application databases on the same schedule. This ensures that the databases are at the same operational state, and reduces the likelihood of application errors after recovery.

Backing Up Operational Files

Other than the database files, most instances require additional files during operation. For example, an application that uses the file system watcher event provider uses one or more XSD files that describe event data. Any application that uses XSLT to format notifications has one or more XSLT files. And any application that uses custom objects has additional files for those custom objects.

To recover an instance, you must have all operational files for all applications hosted by the instance. If these other files are not available, parts of the applications will fail when restored.

Because these other operational files typically change less often than the database files, you probably do not need to back up these files as often as the database files. But you should either store the source files using a version control system or back up the files whenever you change them.

Backing Up Configuration and ADF Files

The configuration file and the application definition files (ADFs) are not required by the instance and its applications when the applications are running. However, you use these files whenever you update the instance or applications. If you do not have backups of these files available, you must re-create these files if the original files are lost. For this reason, you should either store these files in a version control system or back up the files whenever you change them.

Because these files sometimes contain passwords or other information that you do not want others to see, you should secure all backups of these files.

See Also

Recovering Notification Services


Recovering Notification Services

When you recover an instance of Notification Services, you are recovering the instance and application databases or the Notification Services engine components, or possibly both.

Important Depending on your system configuration, your recovery instructions might vary from the ones below. It is very important that you test system recovery and create your own recovery instructions for your instances and applications.

Important If an instance of Notification Services is scaled out across multiple servers, the servers must be restored with the same names or you must update the configuration file and application definition files (ADFs) and then run the NSControl Update command.

Recovering Notification Services Only

If you must recover Notification Services, but have not lost the instance and application databases, you only have to install Notification Services, register all instances, and then start the instances.

To recover Notification Services only, without database recovery

  1. Rebuild the server, installing the operating system, Notification Services prerequisites, any necessary service packs, and then Notification Services. For more information, see Installing Notification Services.
  2. Restore any operational files that were lost.

    The operational files, such as custom components, Extensible Schema definition language (XSD) files for the file system watcher event provider, and XSLT files for notification formatting, should be installed to a central location; the location is specified in the configuration file.

  3. If you are using local Windows accounts for the NS$instance_name service or for running NSControl commands, restore the local accounts.
  4. Register the instance using NSControl Register.
  5. From a command prompt, type the following command to start the instance:
    net start ns$instance_name
Recovering Databases Only

If the instance and application databases are lost, you can restore the databases to the point of the most recent backup plus the current transaction log, if available.

To recover instance and application databases

  1. Gather the backups of the instance and application databases.
  2. Rebuild the database server, installing SQL Server 2000 and any necessary service packs or patches.
  3. Install the Notification Services database components. For more information, see Installing Database Components.
  4. Restore the instance and application databases. For more information about restoring databases, see "Using Recovery Models" in SQL Server Books Online.
  5. Restore security. For more information, see User Accounts Required by Notification Services Applications.
  6. From a command prompt, type the following command to start the instance:
    net start ns$instance_name
Restoring Notification Services and the Databases

If you lose the Notification Services engine components and the databases, it is best to restore the databases first. The only reason is that the databases must be available before you can restore security and then start the instance.

To restore an instance of Notification Services and its databases

  1. Gather the backups of the databases and other operational files.
  2. Restore the database server by doing the following:
    1. Rebuild the server, installing SQL Server 2000 and necessary service packs or patches, and then install the Notification Services database components.
    2. Restore the instance and application databases. For more information about restoring databases, see "Using Recovery Models" in SQL Server Books Online.
  3. Restore Notification Services engine components by doing the following:
    1. Rebuild the server or servers that run the Notification Services instance. These are the servers that run the event providers, the generator, and the distributors.
    2. Restore security. For more information, see User Accounts Required by Notification Services Applications.
    3. Register the instance using NSControl Register.
  4. From a command prompt, type the following command to start the instance:
    net start ns$instance_name

See Also

Backing Up Databases and Other Files


Managing Services

The Notification Services engine is run by a Windows service named NS$instance_name (referred to within the Notification Services documentation as "the NS$instance_name service" or simply "the service"). The service runs the event provider, generator, and distributor components.

The service controls the operation of the instance and its associated applications. The service can be started and stopped, which starts and stops the instance, and individual components of the service can be enabled and disabled, providing control over the operation of the instance.

You install the service when you register an instance of Notification Services.

After you install the service, you must enable and start the instance when you want to run the Notification Services instance and its applications. You can configure the service for automatic startup and automatic restart.

Depending on system configuration, an instance has one or more services associated with it:

  • If Notification Services is installed on one server, one service runs the event provider, generator, and distributor components.
  • If Notification Services is installed on multiple servers for scalability, one service is installed on each server. Each instance can have one generator, zero to many hosted event providers, and one or more distributors.

Because one service can run all components of Notification Services, you must enable or disable the event provider, generator, and distributor components as needed. For example, you can run the event provider and generator on one server, and the distributor on another server. An instance of this sort would have two services: one on each server.

Note Multiple server deployment is available only in Notification Services Enterprise Edition.

The NS$instance_name service topics that this section covers are described in the following table.

Topic | Description
Installing an NS$instance_name Service | Provides instructions for installing the NS$instance_name service on a server.
Configuring an NS$instance_name Service | Explains how to configure NS$instance_name service startup and restart behavior.
Enabling and Disabling Service Components | Explains how to enable and disable components of the NS$instance_name service, entire instances, or individual applications, for testing or for scaling out.
Starting and Stopping an NS$instance_name Service | Explains how to start and stop a NS$instance_name service from a command prompt and from the Services application.

See Also

Event Messages

NSControl Register

NS$instance_name Service Account Security


Installing an NS$instance_name Service

Any server that hosts one or more components of a Notification Services application must have the NS$instance_name service installed. Installing the service involves the following steps:

  1. Install the Notification Services core components on the server. This installs the binary files required by the service.
  2. Register an instance using NSControl Register with the -service argument. This installs the service and registers the instance in the Windows registry.

    The service is registered with the name NS$instance_name, where instance_name is the name of the instance as defined in the configuration file.

After installing the service, you must start the service and enable its components in order to start an instance and its associated applications.

Scale-Out Configurations

If your Notification Services instance is scaled out across multiple servers, you must first install Notification Services Enterprise Edition and then install the service by registering the instance on each of those servers.

Information in the application definition file (ADF) specifies which components run on each server. Specify the server that runs each component using the <Providers>, <Generator>, <Distributors> nodes.

Note If you are running Notification Services Standard Edition, the event provider host, generator, and distributors must all run on the same server. Scale-out is not supported.

See Also

Enabling and Disabling Service Components

Installing Notification Services

NSControl Register

Registering and Unregistering an Instance

Starting and Stopping Services


Configuring an NS$instance_name Service

Configuring an NS$instance_name service in Notification Services involves setting service startup and restart options and establishing security credentials for the service. For example, you can configure a service to start automatically when the computer starts. A service can also attempt to restart automatically if it stops for any reason.

To start an NS$instance_name service when the computer starts

  1. In Control Panel, double-click Administrative Tools, and then double-click Services.
  2. Double-click the NS$instance_name service.
  3. In the Startup type box, select Automatic.

The service for the instance is now configured to start whenever the computer starts. If components are enabled, this means the applications hosted by the instance start processing notifications when the server starts.

To restart an NS$instance_name service automatically

  1. In Control Panel, double-click Administrative Tools, and then double-click Services.
  2. Double-click the NS$instance_name service, and then click the Recovery tab.
  3. In the First Failure, Second Failure, and Subsequent Failures boxes, select Restart the service.
  4. In the Restart service after box, enter 0.

The service will now attempt to restart immediately after a failure.

Configuring Service Security

Each NS$instance_name service runs in the context of a user-defined Windows security account or a built-in service account, such as the NetworkService account in Microsoft Windows® XP. You must ensure that the account associated with the service has the correct permissions to access any other necessary resources, such as the database server and other servers in a scale-out configuration.

In addition, the account associated with the service must have permission to access the instance and application databases and to run the Notification Services extended stored procedures in the master database.

  • If SQL Server uses Windows Authentication, you can assign database permissions to the NS$instance_name service account by adding that account to the appropriate roles in the databases and then using the GrantXPExec command to grant extended stored procedure execute permissions to that account. For more information, see GrantXPExec Utility.
  • If you cannot use Windows integrated security, you must assign a SQL Server user name and password to the service by using NSControl Register, and then you must add that account to the appropriate roles in the databases. After assigning the SQL Server account to the service, use the GrantXPExec command to grant extended stored procedure execute permissions to that account.

In Windows XP and newer operating systems, if you do not specify the serviceusername argument when using NSControl Register, the NetworkService account is used. In Windows 2000 the serviceusername argument is required.

For information about service account security, see NS$instance_name Service Account Security.

To define security for an NS$instance_name service

  • From a command prompt, run NSControl Register.

    Use the serviceusername and servicepassword arguments to establish the security context. If the service account must use SQL Server Authentication to log in to SQL Server, assign a SQL Server login ID and password to the service account also, using sqlusername and sqlpassword. Otherwise, integrated security is used by default. You must grant database permissions to the account used by the service.

    Important Microsoft recommends using integrated security for SQL Server login.

To change the security account for an NS$instance_name service using NSControl Register

  • From a command prompt, run NSControl Register.

    Use the serviceusername and servicepassword arguments to establish the security context. If the service account must use SQL Server Authentication to log in to SQL Server, assign a SQL Server login ID and password to the service account also, using sqlusername and sqlpassword. Otherwise, integrated security is used by default You must grant database permissions to the account used by the service.

To change the security account for an NS$instance_name service using the Services application

  1. In Control Panel, double-click Administrative Tools and then double-click Services.
  2. Double-click the NS$instance_name service, and then click the Log On tab.
  3. Type the account name in the This account box, and then type the password in the Password and Confirm password boxes.

    Note Microsoft does not recommend using the LocalSystem service account because it is a highly privileged service account on the local computer and is not able to access network resources.

See Also

GrantXPExec Utility

Installing the Windows Service

NS$instance_name Service Account Security

Starting and Stopping Services


Enabling and Disabling Service Components

The NS$instance_name service controls the operation of the Notification Services event provider, generator, and distributor components and the ability to add and delete subscribers and subscriptions. Each of the components can be enabled and disabled. When a component is enabled, it can run on that server. When a component is disabled, it does not run on that server.

When you deploy an instance of Notification Services, you will probably enable all components. (If using only independent event providers, do not enable events.) You typically disable components only when you update an instance, or when you need to test or troubleshoot the instance.

To enable instances, applications, and components

  1. On the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Run NSControl Enable.

To disable instances, applications, and components

  1. On the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Run NSControl Disable.

To view the status of an instance, application, or component

  1. On the Start menu, point to Programs\Microsoft SQL Server Notification Services, and then click Notification Services Command Prompt to open a command prompt window.
  2. Run NSControl Status.

See Also

Enabling and Disabling an Instance

Starting and Stopping Services


Starting and Stopping a Service

Starting an NS$instance_name service in Notification Services activates all enabled components of the service. This allows the enabled components to collect events, generate notifications, and distribute notifications.

Stopping a service stops the processing of the enabled components. Instead of stopping an entire service, you can also disable instances, components of instances, and applications. For more information, see Enabling and Disabling Service Components.

Starting an NS$instance_name Service

You can start an instance of Notification Services manually from a command prompt or from the Services application, whichever is more convenient.

To start a service from a command prompt

  • From a command prompt, type:
    net start NS$instance_name

To start a service from the Services application

  1. In Control Panel, double-click Administrative Tools, and then double-click Services.
  2. Double-click the NS$instance_name service.
  3. Click Start.
Stopping an NS$instance_name Service

You can stop an instance of Notification Services manually from a command prompt or from the Services application, whichever is more convenient.

To stop a service from a command prompt

  • From a command prompt, type:
    net stop NS$instance_name

To stop a service from the Services application

  1. In Control Panel, double-click Administrative Tools, and then double-click Services.
  2. Double-click the NS$instance_name service.
  3. Click Stop.

See Also

Enabling and Disabling Service Components

Troubleshooting


Managing Security

Securing Notification Services primarily involves providing the proper access to databases used by Notification Services. All access to event, subscription, and notification data is controlled through database security. Any user or application that must read or write this data, including the Microsoft Windows service, NS$instance_name, that runs an instance of Notification Services, must have permissions granted on the appropriate database objects.

Administrators must have permissions to register, create, and update instances and to monitor the performance of instances and applications. To perform these activities, the administration accounts must have the proper permissions in Windows and in instance and application databases.

To simplify database permissions, Notification Services includes a set of predefined database roles in each database. These roles are used by applications and administrators to perform necessary functions.

The topics that this section covers are described in the following table.

Topic | Description
User Accounts Required by Notification Services Applications | Discusses the user accounts and permissions required by Notification Services instances and applications.
File and Folder Security | Explains why file and folder security is important, and provides some guidelines for configuring this security.
Notification Services Database Roles | Describes the predefined database roles available for Notification Services.
Security Recommended Practices | Provides recommended practices for managing Notification Services security.

See Also

Permissions Required for Installation


User Accounts Required by Notification Services

An instance of Notification Services runs in the context of a user account. When you deploy or administer an instance of Notification Services, you perform these actions in the context of a user account. The following list shows the required and optional user accounts used to deploy, run, and administer instances of Notification Services:

  • Windows account. The NS$instance_name service is a Microsoft Windows service that runs under a local, domain, or built-in Windows account. The service uses this account to access local and network resources, and possibly to access databases.
  • SQL Server login account. If you cannot use Windows Authentication for connections to SQL Server, you can define a SQL Server login account that the service uses to connect to SQL Server.
  • NSControl user account. The NSControl commands, used to deploy and administer instances, are run in the context of a user. Each command requires specific permissions, so you might use one or more user accounts to run these commands.
  • Subscription management application account. If using a subscription management application, this application uses an account to execute stored procedures that read and write data in the instance and application databases.

The NS$instance_name service, the NSControl commands, and subscription management applications each have different security requirements in SQL Server. Even though they can all use the same account to connect to SQL Server, it is typically best to limit the permissions on each application or component to the minimum required for each one. For this reason, use separate accounts for each application or component and grant minimal permissions to the database user accounts through predefined database roles.

The topics that this section covers are described in the following table.

Topic | Description
NS$instance_name Service Account Security | Lists the types of accounts that can be used by the NS$instance_name service, and the permissions required by the service.
SQL Server Permissions for NS$instance_name | Explains the SQL Server permissions required by the NS$instance_name service and how to grant those permissions.
Administration Permissions | Describes the requirements for running NSControl commands.
Subscription Management Application Permissions | Lists the types of accounts that can be used by subscription management applications, and provides instructions for granting permissions to these accounts.


NS$instance_name Service Account Security

The NS$instance_name service is the key to Notification Services operation. This service runs the instance of Notification Services and all applications hosted by the instance. To ensure that the service has the permissions it requires, you must properly configure security for the service.

The service runs in the context of a Microsoft Windows account. You specify the account that the service runs under when you create the service using the NSControl Register command.

Service Account Types

The NS$instance_name service can run under the following account types:

  • A domain user account. Microsoft strongly recommends running the NS$instance_name service under a domain account (which uses the format domain\username). A domain account makes it easier to control access to network resources and to databases. For optimal control of permissions granted to the service, ask your domain administrator to create a custom account for the service.
  • A local user account. You can create a user account on the local computer and run the NS$instance_name service under that account (which uses the format computer\username). If the databases are located on the same computer, you can also grant database permissions to this user account. If the databases are located on a remote computer, you must configure a SQL Server login account for the service.
  • The NT AUTHORITY\NetworkService account. This is a built-in account that is available with Windows XP only. Microsoft discourages using the NetworkService account for the NS$instance_name service. All services running under the NetworkService account are mapped to the domain\remotecomputername$ domain account when accessing network resources. Because multiple services can use this account, it is difficult to control which services have access to network resources and to SQL Server databases.
  • The NT AUTHORITY\LocalSystem account. This is a built-in account. Microsoft strongly discourages using the LocalSystem account for the NS$instance_name service because this account has unrestricted access to all local resources. Also, all services running under the LocalSystem account are mapped to the domain\remotecomputername$ domain account when accessing network resources. Because multiple services can use this account, it difficult to control which services have access to network resources and to SQL Server databases.
Windows Permissions Required by the Service Account

The account under which the NS$instance_name service runs must have the following permissions:

  • Read permission in the Notification Services folder (Program Files\Microsoft SQL Server Notification Services\vn.n.n.n) and subfolders. By default, only members of the local Administrators and Power Users groups have access to the files within these folders.
  • Permission to log on as a service. This right is granted by the NSControl Register command when you create the service.
  • Permission to read and write registry keys at the following registry locations: HKEY_LOCAL_MACHINE\Software\Microsoft\NotificationServices and HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services.
  • Read and modify permissions in the events folder. For applications using the file system watcher event provider, the event provider must be able to read and rename files in the folder where events are dropped. This requires the service to have read and modify permissions in that folder.
  • Write permission in the notifications folder. For applications using the File delivery protocol to post notifications, the service account must have the write permission in the folder where the notifications are written.
  • Possibly membership in the local Administrators group. If an application hosted by the instance uses the Internet Information Services (IIS) Simple Mail Transfer Protocol (SMTP) service to send notifications, the distributor must send those notifications in the context of an administrator. So, for any NS$instance_name service that runs the distributor component and sends notifications through IIS SMTP, the service account must be a member of the local Administrators group.

    Important The service also must have permissions in the SQL Server databases used by the instance. For more information, see SQL Server Permissions for NS$instance_name.

See Also

Managing Services


SQL Server Permissions for NS$instance_name

The account under which the NS$instance_name service runs must have the proper permissions in the SQL Server databases used by the instance. This includes permissions in the instance database, each of the application databases, and the master database.

When you create the service, you specify an account that the NS$instance_name service uses to connect to SQL Server. This account can be either the Microsoft Windows account that the service runs under or a SQL Server login account, depending on which form of Authentication you use:

  • Windows Authentication: If you use Windows Authentication to connect to SQL Server, you can grant SQL Server access to the account that the NS$instance_name service runs under.
  • SQL Server Authentication: If you use SQL Server Authentication for connections to SQL Server, you specify a SQL Server login account to be used by the service when you create the service.

You must use the GrantXPExec command to grant the account permission to run the Notification Services extended stored procedures. You must also grant permissions in the instance and application databases.

This section contains instructions for granting access to SQL Server using Windows Authentication or SQL Server Authentication, and then granting database permissions.

Topic | Description
Configuring SQL Server Access for Windows Authentication | Describes how to configure SQL Server access for the NS$instance_name service when using Windows Authentication for connections to SQL Server.
Configuring SQL Server Access for SQL Server Authentication | Describes how to configure SQL Server access for the NS$instance_name service when using SQL Server Authentication for connections to SQL Server.
Granting Database Permissions | Describes how to grant database permissions to the account used by the NS$instance_name service to connect to SQL Server.

See Also

NS$instance_name Service Account Security


Configuring SQL Server Access for Windows Authentication

If you can use Windows Authentication for connections to SQL Server, you can grant SQL Server access to the account the NS$instance_name service runs under.

Use the following procedure to grant SQL Server access to the account that the NS$instance_name service runs under, grant permission to run the Notification Services extended stored procedures, and create the service.

To grant SQL Server access using Windows Authentication

  1. Grant the domain or local account used by the NS$instance_name service access to SQL Server using the sp_grantlogin stored procedure. Use the SQL Server osql command or SQL Query Analyzer to execute the stored procedure.
  2. Grant the account access to the master database using the sp_grantdbaccess stored procedure. This is necessary in order to grant execute permission for extended stored procedures, which are defined in the master database. Use the SQL Server osql command or SQL Query Analyzer to run the stored procedure.

    Note To grant permission to execute extended stored procedures, you must be a member of the sysadmin fixed server role.

  3. Grant the account permission to execute the Notification Services extended stored procedures using the GrantXPExec command. This command is located in the Notification Services Bin folder.
  4. Create the NS$instance_name service using the NSControl Register command with the -name, -service, -serviceusername, and -servicepassword arguments.
Example

The following example assumes the domain account Corporate\StockService already exists and has the Microsoft Windows permissions required by the NS$Stock service:

osql -E
USE master
EXEC sp_grantlogin 'Corporate\StockService'
GO
EXEC sp_grantdbaccess 'Corporate\StockService'
GO
QUIT
GrantXpExec "Corporate\StockService"
NSControl Register -name Stock -service -serviceusername Corporate\StockService -servicepassword [Password]

See Also

Configuring SQL Server Access for Windows Authentication

Granting Database Permissions


Configuring SQL Server Access for SQL Server Authentication

If you must use SQL Server Authentication for connections to SQL Server, you must create a SQL Server login account for the service, grant extended stored procedure permissions to the login account, and then assign the SQL Server login account to the NS$instance_name service using the NSControl Register command.

Use the following procedure to create a SQL Server login account for the NS$instance_name service, grant permission to run the Notification Services extended stored procedures, and create the service.

To grant SQL Server access using SQL Server Authentication

  1. If necessary, create a domain or local account for the service.
  2. Create a SQL Server login account for the service account with the sp_addlogin stored procedure. Use the SQL Server osql command or SQL Query Analyzer to run the stored procedure.
  3. Grant the SQL Server login account access to the master database using the sp_grantdbaccess stored procedure. This is necessary in order to grant execute permission for extended stored procedures, which are defined in the master database. Use the SQL Server osql command or SQL Query Analyzer to run the stored procedure.

    Note To grant permission to execute extended stored procedures, you must be a member of the sysadmin fixed server role.

  4. Grant the SQL Server login account permission to execute the Notification Services extended stored procedures using the GrantXPExec command. This command is located in the Notification Services Bin folder.
  5. Create the NS$instance_name service using the NSControl Register command with the -name, -service, -serviceusername, -servicepassword, -sqlusername, and -sqlpassword arguments.
Example

The following example adds the SQLStockService login account to SQL Server and grants access to the master database. The account is then granted permission to execute the Notification Services extended stored procedures. Finally, the NS$StockInstance service is created using the NSControl Register command. The example assumes that you are running all commands in a command prompt window:

osql -E
USE master
EXEC sp_addlogin 'SQLStockService', '[Password]'
GO
EXEC sp_grantdbaccess 'SQLStockService'"
GO
QUIT
GrantXpExec "SQLStockService"
NSControl Register -name StockInstance -service -serviceusername Corporate/StockService -servicepassword [Password] -sqlusername SQLStockService -sqlpassword [Password]

See Also

Configuring SQL Server Access for Windows Authentication

Granting Database Permissions


Granting Database Permissions

In addition to SQL Server access and the ability to run the Notification Services extended stored procedures, the NS$instance_name service must have permissions in the instance database and the application databases for all applications hosted by the instance. The following permissions are required by the service:

  • If the NS$instance_name service runs the event provider, generator, and distributor processes, the account must be a member of the NSRunService role in the instance database and in each application database.
  • For a scaled-out instance, you can use different service accounts on each server. If a server runs only a subset of these processes, the service account can obtain permissions through the NSEventProvider, NSGenerator, or NSDistributor roles.

The process for granting database permissions is the same for Microsoft Windows accounts and SQL Server login accounts.

To grant database permissions to the service account

  1. Ensure that the instance and application databases exist. These databases are created when you run the NSControl Create command.
  2. Grant database access to the service account using the sp_grantdbaccess stored procedure. You must do this in the instance database and in the database for each application that is hosted by the instance.
  3. In each database in which you granted permissions, add the service's database user account to the NSRunService role (or to one of the other roles mentioned above) using the sp_addrolemember stored procedure.
Example

The following code grants database access to the Corporate\StockService login account, and then adds the database user to the NSRunService role. This example assumes that you have created the databases using NSControl Create, and that you are using SQL Query Analyzer to run the Transact-SQL statements:

USE StockInstanceNSMain
EXEC sp_grantdbaccess 'Corporate\StockService'
EXEC sp_addrolemember 'NSRunService', 'Corporate\StockService'
USE StockInstanceStock
EXEC sp_grantdbaccess 'Corporate\StockService'
EXEC sp_addrolemember 'NSRunService', 'Corporate\StockService'

See Also

Configuring SQL Server Access for SQL Server Authentication

Configuring SQL Server Access for Windows Authentication


Administration Permissions

Two groups of administrators typically perform administration tasks for Notification Services: the administrators who create and register instances, and the administrators who control and monitor instances (sometimes referred to as an operations group).

The commands used to create, register, update, and delete an instance require specific privileges because these commands can create, alter, or delete applications. These actions require the account that runs the associated NSControl commands to be a member of the local Administrators group or a member of the sysadmin or dbcreator fixed server role.

The commands used by the operations group to enable or disable components and to retrieve information about the instance require a lower level of privileges. These privileges can be granted by adding the accounts used by the operations group to the Notification Services database roles, such as NSAdmin and NSAnalysis.

The NSControl commands and the permissions required to run the commands are shown in the following table.

NSControl Command | Windows Permissions | SQL Server Permissions
NSControl Create | None. | Member of dbcreator or sysadmin fixed server role.
NSControl Delete | None. | Member of dbcreator or sysadmin fixed server role.
NSControl Disable | None. | Member of NSAdmin or db_owner database role, or of sysadmin or dbcreator fixed server role.
NSControl DisplayArgumentKey | Member of Administrators or Power Users group, or you are running the command in the context of the account that the NS$instance_name service runs under. | None.
NSControl Enable | None. | Member of NSAdmin or db_owner database role, or of sysadmin or dbcreator fixed server role.
NSControl ListVersions | Member of local Administrators group. | None.
NSControl Register | Member of local Administrators group. | None.
NSControl Status | Member of the local Administrators group on all servers that host the instance of Notification Services. | Member of NSAnalysis, NSDistributor, NSEventProvider, NSGenerator, NSReader, NSRunService, NSSubscriberAdmin, or NSVacuum database roles; or of sysadmin fixed server role.
NSControl Unregister | Member of local Administrators group. | None.
NSControl Update | None. | Member of db_owner database role, or of sysadmin fixed server role.
NSControl Upgrade | None. | Member of db_owner database role, or of sysadmin fixed server role.

See Also

NSControl Commands

Permissions Required for Installation


Subscription Management Application Permissions

Subscription management applications are custom applications that manage the subscriber and subscription data for Notification Services applications. Subscription management applications are typically Web applications, but can be Microsoft Windows applications.

Subscription management applications must have access to the instance and application databases. Subscription management applications execute stored procedures that read data from and write data to these databases. The applications can connect to the SQL Server database engine using either Windows Authentication or SQL Server Authentication.

When a developer creates a subscription management application, the developer must choose one of the following types of account for connections to the SQL Server database engine:

  • A local or domain Windows account. The server that hosts SQL Server must be in the same domain as the subscription management application. If using a local account, the subscription management application and SQL Server must be on the same server. Otherwise, the subscription management application must use a SQL Server login account.
  • A SQL Server login account.
  • The ASPNET account used by ASP applications. This is a local account created when you install the Microsoft .NET Framework.

You must ensure that the account used by the subscription management application can connect to SQL Server and has the proper database permissions.

To grant database access to a subscription management application

  1. Determine which type of account is used for the SQL Server connection. If you did not develop the application, either contact the application developer or examine the source code.
  2. Grant SQL Server access to the account using one of the following methods:
    • If the account is a local or domain Windows account or the ASPNET account, use the sp_grantlogin stored procedure to grant the account access to SQL Server.
    • If the account is a SQL Server login account, use the sp_addlogin stored procedure to create the login account.
  3. Grant database access using the sp_grantdbaccess stored procedure. You must do this in the instance database and in the database for each application that uses the subscription management application.
  4. In each database to which you added the account, add the database user account to the NSSubscriberAdmin database role. Do this using the sp_addrolemember stored procedure.
Example: Windows Authentication

The following code grants SQL Server access to the Corporate\Subscriber domain account, grants database access to the account, and then adds the account to the NSSubscriberAdmin database role in the instance and application databases. This example assumes that the databases have already been created using NSControl Create, and that you are using SQL Query Analyzer to run the Transact-SQL statements:

USE master
EXEC sp_grantlogin 'Corporate\Subscriber'
USE StockInstanceNSMain
EXEC sp_grantdbaccess 'Corporate\Subscriber'
EXEC sp_addrolemember 'NSSubscriberAdmin', 'Corporate\Subscriber'
USE StockInstanceStock
EXEC sp_grantdbaccess 'Corporate\Subscriber'
EXEC sp_addrolemember 'NSSubscriberAdmin', 'Corporate\Subscriber'
Example: SQL Server Authentication

The following code creates a SQL Server login account named SQLSubscriber, grants database access to the login account, and then adds the user to the NSSubscriberAdmin database role in the instance and application databases. The example assumes that the databases have already been created using NSControl Create, and that you are using SQL Query Analyzer to run the Transact-SQL statements:

USE master
EXEC sp_addlogin 'SQLSubscriber', '[Password]'
USE StockInstanceNSMain
EXEC sp_grantdbaccess 'SQLSubscriber'
EXEC sp_addrolemember 'NSSubscriberAdmin', 'SQLSubscriber'
USE StockInstanceStock
EXEC sp_grantdbaccess 'SQLSubscriber'
EXEC sp_addrolemember 'NSSubscriberAdmin', 'SQLSubscriber'

See Also

NS$instance_name Service Account Security


File and Folder Security

In addition to securing your Notification Services application and your subscription management applications, you must also manage access to files and folders used by your applications.

Separating Run-Time Files from Configuration Files

Each instance of Notification Services has a configuration file. Each application has an application definition file (ADF). These files are required when creating or updating an instance of Notification Services, but are not required when the instance and its applications are running because all operational data from these files is stored in databases. However, these files might contain information about your instance and application that, if a malicious user were to see it, could compromise security.

Applications do use some files at run time. For example, if an application uses the file system watcher event provider, the provider requires an XML Schema definition language (XSD) file that documents the event schema. If using XSLT to format notifications, the application requires XSLT files that specify how the notifications are formatted. These files must be accessible by the account that the NS$instance_name service runs under.

To ensure that applications can access run-time files and that the configuration file and ADF are secure, consider separating the run-time files from other files and then customizing security at the folder level. For more information, see Creating a Deployment Directory Structure.

Securing Folders

The account that the NS$instance_name service runs under must have access to necessary folders. This includes access to the folders where application components are located, where events are posted, and where notifications are posted. For more information, see NS$instance_name Service Account Security.

You also must limit access to these folders so that malicious users cannot submit event data, pick up notifications, or read files. For example, if you use the file system watcher event provider or a similar provider that reads event data dropped to a folder, you must make sure that the NS$instance_name service is able to read files dropped to that folder, but that no malicious users can write to that folder.

Depending on the level of security you require, you can secure these files in the following ways:

  • You can use NTFS permissions to restrict access to the folders and all of their files. For more information about NTFS permissions, see your Microsoft Windows documentation.
  • If you are concerned about unauthorized disclosure of data, you can use the Encrypting File System (EFS) to encrypt specific files and folders. For more information about EFS, see your Windows documentation.

See Also

Configuring and Deploying Instances


Notification Services Database Roles

When you create an instance of Notification Services, Notification Services creates database roles in the instance and application databases. The NS$instance_name service, subscription management applications, custom objects, and administrators use the roles to obtain necessary permissions in the databases. These roles make the assignment of database permissions much easier.

The instance and application databases contain the same Notification Services database roles. The following table lists these roles and their permissions. Database roles and their permissions can be changed by members of the sysadmin fixed server role or the db_owner or db_securityadmin database roles.

Role | Permissions
NSAnalysis Can execute stored procedures that produce reports for performance analysis and troubleshooting.

Users in this role can read all tables in the database, which might be necessary for ad hoc reports.

This role also has NSReader permissions.
NSAdmin Can run NSControl Enable and NSControl Disable commands to enable and disable instances, applications, and components.

Members of the db_owner database role and the sysadmin and dbcreator fixed server roles can also run NSControl Enable and NSControl Disable.
NSDistributor Can execute stored procedures that perform SELECT and UPDATE operations on notification and distributor work tables.

Use this role for the NS$instance_name service account when a distributor is located on its own server and has a unique service account.

This role also has NSReader permissions.
NSEventProvider Can execute stored procedures that perform INSERT operations on the event tables, and SELECT, INSERT, and UPDATE operations on the event batch tables.

Event providers require the permissions associated with this role. Use this role for independent event providers and for the NS$instance_name service account when an event provider is located on its own server and has a unique service account.

This role also has NSReader permissions.
NSGenerator Can execute stored procedures used by the generator. Use this role for the NS$instance_name service account when a generator is located on its own server and has a unique service account.

Use this role for stand-alone generator services if you do not want to add them to the NSRunService role.

User-written rules in the application definition file (ADF) are executed using the permissions of this role.

This role also has NSReader permissions.
NSMonitor Can execute stored procedures that collect performance data.

This role also has NSReader permissions.
NSReader | Can execute stored procedures that read the configuration tables.
NSRunService This role has the combined permissions of the NSEventProvider, NSGenerator, NSDistributor, NSReader, NSMonitor, and NSVacuumer roles.

Important Assign this role to the account used by the NS$instance_name service to log in to SQL Server. The service requires these permissions to evaluate subscriptions and generate notifications.

This role also has NSReader permissions.
NSSubscriberAdmin Can execute stored procedures that read, update, and delete rows from subscriber and subscription-related tables.

Note Notification Services automatically cascades the deletion of a subscriber record to all related subscriptions, in all applications, even if the user deleting the subscriber record does not have access to the application databases. Subscription removal is performed using the permissions of the database owner.

This role also has NSReader permissions.
NSVacuum Can execute stored procedures that remove obsolete data from the application databases.

This role also has NSReader permissions.

Note One of the generator stored procedures issues CREATE TABLE and CREATE VIEW statements. These tables are owned by the user that invokes the stored procedure. For this reason, the NSGenerator and NSRunService roles are members of the db_owner role in the application databases.

To view the permissions assigned to these database roles, use the sp_helprotect system stored procedure. For more information about sp_helprotect, see SQL Server Books Online.

See Also

Administration Permissions


Security Recommended Practices

Microsoft recommends the following practices to help you protect your data and applications from malicious users and accidental user actions.

Notification Services Security Practices
  • Run the NS$instance_name service under a weak domain or local account. Do not use the LocalSystem or NetworkService service account or any account in the Administrators group.

    However, if you are using a delivery protocol that requires the account that the service runs under to have additional privileges, you must use higher privileges. For example, sending notifications using an Internet Information Services (IIS) SMTP server requires the account under which the service runs to be a member of the local Administrators group.

  • Ensure that the password used by the service account is a strong password. For more information about strong passwords, see "Creating Strong Passwords" in the Microsoft Windows documentation.
  • Ensure that all code run by the NS$instance_name service, such as custom event providers, content formatters, and protocols, is from a trusted source. Notification Services assumes that code listed in the application definition file (ADF) comes from a trusted source.
  • Secure all folders containing configuration files or application data. For more information about securing files and folders, see File and Folder Security.
SQL Server Security Practices
  • When installing SQL Server, never allow a blank sa password, even if you select the integrated security mode. This guarantees that if the security mode changes to mixed mode, the sa account will still have a password.
  • Use Windows Authentication whenever possible. Windows Authentication provides advanced security features, such as policies for password length, complexity, and expiration. Note that if the NS$instance_name service uses a SQL Server user name and password to connect to SQL Server, this user name and password are encrypted and stored in the registry.
  • If you use SQL Server Authentication, use strong passwords for the SQL Server login accounts and change the passwords periodically.
  • Do not grant unnecessary permissions to the public role in each database. The public role is a special database role to which every database user belongs, and cannot be dropped from the database. Notification Services does not use the public role.
  • Do not grant database access to the guest user account. The guest user account allows a SQL Server login account that does not have a database user account to access a database.
  • Consider encrypting the database files using NTFS file encryption. This can decrease performance, so you must weigh optimal performance against file security.
Network Communications Security Practices
  • To reduce the possibility of intruders viewing data as it is being transferred between Notification Services and the database, use encrypted communication between client applications and SQL Server. For more information, see "Using Encryption Methods" in SQL Server Books Online.
  • If you are using an HTTP protocol to post data to a Web server, and if the Web server supports SSL, post the notification using an address that starts with https://. This form of address encrypts the data that is sent to the Web server.
Physical Security Practices

Ensure that your servers are located in an area that is adequately secured. If a malicious user can physically access the server, the server is not secure.

See Also

File and Folder Security

Notification Services Database Roles

User Accounts Required by Notification Services Applications


Performance Monitoring and Reporting

When applications are in use, it is important to monitor their status and health. You must make sure that events are arriving, notifications are being generated, and notifications are being distributed. Monitoring performance enables you to observe application status and to determine whether the current system configuration is adequate for the volume of events and notifications being processed.

Notification Services provides collections of performance counters, called performance objects, that report on the status of components, applications, and instances; and performance reports that help you analyze the current and historical performance of your instances and applications. You also can use SQL Server utilities to monitor the databases used by Notification Services.

The topics that this section covers are described in the following table.

Topic | Description
Choosing Monitoring Tools | Lists the monitoring tools and provides guidance on when to use each tool.
Tips for Evaluating Performance | Describes recommended practices for monitoring Notification Services.
Notification Services Performance Objects | Documents the performance objects available in Notification Services.
Using Performance Logs and Alerts | Explains how to use performance counter logs and alerts to monitor Notification Services applications.
Notification Services Performance Reports | Describes the reports available in Notification Services and explains how to use the reports to analyze performance.

See Also

Event Messages

Stored Procedure Reference


Choosing Monitoring Tools

SQL Server provides a comprehensive set of tools for monitoring. Your choice of tool depends on the type of monitoring you need and the events to be monitored. For example, monitoring can be accomplished using Notification Services performance objects or stored procedures in SQL Server.

Performance objects, events, Notification Services stored procedures, and SQL Server system stored procedures provide various ways to monitor Notification Services instances and applications.

Notification Services Performance Objects

System Monitor, a part of the Microsoft Windows Performance tool, enables you to perform real-time monitoring of application performance using predefined performance objects that contain performance-related counters. System Monitor collects counts, rates, and averages about resources and processing, such as notification processing, system CPU activity, and database sizes.

To access performance objects

  1. In Control Panel, open Administrative Tools, and then open Performance.
  2. In the Windows Performance tool, click System Monitor.
  3. Right-click the System Monitor details pane, and then click Add Counters.
  4. In the Add Counters dialog box, select the performance objects you want for NS$instance_name services, and then select the counters and instances you want.
Notification Services Events

The application log of Event Viewer contains messages about errors, warnings, and other information that occurs for various events in Notification Services. You can use the application log data to troubleshoot instances and applications.

To access the application event log

  1. In Control Panel, open Administrative Tools, and then open Event Viewer.
  2. In the Windows Performance tool, click Application Log.

    In the Application Log details pane, the Source column for all Notification Services events contains the service name in the format NS$instance_name.

Notification Services Stored Procedures

Notification Services provides its own set of stored procedures for reporting, debugging, and manually running processes separate from those available from SQL Server. For more information, see Notification Services Performance Reports and the Stored Procedure Reference.

SQL Profiler

SQL Profiler enables you to monitor server and database activity, such as deadlocks, fatal errors, and query activity. You can capture SQL Profiler data to a SQL Server table or a file for later analysis. It also has a trace feature that you can use for planning indexes.

Note Monitoring too many events at one time increases the processing load on the server. Monitor only the events that are necessary for analyzing current performance issues.

For more information about SQL Profiler, see "Monitoring with SQL Profiler" in SQL Server Books Online.

SQL Server System Stored Procedures and Functions

The following SQL Server system stored procedures and functions are useful for monitoring database activity:

sp_who
Provides snapshot information about current SQL Server users and processes, including the currently executing statement and whether the statement is blocked. This is a Transact-SQL alternative to viewing user activity in the current activity window in SQL Server Enterprise Manager.
sp_spaceused
Displays an estimate of the current amount of disk space used by a table or database. This is a Transact-SQL alternative to viewing database usage in SQL Server Enterprise Manager.
sp_monitor
Displays statistics, including CPU usage, I/O usage, and the amount of idle time since sp_monitor was last executed.
built-in functions
Display snapshot statistics about SQL Server activity since the server was started; these statistics are stored in predefined SQL Server counters. For example, @@CPU_BUSY contains the amount of time the CPU has been executing SQL Server code; @@CONNECTIONS contains the number of SQL Server connections or attempted connections; and @@PACKET_ERRORS contains the number of network packets occurring on SQL Server connections.

For more information about these system stored procedures and functions, see SQL Server Books Online.

See Also

Notification Services Performance Objects

Tips for Evaluating Performance

Using Performance Logs and Alerts

Using Reports to Analyze Performance


Tips for Evaluating Performance

You evaluate the status of Notification Services by monitoring the flow of events and notifications through the system. When monitoring the system, you want to ensure that:

  • Events are arriving and being collected by the event providers.
  • Events are accumulating in the event tables and the generator is processing the event batches and generating notifications in a timely manner.
  • Notifications are accumulating in the notification tables and the distributor is formatting notifications and delivering them to the delivery channels.
  • The external delivery system is accepting the formatted notifications and is reporting errors for rejected notifications.
  • The generator is processing all notifications in a timely manner, and is not skipping quanta.
  • The vacuuming process is occurring as scheduled in the application definition file (ADF).
  • The CPU and disks are operating well within their capacity.
  • Database and log files are not filling up and either auto-growing too frequently or running out of space.
Monitoring Production Applications

Monitoring trends and peak requirements will help you to plan system growth. Notification Services applications typically have peak periods and quiet periods because subscribers tend to want information delivered at similar times and because large batches of events often arrive at the same times each day. For this reason, it is very important to monitor applications during peak periods, establish performance baselines, and then compare performance over time.

For applications in production, you should always monitor critical performance counters and set alerts to notify operators of poor performance. You can set alerts using Performance Logs and Alerts, a part of the Microsoft Windows Performance tool.

Responding to Performance Problems

When you encounter performance problems, use all the tools available to determine what is causing the problem. Here are some possible remedies for performance problems:

  • Place database files, log files, and the tempdb database on three separate physical disks. The performance for generating notifications on the database system is often limited by disk resources.
  • Configure indexes for the application rules (event chronicle rules, subscription event rules, and subscription scheduled rules) to tune the application.
  • Do not run queries against the instance and application databases during peak processing periods because you might be creating temporary locks on resources needed by Notification Services.
  • Ensure that the CPU resources are adequate for distribution, which is typically CPU-bound.
  • Ensure that your server has adequate bandwidth to the delivery services to deliver notifications. For example, using only one network card to deliver notifications to an SMTP server limits the number of notifications your applications can send.
  • Ensure that applications are tuned for the best performance. To tune an application, you might need to adjust several elements in the application definition file, especially elements in the <ApplicationExecutionSettings> node.

For any performance problems, it is important to isolate the problem by looking at performance counters, using reports, and examining the application log to see what errors are occurring.

See Also

Choosing Monitoring Tools

Notification Services Performance Objects

Using Performance Logs and Alerts

Using Reports to Analyze Performance


Notification Services Performance Objects

Notification Services has three types of performance objects: component, application, and instance. These objects contain counters for monitoring performance at different system levels of a Notification Services instance:

  • Component-level objects monitor the state of the components on the local server. You cannot use these objects to monitor a single application on a multiple-application instance or to monitor an entire instance if the instance is distributed across multiple servers.
  • Application-level objects monitor the status of a Notification Services application by querying the application database, and can be used on any server that runs the instance that hosts the application.
  • Instance-level objects monitor subscriber activity by querying the instance database, and can be used on any server that hosts the instance.
Component-Level Objects

Notification Services provides the component-level performance objects shown in the following table.

Topic | Description
NS$instance_name: Delivery Channels Object | Provides information about an individual delivery channel.
NS$instance_name: Distributors Object | Provides information about an individual distributor.
NS$instance_name: Event Providers Object | Provides information about an individual event provider.
NS$instance_name: Generator Object | Provides information about the generator component for the instance.

These component-level objects monitor the components as they are updated on the system where the component runs.

Application-Level Objects

Notification Services provides the application-level performance objects shown in the following table.

Topic | Description
NS$instance_name: Events Object | Provides information about events for an application.
NS$instance_name: Notifications Object | Provides information about notifications created by an application.
NS$instance_name: Subscriptions Object | Provides information about the subscriptions for an application.
NS$instance_name: Vacuumer Object | Provides information about the application vacuuming process.

These application-level objects query the application databases, and can be run on any server that has the NS$instance_name service installed and running, but the counter data reflects only the activity that takes place on the local server.

Instance-Level Objects

Notification Services provides the instance-level performance object shown in the following table.

Topic | Description
NS$instance_name:Subscribers Object | Provides information about the subscribers for an instance of Notification Services.

The instance-level object queries the application databases, and can be run on any server that has the NS$instance_name service installed and running, but the counter data reflects only the activity that takes place on the local server.

See Also

Choosing Monitoring Tools

Notification Services Performance Reports

Using Performance Logs and Alerts


NS$instance_name: Delivery Channels Object

The NS$instance_name: Delivery Channels object provides counters for monitoring delivery channels configured for a Notification Services instance.

The delivery channel counters monitor one or all delivery channels on the local server. If the NS$instance_name service is installed on the local server but no distributors are enabled on that server, the counters are available but do not return data.

Counter | Description | Purpose
Messages Written To Transport | Total number of messages written by the selected delivery channel since the distributor started. | Use to determine the activity level of one or all delivery channels.
Messages Written To Transport Rate | Number of messages written per second by the selected delivery channel. | Use to determine how delivery channel activity changes over time.

After selecting a counter, select an instance. You can select All instances, which returns values for all delivery channels on the local server, or you can select just one of the delivery channel names, all of which are defined in the configuration file.

Important Performance counter instances are available only when the instance is running.

See Also

Notification Services Performance Objects


NS$instance_name: Distributors Object

The NS$instance_name: Distributors object provides counters for monitoring the distributor components of a Notification Services instance.

The distributor counters monitor one or all distributors on the local server. If the NS$instance_name service is installed on the local server but no distributors are enabled on that server, the counters are available but do not return data.

Counter | Description | Purpose
Delivery Requests Failed | Total number of failed delivery requests since the distributor started. Ideally this number should be zero. | Flags delivery problems.
Delivery Requests Succeeded | Total number of delivery requests successfully sent since the distributor started. A delivery request can include multiple notifications if multicast is enabled. | Use to determine the delivery activity of a distributor, and to compare against the Format Requests Succeeded counter to determine whether notifications are being formatted but not delivered.
Format Requests Failed | Total number of format requests that failed since the distributor started. Ideally this number should be zero. | Flags format request problems. Check the event log for content formatter errors, and check whether the data being sent to the content formatter is valid and can be transformed.
Format Requests Rate | Number of format requests per second. | Use to determine the activity level of the distributor at different times. This can help with system planning, and can help plan resources for peak periods.
Format Requests Succeeded | Total number of successful format requests since the distributor started. When using multicast or digest delivery, one format request can be for multiple notifications because notifications can be combined into a single message. | Use to determine the formatting activity level of a distributor. Also monitor CPU activity, because formatting is CPU intensive. This information can help you determine when you need to scale up or scale out distribution.
Notification Bodies | Total number of notification bodies formatted since the distributor started. When using multicast or digest delivery, the number of formatted notification bodies should be lower than the number of notifications to be delivered, and equal to the number of successful formatting requests. | Compare to the Notification Headers counter to determine the ratio of notification bodies to notification headers.
Notification Headers | Total number of notification headers since the distributor started. When using multicast or digest delivery, the number of headers formatted should be equal to the number of notifications delivered and higher than the number of successful formatting requests. | Compare to the Notification Bodies counter to determine the ratio of notification headers to notification bodies.

After selecting a counter, select an instance. You can select All instances, which returns values for all distributors on the local server, or you can select one of the distributor instances; distributor instance names are a combination of the application name and the distributor name, such as stock:stockdist1.

Important Performance counter instances are available only when the instance is running.

See Also

Notification Services Performance Objects


NS$instance_name: Event Providers Object

The NS$instance_name: Event Providers object provides counters for monitoring the event provider components of a Notification Services instance.

The event provider counters monitor one or all event providers on the local server. If the NS$instance_name service is installed on the local server but no event providers are enabled on that server, the counters are available but do not return data.

Counter | Description | Purpose
Event Batches Aborted | Total number of event batches that failed since the event provider started. | Use to determine whether event batches arrived, but were not committed to the database. This can indicate problems with the database connections, an event provider, event data, or an event source.
Event Batches Committed | Total number of event batches committed since the event provider started. | Use to determine how many event batches the event provider has submitted per event class.
Events Per Batch | Average number of events per event batch for the selected event provider. | Use to analyze event batch sizes for an individual event provider.
Events Received | Total number of events received since the event provider started. | Use to determine the activity level of an individual event provider.
Events Received Per Second | Number of input events received per second for the selected event provider. | Use to determine the activity level of the event provider at different times. This information can be used to determine whether you need to distribute events, either submitting events at different times or scaling out event providers.

After selecting a counter, select an instance. You can select All instances, which returns values for all event providers on the local server, or you can select one of the event provider instances; event provider instance names are a combination of the application name and the event provider name, such as stock:provider1.

Important Performance counter instances are available only when the instance is running.

See Also

Notification Services Performance Objects


NS$instance_name: Events Object

The NS$instance_name: Events object provides application-level counters. These counters monitor the events and event batches of an application by running queries on the database server. These counters are available only on the server that hosts the Notification Services generator.

Counter1 | Description | Purpose
Event Batches Awaiting Generation | Number of event batches committed but not yet picked up by the generator. The generator must be enabled and running for this counter to be updated. | Use to identify potential backlogs of event batches for an application.
Event Batches In Collection | Number of event batches in process and not yet committed. | Use to determine the current event collection activity.
Event Batches Submitted2 | Number of event batches submitted since the application started. | Use to analyze the volume of event batches handled by an individual application.
Total Events2 | Number of events received since the application started. | Use to analyze the volume of events received by an individual application.

1 - Event counters are updated on a periodic basis using a performance monitoring thread that is hosted by the generator. The update period is specified by the <PerformanceQueryInterval> element in the <ApplicationExecutionSettings> node of the application definition file (ADF).

2 - Vacuuming, which removes data from the database, affects the value of this counter.

After selecting a counter, select an instance. You can select All instances, which returns values for all events for all applications hosted by the instance, or you can select an event instance; event instance names are a combination of the application name and the event class name, such as stock:stockevents.

Important Performance counter instances are available only when the instance is running.

See Also

Notification Services Performance Objects


NS$instance_name: Generator Object

The NS$instance_name: Generator object provides counters for monitoring generator threads of a Notification Services instance. Each generator thread processes notifications for one application.

The generator counters monitor one or all generator threads on the local server. If the NS$instance_name service is installed on the local server but the generator is not enabled on that server, the counters are available but do not return data.

Counter | Description | Use
Notifications Generated Per Second | Number of notifications created per second. | Use to analyze the volume of notifications produced by the generator over time.
Quantums Behind | Number of quanta that the generator is falling behind. | Use to determine whether the generator can keep up with the current workload. This could be due to other processes running on the database system, the need to improve performance on the database system, or possibly the need to improve performance on the system that runs the generator component.
Quantums Failed | Number of failed quanta since the generator started. Quantum failure indicates that at least one of the rules in the quantum failed. Because rules fire in parallel, multiple rules can fail within a single quantum. | Use to determine whether rule firings are failing. An example of a cause is a rule-firing timeout. This could indicate problems connecting to SQL Server or with executing queries.
Quantums Processed | Number of quanta processed since the generator started. If the generator is trying to catch up, this number can be higher than typically expected. | Use to determine how many quanta have been processed.
Rule Firing Failures | Number of failed rule firings since the generator started. | Use to further analyze the Quantums Failed counter. The Rule Firing Failures counter shows you how many rule firings failed, which you can use to troubleshoot rule problems and connection problems.
Rule Firings | Number of rule firings since the generator started. | Compare this value to the Rule Firing Failures counter to see the ratio of successfully fired rules to failed rules.
Skipped Chronicle Rule Firings | Number of quanta skipped for chronicle rule firings since the generator started. | Use to determine whether chronicle rules have been skipped, which can indicate stale chronicle data or a problem with chronicle rules.
Skipped Quantums | Number of quanta the generator skipped since the generator started. | Use to determine whether generation has fallen behind far enough to skip rule firings. To tune your applications, you might need to adjust the <QuantumDuration> and <ChronicleQuantumLimit> elements in the application definition file (ADF).
Skipped Subscription Rule Firings | Number of quanta skipped for subscription rule firings. | Used to determine whether subscription rules are being skipped, which indicates skipped notifications. To tune your applications, you might need to adjust the <QuantumDuration> and <SubscriptionQuantumLimit> elements in the ADF.

After selecting a counter, select an instance. You can select All instances, which returns values for all generator threads on the local server, or you can select one of the generator thread instances; generator thread instance names are the same as application names, such as stock.

Important Performance counter instances are available only when the instance is running.

See Also

Notification Services Performance Objects


NS$instance_name: Notifications Object

The NS$instance_name: Notifications object provides application-level counters. These counters monitor the notifications and notification batches of an application by running queries on the database server. These counters are available only on the server that hosts the Notification Services generator.

Counter | Description | Use
Batches | Number of notification batches generated since the application started. | Use to determine the activity level of the generator, and to compare against the Batches Successfully Delivered counter.
Batches Awaiting Distribution1 | Number of notification batches waiting to be picked up by the distributor. | Use to determine whether there is a backlog of notification batches. A backlog could indicate that the system should be scaled up or scaled out. A backlog could also exist during busy periods, and might not indicate a problem.
Batches Expired1 | Number of notification batches containing expired notifications. The counter includes all expired batches since the application last started. | Use to determine whether notifications are not being sent because they have expired. This can happen if the expiration time elapses before all retries are attempted due to a small <ExpirationAge> value or a prolonged delivery problem.
Batches Failed Delivery1 | Number of notification batches that contain one or more failed notifications. The counter includes all failed batches since the application last started. | Use to determine whether there is a distribution issue. For large numbers of failed notifications, check for errors from the distributor, delivery channel, and delivery service. For smaller problems, check notification and subscriber data. "Failed" does not equal "expired." Failed batches, but not expired batches, might be tried again.
Batches In Generation1 | Number of notification batches currently being created. | Use to determine the current generator workload for the application.
Batches In Retry1 | Number of notification batches currently in the delivery retry queue. | Use to determine whether notification delivery for the application is initially failing. This can help you troubleshoot general delivery channel or distributor issues.
Batches Successfully Delivered1, 2 | Number of notification batches successfully delivered since the application last started. | Use to compare against the Batches counter to determine whether batches generated are being delivered.
Notifications | Number of notifications generated since the application started. If using multicast or digest delivery, this number is the count of notifications before they are consolidated for delivery. | Use to determine the number of notifications the application is generating.
Notifications Awaiting Distribution1 | Number of notifications waiting to be picked up by the distributor. | Use to determine whether there is a backlog of notifications. This counter is similar to the Batches Awaiting Distribution counter, but provides the notification count.
Notifications Failed Delivery1 | Number of notifications that have failed the delivery process since the application last started. | Use to determine how many notifications have failed in the batches marked as failed. Each batch marked as failed contains one or more failed notifications. Note Failed does not equal expired. Failed notifications, but not expired notifications, might be tried again.
Notifications Generated Per Second/Class | Number of notifications generated per second per notification class. This value takes the total number of notifications generated during the System Monitor sampling interval, and determines the number per second for each notification class. | Use to analyze the activity of all notification classes.
Notifications Successfully Delivered1, 2 | Number of notifications successfully delivered since the application last started. | Use to determine the number of notifications the application has sent.

1 – The counter is updated on a periodic basis using a performance monitoring thread hosted by the generator. The update period is specified by the <PerformanceQueryInterval> element in the <ApplicationExecutionSettings> node of the application definition file (ADF).

2 - Vacuuming, which removes data from the database, affects the value of this counter.

After selecting a counter, select a counter instance. You can select All instances, which returns values for all notifications for all applications hosted by the instance, or you can select a specific notification instance; notification instance names are a combination of the application name and the notification class name, such as stock:stocknotifications.

Important Performance counter instances are available only when the instance is running.

See Also

Notification Services Performance Objects


NS$instance_name: Subscribers Object

The NS$instance_name: Subscribers object provides instance-level counters. These counters monitor subscriber-related activity for an instance by querying the instance database. Because these counters query a database, these counters can run on any server that hosts the Notification Services instance.

Counter1 | Description | Use
Subscribers Added | Number of subscribers added since the instance last started. | Use to determine how many subscribers are being added to the system.
Subscribers Disabled | Number of subscribers that are currently marked as disabled. Subscribers are disabled on an individual basis using the Subscriber.Enabled property followed by the Subscriber.Update method. | Use to determine how many subscribers cannot receive notifications because their accounts have been disabled programmatically.
Subscribers Enabled | Number of subscribers that are currently marked as enabled. Subscribers can be enabled on an individual basis using the Subscriber.Enabled property followed by the Subscriber.Update method. | Use to determine how many subscribers can receive notifications.

1 - The subscribers counters are updated on a periodic basis using a performance monitoring thread that is hosted by the generator. The update period is specified by the <PerformanceQueryInterval> element in the <ApplicationExecutionSettings> node of the application definition file (ADF).

For subscribers counters, you do not need to select a counter instance. All subscribers are located in the instance database, so selecting either All instances or _total returns the same values.

Important Performance counter instances are available only when the instance is running.

See Also

Notification Services Performance Objects


NS$instance_name: Subscriptions Object

The NS$instance_name: Subscriptions object provides application-level counters. These counters monitor the subscription-related activity of an application by running queries on the database server. Because application-level counters query databases, these counters can run on any server that hosts the Notification Services instance.

Counter1 | Description | Use
Subscriptions Added | Number of subscriptions added since the application started. Notifications sent are often proportional to the number of subscriptions. | Use to analyze application growth.
Subscriptions Added Per Minute | Number of subscriptions added per minute. | Use to determine application growth, in terms of subscriptions, over time.
Subscriptions Disabled | Number of disabled subscriptions. Subscriptions are disabled at the API level using NSControl Disable. | Use to determine how many subscriptions cannot currently produce notifications.
Subscriptions Enabled | The total number of enabled subscriptions. Subscriptions are enabled at the API level using NSControl Enable. | Use to determine how many subscriptions currently can produce notifications.

1 - Subscriptions counters are updated on a periodic basis using a performance monitoring thread hosted by the generator. The update period is specified by the <PerformanceQueryInterval> element in the <ApplicationExecutionSettings> node of the application definition file (ADF).

After selecting a counter, select a counter instance. You can select All instances, which returns values for all subscriptions for all applications hosted by the instance, or you can select a subscription instance; the subscription instance name is a combination of the application name and the subscription class name, such as stock:stocksubscriptions.

Important Performance counter instances are available only when the instance is running.

See Also

Notification Services Performance Objects


NS$instance_name: Vacuumer Object

The NS$instance_name: Vacuumer object provides counters for monitoring vacuumer progress for Notification Services applications by running queries on the database server. Because vacuumer counters query databases, these counters can run on any server that hosts the Notification Services instance.

Counter | Description | Use
Completed Periods | Number of scheduled vacuuming periods (or intervals) that completed successfully. | Use to determine how many vacuuming periods successfully removed data for all available quanta.
Quantums Remaining | Number of quanta considered for vacuuming at the start of the last vacuuming period, but not vacuumed. A nonzero value could indicate a vacuuming backlog or that items in the batches still require processing. | Use to determine whether all the quanta ready for vacuuming were vacuumed.
Quantums Vacuumed | Number of quanta successfully vacuumed during the last vacuuming period. | Use to determine whether vacuuming is occurring as scheduled.
Timeouts | Number of vacuum periods that ended due to the time limit. | Use to determine whether vacuuming is taking longer than the allotted vacuuming period. If so, vacuuming should occur more frequently or the vacuum period should be increased.

After selecting a counter, select a counter instance. You can select All instances, which returns values for all applications hosted by the instance, or you can select an application name.

Important Performance counter instances are available only when the instance is running.

See Also

Notification Services Performance Objects


Using Performance Logs and Alerts

Consistently monitoring performance requires the use of performance logs and alerts. Performance logs collect data from performance counters at regular intervals, enabling you to analyze performance data at your convenience with robust reporting tools, such as Microsoft Excel. Perfomance alerts enable you to define limits for counters, and then receive alerts when the counter values are above or below the limit.

Creating a Performance Log

Create a performance log using Performance Logs and Alerts, a part of the Microsoft Windows Performance tool.

To create a performance log

  1. In Control Panel, open Administrative Tools, and then open Performance.
  2. In the Windows Performance tool, expand Performance Logs and Alerts, right-click Counter Logs, and then click New Log Settings.
  3. Type a name for the counter log, and then click OK.
  4. Click Add to add as many counters as necessary for your Notification Services instance and other important values, such as processor time, disk time, and database counters.

    The number of counters you add does not have a significant impact on system performance.

  5. When you have finished adding counters, click Close.
  6. On the General tab, under Sample data every, configure a sampling interval: start with a moderate sampling interval, such as 5 minutes, and then adjust the interval if necessary.

    The shorter the interval, the more system resources and disk space will be used. Additionally, intervals shorter than the quantum period can cause a performance report to show sporadic performance numbers, because you will have processing spikes mixed with no activity.

  7. On the Log Files tab, configure the properties of the log file. Comma-delimited files can be viewed later in reporting tools such as Microsoft Excel.
  8. On the Schedule tab, configure a monitoring schedule.

For more information about using counter logs, see the Performance Logs and Alerts documentation.

Analyzing Data from the Performance Log

One benefit of collecting counter data in a log file is that you can import the data to an application like Microsoft Excel and then create charts that illustrate performance over time. You can collect these charts on a regular schedule and use them to compare performance over time.

Setting Counter Alerts

Some counter values indicate an application problem. For example, for your application, you might want to know whether the generator is more than 25 quanta behind or the number of failed delivery requests exceeds 20.

Using the alerts available in the Performance Logs and Alerts part of the Microsoft Windows Performance tool, you can write a message to the event log, run an application, or send a network message in response to counters above or below a specified limit.

For more information about configuring performance alerts, see the Performance Logs and Alerts documentation.

See Also

Notification Services Performance Objects


Notification Services Performance Reports

Notification Services provides performance reports to help administrators and developers monitor and troubleshoot instance and application performance. The reports provide information on event collection, notification generation, delivery, average notification latency, failed deliveries, and many other areas.

Reports are produced by running one of the stored procedures provided with Notification Services. The stored procedures return various record sets, which can be used by other applications, such as Microsoft Excel.

The stored procedures are created and named when you run NSControl Create or NSControl Update and are customized per instance and application.

The topics that this section covers are described in the following table.

Report Category | Description
Overview of Performance Reports | Lists the performance reports and describes how you might use them.
Using Reports to Analyze Performance | Provides a methodology for analyzing application performance using reports.

See Also

Choosing Monitoring Tools

Notification Services Performance Objects


Overview of Performance Reports

Notification Services has five categories of performance reports: an instance report, diagnostic reports, detail reports, quantum reports, and snapshot reports. Each report is produced by running a stored procedure provided with Notification Services.

Instance Report

The administrative history report is the only report focused at the instance level. This report provides an overview of system health so that system administrators can quickly determine system performance over a period of time. The report contains counts and averages for events, subscriptions, notifications, and notification delivery. The NSAdministrationHistory stored procedure, which is in the instance database, produces this report.

Diagnostic Reports

Diagnostic reports are application-specific reports that provide detailed data for a time interval, such as the past 24 hours or week. Use these reports to analyze application processing. The stored procedures that run these reports are in the instance database.

The delivery channel diagnostic report provides information about the notifications delivered through a particular delivery channel. Because a single notification class can deliver messages through multiple delivery channels, it can be difficult to diagnose delivery channel issues through applications or notification classes. Use this report to analyze a particular delivery channel. The NSDiagnosticDeliveryChannel stored procedure produces this report.

The event class diagnostic report provides information about the activity level of a particular event class. Included in this report is information about event batch creation latency, event batch sizes, and the number of pending batches. The NSDiagnosticEventClass stored procedure produces this report.

The event provider diagnostic report provides information about the events collected through a particular event provider. Because an event class can have events collected by multiple event providers, it can be difficult to diagnose event provider issues through applications or event classes. Use this report to analyze a particular event provider. The NSDiagnosticEventProvider stored procedure produces this report.

The failed notification diagnostic report provides information about notifications that could not be delivered. The report contains the application, notification class, and delivery channel names for each failed notification. The report also provides the subscriber ID and the device address for the failed notification, as well as information about failures and retries. The NSDiagnosticFailedNotifications stored procedure produces this report.

The notification class diagnostic report provides information about the activities of a particular notification class. Included in this report are counts of notifications and notification batches, the average number of notifications created per second, and the delivery success of those notifications. The NSDiagnosticNotificationClass stored procedure produces this report.

The subscription class diagnostic report provides information about the activities of a particular subscription class. Included in this report are the number of scheduled subscriptions, the subscription processing latency, and the notifications generated from these subscriptions. The NSDiagnosticSubscriptionClass stored procedure produces this report.

Detail Reports

Detail reports provide detailed information about event batches and their events, notification batches and their notifications, and scheduled subscriptions. After looking at the higher-level reports such as the snapshot and diagnostic reports, you can use these reports to look at the details of individual batches and subscriptions. The stored procedures that run these reports are located in the application databases.

The event batch detail report provides information about a specified event batch. The report contains multiple result sets. One result set contains general information about the event batch, such as the event provider name and the time the event batch was collected. A second result set displays the events that were submitted in the event batch. The NSEventBatchDetails stored procedure produces this report.

The notification batch detail report provides information about a specified notification batch. The report contains information about the rule firing that produced the batch and the notifications contained in the batch. Use this report to troubleshoot notification generation and to analyze the progression of notifications through the application. The NSNotificationBatchDetails stored procedure produces this report.

The scheduled subscription detail report provides information about the scheduled subscriptions for a specified subscription class. The report contains information about when each subscription was created, when it was last modified, and when it is scheduled to run. The NSScheduledSubscriptionDetails stored procedure produces this report.

The scheduled subscription list report provides information about all scheduled subscriptions for a given subscriber. The report shows the subscription ID, class name, and whether the subscriber and subscription are enabled, along with information about the subscription schedules and time zones. The NSScheduledSubscriptionList stored procedure produces this report.

Quantum Reports

Quantum reports are application-specific reports that provide detailed data about application processing intervals, or quanta. Examples of quantum data are the quantum execution time, notifications generated during the quantum, and rule firing details. Use the following reports to analyze and troubleshoot application performance related to generator processing. The stored procedures that run the reports are located in the application databases.

The quantum detail report provides detailed information about a specified quantum. Use this report to troubleshoot long-running quanta and to analyze quantum processing. The NSQuantumDetails stored procedure produces the report.

The quantum execution time report provides information to help you identify problematic generator quanta, which you can then use to analyze the quanta in more detail. The NSQuantumExecutionTime stored procedure produces the report.

The quantum failure report provides information about failed generator quanta. A quantum is failed if the quantum could not complete required processing, such as event-triggered or scheduled subscription rule firings. The NSQuantumFailures stored procedure produces the report.

The quantum list report provides information about quanta processed during a specified time period, and displays the quanta in the order in which they ran. The NSQuantumList stored procedure produces the report.

The quantum performance report provides information about quanta in terms of how long each quantum executed. The result set divides execution time into intervals, so you can see how many quanta executed within each time period. This can help you troubleshoot long-running quanta. The NSQuantumPerformance stored procedure produces the reports.

The quanta skipped report provides information about skipped generator quantum processing. Quanta can be skipped if the generator falls behind and quantum limits are set in the application definition file (ADF). The NSQuantumsSkipped stored procedure produces the reports.

Snapshot Reports

Snapshot reports provide the current health status of an instance. These reports are used primarily by system administrators to generate baselines and determine the current status of an instance against those baselines. The stored procedures that produce these reports are located in the instance database.

The application snapshot reports provide information about the current state of all applications hosted by the instance. The information includes data such as the generator, vacuumer, and subscriber activation states, information about the most recent notification batch and vacuuming occurrence, and information about subscriber data. The NSSnapshotApplications stored procedure produces the reports.

The delivery channels snapshot report provides information about the current state of the delivery channels configured across the instance. The information includes data such as the distributor system name, activation state, the last time each delivery channel processed work items, and the number of messages sent or failed. The NSSnapshotDeliveryChannels stored procedure produces this report.

The events snapshot report provides information about the current state of the event classes configured for applications within the instance. The information includes data about the application and event provider activation states, the last time the event classes collected data, and how many events the event classes have submitted. The NSSnapshotEvents stored procedure produces this report.

The providers snapshot report contains information about the current state of the event providers configured for applications within the instance. The information includes data about the system that the event provider is running on, the activation state, the most recent event class and batch collected by the provider, and the number of events collected. The NSSnapshotProviders stored procedure produces this report.

The subscriptions snapshot report contains information about the subscriptions added to applications hosted by the instance. The information includes the application name, the subscription class name, and the time the most recent subscription was added to the application. The NSSnapshotSubscriptions stored procedure produces this report.

See Also

Performance Monitoring and Reporting

Using Reports to Analyze Performance


Using Reports to Analyze Performance

When analyzing Notification Services performance, start by determining how an instance and its applications are performing. To obtain this information, use the application snapshot report and the administrative report.

The application snapshot report, produced by the NSSnapshotApplications stored procedure. For example, you can use this report to see whether the generator is running behind schedule or whether data is being removed by the vacuumer.

The administrative report, produced by the NSAdministrationHistory stored procedure. For example, you can use this report to look for failed notification batches.

These reports help you determine whether your applications are performing as expected. If not, use the methodology below to analyze poor performance.

Analyzing Poor Performance

Analyzing Notification Services applications begins with the generator quantum. The generator is the heart of Notification Services, and beats on a regular time interval called a quantum. The application developer specifies the duration of a quantum within the application definition file (ADF). The generator uses the quantum duration to determine how often to generate notifications.

When analyzing performance problems, you typically look for quantum periods that did not complete as expected, and then determine what happened during those quanta. Use the following methodology to locate interesting quanta, analyze those quanta, and then analyze instance and application details.

Step 1: Determine a quantum of interest

The first step in analyzing a Notification Services application is to identify a set of relevant quantum periods. A quantum period that is relevant to poor performance typically has one of the following characteristics:

  • The quantum is running longer than expected. This can be caused by several factors, and you must further analyze the application to determine the cause.
  • The quantum is marked as failed. A quantum period can have failures for several reasons, such as that a rule did not run as planned, or notification distribution failed.
  • The quantum was skipped. In an effort to keep the generator processing current data, you can configure the generator to skip quantum periods when necessary. Skipped quanta are usually an effect of long-running quantum periods.

To help identify long-running, failed, or skipped quantum periods, Notification Services provides the quantum performance, quantum execution time, quantum failure, and quanta skipped reports.

The quantum performance report categorizes quanta according to quantum execution times. This can help you determine how long quanta are running in general. The NSQuantumPerformance stored procedure produces the reports.

The quantum execution time report contains quanta that are running longer than a specified time. Using the quantum IDs, you can then analyze the quanta in more detail. The NSQuantumExecutionTime stored procedure produces the report.

The quantum failure report provides information about failed generator quanta. A quantum is failed if the quantum could not complete required processing, such as rule firings. The NSQuantumFailures stored procedure produces the report.

The quanta skipped report provides information about skipped generator quanta. Quanta can be skipped if the generator falls behind and quantum limits are set in the application definition file (ADF). The NSQuantumsSkipped stored procedure produces the reports.

Scenario: Using the NSQuantumPerformance stored procedure, you might determine that quantum 188 ran twice as long as all other quanta. The next step is to discover what happened during that quantum.

Step 2: Analyze detailed quantum information

Once a quantum of interest has been identified, determine what happened during the quantum. To obtain details about the quantum, use the quantum detail and quantum list reports.

The quantum detail report provides detailed information about a specified quantum. Use this report to troubleshoot long-running quanta or analyze quantum processing. The NSQuantumDetails stored procedure produces the report.

The quantum list report provides information about quanta processed during a specified time period, and displays the quanta in the order in which they ran. The NSQuantumList stored procedure produces the report.

Scenario: Continuing the scenario introduced in step 1 above, you run the NSQuantumDetails stored procedure for quantum 188. According to the report, you discover that one of the rule firings consumed 90 percent of the quantum time. The next step is to look at the event and notification batches for this and other quanta. Using this report, you note that event batch 60 and notification batch 40 were processed during this quantum.

Step 3: Analyze detailed application data

After analyzing a quantum period, you might want to focus on the specific events, subscriptions, or notifications within the quantum. The event batch details report, the scheduled subscription details report, and the notification batch detail report provide very detailed information about application data.

The event batch details report provides information about a specific event batch for an event class. The report shows summary information about the event batch, and then shows information about each event in the batch. The NSEventBatchDetails stored procedure produces this report.

The scheduled subscription details report provides information about all the subscriptions in a subscription class. The NSScheduledSubscriptionDetails stored procedure produces this report.

The notification batch detail report provides information about a specific notification batch for a notification class. The report shows summary information about the notification batch, and then shows information about each notification in the batch. The NSNotificationBatchDetails stored procedure produces this report.

You also can use any of the diagnostic or snapshot reports to look at applications in varying levels of detail.

Scenario: To conclude your analysis of quantum 188, you first run the NSNotificationBatchDetails stored procedure for event batch 60 and notice that a large number of events were collected during this quantum. Using NSDiagnosticEventClass, you determine that this event batch had substantially more events than most event classes, which shows you that the longer than normal quantum execution time does not indicate an application problem but optimization of the application, such as optimizing queries and adding indexes, might be required to improve performance.

See Also

Notification Services Performance Reports

Performance Monitoring and Reporting


Programming Reference

This section provides information about the Microsoft® SQL Server™ Notification Services object model and the Notification Services XML vocabulary.

The topics that this section covers are described in the following table.

Topic | Description
Application Definition File Reference | Provides reference information on the nodes and elements in the application definition file (ADF).
Configuration File Reference | Provides reference information on the nodes and elements in the configuration file.
Notification Services Object Model Reference | Provides reference information on the Notification Services APIs.
Stored Procedure Reference | Provides reference information on the Notification Services stored procedures.
Table and View Reference | Provides reference information on the Notification Services tables and views.
Notification Services Code Reference | Provides reference information on the codes used by the Notification Services system.


Application Definition File Reference

An application definition file (ADF) is required for every notification application you create on the Notification Services platform. The ADF stores all metadata that defines the application. This includes the structure of the events and subscriptions that the application accepts as input, and the structure of the notifications it produces.

Your ADF must be an XML file that conforms to the ApplicationDefinitionFile.xsd schema. This schema can be found in the installation directory of the Notification Services instance that you are using. It documents all the standard nodes that are used when defining a Notification Services application.

An ADF contains a hierarchy of XML nodes, each containing elements that specify the application settings and structure. The ADF must conform to the standards for well-formed XML, so all element names are case sensitive. Elements are always specified using Pascal case, which means that the first character is uppercase and the first letter of any subsequent concatenated word is uppercase.

All element values must conform to XML naming conventions. For more information about these conventions, see XML Textual Content in the Microsoft MSDN® Library.

ADF Structure


Reserved Characters

In XML, some characters are reserved for internal use and you must replace them by entity references when they are used in data. Additionally, the Notification Services XML vocabulary reserves the percent sign for use in denoting parameters.

The following table shows the reserved characters and the entity references that must replace them in all ADF data.

Character | Meaning | Entity reference
> | Greater than | &gt;
< | Less than | &lt;
' | Apostrophe (single quote) | &apos;
" | Quotation mark (double quote) | &quot;
& | Ampersand | &amp;
% | Percent | &#37;


The XML Declaration

It is good practice to provide an XML declaration in every XML document. The application definition file (ADF), which is an XML document, should have one.

The declaration identifies the version of XML being used, optionally indicates the encoding used by this document, and indicates whether or not it relies on external documents for additional information. If no encoding attribute is found, the default for the document is set to UTF-8. If an external document such as a document type definition (DTD) is read, the encoding is set to the encoding value found in the external document. If no encoding is found in the external document, the default is again set to UTF-8.

Your ADF XML declaration should appear as follows:

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>

This indicates that you are using XML that complies with the version 1.0 specification, that the document uses UTF-8 encoding, and that the document does not rely on any external documents for additional information.


<Action> Element (<ChronicleRule>)

Provides a Transact-SQL statement that specifies the action to be taken in an event chronicle rule.

Structure
<EventClasses>
   <EventClass>
      ...
      <ChronicleRule>
         ...
         <Action>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 100,000 characters in length.
Default Value | None.
Occurrence | Required once per <ChronicleRule> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ChronicleRule> Node

See Also

Defining Chronicle Rules

Event Chronicles


<Action> Element (<EventRule>)

Provides a Transact-SQL statement that specifies the action to be taken in a subscription event rule.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <EventRules>
         <EventRule>
            ...
            <Action>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 100,000 characters in length.
Default Value | None.
Occurrence | Required once per <EventRule> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <EventRule> Node

See Also

Defining Event Rules

Subscription Rules


<Action> Element (<ScheduledRule>)

Provides a Transact-SQL statement that specifies the action to be taken in a subscription scheduled rule.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <ScheduledRules>
         <ScheduledRule>
            ...
            <Action>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 100,000 characters in length.
Default Value | None.
Occurrence | Required once per <ScheduledRule> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ScheduledRule> Node

See Also

Defining Scheduled Rules

Subscription Rules


<ActionTimeout> Element (<ChronicleRule>)

Specifies an interval during which the Transact-SQL statements specified in the event chronicle <Action> element must complete.

Structure
<EventClasses>
   <EventClass>
      ...
      <ChronicleRule>
         ...
         <ActionTimeout>
Element Characteristics
Characteristic | Description
Data Type | duration.
Default Value | 30 minutes.
Occurrence | Optional once per <ChronicleRule> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ChronicleRule> Node
Remarks

If an action does not complete in the time specified by <ActionTimeout>, the action is canceled and an error is recorded in the event log.

The format of the XML duration data type is P0DT00H00M00S. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

See Also

Defining Chronicle Rules


<ActionTimeout> Element (<EventRule>)

Specifies an interval during which the Transact-SQL statements specified in the subscription event <Action> element must complete successfully.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <EventRules>
         <EventRule>
            ...
            <ActionTimeout>
Element Characteristics
Characteristic | Description
Data Type | duration.
Default Value | 30 minutes.
Occurrence | Optional once per <EventRule> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <EventRule> Node
Remarks

If an action does not complete in the time specified by <ActionTimeout>, the action is canceled and an error is recorded in the event log.

The format of the XML duration data type is P0DT00H00M00S. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

See Also

Defining Event Rules


<ActionTimeout> Element (<ScheduledRule>)

Specifies an interval during which the Transact-SQL statements specified in the event scheduled <Action> element must complete successfully.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <ScheduledRules>
         <ScheduledRule>
            ...
            <ActionTimeout>
Element Characteristics
Characteristic | Description
Data Type | duration.
Default Value | 30 minutes.
Occurrence | Optional once per <ScheduledRule> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ScheduledRule> Node
Remarks

If an action does not complete in the time specified by <ActionTimeout>, the action is canceled and an error is recorded in the event log.

The format of the XML duration data type is P0DT00H00M00S. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

See Also

Defining Scheduled Rules


<Application> Node

Provides the root element of an application definition file (ADF). Contains all elements that describe a single Notification Services application.

Structure
<Application>
Node Characteristics
Characteristic | Description
Occurrence | Required once per ADF.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | None
Child Elements | <ParameterDefaults> Node <Version> Node <History> Node <Database> Node <EventClasses> Node <SubscriptionClasses> Node <NotificationClasses> Node <Providers> Node <Generator> Node <Distributors> Node <ApplicationExecutionSettings> Node
Remarks

You can create an xmlns attribute for this element to specify the Notification Services namespace that is used in the ADF.

Namespaces are used in XML documents to identify the XML vocabulary used in the document. This makes it possible to have identically named elements with different meanings and values and yet tell them apart. It is good practice to include the unique namespace that identifies the XML vocabulary you are using.

Your <Application> node must appear as follows if you want to declare a namespace attribute:

<Application xmlns="http://www.microsoft.com/MicrosoftNotificationServices/ApplicationDefinitionFileSchema">
See Also

For more information about using XML namespaces, see Namespaces in an XML Document in the Microsoft MSDN® Library.


<ApplicationExecutionSettings> Node

Provides a parent location for defining the execution settings for this application.

Structure
<Application>
   ...
   <ApplicationExecutionSettings>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <Application> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Application> Node
Child Elements | <QuantumDuration> Element <ChronicleQuantumLimit> Element <SubscriptionQuantumLimit> Element <ProcessEventsInOrder> Element <PerformanceQueryInterval> Element <EventThrottle> Element <SubscriptionThrottle> Element <NotificationThrottle> Element <DistributorLogging> Node <Vacuum> Node

See Also

Defining the Application Execution Settings


<Argument> Node (/ContentFormatter/Arguments)

Provides a location to define a single initialization argument for a content formatter.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <ContentFormatter>
         ...
         <Arguments>
            <Argument>
Node Characteristics
Characteristic | Description
Occurrence | Required one or more times per <Arguments> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Arguments> Node (<ContentFormatter>)
Child Elements | <Name> Element (/ContentFormatter/Arguments/Argument) <Value> Element (/ContentFormatter/Arguments/Argument)

See Also

Documenting the Content Formatter


<Argument> Node (/HostedProvider/Arguments)

Provides a location to define a single initialization argument for a hosted event provider.

Structure
<Providers>
   <HostedProvider>
      ...
      <Arguments>
         <Argument>
Node Characteristics
Characteristic | Description
Occurrence | Required one or more times per <Arguments> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Arguments> Node (<HostedProvider>)
Child Elements | <Name> Element (/HostedProvider/Arguments/Argument) <Value> Element (/HostedProvider/Arguments/Argument)

See Also

Defining the Event Provider Arguments


<Arguments> Node (<ContentFormatter>)

Provides a location for collecting the initialization arguments for a content formatter.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <ContentFormatter>
         ...
         <Arguments>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <ContentFormatter> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <ContentFormatter> Node
Child Elements | <Argument> Node (/ContentFormatter/Arguments)

See Also

Documenting the Content Formatter


<Arguments> Node (<HostedProvider>)

Provides a location for collecting the initialization arguments for a hosted event provider.

Structure
<Providers>
   <HostedProvider>
      ...
      <Arguments>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <HostedProvider> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <HostedProvider> Node
Child Elements | <Argument> Node (/HostedProvider/Arguments)

See Also

Defining the Event Provider Arguments


<AssemblyName> Element (<ContentFormatter>)

Specifies the assembly that contains the class that implements the content formatter functionality.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <ContentFormatter>
         ...
         <AssemblyName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 260 characters in length.
Default Value | None.
Occurrence | Required once per <ContentFormatter> node for custom components; not used with Notification Services standard components.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ContentFormatter> Node
Remarks

The value for <AssemblyName> must be the file name and path of a managed code assembly.

See Also

Documenting the Content Formatter


<AssemblyName> Element (<HostedProvider>)

Specifies the assembly that contains the class that implements the hosted event provider functionality.

Structure
<Providers>
   <HostedProvider>
      ...
      <AssemblyName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 260 characters in length.
Default Value | None
Occurrence | Required once per <HostedProvider> node for custom components; not used with Notification Services standard components.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <HostedProvider> Node
Remarks

The value for <AssemblyName> must be the file name and path of a managed code assembly.

See Also

Documenting the Event Provider Assembly Name


<Build> Element

Specifies the build component of the application version number.

Structure
<Version>
   ...
   <Build>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | None.
Occurrence | Required once per <Version> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Version> Node

See Also

Maintaining Version Information


<Chronicle> Node (/EventClass/Chronicles)

Provides a location for specifying information about one event chronicle table.

Structure
<EventClasses>
   <EventClass>
      ...
      <Chronicles>
         <Chronicle>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <Chronicles> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Chronicles> Node (<EventClass>)
Child Elements | <ChronicleName> Element (/EventClass/Chronicles/Chronicle) <SqlSchema> Node (/EventClass/Chronicles/Chronicle)
Remarks

If you delete a <Chronicle> node, NSControl Update deletes and re-creates the event class to which it corresponds. This includes dropping and re-creating the SQL Server tables and indexes used by this event class.

Important When you delete a <Chronicle> node, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining Event Chronicle Tables

Event Chronicles


<Chronicle> Node (/SubscriptionClass/Chronicles)

Provides a location for specifying information about one subscription chronicle table.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <Chronicles>
         <Chronicle>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <Chronicles> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Chronicles> Node (<SubscriptionClass>)
Child Elements | <ChronicleName> Element (/SubscriptionClass/Chronicles/Chronicle) <SqlSchema> Node (/SubscriptionClass/Chronicles/Chronicle)
Remarks

If you delete a <Chronicle> node, NSControl Update re-creates the subscription class to which it corresponds. A new subscription table is created, and the existing subscription table is renamed to SubscriptionTableNameOld. Existing subscription table indexes are left unchanged. If you want to transfer data between the old and new subscription tables, it must be done manually.

See Also

Defining Subscription Chronicle Tables

Subscription Chronicles


<ChronicleName> Element (/EventClass/Chronicles/Chronicle)

Specifies the user-defined name of the event chronicle table.

Structure
<EventClasses>
   <EventClass>
      ...
      <Chronicles>
         <Chronicle>
            <ChronicleName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <Chronicle> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Chronicle> Node (/EventClass/Chronicles)
Remarks

Microsoft recommends that the <ChronicleName> value be the name of the physical chronicle table as defined in the related <SqlSchema> node.

If you update a <ChronicleName> element, NSControl Update deletes and re-creates the event class to which it corresponds. This includes dropping and re-creating the SQL Server tables and indexes used by this event class.

Important When you update a <ChronicleName> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining Event Chronicle Tables


<ChronicleName> Element (/SubscriptionClass/Chronicles/Chronicle)

Specifies the user-defined name of the subscription chronicle table.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <Chronicles>
         <Chronicle>
            <ChronicleName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <Chronicle> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Chronicle> Node (/SubscriptionClass/Chronicles)
Remarks

Microsoft recommends that the <ChronicleName> value be the same name as that of the physical chronicle table as defined in the related <SqlSchema> node.

If you update a <ChronicleName> element, NSControl Update re-creates the subscription class to which it corresponds. A new subscription table is created, and the existing subscription table is renamed to SubscriptionTableNameOld. Existing subscription table indexes are left unchanged. If you want to transfer data between the old and new subscription tables, it must be done manually.

See Also

Defining Subscription Chronicle Tables


<ChronicleQuantumLimit> Element

Specifies how far behind the real-time clock the logical clock can fall before it skips processing event chronicle rules in order to catch up.

Structure
<ApplicationExecutionSettings>
   ...
   <ChronicleQuantumLimit>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | 1,440 quanta, which is 1,440 minutes or 1 day, assuming a <QuantumDuration> value of 1 minute.
Occurrence | Optional once per <ApplicationExecutionSettings> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ApplicationExecutionSettings> Node

See Also

Defining the <ChronicleQuantumLimit> Element


<ChronicleRule> Node

Provides a location for defining one or more Transact-SQL statements that maintain data in event chronicle tables.

Structure
<EventClasses>
   <EventClass>
      ...
      <ChronicleRule>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <EventClass> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <EventClass> Node
Child Elements | <RuleName> Element (<ChronicleRule>) <Action> Element (<ChronicleRule>) <ActionTimeout> Element (<ChronicleRule>)

See Also

Defining Chronicle Rules

Event Chronicles


<Chronicles> Node (<EventClass>)

Provides a location for defining one or more Transact-SQL statements that determine the table structure for the chronicle tables used by the event class.

Structure
<EventClasses>
   <EventClass>
      ...
      <Chronicles>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <EventClass> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <EventClass> Node
Child Elements | <Chronicle> Node (/EventClass/Chronicles)
Remarks

If you add or delete the <Chronicles> node, NSControl Update deletes and re-creates the event class to which it corresponds. This includes dropping and re-creating the SQL Server tables and indexes used by this event class.

Important When you add or delete the <Chronicles> node, any data existing in the original SQL Server tables is permanently deleted.

See Also

Event Chronicles


<Chronicles> Node (<SubscriptionClass>)

Provides a location for defining one or more Transact-SQL statements that determine the table structure for the chronicle tables used by the subscription class.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <Chronicles>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <SubscriptionClass> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <SubscriptionClass> Node
Child Elements | <Chronicle> Node (/SubscriptionClass/Chronicles)
Remarks

If you add or delete the <Chronicles> node, NSControl Update re-creates the subscription class to which it corresponds. A new subscription table is created, and the existing subscription table is renamed to SubscriptionTableNameOld. Existing subscription table indexes are left unchanged. If you want to transfer data between the old and new subscription tables, it must be done manually.

See Also

Subscription Chronicles


<ClassName> Element (<ContentFormatter>)

Specifies the class name of the class that provides the content formatter functionality.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <ContentFormatter>
         <ClassName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 4,000 characters in length.
Default Value | None.
Occurrence | Required once per <ContentFormatter> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ContentFormatter> Node
Remarks

The <ClassName> value must conform to Microsoft .NET class naming conventions.

See Also

Documenting the Content Formatter


<ClassName> Element (<HostedProvider>)

Specifies the class name of the class that provides the hosted event provider functionality.

Structure
<Providers>
   <HostedProvider>
      <ClassName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 4,000 characters in length.
Default Value | None.
Occurrence | Required once per <HostedProvider> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <HostedProvider> Node
Remarks

The <ClassName> value must conform to Microsoft .NET class naming conventions.

See Also

Documenting the Event Provider Class Name


<CollationName> Element

Specifies the collation of the database, which determines the languages it supports and the sort order in which query results are returned.

Structure
<Database>
   ...
   <CollationName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | The default collation of the SQL Server instance.
Occurrence | Optional once per <Database> node.
Updates | Cannot be added, deleted, or modified.
Element Relationships
Relationship | Elements
Parent Node | <Database> Node
Remarks

The <CollationName> value must conform to the SQL Server nvarchar data type. It also must be the name of a valid Windows or SQL Server collation.

See Also

Specifying Application Database Information


<ComputedField> Node

Provides a location for defining one specific computed notification class field.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Schema>
         ...
         <ComputedFields>
            <ComputedField>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <ComputedFields> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <ComputedFields> Node
Child Elements | <FieldName> Element (/NotificationClass/Schema/ComputedFields/ComputedField) <SqlExpression> Element (<ComputedField>) <DigestGrouping> Element (<ComputedField>)
Remarks

Computed fields are never stored in the notifications table. Instead, they are computed immediately before the notification data is passed to the content formatter. Computed fields allow you to make use of the formatting and calculation facilities of SQL Server. Use of computed fields can improve the performance of your notification application, and reduce the work that you must do in the content formatter. For instance, using a computed field is more efficient than calculating a field value in the Transact-SQL for a rule, because it allows you to avoid writing additional data to the notification table.

If you add or delete a <ComputedField> node, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important When you add or delete a <ComputedField> node, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Notification Fields


<ComputedFields> Node

Provides a location for all of the computed notification field definitions for one notification class.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Schema>
         ...
         <ComputedFields>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per /NotificationClass/Schema node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Schema> Node (<NotificationClass>)
Child Elements | <ComputedField> Node
Remarks

If you add or delete the <ComputedFields> node, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important When you add or delete the <ComputedFields> node, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Notification Fields


<ContentFormatter> Node

Specifies the content formatter used by the associated notification class.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <ContentFormatter>
Node Characteristics
Characteristic | Description
Occurrence | Required once per <NotificationClass> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | <NotificationClass> Node
Child Elements | <ClassName> Element (<ContentFormatter>) <AssemblyName> Element (<ContentFormatter>) <Arguments> Node (<ContentFormatter>)

See Also

Documenting the Content Formatter

Formatting Notifications


<CreationDate> Element

Specifies the date the application definition file (ADF) was created.

Structure
<History>
   <CreationDate>
Element Characteristics
Characteristic | Description
Data Type | date.
Default Value | None.
Occurrence | Required once per <History> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <History> Node
Remarks

The format of the XML date data type is CCYY-MM-DD with an optional time zone indicator. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

See Also

Maintaining History Information


<CreationTime> Element

Specifies the time at which the application definition file (ADF) was created.

Structure
<History>
   <CreationTime>
Element Characteristics
Characteristic | Description
Data Type | time.
Default Value | None.
Occurrence | Required once per <History> node.
Updates | You can modify this element, but cannot add or delete it. Use NSControl Update to apply any modification.
Element Relationships
Relationship | Elements
Parent Node | <History> Node
Remarks

The format of the XML time data type is HH:MM:SS.sss with an optional time zone indicator. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

See Also

Maintaining History Information


<Database> Node

Provides a parent location for collecting information about the SQL Server database used by this application.

Structure
<Application>
   ...
   <Database>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <Application> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | <Application> Node
Child Elements | <NamedFileGroup> Node <LogFile> Node <DefaultFileGroup> Element <CollationName> Element
Remarks

If no <Database> node is specified, all child elements revert to the defaults on the SQL Server instance being used.

See Also

Specifying Application Database Information


<DefaultFileGroup> node

 SQL Server Notification Services Books Online

<DefaultFileGroup> Element

Specifies one of the <NamedFileGroup> entries to be used as the default filegroup when creating SQL Server objects for this application.

Structure
<Application>
   ...
   <Database>
      ...
      <DefaultFileGroup>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 128 characters in length.
Default Value | The default filegroup of the SQL Server instance being used.
Occurrence | Optional once per <Database> node.
Updates | Cannot be added, deleted, or modified.
Element Relationships
Relationship | Elements
Parent Node | <Database> Node

See Also

Defining a <DefaultFileGroup> Element


<DigestDelivery> Element

Indicates whether the associated notification class uses digest delivery.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <DigestDelivery>
Element Characteristics
Characteristic | Description
Data Type | Boolean.
Default Value | false.
Occurrence | Optional once per <NotificationClass> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <NotificationClass> Node

See Also

Setting the Digest Delivery Option


<DigestGrouping> Element (<ComputedField>)

Indicates whether the value of the computed notification field is considered when grouping notifications for digest delivery.

Structure
<NotificationClasses>
   <NotificationClass>
      <Schema>
         <ComputedFields>
            <ComputedField>
               ...
               <DigestGrouping>
Element Characteristics
Characteristic | Description
Data Type | Boolean.
Default Value | false.
Occurrence | Optional once per <ComputedField> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ComputedField> Node
Remarks

If you add, delete, or update a <DigestGrouping> element, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important When you add, delete, or update a <DigestGrouping> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Notification Fields

Formatting Digest Notifications


<DigestGrouping> Element (<Field>)

Indicates whether the value of the notification field is considered when grouping notifications for digest delivery.

Structure
<NotificationClasses>
   <NotificationClass>
      <Schema>
         <Fields>
            <Field>
               ...
               <DigestGrouping>
Element Characteristics
Characteristic | Description
Data Type | Boolean.
Default Value | false.
Occurrence | Optional once per <Field> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Field> Node (/Schema/Fields)
Remarks

If you add, delete, or update a <DigestGrouping> element, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important When you add, delete, or update a <DigestGrouping> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Notification Fields

Formatting Digest Notifications


<Distributor> Node

Provides a location for defining information about one of the distributors used by this application.

Structure
<Distributors>
   <Distributor>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <Distributors> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Distributors> Node
Child Elements | <SystemName> Element (<Distributor>) <ThreadPoolSize> Element (<Distributor>) <QuantumDuration> Element (<Distributor>)

See Also

Specifying Distributor Settings


<DistributorLogging> Node

Provides a location for specifying distributor logging settings for the application. These settings determine what types of notification delivery information gets logged.

Structure
<ApplicationExecutionSettings>
   ...
   <DistributorLogging>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <ApplicationExecutionSettings> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <ApplicationExecutionSettings> Node
Child Elements | <LogBeforeDeliveryAttempts> Element <LogStatusInfo> Element <LogNotificationText> Element

See Also

Defining the <DistributorLogging> Node


<Distributors> Node

Provides a parent location for defining information about the distributors used by this application.

Structure
<Application>
   ...
   <Distributors>
Node Characteristics
Characteristic | Description
Occurrence | Required once per <Application> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | <Application> Node
Child Elements | <Distributor> Node

See Also

Specifying Distributor Settings


<Duration> Element

Specifies how long the vacuumer will continue to run after it has been started.

Structure
<ApplicationExecutionSettings>
   ...
   <Vacuum>
      ...
      <VacuumSchedule>
         <Schedule>
            ...
            <Duration>
Element Characteristics
Characteristic | Description
Data Type | duration.
Default Value | 6 hours, or until the start of the next vacuuming interval, whichever comes first.
Occurrence | Optional once per /ApplicationExecutionSettings/Vacuum/VacuumSchedule/Schedule node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Schedule> Node (<VacuumSchedule>)
Remarks

The <Duration> element specifies the length of the vacuuming period. Vacuuming occurs daily, so the <Duration> value cannot exceed 24 hours.

The format of the XML duration data type is P0DT00H00M00S. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

See Also

Defining the <Vacuum> Node


<EventClass> Node

Provides a location for defining one event class.

Structure
<EventClasses>
   <EventClass>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <EventClasses> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <EventClasses> Node
Child Elements | <EventClassName> Element (<EventClass>) <Schema> Node (<EventClass>) <FileGroup> Element (<EventClass>) <IndexSqlSchema> Node (<EventClass>) <ChronicleRule> Node <Chronicles> Node (<EventClass>)
Remarks

If you delete an <EventClass> node, NSControl Update deletes the event class to which it corresponds, including all related SQL Server tables and indexes.

Important If you delete an <EventClass> node, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining an Event Class


<EventClasses> Node

Provides a parent location for defining the event classes used by this application.

Structure
<Application>
   ...
   <EventClasses>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <Application> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Application> Node
Child Elements | <EventClass> Node
Remarks

If you delete an <EventClasses> node, NSControl Update deletes the event class to which it corresponds, including all related SQL Server tables and indexes.

Important If you delete an <EventClasses> node, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining an Event Class


<EventClassName> Element (<EventClass>)

Specifies the user-defined name of the event class.

Structure
<EventClasses>
   <EventClass>
      <EventClassName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 128 characters in length.
Default Value | None.
Occurrence | Required once per <EventClass> node.
Updates | You can modify this element, but cannot add or delete it. Use NSControl Update to apply any modification.
Element Relationships
Relationship | Elements
Parent Node | <EventClass> Node
Remarks

The name of an event class must conform to SQL Server identifier naming conventions. It also must be unique within the application. For more information about SQL Server identifier naming conventions, see "Using Identifiers" in SQL Server Books Online.

If you add, delete, or update the <EventClassName> element, NSControl Update deletes and re-creates the event class to which it corresponds. This includes dropping and re-creating the SQL Server tables and indexes used by this event class.

Important If you add, delete, or update the <EventClassName> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Naming the Event Class


<EventClassName> Element (<EventRule>)

Specifies the event class with which the associated rule interacts.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <EventRules>
         <EventRule>
            ...
            <EventClassName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 128 characters in length.
Default Value | None.
Occurrence | Required once per <EventRule> node.
Updates | You can modify this element, but cannot add or delete it. Use NSControl Update to apply any modification.
Element Relationships
Relationship | Elements
Parent Node | <EventRule> Node

See Also

Defining Event Rules


<EventRule> Node

Provides the definition of a single subscription event rule.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <EventRules>
         <EventRule>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <EventRules> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <EventRules> Node
Child Elements | <RuleName> Element (<EventRule>) <Action> Element (<EventRule>) <ActionTimeout> Element (<EventRule>) <EventClassName> Element (<EventRule>)

See Also

Defining Event Rules


<EventRules> Node

Provides a location for all of the subscription event rule definitions for one subscription class.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <EventRules>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <SubscriptionClass> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <SubscriptionClass> Node
Child Elements | <EventRule> Node

See Also

Defining Event Rules


<EventThrottle> Element

Specifies the number of events that can be processed during a single generator quantum.

Structure
<ApplicationExecutionSettings>
   ...
   <EventThrottle>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | 1,000.
Occurrence | Optional once per <ApplicationExecutionSettings> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ApplicationExecutionSettings> Node

See Also

Defining an <EventThrottle> Element


<ExpirationAge> Element

Specifies the amount of time to elapse before unsent messages of the associated notification class are considered to have expired.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <ExpirationAge>
Element Characteristics
Characteristic | Description
Data Type | duration.
Default Value | None.
Occurrence | Optional once per <NotificationClass> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <NotificationClass> Node
Remarks

If no <ExpirationAge> value is specified, notifications never expire. Notification Services continues to attempt delivery of all notifications until the retry schedule is exhausted.

The format of the XML duration data type is P0DT00H00M00S. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

Notifications that have expired per the <ExpirationAge> value will be ignored during any delivery attempts.

See Also

Specifying the Notification Expiration Age


<FailureEventLogInterval> Element

Specifies the minimum amount of time that must pass between writes to the event log, regardless of how many failures occur.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         <Protocol>
            <ProtocolExecutionSettings>
               ...
               <FailureEventLogInterval>
Element Characteristics
Characteristic | Description
Data Type | duration.
Default Value | 0 minutes.
Occurrence | Optional once per <ProtocolExecutionSettings> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ProtocolExecutionSettings> Node
Remarks

The format of the XML duration data type is P0DT00H00M00S. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

The <FailureEventLogInterval> element works in conjunction with the <FailureBeforeLoggingEvent> element, to allow you to configure the error logging to fit the needs of your application.

See Also

Documenting the Delivery Protocols


<FailuresBeforeAbort> Element

Specifies the number of failures that can occur in attempting to deliver a batch of notifications before the attempt is aborted and an error is reported to the event log.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         <Protocol>
            <ProtocolExecutionSettings>
               ...
               <FailureBeforeAbort>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | 20.
Occurrence | Optional once per <ProtocolExecutionSettings> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ProtocolExecutionSettings> Node

See Also

Documenting the Delivery Protocols


<FailuresBeforeLoggingEvent> Element

Specifies the number of failures that can occur in attempting to deliver a batch of notifications before an error is reported to the event log.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         <Protocol>
            <ProtocolExecutionSettings>
               ...
               <FailureBeforeLoggingEvent>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | 1.
Occurrence | Optional once per <ProtocolExecutionSettings> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ProtocolExecutionSettings> Node
Remarks

The <FailureBeforeLoggingEvent> element works in conjunction with the <FailureEventLogInterval> element, to allow you to configure the error logging to fit the needs of your application.

See Also

Documenting the Delivery Protocols


<Field> Node (/EventClass/Schema)

Provides a location for defining one event class field.

Structure
<EventClasses>
   <EventClass>
      ...
      <Schema>
         <Field>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <Schema> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Schema> Node (<EventClass>)
Child Elements | <FieldName> Element (/EventClass/Schema/Field) <FieldType> Element (/EventClass/Schema/Field) <FieldTypeMods> Element (/EventClass/Schema/Field)
Remarks

If you add or delete a <Field> node, NSControl Update deletes and re-creates the event class to which it corresponds. This includes dropping and re-creating the SQL Server tables and indexes used by this event class.

Important If you add or delete a <Field> node, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Event Fields


<Field> Node (/Protocol/Fields)

Provides a location for defining one protocol header field.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         <Protocol>
            <Fields>
               <Field>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <Fields> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Fields> Node (<Protocol>)
Child Elements | <FieldName> Element (/Protocol/Fields/Field) –and– <SqlExpression> Element (/Protocol/Fields/Field) –or– <FieldReference> Element
Remarks

If you add or delete a <Field> node, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you add or delete a <Field> node, any data existing in the original SQL Server tables is permanently deleted.

See Also

Documenting the Delivery Protocols


<Field> Node (/Schema/Fields)

Provides a location for defining one notification class field.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Schema>
         <Fields>
            <Field>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <Fields> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Fields> Node (<Schema>)
Child Elements | <FieldName> Element (/NotificationClass/Schema/Fields/Field) <FieldType> Element (/NotificationClass/Schema/Fields/Field) <DigestGrouping> Element (<Field>)
Remarks

If you add or delete a <Field> node, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you add or delete a <Field> node, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Notification Fields


<Field> Node (/SubscriptionClass/Schema)

Provides a location for defining one subscription class field.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <Schema>
         <Field>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <Schema> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Schema> Node (<SubscriptionClass>)
Child Elements | <FieldName> Element (/SubscriptionClass/Schema/Field) <FieldType> Element (/SubscriptionClass/Schema/Field) <FieldTypeMods> Element (/SubscriptionClass/Schema/Field)
Remarks

If you add or delete a <Field> node, NSControl Update re-creates the subscription class to which it corresponds. A new subscription table is created, and the existing subscription table is renamed to SubscriptionTableNameOld. Existing subscription table indexes are left unchanged. If you want to transfer data between the old and new subscription tables, it must be done manually.

See Also

Defining Subscription Fields


<FieldName> Element (/EventClass/Schema/Field)

Specifies the user-defined name of the event field.

Structure
<EventClasses>
   <EventClass>
      ...
      <Schema>
         <Field>
            <FieldName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 128 characters in length.
Default Value | None.
Occurrence | Required once per <Field> node.
Updates | You can modify this element, but cannot add or delete it. Use NSControl Update to apply any modification.
Element Relationships
Relationship | Elements
Parent Node | <Field> Node (/EventClass/Schema)
Remarks

Field names must conform to SQL Server identifier naming conventions. For more information about SQL Server identifier naming conventions, see "Using Identifiers" in SQL Server Books Online.

Important You cannot name an event field EventBatchID or EventID. Notification Services already uses these two field names internally.

If you update a <FieldName> element, NSControl Update deletes and re-creates the event class to which it corresponds. This includes dropping and re-creating the SQL Server tables and indexes used by this event class.

Important If you update a <FieldName> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Event Fields


<FieldName> Element (/NotificationClass/Schema/ComputedFields/ComputedField)

Specifies the user-defined name of the computed notification field.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Schema>
         ...
         <ComputedFields>
            <ComputedField>
               <FieldName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 128 characters in length.
Default Value | None.
Occurrence | Required once per <ComputedField> node.
Updates | You can modify this element, but cannot add or delete it. Use NSControl Update to apply any modification.
Element Relationships
Relationship | Elements
Parent Node | <ComputedField> Node
Remarks

Field names must conform to SQL Server identifier naming conventions. For more information about SQL Server identifier naming conventions, see "Using Identifiers" in SQL Server Books Online.

If you update a <FieldName> element, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you update a <FieldName> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Notification Fields


<FieldName> Element (/NotificationClass/Schema/Fields/Field)

Specifies the user-defined name of the notification field.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Schema>
         <Fields>
            <Field>
               <FieldName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 128 characters in length.
Default Value | None.
Occurrence | Required once per <Field> node.
Updates | You can modify this element, but cannot add or delete it. Use NSControl Update to apply any modification.
Element Relationships
Relationship | Elements
Parent Node | <Field> Node (/Schema/Fields)
Remarks

Field names must conform to SQL Server identifier naming conventions. For more information about SQL Server identifier naming conventions, see "Using Identifiers" in SQL Server Books Online.

Important The following fields are used internally by Notification Services. You must not create notification fields with these names:

  • DeliveryChannelName
  • DeliveryStatusCode
  • DeviceAddress
  • DeviceName
  • DeviceTypeName
  • DistributorWorkItemId
  • ExpirationTime
  • LinkNotificationId
  • NotificationId
  • NotificationBatchId
  • SentTime
  • SubscriberId
  • SubscriberLocale

If you update a <FieldName> element, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you update a <FieldName> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Notification Fields


<FieldName> Element (/Protocol/Fields/Field)

Specifies the user-defined name of the notification field.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         <Protocol>
            ...
            <Fields>
               <Field>
                  <FieldName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 128 characters in length.
Default Value | None.
Occurrence | Required once per <Field> node.
Updates | You can modify this element, but cannot add or delete it. Use NSControl Update to apply any modification.
Element Relationships
Relationship | Elements
Parent Node | <Field> Node (/Protocol/Fields)
Remarks

Field names must conform to SQL Server identifier naming conventions. For more information about SQL Server identifier naming conventions, see "Using Identifiers" in SQL Server Books Online.

If you update a <FieldName> element, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you update a <FieldName> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Notification Fields


<FieldName> Element (/SubscriptionClass/Schema/Field)

Specifies the user-defined name of the subscription field.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <Schema>
         <Field>
            <FieldName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 128 characters in length.
Default Value | None.
Occurrence | Required once per <Field> node.
Updates | You can modify this element, but cannot add or delete it. Use NSControl Update to apply any modification.
Element Relationships
Relationship | Elements
Parent Node | <Field> Node (/SubscriptionClass/Schema)
Remarks

Field names must conform to SQL Server identifier naming conventions. For more information about SQL Server identifier naming conventions, see "Using Identifiers" in SQL Server Books Online.

Important You cannot name a subscription field Created, Enabled, SubscriberId, SubscriptionId, or Updated. Notification Services already uses these field names internally.

If you update a <FieldName> element, NSControl Update re-creates the subscription class to which it corresponds. A new subscription table is created, and the existing subscription table is renamed to SubscriptionTableNameOld. Existing subscription table indexes are left unchanged. If you want to transfer data between the old and new subscription tables, it must be done manually.

See Also

Defining Subscription Fields


<FieldReference> Element

Provides a reference to a notification field defined in the /NotificationClasses/NotificationClass/Schema/Fields section of the application definition file (ADF) that can be used to supply a protocol field value.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         <Protocol>
            ...
            <Fields>
               <Field>
                  ...
                  <FieldReference>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 128 characters in length.
Default Value | None.
Occurrence | Optional once per /NotificationClasses/NotificationClass/Protocols/Protocol/Fields/Field node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Field> Node (/Protocol/Fields)
Remarks

If you update a <FieldReference> element, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you update a <FieldReference> element, any data existing in the original SQL Server tables is permanently deleted.

Important If a <FieldReference> element is not included in the <Field> node, a <SqlExpression> element must be provided instead.</

See Also

Documenting the Delivery Protocols


<Fields> Node (<Protocol>)

Provides a location for all of the protocol header field definitions needed for one of the protocols used by the associated notification class.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         <Protocol>
            ...
            <Fields>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <Protocol> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Protocol> Node
Child Elements | <Field> Node (/Protocol/Fields)
Remarks

If you update a <Fields> node, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you update a <Fields> node, any data existing in the original SQL Server tables is permanently deleted.

See Also

Documenting the Delivery Protocols


<Fields> Node (<Schema>)

Provides a location for all of the non-computed notification field definitions for one notification class.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Schema>
         <Fields>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <Schema> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Schema> Node (<NotificationClass>)
Child Elements | <Field> Node (/Schema/Fields)
Remarks

If you update a <Fields> node, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you update a <Fields> node, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Notification Fields


<FieldType> Element (EventClass/Schema/Field)

 SQL Server Notification Services Books Online

<FieldType> Element (/EventClass/Schema/Field)

Specifies the SQL Server data type that the event field should implement.

Structure
<EventClasses>
   <EventClass>
      ...
      <Schema>
         <Field>
            ...
            <FieldType>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <Field> node.
Updates | You can modify this element, but cannot add or delete it. Use NSControl Update to apply any modification.
Element Relationships
Relationship | Elements
Parent Node | <Field> Node (/EventClass/Schema)
Remarks

<FieldType> values must conform to SQL Server data types. For more information about SQL Server data types, see "Using Data Types" in SQL Server Books Online.

If you update a <FieldType> element, NSControl Update deletes and re-creates the event class to which it corresponds. This includes dropping and re-creating the SQL Server tables and indexes used by this event class.

Important If you update a <FieldType> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Event Fields


<FieldType> Element (/NotificationClass/Schema/Fields/Field)

Specifies the SQL Server data type that the notification field should implement.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Schema>
         <Fields>
            <Field>
               ...
               <FieldType>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <Field> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Field> Node (/Schema/Fields)
Remarks

If you update a <FieldType> element, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you update a <FieldType> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining Subscription Fields


<FieldType> Element (/SubscriptionClass/Schema/Field)

Specifies the SQL Server data type that the subscription field should implement.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <Schema>
         <Field>
            ...
            <FieldType>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <Field> node.
Updates | You can modify this element, but cannot add or delete it. Use NSControl Update to apply any modification.
Element Relationships
Relationship | Elements
Parent Node | <Field> Node (/SubscriptionClass/Schema)
Remarks

<FieldType> values must conform to SQL Server data types. For more information about SQL Server data types, see "Using Data Types" in SQL Server Books Online.

If you update a <FieldType> element, NSControl Update re-creates the subscription class to which it corresponds. A new subscription table is created, and the existing subscription table is renamed to SubscriptionTableNameOld. Existing subscription table indexes are left unchanged. If you want to transfer data between the old and new subscription tables, it must be done manually.

See Also

Defining Subscription Fields


<FieldTypeMods> Element (/EventClass/Schema/Field)

Specifies optional SQL Server field attributes for an event field, such as null and default values.

Structure
<EventClasses>
   <EventClass>
      ...
      <Schema>
         <Field>
            ...
            <FieldTypeMods>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Optional once per <Field> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Field> Node (/EventClass/Schema)
Remarks

<FieldTypeMods> values must conform to SQL Server Transact-SQL syntax conventions. For more information about this syntax, see "CREATE TABLE" in SQL Server Books Online.

If you update a <FieldTypeMods> element, NSControl Update deletes and re-creates the event class to which it corresponds. This includes dropping and re-creating the SQL Server tables and indexes used by this event class.

Important If you update a <FieldTypeMods> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Event Fields


<FieldTypeMods> Element (/SubscriptionClass/Schema/Field)

Specifies optional SQL Server field attributes for a subscription field, such as null and default values.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <Schema>
         <Field>
            ...
            <FieldTypeMods>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Optional once per <Field> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Field> Node (/SubscriptionClass/Schema)
Remarks

If you update a <FieldTypeMods> element, NSControl Update re-creates the subscription class to which it corresponds. A new subscription table is created, and the existing subscription table is renamed to SubscriptionTableNameOld. Existing subscription table indexes are left unchanged. If you want to transfer data between the old and new subscription tables, it must be done manually.

See Also

Defining Subscription Fields


<FileGroup> Element (<EventClass>)

Specifies the SQL Server filegroup on which the event table will be created.

Structure
<EventClasses>
   <EventClass>
      ...
      <FileGroup>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | The event table is created on the default filegroup specified in the /Database/DefaultFileGroup section of the application definition file (ADF) if the <FileGroup> element is not specified. If the <DefaultFileGroup> element also is not specified, then the default filegroup for the SQL Server instance is used.
Occurrence | Optional once per <EventClass> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <EventClass> Node
Remarks

The <FileGroup> value must map to one of the <NamedFileGroup> values defined in the <Database> node.

If you update a <FileGroup> element, NSControl Update deletes and re-creates the event class to which it corresponds. This includes dropping and re-creating the SQL Server tables and indexes used by this event class.

Important If you update a <FileGroup> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Designating the Filegroup


<FileGroup> Element (<NotificationClass>)

Specifies the SQL Server filegroup on which the notification table will be created.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <FileGroup>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 128 characters in length.
Default Value | The notification table is created on the default filegroup specified in the /Database/DefaultFileGroup section of the application definition file (ADF) if the <FileGroup> element is not specified. If the <DefaultFileGroup> element also is not specified, then the default filegroup for the SQL Server instance is used.
Occurrence | Optional once per <NotificationClass> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <NotificationClass> Node
Remarks

The <FileGroup> value must map to one of the <NamedFileGroup> values defined in the <Database> node.

If you update a <FileGroup> element, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you update a <FileGroup> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Notification Fields

Designating the Filegroup


<FileGroup> Element (<SubscriptionClass>)

Specifies the SQL Server filegroup on which the subscription table will be created.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <FileGroup>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 128 characters in length.
Default Value | The subscription table is created on the default filegroup specified in the /Database/DefaultFileGroup section of the application definition file (ADF) if the <FileGroup> element is not specified. If the <DefaultFileGroup> element also is not specified, then the default filegroup for the SQL Server instance is used.
Occurrence | Optional once per <SubscriptionClass> node
Updates | Can be added, deleted, and modified using NSControl Update
Element Relationships
Relationship | Elements
Parent Node | <SubscriptionClass> Node
Remarks

The <FileGroup> value must map to one of the <NamedFileGroup> values defined in the <Database> node.

If you update a <FileGroup> element, NSControl Update re-creates the subscription class to which it corresponds. A new subscription table is created, and the existing subscription table is renamed to SubscriptionTableNameOld. Existing subscription table indexes are left unchanged. If you want to transfer data between the old and new subscription tables, it must be done manually.

See Also

Designating the Filegroup


<FileGroupName> Element

Specifies the user-defined name of the filegroup.

Structure
<Database>
   <NamedFileGroup>
      <FileGroupName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 128 characters in length.
Default Value | None.
Occurrence | Required once per <NamedFileGroup> node.
Updates | Cannot be added, deleted, or modified.
Element Relationships
Relationship | Elements
Parent Node | <NamedFileGroup> Node

See Also

Defining a <NamedFileGroup> Node


<FileName> Element (<FileSpec>)

Specifies the file name and path of a physical data file used by the application database.

Structure
<Database>
   <NamedFileGroup>
      ...
      <FileSpec>
         ...
         <FileName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 260 characters in length.
Default Value | None.
Occurrence | Required once per <FileSpec> node.
Updateable | Cannot be added, deleted, or modified.
Element Relationships
Relationship | Elements
Parent Node | <FileSpec> Node
Remarks

You must specify the file name of the application database data file in the <FileName> element. This is the full path and physical file name of the data file.

See Also

Defining a <NamedFileGroup> Node


<FileName> Element (<LogFile>)

Specifies the file name and path of a physical log file used by the application database.

Structure
<Database>
   ...
   <LogFile>
      ...
      <FileName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 260 characters in length.
Default Value | None.
Occurrence | Required once per <LogFile> node.
Updates | Cannot be added, deleted, or modified.
Element Relationships
Relationship | Elements
Parent Node | <LogFile> Node
Remarks

You must specify the file name of the application database log file in the <FileName> element. This is the full path and physical file name of the log file.

See Also

Defining a <LogFile> Node.


<FileSpec> Node

Provides a location for the information to create the application's data files.

Structure
<Database>
   <NamedFileGroup>
      ...
      <FileSpec>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <NamedFileGroup> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | <NamedFileGroup> Node
Child Elements | <LogicalName> Element (<FileSpec>) <FileName> Element (<FileSpec>) <Size> Element (<FileSpec>) <MaxSize> Element (<FileSpec>) <GrowthIncrement> Element (<FileSpec>)

See Also

Defining a <NamedFileGroup> Node


<Generator> Node

Provides a parent location for defining information about the generator used by this application.

Structure
<Application>
   ...
   <Generator>
Node Characteristics
Characteristic | Description
Occurrence | Required once per <Application> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | <Application> Node
Child Elements | <SystemName> Element (<Generator>) <ThreadPoolSize> Element (<Generator>)

See Also

Specifying Generator Settings


<GrowthIncrement> Element (<FileSpec>)

Specifies the increments by which the database size will increase when additional space is needed.

Structure
<Database>
   <NamedFileGroup>
      ...
      <FileSpec>
         ...
         <GrowthIncrement>
Element Characteristics
Characteristic | Description
Data Type | string (see Remarks).
Default Value | Increases by the default database growth increment specified for the SQL Server instance.
Occurrence | Optional once per <FileSpec> node.
Updates | Cannot be added, deleted, or modified.
Element Relationships
Relationship | Elements
Parent Node | <FileSpec> Node
Remarks

The <GrowthIncrement> value must be either the increment size or a percentage. If you choose to indicate the increment size, the value must be a non-negative integer, with an optional suffix to indicate the unit of measure: kilobyte (KB), megabyte (MB), gigabyte (GB), or terabyte (TB). If the suffix is not specified, the default unit of measure is megabytes (MB). If you specify a percentage, the database will grow by that percentage of the current database size if it runs out of room and needs to expand.

See Also

Defining a <NamedFileGroup> Node


<GrowthIncrement> Element (<LogFile>)

Specifies the file name and path of a physical log file used by the application database.

Structure
<Database>
   ...
   <LogFile>
      ...
      <GrowthIncrement>
Element Characteristics
Characteristic | Description
Data Type | string (see Remarks).
Default Value | Increases by the default database growth increment specified for the SQL Server instance.
Occurrence | Optional once per <LogFile> node.
Updateable | Cannot be added, deleted, or modified.
Element Relationships
Relationship | Elements
Parent Node | <LogFile> Node
Remarks

The <GrowthIncrement> value must be either the increment size or a percentage. If you choose to indicate the increment size, the value must be a non-negative integer, with an optional suffix to indicate the unit of measure: kilobyte (KB), megabyte (MB), gigabyte (GB), or terabyte (TB). If the suffix is not specified, the default unit of measure is megabytes (MB). If you specify a percentage, the log file will grow by that percentage of the current log file size if it runs out of room and needs to expand.

See Also

Defining a <LogFile> Node


<History> Node

Provides a parent location for collecting application definition file (ADF) history information.

Structure
<Application>
   ...
   <History>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <Application> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Application> Node
Child Elements | <CreationDate> Element <CreationTime> Element <LastModifiedDate> Element <LastModifiedTime> Element

See Also

Maintaining History Information


<HostedProvider> Node

Provides a location for specifying information about one hosted event provider used by this application.

Structure
<Providers>
   <HostedProvider>
Node Characteristics
Characteristic | Description
Occurrence | Optional once or more per <Providers> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Providers> Node
Child Elements | <ProviderName> Element (<HostedProvider>) <ClassName> Element (<HostedProvider>) <AssemblyName> Element (<HostedProvider>) <SystemName> Element (<HostedProvider>) <Schedule> Node (<HostedProvider>) Arguments Node (<HostedProvider>)

See Also

Defining an Event Provider


<IndexSqlSchema> Node (<EventClass>)

Provides a location for specifying the Transact-SQL statements needed for creating one or more indexes on an event table.

Structure
<EventClasses>
   <EventClass>
      ...
      <IndexSqlSchema>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <EventClass> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <EventClass> Node
Child Elements | <SqlStatement> Element (/EventClass/IndexSqlSchema)
Remarks

If you add or delete an <IndexSqlSchema> node, NSControl Update deletes and re-creates the event class to which it corresponds. This includes dropping and re-creating the SQL Server tables and indexes used by this event class.

Important If you add or delete an <IndexSqlSchema> node, any data existing in the original SQL Server tables is permanently deleted.

See Also

Creating the Indexing Statement


<IndexSqlSchema> Node (<SubscriptionClass>)

Provides a location for specifying the Transact-SQL statements needed for creating one or more indexes on a subscription table.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <IndexSqlSchema>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <SubscriptionClass> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <SubscriptionClass> Node
Child Elements | <SqlStatement> Element (/SubscriptionClass/IndexSqlSchema)
Remarks

If you add or delete an <IndexSqlSchema> node, NSControl Update re-creates the subscription class to which it corresponds. A new subscription table is created, and the existing subscription table is renamed to SubscriptionTableNameOld. Existing subscription table indexes are left unchanged. If you want to transfer data between the old and new subscription tables, it must be done manually.

See Also

Creating the Indexing Statement


<Interval> Element

Specifies how frequently after the initial start time the event provider is triggered to run.

Structure
<Providers>
   <HostedProvider>
      ...
      <Schedule>
         ...
         <Interval>
Element Characteristics
Characteristic | Description
Data Type | duration.
Default Value | None.
Occurrence | Required once per /HostedProvider/Schedule node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Schedule> Node (<HostedProvider>)
Remarks

The format of the XML duration data type is P0DT00H00M00S. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

Important The value you specify for the interval must divide evenly within a 24-hour period. For instance, 15 minutes is a valid interval, causing the event provider to run 96 times within a 24-hour period. However, 14 minutes is not a valid interval, because it implies that the event provider should run 102.86 times within a 24-hour period, which does not divide evenly within a 24-hour period.

See Also

Defining the Event Provider Schedule


<LastModifiedDate> Element

Specifies the date the application definition file (ADF) was last changed.

Structure
<History>
   ...
   <LastModifiedDate>
Element Characteristics
Characteristic | Description
Data Type | date.
Default Value | None.
Occurrence | Required once per <History> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <History> Node
Remarks

The format of the XML date data type is CCYY-MM-DD with an optional time zone indicator. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

See Also

Maintaining History Information


<LastModifiedTime> Element

Specifies the time the application definition file (ADF) was last changed.

Structure
<History>
   ...
   <LastModifiedTime>
Element Characteristics
Characteristic | Description
Data Type | time.
Default Value | None.
Occurrence | Required once per <History> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <History> Node
Remarks

The format of the XML time data type is HH:MM:SS.sss with an optional time zone indicator. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

See Also

Maintaining History Information


<LogBeforeDeliveryAttempts> Element

Indicates whether the distributor makes an entry in the distribution log before sending out a notification message.

Structure
<ApplicationExecutionSettings>
   ...
   <DistributorLogging>
      <LogBeforeDeliveryAttempts>
Element Characteristics
Characteristic | Description
Data Type | Boolean.
Default Value | true.
Occurrence | Optional once per <DistributorLogging> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <DistributorLogging> Node

See Also

Defining the <DistributorLogging> Node


<LogFile> Node

Provides a location for the information to create the application database's log files.

Structure
<Database>
   ...
   <LogFile>
Node Characteristics
Characteristic | Description
Occurrence | Optional one or more times per <Database> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | <Database> Node
Child Elements | <LogicalName> Element (<LogFile>) <FileName> Element (<LogFile>) <Size> Element (<LogFile>) <MaxSize> Element (<LogFile>) <GrowthIncrement> Element (<LogFile>)
Remarks

If no <LogFile> node is defined, the log files for the application database will be created on the default filegroup of the SQL Server instance being used.

See Also

Defining a <LogFile> Node


<LogicalName> Element (<FileSpec>)

Specifies the logical name that will be used in SQL Server to refer to the filegroup defined in the <FileSpec> node.

Structure
<Database>
   <NamedFileGroup>
      ...
      <FileSpec>
         <LogicalName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 260 characters in length.
Default Value | None.
Occurrence | Required once per <FileSpec> node.
Updates | Cannot be added, deleted, or modified.
Element Relationships
Relationship | Elements
Parent Node | <FileSpec> Node
Remarks

You must specify the logical name of the application database data file in the <LogicalName> element. The logical name is used to refer to the file in all Transact-SQL statements.

See Also

Defining a <NamedFileGroup> Node


<LogicalName> Element (<LogFile>)

Specifies the logical name that will be used in SQL Server to refer to the filegroup defined in the <LogFile> node.

Structure
<Database>
   ...
   <LogFile>
      <LogicalName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 260 characters in length.
Default Value | None.
Occurrence | Required once per <LogFile> node.
Updates | Cannot be added, deleted, or modified.
Element Relationships
Relationship | Elements
Parent Node | <LogFile> Node
Remarks

You must specify the logical name of the application database log file in the <LogicalName> element. The logical name is used to refer to the file in all Transact-SQL statements.

See Also

Defining a <LogFile> Node


<LogNotificationText> Element

Indicates whether the distributor logs the full text of any notification delivery information returned from the delivery protocol.

Structure
<ApplicationExecutionSettings>
   ...
   <DistributorLogging>
      ...
      <LogNotificationText>
Element Characteristics
Characteristic | Description
Data Type | Boolean.
Default Value | true.
Occurrence | Optional once per <DistributorLogging> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <DistributorLogging> Node
Remarks

Notification Services will always log information for a failed delivery. Setting this option to true will log this information for successful deliveries as well.

See Also

Defining the <DistributorLogging> Node


<LogStatusInfo> Element

Indicates whether the distributor logs the delivery status information for all messages it has attempted to send.

Structure
<ApplicationExecutionSettings>
   ...
   <DistributorLogging>
      ...
      <LogStatusInfo>
Element Characteristics
Characteristic | Description
Data Type | Boolean.
Default Value | true.
Occurrence | Optional once per <DistributorLogging> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <DistributorLogging> Node

See Also

Defining the <DistributorLogging> Node


<Major> Element

Specifies the major component of the application version number.

Structure
<Version>
   <Major>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | None.
Occurrence | Required once per <Version> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Version> Node

See Also

Maintaining Version Information


<MaxSize> Element (<FileSpec>)

Specifies the maximum size to which the SQL Server physical database file can grow.

Structure
<Database>
   <NamedFileGroup>
      ...
      <FileSpec>
         ...
         <MaxSize>
Element Characteristics
Characteristic | Description
Data Type | string (see Remarks).
Default Value | Unrestricted file growth.
Occurrence | Optional once per <FileSpec> node.
Updates | Cannot be added, deleted, or modified.
Element Relationships
Relationship | Elements
Parent Node | <FileSpec> Node
Remarks

The <MaxSize> value must be a non-negative integer indicating the database size, with an optional suffix to indicate the unit of measure: kilobyte (KB), megabyte (MB), gigabyte (GB), or terabyte (TB). If the suffix is not specified, the default unit of measure is megabytes (MB).

See Also

Defining a <NamedFileGroup> Node


<MaxSize> Element (<LogFile>)

Specifies the maximum size to which the SQL Server physical log file can grow.

Structure
<Database>
   ...
   <LogFile>
      ...
      <MaxSize>
Element Characteristics
Characteristic | Description
Data Type | string (see Remarks).
Default Value | Unrestricted file growth.
Occurrence | Optional once per <LogFile> node.
Updates | Cannot be added, deleted, or modified.
Element Relationships
Relationship | Elements
Parent Node | <LogFile> Node
Remarks

The <MaxSize> value must be a non-negative integer indicating the file size, with an optional suffix to indicate the unit of measure: kilobyte (KB), megabyte (MB), gigabyte (GB), or terabyte (TB). If the suffix is not specified, the default unit of measure is megabytes (MB).

See Also

Defining a <LogFile> Node


<Minor> Element

Specifies the minor component of the application version number.

Structure
<Version>
   ...
   <Minor>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | None.
Occurrence | Required once per <Version> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Version> Node

See Also

Maintaining Version Information


<MulticastDelivery> Element

Indicates whether the associated notification class uses multicast delivery.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <MulticastDelivery>
Element Characteristics
Characteristic | Description
Data Type | Boolean.
Default Value | false.
Occurrence | Optional once per <NotificationClass> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <NotificationClass> Node
Remarks

The <MulticastDelivery> value can be set to true only in Notification Services Enterprise Edition. It should be set to false or excluded entirely when using Notification Services Standard Edition.

See Also

Setting the Multicast Delivery Option


<MulticastRecipientLimit> Element

Specifies the number of recipients that can receive a single multicast notification message.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         <Protocol>
            <ProtocolExecutionSettings>
               ...
               <MulticastRecipientLimit>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | 100.
Occurrence | Optional once per <ProtocolExecutionSettings> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ProtocolExecutionSettings> Node

See Also

Documenting the Delivery Protocols


<Name> Element (/ContentFormatter/Arguments/Argument)

Specifies the name of an initialization argument for a content formatter.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <ContentFormatter>
         <Arguments>
            <Argument>
               <Name>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <Argument> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Argument> Node (/ContentFormatter/Arguments)

See Also

Documenting the Content Formatter


<Name> Element (/HostedProvider/Arguments/Argument)

Specifies the name of an initialization argument for a hosted event provider.

Structure
<Providers>
   <HostedProvider>
      ...
         <Arguments>
            <Argument>
               <Name>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <Argument> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Argument> Node (/HostedProvider/Arguments)

See Also

Defining the Event Provider Arguments


<Name> Element (<Parameter>)

Specifies the name of an application parameter.

Structure
<ParameterDefaults>
   <Parameter>
      <Name>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <Parameter> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Parameter> Node

See Also

Defining Application Parameters


<NamedFileGroup> Node

Provides a location for defining a SQL Server filegroup to be used by this application for its data files.

Structure
<Database>
   <NamedFileGroup>
Node Characteristics
Characteristic | Description
Occurrence | Optional one or more times per <Database> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | <Database> Node
Child Elements | <FileGroupName> Element <FileSpec> Node

See Also

Defining a <NamedFileGroup> Node


<NonHostedProvider> Node

Provides a location for specifying information about one independent event provider used by this application.

Structure
<Providers>
   ...
   <NonHostedProvider>
Node Characteristics
Characteristic | Description
Occurrence | Optional once or more per <Providers> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Providers> Node
Child Elements | <ProviderName> Element (<NonHostedProvider>)

See Also

Defining an Event Provider


<NotificationBatchSize> Element

For regular notifications, specifies the maximum number of notifications of the associated notification class that can be included in a batch. For digest notifications, specifies the number of notification batches that will be created.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <NotificationBatchSize>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | Unlimited notifications per batch for regular notifications. 1 notification batch for digest notifications.
Occurrence | Optional once per <NotificationClass> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <NotificationClass> Node
Remarks

<NotificationBatchSize> can be set to a non-zero value only in Notification Services Enterprise Edition.

See Also

Specifying a Notification Batch Size


<NotificationClass> Node

Provides a location for defining one notification class.

Structure
<NotificationClasses>
   <NotificationClass>
Node Characteristics
Characteristic | Description
Occurrence | Optional once or more per <NotificationClasses> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <NotificationClasses> Node
Child Elements | <NotificationClassName> Element <Schema> Node (<NotificationClass>) <FileGroup> Element (<NotificationClass>) <ContentFormatter> Node <DigestDelivery> Element <MulticastDelivery> Element <NotificationBatchSize> Element <Protocols> Node <ExpirationAge> Element
Remarks

If you delete a <NotificationClass> node, NSControl Update deletes the notification table for the notification class. This includes any data the table might contain.

See Also

Defining a Notification Class


<NotificationClasses> Node

Provides a parent location for defining the notification classes used by this application.

Structure
<Application>
   ...
   <NotificationClasses>
Node Characteristics
Characteristic | Description
Occurrence | Required once per <Application> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | <Application> Node
Child Elements | <NotificationClass> Node

See Also

Defining a Notification Class


<NotificationClassName> Element

Specifies the user-defined name of the notification class.

Structure
<NotificationClasses>
   <NotificationClass>
      <NotificationClassName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 128 characters in length.
Default Value | None.
Occurrence | Required once per <NotificationClass> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <NotificationClass> Node
Remarks

The name of a notification class must conform to SQL Server identifier naming conventions. It also must be unique within the application. For more information about SQL Server identifier naming conventions, see "Using Identifiers" in SQL Server Books Online.

If you update the <NotificationClassName> element, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you update the <NotificationClassName> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Naming the Notification Class


<NotificationThrottle> Element

Specifies the number of notifications that can be processed during a single generator quantum.

Structure
<ApplicationExecutionSettings>
   ...
   <NotificationThrottle>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | 1,000.
Occurrence | Optional once per <ApplicationExecutionSettings> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ApplicationExecutionSettings> Node

See Also

Defining the <NotificationThrottle> Element


<Parameter> Node

Provides a location to define a single application parameter.

Structure
<ParameterDefaults>
   <Parameter>
Node Characteristics
Characteristic | Description
Occurrence | Required one or more times per <ParameterDefaults> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <ParameterDefaults> Node
Child Elements | <Name> Element (<Parameter>) <Value> Element (<Parameter>)

See Also

Defining Application Parameters


<ParameterDefaults> Node

Provides a parent location for collecting application parameter information.

Structure
<Application>
   <ParameterDefaults>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <Application> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Application> Node
Child Elements | <Parameter> Node

See Also

Defining Application Parameters


<PerformanceQueryInterval> Element

Specifies how frequently system performance counters are updated.

Structure
<ApplicationExecutionSettings>
   ...
   <PerformanceQueryInterval>
Element Characteristics
Characteristic | Description
Data Type | duration.
Default Value | 60 seconds.
Occurrence | Optional once per <ApplicationExecutionSettings> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ApplicationExecutionSettings> Node
Remarks

The format of the XML duration data type is P0DT00H00M00S. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

See Also

Defining the <PerformanceQueryInterval> Element


<ProcessEventsInOrder> Element

Specifies whether Notification Services uses quantum sequencing or sub-quantum sequencing to process event and subscription rules.

Structure
<ApplicationExecutionSettings>
   ...
   <ProcessEventsInOrder>
Element Characteristics
Characteristic | Description
Data Type | Boolean.
Default Value | false (uses quantum sequencing).
Occurrence | Optional once per <ApplicationExecutionSettings> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ApplicationExecutionSettings> Node

See Also

Defining the <ProcessEventInOrder> Element


<Protocol> Node

Provides a location for defining a protocol that the associated notification class uses for notification message delivery.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         <Protocol>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <Protocols> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Protocols> Node
Child Elements | <ProtocolName> Element <Fields> Node (<Protocol>) <ProtocolExecutionSettings> Node
Remarks

If you add or delete a <Protocol> node, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you add or delete a <Protocol> node, any data existing in the original SQL Server tables is permanently deleted.

See Also

Documenting the Delivery Protocols


<ProtocolExecutionSettings> Node

Provides a location for defining the execution settings for one specific protocol that the associated notification class uses for notification message delivery.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         <Protocol>
            ...
            <ProtocolExecutionSettings>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <Protocol> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Protocol> Node
Child Elements | <RetrySchedule> Node <FailuresBeforeLoggingEvent> Element <FailureEventLogInterval> Element <FailuresBeforeAbort> Element <MulticastRecipientLimit> Element <WorkItemTimeout> Element

See Also

Documenting the Delivery Protocols


<ProtocolName> Element

Specifies the user-defined name of the protocol being used.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         <Protocol>
            <ProtocolName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <Protocol> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Protocol> Node
Remarks

For custom protocols, the <ProtocolName> value must map to the delivery protocol name as specified in the <Protocols> section of the configuration file. For delivery protocols provided by Notification Services, you must specify the well-known name of the protocol (SMTP, for example).

See Also

Documenting the Delivery Protocols


<Protocols> Node

Provides a location for defining one or more protocols that the associated notification class will use for notification message delivery.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <NotificationClass> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <NotificationClass> Node
Child Elements | <Protocol> Node
Remarks

If you add or delete the <Protocols> node, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you add or delete the <Protocols> node, any data existing in the original SQL Server tables is permanently deleted.

See Also

Documenting the Delivery Protocols


<ProviderName> Element (<HostedProvider>)

Specifies the user-defined name of the hosted event provider.

Structure
<Providers>
   <HostedProvider>
      <ProviderName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <HostedProvider> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <HostedProvider> Node
Remarks

The <ProviderName> value must be unique within the application.

See Also

Naming the Event Provider


<ProviderName> Element (<NonHostedProvider>)

Specifies the user-defined name of the independent event provider.

Structure
<Providers>
   <NonHostedProvider>
      <ProviderName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <NonHostedProvider> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <NonHostedProvider> Node
Remarks

The <ProviderName> value must be unique within the application.

See Also

Naming the Event Provider


<Providers> Node

Provides a parent location for defining the event providers used by this application.

Structure
<Application>
   ...
   <Providers>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <Application> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Application> Node
Child Elements | <HostedProvider> Node <NonHostedProvider> Node

See Also

Defining an Event Provider


<QuantumDuration> Element (<Application ExecutionSettings>)

 SQL Server Notification Services Books Online

<QuantumDuration> Element (<ApplicationExecutionSettings>)

Defines the length of time for a generator quantum, which determines how frequently the generator function attempts to process work.

Structure
<ApplicationExecutionSettings>
   <QuantumDuration>
Element Characteristics
Characteristic | Description
Data Type | duration.
Default Value | 60 seconds.
Occurrence | Optional once per <ApplicationExecutionSettings> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ApplicationExecutionSettings> Node
Remarks

The format of the XML duration data type is P0DT00H00M00S. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

See Also

Defining the <QuantumDuration> Element


<QuantumDuration> Element (<Distributor>)

Defines the length of time for a distributor quantum, which determines how frequently the distributor function attempts to process work.

Structure
<Distributors>
   <Distributor>
      ...
      <QuantumDuration>
Element Characteristics
Characteristic | Description
Data Type | duration.
Default Value | 60 seconds.
Occurrence | Optional once per <Distributor> node.
Updateable | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Distributor> Node
Remarks

The format of the XML duration data type is P0DT00H00M00S. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

See Also

Specifying Distributor Settings


<RetentionAge> Element

Specifies the minimum age at which system data is considered to be obsolete and available for removal.

Structure
<ApplicationExecutionSettings>
   ...
   <Vacuum>
      <RetentionAge>
Element Characteristics
Characteristic | Description
Data Type | duration.
Default Value | Seven days.
Occurrence | Optional once per <Vacuum> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Vacuum> Node
Remarks

Data is not removed any earlier than the period specified by the <RetentionAge> element, although it is not necessarily removed immediately on expiration of the specified period.

The format of the XML duration data type is P0DT00H00M00S. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

See Also

Defining the <Vacuum> Node


<RetryDelay> Element

Specifies an interval for the distributor to wait before re-sending any messages that failed to deliver successfully during a previous attempt.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         ...
         <ProtocolExecutionSettings>
            <RetrySchedule>
               <RetryDelay>
Element Characteristics
Characteristic | Description
Data Type | duration.
Default Value | None.
Occurrence | Required once or more per <RetrySchedule> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <RetrySchedule> Node
Remarks

The format of the XML duration data type is P0DT00H00M00S. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

See Also

Documenting the Delivery Protocols

Retry Logic


<RetrySchedule> Node

Provides a location for defining the intervals at which notification messages of this notification class will be re-sent if prior delivery attempts have failed.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         ...
         <ProtocolExecutionSettings>
            <RetrySchedule>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <ProtocolExecutionSettings> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <ProtocolExecutionSettings> Node
Child Elements | <RetryDelay> Element

See Also

Documenting the Delivery Protocols

Retry Logic


<Revision> Element

Specifies the revision component of the application version number.

Structure
<Version>
   ...
   <Revision>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | None.
Occurrence | Required once per <Version> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Version> Node

See Also

Maintaining Version Information


<RuleName> Element (<ChronicleRule>)

Specifies the user-defined name of the event chronicle rule.

Structure
<EventClasses>
   <EventClass>
      ...
      <ChronicleRule>
         <RuleName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <ChronicleRule> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ChronicleRule> Node
Remarks

The <RuleName> value must be unique within the application.

See Also

Defining Chronicle Rules

Event Chronicles


<RuleName> Element (<EventRule>)

Specifies the user-defined name of the subscription event rule.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <EventRules>
         <EventRule>
            <RuleName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <EventRule> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <EventRule> Node
Remarks

The <RuleName> value must be unique within the application.

See Also

Defining Event Rules

Subscription Rules


<RuleName> Element (<ScheduledRule>)

Specifies the user-defined name of the subscription scheduled rule.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <ScheduledRules>
         <ScheduledRule>
            <RuleName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <ScheduledRule> node.
Updateable | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ScheduledRule> Node
Remarks

The <RuleName> value must be unique within the application.

See Also

Defining Scheduled Rules

Subscription Rules


<Schedule> Node (<HostedProvider>)

Specifies the schedule for a hosted event provider.

Structure
<Providers>
   <HostedProvider>
      ...
      <Schedule>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <HostedProvider> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <HostedProvider> Node
Child Elements | <StartTime> Element (/HostedProvider/Schedule) <Interval> Element
Remarks

If no schedule is provided, the event provider runs continuously.

See Also

Defining the Event Provider Schedule


<Schedule> Node (<VacuumSchedule>)

Specifies the schedule for the vacuumer function.

Structure
<ApplicationExecutionSettings>
   ...
   <Vacuum>
      ...
      <VacuumSchedule>
         <Schedule>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <VacuumSchedule> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <VacuumSchedule> Node
Child Elements | <StartTime> Element (/VacuumSchedule/Schedule) <Duration> Element

See Also

Defining the <Vacuum> Node


<ScheduledRule> Node

Provides a location for the definition of a single subscription scheduled rule.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <ScheduledRules>
         <ScheduledRule>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <ScheduledRules> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <ScheduledRules> Node
Child Elements | <RuleName> Element (<ScheduledRule>) <Action> Element (<ScheduledRule>) <ActionTimeout> Element (<ScheduledRule>)

See Also

Defining Scheduled Rules


<ScheduledRules> Node

Provides a location for all subscription scheduled rule definitions for one subscription class.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <ScheduledRules>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <SubscriptionClass> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <SubscriptionClass> Node
Child Elements | <ScheduledRule> Node

See Also

Defining Scheduled Rules


<Schema> Node (<EventClass>)

Provides a location for defining the fields that make up an event class.

Structure
<EventClasses>
   <EventClass>
      ...
      <Schema>
Node Characteristics
Characteristic | Description
Occurrence | Required once per <EventClass> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | <EventClass> Node
Child Elements | <Field> Node (</EventClass/Schema>)

See Also

Defining the Event Fields


<Schema> Node (<NotificationClass>)

Provides a location for defining the fields that make up a notification class.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Schema>
Node Characteristics
Characteristic | Description
Occurrence | Required once per <NotificationClass> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | <NotificationClass> Node
Child Elements | <Fields> Node (<Schema>) <ComputedFields> Node

See Also

Defining the Notification Fields


<Schema> Node (<SubscriptionClass>)

Provides a location for defining the fields that make up a subscription class.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <Schema>
Node Characteristics
Characteristic | Description
Occurrence | Required once per <SubscriptionClass> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | <SubscriptionClass> Node
Child Elements | <Field> Node (/SubscriptionClass/Schema)

See Also

Defining Subscription Fields


<Size> Element (<FileSpec>)

Specifies the initial size of the application database.

Structure
<Database>
   <NamedFileGroup>
      ...
      <FileSpec>
         ...
         <Size
Element Characteristics
Characteristic | Description
Data Type | string (see Remarks).
Default Value | The default initial database size specified for the SQL Server instance; usually 1 megabyte (MB).
Occurrence | Optional once per <FileSpec> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <FileSpec> Node
Remarks

The <Size> value must be a non-negative integer indicating the database size, with an optional suffix to indicate the unit of measure: kilobyte (KB), megabyte (MB), gigabyte (GB), or terabyte (TB). If the suffix is not specified, the default unit of measure is megabytes (MB).

Important You can update the <Size> element for documentation purposes, but doing this has no effect on the application database size. If you want to change the size of the application database, use the SQL Server database administration tools to do so. NSControl Update issues a warning if you attempt to update <Database> or any of its subordinate elements, and no changes will be applied to the database.

See Also

Defining a <NamedFileGroup> Node


<Size> Element (<LogFile>)

Specifies the initial size of the application log file.

Structure
<Database>
   ...
   <LogFile>
      ...
      <Size>
Element Characteristics
Characteristic | Description
Data Type | string (see Remarks).
Default Value | The default initial database size specified for the SQL Server instance; usually 1 megabyte (MB).
Occurrence | Optional once per <LogFile> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <LogFile> Node
Remarks

The <Size> value must be a non-negative integer indicating the file size, with an optional suffix to indicate the unit of measure: kilobyte (KB), megabyte (MB), gigabyte (GB), or terabyte (TB). If the suffix is not specified, the default unit of measure is megabytes (MB).

Important You can update the <Size> element for documentation purposes, but doing this has no effect on the log file size. If you want to change the size of the log file, use the SQL Server database administration tools to do so. NSControl Update issues a warning if you attempt to update <Database> or any of its subordinate elements, and no changes will be applied to the log file.

See Also

Defining a <LogFile> Node


<SqlExpression> Element (<ComputedField>)

Specifies a valid Transact-SQL expression that provides the computed field value.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Schema>
         ...
         <ComputedFields>
            <ComputedField>
               ...
               <SqlExpression>
Element Characteristics
Characteristic | Description
Data Type | string, between 0 and 4,000 characters in length.
Default Value | None.
Occurrence | Required once per <ComputedField> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ComputedField> Node
Remarks

If you update a <SqlExpression> element, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you update a <SqlExpression> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Defining the Notification Fields


<SqlExpression> Element (/Protocol/Fields/Field)

Specifies a valid Transact-SQL expression that provides the protocol field value.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         <Protocol>
            ...
            <Fields>
               <Field>
                  ...
                  <SqlExpression>
Element Characteristics
Characteristic | Description
Data Type | string, between 0 and 4,000 characters in length.
Default Value | None.
Occurrence | Optional once per /NotificationClasses/NotificationClass/Protocols/Protocol/Fields/Field node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Field> Node (/Protocol/Fields)
Remarks

If you update a <SqlExpression> element, NSControl Update deletes and re-creates the notification class to which it corresponds. This includes dropping and re-creating the SQL Server tables used by this notification class.

Important If you update a <SqlExpression> element, any data existing in the original SQL Server tables is permanently deleted.

Important If a <SqlExpression> element is not included in the <Field> node, a <FieldReference> element must be provided instead.

See Also

Documenting the Delivery Protocols


<SqlSchema> Node (/EventClass/Chronicles/Chronicle)

Provides a location for the Transact-SQL statements that define the physical structure of an event chronicle table.

Structure
<EventClasses>
   <EventClass>
      ...
      <Chronicles>
         <Chronicle>
            ...
            <SqlSchema>
Node Characteristics
Characteristic | Description
Occurrence | Required once per <Chronicle> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | <Chronicle> Node (/EventClass/Chronicles)
Child Elements | <SqlStatement> Element (/EventClass/Chronicles/Chronicle/SqlSchema)

See Also

Defining Event Chronicle Tables

Event Chronicles


<SqlSchema> Node (/SubscriptionClass/Chronicles/Chronicle)

Provides a location for the Transact-SQL statements that define the physical structure of a subscription chronicle table.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <Chronicles>
         <Chronicle>
            ...
            <SqlSchema>
Node Characteristics
Characteristic | Description
Occurrence | Required once per <Chronicle> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | <Chronicle> Node (/SubscriptionClass/Chronicles)
Child Elements | <SqlStatement> Element (/SubscriptionClass/Chronicles/Chronicle/SqlSchema)

See Also

Defining Subscription Chronicle Tables

Subscription Chronicles


<SqlStatement> Element (/EventClass/Chronicles/Chronicle/SqlSchema)

Specifies a Transact-SQL statement to create a SQL Server event chronicle table.

Structure
<EventClasses>
   <EventClass>
      ...
      <Chronicles>
         <Chronicle>
            ...
            <SqlSchema>
               <SqlStatement>
Element Characteristics
Characteristic | Description
Data Type | string, between 0 and 100,000 characters in length.
Default Value | None.
Occurrence | Optional once or more per <SqlSchema> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <SqlSchema> Node (/EventClass/Chronicles/Chronicle)
Remarks

If you add, delete, or update a <SqlStatement> element, NSControl Update deletes the old chronicle table and creates a new, empty chronicle table. The data from the old chronicle table is permanently deleted.

See Also

Defining Chronicle Tables


<SqlStatement> Element (/EventClass/IndexSqlSchema)

Specifies a Transact-SQL statement to create a SQL Server index on the event table.

Structure
<EventClasses>
   <EventClass>
      ...
      <IndexSqlSchema>
         <SqlStatement>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 100,000 characters in length.
Default Value | None.
Occurrence | Optional once or more per <IndexSqlSchema> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <IndexSqlSchema> Node (<EventClass>)
Remarks

If you add, delete, or update a <SqlStatement> element, NSControl Update deletes and re-creates the event class to which it corresponds. This includes dropping and re-creating the SQL Server tables and indexes used by this event class.

Important If you add, delete, or update a <SqlStatement> element, any data existing in the original SQL Server tables is permanently deleted.

See Also

Creating the Indexing Statement


<SqlStatement> Element (/SubscriptionClass/Chronicles/Chronicle/SqlSchema)

Specifies a Transact-SQL statement to create a SQL Server subscription chronicle table.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <Chronicles>
         <Chronicle>
            ...
            <SqlSchema>
               <SqlStatement>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 100,000 characters in length.
Default Value | None.
Occurrence | Optional once or more per <SqlSchema> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <SqlSchema> Node (/SubscriptionClass/Chronicles/Chronicle)
Remarks

If you add, delete, or update a <SqlStatement> element, NSControl Update deletes the old chronicle table and creates a new, empty chronicle table. The data from the old chronicle table is permanently deleted.

See Also

Defining Chronicle Tables


<SqlStatement> Element (/SubscriptionClass/IndexSqlSchema)

Specifies a Transact-SQL statement to create a SQL Server index on the subscription table.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      ...
      <IndexSqlSchema>
         <SqlStatement>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 100,000 characters in length.
Default Value | None.
Occurrence | Optional once or more per <IndexSqlSchema> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <IndexSqlSchema> Node (<SubscriptionClass>)
Remarks

If you update a <FieldType> element, NSControl Update re-creates the subscription class to which it corresponds. A new subscription table is created, and the existing subscription table is renamed to SubscriptionTableNameOld. Existing subscription table indexes are left unchanged. If you want to transfer data between the old and new subscription tables, it must be done manually.

See Also

Creating the Indexing Statement


<StartTime> Element (/HostedProvider/Schedule)

Specifies the initial time after the application is set up that the event provider is to start running.

Structure
<Providers>
   <HostedProvider>
      ...
      <Schedule>
         <StartTime>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 512 characters in length.
Default Value | None.
Occurrence | Optional once per HostedProvider/Schedule node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Schedule> Node (<HostedProvider>)
Remarks

If no <StartTime> value is specified, the event provider starts running immediately after the application is set up.

The <StartTime> value must conform to the Microsoft .NET Framework string representation of a DateTime data type. The <StartTime> value must be specified in Universal Coordinated Time (UTC).

See Also

Defining the Event Provider Schedule


<StartTime> Element (/VacuumSchedule/Schedule)

Specifies the daily time when the vacuumer is to start running.

Structure
<ApplicationExecutionSettings>
   ...
   <Vacuum>
      ...
      <VacuumSchedule>
         <Schedule>
            <StartTime>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 512 characters in length.
Default Value | None.
Occurrence | Required once per /VacuumSchedule/Schedule node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Schedule> Node (<VacuumSchedule>)
Remarks

The <StartTime> value must conform to the Microsoft .NET Framework string representation of a DateTime data type. The <StartTime> value must be specified in Universal Coordinated Time (UTC).

If you indicate a date as well as a time for this value, only the time portion is used. The vacuumer starts at the specified time on the current day.

See Also

Defining the <Vacuum> Node


<SubscriptionClass> Node

Provides a location for defining one subscription class.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
Node Characteristics
Characteristic | Description
Occurrence | Optional once or more per <SubscriptionClasses> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <SubscriptionClasses> Node
Child Elements | <SubscriptionClassName> Element <Schema> Node (<SubscriptionClass>) <FileGroup> Element (<SubscriptionClass>) <IndexSqlSchema> Node (<SubscriptionClass>) <EventRules> Node <ScheduledRules> Node <Chronicles> Node (<SubscriptionClass>)
Remarks

If you delete a <SubscriptionClass> node, NSControl Update removes the subscription class, and renames the existing subscription table to SubscriptionTableNameOld. Existing subscription table indexes are left unchanged.

See Also

Defining a Subscription Class


<SubscriptionClasses> Node

Provides a parent location for defining the subscription classes used by this application.

Structure
<Application>
   ...
   <SubscriptionClasses>
Node Characteristics
Characteristic | Description
Occurrence | Required once per <Application> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Elements
Parent Node | <Application> Node
Child Elements | <SubscriptionClass> Node

See Also

Defining a Subscription Class


<SubscriptionClassName> Element

Specifies the user-defined name of the subscription class.

Structure
<SubscriptionClasses>
   <SubscriptionClass>
      <SubscriptionClassName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 128 characters in length.
Default Value | None.
Occurrence | Required once per <SubscriptionClass> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <SubscriptionClass> Node
Remarks

The name of a subscription class must conform to SQL Server identifier naming conventions. It also must be unique within the application. For more information about SQL Server identifier naming conventions, see "Using Identifiers" in SQL Server Books Online.

If you update the <SubscriptionClassName> element, NSControl Update re-creates the subscription class to which it corresponds. A new subscription table is created, and the existing subscription table is renamed to SubscriptionTableNameOld. Existing subscription table indexes are left unchanged. If you want to transfer data between the old and new subscription tables, it must be done manually.

See Also

Naming the Subscription Class


<SubscriptionThrottle> Element

Specifies the number of subscriptions that can be processed during a single generator quantum.

Structure
<ApplicationExecutionSettings>
   ...
   <SubscriptionThrottle>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | 1,000.
Occurrence | Optional once per <ApplicationExecutionSettings> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ApplicationExecutionSettings> Node

See Also

Defining a <SubscriptionThrottle> Element


<SubscriptionQuantumLimit> Element

Specifies how far behind the real-time clock the logical clock can fall before it skips processing subscription rules in order to catch up.

Structure
<ApplicationExecutionSettings>
   ...
   <SubscriptionQuantumLimit>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | 30 quanta, which is 30 minutes, assuming a <QuantumDuration> value of 1 minute.
Occurrence | Optional once per <ApplicationExecutionSettings> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ApplicationExecutionSettings> Node

See Also

Defining the <SubscriptionQuantumLimit> Element


<SystemName> Element (<Distributor>)

Specifies the name of the server on which the distributor runs.

Structure
<Distributors>
   <Distributor>
      <SystemName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <Distributor> node.
Updateable | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Distributor> Node
Remarks

IP addresses are not permitted as values for the <SystemName> element.

In Notification Services Standard Edition, all <SystemName> elements in an application must be identical. In Notification Services Enterprise Edition, the generator, distributors, and event providers can be distributed on multiple systems.

See Also

Specifying a Distributor


<SystemName> Element (<Generator>)

Specifies the name of the server on which the generator runs.

Structure
<Generator>
   <SystemName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <Generator> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Generator> Node
Remarks

IP addresses are not permitted as values for the <SystemName> element.

In Notification Services Standard Edition, all <SystemName> elements in an application must be identical. In Notification Services Enterprise Edition, the generator, distributors, and event providers can be distributed on multiple systems.

See Also

Specifying Generator Settings


<SystemName> Element (<HostedProvider>)

Specifies the name of the server on which the hosted event provider runs.

Structure
<Providers>
   <HostedProvider>
      ...
      <SystemName>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 255 characters in length.
Default Value | None.
Occurrence | Required once per <HostedProvider> node.
Updateable | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <HostedProvider> Node
Remarks

IP addresses are not permitted as values for the <SystemName> element.

In Notification Services Standard Edition, all <SystemName> elements in an application must be identical. In Notification Services Enterprise Edition, the generator, distributors, and event providers can be distributed on multiple systems.

See Also

Identifying the Notification Services System Machine


<ThreadPoolSize> Element (<Distributor>)

Specifies the number of threads that the distributor can use to process work items.

Structure
<Distributors>
   <Distributor>
      ...
      <ThreadPoolSize>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | 3.
Occurrence | Optional once per <Distributor> node.
Updateable | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Distributor> Node
Remarks

The value of the <ThreadPoolSize> element determines the amount of work the distributor can perform in parallel, and affects the overall speed of the Notification Services system.

<ThreadPoolSize> can have values between 1 and 3 in Notification Services Standard Edition. The <ThreadPoolSize> value is unlimited in Notification Services Enterprise Edition.

See Also

Specifying a Distributor

Specifying Distributor Settings


<ThreadPoolSize> Element (<Generator>)

Specifies the number of threads that the generator can use to process event batches.

Structure
<Generator>
   ...
   <ThreadPoolSize>
Element Characteristics
Characteristic | Description
Data Type | Non-negative integer.
Default Value | 1.
Occurrence | Optional once per <Generator> node.
Updateable | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Generator> Node
Remarks

The number of threads allocated to the generator thread pool cannot exceed 25 threads per processor.

The value of the <ThreadPoolSize> element determines the amount of work that the generator can perform in parallel, and affects the overall speed of the Notification Services system.

<ThreadPoolSize> can differ from the default only in Notification Services Enterprise Edition.

See Also

Specifying Generator Settings


<Vacuum> Node

Provides a location for specifying vacuuming information for the application.

Structure
<ApplicationExecutionSettings>
   ...
   <Vacuum>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <ApplicationExecutionSettings> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <ApplicationExecutionSettings> Node
Child Elements | <RetentionAge> Element <VacuumSchedule> Node

See Also

Defining the <Vacuum> Node


<VacuumSchedule> Node

Provides a location for specifying the schedule for the vacuumer.

Structure
<ApplicationExecutionSettings>
   ...
   <Vacuum>
      ...
      <VacuumSchedule>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <Vacuum> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Vacuum> Node
Child Elements | <Schedule> Node (<VacuumSchedule>)

See Also

Defining the <Vacuum> Node


<Value> Element (/ContentFormatter/Arguments/Argument)

Specifies the value of an initialization argument for a content formatter.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <ContentFormatter>
         <Arguments>
            <Argument>
               ...
               <Value>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 4,000 characters in length.
Default Value | None.
Occurrence | Required once per <Argument> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Argument> Node (/ContentFormatter/Arguments)

See Also

Documenting the Content Formatter


<Value> Element (/HostedProvider/Arguments/Argument)

Specifies the value of an initialization argument for a hosted event provider.

Structure
<Providers>
   <HostedProvider>
      ...
         <Arguments>
            <Argument>
               ...
               <Value>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 4,000 characters in length.
Default Value | None.
Occurrence | Required once per <Argument> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Argument> Node (/HostedProvider/Arguments)

See Also

Defining the Event Provider Arguments


<Value> Element (<Parameter>)

Specifies the value of an application parameter.

Structure
<ParameterDefaults>
   <Parameter>
      ...
      <Value>
Element Characteristics
Characteristic | Description
Data Type | string, between 1 and 4,000 characters in length.
Default Value | None.
Occurrence | Required once per <Parameter> node.
Updates | Can be modified, but not added or deleted, using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <Parameter> Node
Remarks

The value of the <Value> element must match the format of the element for which it supplies a parameter. For instance, if the value is to specify information that uses a duration data type, it should follow the P0DT00H00M00S format.

See Also

Defining Application Parameters


<Version> Node

Provides a parent location for collecting application version information.

Structure
<Application>
   ...
   <Version>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <Application> node.
Updates | Can be added and deleted using NSControl Update.
Node Relationships
Relationship | Elements
Parent Node | <Application> Node
Child Elements | <Major> Element <Minor> Element <Build> Element <Revision> Element
Remarks

When updating the <Version> child elements, the complete version number must be greater than or equal to the previous version number.

For example, as shown in the following table, updating from the initial version number of 2.1.24.0 to 2.1.24.1 is fine. However, updating to 2.0.24.1 raises an error from NSControl Update.

Initial version number Acceptable update Invalid update
<Major>2</Major>

<Minor>1</Minor>
<Build>24</Build>
<Revision>0</Revision>

<Major>2</Major>

<Minor>1</Minor>
<Build>24</Build>
<Revision>1</Revision>

<Major>2</Major>

<Minor>0</Minor>
<Build>24</Build>
<Revision>1</Revision>

See Also

Maintaining Version Settings


<WorkItemTimeout> Element

Specifies the amount of time a distributor thread can take to complete a work item assigned to it, before the job is canceled and the work item is returned to the available work item pool.

Structure
<NotificationClasses>
   <NotificationClass>
      ...
      <Protocols>
         <Protocol>
            <ProtocolExecutionSettings>
               ...
               <WorkItemTimeout>
Element Characteristics
Characteristic | Description
Data Type | duration.
Default Value | 15 minutes.
Occurrence | Optional once per <ProtocolExecutionSettings> node.
Updates | Can be added, deleted, and modified using NSControl Update.
Element Relationships
Relationship | Elements
Parent Node | <ProtocolExecutionSettings> Node
Remarks

The format of the XML duration data type is P0DT00H00M00S. For more information about XML data types, see Primitive XML Data Types in the Microsoft MSDN® Library.

See Also

Documenting the Delivery Protocols


Configuration File Reference

A configuration file is a structured XML file that describes a single instance of Notification Services. The instance hosts one or more applications, so the instance contains metadata about those applications. The configuration file also contains metadata about the instance, database server, delivery protocols, and delivery channels.

The configuration file must conform to the ConfigurationFileSchema.xsd schema, which is in the Notification Services XML Schemas folder.

The nodes and elements in the configuration file are described in this reference section. Use the links below to access information about a node or element.

NotificationServicesInstance Node
Node Name | Description
<NotificationServicesInstance> Node | As the top node of the configuration file, contains all other configuration file nodes and elements.
ParameterDefaults Node
Node or Element Name | Description
<ParameterDefaults> Node | Contains one or more <Parameter> nodes, which provide default values for each parameter within the configuration file.
<Parameter> Node (<ParameterDefaults>) | Contains one name/value pair that provides a default value for a parameter in the configuration file.
<Name> Element (/ParameterDefaults/Parameter) | Is the name of one parameter in the configuration file.
<Value> Element (/ParameterDefaults/Parameter) | Is the value of one parameter in the configuration file.
Version Node
Node or Element Name | Description
<Version> Node | Contains elements that provide the Notification Services version number used by the instance.
<Major> Element | Is the major version number, which is the first number in the product version string.
<Minor> Element | Is the minor version number, which is the second number in the product version string.
<Build> Element | Is the build number, which is the third number in the product version string.
<Revision> Element | Is the revision number, which is the fourth number in the product version string.
History Node
Node or Element Name | Description
<History> Node | Contains elements that provide the date and time of the configuration file's creation and last modification.
<CreationDate> Element | Is the date the configuration file was created.
<CreationTime> Element | Provides the time the configuration file was created.
<LastModifiedDate> Element | Provides the date the configuration file was last modified.
<LastModifiedTime> Element | Provides the time the configuration file was last modified.
InstanceName Element
Element Name | Description
<InstanceName> Element | Provides the logical name for the instance of Notification Services.
SqlServerSystem Element
Element Name | Description
<SqlServerSystem> Element | Provides the name of an instance of SQL Server that hosts the Notification Services instance database and its application databases.
Database Node
Node or Element Name | Description
<Database> Node | Contains elements that specify database parameters for the instance database, instance_name NSMain. The <Database> node contains information about filegroups, the database files in those filegroups, and the database log.
<NamedFileGroup> Node | Contains elements that describe a filegroup used by the database.
<FileGroupName> Element | Provides the name of one filegroup used by the instance database.
<FileSpec> Node | Contains elements that describe the properties of one database file.
<LogicalName> Element (<FileSpec>) | Provides the name used to refer to the database file.
<FileName> Element (<FileSpec>) | Provides the path and file name used by the operating system when it creates a database file.
<Size> Element (<FileSpec>) | Provides the initial size of the database file.
<MaxSize> Element (<FileSpec>) | Provides the maximum size to which the database file can grow.
<GrowthIncrement> Element (<FileSpec>) | Is the amount of space that is added to the database file each time new space is needed.
<LogFile> Node | Contains elements that define one log file.
<LogicalName> Element (<LogFile>) | Is the name used to refer to the log file.
<FileName> Element (<LogFile>) | Is the path and file name used by the operating system when it creates a log file.
<Size> Element (<LogFile>) | Is the initial size of the log file.
<MaxSize> Element (<LogFile>) | Is the maximum size to which the log file can grow.
<GrowthIncrement> Element (<LogFile>) | Is the amount of space that is added to the log file each time new space is needed.
<DefaultFileGroup> Element | Specifies one of the <NamedFileGroup> entries to be used as the default filegroup when creating SQL Server objects for the instance.
<CollationName> Element | Specifies the collation of the database, which determines the languages supported by the database, and the sort order in which query results are returned.
Applications Node
Node or Element Name | Description
<Applications> Node | Contains one or more <Application> nodes, each of which describes one application hosted by the instance.
<Application> Node | Contains elements that describe a single notification application.
<ApplicationName> Element | Is the logical name of the application.
<BaseDirectoryPath> Element | Is the path of the application folder, which contains application-related files such as the ADF, XML, and XSLT files.
<ApplicationDefinitionFilePath> Element | Specifies the file name of the ADF, and optionally its relative path.
<Parameters> Node | Contains an application-specific set of parameters that are passed to the ADF.
<Parameter> Node (/Application/Parameters) | Contains one name/value pair that provides a value for a parameter in the ADF.
<Name> Element (/Application/Parameters/Parameter) | Is the name of a parameter to be passed to the ADF.
<Value> Element (/Application/Parameters/Parameter) | Is the value of a parameter passed to the ADF.
Protocols Node
Node or Element Name | Description
<Protocols> Node | Contains one or more <Protocol> nodes, each of which describes a custom delivery protocol used to deliver messages.
<Protocol> Node | Contains elements that describe a single custom delivery protocol.
<ProtocolName> Element | Is the name of a custom delivery protocol.
<ClassName> Element | Is the class name for the delivery protocol, which is within the assembly specified by the <AssemblyName> element.
<AssemblyName> Element | Is the path and file name of the assembly that contains the delivery protocol class.
DeliveryChannels Node
Node or Element Name | Description
<DeliveryChannels> Node | Contains one or more <DeliveryChannel> nodes that describe all the delivery channels used by all applications hosted by the instance.
<DeliveryChannel> Node | Contains elements that describe the properties of a single delivery channel instance.
<DeliveryChannelName> Element | Is the logical name of the delivery channel.
<ProtocolName> Element (<DeliveryChannel>) | Is the name of the protocol, either standard or custom, used by the delivery channel.
<Arguments> Node | Contains one or more <Argument> nodes that specify name/value pairs for delivery channel arguments.
<Argument> Node | Contains one name/value pair that provides a value for a delivery channel argument.
<Name> Element (/DeliveryChannel/Arguments/Argument) | Is the name of one argument to be passed to the delivery channel.
<Value> Element (/DeliveryChannel/Arguments/Argument) | Is the value of one argument passed to the delivery channel.
EncryptArguments Element
Element Name | Description
<EncryptArguments> Element | Specifies whether the instance encrypts delivery channel and event provider arguments before storing the values in the instance and application databases.

See Also

Configuration File Conventions

Configuration File Samples

XML Declaration


Configuration File Rules

The following rules apply to all configuration file nodes and elements in Notification Services:

  • Node and element names are case sensitive.
  • The nodes and elements in the configuration file must appear in the order defined by the schema. For an example, see Complete Configuration File.
  • Optional nodes can be removed or can contain empty child elements.
  • In XML, some characters are reserved for internal use, so you must replace them with entity references. Additionally, the Notification Services XML vocabulary reserves the percent sign (%) for denoting parameters.

    The following table shows the reserved characters and the entity references that must replace them in the configuration file.

    Character Meaning Entity Reference
    > Greater than &gt;
    < Less than &lt;
    ' Apostrophe (single quote) &apos;
    " Quotation mark (double quote) &quot;
    & Ampersand &amp;
    % Percent &#37;

See Also

Configuration File Reference


Configuration File Samples

The two samples that this section covers include one complete sample, which shows the use of optional parameters, and one minimal sample, which shows the use of only the required parameters. You can use these samples as a reference when creating your own configuration files.

Topic | Description
Complete Configuration File | Is a configuration file that shows both optional and required nodes and elements.
Minimal Configuration File | Is a configuration file that shows only the required nodes and elements.

See Also

Configuration File Reference


Complete Configuration File

This sample configuration file shows the use of all configuration file nodes and elements, including the optional <ParameterDefaults>, <Version>, <History>, and <Database> nodes.

This sample configuration file requires values for the following five parameters:

  • %User%
  • %Pwd%
  • %InstanceName%
  • %System%
  • %BaseDirectoryPath%

Two of these parameters, %BaseDirectoryPath% and %System%, are provided with values in the <ParameterDefaults> node. You provide values for the other parameters on the command line when running the NSControl Create or NSControl Update command.

Example: Complete Configuration File XML
<?xml version="1.0" encoding="utf-8"?>
<!--Microsoft Notification Services "Configuration File"-->

<NotificationServicesInstance xmlns:ns="http://www.microsoft.com/MicrosoftNotificationServices/ConfigurationFileSchema" xmlns="http://www.microsoft.com/MicrosoftNotificationServices/ConfigurationFileSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.microsoft.com/MicrosoftNotificationServices/ConfigurationFileSchema http://localhost/NotificationServices/ConfigurationFileSchema.xsd">

<!--Default Parameters-->
<ParameterDefaults>
   <Parameter>
      <Name>BaseDirectoryPath</Name>
      <Value>C:\Program Files\Microsoft Notification Services\%InstanceName%</Value>
   </Parameter>
   <Parameter>
      <Name>System</Name>
      <Value>MyServer</Value>
   </Parameter>
</ParameterDefaults>

<!--Version-->
<Version>
   <Major>2</Major>
   <Minor>0</Minor>
   <Build>162</Build>
   <Revision>1</Revision>
</Version>

<!--History-->
<History>
   <CreationDate>2001-09-22</CreationDate>
   <CreationTime>10:30:00</CreationTime>
   <LastModifiedDate>2002-4-22</LastModifiedDate>
   <LastModifiedTime>22:30:00</LastModifiedTime>
</History>

<!--Instance Name-->
<InstanceName>%InstanceName%</InstanceName>

<!--SQL Server machine name-->
<SqlServerSystem>%System%</SqlServerSystem>

<!--Database-->
<Database>
   <NamedFileGroup>
      <FileGroupName>primary</FileGroupName>
      <FileSpec>
         <LogicalName>PrimaryFG1</LogicalName>
         <FileName>%BaseDirectoryPath%\Primary.mdf</FileName>
         <Size>10MB</Size>
         <MaxSize>14MB</MaxSize>
         <GrowthIncrement>15%</GrowthIncrement>
      </FileSpec>
   </NamedFileGroup>
   <NamedFileGroup>
      <FileGroupName>MyFileGroup</FileGroupName>
      <FileSpec>
         <LogicalName>MyLogicalName</LogicalName>
         <FileName>%BaseDirectoryPath%\MyLogicalName.mdf</FileName>
         <Size>55MB</Size>
         <MaxSize>100MB</MaxSize>
         <GrowthIncrement>15%</GrowthIncrement>
      </FileSpec>
   </NamedFileGroup>
   <NamedFileGroup>
      <FileGroupName>MyDefault2</FileGroupName>
      <FileSpec>
         <LogicalName>MyLogicalDefault2</LogicalName>
         <FileName>%BaseDirectoryPath%\MyDefault2.mdf</FileName>
         <Size>1MB</Size>
         <MaxSize>3MB</MaxSize>
         <GrowthIncrement>15%</GrowthIncrement>
      </FileSpec>
   </NamedFileGroup>
</Database>

<!--Applications-->
<Applications>
   <Application>
      <ApplicationName>Stock</ApplicationName>
      <BaseDirectoryPath>%BaseDirectoryPath%\Stock</BaseDirectoryPath>
      <ApplicationDefinitionFilePath>StockADF.xml</ApplicationDefinitionFilePath>
      <Parameters>
         <Parameter>
            <Name>DBSystem</Name>
            <Value>%System%</Value>
         </Parameter>
         <Parameter>
            <Name>NSSystem</Name>
            <Value>%System%</Value>
         </Parameter>
      </Parameters>
   </Application>
</Applications>

<!--Protocols-->
<Protocols>
   <Protocol>
      <ProtocolName>SMS</ProtocolName>
      <ClassName>Protocols.SMSProtocol</ClassName>
      <AssemblyName>SMS.dll</AssemblyName>
   </Protocol>
</Protocols>

<!--Delivery Channels-->
<DeliveryChannels>
   <DeliveryChannel>
      <DeliveryChannelName>EmailChannel</DeliveryChannelName>
      <ProtocolName>SMTP</ProtocolName>
      <Arguments>
         <Argument>
            <Name>User</Name>
            <Value>%User%</Value>
         </Argument>
         <Argument>
            <Name>Pwd</Name>
            <Value>%Pwd%</Value>
         </Argument>
      </Arguments>
   </DeliveryChannel>
   <DeliveryChannel>
      <DeliveryChannelName>CustomSMSChannel</DeliveryChannelName>
      <ProtocolName>SMS</ProtocolName>
      <Arguments>
         <Argument>
            <Name>User</Name>
            <Value>%User%</Value>
         </Argument>
         <Argument>
            <Name>Pwd</Name>
            <Value>%Pwd%</Value>
         </Argument>
      </Arguments>
   </DeliveryChannel>
</DeliveryChannels>

<!--Argument Encryption Flag -->
<EncryptArguments>false</EncryptArguments>

</NotificationServicesInstance>

See Also

Configuration File Reference

Configuration File Samples


Minimal Configuration File

This sample configuration file shows the sections and elements that must be included in a configuration file for the file to be valid.

This sample configuration file requires definitions for the following three parameters:

  • %InstanceName%
  • %System%
  • %BaseDirectoryPath%

You provide values for these three parameters on the command line when running the NSControl Create or NSControl Update command.

Example: Minimal Configuration File XML
<?xml version="1.0" encoding="utf-8"?>
<NotificationServicesInstance>

<!--Instance Name-->
<InstanceName>%InstanceName%</InstanceName>

<!--SQL Server machine name-->
<SqlServerSystem>%System%</SqlServerSystem>

<!--Applications-->
<Applications>
   <Application>
      <ApplicationName>Stock</ApplicationName>
      <BaseDirectoryPath>%BaseDirectoryPath%</BaseDirectoryPath>
      <ApplicationDefinitionFilePath>StockADF.xml</ApplicationDefinitionFilePath>
   </Application>
</Applications>

<!--Delivery Channels-->
<DeliveryChannels>
   <DeliveryChannel>
      <DeliveryChannelName>EmailChannel</DeliveryChannelName>
      <ProtocolName>SMTP</ProtocolName>
   </DeliveryChannel>
</DeliveryChannels>

</NotificationServicesInstance>

See Also

Configuration File Reference

Configuration File Samples


XML Declaration

Declares the XML version and optionally declares the encoding and whether the file depends on any external resources.

<?xml version="1.0" encoding="UTF-8"? standalone="yes"?>
Attributes
Attribute Name | Description
version | Required.
encoding | Optional. If used, the encoding declaration must appear immediately after the version information in the XML declaration, and must contain a value representing an existing character encoding. The encoding declaration identifies which encoding is used to represent the characters in the document. Although XML parsers can determine automatically whether a document uses the UTF-8 or UTF-16 Unicode encoding, this declaration should be used in documents that support other encodings.
standalone | Optional. If used, the stand-alone declaration must appear last in the XML declaration. The stand-alone declaration indicates whether a document relies on information from an external source, such as external document type definition (DTD), for its content.
Remarks

The XML declaration must appear as the first line of the document without other content or white space before the opening angle bracket (<).

For additional information, see XML Declaration in the Microsoft MSDN® Library.


<Application> Node

Contains elements that describe a single notification application hosted by the instance.

Structure
<Applications>
   <Application>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <Applications> node.
Updates | Can be added or deleted, and then applied using NSControl Update.
Node Relationships
Relationship | Element or Node
Parent Node | <Applications> Node
Child Elements | <ApplicationName> Element <BaseDirectoryPath> Element <ApplicationDefinitionFilePath> Element <Parameters> Node
Remarks

If multiple applications are hosted by the instance, the configuration file contains multiple <Application> nodes, each with child elements that describe an application.

Example

This example shows a complete <Application> node:

<Application>
   <ApplicationName>Stock</ApplicationName>
   <BaseDirectoryPath>C:\NSApps\Stock</BaseDirectoryPath>
   <ApplicationDefinitionFilePath>StockADF.xml</ApplicationDefinitionFilePath>
   <Parameters>
      <Parameter>
         <Name>DBSystem</Name>
         <Value>YourSqlServer</Value>
      </Parameter>
      <Parameter>
         <Name>NSSystem</Name>
         <Value>YourNSServer</Value>
      </Parameter>
   </Parameters>
</Application>

See Also

Application Definition File Reference

Configuration File Reference


<ApplicationDefinitionFilePath> Element

Is the file name, and optionally the path to, the application definition file (ADF).

Structure
<Applications>
   <Application>
      ...
      <ApplicationDefinitionFilePath>
Element Characteristics
Characteristic | Description
Value | string of length between 1 and 260 characters.
Default Value | None.
Occurrence | Required once per <Application> node.
Updates | Can be modified, and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Application> Node
Remarks

If the ADF file is in the folder specified by <BaseDirectoryPath>, use only the ADF name, such as StockADF.xml.

If the ADF file is not in the folder specified by <BaseDirectoryPath>, the <ApplicationDefinitionFilePath> value is a relative path from <BaseDirectoryPath> to the ADF, such as ..\..\Datafiles\StockADF.xml, or is a fully qualified path, such as D:\Datafiles\StockADF.xml or \\Server\Share\StockADF.xml.

Examples

The following examples show two ways to specify a value for the <ApplicationDefinitionFilePath> element.

Specifying only the ADF name

This example shows how to provide an ADF file name when the file is located in the <BaseDirectoryPath> folder:

<ApplicationDefinitionFilePath>StockADF.xml</ApplicationDefinitionFilePath>
Specifying a relative path to the ADF

This example shows how to specify a path relative to the <BaseDirectoryPath> folder:

<ApplicationDefinitionFilePath>..\..\ADFs\StockADF.xml</ApplicationDefinitionFilePath>
Specifying a fully qualified path to the ADF

This example shows how to specify a fully qualified path that is not relative to the <BaseDirectoryPath> folder:

<ApplicationDefinitionFilePath>D:\Datafiles\StockADF.xml</ApplicationDefinitionFilePath>

See Also

Application Definition File Reference

Configuration File Reference


<ApplicationName> Element

Is the logical name of the application, which must be unique within the configuration file. This is the only place where a name is given to the application.

Structure
<Applications>
   <Application>
      <ApplicationName>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 127 characters.
Default Value | None.
Occurrence | Required once per <Application> node.
Updates | Can be modified, and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Application> Node
Remarks

The <ApplicationName> element allows a string of 1 to 255 characters. However, this name, plus the instance name, is used for the application database name, and database names are limited to 128 characters. Because the application database name is a concatenation of application and instance name, limit <ApplicationName> to a length that does not violate object naming rules.

Because this value is used to create SQL Server objects, follow the SQL Server rules for regular identifiers. Do not use SQL Server reserved keywords or special characters. For more information, see "Using Identifiers" in SQL Server Books Online.

If you update <ApplicationName>, NSControl Update disassociates the existing application from the instance and creates a new application with the new name. NSControl Update does not delete the old application database from SQL Server nor does it transfer any data from the old application database to the new application database. When NSControl Update completes, you can manually transfer data and then delete the old application database.

Example

This example shows how to specify an application name of Stock1:

<ApplicationName>Stock1</ApplicationName>

See Also

Application Definition File Reference

Configuration File Reference


<Applications> Node

Contains one or more <Application> nodes, each of which describes an application hosted by the instance.

Structure
<NotificationServicesInstance>
   ...
   <Applications>
Node Characteristics
Characteristic | Description
Occurrence | Required once per <NotificationServicesInstance> node.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Element or Node
Parent Node | <NotificationServicesInstance> Node
Child Elements | <Application> Node
Example

This example shows a complete <Applications> node with two applications. The example illustrates using parameters for the <BaseDirectoryPath> element and passing values to the application definition file (ADF). Values for %BaseDirectoryPath%, %DBSystem%, and %NSSystem% are specified either on the command line or in the <ParameterDefaults> section:

<Applications>
   <Application>
      <ApplicationName>Stock</ApplicationName>
      <BaseDirectoryPath>%BaseDirectoryPath%</BaseDirectoryPath>
      <ApplicationDefinitionFilePath>StockADF.xml</ApplicationDefinitionFilePath>
      <Parameters>
         <Parameter>
            <Name>DBSystem</Name>
            <Value>%DBSystem%</Value>
         </Parameter>
         <Parameter>
            <Name>NSSystem</Name>
            <Value>%NSSystem%</Value>
         </Parameter>
      </Parameters>
   </Application>
   <Application>
      <ApplicationName>Horoscope</ApplicationName>
      <BaseDirectoryPath>%BaseDirectoryPath%</BaseDirectoryPath>
   <ApplicationDefinitionFilePath>HoroscopeADF.xml</ApplicationDefinitionFilePath>
      <Parameters>
         <Parameter>
            <Name>DBSystem</Name>
            <Value>%DBSystem%</Value>
         </Parameter>
         <Parameter>
            <Name>NSSystem</Name>
            <Value>%NSSystem%</Value>
         </Parameter>
      </Parameters>
   </Application>
</Applications>

See Also

Application Definition File Reference

Configuration File Reference


<Argument> Node

Contains one name/value pair for a delivery channel argument. Typical uses of these arguments are to supply a posting URL or to supply a user name and password for the delivery service.

Structure
<DeliveryChannels>
   <DeliveryChannel>
      ...
      <Arguments>

         <Argument>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <Arguments> node.
Updates | Can be added or deleted, and then applied using NSControl Update.
Node Relationships
Relationship | Element or Node
Parent Node | <Arguments> Node
Child Elements | <Name> Element (/DeliveryChannel/Arguments/Argument) <Value> Element (/DeliveryChannel/Arguments/Argument)
Remarks

Delivery channel arguments are dependent on the delivery channel protocol. Each protocol has its own requirements for arguments that must be passed to the protocol with headers. Examples of delivery channel arguments are the server name, a user name, or a password.

Notification Services does not validate delivery channel arguments when you create or update the instance.

Example

This example shows a complete <Argument> node. The delivery channel accepts a User argument. You can specify a value for %User% on the command line or in the <ParameterDefaults> node.

Note Microsoft recommends that you do not store user name and password information in any plain text files.

<Argument>
   <Name>User</Name>
   <Value>%User%</Value>
</Argument>

See Also

Application Definition File Reference

Configuration File Reference


<Arguments> Node

Contains one or more <Argument> nodes that specify a name/value pair for delivery channel arguments. Typical uses of these arguments are to supply a posting URL or to supply a user name and password for the delivery service.

Structure
<DeliveryChannels>
   <DeliveryChannel>
      ...
      <Arguments>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <DeliveryChannel> node.
Updates | Can be added or deleted, and then applied using NSControl Update.
Node Relationships
Relationship | Element or Node
Parent Node | <DeliveryChannel> Node
Child Elements | <Argument> Node
Example

This example shows three delivery channel arguments defined within the <Arguments> node. These arguments are passed to the delivery channel to configure its use for sending notifications.

Note Microsoft recommends that you do not store user name and password information in any plain text files.

<Arguments>
   <Argument>
      <Name>Server</Name>
      <Value>//Exchange10</Value>
   </Argument>
   <Argument>
      <Name>User</Name>
      <Value>%User%</Value>
   </Argument>
   <Argument>
      <Name>Pwd</Name>
      <Value>%Pwd%</Value>
   </Argument>
</Arguments>

See Also

Application Definition File Reference

Configuration File Reference


<AssemblyName> Element

Is the path and file name of the assembly that contains the protocol class.

Structure
<Protocols>
   <Protocol>
      ...
      <AssemblyName>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 260 characters.
Default Value | None.
Occurrence | Optional once per <Protocol> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Protocol> Node
Remarks

Do not use the <AssemblyName> element for built-in protocols, such as HttpExtension.

If you do not know the class and assembly names for the custom protocol, contact the developer who defined the custom protocol. The assembly name is likely the name of a DLL and the class name is the class within the assembly for the protocol.

The assembly must either be located in the <BaseDirectoryPath> folder, or you must include the relative path to the assembly.

Example

This example shows how to specify that the short message service (SMS) protocol assembly is located in the SMS.dll file:

<AssemblyName>SMS.dll</AssemblyName>

See Also

Application Definition File Reference

Configuration File Reference


<BaseDirectoryPath> Element

Is the path of the application directory. This path is used to located files specific to the application, such as XML and XSLT files.

Structure
<Applications>
   <Application>
      ...
      <BaseDirectoryPath>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 260 characters.
Default Value | None.
Occurrence | Required once per <Application> node.
Updates | Can be modified, and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Application> Node
Example

This example shows how to specify the Stock folder as the application directory:

<BaseDirectoryPath>D:\Datafiles\Stock</BaseDirectoryPath>

See Also

Application Definition File Reference

Configuration File Reference


<Build> Element

Is the build number, which is the third number in the product version string. This number is used to distinguish between builds of a release.

Structure
<Version>
   ...
   <Build>
Element Characteristics
Characteristic | Description
Data Type and Length | Non-negative integer.
Default Value | None.
Occurrence | Required once per <Version> node.
Updates | The entire version number can be incremented, and then updated using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Version> Node
Remarks

Use the build number if you want to specify which version of Notification Services the configuration file conforms to or to track changes using your own numbering scheme.

The <Version> node is optional.

When the database is first created using NSControl Create, if you do not specify a version number, 0.0.0.0 is entered into the database. For subsequent updates, the last version specified in the database is used.

A version number is always entered into the database regardless of any other changes in the application definition file (ADF) or configuration file. This action lets the administrator know that NSControl Create or NSControl Update ran.

Example

This example shows how to specify the build number for version 2.0.153.1:

<Build>153</Build>

See Also

Application Definition File Reference

Configuration File Reference


<ClassName> Element

Is the class name for the protocol, which is either a built-in protocol (such as HttpExtension) or a class defined within the assembly specified by the <AssemblyName> element. The assembly developer should provide this information.

Structure
<Protocols>
   <Protocol>
      ...
      <ClassName>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 4,000 characters.
Default Value | None.
Occurrence | Required once per <Protocol> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Protocol> Node
Example

This example shows how to specify the name of the class within the assembly where the SMS protocol is defined:

<ClassName>Protocols.SMSProtocol</ClassName>

See Also

Application Definition File Reference

Configuration File Reference


<CollationName> Element

Specifies the collation of the database, which determines how SQL Server sorts and compares data.

Structure
<Database>
   ...
   <CollationName>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 255 characters.
Default Value | None.
Occurrence | Optional once per <Database> node.
Updates | Cannot be modified.
Element Relationships
Relationship | Element or Node
Parent Node | <Database> Node
Remarks

If the collation must be different from the default collation for the instance of SQL Server, specify the collation name using this element. The default is the collation setting of the model database.

Important The instance and its application databases must all use the same collation.

For more information, see "SQL Collation Name" in SQL Server Books Online.

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

The <CollationName> values specified in each application definition file (ADF) must be the same and must match the <CollationName> values specified in the configuration file.

Example

This example shows how to specify a collation for the instance database. The collation uses the SQL_Latin1_General sort rules, code page 1251, and is case insensitive and accent sensitive:

<CollationName>SQL_Latin1_General_CP1251_CI_AS</CollationName>

See Also

Application Definition File Reference

Configuration File Reference


<CreationDate> Element

Is the date the configuration file was created.

Structure
<History>
   <CreationDate>
Element Characteristics
Characteristic | Description
Data Type and Length | date.
Default Value | None.
Occurrence | Required once per <History> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <History> Node
Remarks

The format of the XML date data type is CCYY-MM-DD with an optional time zone indicator.

The <History> node is optional, but if you use it, you must include all child elements.

History information is not stored in the database and is ignored by NSControl Update.

Example

This example shows how to specify a configuration file creation date of January 21, 2002:

<CreationDate>2002-01-21</CreationDate>

See Also

Application Definition File Reference

Configuration File Reference


<CreationTime> Element

Is the time the configuration file was created.

Structure
<History>
   ...
   <CreationTime>
Element Characteristics
Characteristic | Description
Data Type and Length | time.
Default Value | None.
Occurrence | Required once per <History> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <History> Node
Remarks

The format of the XML time data is HH:MM:SS.sss with an optional time zone indicator.

The <History> node is optional, but if you use it, you must include all child elements.

History information is not stored in the database and is ignored by NSControl Update.

Example

This example shows how to specify a configuration file creation time of 10:30 A.M.:

<CreationTime>10:30:00</CreationTime>

See Also

Application Definition File Reference

Configuration File Reference


<Database> Node

Contains elements that specify database parameters for the instance database, instance_name NSMain.

Structure
<NotificationServicesInstance>
   ...
   <Database>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <NotificationServicesInstance>.
Updates | Cannot be added or deleted after creating the instance.
Node Relationships
Relationship | Element or Node
Parent Node | <NotificationServicesInstance> Node
Child Elements | <NamedFileGroup> Node <LogFile> Node <DefaultFileGroup> Element <CollationName> Element
Remarks

If the configuration file does not contain a <Database> node, the instance database uses the model database as a template.

The specifications for each application database are contained in each application definition file (ADF).

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows a complete <Database> node. The %BaseDirectoryPath% value can be passed in from the command line or can be specified in the <ParameterDefaults> node of the configuration file:

<Database>
   <NamedFileGroup>
      <FileGroupName>Primary</FileGroupName>
      <FileSpec>
         <LogicalName>PrimaryFG</LogicalName>
         <FileName>%BaseDirectoryPath%\Primary.mdf</FileName>
         <Size>10MB</Size>
         <MaxSize>20MB</MaxSize>
         <GrowthIncrement>20%</GrowthIncrement>
      </FileSpec>
   </NamedFileGroup>
   <NamedFileGroup>
      <FileGroupName>Stock</FileGroupName>
      <FileSpec>
         <LogicalName>StockFG</LogicalName>
         <FileName>%BaseDirectoryPath%\Stock.mdf</FileName>
         <Size>20MB</Size>
         <MaxSize>40MB</MaxSize>
         <GrowthIncrement>20%</GrowthIncrement>
      </FileSpec>
   </NamedFileGroup>
   <LogFile>
      <LogicalName>StockLog</LogicalName>
      <FileName>%BaseDirectoryPath%\Stock.ldf</FileName>
      <Size>3MB</Size>
      <MaxSize>6MB</MaxSize>
      <GrowthIncrement>20%</GrowthIncrement>
   </LogFile>
   <DefaultFileGroup>Stock</DefaultFileGroup>
   <CollationName>SQL_Latin1_General_CP1251_CI_AS</CollationName>
</Database>

See Also

Application Definition File Reference

Configuration File Reference


<DefaultFileGroup> Element

Specifies one of the <NamedFileGroup> entries to be used as the default file group when creating SQL Server objects for the instance.

Structure
<Database>
   ...
   <DefaultFileGroup>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 128 characters.
Default Value | DEFAULT, which indicates the Primary filegroup.
Occurrence | Optional once per <Database> node.
Updates | Cannot be added, deleted, or modified after creating the instance.
Element Relationships
Relationship | Element or Node
Parent Node | <Database> Node
Remarks

If no filegroup is specified when creating new database objects, the objects are created in the default filegroup.

For more information about using filegroups, see "Files and Filegroups" in SQL Server Books Online.

If specified, the <DefaultFileGroup> value must be the same value as one of the <FileGroupName> values within the <NamedFileGroup> node. This is not the same as a <LogicalName> value within a <FileSpec> node.

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Examples

The following examples show two ways to specify the default filegroup.

Selecting the Primary filegroup as the default filegroup

If you want to use the Primary filegroup as the default filegroup, you do not need to specify the default. You can either omit the <DefaultFileGroup> element, or you can specify an empty element as follows:

<DefaultFileGroup/>
Selecting a specific default filegroup

The following example shows how to specify that a filegroup with the name Stock should be the default filegroup:

<DefaultFileGroup>Stock</DefaultFileGroup>

See Also

Application Definition File Reference

Configuration File Reference


<DeliveryChannel> Node

Contains elements that describe the properties of a single delivery channel instance.

Structure
<DeliveryChannels>
   <DeliveryChannel>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <DeliveryChannels> node.
Updates | Can be added or deleted, and then applied using NSControl Update.
Node Relationships
Relationship | Element or Node
Parent Node | <DeliveryChannels> Node
Child Elements | <DeliveryChannelName> Element <ProtocolName> Element (<DeliveryChannel>) <Arguments> Node
Remarks

Each <DeliveryChannel> node contains a set of elements that describe the use of a protocol to deliver notifications. You can define multiple delivery channels that use the same protocol. This is often necessary to distribute delivery among multiple delivery services.

If you are using the Simple Mail Transfer Protocol (SMTP) protocol for a delivery channel, you can define only one SMTP delivery channel. This is a limitation of the Microsoft .NET Framework SMTP implementation. If you define two SMTP delivery channels that use different SMTP servers, notifications might go to the wrong servers.

One way to avoid this problem is to use the Internet Information Services (IIS) SMTP service with the Smart Host option. First, configure the IIS SMTP service, and then configure your SMTP delivery channel as follows:

<DeliveryChannel>
   <DeliveryChannelName>EmailChannel</DeliveryChannelName>
   <ProtocolName>SMTP</ProtocolName>
</DeliveryChannel>

For more information about configuring the IIS SMTP service, see Using SMTP for Outgoing Messages in the Microsoft MSDN® Library.

Example

This example shows a complete <DeliveryChannel> node for an HTTP protocol:

<DeliveryChannel>
   <DeliveryChannelName>HTTPExtChannel</DeliveryChannelName>
   <ProtocolName>HTTP</ProtocolName>
   <Arguments>
      <Argument>
         <Name>Server</Name>
         <Value>//Server10</Value>
      </Argument>
   </Arguments>
</DeliveryChannel>

See Also

Application Definition File Reference

Configuration File Reference


<DeliveryChannelName> Element

Contains the logical name of a delivery channel.

Structure
<DeliveryChannels>
   <DeliveryChannel>
      <DeliveryChannelName>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 255 characters.
Default Value | None.
Occurrence | Required once per <DeliveryChannel> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <DeliveryChannel> Node
Remarks

The delivery channel name must be unique within the instance of SQL Server Notification Services.

Renaming a delivery channel is equivalent to deleting the old delivery channel and creating the new delivery channel. After you rename the delivery channel, update any subscriber device records that contain the old delivery channel.

Example

This example shows how to specify that the name of the delivery channel is EmailChannel:

<DeliveryChannelName>EmailChannel</DeliveryChannelName>

See Also

Application Definition File Reference

Configuration File Reference


<DeliveryChannels> Node

Contains <DeliveryChannel> nodes that describe all the delivery channels used by all applications hosted by the instance.

Structure
<NotificationServicesInstance>
   ...
   <DeliveryChannels>
Node Characteristics
Characteristic | Description
Occurrence | Required once per <NotificationServicesInstance> node.
Updates | Cannot be deleted.
Node Relationships
Relationship | Element or Node
Parent Node | <NotificationServicesInstance> Node
Child Elements | <DeliveryChannel> Node
Remarks

Delivery channels are used to deliver notifications. Each delivery channel is based on a protocol, either standard or custom, and defines an instance of the use of a protocol to deliver notifications.

Example

This example shows a complete <DeliveryChannels> node. The %User% and %Pwd% values are passed in from the command line or are specified in the <ParameterDefaults> node:

<DeliveryChannels>
   <DeliveryChannel>
      <DeliveryChannelName>EmailChannel</DeliveryChannelName>
      <ProtocolName>SMTP</ProtocolName>
      <Arguments>
         <Argument>
            <Name>Server</Name>
            <Value>//Exchange10</Value>
         </Argument>
         <Argument>
            <Name>User</Name>
            <Value>%User%</Value>
         </Argument>
         <Argument>
            <Name>Pwd</Name>
            <Value>%Pwd%</Value>
         </Argument>
      </Arguments>
   </DeliveryChannel>
</DeliveryChannels>

See Also

Application Definition File Reference

Configuration File Reference


<EncryptArguments> Element

Specifies whether the instance encrypts delivery channel and event provider arguments before storing the values in the instance and application databases. These arguments can contain user names and passwords, so encrypting these values prevents users from reading the values from the databases.

Structure
<NotificationServicesInstance>
   ...
   <EncryptArguments>
Element Characteristics
Characteristic | Description
Data Type and Length | Boolean (true or false).
Default Value | false.
Occurrence | Optional once per <NotificationServicesInstance> node.
Updates | Cannot be added, deleted, or modified after creating the instance.
Element Relationships
Relationship | Element or Node
Parent Node | <NotificationServicesInstance> Node
Remarks

The Boolean values true and false must be lowercase.

If the <EncryptArguments> value is true, delivery channel and event provider arguments are encrypted before storing them in the instance and application databases.

You must supply a key value when you run NSControl Register to create the NS$instance_name service that runs the instance, and when you run NSControl Create to create instance and application databases.

You cannot change the key value after running NSControl Create.

Example

This example shows how to specify to encrypt arguments for an instance:

<EncryptArguments>true</EncryptArguments>

See Also

Application Definition File Reference

Configuration File Reference

NSControl Create

NSControl DisplayArgumentKey

NSControl Register


<FileGroupName> Element

Is the name of a filegroup used by the instance database.

Structure
<Database>
   <NamedFileGroup>
      <FileGroupName>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 128 characters.
Default Value | None.
Occurrence | Required once per <NamedFileGroup> node.
Updates | Cannot be added, deleted, or modified after creating the instance.
Element Relationships
Relationship | Element or Node
Parent Node | <NamedFileGroup> Node
Remarks

At least one file group must use the name Primary.

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows how to give a filegroup the name Stock:

<FileGroupName>Stock</FileGroupName>

See Also

Application Definition File Reference

Configuration File Reference


<FileName> Element (<FileSpec>)

Is the path and file name used by the operating system when it creates the database file.

Structure
<Database>
   <NamedFileGroup>
      ...
      <FileSpec>
         ...
         <FileName>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 260 characters.
Default Value | None.
Occurrence | Required once per <FileSpec> node.
Updates | Cannot be added, deleted, or modified after creating the instance.
Element Relationships
Relationship | Element or Node
Parent Node | <FileSpec> Node
Remarks

The path portion of the file name must specify a folder accessible by the instance of SQL Server and cannot specify a folder in a compressed file system.

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows how to specify that the database file is stored in a folder specified by the %BaseDirectoryPath% parameter with the name Stock.mdf:

<FileName>%BaseDirectoryPath%\Stock.mdf</FileName>

See Also

Application Definition File Reference

Configuration File Reference


<FileName> Element (<LogFile>)

Is the path and file name used by the operating system when it creates a log file.

Structure
<Database>
   ...
   <LogFile>
      ...
      <FileName>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 260 characters.
Default Value | None.
Occurrence | Required once per <LogFile> node.
Updates | Cannot be added, deleted, or modified after creating the instance.
Element Relationships
Relationship | Element or Node
Parent Node | Defining a <LogFile> Node
Remarks

The path portion of the file name must specify a folder accessible by the instance of SQL Server and cannot specify a folder in a compressed file system.

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows how to specify that the log file is stored in a folder specified by the %BaseDirectoryPath% parameter with the name Stock.ldf:

<FileName>%BaseDirectoryPath%\Stock.ldf</FileName>

See Also

Application Definition File Reference

Configuration File Reference


<FileSpec> Node

Contains elements that describe database file properties.

Structure
<Database>
   <NamedFileGroup>
      ...
      <FileSpec>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <NamedFileGroup> node.
Updates | Cannot be added, deleted, or modified after creating the instance.
Node Relationships
Relationship | Element or Node
Parent Node | <NamedFileGroup> Node
Child Elements | <LogicalName> Element (<FileSpec>) <FileName> Element (<FileSpec>) <Size> Element (<FileSpec>) <MaxSize> Element (<FileSpec>) <GrowthIncrement> Element (<FileSpec>)
Remarks

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows a complete <FileSpec> node:

<FileSpec>
   <LogicalName>StockFG</LogicalName>
   <FileName>C:\DataFiles\Stock.mdf</FileName>
   <Size>20MB</Size>
   <MaxSize>40MB</MaxSize>
   <GrowthIncrement>20%</GrowthIncrement>
</FileSpec>

See Also

Application Definition File Reference

Configuration File Reference


<GrowthIncrement> Element (<FileSpec>)

Is the amount of space added to the database file each time new space is needed.

Structure
<Database>
   <NamedFileGroup>
      ...
      <FileSpec>
         ...
         <GrowthIncrement>
Element Characteristics
Characteristic | Description
Data Type and Length | string.
Default Value | Default growth increment for the SQL Server instance, typically 10 percent.
Occurrence | Optional once per <FileSpec> node.
Updates | Cannot be added, deleted, or modified after creating the instance.
Element Relationships
Relationship | Element or Node
Parent Node | <FileSpec> Node
Remarks

Specify a whole number; do not include a decimal. The value can be specified in megabytes (MB), kilobytes (KB), gigabytes (GB), terabytes (TB), or as a percentage (%). If a number is specified without an MB, KB, or % suffix, the default is MB. When % is specified, the growth increment size is the specified percentage of the size of the file at the time the increment occurs.

The minimum growth value is 64 KB. The size specified is rounded to the nearest 64 KB. A value of 0 indicates no growth.

For more information see "CREATE DATABASE" in SQL Server Books Online.

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows how to specify a growth increment of 20 percent. The database file grows by 20 percent each time the database runs out of space, until the file reaches the maximum size specified by the <MaxSize> element:

<GrowthIncrement>20%</GrowthIncrement>

See Also

Application Definition File Reference

Configuration File Reference


<GrowthIncrement> Element (<LogFile>)

Is the amount of space added to the log file each time new space is needed.

Structure
<Database>
   ...
   <LogFile>
      ...
      <GrowthIncrement>
Element Characteristics
Characteristic | Description
Data Type and Length | string.
Default Value | Default growth increment for the SQL Server instance, typically 10 percent.
Occurrence | Optional once per <LogFile> node.
Updates | Cannot be added, deleted, or modified after creating the instance.
Element Relationships
Relationship | Element or Node
Parent Node | <LogFile> Node
Remarks

Specify a whole number; do not include a decimal. The value can be specified in megabytes (MB), kilobytes (KB), gigabytes (GB), terabytes (TB), or as a percentage (%). If a number is specified without an MB, KB, or % suffix, the default is MB. When % is specified, the growth increment size is the specified percentage of the size of the file at the time the increment occurs.

The minimum growth value is 64 KB. The size specified is rounded to the nearest 64 KB. A value of 0 indicates no growth.

For more information see "CREATE DATABASE" in SQL Server Books Online.

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows how to specify a growth increment of 15 percent. The log file grows by 15 percent each time the log runs out of space, until the file reaches the maximum size specified by the <MaxSize> element:

<GrowthIncrement>15%</GrowthIncrement>

See Also

Application Definition File Reference

Configuration File Reference


<History> Node

Contains elements that provide historical information about the configuration file.

Structure
<NotificationServicesInstance>
   ...
   <History>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <NotificationServicesInstance> node.
Updates | Can be added or deleted, and then applied using NSControl Update.
Node Relationships
Relationship | Element or Node
Parent Node | <NotificationServicesInstance> Node
Child Elements | <CreationDate> Element <CreationTime> Element <LastModifiedDate> Element <LastModifiedTime> Element
Remarks

The <History> node is intended to help developers or administrators keep track of the changes to the configuration file, but the use of this section is up to the file owner.

The <History> node is not used by or validated by SQL Server Notification Services. If you do not use the history information, omit the entire section from the configuration file or use empty tags for child elements.

Example

This example shows a complete <History> node:

<History>
   <CreationDate>2002-01-21</CreationDate>
   <CreationTime>10:30:00</CreationTime>
   <LastModifiedDate>2002-04-28</LastModifiedDate>
   <LastModifiedTime>18:30:00</LastModifiedTime>
</History>

See Also

Application Definition File Reference

Configuration File Reference


<InstanceName> Element

Is the logical name for the instance of SQL Server Notification Services.

Structure
<NotificationServicesInstance>
   ...
   <InstanceName>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 122 characters.
Default Value | None.
Occurrence | Required once per <NotificationServicesInstance> node.
Updates | Cannot be modified after creating the instance.
Element Relationships
Relationship | Element or Node
Parent Node | <NotificationServicesInstance> Node
Remarks

Each instance on a computer must have a unique name. Do not rely on case to make an instance name unique. For example, MyInstance and myinstance are not considered unique names. The commands used to create and register instances are not case sensitive.

The <InstanceName> element accepts up to 255 characters. However, this name concatenated with "NSMain" is the instance database name, and database names are limited to 128 characters. Also, application database names use a concatenation of application and instance name, so limit <InstanceName> to a length that does not violate object naming rules.

Because this name is used to create SQL Server objects, follow the SQL Server rules for regular identifiers. Do not use SQL Server reserved keywords or special characters. For more information, see "Using Identifiers" in SQL Server Books Online.

Example

This example shows how to specify an instance name of StockInstance:

<InstanceName>StockInstance</InstanceName>

See Also

Application Definition File Reference

Configuration File Reference


<LastModifiedDate> Element

Is the date the configuration file was last modified.

Structure
<History>
   ...
   <LastModifiedDate>
Element Characteristics
Characteristic | Description
Data Type and Length | date.
Default Value | None.
Occurrence | Required once per <History> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <History> Node
Remarks

The format of the XML date data type is CCYY-MM-DD with an optional time zone indicator.

The <History> node is optional, but if you do use it, you must include all child elements.

History information is not stored in the database and is ignored by NSControl Update.

Example

This example shows how to specify that the configuration file was last edited on April 29, 2002:

<LastModifiedDate>2002-04-29</LastModifiedDate>

See Also

Application Definition File Reference

Configuration File Reference


<LastModifiedTime> Element

Is the time the configuration file was last modified.

Structure
<History>
   ...
   <LastModifiedDate>
Element Characteristics
Characteristic | Description
Data Type and Length | time.
Default Value | None.
Occurrence | Required once per <History> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <History> Node
Remarks

The format of the XML time data is HH:MM:SS.sss with an optional time zone indicator.

The <History> node is optional, but if you do use it, you must include all child elements.

History information is not stored in the database and is ignored by NSControl Update.

Example

This example shows how to specify that the configuration file was last edited at 6:30 P.M.:

<LastModifiedTime>18:30:00</LastModifiedTime>

See Also

Application Definition File Reference

Configuration File Reference


<LogFile> Node

Specifies properties of a log file.

Structure
<Database>
   ...
   <LogFile>
Node Characteristics
Characteristic | Description
Occurrence | Optional once or more per <Database> node.
Updates | Cannot be added or deleted after creating the instance.
Node Relationships
Relationship | Element or Node
Parent Node | <Database> Node
Child Elements | <LogicalName> Element (<LogFile>) <FileName> Element (<LogFile>) <Size> Element (<LogFile>) <MaxSize> Element (<LogFile>) <GrowthIncrement> Element (<LogFile>)
Remarks

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows a complete <LogFile> node:

<LogFile>
   <LogicalName>StockLog</LogicalName>
   <FileName>%BaseDirectoryPath%\Stock.ldf</FileName>
   <Size>3MB</Size>
   <MaxSize>6MB</MaxSize>
   <GrowthIncrement>20%</GrowthIncrement>
</LogFile>

See Also

Application Definition File Reference

Configuration File Reference


<LogicalName> Element (<FileSpec>)

Is the name used to refer to the database file.

Structure
<Database>
   <NamedFileGroup>
      ...
      <FileSpec>
         <LogicalName>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 260 characters.
Default Value | None.
Occurrence | Required once per <FileSpec> node.
Updates | Cannot be modified after creating the instance.
Element Relationships
Relationship | Element or Node
Parent Node | <FileSpec> Node
Remarks

The <LogicalName> element must be unique in the database and must conform to the rules for identifiers.

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows how to specify that the logical name of a database file is StockFG:

<LogicalName>StockFG</LogicalName>

See Also

Application Definition File Reference

Configuration File Reference


<LogicalName> Element (<LogFile>)

Is the name used to refer to the log file.

Structure
<Database>
   ...
   <LogFile>
      <LogicalName>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 260 characters.
Default Value | None.
Occurrence | Required once per <LogFile> node.
Updates | Cannot be modified after creating the instance.
Element Relationships
Relationship | Element or Node
Parent Node | <LogFile> Node
Remarks

The <LogicalName> element must be unique in the database and must conform to the rules for identifiers.

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows how to specify that the logical name of a log file is StockLog:

<LogicalName>StockLog</LogicalName>

See Also

Application Definition File Reference

Configuration File Reference


<Major> Element

Is the major version number, which is the first number in the product version string.

Structure
<Version>
   <Major>
Element Characteristics
Characteristic | Description
Data Type and Length | Non-negative integer.
Default Value | None.
Occurrence | Required once per <Version> node.
Updates | The entire version number can be incremented, and then updated using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Version> Node
Remarks

Use the major version number if you want to specify which version of Notification Services the configuration file conforms to, or to track changes using your own numbering scheme.

The entire <Version> node is optional.

When the database is first created using NSControl Create, if you do not specify a version number, 0.0.0.0 is entered into the database. For subsequent updates, the last version specified in the database is used.

A version number is always entered into the database regardless of any other changes in the application definition file (ADF) or configuration file. This action lets the administrator know that NSControl Create or NSControl Update ran.

Example

This example shows how to specify the major version number for version 2.0.153.1:

<Major>2</Major>

See Also

Application Definition File Reference

Configuration File Reference


<MaxSize> Element (<FileSpec>)

Is the maximum size to which the database file can grow.

Structure
<Database>
   <NamedFileGroup>
      ...
      <FileSpec>
         ...
         <MaxSize>
Element Characteristics
Characteristic | Description
Data Type and Length | string.
Default Value | Unrestricted file growth.
Occurrence | Optional once per <FileSpec> node.
Updates | Cannot be modified after creating the instance.
Element Relationships
Relationship | Element or Node
Parent Node | <FileSpec> Node
Remarks

You can use the kilobyte (KB), megabyte (MB), gigabyte (GB), or terabyte (TB) suffix. The default is MB. Specify a whole number; do not include a decimal.

If <MaxSize> is not specified, the file grows until the disk is full.

For more information, see "CREATE DATABASE" in SQL Server Books Online.

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows how to specify a maximum database file size of 20 MB:

<MaxSize>20MB</MaxSize>

See Also

Application Definition File Reference

Configuration File Reference


<MaxSize> Element (<LogFile>)

Is the maximum size to which the log file can grow.

Structure
<Database>
   ...
   <LogFile>
      ...
      <MaxSize>
Element Characteristics
Characteristic | Description
Data Type and Length | string.
Default Value | Unrestricted file growth.
Occurrence | Optional once per <LogFile> node.
Updates | Cannot be modified after creating the instance.
Element Relationships
Relationship | Element or Node
Parent Node | <LogFile> Node
Remarks

You can use the kilobyte (KB), megabyte (MB), gigabyte (GB), or terabyte (TB) suffix. The default is MB. Specify a whole number; do not include a decimal.

If <MaxSize> is not specified, the file grows until the disk is full.

For more information, see "CREATE DATABASE" in SQL Server Books Online.

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows how to specify a maximum log file size of 6 MB:

<MaxSize>6MB</MaxSize>

See Also

Application Definition File Reference

Configuration File Reference


<Minor> Element

Is the minor version number, which is the second number in the product version string.

Structure
<Version>
   ...
   <Minor>
Element Characteristics
Characteristic | Description
Data Type and Length | Non-negative integer.
Default Value | None.
Occurrence | Required once per <Version> node.
Updates | The entire version number can be incremented, and then updated using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Version> Node
Remarks

When the database is first created using NSControl Create, if you do not specify a version number, 0.0.0.0 is entered into the database. For subsequent updates, the last version specified in the database is used.

A version number is always entered into the database regardless of any other changes in the application definition file (ADF) or configuration file. This action lets the administrator know that NSControl Create or NSControl Update ran.

Example

This example shows how to specify the minor version number for version 2.0.153.1:

<Minor>0</Minor>

See Also

Application Definition File Reference

Configuration File Reference


<Name> Element (/Application/Parameters/Parameter)

Is the name of a parameter to be passed to the application definition file (ADF).

Structure
<Applications>
   <Application>
      ...
      <Parameters>
         <Parameter>
            <Name>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 255 characters.
Default Value | None.
Occurrence | Required once per <Parameter> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Parameter> Node (/Application/Parameters)
Remarks

The name of the parameter must match the name of a parameter specified in the ADF.

Example

This example shows how to specify a value for the %DBSystem% parameter in the ADF. MyDBServer, specified by the <Value> element, is substituted for %DBSystem% throughout the ADF:

<Parameter>
   <Name>DBSystem</Name>
   <Value>MyDBServer</Value>
</Parameter>

See Also

Application Definition File Reference

Configuration File Reference


<Name> Element (/DeliveryChannel/Arguments/Argument)

Is the name of an argument to be passed to the delivery channel.

Structure
<DeliveryChannels>
   <DeliveryChannel>
      ...
      <Arguments>
         <Argument>
            <Name>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 255 characters.
Default Value | None.
Occurrence | Required once per <Argument> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Argument> Node
Remarks

The name of an argument is determined by the delivery protocol specifications.

Example

This example shows how to specify an argument for a delivery channel. The argument has the name Server and the value \\DeliveryServer10:

<Parameter>
   <Name>Server</Name>
   <Value>\\DeliveryServer10</Value>
</Parameter>

See Also

Application Definition File Reference

Configuration File Reference


<Name> Element (/ParameterDefaults/Parameter)

Is the name of a parameter in the configuration file.

Structure
<ParameterDefaults>
   <Parameter>
      <Name>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 255 characters.
Default Value | None.
Occurrence | Required once per <Parameter> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Parameter> Node (<ParameterDefaults>)
Remarks

This name must match the name of the parameter used in the configuration file, but does not start or end with the % character. The parameter to be replaced must start and end with the % character.

Example

This example shows how to specify a default parameter value for the parameter named BaseDirPath. The NSControl utility substitutes "C:\NS\Applications" wherever %BaseDirPath% appears in the configuration file, unless you specify another value on the command line:

<Parameter>
   <Name>BaseDirPath</Name>
   <Value>C:\NS\Applications</Value>
</Parameter>

See Also

Application Definition File Reference

Configuration File Reference


<NamedFileGroup> Node

Specifies that the disk files used to store the data portions of the database (data files) are defined explicitly by the child elements.

Structure
<Database>
   <NamedFileGroup>
Node Characteristics
Characteristic | Description
Occurrence | Optional once or more per <Database> node.
Updates | Cannot be added or deleted after creating the instance.
Node Relationships
Relationship | Element or Node
Parent Node | <Database> Node
Child Elements | <FileGroupName> Element <FileSpec> Node
Remarks

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows a complete <NamedFileGroup> node that specifies properties of the Primary filegroup:

<NamedFileGroup>
   <FileGroupName>Primary</FileGroupName>
   <FileSpec>
      <LogicalName>PrimaryFG</LogicalName>
      <FileName>%BaseDirectoryPath%\Primary.mdf</FileName>
      <Size>10MB</Size>
      <MaxSize>20MB</MaxSize>
      <GrowthIncrement>20%</GrowthIncrement>
   </FileSpec>
</NamedFileGroup>

See Also

Application Definition File Reference

Configuration File Reference


<NotificationServicesInstance> Node

Is the top node of the configuration file.

Structure
<NotificationServicesInstance xmlns:ns="http://www.microsoft.com/MicrosoftNotificationServices/ConfigurationFileSchema"
xmlns="http://www.microsoft.com/MicrosoftNotificationServices/ConfigurationFileSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.microsoft.com/MicrosoftNotificationServices/ConfigurationFileSchema">
Node Characteristics
Characteristic | Description
Occurrence | Required once per configuration file.
Updates | Cannot be added or deleted.
Node Relationships
Relationship | Element or Node
Parent Node | None
Child Elements | <ParameterDefaults> Node <Version> Node <History> Node <InstanceName> Element <SqlServerSystem> Element <Database> Node <Applications> Node <Protocols> Node <DeliveryChannels> Node
Remarks

The <NotificationServicesInstance> node follows the XML declaration (if the declaration is used) and contains namespace references. For more information about namespaces, see Namespaces in an XML Document.

See Also

Application Definition File Reference

Configuration File Reference


<Parameter> Node (/Application/Parameters)

Contains one name/value pair that passes a value to a parameter in the application definition file (ADF).

Structure
<Applications>
   <Application>
      ...
      <Parameters>
         <Parameter>
Node Characteristics
Characteristic | Description
Occurrence | Optional once or more per <Application> node.
Updates | Can be added or deleted, and then applied using NSControl Update.
Node Relationships
Relationship | Element or Node
Parent Node | <Parameters> Node
Child Elements | <Name> Element (/Application/Parameters/Parameter) <Value> Element (/Application/Parameters/Parameter)
Remarks

Parameters in the <Application> node are passed to the ADF when the instance is created or updated.

The parameter overrides any default settings specified in the ADF.

Example

This example shows how to specify a parameter for the ADF with the name DBSystem. MyDBServer, specified by the <Value> element, is substituted for %DBSystem% in the ADF:

<Parameter>
   <Name>DBSystem</Name>
   <Value>MyDBServer</Value>
</Parameter>

See Also

Application Definition File Reference

Configuration File Reference


<Parameter> Node (<ParameterDefaults>)

Contains one name/value pair that provides a default value for a parameter in the configuration file.

Structure
<ParameterDefaults>
   <Parameter>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <ParameterDefaults> node.
Updates | Can be added or deleted, and then applied using NSControl Update.
Node Relationships
Relationship | Element or Node
Parent Node | <ParameterDefaults> Node
Child Elements | <Name> Element (/ParameterDefaults/Parameter) <Value> Element (/ParameterDefaults/Parameter)
Remarks

The parameter name and value can be provided on the command line, which overrides any defaults specified in this section.

If you do not need to specify default values for parameters, omit the entire section from the configuration file or use empty tags for the child elements.

Example

This example shows a parameter node for the <ParameterDefaults> node. These parameters provide default values for parameters within the configuration file:

   <Parameter>
      <Name>BaseDirPath</Name>
      <Value>C:\NS\Apps</Value>
   </Parameter>

See Also

Application Definition File Reference

Configuration File Reference


<ParameterDefaults> Node

Contains one or more <Parameter> nodes, which provide default values for parameters within the configuration file.

Structure
<NotificationServicesInstance>
   <ParameterDefaults>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <NotificationServicesInstance> node.
Updates | Can be added and deleted after creating the instance, and then applied using NSControl Update.
Node Relationships
Relationship | Element or Node
Parent Node | <NotificationServicesInstance> Node
Child Elements | <Parameter> Node (<ParameterDefaults>)
Remarks

The parameter name and value can be provided on the command line, which overrides any defaults specified in this section.

Example

This example shows a complete <ParameterDefaults> node with two default values specified:

<ParameterDefaults>
   <Parameter>
      <Name>BaseDirPath</Name>
      <Value>C:\NS\Apps</Value>
   </Parameter>
   <Parameter>
      <Name>DBSystem</Name>
      <Value>SQL10</Value>
   </Parameter>
</ParameterDefaults>

See Also

Application Definition File Reference

Configuration File Reference


<Parameters> Node

Contains an application-specific set of parameters. The parameters are passed to the application definition file (ADF).

Structure
<Applications>
   <Application>
      ...
      <Parameters>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <Application> node.
Updates | Can be added or deleted, and then applied using NSControl Update.
Node Relationships
Relationship | Element or Node
Parent Node | <Application> Node
Child Elements | <Name> Element (/Application/Parameters/Parameter) <Value> Element (/Application/Parameters/Parameter)
Remarks

These parameters are passed to the ADF when you create or update the instance by using the NSControl utility.

Example

This example shows a complete <Parameters> node. The parameter name and value are passed to the ADF:

<Parameters>
   <Parameter>
      <Name>DBSystem</Name>
      <Value>YourDBServer</Value>
   </Parameter>
</Parameters>

See Also

Application Definition File Reference

Configuration File Reference


<Protocol> Node

Contains elements that describe a single custom delivery protocol used by one or more applications.

Structure
<Protocols>
   <Protocol>
Node Characteristics
Characteristic | Description
Occurrence | Required once or more per <Protocols> node.
Updates | Can be added or deleted, and then applied using NSControl Update.
Node Relationships
Relationship | Element or Node
Parent Node | <Protocols> Node
Child Elements | <ProtocolName> Element <ClassName> Element <AssemblyName> Element
Example

This example shows a complete <Protocol> node that defines the custom SMS protocol:

<Protocol>
   <ProtocolName>SMS</ProtocolName>
   <ClassName>Protocols.SMSProtocol</ClassName>
   <AssemblyName>SMS.dll</AssemblyName>
</Protocol>

See Also

Application Definition File Reference

Configuration File Reference


<ProtocolName> Element (<DeliveryChannel>)

Contains the name of the protocol, either standard or custom, used by the delivery channel.

Structure
<DeliveryChannels>
   <DeliveryChannel>
      ...
      <ProtocolName>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 255 characters.
Default Value | None.
Occurrence | Required once per <DeliveryChannel> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <DeliveryChannel> Node
Remarks

The protocol name links a delivery protocol to a delivery channel in the configuration file.

Each protocol can be assigned to one or more delivery channels. If a single protocol is assigned to more than one delivery channel, there are multiple instances of the delivery channel for the protocol.

Example

This example shows how to specify the custom protocol SMS for use by the delivery channel:

<ProtocolName>SMS</ProtocolName>

See Also

Application Definition File Reference

Configuration File Reference


<ProtocolName> Element (<Protocol>)

Contains the name of a custom protocol, which is also specified in the delivery channels sections of both the configuration file and the application definition file (ADF).

Structure
<Protocols>
   <Protocol>
      <ProtocolName>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 255 characters.
Default Value | None.
Occurrence | Required once per <Protocol> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Protocol> Node
Example

This example shows how to give a custom protocol the name SMS:

<ProtocolName>SMS</ProtocolName>

See Also

Application Definition File Reference

Configuration File Reference


<Protocols> Node

Contains information about any custom protocols used to deliver messages.

Structure
<NotificationServicesInstance>
   ...
   <Protocols>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <NotificationServicesInstance> node.
Updates | Can be added or deleted, and then updated using NSControl Update.
Node Relationships
Relationship | Element or Node
Parent Node | <NotificationServicesInstance> Node
Child Elements | <Protocol> Node
Remarks

Include the <Protocols> node only if custom protocols are used by any applications. If using only standard protocols, omit the entire section or use empty tags.

Example

This example shows a complete <Protocols> node that contains the definition of one custom protocol:

<Protocols>
   <Protocol>
      <ProtocolName>SMS</ProtocolName>
      <ClassName>Protocols.SMSProtocol</ClassName>
      <AssemblyName>SMS.dll</AssemblyName>
   </Protocol>
</Protocols>

See Also

Application Definition File Reference

Configuration File Reference


<Revision> Element

Is the revision number, which is the fourth number in the product version string.

Structure
<Version>
   ...
   <Revision>
Element Characteristics
Characteristic | Description
Data Type and Length | Non-negative integer.
Default Value | None.
Occurrence | Required once per <Version> node.
Updates | The entire version number can be incremented, and then updated using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Version> Node
Remarks

When the database is first created using NSControl Create, if you do not specify a version number, 0.0.0.0 is entered into the database. For subsequent updates, the last version specified in the database is used.

A version number is always entered into the database regardless of any other changes in the application definition file (ADF) or configuration file. This action lets the administrator know that NSControl Create or NSControl Update ran.

Example

This example shows how to specify the revision number for version 2.0.153.1:

<Revision>1</Revision>

See Also

Application Definition File Reference

Configuration File Reference


<Size> Element (<FileSpec>)

Is the initial size of the database file.

Structure
<Database>
   <NamedFileGroup>
      <FileGroupName>
      <FileSpec>
         ...
         <Size>
Element Characteristics
Characteristic | Description
Data Type and Length | string.
Default Value | Default file size for the SQL Server instance, which is typically 1 MB.
Occurrence | Optional once per <FileGroupName> node.
Updates | You can update <Size> to document any changes you made to the instance database manually, but changing this element has no effect on the instance database.
Element Relationships
Relationship | Element or Node
Parent Node | <FileSpec> Node
Remarks

You can use the kilobyte (KB), megabyte (MB), gigabyte (GB), or terabyte (TB) suffix. The default is MB. Specify a whole number; do not include a decimal.

The minimum value is 512 KB. The default size is 1 MB. The size specified for the Primary file must be at least as large as the Primary file of the model database.

For more information see "CREATE DATABASE" in SQL Server Books Online.

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows how to define the initial size of a database file as 10 MB:

<Size>10MB</Size>

See Also

Application Definition File Reference

Configuration File Reference


<Size> Element (<LogFile>)

Is the initial size of the log file.

Structure
<Database>
   ...
   <LogFile>
      ...
      <Size>
Element Characteristics
Characteristic | Description
Data Type and Length | string.
Default Value | Default file size for the SQL Server instance, which is typically 1 MB.
Occurrence | Optional once per <LogFile> node.
Updates | You can update <Size> to document any changes you made to the log file manually, but changing this element has no effect on the log file.
Element Relationships
Relationship | Element or Node
Parent Node | <LogFile> Node
Remarks

You can use the kilobyte (KB), megabyte (MB), gigabyte (GB), or terabyte (TB) suffix. The default is MB. Specify a whole number; do not include a decimal.

The minimum value for <Size> is 512 KB. The default size is 1 MB.

For more information, see "CREATE DATABASE" in SQL Server Books Online.

If you need to change database attributes represented by any child elements of the <Database> node, use the SQL Server tools, such as SQL Server Enterprise Manager.

Example

This example shows how to define the initial size of a log file as 3 MB:

<Size>3MB</Size>

See Also

Application Definition File Reference

Configuration File Reference


<SqlServerSystem> Element

Contains the name of a SQL Server instance that hosts the instance database and its application databases.

Structure
<NotificationServicesInstance>
   ...
   <SqlServerSystem>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 1 and 255 characters.
Default Value | None.
Occurrence | Required once per <NotificationServicesInstance> node.
Updates | Cannot be modified after creating the instance.
Element Relationships
Relationship | Element or Node
Parent Node | <NotificationServicesInstance> Node
Remarks

The name is specified in one of the following ways:

  • If Notification Services uses the default instance of SQL Server on the local computer or another computer, use the computer name. For example, if the network name of the computer is DBServer01, use DBServer01. IP addresses are not supported.
  • If Notification Services uses a named instance of SQL Server, use the computer name followed by a backslash and the instance name. For example, if the computer name is DbServer01 and the instance of SQL Server is named NSData, use DbServer01\NSData as the value.
Example

This example shows how to specify that the database server is DBServer01:

<SqlServerSystem>DBServer01</SqlServerSystem>

See Also

Application Definition File Reference

Configuration File Reference


<Value> Element (/Application/Parameters/Parameter)

Contains the value of a parameter to be passed to the application definition file (ADF).

Structure
<Applications>
   <Application>
      ...
      <Parameters>
         <Parameter>
            ...
            <Value>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 0 and 4,000 characters.
Default Value | None.
Occurrence | Required once per <Parameter> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Parameter> Node (/Application/Parameters)
Example

This example shows how to specify a value for the DBSystem parameter in the ADF. DBServer01, specified by the <Value> element, is substituted for %DBSystem% in the ADF:

<Parameter>
   <Name>DBSystem</Name>
   <Value>DBServer01</Value>
</Parameter>

See Also

Application Definition File Reference

Configuration File Reference


<Value> Element (/DeliveryChannel/Arguments/Argument)

Contains the value of an argument to be passed to the delivery channel.

Structure
<DeliveryChannels>
   <DeliveryChannel>
      ...
      <Arguments>
         <Argument>
            ...
            <Value>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 0 and 4,000 characters.
Default Value | None.
Occurrence | Required once per <Argument> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Argument> Node
Example

This example shows how to specify the value DeliveryServer10 for the Server argument:

<Argument>
   <Name>Server</Name>
   <Value>DeliveryServer10</Value>
</Argument>

See Also

Application Definition File Reference

Configuration File Reference


<Value> Element (/ParameterDefaults/Parameter)

Contains the value of a parameter used in the configuration file.

Structure
<ParameterDefaults>
   <Parameter>
      ...
      <Value>
Element Characteristics
Characteristic | Description
Data Type and Length | string of length between 0 and 4,000 characters.
Default Value | None.
Occurrence | Required once per <Parameter> node.
Updates | Can be modified and then applied using NSControl Update.
Element Relationships
Relationship | Element or Node
Parent Node | <Parameter> Node (<ParameterDefaults>)
Example

This example shows how to specify a default value of C:\NS\Apps for the parameter BaseDirPath:

   <Parameter>
      <Name>BaseDirPath</Name>
      <Value>C:\NS\Apps</Value>
   </Parameter>

See Also

Application Definition File Reference

Configuration File Reference


<Version> Node

Contains information about the version of Notification Services used by the instance.

Structure
<NotificationServicesInstance>
   ...
   <Version>
Node Characteristics
Characteristic | Description
Occurrence | Optional once per <NotificationServicesInstance> node.
Updates | Can be added or deleted, and then applied using NSControl Update.
Node Relationships
Relationship | Element or Node
Parent Node | <NotificationServicesInstance> Node
Child Elements | <Major> Element <Minor> Element <Build> Element <Revision> Element
Remarks

When the database is first created using NSControl Create, if you do not specify a version number, 0.0.0.0 is entered into the database. For subsequent updates, the last version specified in the database is used.

A version number is always entered into the database regardless of any other changes in the application definition file (ADF) or configuration file. This action lets the administrator know that NSControl Create or NSControl Update ran.

The Notification Services version number can be obtained by looking at the installation path for a particular installation of Notification Services.

You do not need to specify version numbers, but if the file's schema does not match the schema required by the version of Notification Services, the instance is not created or updated. The configuration file schema might change between versions, so using version information can help keep configuration file versions organized.

If you do not specify the version information, omit the entire section from the configuration file or use empty tags for the child elements.

Example

This example shows a complete version node for version 2.0.153.1:

<Version>
   <Major>2</Major>
   <Minor>0</Minor>
   <Build>153</Build>
   <Revision>1</Revision>
</Version>

See Also

Application Definition File Reference

Configuration File Reference


Notification Services Object Model Reference

This section documents the classes and interfaces of the Notification Services object model.

The following graphic illustrates the Notification Services API hierarchy.

See Also

Microsoft.SqlServer.NotificationServices Namespace


Microsoft.SqlServer.NotificationServices

 SQL Server Notification Services Books Online

Microsoft.SqlServer.NotificationServices Namespace

The Microsoft.SqlServer.NotificationServices namespace contains all of the Notification Services classes and interfaces. This includes:

  • All classes relating to Notification Services instances and applications.
  • All classes relating to creating and maintaining subscribers, subscriber devices, and subscriptions.
  • All classes relating to submitting events to the Notification Services system.
  • All interfaces used in developing custom Notification Services components.

This namespace is provided by the Microsoft.SqlServer.NotificationServices.dll assembly, which installs by default to C:\Program Files\Microsoft Notification Services\VersionNumber\bin. To use this namespace in the Microsoft Visual Studio® .NET IDE, you must browse for the Microsoft.SqlServer.NotificationServices.dll and add it to the references for the project.

Classes
ApplicationEnumerationClass | Represents the collection of Notification Services applications in a specified Notification Services instance. Can be used to return an NSApplication object.
DeliveryChannel Class | Represents a Notification Services delivery channel.
DeliveryChannelEnumeration Class | Represents the collection of delivery channels in a specified Notification Services instance. Can be used to return a DeliveryChannel object.
Event Class | Encapsulates a single event, which is then submitted to the Notification Services application through an EventCollector object.
EventClass Class | Represents any event class defined in an application definition file (ADF).
EventClassEnumeration Class | Represents the collection of event classes in a specified Notification Services application.
EventCollector Class | Accepts events as Event objects and submits them to the application.
EventLoader Class | Submits XML document event data to the application.
InstanceEnumeration Class | Represents the collection of local Notification Services instances. Can be used to return an NSInstanceDescription object.
NotificationHeaders Class | Used by the distributor to provide notification routing and delivery information to the delivery protocol component.
NotificationStatus Class | Used by a delivery protocol to provide notification delivery status information back to the distributor.
NSApplication Class | Represents a specified Notification Services application.
NSInstance Class | Represents a specified Notification Services instance.
NSInstanceDescription Class | Provides descriptive information about a specified Notification Services instance.
RecipientInfo Class | Provides descriptive information about a recipient.
Subscriber Class | Represents a specified Notification Services subscriber.
SubscriberDevice Class | Represents a specified Notification Services subscriber device.
SubscriberDeviceEnumeration Class | Represents the collection of Notification Services subscriber devices in a specified Notification Services instance. Can be used to return a SubscriberDevice object.
SubscriberEnumeration Class | Represents the collection of Notification Services subscribers in a specified Notification Services instance. Can be used to return a Subscriber object.
SubscriberLocale Class | Represents a Notification Services subscriber locale.
SubscriberLocaleEnumeration Class | Represents the collection of Notification Services subscriber locales. Can be used to return a SubscriberLocale object.
Subscription Class | Represents a specified Notification Services subscription.
SubscriptionClass Class | Represents any subscription class defined in an ADF.
SubscriptionClassEnumeration Class | Represents the collection of subscription classes in a specified Notification Services application.
SubscriptionEnumeration Class | Represents the collection of Notification Services subscriptions in a specified Notification Services application. Can be used to return a Subscription object.
TimeZone Class | Represents a time zone.
TimeZoneEnumeration Class | Represents the collection of time zones. Can be used to return a TimeZone object.
Interfaces
IContentFormatter Interface | Provides a framework for developing a content formatter.
IDeliveryProtocol Interface | Provides a framework for developing a delivery protocol.
IEventProvider Interface | Provides a framework for developing a hosted continuous event provider.
IHttpProtocolProvider | Provides a framework for developing an HTTP delivery protocol.
IScheduledEventProvider Interface | Provides a framework for developing a hosted scheduled event provider.
Delegates
NotificationStatusCallback | Provides a means for a delivery protocol to report notification delivery information back to the system.
StopHandler | Provides a means for an event provider to request termination.


ApplicationEnumeration Class

Represents the collection of Notification Services applications in a given Notification Services instance.

For a list of all members of this type, see ApplicationEnumeration Members.

System.Object

Microsoft.SqlServer.NotificationServices.ApplicationEnumeration
[Visual Basic .NET]
NonInheritable Public Class ApplicationEnumeration
Implements IApplicationEnumeration, IEnumerable
[C#]
public sealed class ApplicationEnumeration : IApplicationEnumeration, IEnumerable
[C++]
public __gc __sealed class ApplicationEnumeration : public IApplicationEnumeration, IEnumerable
[JScript]
public class ApplicationEnumeration implements IApplicationEnumeration, IEnumerable
Remarks

The ApplicationEnumeration class allows an application to iterate through the set of Notification Services applications in a given Notification Services instance. It also provides an Item property to return an NSApplication object that represents a specific Notification Services application. This class is used primarily for administrative purposes and for configuring subscription management applications.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

ApplicationEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


ApplicationEnumeration Members

Public Constructors
ApplicationEnumeration Constructor Overloaded. Creates a new object of the ApplicationEnumeration class.
Public Properties
Item Returns an NSApplication object, which represents a specific Notification Services application.

In C#, this property is the indexer for the ApplicationEnumeration class.
Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the applications.
Initialize | Initializes an object of the ApplicationEnumeration class.

See Also

ApplicationEnumeration Class

Microsoft.SqlServer.NotificationServices Namespace


ApplicationEnumeration Constructor

Creates a new object of the ApplicationEnumeration class.

Overload List

Creates an uninitialized object of the ApplicationEnumeration class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New ()

[C#]

public ApplicationEnumeration();

[C++]

public: ApplicationEnumeration();

[JScript]

public function ApplicationEnumeration();

Creates an object of the ApplicationEnumeration class, and initializes it with a reference to an NSInstance object.

[Visual Basic .NET]

Public Sub New(NSInstance)

[C#]

public ApplicationEnumeration(NSInstance);

[C++]

public: ApplicationEnumeration(NSInstance);

[JScript]

public function ApplicationEnumeration(NSInstance);

See Also

ApplicationEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


ApplicationEnumeration Constructor ()

Creates an uninitialized object of the ApplicationEnumeration class.

[Visual Basic .NET]
Public Sub New()
[C#]
public ApplicationEnumeration();
[C++]
public: ApplicationEnumeration();
[JScript]
public function ApplicationEnumeration();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with a reference to an NSInstance object before it can be used.

Example

The following example shows how to create and initialize an ApplicationEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplicationEnumeration

const instanceName = "MyInstanceName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an ApplicationEnumeration object.
set myApplicationEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.ApplicationEnumeration")
myApplicationEnumeration.Initialize myInstance
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

ApplicationEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


ApplicationEnumeration Constructor (NSInstance)

Creates and initializes an object of the ApplicationEnumeration class.

[Visual Basic .NET]
Public Sub New(ByVal instance As NSInstance)
[C#]
public ApplicationEnumeration(NSInstance instance);
[C++]
public: ApplicationEnumeration(NSInstance instance);
[JScript]
public function ApplicationEnumeration(instance : NSInstance);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing the applications to be enumerated by this ApplicationEnumeration object.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize an ApplicationEnumeration object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an ApplicationEnumeration object.
Dim myApplicationEnumeration As New Microsoft.SqlServer.NotificationServices.ApplicationEnumeration(myInstance)
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an ApplicationEnumeration object.
Microsoft.SqlServer.NotificationServices.ApplicationEnumeration myApplicationEnumeration = new Microsoft.SqlServer.NotificationServices.ApplicationEnumeration(myInstance);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

ApplicationEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

ApplicationEnumeration Properties

Public Properties
Item Returns an NSApplication object, which represents a specific Notification Services application.

In C#, this property is the indexer for the ApplicationEnumeration class.

See Also

ApplicationEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property

 SQL Server Notification Services Books Online

ApplicationEnumeration.Item Property

Gets a reference to a specific Notification Services application.

[C#]

In C#, this property is the indexer for the ApplicationEnumeration class.

[Visual Basic .NET]
Public Property Item(ByVal applicationName As String) As NSApplication
[C#]
public NSApplication this[string applicationName] {get;}
[C++]
public: __property NSApplication get_Item(String* applicationName);
[JScript]
returnValue = ApplicationEnumerationObject.Item(applicationName);
-or-
returnValue = ApplicationEnumerationObject(applicationName);
Parameters

applicationName

The name of the Notification Services application that you want returned.

Property Value

An NSApplication object, which represents a specific Notification Services application.

Exceptions
Exception Type | Condition
IndexOutOfRangeException | The requested application name does not exist within the Notification Services instance.
Example
[Visual Basic .NET, C#]

The following examples show how to use the Item property to return an NSApplication object representing a specific Notification Services application:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an ApplicationEnumeration object.
Dim myApplicationEnumeration As New Microsoft.SqlServer.NotificationServices.ApplicationEnumeration(myInstance)

'Use the Item property to return an NSApplication object.
Dim myApplication As Microsoft.SqlServer.NotificationServices.NSApplication = myApplicationEnumeration(applicationName)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an ApplicationEnumeration object.
Microsoft.SqlServer.NotificationServices.ApplicationEnumeration myApplicationEnumeration = new Microsoft.SqlServer.NotificationServices.ApplicationEnumeration(myInstance);

//Use the Item property to return an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = myApplicationEnumeration[applicationName];
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

ApplicationEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

ApplicationEnumeration Methods

Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the applications.
Initialize | Initializes an object of the ApplicationEnumeration class.

See Also

ApplicationEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


GetEnumerator Method

 SQL Server Notification Services Books Online

ApplicationEnumeration.GetEnumerator Method

Gets an IEnumerator interface that allows you to iterate through the collection of applications represented by the ApplicationEnumeration object.

[Visual Basic .NET]
Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();
[C++]
public: IEnumerator* GetEnumerator();
[JScript]
public function GetEnumerator() : IEnumerator;
Return Value

An IEnumerator interface for the ApplicationEnumeration object.

Implements

IEnumerable.GetEnumerator

Remarks

Use this method to return an IEnumerator interface that allows you to iterate through the Notification Services applications in an ApplicationEnumeration object. An initialized ApplicationEnumeration object represents the collection of Notification Services applications in a specified Notification Services instance.

Example
[Visual Basic .NET, C#]

The following examples show how to use an ApplicationEnumeration object to iterate through a set of Notification Services applications. The GetEnumerator method makes the For Each and foreach statements possible:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an ApplicationEnumeration object.
Dim myApplicationEnumeration As New Microsoft.SqlServer.NotificationServices.ApplicationEnumeration(myInstance)

'Iterate through the applications.
Dim application As Microsoft.SqlServer.NotificationServices.NSApplication
For Each application In myApplicationEnumeration
   Console.WriteLine("Application Name: {0}, Version: {1}", application.ApplicationName, application.Version)
Next application
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an ApplicationEnumeration object.
Microsoft.SqlServer.NotificationServices.ApplicationEnumeration myApplicationEnumeration = new Microsoft.SqlServer.NotificationServices.ApplicationEnumeration(myInstance);

//Iterate through the applications.
foreach (Microsoft.SqlServer.NotificationServices.NSApplication application in myApplicationEnumeration)
{
   Console.WriteLine("Application Name: {0}, Version: {1}", application.ApplicationName, application.Version);
}
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

ApplicationEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

ApplicationEnumeration.Initialize Method

Initializes an object of the ApplicationEnumeration class.

[Visual Basic .NET]
Public Sub Initialize(ByVal instance As NSInstance)
[C#]
public void Initialize(NSInstance instance);
[C++]
public: void Initialize(NSInstance instance);
[JScript]
public function Initialize(instance : NSInstance);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing the applications to be enumerated by this ApplicationEnumeration object.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on an ApplicationEnumeration object created with the parameter-less constructor.

Example

The following example shows how to create and initialize an ApplicationEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplicationEnumeration

const instanceName = "MyInstanceName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an ApplicationEnumeration object.
set myApplicationEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.ApplicationEnumeration")
myApplicationEnumeration.Initialize myInstance
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

ApplicationEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


DeliveryChannel Class

Represents a delivery channel in a specified Notification Services instance.

For a list of all members of this type, see DeliveryChannel Members.

System.Object

Microsoft.SqlServer.NotificationServices.DeliveryChannel
[Visual Basic .NET]
NonInheritable Public Class DeliveryChannel Implements IDeliveryChannel
[C#]
public sealed class DeliveryChannel : IDeliveryChannel
[C++]
public __gc __sealed class DeliveryChannel : public IDeliveryChannel
[JScript]
public class DeliveryChannel implements IDeliveryChannel
Remarks

This class exists to encapsulate a delivery channel and expose it for use in your subscription management application.

The DeliveryChannel class has no constructor. DeliveryChannel objects are returned by the DeliveryChannelEnumeration.Item property.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

DeliveryChannel Members

Microsoft.SqlServer.NotificationServices Namespace


DeliveryChannel Members

Public Properties
DeliveryChannelName | Gets the name of the delivery channel.
ProtocolName | Gets the name of the delivery protocol component used by this delivery channel.

See Also

DeliveryChannel Class

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

DeliveryChannel Properties

Public Properties
DeliveryChannelName | Gets the name of the delivery channel.
ProtocolName | Gets the name of the delivery protocol component used by this delivery channel.

See Also

DeliveryChannel Members

Microsoft.SqlServer.NotificationServices Namespace


DeliveryChannelName Property

 SQL Server Notification Services Books Online

DeliveryChannel.DeliveryChannelName Property

Gets the name of the delivery channel.

[Visual Basic .NET]
Public Property DeliveryChannelName As String
[C#]
public string DeliveryChannelName {get;}
[C++]
public: __property string get_DeliveryChannelName();
[JScript]
public function get DeliveryChannelName() : String;
Property Value

A string containing the delivery channel name.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

DeliveryChannel Members

Microsoft.SqlServer.NotificationServices Namespace


ProtocolName Property

 SQL Server Notification Services Books Online

DeliveryChannel.ProtocolName Property

Gets the name of the delivery protocol used by this delivery channel.

[Visual Basic .NET]
Public Property ProtocolName As String
[C#]
public string ProtocolName {get;}
[C++]
public: __property string get_ProtocolName();
[JScript]
public function get ProtocolName() : String;
Property Value

A string containing the delivery protocol name.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

DeliveryChannel Members

Microsoft.SqlServer.NotificationServices Namespace


DeliveryChannelEnumeration Class

Represents the collection of delivery channels available within a given Notification Services instance.

For a list of all members of this type, see DeliveryChannelEnumeration Members.

System.Object

Microsoft.SqlServer.NotificationServices.DeliveryChannelEnumeration
[Visual Basic .NET]
NonInheritable Public Class DeliveryChannelEnumeration Implements IDeliveryChannelEnumeration, IEnumerable
[C#]
public sealed class DeliveryChannelEnumeration : IDeliveryChannelEnumeration, IEnumerable
[C++]
public __gc __sealed class DeliveryChannelEnumeration : public IDeliveryChannelEnumeration, IEnumerable
[JScript]
public class DeliveryChannelEnumeration implements IDeliveryChannelEnumeration, IEnumerable
Remarks

The DeliveryChannelEnumeration class allows you to iterate through the set of delivery channels available within a given Notification Services instance. It also provides an Item property to return a DeliveryChannel object that represents a specific delivery channel. The primary use for this class is to allow you to populate a delivery channel drop-down box in your subscription management application.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

DeliveryChannelEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


DeliveryChannelEnumeration Members

Public Constructors
DeliveryChannelEnumeration Constructor Overloaded. Creates a new object of the DeliveryChannel class.
Public Properties
Item Returns a DeliveryChannel object, which represents a delivery channel.

In C#, this property is the indexer for the DeliveryChannelEnumeration class.
Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the delivery channels.
Initialize | Initializes an object of the DeliveryChannelEnumeration class.

See Also

DeliveryChannelEnumeration Class

Microsoft.SqlServer.NotificationServices Namespace


DeliveryChannelEnumeration Constructor

Creates a new object of the DeliveryChannelEnumeration class.

Overload List

Creates an uninitialized object of the DeliveryChannelEnumeration class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public DeliveryChannelEnumeration();

[C++]

public: DeliveryChannelEnumeration();

[JScript]

public function DeliveryChannelEnumeration();

Creates a new object of the DeliveryChannelEnumeration class, and initializes it with a reference to an NSInstance object.

[Visual Basic .NET]

Public Sub New(NSInstance)

[C#]

public DeliveryChannelEnumeration(NSInstance);

[C++]

public: DeliveryChannelEnumeration(NSInstance);

[JScript]

public function DeliveryChannelEnumeration(NSInstance);

See Also

DeliveryChannelEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


DeliveryChannelEnumeration Constructor ()

Creates an uninitialized object of the DeliveryChannelEnumeration class.

[Visual Basic .NET]
Public Sub New()
[C#]
public DeliveryChannelEnumeration();
[C++]
public: DeliveryChannelEnumeration();
[JScript]
public function DeliveryChannelEnumeration();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with a reference to an NSInstance object before it can be used.

Example

The following example shows how to create and initialize a DeliveryChannelEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myDeliveryChannelEnumeration

const instanceName = "MyInstanceName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize a DeliveryChannelEnumeration object.
set myDeliveryChannelEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.DeliveryChannelEnumeration")
myDeliveryChannelEnumeration.Initialize myInstance
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

DeliveryChannelEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


DeliveryChannelEnumeration Constructor (NSInstance)

Creates and initializes an object of the DeliveryChannelEnumeration class.

[Visual Basic .NET]
Public Sub New(ByVal instance As NSInstance)
[C#]
public DeliveryChannelEnumeration(NSInstance instance);
[C++]
public: DeliveryChannelEnumeration(NSInstance instance);
[JScript]
public function DeliveryChannelEnumeration(instance : NSInstance);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing the delivery channels to be enumerated by this DeliveryChannelEnumeration object.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize a DeliveryChannelEnumeration object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a DeliveryChannelEnumeration object.
Dim myDeliveryChannelEnumeration As New Microsoft.SqlServer.NotificationServices.DeliveryChannelEnumeration(myInstance)
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a DeliveryChannelEnumeration object.
Microsoft.SqlServer.NotificationServices.DeliveryChannelEnumeration myDeliveryChannelEnumeration = new Microsoft.SqlServer.NotificationServices.DeliveryChannelEnumeration(myInstance);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

DeliveryChannelEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

DeliveryChannelEnumeration Properties

Public Properties
Item Returns a DeliveryChannel object, which represents a delivery channel.

In C#, this property is the indexer for the DeliveryChannelEnumeration class.

See Also

DeliveryChannelEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property

 SQL Server Notification Services Books Online

DeliveryChannelEnumeration.Item Property

Returns a reference to a delivery channel.

[C#]

In C#, this property is the indexer for the DeliveryChannelEnumeration class.

[Visual Basic .NET]
Public Property Item(ByVal deliveryChannelName As String) As DeliveryChannel
[C#]
public DeliveryChannel this[string deliveryChannelName] {get;}
[C++]
public: __property DeliveryChannel get_Item(String* deliveryChannelName);
[JScript]
returnValue = DeliveryChannelEnumerationObject.Item(deliveryChannelName);
-or-
returnValue = DeliveryChannelEnumerationObject(deliveryChannelName);
Parameters

deliveryChannelName

The name of the delivery channel that you want returned.

Property Value

A DeliveryChannel object, which represents a specific delivery channel.

Exceptions
Exception Type | Condition
IndexOutOfRangeException | The requested delivery channel name does not exist within the Notification Services instance.
Example
[Visual Basic .NET, C#]

The following examples show how to use the Item property to return a DeliveryChannel object:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim deliveryChannelName As String = "MyDeliveryChannelName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a DeliveryChannelEnumeration object.
Dim myDeliveryChannelEnumeration As New Microsoft.SqlServer.NotificationServices.DeliveryChannelEnumeration(myInstance)

'Use the Item property to return a DeliveryChannel object.
Dim myDeliveryChannel As Microsoft.SqlServer.NotificationServices.DeliveryChannel = myDeliveryChannelEnumeration(deliveryChannelName)
[C#]
string instanceName = "MyInstanceName";
string deliveryChannelName = "MyDeliveryChannelName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a DeliveryChannelEnumeration object.
Microsoft.SqlServer.NotificationServices.DeliveryChannelEnumeration myDeliveryChannelEnumeration = new Microsoft.SqlServer.NotificationServices.DeliveryChannelEnumeration(myInstance);

//Use the Item property to return a DeliveryChannel object.
Microsoft.SqlServer.NotificationServices.DeliveryChannel myDeliveryChannel = myDeliveryChannelEnumeration[deliveryChannelName];
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

DeliveryChannelEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

DeliveryChannelEnumeration Methods

Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the delivery channels.
Initialize | Initializes an object of the DeliveryChannelEnumeration class.

See Also

DeliveryChannelEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


GetEnumerator Method

 SQL Server Notification Services Books Online

DeliveryChannelEnumeration.GetEnumerator Method

Gets an IEnumerator interface that allows you to iterate through the collection of delivery channels represented by the DeliveryChannelEnumeration object.

[Visual Basic .NET]
Public Function GetEnumerator() As IEnumerator Implements  IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();
[C++]
public: IEnumerator* GetEnumerator();
[JScript]
public function GetEnumerator() : IEnumerator;
Return Value

An IEnumerator interface for the DeliveryChannelEnumeration object.

Implements

IEnumerable.GetEnumerator

Remarks

Use this method to return an IEnumerator interface that allows you to iterate through the delivery channels in a DeliveryChannelEnumeration object. An initialized DeliveryChannelEnumeration object represents the collection of delivery channels in a specified Notification Services instance.

Example
[Visual Basic .NET, C#]

The following examples show how to use a DeliveryChannelEnumeration object to iterate through a set of delivery channels. The GetEnumerator method makes the For Each and foreach statements possible:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a DeliveryChannelEnumeration object.
Dim myDeliveryChannelEnumeration As New Microsoft.SqlServer.NotificationServices.DeliveryChannelEnumeration(myInstance)

'Iterate through the delivery channels.
Dim deliveryChannel As Microsoft.SqlServer.NotificationServices.DeliveryChannel
For Each deliveryChannel In myDeliveryChannelEnumeration
   Console.WriteLine("Delivery Channel Name: {0}", deliveryChannel.DeliveryChannelName)
Next deliveryChannel
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a DeliveryChannelEnumeration object.
Microsoft.SqlServer.NotificationServices.DeliveryChannelEnumeration myDeliveryChannelEnumeration = new Microsoft.SqlServer.NotificationServices.DeliveryChannelEnumeration(myInstance);

//Iterate through the delivery channels.
foreach (Microsoft.SqlServer.NotificationServices.DeliveryChannel deliveryChannel in myDeliveryChannelEnumeration)
{
   Console.WriteLine("Delivery Channel Name: {0}", deliveryChannel.DeliveryChannelName);
}
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

DeliveryChannelEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

DeliveryChannelEnumeration.Initialize Method

Initializes an object of the DeliveryChannelEnumeration class.

[Visual Basic .NET]
Public Sub Initialize(ByVal instance As NSInstance)
[C#]
public void Initialize(NSInstance instance);
[C++]
public: void Initialize(NSInstance instance);
[JScript]
public function Initialize(instance : NSInstance);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing the delivery channels to be enumerated by this DeliveryChannelEnumeration object.

Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on a DeliveryChannelEnumeration object created with the parameter-less constructor.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Example

The following example shows how to create and initialize a DeliveryChannelEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myDeliveryChannelEnumeration

const instanceName = "MyInstanceName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize a DeliveryChannelEnumeration object.
set myDeliveryChannelEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.DeliveryChannelEnumeration")
myDeliveryChannelEnumeration.Initialize myInstance
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

DeliveryChannelEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Event Class

Represents a single event.

For a list of all members of this type, see Event Members.

System.Object

Microsoft.SqlServer.NotificationServices.Event
[Visual Basic .NET]
<Serializable>
NonInheritable Public Class Event Implements IEvent
[C#]
[Serializable]
public sealed class Event : IEvent
[C++]
[Serializable]
public __gc __sealed class Event : public IEvent
[JScript]
public
   Serializable
class Event implements IEvent
Remarks

The Event object encapsulates the event data for a single event. A reference to the Event object is passed to an EventCollector object, which writes the data to the application database.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


Event Members

Public Constructors
Event Constructor Overloaded. Creates a new object of the Event class.
Public Properties
FieldCount | Returns the number of developer-defined event fields for this event, as specified in the event class in the application definition file (ADF).
Item | Overloaded. Gets or sets the value of an event data field in the event. In C#, this property is the indexer for the Event class.
Public Methods
GetFieldName | Returns the name of a field in the event record when passed a field ordinal.
GetFieldOrdinal | Returns the ordinal of a field in the event record when passed a field name.
GetFieldValue | Returns the value of a field in the event record when passed a field name. This method is provided for COM interoperability.
Initialize | Initializes an object of the Event class with an event class name and a reference to an NSApplication object.
SetFieldValue | Sets the value of a field in the event record when passed a field name. This method is provided for COM interoperability.

See Also

Event Class

Microsoft.SqlServer.NotificationServices Namespace


Event Constructor

Creates a new object of the Event class.

Overload List

Creates an uninitialized object of the Event class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public Event();

[C++]

public: Event();

[JScript]

public function Event();

Creates a new object of the Event class, and initializes it with a reference to an NSApplication object and an event class name.

[Visual Basic .NET]

Public Sub New(NSApplication, String)

[C#]

public Event(NSApplication, string);

[C++]

public: Event(NSApplication, String*);

[JScript]

public function Event(NSApplication, String);

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


Event Constructor ()

Creates an uninitialized object of the Event class.

[Visual Basic .NET]
Public Sub New()
[C#]
public Event();
[C++]
public: Event();
[JScript]
public function Event();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with an event class name and a reference to an NSApplication object before it can be used.

Example

The following example shows how to create and initialize an Event object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, myEvent

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const eventClassName = "MyEventClassName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize an Event object.
set myEvent = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Event")
myEvent.Initialize myApplication, eventClassName
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


Event Constructor (NSApplication, String)

Creates and initializes an object of the Event class.

[Visual Basic .NET]
Public Sub New(ByVal application As NSApplication, ByVal eventClassName As String)
[C#]
public Event(NSApplication application, string eventClassName);
[C++]
public: Event(NSApplication application, String* eventClassName);
[JScript]
public function Event(application : NSApplication, eventClassName : String);
Parameters

application

An NSApplication object that represents the Notification Services application to which the Event object provides event data.

eventClassName

A string containing the name of the event class that defines the event data provided by the Event object.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Remarks

It is possible to construct an Event object without initializing it with an NSApplication object. In this case, the event class is not verified, and event field names must be hard-coded. This can be useful in cases where you would like to use an Event object in an application that does not have a direct connection to a Notification Services server, for example in a disconnected Message Queuing (also known as MSMQ) scenario. For more information about using an Event object in this way, see Creating a Disconnected Event Object.

Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize an Event object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an Event object.
Dim myEvent As New Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an Event object.
Microsoft.SqlServer.NotificationServices.Event myEvent = new Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

Event Properties

Public Properties
FieldCount | Returns the number of developer-defined event fields for this event, as specified in the event class in the application definition file (ADF).
Item | Overloaded. Gets or sets the value of an event data field in the event. In C#, this property is the indexer for the Event class.

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


FieldCount Property

 SQL Server Notification Services Books Online

Event.FieldCount Property

Returns the number of developer-defined event fields for this event, as specified in the event class in the application definition file (ADF).

[Visual Basic .NET]
Public Property FieldCount As Integer
[C#]
public int FieldCount {get;}
[C++]
public: __property int get_FieldCount();
[JScript]
public function get FieldCount() : int;
Property Value

An integer representing the number of developer-defined event fields in an event class. These are the fields defined in the /EventClasses/EventClass/Schema section of the ADF for the associated event class.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property

 SQL Server Notification Services Books Online

Event.Item Property

Gets or sets the value of an event data field in the event record.

[C#]

In C#, this property is the indexer for the Event class.

Overload List

Gets or sets the value of an event data field in the event record, using the field name as an identifier.

[Visual Basic .NET]

Public Property Item(String) As Object

[C#]

public object this[string] {get;set;}

[C++]

public: __property Object* get_Item(String*);

public: __property void set_Item(String*, Object*);

[JScript]

Event.Item (String)

Gets or sets the value of an event data field in the event record, using the field ordinal as an identifier.

[Visual Basic .NET]

Public Property Item(Integer) As Object

[C#]

public Object this[int] {get;set;}

[C++]

public: __property Object* get_Item(int);

public: __property void set_Item(int, Object*);

[JScript]

Event.Item (int)

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property (String)

 SQL Server Notification Services Books Online
Event.Item Property (String)

Gets or sets the value of an event data field in the event record, using the field name as an identifier.

[Visual Basic .NET]
Public Property Item(ByVal fieldName As String) As Object
[C#]
public object this[string fieldName] {get;set;}
[C++]
public: __property Object* get_Item(String* fieldName);
public: __property void set_Item(String* fieldName, Object*);
[JScript]
returnValue = EventObject.Item(fieldName);
EventObject.Item(fieldName) = value;
-or-
returnValue = EventObject(fieldName);
EventObject(fieldName) = value;
Parameters

fieldName

The name of the event field for which you want the value returned.

Property Value

An object that represents the field's value.

Exceptions
Exception Type | Condition
IndexOutOfRangeException | No event field can be identified using the field name provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the Item property to set a field value:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"
Dim eventFieldName As String = "MyEventFieldName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an Event object.
Dim myEvent As New Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName)

'Use the Item property to set a field value.
myEvent(eventFieldName) = txtFieldValue.Text
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";
string eventFieldName = "MyEventFieldName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an Event object.
Microsoft.SqlServer.NotificationServices.Event myEvent = new Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName);

//Use the Item property to set a field value.
myEvent[eventFieldName] = txtFieldValue.Text;
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property (Int32)

 SQL Server Notification Services Books Online
Event.Item Property (Int32)

Gets or sets the value of an event data field in the subscription record, using the field ordinal as an identifier.

[Visual Basic .NET]
Public Property Item(ByVal fieldOrdinal As Integer) As Object
[C#]
public object this[int fieldOrdinal] {get;set;}
[C++]
public: __property Object* get_Item(int fieldOrdinal);
public: __property void set_Item(int fieldOrdinal, Object*);
[JScript]
returnValue = EventObject.Item(fieldOrdinal);
EventObject.Item(fieldOrdinal) = returnValue;
-or-
returnValue = EventObject(fieldOrdinal);
EventObject(fieldOrdinal) = returnValue;
Parameters

fieldOrdinal

The zero-based ordinal of the event field for which you want the value returned.

Property Value

An object that represents the field's value.

Exceptions
Exception Type | Condition
IndexOutOfRangeException | No event field can be identified using the field ordinal provided.
Remarks

The Int32 overload of the Item property is not available through COM interop.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Item property to set a field value:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an Event object.
Dim myEvent As New Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName)

'Use the Item property to set a field value.
myEvent(0) = txtFieldValue.Text
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an Event object.
Microsoft.SqlServer.NotificationServices.Event myEvent = new Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName);

//Use the Item property to set a field value.
myEvent[0] = txtFieldValue.Text;
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

Event Methods

Public Methods
GetFieldName | Returns the name of a field in the event record when passed a field ordinal.
GetFieldOrdinal | Returns the ordinal of a field in the event record when passed a field name.
GetFieldValue | Returns the value of a field in the event record when passed a field name. This method is provided for COM interoperability.
Initialize | Initializes an object of the Event class with an event class name and a reference to an NSApplication object.
SetFieldValue | Sets the value of a field in the event record when passed a field name. This method is provided for COM interoperability.

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


GetFieldName Method

 SQL Server Notification Services Books Online

Event.GetFieldName Method

Gets the name of a field in the event record.

[Visual Basic .NET]
Public Function GetFieldName(ByVal fieldOrdinal As Integer) As String
[C#]
public string GetFieldName(int fieldOrdinal);
[C++]
public: String* GetFieldName(int fieldOrdinal);
[JScript]
public function GetFieldName(fieldOrdinal : int ) : String;
Parameters

fieldOrdinal

The zero-based ordinal of the event field for which you want the name returned.

Return Value

A string containing the field name.

Example
[Visual Basic .NET, C#]

The following examples show how to use the GetFieldName method to get the name of an event field by providing the field ordinal:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"
Dim fieldOrdinal As Integer = 0

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an Event object.
Dim myEvent As New Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName)

'Use the GetFieldName method to get a field name.
Dim fieldName As String = myEvent.GetFieldName(fieldOrdinal)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";
int fieldOrdinal = 0;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an Event object.
Microsoft.SqlServer.NotificationServices.Event myEvent = new Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName);

//Use the GetFieldName method to get a field name.
string fieldName = myEvent.GetFieldName(fieldOrdinal);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


GetFieldOrdinal Method

 SQL Server Notification Services Books Online

Event.GetFieldOrdinal Method

Returns the zero-based ordinal of a field in the event record.

[Visual Basic .NET]
Public Function GetFieldOrdinal(ByVal fieldName As String) As Integer
[C#]
public int GetFieldOrdinal(string fieldName);
[C++]
public: int GetFieldOrdinal(String* fieldName);
[JScript]
public function GetFieldOrdinal(fieldName : String ) : int;
Parameters

fieldName

The name of the event field for which you want the ordinal returned.

Return Value

An integer representing the zero-based field ordinal.

Example
[Visual Basic .NET, C#]

The following examples show how to use the GetFieldOrdinal method to get the ordinal of an event field by providing the field name:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"
Dim fieldName As String = "MyEventFieldName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an Event object.
Dim myEvent As New Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName)

'Use the GetFieldOrdinal method to get a field ordinal.
Dim fieldOrdinal As Integer = myEvent.GetFieldOrdinal(fieldName)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";
string fieldName = "MyEventFieldName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an Event object.
Microsoft.SqlServer.NotificationServices.Event myEvent = new Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName);

//Use the GetFieldOrdinal method to get a field ordinal.
int fieldOrdinal = myEvent.GetFieldOrdinal(fieldName);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


GetFieldValue Method

 SQL Server Notification Services Books Online

Event.GetFieldValue Method

Returns the value of a field in the event record.

[Visual Basic .NET]
Public Function GetFieldValue(ByVal fieldName As String) As Object
[C#]
public object GetFieldValue(string fieldName);
[C++]
public: Object* GetFieldValue(String* fieldName);
[JScript]
public function GetFieldValue(fieldName : String ) : Object;
Parameters

fieldName

The name of the event field for which you want the value returned.

Return Value

An object that represents the field's value.

Remarks

This method is provided for COM interoperability, to allow callers from unmanaged code to get field values from an event record.

Example

The following example shows how to use the GetFieldValue method in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code to get the value of an event field:

Dim myInstance, myApplication, myEvent, fieldValue

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const eventClassName = "MyEventClassName"
const eventFieldName = "MyEventFieldName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize an Event object.
set myEvent = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Event")
myEvent.Initialize myApplication, eventClassName

'Use the SetFieldValue method to set a field value.
myEvent.SetFieldValue eventFieldName, "Test"

'Use the GetFieldValue method to return a field value.
fieldValue = myEvent.GetFieldValue(eventFieldName)
WScript.Echo "Field Value = " + fieldValue
WScript.Echo
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

Event.Initialize Method

Initializes an object of the Event class.

[Visual Basic .NET]
Public Sub Initialize(ByVal application As NSApplication, ByVal eventClassName As String)
[C#]
public void Initialize(NSApplication application, string eventClassName);
[C++]
public: void Initialize(NSApplication application, String* eventClassName);
[JScript]
public function Initialize(application : NSApplication, eventClassName : String);
Parameters

application

An NSApplication object that represents the Notification Services application containing the event class to be implemented by this Event object.

eventClassName

A string containing the name of the event class that this Event object implements. This event class determines what event fields this Event object exposes.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on an Event object created with the parameter-less constructor.

Example

The following example shows how to create and initialize an Event object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, myEvent

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const eventClassName = "MyEventClassName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize an Event object.
set myEvent = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Event")
myEvent.Initialize myApplication, eventClassName
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


SetFieldValue Method

 SQL Server Notification Services Books Online

Event.SetFieldValue Method

Sets the value of a field in the event record.

[Visual Basic .NET]
Public Sub SetFieldValue(ByVal fieldName As String, ByVal newValue As Object)
[C#]
public void SetFieldValue(string fieldname, object newValue);
[C++]
public: void SetFieldValue(String* fieldName, Object* newValue);
[JScript]
public function SetFieldValue(fieldName : String, newValue: Object);
Parameters

fieldName

The name of the event field for which you want the value set.

newValue

The value to which you want the event field set.

Remarks

This method is provided for COM interoperability, to allow callers from unmanaged code to set field values for an event record.

Example

The following example shows how to use the SetFieldValue method in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code to set the value of an event field:

Dim myInstance, myApplication, myEvent

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const eventClassName = "MyEventClassName"
const eventFieldName = "MyEventFieldName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize an Event object.
set myEvent = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Event")
myEvent.Initialize myApplication, eventClassName

'Use the SetFieldValue method to set a field value.
myEvent.SetFieldValue eventFieldName, "Test"
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Event Members

Microsoft.SqlServer.NotificationServices Namespace


EventClass Class

Represents any event class that is specified in an application definition file (ADF). It is used to access the event class metadata, and should not be confused with the Event class, which is used to encapsulate event information for a single event.

For a list of all members of this type, see EventClass Members.

System.Object

Microsoft.SqlServer.NotificationServices.EventClass
[Visual Basic .NET]
Public Class EventClass Implements IEventClass
[C#]
public class EventClass : IEventClass
[C++]
public class EventClass : public IEventClass
[JScript]
public class EventClass implements IEventClass
Remarks

The EventClass class provides access to the metadata of any event class defined in an ADF. It should not be confused with the Event class, which provides a means of encapsulating a single event for submission to the application. The EventClass class provides methods to return information about the event fields defined in the /EventClasses/EventClass/Schema section of the ADF for the specified event class.

The EventClass class has no public constructor. Use EventClassEnumeration.Item to return an EventClass object.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

EventClass Members

Microsoft.SqlServer.NotificationServices Namespace


EventClass Members

Public Properties
FieldCount | Gets the number of fields specified in the /EventClasses/EventClass/Schema section of the application definition file (ADF) for this event class.
EventClassName | Gets the event class name specified in the /EventClasses/EventClass/EventClassName section of the ADF for this event class.
Public Methods
FieldName | Gets the field name as specified in the /EventClasses/EventClass/Schema section of the ADF when passed a field ordinal.
FieldOrdinal | Gets the field ordinal of the field based on its location in the /EventClasses/EventClass/Schema section of the ADF when passed a field name.
FieldType | Gets the field type as specified in the /EventClasses/EventClass/Schema section of the ADF when passed a field ordinal.
FieldTypeMods | Gets the field type modifiers as specified in the /EventClasses/EventClass/Schema section of the ADF when passed a field ordinal.

See Also

EventClass Class

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

EventClass Properties

Public Properties
FieldCount | Gets the number of fields specified in the /EventClasses/EventClass/Schema section of the application definition file (ADF) for this event class.
EventClassName | Gets the event class name specified in the /EventClasses/EventClass/EventClassName section of the ADF for this event class.

See Also

EventClass Members

Microsoft.SqlServer.NotificationServices Namespace


FieldCount Property

 SQL Server Notification Services Books Online

EventClass.FieldCount Property

Gets the number of event fields specified in an event class.

[Visual Basic .NET]
Public Property FieldCount As Integer
[C#]
public int FieldCount {get;}
[C++]
public: __property int get_FieldCount();
[JScript]
public function get FieldCount() : int;
Property Value

An integer representing the number of event data fields in an event class. These are the fields defined in the /EventClasses/EventClass/Schema section of the application definition file (ADF).

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventClass Members

Microsoft.SqlServer.NotificationServices Namespace


EventClassName Property

 SQL Server Notification Services Books Online

EventClass.EventClassName Property

Gets the name of an event class.

[Visual Basic .NET]
Public Property EventClassName As String
[C#]
public string EventClassName {get;}
[C++]
public: __property String* get_EventClassName();
[JScript]
public function get EventClassName() : String;
Property Value

A string containing the event class name. This is specified in the /EventClasses/EventClass/EventClassName section of the application definition file (ADF).

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventClass Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

EventClass Methods

Public Methods
FieldName | Gets the field name as specified in the /EventClasses/EventClass/Schema section of the application definition file (ADF) when passed a field ordinal.
FieldOrdinal | Gets the field ordinal of the field based on its location in the /EventClasses/EventClass/Schema section of the ADF when passed a field name.
FieldType | Gets the field type as specified in the /EventClasses/EventClass/Schema section of the ADF when passed a field ordinal.
FieldTypeMods | Gets the field type modifiers as specified in the /EventClasses/EventClass/Schema section of the ADF when passed a field ordinal.

See Also

EventClass Members

Microsoft.SqlServer.NotificationServices Namespace


FieldName Method

 SQL Server Notification Services Books Online

EventClass.FieldName Method

Gets the name of a field in the event class.

[Visual Basic .NET]
Public Function FieldName(ByVal fieldOrdinal As Integer) As String
[C#]
public string FieldName(int fieldOrdinal);
[C++]
public: String* FieldName(int fieldOrdinal);
[JScript]
public function FieldName(fieldOrdinal : int ) : String;
Parameters

fieldOrdinal

The zero-based ordinal of the developer-defined field in the event class definition for which you want the name returned.

Return Value

A string containing the field name.

Exceptions
Exception Type | Condition
ArgumentOutOfRangeException | No event class field can be identified using the field ordinal provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the FieldName method to get the name of an event class field by providing the field ordinal:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"
Dim fieldOrdinal As Integer = 0

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an EventClassEnumeration object.
Dim myEventClassEnumeration As New Microsoft.SqlServer.NotificationServices.EventClassEnumeration(myApplication)

'Use the EventClassEnumeration.Item
'to return an EventClass object.
Dim myEventClass As Microsoft.SqlServer.NotificationServices.EventClass = myEventClassEnumeration(eventClassName)

'Use the FieldName method to get a field name.
Dim fieldName As String = myEventClass.FieldName(fieldOrdinal)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";
int fieldOrdinal = 0;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an EventClassEnumeration object.
Microsoft.SqlServer.NotificationServices.EventClassEnumeration myEventClassEnumeration = new Microsoft.SqlServer.NotificationServices.EventClassEnumeration(myApplication);

//Use the EventClassEnumeration.Item
//to return an EventClass object.
Microsoft.SqlServer.NotificationServices.EventClass myEventClass = myEventClassEnumeration[eventClassName];

//Use the FieldName method to get a field name.
string fieldName = myEventClass.FieldName(fieldOrdinal);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventClass Members

Microsoft.SqlServer.NotificationServices Namespace


FieldOrdinal Method

 SQL Server Notification Services Books Online

EventClass.FieldOrdinal Method

Gets the zero-based ordinal of a field in the event class.

[Visual Basic .NET]
Public Function FieldOrdinal(ByVal fieldName As String) As Integer
[C#]
public int FieldOrdinal(string fieldName);
[C++]
public: int FieldOrdinal(String* fieldName);
[JScript]
public function FieldOrdinal(fieldName : String ) : int;
Parameters

fieldName

The name of the developer-defined field in the event class definition for which you want the ordinal returned.

Return Value

An integer representing the zero-based field ordinal.

Exceptions
Exception Type | Condition
ArgumentOutOfRangeException | No event class field can be identified using the field name provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the FieldOrdinal method to get the ordinal of an event class field by providing the field name:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"
Dim fieldName As String = "MyEventFieldName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an EventClassEnumeration object.
Dim myEventClassEnumeration As New Microsoft.SqlServer.NotificationServices.EventClassEnumeration(myApplication)

'Use the EventClassEnumeration.Item
'to return an EventClass object.
Dim myEventClass As Microsoft.SqlServer.NotificationServices.EventClass = myEventClassEnumeration(eventClassName)

'Use the FieldOrdinal method to get a field ordinal.
Dim fieldOrdinal As Integer = myEventClass.FieldOrdinal(fieldName)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";
string fieldName = "MyEventFieldName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an EventClassEnumeration object.
Microsoft.SqlServer.NotificationServices.EventClassEnumeration myEventClassEnumeration = new Microsoft.SqlServer.NotificationServices.EventClassEnumeration(myApplication);

//Use the EventClassEnumeration.Item
//to return an EventClass object.
Microsoft.SqlServer.NotificationServices.EventClass myEventClass = myEventClassEnumeration[eventClassName];

//Use the FieldOrdinal method to get a field ordinal.
int fieldOrdinal = myEventClass.FieldOrdinal(fieldName);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionClass Members

Microsoft.SqlServer.NotificationServices Namespace


FieldType Method

 SQL Server Notification Services Books Online

EventClass.FieldType Method

Gets the data type of a field in the event class.

[Visual Basic .NET]
Public Function FieldType(ByVal fieldOrdinal As Integer) As String
[C#]
public string FieldType(int fieldOrdinal);
[C++]
public: String* FieldType(int fieldOrdinal);
[JScript]
public function FieldType(fieldOrdinal : int ) : String;
Parameters

fieldOrdinal

The zero-based ordinal of the developer-defined field in the event class definition for which you want the data type returned.

Return Value

A string containing the data type of the event class field identified.

Exceptions
Exception Type | Condition
ArgumentOutOfRangeException | No event class field can be identified using the field ordinal provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the FieldType method to get the data type of an event class field by providing the field ordinal:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"
Dim fieldOrdinal As Integer = 0

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an EventClassEnumeration object.
Dim myEventClassEnumeration As New Microsoft.SqlServer.NotificationServices.EventClassEnumeration(myApplication)

'Use the EventClassEnumeration.Item
'to return an EventClass object.
Dim myEventClass As Microsoft.SqlServer.NotificationServices.EventClass = myEventClassEnumeration(eventClassName)

'Use the FieldType method to get a field data type.
Dim fieldType As String = myEventClass.FieldType(fieldOrdinal)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";
int fieldOrdinal = 0;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an EventClassEnumeration object.
Microsoft.SqlServer.NotificationServices.EventClassEnumeration myEventClassEnumeration = new Microsoft.SqlServer.NotificationServices.EventClassEnumeration(myApplication);

//Use the EventClassEnumeration.Item
//to return an EventClass object.
Microsoft.SqlServer.NotificationServices.EventClass myEventClass = myEventClassEnumeration[eventClassName];

//Use the FieldType method to get a field data type.
string fieldType = myEventClass.FieldType(fieldOrdinal);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventClass Members

Microsoft.SqlServer.NotificationServices Namespace


FieldTypeMods Method

 SQL Server Notification Services Books Online

EventClass.FieldTypeMods Method

Gets the field modifiers of a field in the event class.

[Visual Basic .NET]
Public Function FieldType(ByVal fieldOrdinal As Integer) As String
[C#]
public string FieldType(int fieldOrdinal);
[C++]
public: String* FieldType(int fieldOrdinal);
[JScript]
public function FieldType(fieldOrdinal : int ) : String;
Parameters

fieldOrdinal

The zero-based ordinal of the developer-defined field in the event class definition for which you want the field modifiers returned.

Return Value

A string containing the field modifiers for this data field, if any are specified. Field modifiers include such information as whether the field accepts null values, or has a default specified.

Exceptions
Exception Type | Condition
ArgumentOutOfRangeException | No event class field can be identified using the field ordinal provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the FieldTypeMods method to get the field modifiers of an event class field by providing the field ordinal:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"
Dim fieldOrdinal As Integer = 0

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an EventClassEnumeration object.
Dim myEventClassEnumeration As New Microsoft.SqlServer.NotificationServices.EventClassEnumeration(myApplication)

'Use the EventClassEnumeration.Item
'to return an EventClass object.
Dim myEventClass As Microsoft.SqlServer.NotificationServices.EventClass = myEventClassEnumeration(eventClassName)

'Use the FieldTypeMods method to get a field's modifiers.
Dim fieldTypeMods As String = myEventClass.FieldTypeMods(fieldOrdinal)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";
int fieldOrdinal = 0;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an EventClassEnumeration object.
Microsoft.SqlServer.NotificationServices.EventClassEnumeration myEventClassEnumeration = new Microsoft.SqlServer.NotificationServices.EventClassEnumeration(myApplication);

//Use the EventClassEnumeration.Item
//to return an EventClass object.
Microsoft.SqlServer.NotificationServices.EventClass myEventClass = myEventClassEnumeration[eventClassName];

//Use the FieldTypeMods method to get a field's modifiers.
string fieldTypeMods = myEventClass.FieldTypeMods(fieldOrdinal);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventClass Members

Microsoft.SqlServer.NotificationServices Namespace


EventClassEnumeration Class

Represents the collection of event classes in a given Notification Services application.

For a list of all members of this type, see EventClassEnumeration Members.

System.Object

Microsoft.SqlServer.NotificationServices.EventClassEnumeration
[Visual Basic .NET]
Public Class EventClassEnumeration
Implements IEventClassEnumeration, IEnumerable
[C#]
public class EventClassEnumeration : IEventClassEnumeration, IEnumerable
[C++]
public class EventClassEnumeration : public IEventClassEnumeration, IEnumerable
[JScript]
public class EventClassEnumeration implements IEventClassEnumeration, IEnumerable
Remarks

The EventClassEnumeration class allows an application to iterate through the set of event classes in a given Notification Services application. It also provides an Item property to return an EventClass object that represents a specific event class.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

EventClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


EventClassEnumeration Members

Public Constructors
EventClassEnumeration Constructor Overloaded. Creates a new object of the EventClassEnumeration class.
Public Properties
Count | Gets the count of event classes in the specified Notification Services application.
Item | Returns an EventClass object, which represents a specific event class. In C#, this property is the indexer for the EventClassEnumeration class.
Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the event classes.
Initialize | Initializes an object of the EventClassEnumeration class.

See Also

EventClassEnumeration Class

Microsoft.SqlServer.NotificationServices Namespace


EventClassEnumeration Constructor

Creates a new object of the EventClassEnumeration class.

Overload List

Creates an uninitialized object of the EventClassEnumeration class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public EventClassEnumeration();

[C++]

public: EventClassEnumeration();

[JScript]

public function EventClassEnumeration();

Creates an object of the EventClassEnumeration class, and initializes it with a reference to an NSApplication object.

[Visual Basic .NET]

Public Sub New(NSApplication)

[C#]

public EventClassEnumeration(NSApplication);

[C++]

public: EventClassEnumeration(NSApplication);

[JScript]

public function EventClassEnumeration(NSApplication);

See Also

EventClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


EventClassEnumeration Constructor()

Creates an uninitialized object of the EventClassEnumeration class.

[Visual Basic .NET]
Public Sub New()
[C#]
public EventClassEnumeration();
[C++]
public: EventClassEnumeration();
[JScript]
public function EventClassEnumeration();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with a reference to an NSApplication object before it can be used.

Example

The following example shows how to create and initialize an EventClassEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, myEventClassEnumeration

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize an EventClassEnumeration object.
set myEventClassEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.EventClassEnumeration")
myEventClassEnumeration.Initialize myApplication
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


EventClassEnumeration Constructor (NSApplication)

Creates and initializes an object of the EventClassEnumeration class.

[Visual Basic .NET]
Public Sub New(ByVal application As NSApplication)
[C#]
public EventClassEnumeration(NSApplication application);
[C++]
public: EventClassEnumeration(NSApplication application);
[JScript]
public function EventClassEnumeration(application : NSApplication);
Parameters

application

An NSApplication object that represents the Notification Services application containing the event classes to be enumerated by this EventClassEnumeration object.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize an EventClassEnumeration object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an EventClassEnumeration object.
Dim myEventClassEnumeration As New Microsoft.SqlServer.NotificationServices.EventClassEnumeration(myApplication)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an EventClassEnumeration object.
Microsoft.SqlServer.NotificationServices.EventClassEnumeration myEventClassEnumeration = new Microsoft.SqlServer.NotificationServices.EventClassEnumeration(myApplication);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

EventClassEnumeration Properties

Public Properties
Count | Gets the count of event classes in the specified Notification Services application.
Item | Returns an EventClass object, which represents a specific event class. In C#, this property is the indexer for the EventClassEnumeration class.

See Also

EventClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Count Property

 SQL Server Notification Services Books Online

EventClassEnumeration.Count Property

Gets the count of event classes in a Notification Services application.

[Visual Basic .NET]
Public Property Count As Integer
[C#]
public int Count {get;}
[C++]
public: __property int get_Count();
[JScript]
public function get Count() : int;
Property Value

An integer representing the number of event classes in a Notification Services application.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property

 SQL Server Notification Services Books Online

EventClassEnumeration.Item Property

Gets a reference to an event class.

[C#]

In C#, this property is the indexer for the EventClassEnumeration class.

[Visual Basic .NET]
Public Property Item(ByVal eventClassName As String) As EventClass
[C#]
public EventClass this[string eventClassName] {get;}
[C++]
public: __property EventClass get_Item(String* eventClassName);
[JScript]
returnValue = EventClassEnumerationObject.Item(eventClassName);
-or-
returnValue = EventClassEnumerationObject(eventClassName);
Parameters

eventClassName

The name of the event class that you want returned.

Property Value

An EventClass object, which represents a specific event class.

Exceptions
Exception Type | Condition
IndexOutOfRangeException | No event class can be identified using the event class name specified.
Example
[Visual Basic .NET, C#]

The following examples show how to use the Item property to return an EventClass object representing a specific event class:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an EventClassEnumeration object.
Dim myEventClassEnumeration As New Microsoft.SqlServer.NotificationServices.EventClassEnumeration(myApplication)

'Use the Item property to return an EventClass object.
Dim myEventClass As Microsoft.SqlServer.NotificationServices.EventClass = myEventClassEnumeration(eventClassName)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);
//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an EventClassEnumeration object.
Microsoft.SqlServer.NotificationServices.EventClassEnumeration myEventClassEnumeration = new Microsoft.SqlServer.NotificationServices.EventClassEnumeration(myApplication);

//Use the Item property to return an EventClass object.
Microsoft.SqlServer.NotificationServices.EventClass myEventClass = myEventClassEnumeration[eventClassName];
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

EventClassEnumeration Methods

Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the event classes.
Initialize | Initializes an object of the EventClassEnumeration class.

See Also

EventClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


GetEnumerator Method

 SQL Server Notification Services Books Online

EventClassEnumeration.GetEnumerator Method

Gets an IEnumerator interface that allows you to iterate through the collection of event classes represented by the EventClassEnumeration object.

[Visual Basic .NET]
Public Function GetEnumerator() As IEnumerator Implements  IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();
[C++]
public: IEnumerator* GetEnumerator();
[JScript]
public function GetEnumerator() : IEnumerator;
Return Value

An IEnumerator interface for the EventClassEnumeration object.

Implements

IEnumerable.GetEnumerator

Remarks

Use this method to return an IEnumerator interface that allows you to iterate through the event classes in an EventClassEnumeration object. An initialized EventClassEnumeration object represents the collection of event classes in a specified Notification Services application.

Example
[Visual Basic .NET, C#]

The following examples show how to use an EventClassEnumeration object to iterate through a set of event classes. The GetEnumerator method makes the For Each and foreach statements possible:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an EventClassEnumeration object.
Dim myEventClassEnumeration As New Microsoft.SqlServer.NotificationServices.EventClassEnumeration(myApplication)

'Iterate through the event classes.
Dim eventClass As Microsoft.SqlServer.NotificationServices.EventClass
For Each eventClass In myEventClassEnumeration
   Console.WriteLine("Event Class Name: {0}", eventClass.EventClassName)
Next eventClass
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);
//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an EventClassEnumeration object.
Microsoft.SqlServer.NotificationServices.EventClassEnumeration myEventClassEnumeration = new Microsoft.SqlServer.NotificationServices.EventClassEnumeration(myApplication);

//Iterate through the event classes.
foreach (Microsoft.SqlServer.NotificationServices.EventClass eventClass in myEventClassEnumeration)
{
   Console.WriteLine("Event Class Name: {0}", eventClass.EventClassName);
}
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

EventClassEnumeration.Initialize Method

Initializes an object of the EventClassEnumeration class.

[Visual Basic .NET]
Public Sub Initialize(ByVal application As NSApplication)
[C#]
public void Initialize(NSApplication application);
[C++]
public: void Initialize(NSApplication application);
[JScript]
public function Initialize(application : NSApplication);
Parameters

application

An NSApplication object that represents the Notification Services application containing the event classes to be enumerated by this EventClassEnumeration object.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on an EventClassEnumeration object created with the parameter-less constructor.

Example

The following example shows how to create and initialize an EventClassEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, myEventClassEnumeration

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize an EventClassEnumeration object.
set myEventClassEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.EventClassEnumeration")
myEventClassEnumeration.Initialize myApplication
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


EventCollector Class

Collects events into batches, and then writes them to the application database.

For a list of all members of this type, see EventCollector Members.

System.MarshalByRefObject

Microsoft.SqlServer.NotificationServices.EventCollector
[Visual Basic .NET]
NonInheritable Public Class EventCollector Implements MarshalByRefObject, IEventCollector, IDisposable
[C#]
public sealed class EventCollector : MarshalByRefObject, IEventCollector, IDisposable
[C++]
public __gc __sealed class EventCollector : public MarshalByRefObject, IEventCollector, IDisposable
[JScript]
public class EventCollector implements MarshalByRefObject, IEventCollector, IDisposable
Remarks

Once you have created an Event object and populated it with event data, you submit it to an EventCollector object, using the EventCollector.Write method. You create an Event object, then populate and submit it once for each event record that you want to create. The EventCollector object then gathers the events written to it into a batch, and adds the event batch to the application database when the Commit method is called. The EventCollector is reinitialized to create a new event batch following a Commit call.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

EventCollector Members

Microsoft.SqlServer.NotificationServices Namespace


EventCollector Members

Public Constructors
EventCollector Constructor Overloaded. Creates a new object of the EventCollector class.
Public Methods
Abort | Discards the current event batch and all event data associated with it.
Commit | Submits an event batch to the application database.
Dispose | Disposes of the EventCollector object. Releases all resources allocated for it and leaves it unusable. Discards any event data that has been written to the EventCollector since the last Commit call.
Initialize | Initializes an object of the EventCollector class with an event provider name and a reference to an NSApplication object.
Write | Writes one event, encapsulated as an Event object, to the EventCollector object.

See Also

EventCollector Class

Microsoft.SqlServer.NotificationServices Namespace


EventCollector Constructor

Creates a new object of the EventCollector class.

Overload List

Creates an uninitialized object of the EventCollector class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public EventCollector();

[C++]

public: EventCollector();

[JScript]

public function EventCollector();

Creates a new object of the EventCollector class, and initializes it with a reference to an NSApplication object and an event provider name.

[Visual Basic .NET]

Public Sub New(NSApplication, String)

[C#]

public EventCollector(NSApplication, string);

[C++]

public: EventCollector(NSApplication, String*);

[JScript]

public function EventCollector(NSApplication, String);

See Also

EventCollector Members

Microsoft.SqlServer.NotificationServices Namespace


EventCollector Constructor ()

Creates an uninitialized object of the EventCollector class.

[Visual Basic .NET]
Public Sub New()
[C#]
public EventCollector();
[C++]
public: EventCollector();
[JScript]
public function EventCollector();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with an event provider name and a reference to an NSApplication object before it can be used.

Example

The following example shows how to create and initialize an EventCollector object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, myEventCollector

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const eventProviderName = "MyEventProviderName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize an EventCollector object.
set myEventCollector = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.EventCollector")
myEventCollector.Initialize myApplication, eventProviderName
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventCollector Members

Microsoft.SqlServer.NotificationServices Namespace


EventCollector Constructor (NSApplication, String)

Creates and initializes a new object of the EventCollector class.

[Visual Basic .NET]
Public Sub New(ByVal application As NSApplication, ByVal eventProviderName As String)
[C#]
public EventCollector(NSApplication application, string eventProviderName);
[C++]
public: EventCollector(NSApplication application, String* eventProviderName);
[JScript]
public function EventCollector(application : NSApplication, eventProviderName : String);
Parameters

application

An NSApplication object that represents the Notification Services application to which this EventCollector submits events. Provided so that event statistics for the given event provider can be collected.

eventProviderName

A string containing the name of the event provider that hosts this EventCollector object.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize an EventCollector object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventProviderName As String = "MyEventProviderName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an EventCollector object.
Dim myEventCollector As New Microsoft.SqlServer.NotificationServices.EventCollector(myApplication, eventProviderName)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventProviderName = "MyEventProviderName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an EventCollector object.
Microsoft.SqlServer.NotificationServices.EventCollector myEventCollector = new Microsoft.SqlServer.NotificationServices.EventCollector(myApplication, eventProviderName);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventCollector Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

EventCollector Methods

Public Methods
Abort | Discards the current event batch and all event data associated with it.
Commit | Submits an event batch to the application database.
Dispose | Disposes of the EventCollector object. Releases all resources allocated for it and leaves it unusable. Discards any event data that has been written to the EventCollector since the last Commit call.
Initialize | Initializes an object of the EventCollector class with an event provider name and a reference to an NSApplication object.
Write | Writes one event, encapsulated as an Event object, to the EventCollector object.

See Also

EventCollector Members

Microsoft.SqlServer.NotificationServices Namespace


Abort Method

 SQL Server Notification Services Books Online

EventCollector.Abort Method

Discards the current event batch and all event data associated with it.

[Visual Basic .NET]
Public Sub Abort()
[C#]
public void Abort();
[C++]
public: void Abort();
[JScript]
public function Abort();
Remarks

An event provider calls the EventCollector.Write method to submit an event (encapsulated as an Event object) to an EventCollector object. The EventCollector gathers all submitted events into an event batch. The event batch is submitted to the Notification Services application database for processing when the event provider calls the EventCollector.Commit method.

The EventCollector creates a new event batch when the event provider first calls Write, and then again on the first Write call after an Abort or Commit call.

An event provider can force the current batch to be discarded by calling the EventCollector.Abort method.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Abort method to discard an event batch:

[Visual Basic .NET]
Try
   'Add event batch processing code here.
Catch e As System.Exception
   'Discard the event batch if there is an error.
   myEventCollector.Abort()
End Try
[C#]
try
{
   //Add event batch processing code here.
}
catch (System.Exception e)
{
   //Discard the event batch if there is an error.
   myEventCollector.Abort();
}
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventCollector Members

Microsoft.SqlServer.NotificationServices Namespace


Commit Method

 SQL Server Notification Services Books Online

EventCollector.Commit Method

Submits an event batch to the application database.

[Visual Basic .NET]
Public Function Commit() As Integer
[C#]
public int Commit();
[C++]
public: int Commit();
[JScript]
public function Commit() : int;
Return Value

An integer specifying how many events have been submitted in this Commit call.

Remarks

An event provider calls the EventCollector.Write method to submit an event (encapsulated as an Event object) to an EventCollector object. The EventCollector gathers all submitted events into an event batch. The event batch is submitted to the Notification Services application database for processing when the event provider calls the EventCollector.Commit method.

The EventCollector creates a new event batch when the event provider first calls Write, and then again on the first Write call after an Abort or Commit call.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Commit method to commit an event batch:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"
Dim eventProviderName As String = "MyEventProviderName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an Event object.
Dim myEvent As New Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName)

'Create an EventCollector object.
Dim myEventCollector As New Microsoft.SqlServer.NotificationServices.EventCollector(myApplication, eventProviderName)

'Add code to collect event information here.

'Commit the event batch to the application database.
Dim eventsWritten As Integer = myEventCollector.Commit()
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";
string eventProviderName = "MyEventProviderName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an Event object.
Microsoft.SqlServer.NotificationServices.Event myEvent = new Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName);

//Create an EventCollector object.
Microsoft.SqlServer.NotificationServices.EventCollector myEventCollector = new Microsoft.SqlServer.NotificationServices.EventCollector(myApplication, eventProviderName);

//Add code to collect event information here.

//Commit the event batch to the application database.
int eventsWritten = myEventCollector.Commit();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventCollector Members

Microsoft.SqlServer.NotificationServices Namespace


Dispose Method

 SQL Server Notification Services Books Online

EventCollector.Dispose Method

Disposes of the EventCollector object.

[Visual Basic .NET]
Public Sub Dispose()
[C#]
public void Dispose();
[C++]
public: void Dispose();
[JScript]
public function Dispose();
Remarks

Calling this method releases all resources allocated for the EventCollector object, and leaves it unusable. Any event data that has been written to the EventCollector since the last Commit call is discarded.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Dispose method to dispose of an EventCollector object:

[Visual Basic .NET]
Try
   'Add event batch processing code here.
Catch e As System.Exception
   'Add error handling code here.
Finally
   'Dispose of the EventCollector object.
   myEventCollector.Dispose()
End Try
[C#]
try
{
   //Add event batch processing code here.
}
catch (System.Exception e)
{
   //Add error handling code here.
}
finally
{
   //Dispose of the EventCollector object.
   myEventCollector.Dispose();
}
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventCollector Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

EventCollector.Initialize Method

Initializes an object of the EventCollector class.

[Visual Basic .NET]
Public Sub Initialize(ByVal application As NSApplication, ByVal eventProviderName As String)
[C#]
public void Initialize(NSApplication application, string eventProviderName);
[C++]
public: void Initialize(NSApplication application, String* eventProviderName);
[JScript]
public function Initialize(application : NSApplication, eventProviderName : String);
Parameters

application

An NSApplication object that represents the Notification Services application to which this EventCollector submits events. Provided so that event statistics for the given event provider can be collected.

eventProviderName

A string containing the name of the event provider that hosts this EventCollector object.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on an EventCollector object created with the parameter-less constructor.

Example

The following example shows how to create and initialize an EventCollector object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, myEventCollector

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const eventProviderName = "MyEventProviderName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize an EventCollector object.
set myEventCollector = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.EventCollector")
myEventCollector.Initialize myApplication, eventProviderName
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventCollector Members

Microsoft.SqlServer.NotificationServices Namespace


Write Method

 SQL Server Notification Services Books Online

EventCollector.Write Method

Writes one event to the EventCollector.

[Visual Basic .NET]
Public Function Write(ByVal event As Object) As Integer
[C#]
public int Write(object event);
[C++]
public: int Write(Object* event);
[JScript]
public function Write(event : Object) : int;
Parameters

eventClass

An Event object that encapsulates the data for a single event.

Exceptions
Exception Type | Condition
NSException with an NSEventEnum.InvalidField argument | One of the fields in the event data fails to meet a database requirement or a constraint (such as a column data type).
NSException with an NSEventEnum.MissingField argument | One of the fields in the event data fails to meet a NOT NULL requirement in the event table.
Remarks

An event provider calls the EventCollector.Write method to submit an event (encapsulated as an Event object) to an EventCollector object. The EventCollector gathers all submitted events into an event batch. The event batch is submitted to the Notification Services application database for processing when the event provider calls the EventCollector.Commit method.

The EventCollector creates a new event batch when the event provider first calls Write, and then again on the first Write call after an Abort or Commit call.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Write method to dispose of an EventCollector object:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"
Dim eventProviderName As String = "MyEventProviderName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an Event object.
Dim myEvent As New Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName)

'Create an EventCollector object.
Dim myEventCollector As New Microsoft.SqlServer.NotificationServices.EventCollector(myApplication, eventProviderName)

'Add code here to populate the Event object.

'Use the Write method to write the event to the EventCollector.
myEventCollector.Write(myEvent)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";
string eventProviderName = "MyEventProviderName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an Event object.
Microsoft.SqlServer.NotificationServices.Event myEvent = new Microsoft.SqlServer.NotificationServices.Event(myApplication, eventClassName);

//Create an EventCollector object.
Microsoft.SqlServer.NotificationServices.EventCollector myEventCollector = new Microsoft.SqlServer.NotificationServices.EventCollector(myApplication, eventProviderName);

//Add code here to populate the Event object.

//Use the Write method to write the event to the EventCollector.
myEventCollector.Write(myEvent);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventCollector Members

Microsoft.SqlServer.NotificationServices Namespace


EventLoader Class

Provides a way to submit XML documents as events.

For a list of all members of this type, see EventLoader Members.

System.MarshalByRefObject

Microsoft.SqlServer.NotificationServices.EventLoader
[Visual Basic .NET]
NonInheritable Public Class EventLoader Implements MarshalByRefObject, IDisposable
[C#]
public sealed class EventLoader : MarshalByRefObject, IDisposable
[C++]
public __gc __sealed class EventLoader : public MarshalByRefObject, IDisposable
[JScript]
public class EventLoader implements MarshalByRefObject, IDisposable
Remarks

An EventLoader object is used to write XML data from files or Stream objects to the notification application.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

EventLoader Members

Microsoft.SqlServer.NotificationServices Namespace


EventLoader Members

Public Constructors
EventLoader Constructor Overloaded. Creates a new object of the EventLoader class.
Public Properties
EventSchema Sets the SQL-annotated XML schema file that allows you to convert the event data from the XML document format to the event class format.
Public Methods
Dispose | Disposes of the EventLoader object. Releases all resources allocated for it and leaves it unusable.
Initialize | Initializes an object of the EventLoader class.
LoadXml | Overloaded. Submits the contents of an XML document to the application database.

See Also

EventLoader Class

Microsoft.SqlServer.NotificationServices Namespace


EventLoader Constructor

Creates a new object of the EventLoader class.

Overload List

Creates an uninitialized object of the EventLoader class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public EventLoader();

[C++]

public: EventLoader();

[JScript]

public function EventLoader();

Creates a new object of the EventLoader class, and initializes it with a reference to an NSApplication object, an event provider name, an event class name, and a reference to an SQL-annotated XML schema file.

[Visual Basic .NET]

Public Sub New(NSApplication, String, String, String)

[C#]

public EventLoader(NSApplication, string, string, string);

[C++]

public: EventLoader(NSApplication, String*, String*, String*);

[JScript]

public function EventLoader(NSApplication, String, String, String);

See Also

EventLoader Members

Microsoft.SqlServer.NotificationServices Namespace


EventLoader Constructor ()

Creates an uninitialized object of the EventLoader class.

[Visual Basic .NET]
Public Sub New()
[C#]
public EventLoader();
[C++]
public: EventLoader();
[JScript]
public function EventLoader();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with a reference to an NSApplication object, an event provider name, an event class name, and a reference to an SQL-annotated XML schema file before it can be used.

Example

The following example shows how to create and initialize an EventLoader object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, myEventLoader

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const eventProviderName = "MyEventProviderName"
const eventClassName = "MyEventClassName"
const schemaFile = "MySchemaFilePathAndName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize an EventLoader object.
set myEventLoader = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.EventLoader")
myEventLoader.Initialize myApplication, eventProviderName, eventClassName, schemaFile
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventLoader Members

Microsoft.SqlServer.NotificationServices Namespace


EventLoader Constructor (NSApplication, String, String, String)

Creates and initializes an object of the EventLoader class.

[Visual Basic .NET]
Public Sub New(ByVal application As NSApplication, ByVal eventProviderName As _ String, ByVal eventClassName As String, ByVal eventSchema As String)
[C#]
public EventLoader(NSApplication application, string eventProviderName, string eventClassName, string eventSchema);
[C++]
public: EventLoader(NSApplication application, String* eventProviderName, String* eventClassName, String* eventSchema);
[JScript]
public function EventLoader(application : NSApplication, eventProviderName : String, eventClassName : String, eventSchema : String);
Parameters

application

An NSApplication object that represents the Notification Services application to which this EventLoader submits events.

eventProviderName

A string containing the name of the event provider that hosts this EventLoader object.

eventClassName

The event class that defines the structure of the events that this EventLoader submits.

eventSchema

A string representing the path and name of an SQL-annotated XML schema file. This schema file must contain the event class schema, and is used to convert the event data in the XML document to the expected format.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize an EventLoader object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"
Dim eventProviderName As String = "MyEventProviderName"
Dim eventSchema As String = "MySchemaFilePathAndName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an EventLoader object.
Dim myEventLoader As New Microsoft.SqlServer.NotificationServices.EventLoader(myApplication, eventProviderName, eventClassName, eventSchema)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";
string eventProviderName = "MyEventProviderName";
string eventSchema = "MySchemaFilePathAndName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an EventLoader object.
Microsoft.SqlServer.NotificationServices.EventLoader myEventLoader = new Microsoft.SqlServer.NotificationServices.EventLoader(myApplication, eventProviderName, eventClassName, eventSchema);

See Also

EventLoader Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

EventLoader Properties

Public Properties
EventSchema Sets the SQL-annotated XML schema file that allows you to convert the event data from the XML document format to the event class format.

See Also

EventLoader Members

Microsoft.SqlServer.NotificationServices Namespace


EventSchema Property

 SQL Server Notification Services Books Online

EventLoader.EventSchema Property

Sets the event schema for the EventLoader object.

[Visual Basic .NET]
Public Property EventSchema
[C#]
public void EventSchema {set;}
[C++]
public: __property void set_EventSchema();
[JScript]
public function set EventSchema();
Remarks

This property expects a string representing the path and name of an SQL-annotated XML schema file. This schema file must contain the event class schema, and is used to convert the event data in the XML document to the expected format.

Event schema example
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
   <xsd:element name="event" sql:relation="MyEventClassName">
      <xsd:complexType>
         <xsd:sequence>
            <xsd:element name="StockSymbol" type="xsd:string" />
            <xsd:element name="StockPrice" type="xsd:float" />
         </xsd:sequence>
      </xsd:complexType>
   </xsd:element>
</xsd:schema>
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventLoader Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

EventLoader Methods

Public Methods
Dispose | Disposes of the EventLoader object. Releases all resources allocated for it and leaves it unusable.
Initialize | Initializes an object of the EventLoader class.
LoadXml | Overloaded. Submits the contents of an XML document to the application database.

See Also

EventLoader Members

Microsoft.SqlServer.NotificationServices Namespace


Dispose Method

 SQL Server Notification Services Books Online

EventLoader.Dispose Method

Disposes of the EventLoader object.

[Visual Basic .NET]
Public Sub Dispose()
[C#]
public void Dispose();
[C++]
public: void Dispose();
[JScript]
public function Dispose();
Remarks

Calling this method releases all resources allocated for the EventLoader object, and leaves it unusable.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Dispose method to dispose of an EventLoader object:

[Visual Basic .NET]
Try
   'Add code to process event information here.
Catch e As System.Exception
   'Add code to handle errors here.
Finally
   'Dispose of the EventLoader object.
   myEventLoader.Dispose()
End Try
[C#]
try
{
   //Add code to process event information here.
}
catch (System.Exception e)
{
   //Add code to handle errors here.
}
finally
{
   //Dispose of the EventLoader object.
   myEventLoader.Dispose();
}
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventLoader Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

EventLoader.Initialize Method

Initializes an object of the EventLoader class.

[Visual Basic .NET]
Public Sub Initialize(ByVal application As NSApplication, ByVal eventProviderName As _ String, ByVal eventClassName As String, ByVal eventSchema As String)
[C#]
public void Initialize(NSApplication application, string eventProviderName, string eventClassName, string eventSchema);
[C++]
public: void Initialize(NSApplication application, String* eventProviderName, String* eventClassName, String* eventSchema);
[JScript]
public function Initialize(application : NSApplication, eventProviderName : String, eventClassName : String, eventSchema : String);
Parameters

application

An NSApplication object that represents the Notification Services application to which this EventLoader object submits events.

eventProviderName

A string containing the name of the event provider that hosts this EventLoader object.

eventClassName

The event class that defines the structure of the events that this EventLoader object submits.

eventSchema

A string representing the path and name of an SQL-annotated XML schema file. This schema file must contain the event class schema, and is used to convert the event data in the XML document to the expected format.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on an EventLoader object created with the parameter-less constructor.

Example

The following example shows how to create and initialize an EventLoader object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, myEventLoader

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const eventProviderName = "MyEventProviderName"
const eventClassName = "MyEventClassName"
const schemaFile = "MySchemaFilePathAndName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize an EventLoader object.
set myEventLoader = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.EventLoader")
myEventLoader.Initialize myApplication, eventProviderName, eventClassName, schemaFile
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventLoader Members

Microsoft.SqlServer.NotificationServices Namespace


LoadXml Method

 SQL Server Notification Services Books Online

EventLoader.LoadXml Method

Submits the contents of an XML document to the application database.

Overload List

Submits the contents of an XML file to the application database.

[Visual Basic .NET]

Public Function LoadXml(String) As Integer

[C#]

public int LoadXml(string);

[C++]

public: int LoadXml(String*);

[JScript]

public function LoadXml(String) : int;

Submits the contents of an XML Stream object to the application database.

[Visual Basic .NET]

Public Function LoadXml(Stream) As Integer

[C#]

public int LoadXml(Stream);

[C++]

public: int LoadXml(Stream);

[JScript]

public function LoadXml(Stream) : int;

See Also

EventLoader Members

Microsoft.SqlServer.NotificationServices Namespace


LoadXml Method (String)

 SQL Server Notification Services Books Online
EventLoader.LoadXml Method (String)

Submits the contents of an XML file to the application database.

[Visual Basic .NET]
Public Function LoadXml(ByVal eventDoc As String) As Integer
[C#]
public int LoadXml(string eventDoc);
[C++]
public: int LoadXml(String* eventDoc);
[JScript]
public function LoadXml(eventDoc : String) : int;
Parameters

eventDoc

A string representing the path and name of the XML file that contains the event data to be loaded.

Return Value

An integer specifying how many events have been submitted in this LoadXml call.

Example
[Visual Basic .NET, C#]

The following examples show how to use the LoadXml method to submit event data from an XML file to the application database:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"
Dim eventProviderName As String = "MyEventProviderName"
Dim eventSchema As String = "MySchemaFilePathAndName"
Dim myXmlFile As String = "MyXMLFilePathAndName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an EventLoader object.
Dim myEventLoader As New Microsoft.SqlServer.NotificationServices.EventLoader(myApplication, eventProviderName, eventClassName, eventSchema)

'Use the LoadXml method to load an XML document.
Dim eventsWritten As Integer = myEventLoader.LoadXml(myXmlFile)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";
string eventProviderName = "MyEventProviderName";
string eventSchema = "MySchemaFilePathAndName";
string myXmlFile = "MyXMLFilePathAndName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an EventLoader object.
Microsoft.SqlServer.NotificationServices.EventLoader myEventLoader = new Microsoft.SqlServer.NotificationServices.EventLoader(myApplication, eventProviderName, eventClassName, eventSchema);

//Use the LoadXml method to load an XML document.
int eventsWritten = myEventLoader.LoadXml(myXmlFile);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventLoader Members

Microsoft.SqlServer.NotificationServices Namespace


LoadXml Method (Stream)

 SQL Server Notification Services Books Online
EventLoader.LoadXml Method (Stream)

Submits the contents of a Stream object to the application database.

[Visual Basic .NET]
Public Function LoadXml(ByVal eventStream As Stream) As Integer
[C#]
public int LoadXml(Stream eventStream);
[C++]
public: int LoadXml(Stream eventStream);
[JScript]
public function LoadXml(eventStream : Stream) : int;
Parameters

eventStream

A Stream object containing the XML event data to be loaded.

Return Value

An integer specifying how many events have been submitted in this LoadXml call.

Remarks

This method can take an object of any of the classes that inherit from the System.IO.Stream class as its input parameter. However, not all of these classes are truly applicable. The classes that are compatible with this method are:

  • BufferedStream
  • FileStream
  • MemoryStream

The Stream class itself is abstract, which means that it cannot be used directly. Instead, it serves as a base class from which other classes can be derived.

Example
[Visual Basic .NET, C#]

The following examples show how to use the LoadXml method to submit XML event data from a Stream object to the application database:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim eventClassName As String = "MyEventClassName"
Dim eventProviderName As String = "MyEventProviderName"
Dim eventSchema As String = "MySchemaFilePathAndName"
Dim myXmlFile As String = "MyXMLFilePathAndName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create an EventLoader object.
Dim myEventLoader As New Microsoft.SqlServer.NotificationServices.EventLoader(myApplication, eventProviderName, eventClassName, eventSchema)

'Use the LoadXml method to load an XML document.
Dim myStream As New System.IO.FileStream(myXmlFile, System.IO.FileMode.Open)
Dim eventsWritten As Integer = myEventLoader.LoadXml(myStream)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string eventClassName = "MyEventClassName";
string eventProviderName = "MyEventProviderName";
string eventSchema = "MySchemaFilePathAndName";
string myXmlFile = "MyXMLFilePathAndName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create an EventLoader object.
Microsoft.SqlServer.NotificationServices.EventLoader myEventLoader = new Microsoft.SqlServer.NotificationServices.EventLoader(myApplication, eventProviderName, eventClassName, eventSchema);

//Use the LoadXml method to load an XML document.
System.IO.FileStream myStream = new System.IO.FileStream(myXmlFile, System.IO.FileMode.Open);
int eventsWritten = myEventLoader.LoadXml(myStream);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

EventLoader Members

Microsoft.SqlServer.NotificationServices Namespace


InstanceEnumeration Class

Represents the collection of Notification Services instances hosted on the local computer.

For a list of all members of this type, see InstanceEnumeration Members.

System.Object

Microsoft.SqlServer.NotificationServices.InstanceEnumeration
[Visual Basic .NET]
NotInheritable Public Class InstanceEnumeration
Implements IInstanceEnumeration, IEnumerable
[C#]
public sealed class InstanceEnumeration : IInstanceEnumeration, IEnumerable
[C++]
public __gc __sealed class InstanceEnumeration : public IInstanceEnumeration, IEnumerable
[JScript]
public class InstanceEnumeration implements IInstanceEnumeration, IEnumerable
Remarks

The InstanceEnumeration class allows an application to iterate through the set of Notification Services instances available on the local computer. It also provides an Item property to return information about a specific Notification Services instance as an NSInstanceDescription object.

This class is used primarily for administrative purposes and for configuring subscription management applications.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

InstanceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


InstanceEnumeration Members

Public Constructors
InstanceEnumeration Constructor Creates a new object of the InstanceEnumeration class.
Public Properties
Item Returns an NSInstanceDescription object, which provides information about the Notification Services instance identified by the specified instance name.

In C#, this property is the indexer for the InstanceEnumeration class.
Public Methods
GetEnumerator Returns an IEnumerator interface that allows you to iterate through the instances.

See Also

InstanceEnumeration Class

Microsoft.SqlServer.NotificationServices Namespace


InstanceEnumeration Constructor

Creates an object of the InstanceEnumeration class.

[Visual Basic .NET]
Public Sub New()
[C#]
public InstanceEnumeration();
[C++]
public: InstanceEnumeration();
[JScript]
public function InstanceEnumeration();
Remarks

The InstanceEnumeration constructor can be used in both managed and unmanaged code, because it does not require any parameters.

Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize an InstanceEnumeration object in managed code:

[Visual Basic .NET]
'Create an InstanceEnumeration object.
 Dim myInstanceEnumeration As New Microsoft.SqlServer.NotificationServices.InstanceEnumeration()
[C#]
//Create an InstanceEnumeration object.
Microsoft.SqlServer.NotificationServices.InstanceEnumeration myInstanceEnumeration = new Microsoft.SqlServer.NotificationServices.InstanceEnumeration();

The following example shows how to create an InstanceEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

'Create an InstanceEnumeration object.
set myInstanceEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.InstanceEnumeration")
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

InstanceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

InstanceEnumeration Properties

Public Properties
Item Returns an NSInstanceDescription object, which provides information about the Notification Services instance identified by the specified instance name.

In C#, this property is the indexer for the InstanceEnumeration class.

See Also

InstanceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property

 SQL Server Notification Services Books Online

InstanceEnumeration.Item Property

Returns a reference to a Notification Services instance description.

[C#]

In C#, this property is the indexer for the InstanceEnumeration class.

[Visual Basic .NET]
Public Property Item(ByVal instanceName As String) As NSInstanceDescription
[C#]
public NSInstanceDescription this[string instanceName] {get;}
[C++]
public: __property NSInstanceDescription get_Item(String* instanceName);
[JScript]
returnValue = InstanceEnumerationObject.Item(instanceName);
-or-
returnValue = InstanceEnumerationObject(instanceName);
Parameters

instanceName

The name of the Notification Services instance for which a description is to be returned.

Property Value

An NSInstanceDescription object, which contains descriptive information about the specified Notification Services instance.

Exceptions
Exception Type | Condition
IndexOutOfRangeException |
Example
[Visual Basic .NET, C#]

The following examples show how to use the Item property to return an NSInstanceDescription object:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an InstanceEnumeration object.
Dim myInstanceEnumeration As New Microsoft.SqlServer.NotificationServices.InstanceEnumeration()

'Use the Item property to return an NSInstanceDescription object.
Dim myInstanceDescription As Microsoft.SqlServer.NotificationServices.NSInstanceDescription = myInstanceEnumeration(instanceName)
[C#]
string instanceName = "MyInstanceName";

//Create an InstanceEnumeration object.
Microsoft.SqlServer.NotificationServices.InstanceEnumeration myInstanceEnumeration = new Microsoft.SqlServer.NotificationServices.InstanceEnumeration();

//Use the Item property to return an NSInstanceDescription object.
Microsoft.SqlServer.NotificationServices.NSInstanceDescription myInstanceDescription = myInstanceEnumeration[instanceName];
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

InstanceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

InstanceEnumeration Methods

Public Methods
GetEnumerator Returns an IEnumerator interface that allows you to iterate through the instances.

See Also

InstanceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


GetEnumerator Method

 SQL Server Notification Services Books Online

InstanceEnumeration.GetEnumerator Method

Gets an IEnumerator interface that allows you to iterate through the collection of Notification Services instance descriptions represented by the InstanceEnumeration object.

[Visual Basic .NET]
Public Function GetEnumerator() As IEnumerator Implements  IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();
[C++]
public: IEnumerator* GetEnumerator();
[JScript]
public function GetEnumerator() : IEnumerator;
Return Value

An IEnumerator interface for the InstanceEnumeration object.

Implements

IEnumerable.GetEnumerator

Remarks

You should use this method to return an IEnumerator interface that allows you to iterate through the Notification Services instance descriptions in an InstanceEnumeration object.

Example
[Visual Basic .NET, C#]

The following examples show how to use an InstanceEnumeration object to iterate through a set of Notification Services instance descriptions. The GetEnumerator method makes the For Each and foreach statements possible:

[Visual Basic .NET]
'Create an InstanceEnumeration object.
Dim myInstanceEnumeration As New Microsoft.SqlServer.NotificationServices.InstanceEnumeration()

'Iterate through the instance descriptions.
Dim instanceDescription As Microsoft.SqlServer.NotificationServices.NSInstanceDescription
For Each instanceDescription In myInstanceEnumeration
   Console.WriteLine("Instance Name: {0}", instanceDescription.InstanceName)
Next instanceDescription
[C#]
//Create an InstanceEnumeration object.
Microsoft.SqlServer.NotificationServices.InstanceEnumeration myInstanceEnumeration = new Microsoft.SqlServer.NotificationServices.InstanceEnumeration();

//Iterate through the instance descriptions.
foreach (Microsoft.SqlServer.NotificationServices.NSInstanceDescription instanceDescription in myInstanceEnumeration)
{
   Console.WriteLine("Instance Name: {0}", instanceDescription.InstanceName);
}
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

InstanceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


NotificationHeaders Class

Provides notification header information to a delivery protocol.

For a list of all members of this type, see NotificationHeaders Members.

System.Object

Microsoft.SqlServer.NotificationServices.NotificationHeaders
[Visual Basic .NET]
Public Class NotificationHeaders
[C#]
public class NotificationHeaders
[C++]
public class NotificationHeaders
[JScript]
public class NotificationHeaders
Remarks

The NotificationHeaders class contains information that the delivery protocol uses to create the notification packet (if necessary), and then route the notification message to the appropriate external delivery system.

The NotificationHeaders class has no public constructor. The distributor creates an object of this class and passes it to the DeliverNotification method of the delivery protocol.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

NotificationHeaders Members

Microsoft.SqlServer.NotificationServices Namespace


NotificationHeaders Members

Public Properties
NotificationState | Gets a NotificationState object that contains notification information.
ProtocolFields | Gets a StringDictionary object that contains the protocol field information needed to construct the notification packet.
RecipientInfo | Gets a RecipientInfo object that contains notification recipient information.

See Also

NotificationHeaders Class

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

NotificationHeaders Properties

Public Properties
NotificationState | Gets a NotificationState object that contains notification information.
ProtocolFields | Gets a StringDictionary object that contains the protocol field information needed to construct the notification packet.
RecipientInfo | Gets a RecipientInfo object that contains notification recipient information.

See Also

NotificationHeaders Class

Microsoft.SqlServer.NotificationServices Namespace


NotificationState Property

 SQL Server Notification Services Books Online

NotificationHeaders.NotificationState Property

Gets a NotificationState object that contains notification information.

[Visual Basic .NET]
Public Property NotificationState As NotificationState
[C#]
public NotificationState NotificationState {get;}
[C++]
public: __property NotificationState get_NotificationState();
[JScript]
public function get NotificationState() : NotificationState;
Property Value

A NotificationState object that contains notification information.

Remarks

The NotificationState object is passed to the delivery protocol for the express purpose of being passed back again as part of the notification delivery status information in a NotificationStatus object. The information contained in the NotificationState object is not used within the delivery protocol.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NotificationHeaders Class

Microsoft.SqlServer.NotificationServices Namespace


ProtocolFields Property

 SQL Server Notification Services Books Online

NotificationHeaders.ProtocolFields Property

Gets a StringDictionary object that contains the protocol field information needed to construct the notification packet.

[Visual Basic .NET]
Public Property ProtocolFields As StringDictionary
[C#]
public StringDictionary ProtocolFields {get;}
[C++]
public: __property StringDictionary get_ProtocolFields();
[JScript]
public function get ProtocolFields() : StringDictionary;
Property Value

A StringDictionary object that contains the protocol field information needed to construct the notification packet. The list of protocol fields is drawn from the /NotificationClasses/NotificationClass/Protocols/Protocol/Fields section of the application definition file (ADF). The values for these fields are derived from the notification data.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NotificationHeaders Class

Microsoft.SqlServer.NotificationServices Namespace


RecipientInfo Property

 SQL Server Notification Services Books Online

NotificationHeaders.RecipientInfo Property

Gets a RecipientInfo object that contains notification recipient information.

[Visual Basic .NET]
Public Property RecipientInfo As RecipientInfo
[C#]
public RecipientInfo RecipientInfo {get;}
[C++]
public: __property RecipientInfo get_RecipientInfo();
[JScript]
public function get RecipientInfo() : RecipientInfo;
Property Value

A RecipientInfo object that contains notification recipient information.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NotificationHeaders Class

Microsoft.SqlServer.NotificationServices Namespace


NotificationStatus Class

Provides notification delivery status information to the distributor.

For a list of all members of this type, see NotificationStatus Members.

System.Object

Microsoft.SqlServer.NotificationServices.NotificationStatus
[Visual Basic .NET]
NonInheritable Public Class NotificationStatus
[C#]
public sealed class NotificationStatus
[C++]
public __gc __sealed class NotificationStatus
[JScript]
public class NotificationStatus
Remarks

The NotificationStatus class is used by the delivery protocol component to pass notification delivery status information back to the distributor. This is done by passing an array of NotificationStatus objects to the NotificationStatusCallback delegate.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

NotificationStatus Members

Microsoft.SqlServer.NotificationServices Namespace


NotificationStatus Members

Public Constructors
NotificationStatus Constructor Creates a new object of the NotificationStatus class.
Public Properties
NotificationState | Gets a NotificationState object that contains notification information that must be passed back to the distributor.
NotificationText | Gets the notification text of the notification.
StatusInfo | Gets detailed delivery status information about the notification.
Succeeded | Gets a Boolean value indicating whether the notification has been delivered successfully.
TimeStamp | Gets the date and time, in Universal Time Coordinate (UTC) format, of notification delivery.

See Also

NotificationStatus Class

Microsoft.SqlServer.NotificationServices Namespace


NotificationStatus Constructor

Creates an object of the NotificationStatus class, and initializes it with references to a NotificationState object, a Boolean value indicating whether the delivery was a success, the delivery status, the notification text, and the delivery date and time. The notification delivery time information must be provided in Universal Time Coordinate (UTC) format.

[Visual Basic .NET]
Public Sub New(ByVal notificationState As NotificationState, ByVal succeeded As Boolean, ByVal statusInfo As String, ByVal notificationText As String, ByVal timeStamp As Object)
[C#]
public NotificationStatus(NotificationState notificationState, bool succeeded, string statusInfo, string notificationText, object timeStamp);
[C++]
public: NotificationStatus(NotificationState notificationState, bool succeeded, String* statusInfo, String* notificationText, Object* timeStamp);
[JScript]
public function NotificationStatus(notificationState : NotificationState, succeeded : Boolean, statusInfo : String, notificationText : String, timeStamp : Object);
Parameters

notificationState

A NotificationState object that contains notification information needed by the distributor to correctly interpret the delivery status information. The NotificationState object is passed to the delivery protocol in the DeliverNotification method, as part of the NotificationHeaders object.

succeeded

A Boolean value that indicates whether the notification was successfully delivered. Can be null if not required.

statusInfo

A string containing any additional notification status information. Can be null or a zero-length string if the value is not required.

notificationText

A string containing the formatted notification data that the delivery protocol tried to deliver. Can be null or a zero-length string if the value is not required.

timeStamp

An object representing the time of the delivery attempt. Can be null if not required.

Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize a NotificationStatus object in managed code:

[Visual Basic .NET]
Imports Microsoft.SqlServer.NotificationServices

Private Function CreateStatus(ByVal header As NotificationHeaders, ByVal successfulDelivery As Boolean, ByVal body As String, ByVal failureException As NSException, ByVal notifState As NotificationState) As NotificationStatus

   Dim timeStamp As Object = DateTime.UtcNow
   Dim notification As NotificationHeaders = header
   Dim statusInfo As String = ""
   Dim notificationText As String = ""

   If Not (failureException Is Nothing) Then
      statusInfo = failureException.Message
      notificationText = body
   End If

   Dim status As New NotificationStatus(notifState, successfulDelivery, statusInfo, notificationText, timeStamp)
   Return status

End Function 'CreateStatus
[C#]
using Microsoft.SqlServer.NotificationServices;

private NotificationStatus CreateStatus(NotificationHeaders header, bool successfulDelivery, string body, NSException failureException, NotificationState notifState)
{
   object timeStamp = DateTime.UtcNow;
   NotificationHeaders notification = header;
   string statusInfo = "";
   string notificationText = "";

   if (failureException != null)
   {
      statusInfo = failureException.Message;
      notificationText = body;
   }

   NotificationStatus status = new NotificationStatus(notifState, successfulDelivery, statusInfo, notificationText, timeStamp);
   return status;
}
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NotificationStatus Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

NotificationStatus Properties

Public Properties
NotificationState | Gets a NotificationState object that contains notification information that must be passed back to the distributor.
NotificationText | Gets the notification text of the notification.
StatusInfo | Gets detailed delivery status information about the notification.
Succeeded | Gets a Boolean value indicating whether the notification has been delivered successfully.
TimeStamp | Gets the date and time, in Universal Time Coordinate (UTC) format, of notification delivery.

See Also

NotificationStatus Members

Microsoft.SqlServer.NotificationServices Namespace


NotificationState Property

 SQL Server Notification Services Books Online

NotificationStatus.NotificationState Property

Gets a NotificationState object that contains notification information that must be passed back to the distributor.

[Visual Basic .NET]
Public Property NotificationState As NotificationState
[C#]
public NotificationState NotificationState {get;}
[C++]
public: __property NotificationState get_NotificationState();
[JScript]
public function get NotificationState() : NotificationState;
Property Value

A NotificationState object that contains notification information that must be passed back to the distributor.

Remarks

The NotificationState object is passed to the delivery protocol in the DeliverNotification method, as part of the NotificationHeaders object. NotificationState is passed to the delivery protocol for the express purpose of being passed back again as part of the notification delivery status information in a NotificationStatus object. The information contained in NotificationState is not used within the delivery protocol; the object must just be copied from NotificationHeaders to th NotificationStatus.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NotificationStatus Members

Microsoft.SqlServer.NotificationServices Namespace


NotificationText Property

 SQL Server Notification Services Books Online

NotificationStatus.NotificationText Property

Gets the notification text of the notification.

[Visual Basic .NET]
Public Property NotificationText As String
[C#]
public string NotificationText {get;}
[C++]
public: __property String* get_NotificationText();
[JScript]
public function get NotificationText() : String;
Property Value

A string containing the formatted notification data that the delivery protocol tried to deliver.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NotificationStatus Members

Microsoft.SqlServer.NotificationServices Namespace


StatusInfo Property

 SQL Server Notification Services Books Online

NotificationStatus.StatusInfo Property

Gets the detailed delivery status information about the notification.

[Visual Basic .NET]
Public Property StatusInfo As String
[C#]
public string StatusInfo {get;}
[C++]
public: __property String* get_StatusInfo();
[JScript]
public function get StatusInfo() : String;
Property Value

A string containing any additional notification status information.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NotificationStatus Members

Microsoft.SqlServer.NotificationServices Namespace


Succeeded Property

 SQL Server Notification Services Books Online

NotificationStatus.Succeeded Property

Indicates whether the notification has been delivered successfully.

[Visual Basic .NET]
Public Property Succeeded As Boolean
[C#]
public bool Succeeded {get;}
[C++]
public: __property bool get_Succeeded();
[JScript]
public function get Succeeded() : Boolean;
Property Value

A Boolean value that indicates whether the notification was successfully delivered.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NotificationStatus Members

Microsoft.SqlServer.NotificationServices Namespace


TimeStamp Property

 SQL Server Notification Services Books Online

NotificationStatus.TimeStamp Property

Gets the date and time, in Universal Time Coordinate (UTC) format, that the notification was delivered.

[Visual Basic .NET]
Public Property TimeStamp As Object
[C#]
public object TimeStamp {get;}
[C++]
public: __property Object* get_TimeStamp();
[JScript]
public function get TimeStamp() : Object;
Property Value

An object representing the time of the delivery attempt.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NotificationStatus Members

Microsoft.SqlServer.NotificationServices Namespace


NSApplication Class

Represents a Notification Services application.

For a list of all members of this type, see NSApplication Members.

Microsoft.SqlServer.NotificationServices.Common.NSDBState

Microsoft.SqlServer.NotificationServices.NSApplication
[Visual Basic .NET]
Public Class NSApplication Implements INSApplication
[C#]
public class NSApplication : INSApplication
[C++]
public class NSApplication : public INSApplication
[JScript]
public class NSApplication implements INSApplication
Remarks

An NSApplication object represents a specific Notification Services application. Many Notification Services classes require a reference to an NSApplication object in order to be initialized.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

NSApplication Members

Microsoft.SqlServer.NotificationServices Namespace


NSApplication Members

Public Constructors
NSApplication Constructor Overloaded. Creates a new object of the NSApplication class.
Public Properties
ApplicationName | Gets the name of the Notification Services application.
DatabaseName | Gets the name of the Notification Services application database.
Version | Gets the version of the Notification Services application.
Public Methods
Initialize | Initializes an object of the NSApplication class.
Verify | Verifies the ApplicationName and Version properties of the Notification Services application.

See Also

NSApplication Class

Microsoft.SqlServer.NotificationServices Namespace


NSApplication Constructor

Creates a new object of the NSApplication class.

Overload List

Creates an uninitialized object of the NSApplication class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public NSApplication();

[C++]

public: NSApplication();

[JScript]

public function NSApplication();

Creates a new object of the NSApplication class, and initializes it with a reference to an NSInstance object and the application name.

[Visual Basic .NET]

Public Sub New(NSInstance, String)

[C#]

public NSApplication(NSInstance, string);

[C++]

public: NSApplication(NSInstance, String*);

[JScript]

public function NSApplication(NSInstance, String);

See Also

NSApplication Members

Microsoft.SqlServer.NotificationServices Namespace


NSApplication Constructor ()

Creates an uninitialized object of the NSApplication class.

[Visual Basic .NET]
Public Sub New()
[C#]
public NSApplication();
[C++]
public: NSApplication();
[JScript]
public function NSApplication();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with an application name and a reference to an NSInstance object before it can be used.

Example

The following example shows how to create and initialize an NSApplication object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSApplication Members

Microsoft.SqlServer.NotificationServices Namespace


NSApplication Constructor (NSInstance, String)

Creates and initializes a new object of the NSApplication class.

[Visual Basic .NET]
Public Sub New(ByVal instance As NSInstance, ByVal applicationName As String)
[C#]
public NSApplication(NSInstance instance, string applicationName);
[C++]
public: NSApplication(NSInstance instance, String* applicationName);
[JScript]
public function NSApplication(instance : NSInstance, applicationName : String);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing this application.

applicationName

A string containing the name of the application.

Exceptions
Exception Type | Condition
ArgumentNullException | The applicationName or instance argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize an NSApplication object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSApplication Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

NSApplication Properties

Public Properties
ApplicationName | Gets the name of the Notification Services application.
DatabaseName | Gets the name of the Notification Services application database.
Version | Gets the version of the Notification Services application.

See Also

NSApplication Members

Microsoft.SqlServer.NotificationServices Namespace


ApplicationName Property

 SQL Server Notification Services Books Online

NSApplication.ApplicationName Property

Gets the name of the Notification Services application.

[Visual Basic .NET]
Public Property ApplicationName As String
[C#]
public string ApplicationName {get;}
[C++]
public: __property String* get_ApplicationName();
[JScript]
public function get ApplicationName() : String;
Property Value

A string containing the name of the Notification Services application.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSApplication Members

Microsoft.SqlServer.NotificationServices Namespace


DatabaseName Property

 SQL Server Notification Services Books Online

NSApplication.DatabaseName Property

Gets the name of the Notification Services application database.

[Visual Basic .NET]
Public Property DatabaseName As String
[C#]
public string DatabaseName {get;}
[C++]
public: __property String* get_DatabaseName();
[JScript]
public function get DatabaseName() : String;
Property Value

A string containing the name of the Notification Services application database.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSApplication Members

Microsoft.SqlServer.NotificationServices Namespace


Version Property

 SQL Server Notification Services Books Online

NSApplication.Version Property

Gets the version of the Notification Services application.

[Visual Basic .NET]
Public Property Version As String
[C#]
public string Version {get;}
[C++]
public: __property String* get_Version();
[JScript]
public function get Version() : String;
Property Value

A string containing the version of the Notification Services application.

Remarks

The application version information is retrieved from the <Version> node of the application definition file (ADF).

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSApplication Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

NSApplication Methods

Public Methods
Initialize | Initializes an object of the NSApplication class.
Verify | Verifies the ApplicationName and Version properties of the Notification Services application.

See Also

NSApplication Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

NSApplication.Initialize Method

Initializes an object of the NSApplication class.

[Visual Basic .NET]
Public Sub Initialize(ByVal instance As NSInstance, ByVal applicationName As String)
[C#]
public void Initialize(NSInstance instance, string applicationName);
[C++]
public: void Initialize(NSInstance instance, String* applicationName);
[JScript]
public function Initialize(instance : NSInstance, applicationName : String);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing this application.

applicationName

A string containing the name of the application.

Exceptions
Exception Type | Condition
ArgumentNullException | The applicationName or instance argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on an NSApplication object created with the parameter-less constructor.

Example

The following example shows how to create and initialize an NSApplication object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSApplication Members

Microsoft.SqlServer.NotificationServices Namespace


Verify Method

 SQL Server Notification Services Books Online

NSApplication.Verify Method

Tests the connection to the application database.

[Visual Basic .NET]
Public Sub Verify()
[C#]
public void Verify();
[C++]
public: void Verify();
[JScript]
public function Verify();
Exceptions
Exception Type | Condition
NSException with an NSEventEnum.EditionMismatch argument | The database being accessed is of a different Notification Services edition than the NSApplication object.
NSException with an NSEventEnum.FailedToGetDatabaseOptions argument | The database information for this application could not be verified.
NSException with an NSEventEnum.FailedToGetVersionInfo argument | The version information for this application could not be verified.
NSException with an NSEventEnum.InstanceDatabaseNotFound argument | The Notification Services instance database could not be found.
NSException with an NSEventEnum.InvalidApplicationName argument | The application name set for the NSApplication object is not valid.
NSException with an NSEventEnum.SqlInvalidConnection argument | The connection to the SQL Server instance is not valid.
NSException with an NSEventEnum.SqlLoginFailed argument | The login attempt on the SQL Server instance failed.

These are the most common exceptions. Other exceptions are also possible, so you should always include a catch block for NSException.

Remarks

Calling Verify tests the connection to the application database, to verify that it is reachable. This allows you to force any connection-related errors for the NSApplication object at one place in your application, before you use it to initialize other objects.

For information on setting up accounts for connection to the SQL Server instance, see the "sp_addlogin", "sp_grantlogin", and "sp_grantdbaccess" topics in SQL Server Books Online.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Verify method to validate NSApplication data:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Verify the NSApplication object.
myApplication.Verify()
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Verify the NSApplication object.
myApplication.Verify();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSApplication Members

Microsoft.SqlServer.NotificationServices Namespace


NSInstance Class

Represents a Notification Services instance.

For a list of all members of this type, see NSInstance Members.

Microsoft.SqlServer.NotificationServices.Common.NSDBState

Microsoft.SqlServer.NotificationServices.NSInstance
[Visual Basic .NET]
Public Class NSInstance Implements INSInstance
[C#]
public class NSInstance : INSInstance
[C++]
public class NSInstance : public INSInstance
[JScript]
public class NSInstance implements INSInstance
Remarks

An NSInstance object represents a specific Notification Services instance. Several Notification Services classes require a reference to an NSInstance object in order to be initialized.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

NSInstance Members

Microsoft.SqlServer.NotificationServices Namespace


NSInstance Members

Public Constructors
NSInstance Constructor Overloaded. Creates a new object of the NSInstance class.
Public Properties
InstanceName | Gets the name of the Notification Services instance.
DatabaseName | Gets the name of the Notification Services instance database.
SqlPassword | Sets the password of the SQL Server account that this Notification Services instance uses for access. This property is used to support SQL Server Authentication in environments where SQL Server uses mixed mode Authentication (both Microsoft Windows and SQL Server Authentication). If the SqlUser and SqlPassword properties are not set, it is assumed that SQL Server is using Windows Authentication, and login is attempted with the current Windows user account.
SqlUser | Sets the user name of the SQL Server account that this Notification Services instance uses for access. This property is used to support SQL Server Authentication in environments where SQL Server uses mixed mode Authentication (both Windows and SQL Server Authentication). If the SqlUser and SqlPassword properties are not set, it is assumed that SQL Server is using Windows Authentication, and login is attempted with the current Windows user account.
Version | Gets the version of the Notification Services instance.
Public Methods
Initialize | Initializes an object of the NSInstance class.
Verify | Verifies the InstanceName, SqlUser, and SqlPassword properties of the Notification Services instance.

See Also

NSInstance Class

Microsoft.SqlServer.NotificationServices Namespace


NSInstance Constructor

Creates an object of the NSInstance class.

Overload List

Creates an uninitialized object of the NSInstance class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public NSInstance();

[C++]

public: NSInstance();

[JScript]

public function NSInstance();

Creates an object of the NSInstance class, and initializes it with a Notification Services instance name.

[Visual Basic .NET]

Public Sub New(String)

[C#]

public NSInstance(string);

[C++]

public: NSInstance(String*);

[JScript]

public function NSInstance(String);

See Also

NSInstance Members

Microsoft.SqlServer.NotificationServices Namespace


NSInstance Constructor ()

Creates an uninitialized object of the NSInstance class.

[Visual Basic .NET]
Public Sub New()
[C#]
public NSInstance();
[C++]
public: NSInstance();
[JScript]
public function NSInstance();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with an instance name before it can be used.

Example

The following example shows how to create and initialize an NSInstance object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance

const instanceName = "MyInstanceName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSInstance Members

Microsoft.SqlServer.NotificationServices Namespace


NSInstance Constructor (String)

Creates and initializes an object of the NSInstance class.

[Visual Basic .NET]
Public Sub New(ByVal instanceName As String)
[C#]
public NSInstance(string instanceName);
[C++]
public: NSApplication(String* instanceName);
[JScript]
public function NSApplication(instanceName : String);
Parameters

instanceName

A string containing the name of the Notification Services instance.

Exceptions
Exception Type | Condition
ArgumentNullException | The instanceName argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize an NSInstance object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSInstance Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

NSInstance Properties

Public Properties
InstanceName | Gets the name of the Notification Services instance.
DatabaseName | Gets the name of the Notification Services instance database.
SqlPassword | Sets the password of the SQL Server account that this Notification Services instance uses for access. This property is only used in environments that use mixed security (both Microsoft Windows and SQL Server) and SQL Authentication is desired. If the SqlUser and SqlPassword properties are not set, SQL Integrated Security is used with the current Windows user.
SqlUser | Sets the user name of the SQL Server account that this Notification Services instance uses for access. This property is only used in environments that use mixed security (both Windows and SQL Server) and SQL Authentication is desired. If the SqlUser and SqlPassword properties are not set, SQL Integrated Security is used with the current Windows user.
Version | Gets the version of the Notification Services instance.

See Also

NSInstance Members

Microsoft.SqlServer.NotificationServices Namespace


InstanceName Property

 SQL Server Notification Services Books Online

NSInstance.InstanceName Property

Gets the name of the Notification Services instance.

[Visual Basic .NET]
Public Property InstanceName As String
[C#]
public string InstanceName {get;}
[C++]
public: __property String* get_InstanceName();
[JScript]
public function get InstanceName() : String;
Property Value

A string containing the name of the Notification Services instance.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSInstance Members

Microsoft.SqlServer.NotificationServices Namespace


DatabaseName Property

 SQL Server Notification Services Books Online

NSInstance.DatabaseName Property

Gets the name of the Notification Services instance database.

[Visual Basic .NET]
Public Property DatabaseName As String
[C#]
public string DatabaseName {get;}
[C++]
public: __property String* get_DatabaseName();
[JScript]
public function get DatabaseName() : String;
Property Value

A string containing the name of the Notification Services instance database.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSInstance Members

Microsoft.SqlServer.NotificationServices Namespace


SqlPassword Property

 SQL Server Notification Services Books Online

NSInstance.SqlPassword Property

Sets the password of the SQL Server account that this Notification Services instance uses for access.

This property is used only in environments that use mixed security (both Microsoft Windows and SQL Server Authentication).

[Visual Basic .NET]
Public Property SqlPassword As String
[C#]
public string SqlPassword {set;}
[C++]
public: __property void set_SqlPassword(String*);
[JScript]
public function set SqlPassword(String);
Property Value

A string containing the password for the SQL Server login account.

Remarks

This property needs to be set only if you are using SQL Server Authentication on the SQL Server instance that hosts your Notification Services databases.

NSInstance.SqlPassword is used in conjunction with the NSInstance.SqlUser property to specify the username and password of the SQL Server login account that your application will use to access the Notification Services databases. If these values are not specified, Windows Authentication will be used instead.

Important Microsoft strongly recommends that you use Windows Authentication rather than SQL Server Authentication. Windows Authentication provides better security features, such as secure validation and encryption of passwords, auditing, password expiration, minimum password length, and account lockout after multiple invalid login requests.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSInstance Members

Microsoft.SqlServer.NotificationServices Namespace


SqlUser Property

 SQL Server Notification Services Books Online

NSInstance.SqlUser Property

Sets the user name of the SQL Server account that this Notification Services instance uses for access.

This property is only used in environments that use mixed security (both Microsoft Windows and SQL Server Authentication).

[Visual Basic .NET]
Public Property SqlUser As String
[C#]
public string SqlUser {set;}
[C++]
public: __property void set_SqlUser(String*);
[JScript]
public function set SqlUser(String);
Property Value

A string containing the account name for the SQL Server login account.

Remarks

This property needs to be set only if you are using SQL Server Authentication on the SQL Server instance that hosts your Notification Services databases.

NSInstance.SqlUser is used in conjunction with the NSInstance.SqlPassword property to specify the username and password of the SQL Server login account that your application will use to access the Notification Services databases. If these values are not specified, Windows Authentication will be used instead.

Important Microsoft strongly recommends that you use Windows Authentication rather than SQL Server Authentication. Windows Authentication provides better security features, such as secure validation and encryption of passwords, auditing, password expiration, minimum password length, and account lockout after multiple invalid login requests.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSInstance Members

Microsoft.SqlServer.NotificationServices Namespace


Version Property

 SQL Server Notification Services Books Online

NSInstance.Version Property

Gets the version of the Notification Services instance.

[Visual Basic .NET]
Public Property Version As String
[C#]
public string Version {get;}
[C++]
public: __property String* get_Version();
[JScript]
public function get Version() : String;
Property Value

A string containing the version of the Notification Services instance.

Remarks

The instance version information is determined by looking at the version of the Notification Services assembly that is being used.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSInstance Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

NSInstance Methods

Public Methods
Initialize | Initializes an object of the NSInstance class.
Verify | Verifies the InstanceName, SqlUser, and SqlPassword properties of the Notification Services instance.

See Also

NSInstance Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

NSInstance.Initialize Method

Initializes an object of the NSInstance class.

[Visual Basic .NET]
Public Sub Initialize(ByVal instanceName As String)
[C#]
public void Initialize(string instanceName);
[C++]
public: void Initialize(String* instanceName);
[JScript]
public function Initialize(instanceName : String);
Parameters

instanceName

A string containing the name of the Notification Services instance.

Exceptions
Exception Type | Condition
ArgumentNullException | The instanceName argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on an NSInstance object created with the parameter-less constructor.

Example

The following example shows how to create and initialize an NSInstance object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance

const instanceName = "MyInstanceName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSInstance Members

Microsoft.SqlServer.NotificationServices Namespace


Verify Method

 SQL Server Notification Services Books Online

NSInstance.Verify Method

Tests the connection to the instance database.

[Visual Basic .NET]
Public Sub Verify()
[C#]
public void Verify();
[C++]
public: void Verify();
[JScript]
public function Verify();
Exceptions
Exception Type | Condition
NSException with an NSEventEnum.EditionMismatch argument | The database being accessed is of a different Notification Services edition than the NSInstance object.
NSException with an NSEventEnum.FailedToGetDatabaseOptions argument | The database information for this instance could not be verified.
NSException with an NSEventEnum.FailedToGetVersionInfo argument | The version information for this instance could not be verified.
NSException with an NSEventEnum.InstanceDatabaseNotFound argument | The Notification Services instance database could not be found.
NSException with an NSEventEnum.SqlInvalidConnection argument | The connection to the SQL Server instance is not valid.
NSException with an NSEventEnum.SqlLoginFailed argument | The login attempt on the SQL Server instance failed.

These are the most common exceptions. Other exceptions are also possible, so you should always include a catch block for NSException.

Remarks

Calling Verify tests the connection to the instance database, to verify that it is reachable. This allows you to force any connection-related errors for the NSInstance object at one place in your application, before you use it to initialize other objects.

For information on setting up accounts for connection to the SQL Server instance, see the "sp_addlogin", "sp_grantlogin", and "sp_grantdbaccess" topics in SQL Server Books Online.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Verify method to validate NSInstance data:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Verify the NSInstance object.
myInstance.Verify()
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Verify the NSInstance object.
myInstance.Verify();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSInstance Members

Microsoft.SqlServer.NotificationServices Namespace


NSInstanceDescription Class

Provides descriptive data about Notification Services instances.

For a list of all members of this type, see NSInstanceDescription Members.

System.Object

Microsoft.SqlServer.NotificationServices.NSInstanceDescription
[Visual Basic .NET]
NonInheritable Public Class NSInstanceDescription Implements INSInstanceDescription
[C#]
public sealed class NSInstanceDescription : INSInstanceDescription
[C++]
public __gc __sealed class NSInstanceDescription : public INSInstanceDescription
[JScript]
public class NSInstanceDescription implements INSInstanceDescription
Remarks

An NSInstanceDescription object represents the information about a specific Notification Services instance. The InstanceEnumeration class provides an indexer that returns an NSInstanceDescription object.

The NSInstanceDescription class has no constructor. NSInstanceDescription objects are created by the InstanceEnumeration.Item property.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

NSInstanceDescription Members

Microsoft.SqlServer.NotificationServices Namespace


NSInstanceDescription Members

Public Properties
DBServerName | Gets the computer name of the database server that hosts this Notification Services instance.
InstanceName | Gets the name of the Notification Services instance.
Version | Gets the version of the Notification Services instance.

See Also

NSInstanceDescription Class

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

NSInstanceDescription Properties

Public Properties
DBServerName | Gets the computer name of the database server that hosts this Notification Services instance.
InstanceName | Gets the name of the Notification Services instance.
Version | Gets the version of the Notification Services instance.

See Also

NSInstanceDescription Members

Microsoft.SqlServer.NotificationServices Namespace


DBServerName Property

 SQL Server Notification Services Books Online

NSInstanceDescription.DBServerName Property

Gets the name of the Notification Services database server.

[Visual Basic .NET]
Public Property DBServerName As String
[C#]
public string DBServerName {get;}
[C++]
public: __property String* get_DBServerName();
[JScript]
public function get DBServerName() : String;
Property Value

A string containing the computer name of the server that hosts the SQL Server instance that this Notification Services instance uses.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSInstanceDescription Members

Microsoft.SqlServer.NotificationServices Namespace


InstanceName Property

 SQL Server Notification Services Books Online

NSInstanceDescription.InstanceName Property

Gets the name of the Notification Services instance.

[Visual Basic .NET]
Public Property InstanceName As String
[C#]
public string InstanceName {get;}
[C++]
public: __property String* get_InstanceName();
[JScript]
public function get InstanceName() : String;
Property Value

A string containing the name of the Notification Services instance.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSInstanceDescription Members

Microsoft.SqlServer.NotificationServices Namespace


Version Property

 SQL Server Notification Services Books Online

NSInstanceDescription.Version Property

Gets the version of the Notification Services instance.

[Visual Basic .NET]
Public Property Version As String
[C#]
public string Version {get;}
[C++]
public: __property String* get_Version();
[JScript]
public function get Version() : String;
Property Value

A string containing the version of the Notification Services instance.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

NSInstanceDescription Members

Microsoft.SqlServer.NotificationServices Namespace


RecipientInfo Class

Provides recipient information for a notification.

For a list of all members of this type, see RecipientInfo Members.

System.Object

Microsoft.SqlServer.NotificationServices.RecipientInfo
[Visual Basic .NET]
NonInheritable Public Class RecipientInfo
[C#]
public sealed class RecipientInfo
[C++]
public __gc __sealed class RecipientInfo
[JScript]
public class RecipientInfo
Remarks

The RecipientInfo class is used by the distributor to provide recipient information to content formatters and delivery protocols.

The RecipientInfo class has no public constructor. The distributor creates an object of this class and passes it to the FormatContent method of the content formatter.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

RecipientInfo Members

Microsoft.SqlServer.NotificationServices Namespace


RecipientInfo Members

Public Properties
DeviceAddress | Gets the target device address for the notification.
SubscriberId | Gets the subscriber ID for the notification.

See Also

RecipientInfo Class

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

RecipientInfo Properties

Public Properties
DeviceAddress | Gets the target device address for the notification.
SubscriberId | Gets the subscriber ID for the notification.

See Also

RecipientInfo Members

Microsoft.SqlServer.NotificationServices Namespace


DeviceAddress Property

 SQL Server Notification Services Books Online

RecipientInfo.DeviceAddress Property

Gets the target device address for the notification.

[Visual Basic .NET]
Public Property DeviceAddress As String
[C#]
public string DeviceAddress {get;}
[C++]
public: __property String* get_DeviceAddress();
[JScript]
public function get DeviceAddress() : String;
Property Value

A string containing the address of the target device for the given recipient.

Remarks

The format of the device address string varies according to the delivery protocol being used.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

RecipientInfo Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberId Property

 SQL Server Notification Services Books Online

RecipientInfo.SubscriberId Property

Gets the subscriber ID for the notification. The SubscriberId value is dependent on the requirements of the Notification Services instance and application. It can be a GUID, or any other identifier you choose to use.

[Visual Basic .NET]
Public Property SubscriberId As String
[C#]
public string SubscriberId {get;}
[C++]
public: __property String* get_SubscriberId();
[JScript]
public function get SubscriberId() : String;
Property Value

A string containing the subscriber ID of the given recipient.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

RecipientInfo Members

Microsoft.SqlServer.NotificationServices Namespace


Subscriber Class

Represents an individual subscriber in a given Notification Services instance.

For a list of all members of this type, see Subscriber Members.

System.Object

Microsoft.SqlServer.NotificationServices.Subscriber
[Visual Basic .NET]
NonInheritable Public Class Subscriber Implements ISubscriber
[C#]
public sealed class Subscriber : ISubscriber
[C++]
public __gc __sealed class Subscriber : public ISubscriber
[JScript]
public class Subscriber implements ISubscriber
Remarks

An object of the Subscriber class represents a Notification Services subscriber. Subscriptions and subscriber devices in the Notification Services system are associated with a subscriber by means of the subscriber ID.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


Subscriber Members

Public Constructors
Subscriber Constructor Overloaded. Creates a new object of the Subscriber class.
Public Properties
Enabled | Gets or sets the status of the subscriber record. A value of true indicates the subscriber is enabled to receive notifications. This property default is true.
SubscriberId | Gets or sets the subscriber ID for a subscriber record.
Public Methods
Add | Adds a subscriber record to the Notification Services database.
Delete | Deletes a subscriber record from the Notification Services database.
DeleteSubscriptions | Overloaded. Deletes subscriptions for a subscriber.
GetSubscriptions | Returns a SubscriptionEnumeration object representing the subscriptions of one subscription class in one application for a specified subscriber.
GetDevices | Returns a SubscriberDeviceEnumeration object representing the devices for a specified subscriber.
Initialize | Initializes an object of the Subscriber class.
Update | Modifies a subscriber record in the Notification Services database.

See Also

Subscriber Class

Microsoft.SqlServer.NotificationServices Namespace


Subscriber Constructor

Creates a new object of the Subscriber class.

Overload List

Creates an uninitialized object of the Subscriber class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public Subscriber();

[C++]

public: Subscriber();

[JScript]

public function Subscriber();

Creates a new object of the Subscriber class, and initializes it with a reference to an NSInstance object.

[Visual Basic .NET]

Public Sub New(NSInstance)

[C#]

public Subscriber(NSInstance);

[C++]

public: Subscriber(NSInstance);

[JScript]

public function Subscriber(NSInstance);

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


Subscriber Constructor ()

Creates an uninitialized object of the Subscriber class.

[Visual Basic .NET]
Public Sub New()
[C#]
public Subscriber();
[C++]
public: Subscriber();
[JScript]
public function Subscriber();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with a reference to an NSInstance object before it can be used.

Example

The following example shows how to create and initialize a Subscriber object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, mySubscriber

const instanceName = "MyInstanceName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize a Subscriber object.
set mySubscriber = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscriber")
mySubscriber.Initialize myInstance
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


Subscriber Constructor (NSInstance)

Creates and initializes an object of the Subscriber class.

[Visual Basic .NET]
Public Sub New(ByVal instance As NSInstance)
[C#]
public Subscriber(NSInstance instance);
[C++]
public: Subscriber(NSInstance instance);
[JScript]
public function Subscriber(instance : NSInstance);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing the subscriber.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize a Subscriber object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a Subscriber object.
Dim mySubscriber As New Microsoft.SqlServer.NotificationServices.Subscriber(myInstance)
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

Subscriber Properties

Public Properties
Enabled | Gets or sets the status of the subscriber record.
SubscriberId | Gets or sets the subscriber ID for a subscriber record.

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


Enabled Property

 SQL Server Notification Services Books Online

Subscriber.Enabled Property

Gets or sets the status of a subscriber.

[Visual Basic .NET]
Public Property Enabled As Boolean
[C#]
public bool Enabled {get;set;}
[C++]
public: __property bool get_Enabled();
public: __property void set_Enabled(bool);
[JScript]
public function get Enabled() : Boolean;
public function set Enabled(Boolean);
Property Value

A Boolean value indicating whether the subscriber is enabled.

Remarks

This property gets or sets the status of a subscriber, by changing the value of the Enabled field in the subscriber record.

The Enabled field is used to enable or disable a subscriber within the Notification Services system. When the Enabled status is true, the subscriber is active, and can receive notifications. When the Enabled status is false, the subscriber and all of the subscriber's subscriptions are disabled.

This property default is true.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberId Property

 SQL Server Notification Services Books Online

Subscriber.SubscriberId Property

Gets or sets the identifier of the subscriber record.

[Visual Basic .NET]
Public Property SubscriberId As String
[C#]
public string SubscriberId {get;set;}
[C++]
public: __property String* get_SubscriberId();
public: __property void set_SubscriberId(String*);
[JScript]
public function get SubscriberId() : String;
public function set SubscriberId(String);
Property Value

A string containing the subscriber ID of the subscriber.

Remarks

The subscriber ID cannot be null or a zero-length string.

How the system interprets the uniqueness of a subscriber ID is dependent partially on the collation used by the instance database. Trailing spaces and case changes are interpreted based on the collation used. For instance, some systems interpret "mySubscriber" and "MySubscriber" as two different legitimate IDs, and others do not. Make sure you take your database collation into account when planning the data verification code for your subscription management application.

Setting the subscriber ID in a procedure causes all subsequent update and delete actions to be performed on the record identified by the subscriber ID that was set, and not on the record that was originally retrieved.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

Subscriber Methods

Public Methods
Add | Adds a subscriber record to the Notification Services database.
Delete | Deletes a subscriber record from the Notification Services database.
DeleteSubscriptions | Overloaded. Deletes subscriptions for a subscriber.
GetSubscriptions | Returns a SubscriptionEnumeration object representing the subscriptions of one subscription class in one application for a specified subscriber.
GetDevices | Returns a SubscriberDeviceEnumeration object representing the devices for a specified subscriber.
Initialize | Initializes an object of the Subscriber class.
Update | Modifies a subscriber record in the Notification Services database.

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


Add Method

 SQL Server Notification Services Books Online

Subscriber.Add Method

Adds a subscriber record to the Notification Services database.

[Visual Basic .NET]
Public Sub Add()
[C#]
public void Add();
[C++]
public: void Add();
[JScript]
public function Add();
Exceptions
Exception Type | Condition
NSException with an NSEventEnum.InvalidField argument | One of the fields in the subscriber data fails to meet a database requirement or a constraint (such as a column data type).
NSException with an NSEventEnum.MissingField argument | One of the fields in the subscriber data fails to meet a NOT NULL requirement in the subscriber table.
Example
[Visual Basic .NET, C#]

The following examples show how to use the Add method to add a subscriber:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a Subscriber object.
Dim mySubscriber As New Microsoft.SqlServer.NotificationServices.Subscriber(myInstance)

'Set subscriber information.
mySubscriber.SubscriberId = txtID.Text

'Add the new subscriber record.
mySubscriber.Add()
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set subscriber information.
mySubscriber.SubscriberId = txtID.Text;

//Add the new subscriber record.
mySubscriber.Add();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


Delete Method

 SQL Server Notification Services Books Online

Subscriber.Delete Method

Deletes a subscriber record from the Notification Services database.

[Visual Basic .NET]
Public Sub Delete()
[C#]
public void Delete();
[C++]
public: void Delete();
[JScript]
public function Delete();
Exceptions
Exception Type | Condition
NSException with an NSEventEnum.FailedToDeleteSubscriber argument The subscriber record could not be deleted for some reason. Check the event log for further details. | The subscriber record could not be deleted. Check the event log for further details. The subscriber record could not be deleted for some reason. Check the event log for further details.
NSException with an NSEventEnum.SubscribersDisabled argument | The subscriber record is disabled. It must be enabled in order to be deleted.
Remarks

The Delete method removes the subscriber and all associated subscriptions and subscriber devices.

If the subscriber ID is set in a procedure, the delete action is performed on the record identified by the subscriber ID that was set, and not on the record that was originally retrieved.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Delete method to delete a subscriber:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a Subscriber object.
Dim mySubscriber As New Microsoft.SqlServer.NotificationServices.Subscriber(myInstance)

'Set the subscriber ID, so that the
'correct subscriber record is deleted.
mySubscriber.SubscriberId = txtID.Text

'Delete the subscriber record from the database.
mySubscriber.Delete()
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the subscriber ID, so that the
//correct subscriber record is deleted.
mySubscriber.SubscriberId = txtID.Text;

//Delete the subscriber record from the database.
mySubscriber.Delete();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


DeleteSubscriptions Method

 SQL Server Notification Services Books Online

Subscriber.DeleteSubscriptions Method

Deletes subscriptions for a subscriber. All subscriptions can be deleted, or just those for a particular application or subscription class, depending on the parameters that are passed to the method.

Overload List

Deletes all subscriptions for one subscriber.

[Visual Basic .NET]

Public Sub DeleteSubscriptions()

[C#]

public void DeleteSubscriptions();

[C++]

public: void DeleteSubscriptions();

[JScript]

public function DeleteSubscriptions();

Deletes all subscriptions in the specified Notification Services application for one subscriber.

[Visual Basic .NET]

Public Sub DeleteSubscriptions(NSApplication)

[C#]

public void DeleteSubscriptions(NSApplication);

[C++]

public: void DeleteSubscriptions(NSApplication);

[JScript]

public function DeleteSubscriptions(NSApplication);

Deletes all subscriptions in the specified Notification Services application, of the specified subscription class, for one subscriber.

[Visual Basic .NET]

Public Sub DeleteSubscriptions(NSApplication, String)

[C#]

public void DeleteSubscriptions(NSApplication, string);

[C++]

public: void DeleteSubscriptions(NSApplication, String*);

[JScript]

public function DeleteSubscriptions(NSApplication, String);

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


DeleteSubscriptions Method ()

 SQL Server Notification Services Books Online
Subscriber.DeleteSubscriptions Method ()

Deletes all subscriptions for one subscriber.

[Visual Basic .NET]
Public Sub DeleteSubscriptions()
[C#]
public void DeleteSubscriptions();
[C++]
public: void DeleteSubscriptions();
[JScript]
public function DeleteSubscriptions();
Example
[Visual Basic .NET, C#]

The following examples show how to use the DeleteSubscriptions method to delete all subscriptions for a subscriber:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a Subscriber object.
Dim mySubscriber As New Microsoft.SqlServer.NotificationServices.Subscriber(myInstance)

'Set the subscriber ID, so that the
'correct subscriptions will be deleted.
mySubscriber.SubscriberId = txtID.Text

'Delete all subscriptions.
mySubscriber.DeleteSubscriptions()
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the subscriber ID, so that the
//correct subscriptions will be deleted.
mySubscriber.SubscriberId = txtID.Text;

//Delete all subscriptions.
mySubscriber.DeleteSubscriptions();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


DeleteSubscriptions Method (NSApplication)

 SQL Server Notification Services Books Online
Subscriber.DeleteSubscriptions Method (NSApplication)

Deletes all subscriptions in the specified Notification Services application for one subscriber.

[Visual Basic .NET]
Public Sub DeleteSubscriptions(ByVal application As NSApplication)
[C#]
public void DeleteSubscriptions(NSApplication application);
[C++]
public: void DeleteSubscriptions(NSApplication application);
[JScript]
public function DeleteSubscriptions(application : NSApplication);
Parameters

application

An NSApplication object that represents the Notification Services application from which all subscriptions for this subscriber should be deleted.

Example
[Visual Basic .NET, C#]

The following examples show how to use the DeleteSubscriptions method to delete all subscriptions in one Notification Services application for a subscriber:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a Subscriber object.
Dim mySubscriber As New Microsoft.SqlServer.NotificationServices.Subscriber(myInstance)

'Set the subscriber ID, so that the
'correct subscriptions will be deleted.
mySubscriber.SubscriberId = txtID.Text

'Delete subscriptions for an application.
mySubscriber.DeleteSubscriptions(myApplication)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the subscriber ID, so that the
//correct subscriptions will be deleted.
mySubscriber.SubscriberId = txtID.Text;

//Delete subscriptions for an application.
mySubscriber.DeleteSubscriptions(myApplication);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


DeleteSubscriptions Method (NSApplication, String)

 SQL Server Notification Services Books Online
Subscriber.DeleteSubscriptions Method (NSApplication, String)

Deletes all subscriptions in the specified Notification Services application, of the specified subscription class, for one subscriber.

[Visual Basic .NET]
Public Sub DeleteSubscriptions(ByVal application As NSApplication, _
ByVal subscriptionClassName As String)
[C#]
public void DeleteSubscriptions(NSApplication application, string subscriptionClassName);
[C++]
public: void DeleteSubscriptions(NSApplication application, String* subscriptionClassName);
[JScript]
public function DeleteSubscriptions(application : NSApplication, subscriptionClassName : String);
Parameters

application

An NSApplication object that represents the Notification Services application containing the subscription class from which all subscriptions for this subscriber are to be deleted.

subscriptionClassName

A string containing the name of the subscription class from which all subscriptions for this subscriber are to be deleted.

Example
[Visual Basic .NET, C#]

The following examples show how to use the DeleteSubscriptions method to delete all subscriptions in one subscription class of one Notification Services application for a subscriber:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a Subscriber object.
Dim mySubscriber As New Microsoft.SqlServer.NotificationServices.Subscriber(myInstance)

'Set the subscriber ID, so that the
'correct subscriptions will be deleted.
mySubscriber.SubscriberId = txtID.Text

'Delete subscriptions for a subscription class.
mySubscriber.DeleteSubscriptions(myApplication, subscriptionClassName)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the subscriber ID, so that the
//correct subscriptions will be deleted.
mySubscriber.SubscriberId = txtID.Text;

//Delete subscriptions for a subscription class.
mySubscriber.DeleteSubscriptions(myApplication, subscriptionClassName);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


GetSubscriptions Method

 SQL Server Notification Services Books Online

Subscriber.GetSubscriptions Method

Gets all subscriptions of the specified subscription class, in the specified Notification Services application, for one subscriber.

[Visual Basic .NET]
Public Function GetSubscriptions(ByVal application As NSApplication, ByVal _ subscriptionClassName As String) As SubscriptionEnumeration
[C#]
public SubscriptionEnumeration GetSubscriptions(NSApplication  application, string subscriptionClassName);
[C++]
public: SubscriptionEnumeration GetSubscriptions(NSApplication  application, String* subscriptionClassName);
[JScript]
public function GetSubscriptions(application : NSApplication, subscriptionClassName : String) : SubscriptionEnumeration;
Parameters

application

An NSApplication object that represents the Notification Services application containing the subscription class for which all subscriptions for this subscriber should be retrieved.

subscriptionClassName

A string containing the name of the subscription class for which all subscriptions for this subscriber should be retrieved.

Return Value

A SubscriptionEnumeration object that contains all subscriptions for the subscriber from the specified Notification Services application and subscription class. To see all subscription classes for an application, use the SubscriptionClass class instead. For more information, see SubscriptionClass Class.

Example
[Visual Basic .NET, C#]

The following examples show how to use the GetSubscriptions method to retrieve all subscriptions in one subscription class of one Notification Services application for a subscriber:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a Subscriber object.
Dim mySubscriber As New Microsoft.SqlServer.NotificationServices.Subscriber(myInstance)

'Set the subscriber ID, so that the
'correct subscriptions will be retrieved.
mySubscriber.SubscriberId = txtID.Text

'Get the subscriptions.
mySubscriber.GetSubscriptions(myApplication, subscriptionClassName)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the subscriber ID, so that the
//correct subscriptions will be retrieved.
mySubscriber.SubscriberId = txtID.Text;

//Get the subscriptions.
mySubscriber.GetSubscriptions(myApplication, subscriptionClassName);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


GetDevices Method

 SQL Server Notification Services Books Online

Subscriber.GetDevices Method

Gets all devices for one subscriber.

[Visual Basic .NET]
Public Function GetDevices() As SubscriberDeviceEnumeration
[C#]
public SubscriberDeviceEnumeration GetDevices();
[C++]
public: SubscriberDeviceEnumeration GetDevices();
[JScript]
public function GetDevices() : SubscriberDeviceEnumeration;
Return Value

A SubscriberDeviceEnumeration object that contains all devices for the subscriber.

Example
[Visual Basic .NET, C#]

The following examples show how to use the GetDevices method to retrieve all devices for a subscriber:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a Subscriber object.
Dim mySubscriber As New Microsoft.SqlServer.NotificationServices.Subscriber(myInstance)

'Set the subscriber ID, so that the
'correct devices will be retrieved.
mySubscriber.SubscriberId = txtID.Text

'Get the devices.
mySubscriber.GetDevices()
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the subscriber ID, so that the
//correct devices will be retrieved.
mySubscriber.SubscriberId = txtID.Text;

//Get the devices.
mySubscriber.GetDevices();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

Subscriber.Initialize Method

Initializes an object of the Subscriber class. Is used in conjunction with the parameter-less constructor to enable COM interoperability.

[Visual Basic .NET]
Public Sub Initialize(ByVal instance As NSInstance)
[C#]
public void Initialize(NSInstance instance);
[C++]
public: void Initialize(NSInstance instance);
[JScript]
public function Initialize(instance : NSInstance);
Parameters

instance

An NSInstance object that represents the Notification Services instance that contains the subscriber.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on a Subscriber object created with the parameter-less constructor.

Example

The following example shows how to create and initialize a Subscriber object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, mySubscriber

const instanceName = "MyInstanceName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize a Subscriber object.
set mySubscriber = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscriber")
mySubscriber.Initialize myInstance
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


Update Method

 SQL Server Notification Services Books Online

Subscriber.Update Method

Updates the information in a subscriber record.

[Visual Basic .NET]
Public Sub Update()
[C#]
public void Update();
[C++]
public: void Update();
[JScript]
public function Update();
Exceptions
Exception Type | Condition
IndexOutOfRangeException | The subscriber ID specified for the record to be updated does not match the subscriber ID of any subscriber records in the database.
NSException with an NSEventEnum.FailedToUpdateSubscriber argument | The subscriber record could not be updated. Check the event log for further details.
NSException with an NSEventEnum.SubscribersDisabled argument | The subscriber record is disabled. It must be enabled in order to be updated.
Remarks

If the subscriber ID is set in a procedure, all subsequent updates is performed on the record identified by the subscriber ID that was set, and not on the record that was originally retrieved.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Update method to modify subscriber information:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a Subscriber object.
Dim mySubscriber As New Microsoft.SqlServer.NotificationServices.Subscriber(myInstance)

'Set the subscriber ID, so that the
'correct subscriber record will be updated.
mySubscriber.SubscriberId = txtID.Text

'Modify subscriber information.
mySubscriber.Enabled = false

'Update the subscriber record.
mySubscriber.Update()
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = new Microsoft.SqlServer.NotificationServices.Subscriber(myInstance);

//Set the subscriber ID, so that the
//correct subscriber record will be updated.
mySubscriber.SubscriberId = txtID.Text;

//Modify subscriber information.
mySubscriber.Enabled = false;

//Update the subscriber record.
mySubscriber.Update();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscriber Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberDevice Class

Represents a device that can receive notifications.

For a list of all members of this type, see SubscriberDevice Members.

System.Object

Microsoft.SqlServer.NotificationServices.SubscriberDevice
[Visual Basic .NET]
NonInheritable Public Class SubscriberDevice Implements ISubscriberDevice
[C#]
public sealed class SubscriberDevice : ISubscriberDevice
[C++]
public __gc __sealed class SubscriberDevice : public ISubscriberDevice
[JScript]
public class SubscriberDevice implements ISubscriberDevice
Remarks

An object of the SubscriberDevice class represents a device belonging to a subscriber that can be used to receive notifications. Subscriber devices in the Notification Services system are associated with a subscriber by means of the subscriber ID.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberDevice Members

Public Constructors
SubscriberDevice Constructor Overloaded. Creates a new object of the SubscriberDevice class.
Public Properties
DeliveryChannelName | Gets or sets the name of the delivery channel a device uses.
DeviceAddress | Gets or sets the address used to contact the device.
DeviceName | Gets or sets the device name.
DeviceTypeName | Gets or sets the name of the device type that describes a device.
SubscriberId | Gets or sets the subscriber ID that identifies the subscriber with which this device is associated.
Public Methods
Add | Adds a subscriber device record to the Notification Services database.
Delete | Deletes a subscriber device record from the Notification Services database.
Initialize | Initializes an object of the SubscriberDevice class.
Update | Modifies a subscriber device record in the Notification Services database.

See Also

SubscriberDevice Class

Microsoft.SqlServer.NotificationServices Namespace


SubscriberDevice Constructor

Creates a new object of the SubscriberDevice class.

Overload List

Creates an uninitialized object of the SubscriberDevice class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public SubscriberDevice();

[C++]

public: SubscriberDevice();

[JScript]

public function SubscriberDevice();

Creates a new object of the SubscriberDevice class, and initializes it with a reference to an NSInstance object.

[Visual Basic .NET]

Public Sub New(NSInstance)

[C#]

public SubscriberDevice(NSInstance);

[C++]

public: SubscriberDevice(NSInstance);

[JScript]

public function SubscriberDevice(NSInstance);

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberDevice Constructor ()

Creates an uninitialized object of the SubscriberDevice class.

[Visual Basic .NET]
Public Sub New()
[C#]
public SubscriberDevice();
[C++]
public: SubscriberDevice();
[JScript]
public function SubscriberDevice();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with a reference to an NSInstance object before it can be used.

Example

The following example shows how to create and initialize a SubscriberDevice object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, mySubscriberDevice

const instanceName = "MyInstanceName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize a SubscriberDevice object.
set mySubscriberDevice = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriberDevice")
mySubscriberDevice.Initialize myInstance
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberDevice Constructor (NSInstance)

Creates and initializes an object of the SubscriberDevice class.

[Visual Basic .NET]
Public Sub New(ByVal instance As NSInstance)
[C#]
public SubscriberDevice(NSInstance instance);
[C++]
public: SubscriberDevice(NSInstance instance);
[JScript]
public function SubscriberDevice(instance : NSInstance);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing the subscriber device.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize a SubscriberDevice object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a SubscriberDevice object.
Dim mySubscriberDevice As New Microsoft.SqlServer.NotificationServices.SubscriberDevice(myInstance)
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a SubscriberDevice object.
Microsoft.SqlServer.NotificationServices.SubscriberDevice mySubscriberDevice = new Microsoft.SqlServer.NotificationServices.SubscriberDevice(myInstance);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

SubscriberDevice Properties

Public Properties
DeliveryChannelName | Gets or sets the name of the delivery channel a device uses.
DeviceAddress | Gets or sets the address used to contact the device.
DeviceName | Gets or sets the device name.
DeviceTypeName | Gets or sets the name of the device type that describes a device.
SubscriberId | Gets or sets the subscriber ID that identifies the subscriber with which this device is associated.

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


DeliveryChannelName Property

 SQL Server Notification Services Books Online

SubscriberDevice.DeliveryChannelName Property

Gets or sets the name of the delivery channel a device uses.

[Visual Basic .NET]
Public Property DeliveryChannelName As String
[C#]
public string DeliveryChannelName {get;set;}
[C++]
public: __property String* get_DeliveryChannelName();
public: __property void set_DeliveryChannelName(String*);
[JScript]
public function get DeliveryChannelName() : String;
public function set DeliveryChannelName(String);
Property Value

A string containing the name of the delivery channel used by the subscriber device.

Remarks

The delivery channel contains the delivery information — the protocol used and the specific implementation of it in the given environment — that determines how a notification is delivered to a device.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


DeviceAddress Property

 SQL Server Notification Services Books Online

SubscriberDevice.DeviceAddress Property

Gets or sets the address used to contact the device.

[Visual Basic .NET]
Public Property DeviceAddress As String
[C#]
public string DeviceAddress {get;set;}
[C++]
public: __property String* get_DeviceAddress();
public: __property void set_DeviceAddress(String*);
[JScript]
public function get DeviceAddress() : String;
public function set DeviceAddress(String);
Property Value

A string containing the address of the subscriber device.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


DeviceName Property

 SQL Server Notification Services Books Online

SubscriberDevice.DeviceName Property

Gets or sets the device name.

[Visual Basic .NET]
Public Property DeviceName As String
[C#]
public string DeviceName {get;set;}
[C++]
public: __property String* get_DeviceName();
public: __property void set_DeviceName(String*);
[JScript]
public function get DeviceName() : String;
public function set DeviceName(String);
Property Value

A string containing the name of the subscriber device.

Remarks

The device name, in combination with the subscriber ID, uniquely identifies this record in the subscriber devices table.

Note The combined length of the values in the DeviceName and SubscriberId columns cannot exceed 900 bytes. This is 900 characters for single-byte data types (like char and varchar), or 450 characters for double-byte data types (like nchar and nvarchar).

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


DeviceTypeName Property

 SQL Server Notification Services Books Online

SubscriberDevice.DeviceTypeName Property

Gets or sets the name of the device type that describes a device.

[Visual Basic .NET]
Public Property DeviceTypeName As String
[C#]
public string DeviceTypeName {get;set;}
[C++]
public: __property String* get_DeviceTypeName();
public: __property void set_DeviceTypeName(String*);
[JScript]
public function get DeviceTypeName() : String;
public function set DeviceTypeName(String);
Property Value

A string containing the name of the device type that describes the subscriber device.

Remarks

The device type name describes what type of device this is, such as a cellular phone or an instant messaging account.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberId Property

 SQL Server Notification Services Books Online

SubscriberDevice.SubscriberId Property

Gets or sets the subscriber ID that identifies the subscriber with which this device is associated.

[Visual Basic .NET]
Public Property SubscriberId As String
[C#]
public string SubscriberId {get;set;}
[C++]
public: __property String* get_SubscriberId();
public: __property void set_SubscriberId(String*);
[JScript]
public function get SubscriberId() : String;
public function set SubscriberId(String);
Property Value

A string containing the subscriber ID of the subscriber with which the subscriber device is associated.

Remarks

The subscriber ID, in combination with the device name, uniquely identifies this record in the subscriber devices table.

Note The combined length of the values in the DeviceName and SubscriberId columns cannot exceed 900 bytes. This is 900 characters for single-byte data types (like char and varchar), or 450 characters for double-byte data types (like nchar and nvarchar).

Setting the subscriber ID in a procedure can cause all subsequent update and delete actions to be performed on the record identified by the subscriber ID that was set, and not on the record that was originally retrieved. This occurs in situations where a record with a device name value identical to the record that was originally retrieved exists for the record identified by the subscriber ID that was set.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

SubscriberDevice Methods

Public Methods
Add | Adds a subscriber device record to the Notification Services database.
Delete | Deletes a subscriber device record from the Notification Services database.
Initialize | Initializes an object of the SubscriberDevice class.
Update | Modifies a subscriber device record in the Notification Services database.

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


Add Method

 SQL Server Notification Services Books Online

SubscriberDevice.Add Method

Adds a subscriber device record to the Notification Services database.

[Visual Basic .NET]
Public Sub Add()
[C#]
public void Add();
[C++]
public: void Add();
[JScript]
public function Add();
Exceptions
Exception Type | Condition
NSException with an NSEventEnum.InvalidField argument | One of the fields in the subscriber device data fails to meet a database requirement or a constraint (such as a column data type).
NSException with an NSEventEnum.MissingField argument | One of the fields in the subscriber device data fails to meet a NOT NULL requirement in the subscriber device table.
Example
[Visual Basic .NET, C#]

The following examples show how to use the Add method to add a subscriber device:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a SubscriberDevice object.
Dim mySubscriberDevice As New Microsoft.SqlServer.NotificationServices.SubscriberDevice(myInstance)

'Add code here to set subscriber device information.

'Add the new subscriber device record.
mySubscriberDevice.Add()
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a SubscriberDevice object.
Microsoft.SqlServer.NotificationServices.SubscriberDevice mySubscriberDevice = new Microsoft.SqlServer.NotificationServices.SubscriberDevice(myInstance);

//Add code here to set subscriber device information.

//Add the new subscriber device record.
mySubscriberDevice.Add();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


Delete Method

 SQL Server Notification Services Books Online

SubscriberDevice.Delete Method

Deletes a subscriber device record from the Notification Services database.

[Visual Basic .NET]
Public Sub Delete()
[C#]
public void Delete();
[C++]
public: void Delete();
[JScript]
public function Delete();
Exceptions
Exception Type | Condition
NSException with an NSEventEnum.FailedToDeleteSubscriberDevice argument | The subscriber device record could not be deleted. Check the event log for further details.
Remarks

This method removes the subscriber device from the system.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Delete method to delete a subscriber device:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a SubscriberDevice object.
Dim mySubscriberDevice As New Microsoft.SqlServer.NotificationServices.SubscriberDevice(myInstance)

'Set the subscriber ID and the device name, so that
'the correct subscriber device record will be deleted.
mySubscriberDevice.SubscriberId = txtID.Text
mySubscriberDevice.DeviceName = txtDeviceName.Text

'Delete the subscriber device record from the database.
mySubscriberDevice.Delete()
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a SubscriberDevice object.
Microsoft.SqlServer.NotificationServices.SubscriberDevice mySubscriberDevice = new Microsoft.SqlServer.NotificationServices.SubscriberDevice(myInstance);

//Set the subscriber ID and the device name, so that
//the correct subscriber device record will be deleted.
mySubscriberDevice.SubscriberId = txtID.Text;
mySubscriberDevice.DeviceName = txtDeviceName.Text;

//Delete the subscriber device record from the database.
mySubscriberDevice.Delete();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

SubscriberDevice.Initialize Method

Initializes an object of the SubscriberDevice class.

[Visual Basic .NET]
Public Sub Initialize(ByVal instance As NSInstance)
[C#]
public void Initialize(NSInstance instance);
[C++]
public: void Initialize(NSInstance instance);
[JScript]
public function Initialize(instance : NSInstance);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing the subscriber device.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on a SubscriberDevice object created with the parameter-less constructor.

Example

The following example shows how to create and initialize a SubscriberDevice object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, mySubscriberDevice

const instanceName = "MyInstanceName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize a SubscriberDevice object.
set mySubscriberDevice = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriberDevice")
mySubscriberDevice.Initialize myInstance
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


Update Method

 SQL Server Notification Services Books Online

SubscriberDevice.Update Method

Updates the information in a subscriber device record.

[Visual Basic .NET]
Public Sub Update()
[C#]
public void Update();
[C++]
public: void Update();
[JScript]
public function Update();
Exceptions
Exception Type | Condition
NSException with an NSEventEnum.AddSubscriberIdInvalid argument | The subscriber ID specified for the subscriber device is not valid.
NSException with an NSEventEnum.FailedToUpdateSubscriberDevice argument | The subscriber device record could not be updated. Check the event log for further details.
NSException with an NSEventEnum.InvalidField argument | One of the fields in the subscriber device data fails to meet a database requirement or a constraint (such as a column data type).
NSException with an NSEventEnum.MissingField argument | One of the fields in the subscriber device data fails to meet a NOT NULL requirement in the subscriber device table.
Remarks

The update applies to the record identified by the combination of subscriber ID and device name.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Update method to modify subscriber device information:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a SubscriberDevice object.
Dim mySubscriberDevice As New Microsoft.SqlServer.NotificationServices.SubscriberDevice(myInstance)

'Set the subscriber ID and the device name, so that
'the correct subscriber device record will be updated.
mySubscriberDevice.SubscriberId = txtID.Text
mySubscriberDevice.DeviceName = txtDeviceName.Text

'Modify subscriber device information.

'Update the subscriber device record.
mySubscriberDevice.Update()
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a SubscriberDevice object.
Microsoft.SqlServer.NotificationServices.SubscriberDevice mySubscriberDevice = new Microsoft.SqlServer.NotificationServices.SubscriberDevice(myInstance);

//Set the subscriber ID and the device name, so that
//the correct subscriber device record will be deleted.
mySubscriberDevice.SubscriberId = txtID.Text;
mySubscriberDevice.DeviceName = txtDeviceName.Text;

//Modify subscriber device information.

//Update the subscriber device record.
mySubscriberDevice.Update();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDevice Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberDeviceEnumeration Class

Represents the collection of devices for a given subscriber.

For a list of all members of this type, see SubscriberDeviceEnumeration Members.

System.Object

Microsoft.SqlServer.NotificationServices.SubscriberDeviceEnumeration
[Visual Basic .NET]
NonInheritable Public Class SubscriberDeviceEnumeration Implements ISubscriberDeviceEnumeration, IEnumerable
[C#]
public sealed class SubscriberDeviceEnumeration : ISubscriberDeviceEnumeration, IEnumerable
[C++]
public __gc __sealed class SubscriberDeviceEnumeration : public ISubscriberDeviceEnumeration, IEnumerable
[JScript]
public class SubscriberDeviceEnumeration implements ISubscriberDeviceEnumeration, IEnumerable
Remarks

The SubscriberDeviceEnumeration class allows an application to iterate through the set of devices for a given subscriber. It also provides an Item property to return a SubscriberDevice object that represents a specific device.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

SubscriberDeviceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberDeviceEnumeration Members

Public Constructors
SubscriberDeviceEnumeration Constructor Overloaded. Creates a new object of the SubscriberDeviceEnumeration class.
Public Properties
Item Returns a SubscriberDevice object, which represents an individual device.

In C#, this property is the indexer for the SubscriberDeviceEnumeration class.
Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the subscriber devices.
Initialize | Initializes an object of the SubscriberDeviceEnumeration class.

See Also

SubscriberDeviceEnumeration Class

Microsoft.SqlServer.NotificationServices Namespace


SubscriberDeviceEnumeration Constructor

Creates a new object of the SubscriberDeviceEnumeration class.

Overload List

Creates an uninitialized object of the SubscriberDeviceEnumeration class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public SubscriberDeviceEnumeration();

[C++]

public: SubscriberDeviceEnumeration();

[JScript]

public function SubscriberDeviceEnumeration();

Creates a new object of the SubscriberDeviceEnumeration class, and initializes it with a reference to an NSInstance object and a subscriber ID. This object returns a collection of all devices for a single user.

[Visual Basic .NET]

Public Sub New(NSInstance, String)

[C#]

public SubscriberDeviceEnumeration(NSInstance, string);

[C++]

public: SubscriberDeviceEnumeration(NSInstance, String*);

[JScript]

public function SubscriberDeviceEnumeration(NSInstance, String);

See Also

SubscriberDeviceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberDeviceEnumeration Constructor ()

Creates an uninitialized object of the SubscriberDeviceEnumeration class.

[Visual Basic .NET]
Public Sub New()
[C#]
public SubscriberDeviceEnumeration();
[C++]
public: SubscriberDeviceEnumeration();
[JScript]
public function SubscriberDeviceEnumeration();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with a reference to an NSInstance object and a subscriber ID before it can be used.

Example

The following example shows how to create and initialize a SubscriberDeviceEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, mySubscriberDeviceEnumeration

const instanceName = "MyInstanceName"
subscriberId = "TestSubscriber"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

set mySubscriberDeviceEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriberDeviceEnumeration")
mySubscriberDeviceEnumeration.Initialize myInstance, subscriberId
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDeviceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberDeviceEnumeration Constructor (NSInstance, String)

Creates and initializes an object of the SubscriberDeviceEnumeration class.

[Visual Basic .NET]
Public Sub New(ByVal instance As NSInstance, ByVal subscriberId As String)
[C#]
public SubscriberDeviceEnumeration(NSInstance instance, string subscriberId);
[C++]
public: SubscriberDeviceEnumeration(NSInstance instance, String* subscriberId);
[JScript]
public function SubscriberDeviceEnumeration(instance : NSInstance, subscriberId : String);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing the subscriber devices.

subscriberId

A string containing the subscriber ID of the subscriber with whom the devices are associated.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize a SubscriberDeviceEnumeration object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim subscriberId As String = txtSubscriberId.Text

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a SubscriberDeviceEnumeration object.
Dim mySubscriberDeviceEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriberDeviceEnumeration(myInstance, subscriberId)
[C#]
string instanceName = "MyInstanceName";
string subscriberId = txtSubscriberId.Text;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a SubscriberDeviceEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriberDeviceEnumeration mySubscriberDeviceEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriberDeviceEnumeration(myInstance, subscriberId);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDeviceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

SubscriberDeviceEnumeration Properties

Public Properties
Item Returns a SubscriberDevice object, which represents an individual device.

In C#, this property is the indexer for the SubscriberDeviceEnumeration class.

See Also

SubscriberDeviceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property

 SQL Server Notification Services Books Online

SubscriberDeviceEnumeration.Item Property

Returns a reference to an individual device.

[C#]

In C#, this property is the indexer for the SubscriberDeviceEnumeration class.

[Visual Basic .NET]
Public Property Item(ByVal deviceName As String) As SubscriberDevice
[C#]
public SubscriberDevice this[string deviceName] {get;}
[C++]
public: __property SubscriberDevice get_Item(String* deviceName);
[JScript]
returnValue = SubscriberDeviceEnumerationObject.Item(deviceName);
-or-
returnValue = SubscriberDeviceEnumerationObject(deviceName);
Parameters

deviceName

The name of the subscriber device that you want returned.

Property Value

A SubscriberDevice object, which represents a target device for receiving notifications.

Exceptions
Exception Type | Condition
IndexOutOfRangeException | No record can be identified using the subscriber device name provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the Item property to return a SubscriberDevice object:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim subscriberId As String = txtSubscriberId.Text
Dim deviceName As String = txtDeviceName.Text

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a SubscriberDeviceEnumeration object.
Dim mySubscriberDeviceEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriberDeviceEnumeration(myInstance, subscriberId)

'Use the Item property to return a SubscriberDevice object.
Dim mySubscriberDevice As Microsoft.SqlServer.NotificationServices.SubscriberDevice = mySubscriberDeviceEnumeration(deviceName)
[C#]
string instanceName = "MyInstanceName";
string subscriberId = txtSubscriberId.Text;
string deviceName = txtDeviceName.Text;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a SubscriberDeviceEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriberDeviceEnumeration mySubscriberDeviceEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriberDeviceEnumeration(myInstance, subscriberId);

//Use the Item property to return a SubscriberDevice object.
Microsoft.SqlServer.NotificationServices.SubscriberDevice mySubscriberDevice = mySubscriberDeviceEnumeration[deviceName];
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDeviceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

SubscriberDeviceEnumeration Methods

Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the subscriber devices.
Initialize | Initializes an object of the SubscriberDeviceEnumeration class.

See Also

SubscriberDeviceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


GetEnumerator Method

 SQL Server Notification Services Books Online

SubscriberDeviceEnumeration.GetEnumerator Method

Gets an IEnumerator interface that allows you to iterate through the collection of subscriber devices represented by the SubscriberDeviceEnumeration object.

[Visual Basic .NET]
Public Function GetEnumerator() As IEnumerator Implements  IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();
[C++]
public: IEnumerator* GetEnumerator();
[JScript]
public function GetEnumerator() : IEnumerator;
Return Value

An IEnumerator interface for the SubscriberDeviceEnumeration object.

Implements

IEnumerable.GetEnumerator

Remarks

Use this method to return an IEnumerator interface that allows you to iterate through the subscriber devices in a SubscriberDeviceEnumeration object. An initialized SubscriberDeviceEnumeration object represents the collection of devices for one subscriber in a specified Notification Services instance.

Example
[Visual Basic .NET, C#]

The following examples show how to use a SubscriberDeviceEnumeration object to iterate through a set of subscriber devices. The GetEnumerator method makes the For Each and foreach statements possible:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim subscriberId As String = txtSubscriberId.Text

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a SubscriberDeviceEnumeration object.
Dim mySubscriberDeviceEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriberDeviceEnumeration(myInstance, subscriberId)

'Iterate through the subscriber devices.
Dim subscriberDevice As Microsoft.SqlServer.NotificationServices.SubscriberDevice
For Each subscriberDevice In mySubscriberDeviceEnumeration
   Console.WriteLine("Device Name: {0}", subscriberDevice.DeviceName)
Next subscriberDevice
[C#]
string instanceName = "MyInstanceName";
string subscriberId = txtSubscriberId.Text;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a SubscriberDeviceEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriberDeviceEnumeration mySubscriberDeviceEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriberDeviceEnumeration(myInstance, subscriberId);

//Iterate through the subscriber devices.
foreach (Microsoft.SqlServer.NotificationServices.SubscriberDevice subscriberDevice in mySubscriberDeviceEnumeration)
{
   Console.WriteLine("Device Name: {0}", subscriberDevice.DeviceName);
}
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDeviceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

SubscriberDeviceEnumeration.Initialize Method

Initializes an object of the SubscriberDeviceEnumeration class.

[Visual Basic .NET]
Public Sub Initialize(ByVal instance As NSInstance, ByVal subscriberId As String)
[C#]
public void Initialize(NSInstance instance, string subscriberId);
[C++]
public: void Initialize(NSInstance instance, String* subscriberId);
[JScript]
public function Initialize(instance : NSInstance, subscriberId : String);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing the subscriber devices.

subscriberId

A string containing the subscriber ID of the subscriber with whom the devices are associated.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on a SubscriberDeviceEnumeration object created with the parameter-less constructor.

Example

The following example shows how to create and initialize a SubscriberDeviceEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, mySubscriberDeviceEnumeration

const instanceName = "MyInstanceName"
subscriberId = "TestSubscriber"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

set mySubscriberDeviceEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriberDeviceEnumeration")
mySubscriberDeviceEnumeration.Initialize myInstance, subscriberId
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberDeviceEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberEnumeration Class

Represents the collection of subscribers in a given Notification Services instance.

For a list of all members of this type, see SubscriberEnumeration Members.

System.Object

Microsoft.SqlServer.NotificationServices.SubscriberEnumeration
[Visual Basic .NET]
NonInheritable Public Class SubscriberEnumeration Implements ISubscriberEnumeration, IEnumerable
[C#]
public sealed class SubscriberEnumeration : ISubscriberEnumeration, IEnumerable
[C++]
public __gc __sealed class SubscriberEnumeration : public ISubscriberEnumeration, IEnumerable
[JScript]
public class SubscriberEnumeration implements public ISubscriberEnumeration, IEnumerable
Remarks

The SubscriberEnumeration class allows an application to iterate through the set of subscribers in a given Notification Services instance. It also provides an Item property to return a Subscriber object that represents a specific subscriber.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

SubscriberEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberEnumeration Members

Public Constructors
SubscriberEnumeration Constructor Overloaded. Creates a new object of the SubscriberEnumeration class.
Public Properties
Item Returns a Subscriber object, which represents an individual subscriber.

In C#, this property is the indexer for the SubscriberEnumeration class.
Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the subscribers.
Initialize | Initializes an object of the SubscriberEnumeration class.

See Also

SubscriberEnumeration Class

Microsoft.SqlServer.NotificationServices Namespace


SubscriberEnumeration Constructor

Creates a new object of the SubscriberEnumeration class.

Overload List

Creates an uninitialized object of the SubscriberEnumeration class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public SubscriberEnumeration();

[C++]

public: SubscriberEnumeration();

[JScript]

public function SubscriberEnumeration();

Creates a new object of the SubscriberEnumeration class, and initializes it with a reference to an NSInstance object.

[Visual Basic .NET]

Public Sub New(NSInstance)

[C#]

public SubscriberEnumeration(NSInstance);

[C++]

public: SubscriberEnumeration(NSInstance);

[JScript]

public function SubscriberEnumeration(NSInstance);

See Also

SubscriberEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberEnumeration Constructor ()

Creates an uninitialized object of the SubscriberEnumeration class.

[Visual Basic .NET]
Public Sub New()
[C#]
public SubscriberEnumeration();
[C++]
public: SubscriberEnumeration();
[JScript]
public function SubscriberEnumeration();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with a reference to an NSInstance object before it can be used.

Example

The following example shows how to create and initialize a SubscriberEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, mySubscriberEnumeration

const instanceName = "MyInstanceName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize a SubscriberEnumeration object.
set mySubscriberEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriberEnumeration")
mySubscriberEnumeration.Initialize myInstance
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberEnumeration Constructor (NSInstance)

Creates and initializes an object of the SubscriberEnumeration class.

[Visual Basic .NET]
Public Sub New(ByVal instance As NSInstance)
[C#]
public SubscriberEnumeration(NSInstance instance);
[C++]
public: SubscriberEnumeration(NSInstance instance);
[JScript]
public function SubscriberEnumeration(instance : NSInstance);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing the collection of subscribers.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize a SubscriberEnumeration object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a SubscriberDevice object.
Dim mySubscriberEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriberEnumeration(myInstance)
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a SubscriberEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriberEnumeration mySubscriberEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriberEnumeration(myInstance);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

SubscriberEnumeration Properties

Public Properties
Item Returns a Subscriber object, which represents an individual subscriber.

In C#, this property is the indexer for the SubscriberEnumeration class.

See Also

SubscriberEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property

 SQL Server Notification Services Books Online

SubscriberEnumeration.Item Property

Returns a reference to an individual subscriber.

In C#, this property is the indexer for the SubscriberEnumeration class.

[Visual Basic .NET]
Public Property Item(ByVal subscriberId As String) As Subscriber
[C#]
public Subscriber this[string subscriberId] {get;}
[C++]
public: __property Subscriber get_Item(String* subscriberId);
[JScript]
returnValue = SubscriberEnumerationObject.Item(subscriberId);
-or-
returnValue = SubscriberEnumerationObject(subscriberId);
Parameters

subscriberId

The identifier of the subscriber that you want returned.

Property Value

A Subscriber object, which represents an individual subscriber.

Exceptions
Exception Type | Condition
IndexOutOfRangeException | No record can be identified using the subscriber ID provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the Item property to return a Subscriber object:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim subscriberId As String = txtID.Text

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a SubscriberEnumeration object.
Dim mySubscriberEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriberEnumeration(myInstance)

'Use the Item property to return a Subscriber object.
Dim mySubscriber As Microsoft.SqlServer.NotificationServices.Subscriber = mySubscriberEnumeration(subscriberId)
[C#]
string instanceName = "MyInstanceName";
string subscriberId = txtID.Text;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a SubscriberEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriberEnumeration mySubscriberEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriberEnumeration(myInstance);

//Use the Item property to return a Subscriber object.
Microsoft.SqlServer.NotificationServices.Subscriber mySubscriber = mySubscriberEnumeration[subscriberId];
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

SubscriberEnumeration Methods

Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the subscribers.
Initialize | Initializes an object of the SubscriberEnumeration class.

See Also

SubscriberEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


GetEnumerator Method

 SQL Server Notification Services Books Online

SubscriberEnumeration.GetEnumerator Method

Gets an IEnumerator interface that allows you to iterate through the collection of subscribers represented by the SubscriberEnumeration object.

[Visual Basic .NET]
Public Function GetEnumerator() As IEnumerator Implements  IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();
[C++]
public: IEnumerator* GetEnumerator();
[JScript]
public function GetEnumerator() : IEnumerator;
Return Value

An IEnumerator interface for the SubscriberEnumeration object.

Implements

IEnumerable.GetEnumerator

Remarks

Use this method to return an IEnumerator interface that allows you to iterate through the subscribers in a SubscriberEnumeration object. An initialized SubscriberEnumeration object represents the collection of subscribers in a specified Notification Services instance.

Example
[Visual Basic .NET, C#]

The following examples show how to use a SubscriberEnumeration object to iterate through a set of subscribers. The GetEnumerator method makes the For Each and foreach statements possible:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a SubscriberEnumeration object.
Dim mySubscriberEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriberEnumeration(myInstance)

'Iterate through the subscribers.
Dim subscriber As Microsoft.SqlServer.NotificationServices.Subscriber
For Each subscriber In mySubscriberEnumeration
   Console.WriteLine("Subscriber ID: {0}", subscriber.SubscriberId)
Next subscriber
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a SubscriberEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriberEnumeration mySubscriberEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriberEnumeration(myInstance);

//Iterate through the subscribers.
foreach (Microsoft.SqlServer.NotificationServices.Subscriber subscriber in mySubscriberEnumeration)
{
   Console.WriteLine("Subscriber ID: {0}", subscriber.SubscriberId);
}
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

SubscriberEnumeration.Initialize Method

Initializes an object of the SubscriberEnumeration class.

[Visual Basic .NET]
Public Sub Initialize(ByVal instance As NSInstance)
[C#]
public void Initialize(NSInstance instance);
[C++]
public: void Initialize(NSInstance instance, String* subscriberId);
[JScript]
public function Initialize(instance : NSInstance, subscriberId : String);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing the collection of subscribers.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on a SubscriberEnumeration object created with the parameter-less constructor.

Example

The following example shows how to create and initialize a SubscriberEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, mySubscriberEnumeration

const instanceName = "MyInstanceName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize a SubscriberEnumeration object.
set mySubscriberEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriberEnumeration")
mySubscriberEnumeration.Initialize myInstance
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberLocale Class

Represents a valid subscriber locale.

For a list of all members of this type, see SubscriberLocale Members.

System.Object

Microsoft.SqlServer.NotificationServices.SubscriberLocale
[Visual Basic .NET]
NonInheritable Public Class SubscriberLocale Implements ISubscriberLocale
[C#]
public sealed class SubscriberLocale : ISubscriberLocale
[C++]
public __gc __sealed class SubscriberLocale : public ISubscriberLocale
[JScript]
public class SubscriberLocale implements ISubscriberLocale
Remarks

An object of the SubscriberLocale class represents a valid subscriber locale.

This class exists to support a set of subscriber locale properties and expose them for use in your subscription management application. The subscriber locale code is used to specify the language and country/region of the subscriber, so that notifications can be appropriately formatted.

The SubscriberLocale class has no public constructor. Use the SubscriberLocaleEnumeration.Item property to obtain a reference to a SubscriberLocale object.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

SubscriberLocale Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberLocale Members

Public Properties
Locale Gets the locale string.

See Also

SubscriberLocale Class

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

SubscriberLocale Properties

Public Properties
Locale Gets the locale string.

See Also

SubscriberLocale Members

Microsoft.SqlServer.NotificationServices Namespace


Locale Property

 SQL Server Notification Services Books Online

SubscriberLocale.Locale Property

Gets the locale information.

[Visual Basic .NET]
Public Property Locale As String
[C#]
public string Locale {get;}
[C++]
public: __property String* get_Locale();
[JScript]
public function get Locale() : String;
Property Value

A string containing the locale information.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberLocale Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberLocaleEnumeration Class

Represents the collection of subscriber locales available within a given Notification Services instance.

For a list of all members of this type, see SubscriberLocaleEnumeration Members.

System.Object

Microsoft.SqlServer.NotificationServices.SubscriberLocaleEnumeration
[Visual Basic .NET]
Public Class SubscriberLocaleEnumeration Implements ISubscriberLocaleEnumeration, IEnumerable
[C#]
public class SubscriberLocaleEnumeration : ISubscriberLocaleEnumeration, IEnumerable
[C++]
public __gc __sealed class SubscriberLocaleEnumeration : public ISubscriberLocaleEnumeration, IEnumerable
[JScript]
public class SubscriberLocaleEnumeration implements ISubscriberLocaleEnumeration, IEnumerable
Remarks

The SubscriberLocaleEnumeration class allows an application to iterate through the set of valid subscriber locales. It also provides an Item property to return a SubscriberLocale object that represents a specific locale.

This class allows you to populate a subscriber locale drop-down box in your subscription management application.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

SubscriberLocaleEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberLocaleEnumeration Members

Public Constructors
SubscriberLocaleEnumeration Constructor Overloaded. Creates a new object of the SubscriberLocaleEnumeration class.
Public Properties
Item Returns a SubscriberLocale object, which represents a valid subscriber locale.

In C#, this property is the indexer for the SubscriberLocaleEnumeration class.
Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the subscriber locales.
Initialize | Initializes an object of the SubscriberLocaleEnumeration class.

See Also

SubscriberLocaleEnumeration Class

Microsoft.SqlServer.NotificationServices Namespace


SubscriberLocaleEnumeration Constructor

Creates a new object of the SubscriberLocaleEnumeration class.

Overload List

Creates an uninitialized object of the SubscriberLocaleEnumeration class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public SubscriberLocaleEnumeration();

[C++]

public: SubscriberLocaleEnumeration();

[JScript]

public function SubscriberLocaleEnumeration();

Creates a new object of the SubscriberLocaleEnumeration class, and initializes it with a reference to an NSInstance object.

[Visual Basic .NET]

Public Sub New(NSInstance)

[C#]

public SubscriberLocaleEnumeration(NSInstance);

[C++]

public: SubscriberLocaleEnumeration(NSInstance);

[JScript]

public function SubscriberLocaleEnumeration(NSInstance);

See Also

SubscriberLocaleEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberLocaleEnumeration Constructor ()

Creates an uninitialized object of the SubscriberLocaleEnumeration class.

[Visual Basic .NET]
Public Sub New()
[C#]
public SubscriberLocaleEnumeration();
[C++]
public: SubscriberLocaleEnumeration();
[JScript]
public function SubscriberLocaleEnumeration();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with a reference to an NSInstance object before it can be used.

Example

The following example shows how to create and initialize a SubscriberLocaleEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, mySubscriberLocaleEnumeration

const instanceName = "MyInstanceName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize a SubscriberLocaleEnumeration object.
set mySubscriberLocaleEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriberLocaleEnumeration")
mySubscriberLocaleEnumeration.Initialize myInstance
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberLocaleEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberLocaleEnumeration Constructor (NSInstance)

Creates and initializes an object of the SubscriberLocaleEnumeration class.

[Visual Basic .NET]
Public Sub New(ByVal instance As NSInstance)
[C#]
public SubscriberLocaleEnumeration(NSInstance instance);
[C++]
public: SubscriberLocaleEnumeration(NSInstance instance);
[JScript]
public function SubscriberLocaleEnumeration(instance : NSInstance);
Parameters

instance

An NSInstance object that represents the Notification Services instance that contains the collection of subscriber locales.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize a SubscriberLocaleEnumeration object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a SubscriberLocaleEnumeration object.
Dim mySubscriberLocaleEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriberLocaleEnumeration(myInstance)
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a SubscriberLocaleEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriberLocaleEnumeration mySubscriberLocaleEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriberLocaleEnumeration(myInstance);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberLocaleEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

SubscriberLocaleEnumeration Properties

Public Properties
Item Returns a SubscriberLocale object, which represents a valid subscriber locale.

In C#, this property is the indexer for the SubscriberLocaleEnumeration class.

See Also

SubscriberLocaleEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property

 SQL Server Notification Services Books Online

SubscriberLocaleEnumeration.Item Property

Returns a SubscriberLocale object, which represents a valid subscriber locale.

[C#]

In C#, this property is the indexer for the SubscriberLocaleEnumeration class.

[Visual Basic .NET]
Public Property Item(ByVal locale As String) As SubscriberLocale
[C#]
public SubscriberLocale this[string locale] {get;}
[C++]
public: __property SubscriberLocale get_Item(String* locale);
[JScript]
returnValue = SubscriberLocaleEnumerationObject.Item(locale);
-or-
returnValue = SubscriberLocaleEnumerationObject(locale);
Parameters

locale

The 10-character locale string of the locale that you want returned.

Property Value

A SubscriberLocale object, which represents a locale.

Exceptions
Exception Type | Condition
IndexOutOfRangeException | No record can be identified using the locale provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the Item property to return a Locale object:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim locale As String = "en-US"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a SubscriberLocaleEnumeration object.
Dim mySubscriberLocaleEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriberLocaleEnumeration(myInstance)

'Use the Item property to return a SubscriberLocale object.
Dim mySubscriberLocale As Microsoft.SqlServer.NotificationServices.SubscriberLocale = mySubscriberLocaleEnumeration(locale)
[C#]
string instanceName = "MyInstanceName";
string locale = "en-US";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a SubscriberLocaleEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriberLocaleEnumeration mySubscriberLocaleEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriberLocaleEnumeration(myInstance);

//Use the Item property to return a SubscriberLocale object.
Microsoft.SqlServer.NotificationServices.SubscriberLocale mySubscriberLocale = mySubscriberLocaleEnumeration[locale];
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberLocaleEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

SubscriberLocaleEnumeration Methods

Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the subscriber locales.
Initialize | Initializes an object of the SubscriberLocaleEnumeration class.

See Also

SubscriberLocaleEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


GetEnumerator Method

 SQL Server Notification Services Books Online

SubscriberLocaleEnumeration.GetEnumerator Method

Gets an IEnumerator interface that allows you to iterate through the collection of subscriber locales represented by the SubscriberLocaleEnumeration object.

[Visual Basic .NET]
Public Function GetEnumerator() As IEnumerator Implements  IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();
[C++]
public: IEnumerator* GetEnumerator();
[JScript]
public function GetEnumerator() : IEnumerator;
Return Value

An IEnumerator interface for the SubscriberLocaleEnumeration object.

Implements

IEnumerable.GetEnumerator

Remarks

Use this method to return an IEnumerator interface that allows you to iterate through the subscriber locales in a SubscriberLocaleEnumeration object. An initialized SubscribeLocaleEnumeration object represents the collection of subscriber locales in a specified Notification Services instance.

Example
[Visual Basic .NET, C#]

The following examples show how to use a SubscriberLocaleEnumeration object to iterate through a set of subscriber locales. The GetEnumerator method makes the For Each and foreach statements possible:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a SubscriberLocaleEnumeration object.
Dim mySubscriberLocaleEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriberLocaleEnumeration(myInstance)

'Iterate through the subscriber locales.
Dim subscriberLocale As Microsoft.SqlServer.NotificationServices.SubscriberLocale
For Each subscriberLocale In  mySubscriberLocaleEnumeration
   Console.WriteLine("Locale: {0}", subscriberLocale.Locale)
Next subscriberLocale
[C#]
string instanceName = "MyInstanceName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a SubscriberLocaleEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriberLocaleEnumeration mySubscriberLocaleEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriberLocaleEnumeration(myInstance);

//Iterate through the subscriber locales.
foreach (Microsoft.SqlServer.NotificationServices.SubscriberLocale subscriberLocale in mySubscriberLocaleEnumeration)
{
   Console.WriteLine("Locale: {0}", subscriberLocale.Locale);
}
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberLocaleEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

SubscriberLocaleEnumeration.Initialize Method

Initializes an object of the SubscriberLocaleEnumeration class. Is used in conjunction with the parameter-less constructor to enable COM interoperability.

[Visual Basic .NET]
Public Sub Initialize(ByVal instance As NSInstance)
[C#]
public void Initialize(NSInstance instance);
[C++]
public: void Initialize(NSInstance instance);
[JScript]
public function Initialize(instance : NSInstance);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing the collection of subscriber locales.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on a SubscriberLocaleEnumeration object created with the parameter-less constructor.

Example

The following example shows how to create and initialize a SubscriberLocaleEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, mySubscriberLocaleEnumeration

const instanceName = "MyInstanceName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize a SubscriberLocaleEnumeration object.
set mySubscriberLocaleEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriberLocaleEnumeration")
mySubscriberLocaleEnumeration.Initialize myInstance
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriberLocaleEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Subscription Class

Represents a single subscription.

For a list of all members of this type, see Subscription Members.

System.Object

Microsoft.SqlServer.NotificationServices.Subscription
[Visual Basic .NET]
NonInheritable Public Class Subscription Implements ISubscription
[C#]
public sealed class Subscription : ISubscription
[C++]
public __gc __sealed class Subscription : public ISubscription
[JScript]
public class Subscription implements ISubscription
Remarks

This class represents a single subscription within a specified Notification Services application, belonging to a single subscriber. It provides an Item property to return application-specific subscription data fields.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


Subscription Members

Public Constructors
Subscription Constructor Overloaded. Creates a new object of the Subscription class.
Public Properties
Enabled | Gets or sets the status of the subscription record. A value of true indicates the subscription is enabled to generate notifications. This property default is true.
FieldCount | Returns the number of developer-defined subscription fields for this subscription, as specified in a subscription class in the application definition file (ADF).
HasTimedRule | Returns true if the subscription has one or more scheduled subscription rules.
Item | Overloaded. Gets or sets the value of a field in the subscription. In C#, this property is the indexer for the Subscription class.
NSApplication | Gets an NSApplication object representing the Notification Services application that contains this subscription.
ScheduleRecurrence | Gets or sets the schedule recurrence information. This property can be null if ScheduleStart is also null; otherwise this property must have a specified value.
ScheduleStart | Gets or sets the schedule start date and time. This property can be null if ScheduleRecurrence is also null; otherwise this property must have a specified value.
SubscriberId | Gets or sets the subscriber ID that identifies the subscriber with which this subscription is associated.
SubscriptionClass | Gets a SubscriptionClass object representing the subscription class that defines this subscription.
SubscriptionId | Gets or sets the subscription identifier for a subscription record.
Public Methods
Add | Adds a subscription record to the application database.
Delete | Deletes a subscription record from the application database.
GetFieldName | Returns the name of a subscription class field when passed a field ordinal.
GetFieldOrdinal | Returns the ordinal of a subscription class field when passed a field name.
GetFieldValue | Returns the value of a field in the subscription record when passed a field name. This method is provided for COM interoperability.
Initialize | Initializes an object of the Subscription class.
SetFieldValue | Sets the value of a field in the subscription record when passed a field name. This method is provided for COM interoperability.
Update | Modifies a subscription record in the application database.

See Also

Subscription Class

Microsoft.SqlServer.NotificationServices Namespace


Subscription Constructor

Creates a new object of the Subscription class.

Overload List

Creates an uninitialized object of the Subscription class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public Subscription();

[C++]

public: Subscription();

[JScript]

public function Subscription();

Creates a new object of the Subscription class, and initializes it with a reference to an NSApplication object and a subscription class name.

[Visual Basic .NET]

Public Sub New(NSApplication, String)

[C#]

public Subscription(NSApplication, string);

[C++]

public: Subscription(NSApplication, String*);

[JScript]

public function Subscription(NSApplication, String);

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


Subscription Constructor ()

Creates an uninitialized object of the Subscription class.

[Visual Basic .NET]
Public Sub New()
[C#]
public Subscription();
[C++]
public: Subscription();
[JScript]
public function Subscription();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with a reference to an NSApplication object and a subscription class name before it can be used.

Example

The following example shows how to create and initialize a Subscription object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, mySubscription

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const subscriptionClassName = "MySubscriptionClassName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize a Subscription object.
set mySubscription = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscription")
mySubscription.Initialize myApplication, subscriptionClassName
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


Subscription Constructor (NSApplication, String)

Creates and initializes an object of the Subscription class.

[Visual Basic .NET]
Public Sub New(ByVal application As NSApplication, ByVal subscriptionClassName As _ String)
[C#]
public Subscription(NSApplication application, string subscriptionClassName);
[C++]
public: SubscriberEnumeration(NSApplication application, String* subscriptionClassName);
[JScript]
public function SubscriberEnumeration(application : NSApplication, subscriptionClassName : String);
Parameters

application

An NSApplication object that represents the Notification Services application to which the Subscription object provides subscription data.

subscriptionClassName

A string containing the name of the subscription class that defines the subscription data provided by the Subscription object.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize a Subscription object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a Subscription object.
Dim mySubscription As New Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = new Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

Subscription Properties

Public Properties
Enabled | Gets or sets the status of the subscription record. A value of true indicates the subscription is enabled to generate notifications. This property default is true.
FieldCount | Returns the number of developer-defined subscription fields for this subscription, as specified in the subscription class schema in the application definition file (ADF).
HasTimedRule | Returns true if the subscription has one or more scheduled subscription rules.
Item | Overloaded. Gets or sets the value of a field in the subscription. In C#, this property is the indexer for the Subscription class.
NSApplication | Gets an NSApplication object representing the Notification Services application that contains this subscription.
ScheduleRecurrence | Gets or sets the schedule recurrence information. This property can be null if ScheduleStart is also null; otherwise this property must have a specified value.
ScheduleStart | Gets or sets the schedule start date and time. This property can be null if ScheduleRecurrence is also null; otherwise this property must have a specified value.
SubscriberId | Gets or sets the subscriber ID that identifies the subscriber with which this subscription is associated.
SubscriptionClass | Gets a SubscriptionClass object representing the subscription class that defines this subscription.
SubscriptionId | Gets or sets the subscription identifier for a subscription record.

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


Enabled Property

 SQL Server Notification Services Books Online

Subscription.Enabled Property

Gets or sets the status of a subscription.

[Visual Basic .NET]
Public Property Enabled As Boolean
[C#]
public bool Enabled {get;set;}
[C++]
public: __property bool Enabled();
public: __property void set_Enabled(bool);
[JScript]
public function get Enabled() : Boolean;
public function set Enabled(Boolean);
Property Value

A Boolean value indicating whether the subscription is enabled.

Remarks

This property gets or sets the status of a subscription, by changing the value of the Enabled field in the subscription record.

The Enabled field allows you to enable or disable a subscription within the Notification Services system. When the Enabled property value is true, the subscription is active and can generate notifications. When the Enabled property value is false, the subscription is disabled.

This property default is true.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


FieldCount Property

 SQL Server Notification Services Books Online

Subscription.FieldCount Property

Returns the number of developer-defined subscription fields for this subscription, as specified in a subscription class schema in the application definition file (ADF).

[Visual Basic .NET]
Public Property FieldCount As Integer
[C#]
public int FieldCount {get;}
[C++]
public: __property int get_FieldCount();
[JScript]
public function get FieldCount() : int;
Property Value

An integer representing the number of developer-defined data fields in a subscription class.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


HasTimedRule Property

 SQL Server Notification Services Books Online

Subscription.HasTimedRule Property

Indicates whether this subscription has one or more scheduled rules.

[Visual Basic .NET]
Public Property HasTimedRule As Boolean
[C#]
public bool HasTimedRule {get;}
[C++]
public: __property bool get_HasTimedRule();
[JScript]
public function get HasTimedRule() : Boolean;
Property Value

A Boolean value indicating whether the subscription class that defines this subscription has one or more subscription scheduled rules. These rules are defined in the application definition file (ADF).

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property

 SQL Server Notification Services Books Online

Subscription.Item Property

Gets or sets the value of a field in the subscription record.

[C#]

In C#, this property is the indexer for the Subscription class.

Overload List

Gets or sets the value of a field in the subscription record, using the field name as an identifier.

[Visual Basic .NET]

Public Property Item(String) As Object

[C#]

public object this[string] {get;set;}

[C++]

public: __property Object* get_Item(String*);

public: __property void set_Item(String*, Object*);

[JScript]

Subscription.Item (String)

Gets or sets the value of a field in the subscription record, using the field ordinal as an identifier.

[Visual Basic .NET]

Public Property Item(Integer) As Object

[C#]

public Object this[int] {get;set;}

[C++]

public: __property Object* get_Item(int);

public: __property void set_Item(int, Object*);

[JScript]

Subscription.Item (int)

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property (String)

 SQL Server Notification Services Books Online
Subscription.Item Property (String)

Gets or sets the value of a field in the subscription record, using the field name as an identifier.

[Visual Basic .NET]
Public Property Item(ByVal fieldName As String) As Object
[C#]
public Object this[string fieldName] {get;set;}
[C++]
public: __property Object* get_Item(String* fieldName);
public: __property void set_Item(String* fieldName, Object*);
[JScript]
returnValue = SubscriptionObject.Item(fieldName);
SubscriptionObject.Item(fieldName) = value;
-or-
returnValue = SubscriptionObject(fieldName);
SubscriptionObject(fieldName) = value;
Parameters

fieldName

The name of the subscription field for which you want the value returned.

Property Value

An object that represents the field's value.

Exceptions
Exception Type | Condition
IndexOutOfRange | No subscription field can be identified using the field name provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the Item property to set a field value:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"
Dim subscriptionFieldName As String = "MySubscriptionFieldName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a Subscription object.
Dim mySubscription As New Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName)

'Use the Item property to set a field value.
mySubscription(subscriptionFieldName) = txtFieldValue.Text
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";
string subscriptionFieldName = "MySubscriptionFieldName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = new Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName);

//Use the Item property to set a field value.
mySubscription[subscriptionFieldName] = txtFieldValue.Text;
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property (Int32)

 SQL Server Notification Services Books Online
Subscription.Item Property (Int32)

Gets or sets the value of a field in the subscription record, using the field ordinal as an identifier.

[Visual Basic .NET]
Public Property Item(ByVal fieldOrdinal As Integer) As Object
[C#]
public Object this[int fieldOrdinal] {get;set;}
[C++]
public: __property Object* get_Item(int fieldOrdinal);
public: __property void set_Item(int fieldOrdinal, Object*);
[JScript]
returnValue = SubscriptionObject.Item(fieldOrdinal);
SubscriptionObject.Item(fieldOrdinal) = returnValue;
-or-
returnValue = SubscriptionObject(fieldOrdinal);
SubscriptionObject(fieldOrdinal) = returnValue;
Parameters

fieldOrdinal

The zero-based ordinal of the subscription field for which you want the value returned.

Property Value

An object that represents the field's value.

Exceptions
Exception Type | Condition
IndexOutOfRange | No subscription field can be identified using the field ordinal provided.
Remarks

This property is not available in COM interop. Because only one overload of a given property or method can be made available in COM interop, the String overload of the Item property was chosen because it is more widely used.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Item property to set a field value:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a Subscription object.
Dim mySubscription As New Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName)

'Use the Item property to set a field value.
mySubscription(0) = txtFieldValue.Text
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = new Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName);

//Use the Item property to set a field value.
mySubscription[0] = txtFieldValue.Text;
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


NSApplication Property

 SQL Server Notification Services Books Online

Subscription.NSApplication Property

Gets an NSApplication object representing the Notification Services application that contains this subscription.

[Visual Basic .NET]
Public Property NSApplication As NSApplication
[C#]
public NSApplication NSApplication {get;}
[C++]
public: __property NSApplication get_NSApplication();
[JScript]
public function get NSApplication() : NSApplication;
Property Value

An NSApplication object representing the Notification Services application that contains this subscription.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


ScheduleRecurrence Property

 SQL Server Notification Services Books Online

Subscription.ScheduleRecurrence Property

Gets or sets the schedule recurrence information.

[Visual Basic .NET]
Public Property ScheduleRecurrence As String
[C#]
public string ScheduleRecurrence {get;set;}
[C++]
public: __property String* get_ScheduleRecurrence();
public: __property void set_ScheduleRecurrence(String*);
[JScript]
public function get ScheduleRecurrence() : String;
public function set ScheduleRecurrence(String);
Property Value

A string containing schedule recurrence information.

Exceptions
Exception Type | Condition
NSException with an NSEventEnum.NotScheduledSubscription argument | A subscription with no scheduled rules (where the HasTimedRule property is false) has attempted to specify values for the ScheduleStart and ScheduleRecurrence properties.
Remarks

The ScheduleRecurrence property can be null if the ScheduleStart property is also null; otherwise ScheduleRecurrence must have a specified value. These properties are used together to assign a schedule to a subscription.

The value of the ScheduleRecurrence property must be in ICalendar interface format and use ICalendar recurrence rule syntax. All alphabetic characters in the ScheduleRecurrence property value must be in upper case.

A subscription with no timed rules (where the HasTimedRule property is false) does not permit values to be specified for the ScheduleStart and ScheduleRecurrence properties.

The ICalendar recurrence options are shown in the following table.

ICalendar Recurrence Options
FREQ=DAILY;
FREQ=WEEKLY;BYDAY=DaysOfWeekList;[BYMONTH=MonthsOfYearList;]
FREQ=MONTHLY;BYMONTHDAY=DaysOfMonthList;[BYMONTH=MonthsOfYearList;]
FREQ=YEARLY;BYMONTHDAY=DayOfMonth;BYMONTH=MonthOfYear;

The options that can be used to specify the schedule are:

  • DaysOfWeekList is [DayOfWeek | DayOfWeek,DaysOfWeekList]

    DayOfWeek is [MO | TU | WE | TH | FR | SA | SU]

  • DaysOfMonthList is [DayOfMonth | DayOfMonth,DaysOfMonthList]

    DayOfMonth is [1 | 2 | 3 | ... | 30 | 31]

  • MonthsOfYearList is [MonthOfYear | MonthOfYear,MonthsOfYearList]

    MonthOfYear is [1 | 2 | 3 | ... | 11 | 12]

For example, a valid ScheduleRecurrence value for recurrences on the first and last three months, for the first, eleventh, and fiftheenth days of those months, would be FREQ=MONTHLY;BYMONTHDAY=1,11,15;BYMONTH=1,2,3,10,11,12.

Example
[Visual Basic .NET, C#]

The following examples show how to use the ScheduleRecurrence property to set subscription schedule recurrence information:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a Subscription object.
Dim mySubscription As New Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName)

'Set subscription schedule recurrence information.
Dim myStringBuilder As New System.Text.StringBuilder()
myStringBuilder.AppendFormat("FREQ=MONTHLY;BYMONTHDAY={0};BYMONTH={1}", txtDays.Text, txtMonths.Text)
mySubscription.ScheduleRecurrence = myStringBuilder.ToString()
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = new Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName);

//Set subscription schedule recurrence information.
System.Text.StringBuilder myStringBuilder = new System.Text.StringBuilder();
myStringBuilder.AppendFormat(
   "FREQ=MONTHLY;BYMONTHDAY={0};BYMONTH={1}",
   txtDays.Text,
   txtMonths.Text);
mySubscription.ScheduleRecurrence = myStringBuilder.ToString();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


ScheduleStart Property

 SQL Server Notification Services Books Online

Subscription.ScheduleStart Property

Gets or sets the schedule start information.

[Visual Basic .NET]
Public Property ScheduleStart As String
[C#]
public string ScheduleStart {get;set;}
[C++]
public: __property String* get_ScheduleStart();
public: __property void set_ScheduleStart(String*);
[JScript]
public function get ScheduleStart() : String;
public function set ScheduleStart(String);
Property Value

A string containing schedule start information.

Exceptions
Exception Type | Condition
NSException with an NSEventEnum.NotScheduledSubscription argument | A subscription with no scheduled rules (where the HasTimedRule property is false) has attempted to specify values for the ScheduleStart and ScheduleRecurrence properties.
Remarks

The ScheduleStart property can be null if the ScheduleRecurrence property is also null; otherwise ScheduleStart must have a specified value. These properties are used together to assign a schedule to a subscription.

A subscription with no timed rules (where the HasTimedRule property is false) does not permit values to be specified for the ScheduleStart and ScheduleRecurrence properties.

You can specify the ScheduleStart value by using one of the following notations:

TZID=TimeZoneId: yyyymmdd T hhnnss

yyyymmdd T hhnnss Z

where the format indicates the following:

  • TimeZoneId is the time zone ID.
  • T is the uppercase character "T". It is the date-time separation character and it must appear between the date and time.
  • Z is the uppercase character "Z". It represents "UTC Time". It is equivalent to specifying "TZID=UTC Time:".
  • yyyy is the four-digit year.

    [2000 | 2001 | 2002 | 2003 | ...]

  • mm is the two-digit month of the year.

    [01 | 02 | 03 | ... | 11 | 12]

  • dd is the two-digit day of the month.

    [01 | 02 | 03 | ... | 30 | 31]

  • hh is the two-digit hour in 24-hour time.

    [00 | 01 | 02 | 03 | ... | 12 | 13 | ... | 22 | 23]

  • nn is the two-digit minute.

    [00 | 01 | 02 | 03 | ... | 58 | 59]

  • ss is the two-digit second.

    [00 | 01 | 02 | 03 | ... | 58 | 59]

Specifying the Notification Services time zone ID (returned by a TimeZoneEnumeration object) causes that subscription to be enabled for the selected time zone. Otherwise, you must use the constant Z to indicate that you are using Universal Time Coordinate (UTC) notation instead.

The time and time zone specify the local time of day at which the notification is generated. Notification Services uses the time zone to convert the local time of day to Greenwich Mean Time (GMT) time. Notification Services is aware of daylight savings time transitions and adjusts delivery times accordingly.

For example, a valid ScheduleStart value would be 20010501T093000Z.

Example
[Visual Basic .NET, C#]

The following examples show how to use the ScheduleStart property to set subscription schedule start information:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a Subscription object.
Dim mySubscription As New Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName)

'Set subscription schedule start information.
Dim myStringBuilder As New System.Text.StringBuilder()
myStringBuilder.AppendFormat("TZID={0}:{1}{2}{3}T{4}{5}{6}", ddTimeZones.SelectedItem.ToString().Trim(), DateTime.Now.Year.ToString("D4"), DateTime.Now.Month.ToString("D2"), DateTime.Now.Day.ToString("D2"), ddHours.SelectedItem.ToString().Trim(), ddMinutes.SelectedItem.ToString().Trim(), ddSeconds.SelectedItem.ToString().Trim())
mySubscription.ScheduleStart = myStringBuilder.ToString()
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = new Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName);

//Set subscription schedule start information.
System.Text.StringBuilder myStringBuilder = new System.Text.StringBuilder();
myStringBuilder.AppendFormat("TZID={0}:{1}{2}{3}T{4}{5}{6}", ddTimeZones.SelectedItem.ToString().Trim(), DateTime.Now.Year.ToString("D4"), DateTime.Now.Month.ToString("D2"), DateTime.Now.Day.ToString("D2"), ddHours.SelectedItem.ToString().Trim(), ddMinutes.SelectedItem.ToString().Trim(), ddSeconds.SelectedItem.ToString().Trim ()); mySubscription.ScheduleStart = myStringBuilder.ToString();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriberId Property

 SQL Server Notification Services Books Online

Subscription.SubscriberId Property

Gets or sets the subscriber ID for this subscription.

[Visual Basic .NET]
Public Property SubscriberId As String
[C#]
public string SubscriberId {get;set;}
[C++]
public: __property String* get_SubscriberId();
public: __property void set_SubscriberId(String*);
[JScript]
public function get SubscriberId() : String;
public function set SubscriberId(String);
Property Value

A string containing the subscriber ID for this subscription.

Exceptions
Exception Type | Condition
IndexOutOfRangeException | No related subscriber record can be identified using the subscriber ID provided.
Remarks

The subscriber ID identifies the subscriber with which this subscription is associated.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionClass Property

 SQL Server Notification Services Books Online

Subscription.SubscriptionClass Property

Gets a SubscriptionClass object representing the subscription class that defines this subscription.

[Visual Basic .NET]
Public Property SubscriptionClass As SubscriptionClass
[C#]
public SubscriptionClass SubscriptionClass {get;}
[C++]
public: __property SubscriptionClass get_SubscriptionClass();
[JScript]
public function get SubscriptionClass() : SubscriptionClass;
Property Value

A SubscriptionClass object representing the subscription class that defines this subscription.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionId Property

 SQL Server Notification Services Books Online

Subscription.SubscriptionId Property

Gets or sets the subscription identifier for a subscription record.

[Visual Basic .NET]
Public Property SubscriptionId As String
[C#]
public string SubscriptionId {get;set;}
[C++]
public: __property String* get_SubscriptionId();
public: __property void set_SubscriptionId(String*);
[JScript]
public function get SubscriptionId() : String;
public function set SubscriptionId(String);
Property Value

A string containing the subscription ID for this subscription.

Remarks

When a new subscription is added to the database, Notification Services assigns it a unique subscription ID. Notification Services components use this subscription ID to identify the subscription.

Setting the subscription ID in a procedure causes all subsequent update and delete actions to be performed on the record identified by the subscription ID that was set, and not on the record that was originally retrieved.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

Subscription Methods

Public Methods
Add | Adds a subscription record to the application database.
Delete | Deletes a subscription record from the application database.
GetFieldName | Returns the name of a subscription class field when passed a field ordinal.
GetFieldOrdinal | Returns the ordinal of a subscription class field when passed a field name.
GetFieldValue | Returns the value of a field in the subscription record when passed a field name. This method is provided for COM interoperability.
Initialize | Initializes an object of the Subscription class.
SetFieldValue | Sets the value of a field in the subscription record when passed a field name. This method is provided for COM interoperability.
Update | Modifies a subscription record in the application database.

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


Add Method

 SQL Server Notification Services Books Online

Subscription.Add Method

Adds a subscription record to the application database.

[Visual Basic .NET]
Public Function Add() As String
[C#]
public string Add();
[C++]
public: String* Add();
[JScript]
public function Add() : String;
Return Value

A string containing the subscription ID of the new subscription.

Exceptions
Exception Type | Condition
NSException with an NSEventEnum.InvalidField argument | One of the fields in the event data fails to meet a database requirement or a constraint (such as a column data type).
NSException with an NSEventEnum.MissingField argument | One of the fields in the event data fails to meet a NOT NULL requirement in the event table.
NSException with an NSEventEnum.FailedToAddSubscription argument | The subscription record could not be added. Check the event log for further details.
Remarks

When a new subscription is added to the database, Notification Services assigns it a unique subscription ID. Notification Services components use this subscription ID to identify the subscription.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Add method to add a subscription:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a Subscription object.
Dim mySubscription As New Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName)

'Add code to set subscription info here.

Dim subscriptionId As String = mySubscription.Add()
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = new Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName);

//Add code to set subscription info here.

string subscriptionId = mySubscription.Add();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


Delete Method

 SQL Server Notification Services Books Online

Subscription.Delete Method

Deletes a subscription record from the Notification Services database.

[Visual Basic .NET]
Public Sub Delete()
[C#]
public void Delete();
[C++]
public: void Delete();
[JScript]
public function Delete();
Exceptions
Exception Type | Condition
NSException with an NSEventEnum.FailedToDeleteSubscriptions argument | The subscription record could not be deleted. Check the event log for further details.
NSException with an NSEventEnum.InvalidSubscriptionData argument | The subscription ID is set to 0.
NSException with an NSEventEnum.SubscriptionsDisabledForApplication argument | Subscription updates are disabled for this application.
Remarks

This method removes the subscription from the system.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Delete method to delete a subscription:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a Subscription object.
Dim mySubscription As New Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName)

'Set the subscription ID, so that the
'correct subscription will be deleted.
mySubscription.SubscriptionId = txtID.Text

'Delete the subscription record from the database.
 mySubscription.Delete()
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = new Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName);

//Set the subscription ID, so that the
//correct subscription will be deleted.
mySubscription.SubscriptionId = txtID.Text;

//Delete the subscription record from the database.
mySubscription.Delete();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


GetFieldName Method

 SQL Server Notification Services Books Online

Subscription.GetFieldName Method

Returns the name of a field in the subscription record.

[Visual Basic .NET]
Public Function GetFieldName(ByVal fieldOrdinal As Integer) As String
[C#]
public string GetFieldName(int fieldOrdinal);
[C++]
public: String* GetFieldName(int fieldOrdinal);
[JScript]
public function GetFieldName(fieldOrdinal : int ) : String;
Parameters

fieldOrdinal

The zero-based ordinal of the subscription field for which you want the name returned.

Return Value

A string containing the field name.

Exceptions
Exception Type | Condition
ArgumentOutOfRangeException | No subscription field can be identified using the field ordinal provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the GetFieldName method to get the name of a subscription field by providing the field ordinal:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"
Dim fieldOrdinal As Integer = 0

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a Subscription object.
Dim mySubscription As New Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName)

'Retrieve the field name.
Dim fieldName As String = mySubscription.GetFieldName(fieldOrdinal)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";
int fieldOrdinal = 0;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = new Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName);

//Retrieve the field name.
string fieldName = mySubscription.GetFieldName(fieldOrdinal);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


GetFieldOrdinal Method

 SQL Server Notification Services Books Online

Subscription.GetFieldOrdinal Method

Returns the ordinal of a field in the subscription record.

[Visual Basic .NET]
Public Function GetFieldOrdinal(ByVal fieldname As String) As Integer
[C#]
public int GetFieldOrdinal(string fieldName);
[C++]
public: int GetFieldOrdinal(String* fieldName);
[JScript]
public function GetFieldOrdinal(fieldName : String ) : int;
Parameters

fieldName

The name of the subscription field for which you want the ordinal returned.

Return Value

An integer representing the zero-based field ordinal.

Exceptions
Exception Type | Condition
ArgumentOutOfRangeException | No subscription field can be identified using the field name provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the GetFieldOrdinal method to get the ordinal of a subscription field by providing the field name:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"
Dim fieldName As String = "MySubscriptionFieldName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a Subscription object.
Dim mySubscription As New Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName)

'Retrieve the field ordinal.
Dim fieldOrdinal As Integer = mySubscription.GetFieldOrdinal(fieldName)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";
string fieldName = "MySubscriptionFieldName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = new Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName);

//Retrieve the field ordinal.
int fieldOrdinal = mySubscription.GetFieldOrdinal(fieldName);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


GetFieldValue Method

 SQL Server Notification Services Books Online

Subscription.GetFieldValue Method

Returns the value of a field in the subscription record.

[Visual Basic .NET]
Public Function GetFieldValue(ByVal fieldName As String) As Object
[C#]
public object GetFieldValue(string fieldName);
[C++]
public: Object* GetFieldValue(String* fieldName);
[JScript]
public function GetFieldValue(fieldName : String ) : Object;
Parameters

fieldName

The name of the subscription field for which you want the value returned.

Return Value

An object that represents the value of the field.

Exceptions
Exception Type | Condition
ArgumentOutOfRangeException | No subscription field can be identified using the field name provided.
Remarks

This method is provided for COM interoperability, to allow callers from unmanaged code to get field values from a subscription record. Managed callers do not use this method.

Example

The following example shows how to use the GetFieldValue method in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code to get the value of a subscription field:

Dim myInstance, myApplication, mySubscription, fieldValue

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const subscriptionClassName = "MySubscriptionClassName"
const fieldName = "MySubscriptionFieldName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize a Subscription object.
set mySubscription = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscription")
mySubscription.Initialize myApplication, subscriptionClassName

'Get the field value.
fieldValue = mySubscription.GetFieldValue(fieldName)
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

Subscription.Initialize Method

Initializes an object of the Subscription class with a subscription class name and a reference to an NSApplication object. Is used in conjunction with the parameter-less constructor to enable COM interoperability.

[Visual Basic .NET]
Public Sub Initialize(ByVal application As NSApplication, ByVal subscriptionClassName _ As String)
[C#]
public void Initialize(NSApplication application, string subscriptionClassName);
[C++]
public: void Initialize(NSApplication application, String* subscriptionClassName);
[JScript]
public function Initialize(application : NSApplication, subscriptionClassName : String);
Parameters

application

An NSApplication object that represents the Notification Services application to which the Subscription object provides subscription data.

subscriptionClassName

A string containing the name of the subscription class that defines the subscription data that the Subscription object provides. This determines what subscription fields this Subscription object exposes.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on a Subscription object created with the parameter-less constructor.

Example

The following example shows how to create and initialize a Subscription object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, mySubscription

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const subscriptionClassName = "MySubscriptionClassName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize a Subscription object.
set mySubscription = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscription")
mySubscription.Initialize myApplication, subscriptionClassName
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


SetFieldValue Method

 SQL Server Notification Services Books Online

Subscription.SetFieldValue Method

Sets the value of a field in the subscription record.

[Visual Basic .NET]
Public Sub SetFieldValue(ByVal fieldName As String, ByVal newValue As Object)
[C#]
public void SetFieldValue(string fieldname, object newValue);
[C++]
public: void SetFieldValue(String* fieldName, Object* newValue);
[JScript]
public function SetFieldValue(fieldName : String, newValue : Object);
Parameters

fieldName

The name of the subscription field for which you want the value set.

newValue

The value to which you want the subscription field set.

Exceptions
Exception Type | Condition
ArgumentOutOfRangeException | No subscription field can be identified using the field name provided.
Remarks

This method is provided for COM interoperability, to allow callers from unmanaged code to set field values for a subscription record. Managed callers do not use this method.

Example

The following example shows how to use the SetFieldValue method in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code to set the value of a subscription field:

Dim myInstance, myApplication, mySubscription

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const subscriptionClassName = "MySubscriptionClassName"
const subscriptionFieldName = "MySubscriptionFieldName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize a Subscription object.
set mySubscription = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.Subscription")
mySubscription.Initialize myApplication, subscriptionClassName

'Set the field value.
mySubscription.SetFieldValue subscriptionFieldName, "Test"
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


Update Method

 SQL Server Notification Services Books Online

Subscription.Update Method

Updates the information in a subscription record.

[Visual Basic .NET]
Public Sub Update()
[C#]
public void Update();
[C++]
public: void Update();
[JScript]
public function Update();
Exceptions
Exception Type | Condition
NSException with an NSEventEnum.FailedToUpdateSubscriptions argument | The subscription record could not be updated. Check the event log for further details.
NSException with an NSEventEnum.InvalidSubscriptionData argument | The subscription ID is set to 0.
NSException with an NSEventEnum.SubscriptionsDisabledForApplication argument | Subscription updates are disabled for this application.
Remarks

The update applies to the record identified by the subscription ID.

Example
[Visual Basic .NET, C#]

The following examples show how to use the Update method to modify subscription information:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a Subscription object.
Dim mySubscription As New Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName)

'Set the subscription ID, so that the
'correct subscription will be updated.
mySubscription.SubscriptionId = txtID.Text

'Modify subscription info.

'Update the subscription record.
mySubscription.Update()
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = new Microsoft.SqlServer.NotificationServices.Subscription(myApplication, subscriptionClassName);

//Set the subscription ID, so that the
//correct subscription will be updated.
mySubscription.SubscriptionId = txtID.Text;

//Modify subscription info.

//Update the subscription record.
mySubscription.Update();
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Subscription Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionClass Class

Represents a subscription class, as specified in the application definition file (ADF) of a given application.

For a list of all members of this type, see SubscriptionClass Members.

System.Object

Microsoft.SqlServer.NotificationServices.SubscriptionClass
[Visual Basic .NET]
Public Class SubscriptionClass Implements ISubscriptionClass
[C#]
public class SubscriptionClass : ISubscriptionClass
[C++]
public class SubscriptionClass : public ISubscriptionClass
[JScript]
public class SubscriptionClass implements ISubscriptionClass
Remarks

The SubscriptionClass class provides access to the metadata of any subscription class defined in an ADF. It should not be confused with the Subscription class, which provides a means of adding, updating, or deleting a specified subscription in the application. It provides methods to return information about the subscription fields defined in the /SubscriptionClasses/SubscriptionClass/Schema section of the ADF for the specified subscription class.

The SubscriptionClass class has no public constructor. Use SubscriptionClassEnumeration.Item to return a SubscriptionClass object.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

SubscriptionClass Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionClass Members

Public Properties
FieldCount | Gets the number of fields specified in the /SubscriptionClasses/SubscriptionClass/Schema section of the application definition file (ADF) for this subscription class.
SubscriptionClassName | Gets the subscription class name specified in the /SubscriptionClasses/SubscriptionClass/SubscriptionClassName section of the ADF for this subscription class.
Public Methods
FieldName | Gets the field name as specified in the /SubscriptionClasses/SubscriptionClass/Schema section of the ADF when passed a field ordinal.
FieldOrdinal | Gets the field ordinal of the field based on its location in the /SubscriptionClasses/SubscriptionClass/Schema section of the ADF when passed a field name.
FieldType | Gets the field type as specified in the /SubscriptionClasses/SubscriptionClass/Schema section of the ADF when passed a field ordinal.
FieldTypeMods | Gets the field type modifications as specified in the /SubscriptionClasses/SubscriptionClass/Schema section of the ADF when passed a field ordinal.

See Also

SubscriptionClass Class

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

SubscriptionClass Properties

Public Properties
FieldCount | Gets the number of fields specified in the /SubscriptionClasses/SubscriptionClass/Schema section of the application definition file (ADF) for this subscription class.
SubscriptionClassName | Gets the subscription class name specified in the /SubscriptionClasses/SubscriptionClass/SubscriptionClassName section of the ADF for this subscription class.

See Also

SubscriptionClass Members

Microsoft.SqlServer.NotificationServices Namespace


FieldCount Property

 SQL Server Notification Services Books Online

SubscriptionClass.FieldCount Property

Gets the number of subscription fields specified in a subscription class.

[Visual Basic .NET]
Public Property FieldCount As Integer
[C#]
public int FieldCount {get;}
[C++]
public: __property int get_FieldCount();
[JScript]
public function get FieldCount() : int;
Property Value

An integer representing the number of subscription data fields in a subscription class. These are the fields defined in the /SubscriptionClasses/SubscriptionClass/Schema section of the application definition file (ADF).

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionClass Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionClassName Property

 SQL Server Notification Services Books Online

SubscriptionClass.SubscriptionClassName Property

Gets the name of a subscription class.

[Visual Basic .NET]
Public Property SubscriptionClassName As String
[C#]
public string SubscriptionClassName {get;}
[C++]
public: __property String* get_SubscriptionClassName();
[JScript]
public function get SubscriptionClassName() : String;
Property Value

A string containing the subscription class name. This is specified in the /SubscriptionClasses/SubscriptionClass/SubscriptionClassName section of the application definition file (ADF).

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionClass Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

SubscriptionClass Methods

Public Methods
FieldName | Gets the field name as specified in the /SubscriptionClasses/SubscriptionClass/Schema section of the application definition file (ADF) when passed a field ordinal.
FieldOrdinal | Gets the field ordinal of the field based on its location in the /SubscriptionClasses/SubscriptionClass/Schema section of the ADF when passed a field name.
FieldType | Gets the field type as specified in the /SubscriptionClasses/SubscriptionClass/Schema section of the ADF when passed a field ordinal.
FieldTypeMods | Gets the field type modifications as specified in the /SubscriptionClasses/SubscriptionClass/Schema section of the ADF when passed a field ordinal.

See Also

SubscriptionClass Members

Microsoft.SqlServer.NotificationServices Namespace


FieldName Method

 SQL Server Notification Services Books Online

SubscriptionClass.FieldName Method

Gets the name of a field in the subscription class.

[Visual Basic .NET]
Public Function FieldName(ByVal fieldOrdinal As Integer) As String
[C#]
public string FieldName(int fieldOrdinal);
[C++]
public: String* FieldName(int fieldOrdinal);
[JScript]
public function FieldName(fieldOrdinal : int ) : String;
Parameters

fieldOrdinal

The zero-based ordinal of the developer-defined field in the subscription class definition for which you want the name returned.

Return Value

A string containing the field name.

Exceptions
Exception Type | Condition
ArgumentOutOfRangeException | No subscription field can be identified using the field ordinal provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the FieldName method to get the name of a subscription field by providing the field ordinal:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"
Dim fieldOrdinal As Integer = 0

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a SubscriptionClassEnumeration object.
Dim mySubscriptionClassEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration(myApplication)

'Use the SubscriptionClassEnumeration.Item
'to return a SubscriptionClass object.
Dim mySubscriptionClass As Microsoft.SqlServer.NotificationServices.SubscriptionClass = mySubscriptionClassEnumeration(subscriptionClassName)

'Use the FieldName method to get a field name.
Dim fieldName As String = mySubscriptionClass.FieldName(fieldOrdinal)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";
int fieldOrdinal = 0;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a SubscriptionClassEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration mySubscriptionClassEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration(myApplication);

//Use the SubscriptionClassEnumeration.Item
//to return a SubscriptionClass object.
Microsoft.SqlServer.NotificationServices.SubscriptionClass mySubscriptionClass = mySubscriptionClassEnumeration[subscriptionClassName];

//Use the FieldName method to get a field name.
string fieldName  = mySubscriptionClass.FieldName(fieldOrdinal);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionClass Members

Microsoft.SqlServer.NotificationServices Namespace


FieldOrdinal Method

 SQL Server Notification Services Books Online

SubscriptionClass.FieldOrdinal Method

Gets the ordinal of a field in the subscription class.

[Visual Basic .NET]
Public Function FieldOrdinal(ByVal fieldName As String) As Integer
[C#]
public int FieldOrdinal(string fieldName);
[C++]
public: int FieldOrdinal(String* fieldName);
[JScript]
public function FieldOrdinal(fieldName : String ) : int;
Parameters

fieldName

The name of the developer-defined field in the subscription class definition for which you want the ordinal returned.

Return Value

An integer representing the zero-based field ordinal.

Exceptions
Exception Type | Condition
ArgumentOutOfRangeException | No subscription field can be identified using the field name provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the FieldOrdinal method to get the ordinal of a subscription field by providing the field name:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"
Dim fieldName As String = "MySubscriptionFieldName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a SubscriptionClassEnumeration object.
Dim mySubscriptionClassEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration(myApplication)

'Use the SubscriptionClassEnumeration.Item
'to return a SubscriptionClass object.
Dim mySubscriptionClass As Microsoft.SqlServer.NotificationServices.SubscriptionClass = mySubscriptionClassEnumeration(subscriptionClassName)

'Use the FieldOrdinal method to get a field ordinal.
Dim fieldOrdinal As Integer = mySubscriptionClass.FieldOrdinal(fieldName)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";
string fieldName = "MySubscriptionFieldName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a SubscriptionClassEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration mySubscriptionClassEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration(myApplication);

//Use the SubscriptionClassEnumeration.Item
//to return a SubscriptionClass object.
Microsoft.SqlServer.NotificationServices.SubscriptionClass mySubscriptionClass = mySubscriptionClassEnumeration[subscriptionClassName];

//Use the FieldOrdinal method to get a field ordinal.
int fieldOrdinal  = mySubscriptionClass.FieldOrdinal(fieldName);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionClass Members

Microsoft.SqlServer.NotificationServices Namespace


FieldType Method

 SQL Server Notification Services Books Online

SubscriptionClass.FieldType Method

Gets the data type of a field in the subscription class.

[Visual Basic .NET]
Public Function FieldType(ByVal fieldOrdinal As Integer) As String
[C#]
public string FieldType(int fieldOrdinal);
[C++]
public: String* FieldType(int fieldOrdinal);
[JScript]
public function FieldType(fieldOrdinal : int ) : String;
Parameters

fieldOrdinal

The zero-based ordinal of the developer-defined field in the subscription class definition for which you want the data type returned.

Return Value

A string containing the data type of the field.

Exceptions
Exception Type | Condition
ArgumentOutOfRangeException | No subscription field can be identified using the field ordinal provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the FieldType method to get the data type of a subscription field by providing the field ordinal:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"
Dim fieldOrdinal As Integer = 0

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a SubscriptionClassEnumeration object.
Dim mySubscriptionClassEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration(myApplication)

'Use the SubscriptionClassEnumeration.Item
'to return a SubscriptionClass object.
Dim mySubscriptionClass As Microsoft.SqlServer.NotificationServices.SubscriptionClass = mySubscriptionClassEnumeration(subscriptionClassName)

'Use the FieldType method to get a field data type.
Dim fieldType As String = mySubscriptionClass.FieldType(fieldOrdinal)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";
int fieldOrdinal = 0;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a SubscriptionClassEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration mySubscriptionClassEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration(myApplication);

//Use the SubscriptionClassEnumeration.Item
//to return a SubscriptionClass object.
Microsoft.SqlServer.NotificationServices.SubscriptionClass mySubscriptionClass = mySubscriptionClassEnumeration[subscriptionClassName];

//Use the FieldType method to get a field data type.
string fieldType  = mySubscriptionClass.FieldType(fieldOrdinal);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionClass Members

Microsoft.SqlServer.NotificationServices Namespace


FieldTypeMods Method

 SQL Server Notification Services Books Online

SubscriptionClass.FieldTypeMods Method

Gets the field modifiers of a field in the subscription class.

[Visual Basic .NET]
Public Function FieldType(ByVal fieldOrdinal As Integer) As String
[C#]
public string FieldType(int fieldOrdinal);
[C++]
public: String* FieldType(int fieldOrdinal);
[JScript]
public function FieldType(fieldOrdinal : int ) : String;
Parameters

fieldOrdinal

The zero-based ordinal of the developer-defined field in the subscription class definition for which you want the field modifiers returned.

Return Value

A string containing the field modifiers for this data field, if any are specified. Field modifiers include such information as whether the field accepts null values, or has a default specified.

Exceptions
Exception Type | Condition
ArgumentOutOfRangeException | No subscription field can be identified using the field ordinal provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the FieldTypeMods method to get the field modifiers of a subscription field by providing the field ordinal:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"
Dim fieldOrdinal As Integer = 0

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a SubscriptionClassEnumeration object.
Dim mySubscriptionClassEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration(myApplication)

'Use the SubscriptionClassEnumeration.Item
'to return a SubscriptionClass object.
Dim mySubscriptionClass As Microsoft.SqlServer.NotificationServices.SubscriptionClass = mySubscriptionClassEnumeration(subscriptionClassName)

'Use the FieldTypeMods method to get a field's modifiers.
Dim fieldTypeMods As String = mySubscriptionClass.FieldTypeMods(fieldOrdinal)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";
int fieldOrdinal = 0;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a SubscriptionClassEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration mySubscriptionClassEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration(myApplication);

//Use the SubscriptionClassEnumeration.Item
//to return a SubscriptionClass object.
Microsoft.SqlServer.NotificationServices.SubscriptionClass mySubscriptionClass = mySubscriptionClassEnumeration[subscriptionClassName];

//Use the FieldTypeMods method to get a field's modifiers.
string fieldTypeMods  = mySubscriptionClass.FieldTypeMods(fieldOrdinal);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionClass Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionClassEnumeration Class

Represents the collection of subscription classes in a given Notification Services application.

For a list of all members of this type, see SubscriptionClassEnumeration Members.

System.Object

Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration
[Visual Basic .NET]
Public Class SubscriptionClassEnumeration
Implements ISubscriptionClassEnumeration, IEnumerable
[C#]
public class SubscriptionClassEnumeration : ISubscriptionClassEnumeration, IEnumerable
[C++]
public class SubscriptionClassEnumeration : public ISubscriptionClassEnumeration, IEnumerable
[JScript]
public class SubscriptionClassEnumeration implements ISubscriptionClassEnumeration, IEnumerable
Remarks

The SubscriptionClassEnumeration class allows an application to iterate through the set of subscription classes in a given Notification Services application. It also provides an Item property to return a SubscriptionClass object that represents a specific subscription class. This class is used primarily in subscription management applications.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

SubscriptionClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionClassEnumeration Members

Public Constructors
SubscriptionClassEnumeration Constructor Overloaded. Creates a new object of the SubscriptionClassEnumeration class.
Public Properties
Count | Gets the count of subscription classes in the specified Notification Services application.
Item | Returns a SubscriptionClass object, which represents a specific subscription class. In C#, this property is the indexer for the SubscriptionClassEnumeration class.
Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the subscription classes.
Initialize | Initializes an object of the SubscriptionClassEnumeration class.

See Also

SubscriptionClassEnumeration Class

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionClassEnumeration Constructor

Creates a new object of the SubscriptionClassEnumeration class.

Overload List

Creates an uninitialized object of the SubscriptionClassEnumeration class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public SubscriptionClassEnumeration();

[C++]

public: SubscriptionClassEnumeration();

[JScript]

public function SubscriptionClassEnumeration();

Creates an object of the SubscriptionClassEnumeration class, and initializes it with a reference to an NSApplication object.

[Visual Basic .NET]

Public Sub New(NSApplication)

[C#]

public SubscriptionClassEnumeration(NSApplication);

[C++]

public: SubscriptionClassEnumeration(NSApplication);

[JScript]

public function SubscriptionClassEnumeration(NSApplication);

See Also

SubscriptionClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionClassEnumeration Constructor ()

Creates an uninitialized object of the SubscriptionClassEnumeration class.

[Visual Basic .NET]
Public Sub New()
[C#]
public SubscriptionClassEnumeration();
[C++]
public: SubscriptionClassEnumeration();
[JScript]
public function SubscriptionClassEnumeration();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with a reference to an NSApplication object before it can be used.

Example

The following example shows how to create and initialize a SubscriptionClassEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, mySubscriptionClassEnumeration

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize a SubscriptionClassEnumeration object.
set mySubscriptionClassEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration")
mySubscriptionClassEnumeration.Initialize myApplication
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionClassEnumeration Constructor (NSApplication)

Creates and initializes an object of the SubscriptionClassEnumeration class.

[Visual Basic .NET]
Public Sub New(ByVal application As NSApplication)
[C#]
public SubscriptionClassEnumeration(NSApplication application);
[C++]
public: SubscriptionClassEnumeration(NSApplication application);
[JScript]
public function SubscriptionClassEnumeration(application : NSApplication);
Parameters

application

An NSApplication object that represents the Notification Services application containing the subscription classes to be enumerated by this SubscriptionClassEnumeration object.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize an SubscriptionClassEnumeration object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a SubscriptionClassEnumeration object.
Dim mySubscriptionClassEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration(myApplication)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a SubscriptionClassEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration mySubscriptionClassEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration(myApplication);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

SubscriptionClassEnumeration Properties

Public Properties
Count | Gets the count of subscription classes in the specified Notification Services application.
Item | Returns a SubscriptionClass object, which represents a specific subscription class. In C#, this property is the indexer for the SubscriptionClassEnumeration class.

See Also

SubscriptionClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Count property

 SQL Server Notification Services Books Online

SubscriptionClassEnumeration.Count Property

Gets the count of subscription classes in a Notification Services application.

[Visual Basic .NET]
Public Property Count As Integer
[C#]
public int Count {get;}
[C++]
public: __property int get_Count();
[JScript]
public function get Count() : int;
Property Value

An integer representing the number of subscription classes in a Notification Services application.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property

 SQL Server Notification Services Books Online

SubscriptionClassEnumeration.Item Property

Gets a reference to a subscription class.

[C#]

In C#, this property is the indexer for the SubscriptionClassEnumeration class.

[Visual Basic .NET]
Public Property Item(ByVal subscriptionClassName As String) As SubscriptionClass
[C#]
public SubscriptionClass this[string subscriptionClassName] {get;}
[C++]
public: __property SubscriptionClass get_Item(String* subscriptionClassName);
[JScript]
returnValue = SubscriptionClassEnumerationObject.Item(subscriptionClassName);
-or-
returnValue = SubscriptionClassEnumerationObject(subscriptionClassName);
Parameters

subscriptionClassName

The name of the subscription class that you want returned.

Property Value

A SubscriptionClass object, which represents a specific subscription class.

Exceptions
Exception Type | Condition
IndexOutOfRangeException | No subscription class can be identified using the subscription class name provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the Item property to return a SubscriptionClass object representing a specific subscription class:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a SubscriptionClassEnumeration object.
Dim mySubscriptionClassEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration(myApplication)

'Use the Item property to return a SubscriptionClass object.
Dim mySubscriptionClass As Microsoft.SqlServer.NotificationServices.SubscriptionClass = mySubscriptionClassEnumeration(subscriptionClassName)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a SubscriptionClassEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration mySubscriptionClassEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration(myApplication);

//Use the Item property to return a SubscriptionClass object.
Microsoft.SqlServer.NotificationServices.SubscriptionClass mySubscriptionClass = mySubscriptionClassEnumeration[subscriptionClassName];
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

SubscriptionClassEnumeration Methods

Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the subscription classes.
Initialize | Initializes an object of the SubscriptionClassEnumeration class.

See Also

SubscriptionClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


GetEnumerator Method

 SQL Server Notification Services Books Online

SubscriptionClassEnumeration.GetEnumerator Method

Gets an IEnumerator interface that allows you to iterate through the collection of subscription classes represented by the SubscriptionClassEnumeration object.

[Visual Basic .NET]
Public Function GetEnumerator() As IEnumerator Implements  IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();
[C++]
public: IEnumerator* GetEnumerator();
[JScript]
public function GetEnumerator() : IEnumerator;
Return Value

An IEnumerator interface for the SubscriptionClassEnumeration object.

Implements

IEnumerable.GetEnumerator

Remarks

Use this method to return an IEnumerator interface that allows you to iterate through the subscription classes in a SubscriptionClassEnumeration object. An initialized SubscriptionClassEnumeration object represents the collection of subscription classes in a specified Notification Services application.

Example
[Visual Basic .NET, C#]

The following examples show how to use a SubscriptionClassEnumeration object to iterate through a set of subscription classes. The GetEnumerator method makes the For Each and foreach statements possible:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a SubscriptionClassEnumeration object.
Dim mySubscriptionClassEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration(myApplication)

'Iterate through the subscription classes.
Dim subscriptionClass As Microsoft.SqlServer.NotificationServices.SubscriptionClass
For Each subscriptionClass In mySubscriptionClassEnumeration
   Console.WriteLine("Subscription Class Name: {0}", subscriptionClass.SubscriptionClassName)
Next subscriptionClass
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a SubscriptionClassEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration mySubscriptionClassEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration(myApplication);

//Iterate through the subscription classes.
foreach (Microsoft.SqlServer.NotificationServices.SubscriptionClass subscriptionClass in mySubscriptionClassEnumeration)
{
Console.WriteLine("Subscription Class Name: {0}", subscriptionClass.SubscriptionClassName);
}
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

SubscriptionClassEnumeration.Initialize Method

Initializes an object of the SubscriptionClassEnumeration class.

[Visual Basic .NET]
Public Sub Initialize(ByVal application As NSApplication)
[C#]
public void Initialize(NSApplication application);
[C++]
public: void Initialize(NSApplication application);
[JScript]
public function Initialize(application : NSApplication);
Parameters

application

An NSApplication object that represents the Notification Services application containing the event classes to be enumerated by this SubscriptionClassEnumeration object.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on a SubscriptionClassEnumeration object created with the parameter-less constructor.

Example

The following example shows how to create and initialize a SubscriptionClassEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, mySubscriptionClassEnumeration

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize a SubscriptionClassEnumeration object.
set mySubscriptionClassEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriptionClassEnumeration")
mySubscriptionClassEnumeration.Initialize myApplication
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionClassEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionEnumeration Class

Represents the collection of subscriptions for a given subscriber.

For a list of all members of this type, see SubscriptionEnumeration Members.

System.Object

Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration
[Visual Basic .NET]
NonInheritable Public Class SubscriptionEnumeration Implements ISubscriptionEnumeration, IEnumerable
[C#]
public sealed class SubscriptionEnumeration : ISubscriptionEnumeration, IEnumerable
[C++]
public __gc __sealed class SubscriptionEnumeration : public ISubscriptionEnumeration, IEnumerable
[JScript]
public class SubscriptionEnumeration implements ISubscriptionEnumeration, IEnumerable
Remarks

The SubscriptionEnumeration class allows an application to iterate through the set of subscriptions for a given subscriber. The set of subscriptions is defined by the parameters provided within the constructor or the Initialize method. It also provides an Item property to return a Subscription object that represents a specific subscription.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

SubscriptionEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionEnumeration Members

Public Constructors
SubscriptionEnumeration Constructor Overloaded. Creates a new object of the SubscriptionEnumeration class.
Public Properties
Item Returns a Subscription object, which represents an individual subscription.

In C#, this property is the indexer for the SubscriptionEnumeration class.
Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the subscriptions.
Initialize | Overloaded. Initializes an object of the SubscriptionEnumeration class.

See Also

SubscriptionEnumeration Class

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionEnumeration Constructor

Creates a new object of the SubscriptionEnumeration class.

Overload List

Creates an uninitialized object of the SubscriptionEnumeration class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public SubscriptionEnumeration();

[C++]

public: SubscriptionEnumeration();

[JScript]

public function SubscriptionEnumeration();

Creates a new object of the SubscriptionEnumeration class, and initializes it with a subscription class name and a reference to an NSApplication object. The set of subscriptions returned is all subscriptions associated with a particular application and subscription class, regardless of subscriber.

[Visual Basic .NET]

Public Sub New(NSApplication, String)

[C#]

public SubscriptionEnumeration(NSApplication, string);

[C++]

public: SubscriptionEnumeration(NSApplication, String*);

[JScript]

public function SubscriptionEnumeration(NSApplication, String);

Creates a new object of the SubscriptionEnumeration class, and initializes it with a subscriber ID, a subscription class name, and a reference to an NSApplication object. The set of subscriptions returned is all subscriptions associated with a single subscriber, application, and subscription class.

[Visual Basic .NET]

Public Sub New(NSApplication, String, String)

[C#]

public SubscriptionEnumeration(NSApplication, string, string);

[C++]

public: SubscriptionEnumeration(NSApplication, String*, String*);

[JScript]

public function SubscriptionEnumeration(NSApplication, String, String);

See Also

SubscriptionEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionEnumeration Constructor ()

Creates an uninitialized object of the SubscriptionEnumeration class.

[Visual Basic .NET]
Public Sub New()
[C#]
public SubscriptionEnumeration();
[C++]
public: SubscriptionEnumeration();
[JScript]
public function SubscriptionEnumeration();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with a reference to an NSApplication object, a subscription class name, and optionally a subscriber ID before it can be used.

Example

The following example shows how to create and initialize a SubscriptionEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, mySubscriptionEnumeration, subscriberId

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const subscriptionClassName = "MySubscriptionClassName"
subscriberId = Request.Form("SubscriberId")

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize a SubscriptionEnumeration object.
set mySubscriptionEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration")
mySubscriptionEnumeration.Initialize myApplication, subscriptionClassName, subscriberId
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionEnumeration Constructor (NSApplication, String)

Creates and initializes an object of the SubscriptionEnumeration class.

The set of subscriptions returned is all subscriptions associated with a particular application and subscription class, regardless of subscriber.

[Visual Basic .NET]
Public Sub New(ByVal application As NSApplication, ByVal subscriptionClassName As String)
[C#]
public SubscriptionEnumeration(NSApplication application, string subscriptionClassName);
[C++]
public: SubscriptionEnumeration(NSApplication application, String* subscriptionClassName);
[JScript]
public function SubscriptionEnumeration(application : NSApplication, subscriptionClassName : String);
Parameters

application

An NSApplication object that represents the Notification Services application containing the collection of subscriptions.

subscriptionClassName

A string containing the name of the subscription class.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize a SubscriptionEnumeration object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a SubscriptionEnumeration object.
Dim mySubscriptionEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration(myApplication, subscriptionClassName)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a SubscriptionEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration mySubscriptionEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration(myApplication, subscriptionClassName);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


SubscriptionEnumeration Constructor (NSApplication, String, String)

Creates and initializes an object of the SubscriptionEnumeration class.

The set of subscriptions returned is all subscriptions associated with a single subscriber, application, and subscription class.

[Visual Basic .NET]
Public Sub New(ByVal application As NSApplication, ByVal subscriptionClassName As String, _ ByVal subscriberId As String)
[C#]
public SubscriptionEnumeration(NSApplication application, string subscriptionClassName, string subscriberId);
[C++]
public: SubscriptionEnumeration(NSApplication application, String* subscriptionClassName, String* subscriberId);
[JScript]
public function SubscriptionEnumeration(application : NSApplication, subscriptionClassName : String, subscriberId : String);
Parameters

application

An NSApplication object that represents the Notification Services application containing the collection of subscriptions.

subscriptionClassName

A string containing the name of the subscription class.

subscriberId

A string containing the subscriber ID.

Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize a SubscriptionEnumeration object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"
Dim subscriberId As String = txtId.Text

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a SubscriptionEnumeration object.
Dim mySubscriptionEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration(myApplication, subscriptionClassName, subscriberId)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";
string subscriberId = txtId.Text;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a SubscriptionEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration mySubscriptionEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration(myApplication, subscriptionClassName, subscriberId);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

SubscriptionEnumeration Properties

Public Properties
Item Returns a Subscription object, which represents an individual subscription.

In C#, this property is the indexer for the SubscriptionEnumeration class.

See Also

SubscriptionEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property

 SQL Server Notification Services Books Online

SubscriptionEnumeration.Item Property

Returns a reference to an individual subscription.

[C#]

In C#, this property is the indexer for the SubscriptionEnumeration class.

[Visual Basic .NET]
Public Property Item(ByVal subscriptionId As String) As Subscription
[C#]
public Subscription this[string subscriptionId] {get;}
[C++]
public: __property Subscription get_Item(String* subscriptionId);
[JScript]
returnValue = SubscriptionEnumerationObject.Item(subscriptionId);
-or-
returnValue = SubscriptionEnumerationObject(subscriptionId);
Parameters

subscriptionId

The identifier of the subscription that you want returned.

Property Value

A Subscription object, which represents an individual subscription.

Exceptions
Exception Type | Condition
IndexOutOfRangeException | No subscription can be identified using the subscription ID provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the Item property to return a Subscription object:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"
Dim subscriberId As String = txtSubscriberId.Text
Dim subscriptionId As String = txtSubscriptionId.Text

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a SubscriptionEnumeration object.
Dim mySubscriptionEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration(myApplication, subscriptionClassName, subscriberId)

'Use the Item property to return a Subscription object.
Dim mySubscription As Microsoft.SqlServer.NotificationServices.Subscription = mySubscriptionEnumeration(subscriptionId)
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";
string subscriberId = txtSubscriberId.Text;
string subscriptionId = txtSubscriptionId.Text;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a SubscriptionEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration mySubscriptionEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration(myApplication, subscriptionClassName, subscriberId);

//Use the Item property to return a Subscription object.
Microsoft.SqlServer.NotificationServices.Subscription mySubscription = mySubscriptionEnumeration[subscriptionId];
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

SubscriptionEnumeration Methods

Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the subscriptions.
Initialize | Overloaded. Initializes an object of the SubscriptionEnumeration class.

See Also

SubscriptionEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


GetEnumerator Method

 SQL Server Notification Services Books Online

SubscriptionEnumeration.GetEnumerator Method

Gets an IEnumerator interface that allows you to iterate through the collection of subscriptions represented by the SubscriptionEnumeration object.

[Visual Basic .NET]
Public Function GetEnumerator() As IEnumerator Implements  IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();
[C++]
public: IEnumerator* GetEnumerator();
[JScript]
public function GetEnumerator() : IEnumerator;
Return Value

An IEnumerator interface for the SubscriptionEnumeration object.

Implements

IEnumerable.GetEnumerator

Remarks

Use this method to return an IEnumerator interface that allows you to iterate through the subscriptions in a SubscriptionEnumeration object. An initialized SubscriptionEnumeration object represents the collection of subscriptions of a particular subscription class for one subscriber in a specified Notification Services application.

Example
[Visual Basic .NET, C#]

The following examples show how to use a SubscriptionEnumeration object to iterate through a set of subscriptions. The GetEnumerator method makes the For Each and foreach statements possible:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim applicationName As String = "MyApplicationName"
Dim subscriptionClassName As String = "MySubscriptionClassName"
Dim subscriberId As String = txtSubscriberId.Text

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create an NSApplication object.
Dim myApplication As New Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName)

'Create a SubscriptionEnumeration object.
Dim mySubscriptionEnumeration As New Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration(myApplication, subscriptionClassName, subscriberId)

'Iterate through the subscriptions.
Dim subscription As Microsoft.SqlServer.NotificationServices.Subscription
For Each subscription In mySubscriptionEnumeration
   Console.WriteLine("Subscription ID: {0}", subscription.SubscriptionId)
Next subscription
[C#]
string instanceName = "MyInstanceName";
string applicationName = "MyApplicationName";
string subscriptionClassName = "MySubscriptionClassName";
string subscriberId = txtSubscriberId.Text;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create an NSApplication object.
Microsoft.SqlServer.NotificationServices.NSApplication myApplication = new Microsoft.SqlServer.NotificationServices.NSApplication(myInstance, applicationName);

//Create a SubscriptionEnumeration object.
Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration mySubscriptionEnumeration = new Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration(myApplication, subscriptionClassName, subscriberId);

//Iterate through the subscriptions.
foreach (Microsoft.SqlServer.NotificationServices.Subscription subscription in mySubscriptionEnumeration)
{
   Console.WriteLine("Subscription ID: {0}", subscription.SubscriptionId);
}
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

SubscriptionEnumeration.Initialize Method

Initializes an object of the SubscriptionEnumeration class. Is used in conjunction with the parameter-less constructor to enable COM interoperability.

Overload List

Initializes an object of the SubscriptionEnumeration class. The set of subscriptions returned is all subscriptions associated with a particular application and subscription class, regardless of subscriber.

[Visual Basic .NET]

Public Sub Initialize(NSApplication, String)

[C#]

public void Initialize(NSApplication, string);

[C++]

public: void Initialize(NSApplication, String*);

[JScript]

public function Initialize(NSApplication, String);

Initializes an object of the SubscriptionEnumeration class. The set of subscriptions returned is all subscriptions associated with a single subscriber, application, and subscription class.

[Visual Basic .NET]

Public Sub Initialize(NSApplication, String, String)

[C#]

public void Initialize(NSApplication, string, string);

[C++]

public: void Initialize(NSApplication, String*, String*);

[JScript]

public function Initialize(NSApplication, String, String);

See Also

SubscriptionEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method (NSApplication, String)

 SQL Server Notification Services Books Online
SubscriptionEnumeration.Initialize Method (NSApplication, String)

Initializes an object of the SubscriptionEnumeration class. The set of subscriptions returned is all subscriptions associated with a particular application and subscription class, regardless of subscriber.

[Visual Basic .NET]
Public Sub Initialize(ByVal application As NSApplication, ByVal subscriptionClassName As _ String)
[C#]
public void Initialize(NSApplication application, string subscriptionClassName);
[C++]
public: void Initialize(NSApplication application, String* subscriptionClassName);
[JScript]
public function Initialize(application : NSApplication, subscriptionClassName : String);
Parameters

application

An NSApplication object that represents the Notification Services application containing the collection of subscriptions.

subscriptionClassName

A string containing the name of the subscription class.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on a SubscriptionEnumeration object created with the parameter-less constructor.

Example

The following example shows how to create and initialize a SubscriptionEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, mySubscriptionEnumeration

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const subscriptionClassName = "MySubscriptionClassName"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize a SubscriptionEnumeration object.
set mySubscriptionEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration")
mySubscriptionEnumeration.Initialize myApplication, subscriptionClassName
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method (NSApplication, String, String)

 SQL Server Notification Services Books Online
SubscriptionEnumeration.Initialize Method (NSApplication, String, String)

Initializes an object of the SubscriptionEnumeration class. The set of subscriptions returned is all subscriptions associated with a single subscriber, application, and subscription class.

[Visual Basic .NET]
Public Sub Initialize(ByVal application As NSApplication, ByVal subscriptionClassName As _ String, ByVal subscriberId As String)
[C#]
public void Initialize(NSApplication application, string subscriptionClassName, string subscriberId);
[C++]
public: void Initialize(NSApplication application, String* subscriptionClassName, String* subscriberId);
[JScript]
public function Initialize(application : NSApplication, subscriptionClassName : String, subscriberId : String);
Parameters

application

An NSApplication object that represents the Notification Services application containing the collection of subscriptions.

subscriptionClassName

A string containing the name of the subscription class.

subscriberId

A string containing the subscriber ID of the subscriber to whom all returned subscriptions must belong.

Exceptions
Exception Type | Condition
ArgumentNullException | The application argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on a SubscriptionEnumeration object created with the parameter-less constructor.

Example

The following example shows how to create and initialize a SubscriptionEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myApplication, mySubscriptionEnumeration, subscriberId

const instanceName = "MyInstanceName"
const applicationName = "MyApplicationName"
const subscriptionClassName = "MySubscriptionClassName"
subscriberId = "TestSubscriber"

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize an NSApplication object.
set myApplication = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSApplication")
myApplication.Initialize myInstance, applicationName

'Create & initialize a SubscriptionEnumeration object.
set mySubscriptionEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.SubscriptionEnumeration")
mySubscriptionEnumeration.Initialize myApplication, subscriptionClassName, subscriberId
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

SubscriptionEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


TimeZone Class

Represents a valid time zone. Exists to support a set of time zone properties and expose them for use in your subscription management application.

For a list of all members of this type, see TimeZone Members.

System.Object

Microsoft.SqlServer.NotificationServices.TimeZone
[Visual Basic .NET]
NonInheritable Public Class TimeZone Implements ITimeZone
[C#]
public sealed class TimeZone : ITimeZone
[C++]
public __gc __sealed class TimeZone : public ITimeZone
[JScript]
public class TimeZone implements ITimeZone
Remarks

An object of the TimeZone class represents a valid time zone. A time zone ID is used in setting subscription schedule information.

The TimeZone class has no constructor. To create a TimeZone object, you must return one from the TimeZoneEnumeration.Item property.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

TimeZone Members

Microsoft.SqlServer.NotificationServices Namespace


TimeZone Members

Public Properties
DaylightName | Gets the daylight savings time name for the time zone.
DisplayName | Gets the language-independent name for the time zone.
Language | Gets the language for the time zone.
LocationName | Gets the location name for the time zone.
StandardName | Gets the standard time name for the time zone.
TimeZoneId | Gets the identifier for the time zone.
TimeZoneName | Gets the Notification Services-assigned name for the time zone.
UtcOffset | Gets the Universal Time Coordinate (UTC) offset value for the time zone.

See Also

TimeZone Class

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

TimeZone Properties

Public Properties
DaylightName | Gets the daylight savings time name for the time zone, for example, "Central Europe Daylight Time".
DisplayName | Gets the language-independent name for the time zone.
Language | Gets the language in which the selected time zone information is stored.
LocationName | Gets the location name for the time zone, for example, "Central Europe Time".
StandardName | Gets the standard name for the time zone, for example, "Central Europe Standard Time".
TimeZoneId | Gets the identifier for the time zone.
TimeZoneName | Gets the Notification Services–assigned name for the time zone, for example, "(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague".
UtcOffset | Gets the Universal Time Coordinate (UTC) offset value for the time zone.

See Also

TimeZone Members

Microsoft.SqlServer.NotificationServices Namespace


DaylightName Property

 SQL Server Notification Services Books Online

TimeZone.DaylightName Property

Gets the daylight savings time name for the time zone, for example, "Central Europe Daylight Time".

[Visual Basic .NET]
Public Property DaylightName As String
[C#]
public string DaylightName {get;}
[C++]
public: __property String* get_DaylightName();
[JScript]
public function get DaylightName() : String;
Property Value

A string containing the daylight savings time name for the time zone.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

TimeZone Members

Microsoft.SqlServer.NotificationServices Namespace


DisplayName Property

 SQL Server Notification Services Books Online

TimeZone.DisplayName Property

Gets the language-independent display name for the time zone.

[Visual Basic .NET]
Public Property DisplayName As String
[C#]
public string DisplayName {get;}
[C++]
public: __property String* get_DisplayName();
[JScript]
public function get DisplayName() : String;
Property Value

A string containing the display name for the time zone.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

TimeZone Members

Microsoft.SqlServer.NotificationServices Namespace


Language Property

 SQL Server Notification Services Books Online

TimeZone.Language Property

Gets the language in which the selected time zone information is stored.

[Visual Basic .NET]
Public Property Language As String
[C#]
public string Language {get;}
[C++]
public: __property String* get_Language();
[JScript]
public function get Language() : String;
Property Value

A string containing the language for the time zone.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

TimeZone Members

Microsoft.SqlServer.NotificationServices Namespace


LocationName Property

 SQL Server Notification Services Books Online

TimeZone.LocationName Property

Gets the location name for the time zone, for example, "Central Europe Time".

[Visual Basic .NET]
Public Property LocationName As String
[C#]
public string LocationName {get;}
[C++]
public: __property String* get_LocationName();
[JScript]
public function get LocationName() : String;
Property Value

A string containing the location name for the time zone.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

TimeZone Members

Microsoft.SqlServer.NotificationServices Namespace


StandardName Property

 SQL Server Notification Services Books Online

TimeZone.StandardName Property

Gets the standard name for the time zone, for example, "Central Europe Standard Time".

[Visual Basic .NET]
Public Property StandardName As String
[C#]
public string StandardName {get;}
[C++]
public: __property String* get_StandardName();
[JScript]
public function get StandardName() : String;
Property Value

A string containing the standard name for the time zone.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

TimeZone Members

Microsoft.SqlServer.NotificationServices Namespace


TimeZoneId Property

 SQL Server Notification Services Books Online

TimeZone.TimeZoneId Property

Gets the identifier for the time zone.

[Visual Basic .NET]
Public Property TimeZoneId As Short
[C#]
public short TimeZoneId {get;}
[C++]
public: __property short get_TimeZoneId();
[JScript]
public function get TimeZoneId() : Int16;
Property Value

A short value containing the time zone identifier.

Remarks

The TimeZoneId property value can be used as part of the Subscription.ScheduleStart property value for scheduled subscriptions.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

TimeZone Members

Microsoft.SqlServer.NotificationServices Namespace


TimeZoneName Property

 SQL Server Notification Services Books Online

TimeZone.TimeZoneName Property

Gets the Notification Services–assigned name for the time zone, for example, "(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague".

[Visual Basic .NET]
Public Property TimeZoneName As String
[C#]
public string TimeZoneName {get;}
[C++]
public: __property String* get_TimeZoneName();
[JScript]
public function get TimeZoneName() : String;
Property Value

A string containing the time zone name.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

TimeZone Members

Microsoft.SqlServer.NotificationServices Namespace


UtcOffset Property

 SQL Server Notification Services Books Online

TimeZone.UtcOffset Property

Gets the Universal Time Coordinate (UTC) offset value for the time zone.

[Visual Basic .NET]
Public Property UtcOffset As Integer
[C#]
public int UtcOffset {get;}
[C++]
public: __property int get_UtcOffset();
[JScript]
public function get UtcOffset() : int;
Property Value

An integer representing the UTC offset value for the time zone.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

TimeZone Members

Microsoft.SqlServer.NotificationServices Namespace


TimeZoneEnumeration Class

Represents the collection of time zones available within a given Notification Services instance. This class allows you to populate a time zone drop-down box in your subscription management application.

For a list of all members of this type, see TimeZoneEnumeration Members.

System.Object

Microsoft.SqlServer.NotificationServices.TimeZoneEnumeration

[Visual Basic .NET]
Public Class TimeZoneEnumeration Implements ITimeZoneEnumeration, IEnumerable
[C#]
public class TimeZoneEnumeration : ITimeZoneEnumeration, IEnumerable
[C++]
public __gc __sealed class TimeZoneEnumeration : public ITimeZoneEnumeration, IEnumerable
[JScript]
public class TimeZoneEnumeration implements ITimeZoneEnumeration, IEnumerable
Remarks

The TimeZoneEnumeration class allows an application to iterate through the set of time zones available within a given Notification Services instance. The set of time zones can be provided in any of the languages that Notification Services supports. The language of the enumeration is selected when the TimeZoneEnumeration object is initialized. This class provides an Item property to return a TimeZone object that represents a specific time zone.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

TimeZoneEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


TimeZoneEnumeration Members

Public Constructors
TimeZoneEnumeration Constructor Overloaded. Creates a new object of the TimeZoneEnumeration class.
Public Properties
Item Returns a TimeZone object, which represents a valid time zone.

In C#, this property is the indexer for the TimeZoneEnumeration class.
Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the time zones.
Initialize | Initializes an object of the TimeZoneEnumeration class.

See Also

TimeZoneEnumeration Class

Microsoft.SqlServer.NotificationServices Namespace


TimeZoneEnumeration Constructor

Creates a new object of the TimeZoneEnumeration class.

Overload List

Creates an uninitialized object of the TimeZoneEnumeration class. It is used along with the Initialize method to support the two-step class initialization required by COM interop.

[Visual Basic .NET]

Public Sub New()

[C#]

public TimeZoneEnumeration();

[C++]

public: TimeZoneEnumeration();

[JScript]

public function TimeZoneEnumeration();

Creates a new object of the TimeZoneEnumeration class, and initializes it with a reference to an NSInstance object, and a string indicating the language to be used.

[Visual Basic .NET]

Public Sub New(NSInstance, String)

[C#]

public TimeZoneEnumeration(NSInstance, string);

[C++]

public: TimeZoneEnumeration(NSInstance, String*);

[JScript]

public function TimeZoneEnumeration(NSInstance, String);

See Also

TimeZoneEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


TimeZoneEnumeration Constructor ()

Creates an uninitialized object of the TimeZoneEnumeration class.

[Visual Basic .NET]
Public Sub New()
[C#]
public TimeZoneEnumeration();
[C++]
public: TimeZoneEnumeration();
[JScript]
public function TimeZoneEnumeration();
Remarks

The parameter-less constructor is used in conjunction with the Initialize method to enable COM interoperability. After construction, the resulting object must be initialized with a reference to an NSInstance object and a string containing the desired language for the time zone data before it can be used.

Example

The following example shows how to create and initialize a TimeZoneEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myTimeZoneEnumeration

const instanceName = "MyInstanceName"
language = Request.Form("PreferredLanguage")

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize a TimeZoneEnumeration object.
set myTimeZoneEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.TimeZoneEnumeration")
myTimeZoneEnumeration.Initialize myInstance, language
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

TimeZoneEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


TimeZoneEnumeration Constructor (NSInstance, String)

Creates and initializes an object of the TimeZoneEnumeration class.

[Visual Basic .NET]
Public Sub New(ByVal instance As NSInstance, ByVal language As String)
[C#]
public TimeZoneEnumeration(NSInstance instance, string language);
[C++]
public: TimeZoneEnumeration(NSInstance instance, String* language);
[JScript]
public function TimeZoneEnumeration(instance : NSInstance, language : String);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing the collection of time zones.

language

A string indicating the language in which the time zone data is to be returned.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Example
[Visual Basic .NET, C#]

The following examples show how to create and initialize a TimeZoneEnumeration object in managed code:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim language As String = ddPreferredLanguage.SelectedItem.Value

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a TimeZoneEnumeration object.
Dim myTimeZoneEnumeration As New Microsoft.SqlServer.NotificationServices.TimeZoneEnumeration(myInstance, language)
[C#]
string instanceName = "MyInstanceName";
string language = ddPreferredLanguage.SelectedItem.Value;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a TimeZoneEnumeration object.
Microsoft.SqlServer.NotificationServices.TimeZoneEnumeration myTimeZoneEnumeration = new Microsoft.SqlServer.NotificationServices.TimeZoneEnumeration(myInstance, language);
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

TimeZoneEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Properties

 SQL Server Notification Services Books Online

TimeZoneEnumeration Properties

Public Properties
Item Returns a TimeZone object, which represents a valid time zone.

In C#, this property is the indexer for the TimeZoneEnumeration class.

See Also

TimeZoneEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Item Property

 SQL Server Notification Services Books Online

TimeZoneEnumeration.Item Property

Returns a TimeZone object, which represents a valid time zone.

[C#]

In C#, this property is the indexer for the TimeZoneEnumeration class.

[Visual Basic .NET]
Public Property Item(ByVal timeZoneId As Short) As TimeZone
[C#]
public TimeZone this[short timeZoneId] {get;}
[C++]
public: __property TimeZone get_Item(short timeZoneId);
[JScript]
returnValue = TimeZoneEnumerationObject.Item(timeZoneId);
-or-
returnValue = TimeZoneEnumerationObject(timeZoneId);
Parameters

timeZoneId

The identifier of the time zone that you want returned.

Property Value

A TimeZone object, which represents a time zone.

Exceptions
Exception Type | Condition
IndexOutOfRangeException | No record can be identified using the time zone ID provided.
Example
[Visual Basic .NET, C#]

The following examples show how to use the Item property to return a TimeZone object:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim timeZoneId As Short = 40
Dim language As String = ddPreferredLanguage.SelectedItem.Value

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a TimeZoneEnumeration object.
Dim myTimeZoneEnumeration As New Microsoft.SqlServer.NotificationServices.TimeZoneEnumeration(myInstance, language)

'Use the Item property to return a TimeZone object.
Dim myTimeZone As Microsoft.SqlServer.NotificationServices.TimeZone = myTimeZoneEnumeration(timeZoneId)
[C#]
string instanceName = "MyInstanceName";
short timeZoneId = 40;
string language = ddPreferredLanguage.SelectedItem.Value;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a TimeZoneEnumeration object.
Microsoft.SqlServer.NotificationServices.TimeZoneEnumeration myTimeZoneEnumeration = new Microsoft.SqlServer.NotificationServices.TimeZoneEnumeration(myInstance, language);

//Use the Item property to return a TimeZone object.
Microsoft.SqlServer.NotificationServices.TimeZone myTimeZone = myTimeZoneEnumeration[timeZoneId];
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

TimeZoneEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

TimeZoneEnumeration Methods

Public Methods
GetEnumerator | Returns an IEnumerator interface that allows you to iterate through the time zones.
Initialize | Initializes an object of the TimeZoneEnumeration class.

See Also

TimeZoneEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


GetEnumerator Method

 SQL Server Notification Services Books Online

TimeZoneEnumeration.GetEnumerator Method

Gets an IEnumerator interface that allows you to iterate through the collection of time zones represented by the TimeZoneEnumeration object.

[Visual Basic .NET]
Public Function GetEnumerator() As IEnumerator Implements  IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();
[C++]
public: IEnumerator* GetEnumerator();
[JScript]
public function GetEnumerator() : IEnumerator;
Return Value

An IEnumerator interface for the TimeZoneEnumeration object.

Implements

IEnumerable.GetEnumerator

Remarks

Use this method to return an IEnumerator interface that allows you to iterate through the time zones in a TimeZoneEnumeration object. An initialized TimeZoneEnumeration object represents the collection of time zones in a specified Notification Services instance.

Example
[Visual Basic .NET, C#]

The following examples show how to use a TimeZoneEnumeration object to iterate through a set of time zones. The GetEnumerator method makes the For Each and foreach statements possible:

[Visual Basic .NET]
Dim instanceName As String = "MyInstanceName"
Dim language As String = ddPreferredLanguage.SelectedItem.Value

'Create an NSInstance object.
Dim myInstance As New Microsoft.SqlServer.NotificationServices.NSInstance(instanceName)

'Create a TimeZoneEnumeration object.
Dim myTimeZoneEnumeration As New Microsoft.SqlServer.NotificationServices.TimeZoneEnumeration(myInstance, language)

'Iterate through the time zones.
Dim timeZone As Microsoft.SqlServer.NotificationServices.TimeZone
For Each timeZone In myTimeZoneEnumeration
   Console.WriteLine("Time Zone ID: {0}", TimeZone.TimeZoneId)
Next timeZone
[C#]
string instanceName = "MyInstanceName";
string language = ddPreferredLanguage.SelectedItem.Value;

//Create an NSInstance object.
Microsoft.SqlServer.NotificationServices.NSInstance myInstance = new Microsoft.SqlServer.NotificationServices.NSInstance(instanceName);

//Create a TimeZoneEnumeration object.
Microsoft.SqlServer.NotificationServices.TimeZoneEnumeration myTimeZoneEnumeration = new Microsoft.SqlServer.NotificationServices.TimeZoneEnumeration(myInstance, language);

//Iterate through the time zones.
foreach (Microsoft.SqlServer.NotificationServices.TimeZone timeZone in myTimeZoneEnumeration)
{
   Console.WriteLine("Time Zone ID: {0}", timeZone.TimeZoneId);
}
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

TimeZoneEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

TimeZoneEnumeration.Initialize Method

Initializes an object of the TimeZoneEnumeration class.

[Visual Basic .NET]
Public Sub Initialize(ByVal instance As NSInstance, ByVal language As String)
[C#]
public void Initialize(NSInstance instance, string language);
[C++]
public: void Initialize(NSInstance instance, String* language);
[JScript]
public function Initialize(instance : NSInstance, language : String);
Parameters

instance

An NSInstance object that represents the Notification Services instance containing the collection of time zones.

language

A string indicating the language in which the time zone data is to be returned.

Exceptions
Exception Type | Condition
ArgumentNullException | The instance argument is null.
Remarks

The Initialize method is used in conjunction with the parameter-less constructor to enable COM interoperability. It must be called before any other property or method is called on a TimeZoneEnumeration object created with the parameter-less constructor.

Example

The following example shows how to create and initialize a TimeZoneEnumeration object in unmanaged Microsoft Visual Basic® Scripting Edition (VBScript) code:

Dim myInstance, myTimeZoneEnumeration

const instanceName = "MyInstanceName"
language = Request.Form("PreferredLanguage")

'Create & initialize an NSInstance object.
set myInstance = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.NSInstance")
myInstance.Initialize instanceName

'Create & initialize a TimeZoneEnumeration object.
set myTimeZoneEnumeration = WScript.CreateObject("Microsoft.SqlServer.NotificationServices.TimeZoneEnumeration")
myTimeZoneEnumeration.Initialize myInstance, language
Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

TimeZoneEnumeration Members

Microsoft.SqlServer.NotificationServices Namespace


IContentFormatter Interface

Provides a framework for developing a custom content formatter. A content formatter is used to format notification data for display.

For a list of all members of this type, see IContentFormatter Members.

Microsoft.SqlServer.NotificationServices.IContentFormatter

[Visual Basic .NET]
Public Interface IContentFormatter
[C#]
public interface IContentFormatter
[C++]
public __gc __interface IContentFormatter
[JScript]
public interface IContentFormatter
Remarks

This interface provides a framework for developing a custom content formatter. Any custom content formatters that you develop must implement this interface in order to interact with the Notification Services system.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

IContentFormatter Members

Microsoft.SqlServer.NotificationServices Namespace


IContentFormatter Members

Public Methods
Close | Notifies the content formatter to release any resources it is holding, and prepare for shutdown.
FormatContent | Passes raw notification data to the content formatter for formatting.
Initialize | Notifies the content formatter that it must perform initialization.

See Also

IContentFormatter Interface

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

IContentFormatter Methods

Public Methods
Close | Notifies the content formatter to release any resources it is holding, and prepare for shutdown.
FormatContent | Passes raw notification data to the content formatter for formatting.
Initialize | Notifies the content formatter that it must perform initialization.

See Also

IContentFormatter Members

Microsoft.SqlServer.NotificationServices Namespace


Close Method

 SQL Server Notification Services Books Online

IContentFormatter.Close Method

Closes the content formatter.

[Visual Basic .NET]
Public Sub Close()
[C#]
public void Close();
[C++]
public: void Close();
[JScript]
public function Close();
Remarks

The distributor calls this method to tell the content formatter to release any resources it is holding, and prepare for shutdown.

Example

For an example of how to implement the IContentFormatter.Close method, see Implementing the Close Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IContentFormatter Members

Microsoft.SqlServer.NotificationServices Namespace


FormatContent Method

 SQL Server Notification Services Books Online

IContentFormatter.FormatContent Method

Activates the content formatter to format notification data.

[Visual Basic .NET]
Public Sub FormatContent(ByVal subscriberLocale As String, ByVal deviceTypeName As String, _ ByVal recipientInfo As RecipientInfo, ByVal _ rawContent() As Hashtable)
[C#]
public void FormatContent(string subscriberLocale, string deviceTypeName, RecipientInfo recipientInfo, Hashtable[] rawContent );
[C++]
public: void FormatContent(String* subscriberLocale, String* deviceTypeName, RecipientInfo recipientInfo, Hashtable[] rawContent );
[JScript]
public function FormatContent(subscriberLocale : String, deviceTypeName : String, recipientInfo : RecipientInfo, rawContent : Hashtable[]);
Parameters

subscriberLocale

A string containing the subscriber locale information.

deviceTypeName

A string indicating the type of the target device for the notification.

recipientInfo

A RecipientInfo object containing the recipient's device address and subscriber ID data.

rawContent

An array of Hashtable objects containing the raw notification data that is to be formatted.

Remarks

The distributor uses this method to pass raw notification data to the content formatter and have it generate formatted content.

Example

For an example of how to implement the IContentFormatter.FormatContent method, see Implementing the FormatContent Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IContentFormatter Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

IContentFormatter.Initialize Method

Initializes the content formatter.

[Visual Basic .NET]
Public Sub Initialize(ByVal arguments As StringDictionary, ByVal digest As Boolean)
[C#]
public void Initialize(StringDictionary arguments, bool digest);
[C++]
public: void Initialize(StringDictionary arguments, bool digest);
[JScript]
public function Initialize(arguments : StringDictionary, digest : Boolean);
Parameters

arguments

A StringDictionary object containing the names and values of the initialization arguments. The values in the StringDictionary object are taken from the /Notification Classes/NotificationClass/ContentFormatter/Arguments section of the application definition file (ADF).

digest

A Boolean value indicating whether the notification class for which the content formatter is being used has digest delivery enabled. If this parameter is true, then multiple sets of notification data that are passed in a single call to FormatContent should be aggregated into a single digest notification.

Remarks

The distributor calls this method to notify the content formatter that it must perform initialization. The arguments parameter provides the initialization arguments for the content formatter. These arguments are defined in the /NotificationClass/NotificationClasses/ContentFormatter/Arguments section of the ADF.

The digest parameter indicates whether digest delivery is being used as specified by the /Notification Classes/NotificationClass/DigestDelivery setting in the ADF. The content formatter should store the value of this parameter, and use it to decide whether to do digest aggregation in the call to the FormatContent method.

Example

For an example of how to implement the IContentFormatter.Initialize method, see Implementing the Initialize Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IContentFormatter Members

Microsoft.SqlServer.NotificationServices Namespace


IDeliveryProtocol Interface

Provides a framework for developing a custom delivery protocol, which can be used by one or more delivery channels. A delivery protocol is used to create a notification message and route it to an external delivery system for delivery.

For a list of all members of this type, see IDeliveryProtocol Members.

Microsoft.SqlServer.NotificationServices.IDeliveryProtocol

[Visual Basic .NET]
Public Interface IDeliveryProtocol
[C#]
public interface IDeliveryProtocol
[C++]
public __gc __interface IDeliveryProtocol
[JScript]
public interface IDeliveryProtocol
Remarks

This interface provides a framework for developing a custom delivery protocol. Any custom delivery protocols that you develop must implement this interface in order to interact with the Notification Services system.

Note The IHttpProtocolProvider interface is offered to speed development of HTTP-based delivery protocols, because these protocols are commonly candidates for custom development. The IDeliveryProtocol interface is to be used for custom delivery protocols that implement other protocols, or for HTTP-based delivery protocols that require more flexibility than IHttpProtocolProvider provides. For more information about the IHttpProtocolProvider interface, see IHttpProtocolProvider Interface.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

IDeliveryProtocol Members

Microsoft.SqlServer.NotificationServices Namespace


IDeliveryProtocol Members

Public Methods
Close | Notifies the delivery protocol to release any resources it is holding, and prepare for shutdown.
DeliverNotification | Passes formatted notification data to the delivery protocol, which then generates the notification message (if necessary) and routes it to an external delivery system.
Flush | Notifies the delivery protocol that it must either complete or abort all pending operations for notifications it is handling.
Initialize | Notifies the delivery protocol that it must perform initialization.

See Also

IDeliveryProtocol Interface

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

IDeliveryProtocol Methods

Public Methods
Close | Notifies the delivery protocol to release any resources it is holding, and prepare for shutdown.
DeliverNotification | Passes formatted notification data to the delivery protocol, which then generates the notification message (if necessary) and routes it to an external delivery system.
Flush | Notifies the delivery protocol that it must either complete or abort all pending operations for notifications it is handling.
Initialize | Notifies the delivery protocol that it must perform initialization.

See Also

IDeliveryProtocol Members

Microsoft.SqlServer.NotificationServices Namespace


Close Method

 SQL Server Notification Services Books Online

IDeliveryProtocol.Close Method

Closes the delivery protocol.

[Visual Basic .NET]
Public Sub Close()
[C#]
public void Close();
[C++]
public: void Close();
[JScript]
public function Close();
Remarks

The distributor calls this method to tell the delivery protocol to release any resources it is holding, and prepare for shutdown.

Example

For an example of how to implement the IDeliveryProtocol.Close method, see Implementing the Close Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IDeliveryProtocol Members

Microsoft.SqlServer.NotificationServices Namespace


DeliverNotification Method

 SQL Server Notification Services Books Online

IDeliveryProtocol.DeliverNotification Method

Activates the delivery protocol to package the notification data (if necessary) and route it to the external delivery system.

[Visual Basic .NET]
Public Sub DeliverNotification(ByVal headersList() As NotificationHeaders, ByVal body As String)
[C#]
public void DeliverNotification(NotificationHeaders[] headersList, string body);
[C++]
public: void DeliverNotification(NotificationHeaders[] headersList, String* body);
[JScript]
public function DeliverNotification(headersList : NotificationHeaders[], body: String);
Parameters

headersList

An array of NotificationHeaders objects containing the header information for the notifications to be delivered.

body

The formatted notification data that comprises the body of the notification message.

Remarks

The distributor uses this method to pass formatted notification data (created by the content formatter and passed as the body parameter) and header information (collected by the distributor from the /NotificationClass/NotificationClasses/Protocols/Protocol/Fields section of the ADF) to the delivery protocol. The delivery protocol then generates the notification message (if necessary) and hands it off to an external delivery system.

Example

For an example of how to implement the IDeliveryProtocol.DeliverNotification method, see Implementing the DeliverNotification Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IDeliveryProtocol Members

Microsoft.SqlServer.NotificationServices Namespace


Flush Method

 SQL Server Notification Services Books Online

IDeliveryProtocol.Flush Method

Tells the delivery protocol to either complete and send, or abort, any notifications it is currently processing.

[Visual Basic .NET]
Public Sub Flush()
[C#]
public void Flush();
[C++]
public: void Flush();
[JScript]
public function Flush();
Remarks

The distributor calls this method to notify the delivery protocol that it must either complete or abort all pending operations for notifications it is handling.

Example

For an example of how to implement the IDeliveryProtocol.Flush method, see Implementing the Flush Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IDeliveryProtocol Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

IDeliveryProtocol.Initialize Method

Initializes the delivery protocol.

[Visual Basic .NET]
Public Sub Initialize(ByVal channelArgs As StringDictionary, ByVal multicast As Boolean, ByVal nsc As NotificationStatusCallback)
[C#]
public void Initialize(StringDictionary channelArgs, bool multicast, NotificationStatusCallback nsc);
[C++]
public: void Initialize(StringDictionary channelArgs, bool multicast, NotificationStatusCallback nsc);
[JScript]
public function Initialize(channelArgs : StringDictionary, multicast : Boolean, nsc : NotificationStatusCallback);
Parameters

channelArgs

A StringDictionary object containing the names and values of the initialization arguments for the delivery channel in which the protocol is being used.

multicast

A Boolean value indicating whether multicast delivery is being used.

nsc

A NotificationStatusCallback delegate that the delivery protocol can use to send notification delivery status information back to the distributor.

Remarks

The distributor calls this method to notify the delivery protocol that it must perform initialization. The arguments parameter provides the initialization arguments for the delivery protocol. The arguments parameter values are collected by the distributor from the /DeliveryChannels/DeliveryChannel/Arguments section of the configuration file. The protocol should store the value of the nsc parameter for later use to indicate notification status.

Example

For an example of how to implement the IDeliveryProtocol.Initialize method, see Implementing the Initialize Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IDeliveryProtocol Members

Microsoft.SqlServer.NotificationServices Namespace


IEventProvider Interface

Provides a framework for developing a hosted continuous event provider. An event provider collects events and submits them to a Notification Services application, where they are matched with subscription information to produce notifications.

For a list of all members of this type, see IEventProvider Members.

Microsoft.SqlServer.NotificationServices.IEventProvider

[Visual Basic .NET]
Public Interface IEventProvider
[C#]
public interface IEventProvider
[C++]
public __gc __interface IEventProvider
[JScript]
public interface IEventProvider
Remarks

This interface provides a framework for developing a hosted continuous event provider. Any custom continuous event providers that you develop must implement this interface if you want them to interact with the provider host component of the NS$instance_name service.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

IEventProvider Members

Microsoft.SqlServer.NotificationServices Namespace


IEventProvider Members

Public Methods
Initialize | Notifies the continuous event provider that it must perform initialization.
Run | Notifies the continuous event provider to start collecting events.
Terminate | Notifies the continuous event provider to stop collecting events, and to release any resources it is holding.

See Also

IEventProvider Interface

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

IEventProvider Methods

Public Methods
Initialize | Notifies the continuous event provider that it must perform initialization.
Run | Notifies the continuous event provider to start collecting events.
Terminate | Notifies the continuous event provider to stop collecting events, and to release any resources it is holding.

See Also

IEventProvider Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

IEventProvider.Initialize Method

Initializes the event provider.

[Visual Basic .NET]
Public Sub Initialize(ByVal application As NSApplication, ByVal providerName As String, _ ByVal args As StringDictionary, ByVal stopDelegate As StopHandler)
[C#]
public void Initialize(NSApplication application, string providerName, StringDictionary args, StopHandler stopDelegate);
[C++]
public: void Initialize(NSApplication application, String* providerName, StringDictionary args, StopHandler stopDelegate);
[JScript]
public function Initialize(application : NSApplication, providerName : String, args : StringDictionary, stopDelegate : StopHandler);
Parameters

application

A NSApplication object that represents the Notification Services application to which this event provider delivers events.

providerName

A string containing the name of the event provider.

args

A StringDictionary object containing the names and values of the initialization arguments.

stopDelegate

A StopHandler delegate that the event provider can use to call back to the provider host to request termination.

Remarks

The provider host calls this method to notify the continuous event provider that it must perform initialization. The args parameter provides the initialization arguments for the event provider. These arguments are defined in the /Providers/HostedProvider/Arguments section of the application definition file (ADF).

Example

For an example of how to implement the IEventProvider.Initialize method, see Implementing the Initialize Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IEventProvider Members

Microsoft.SqlServer.NotificationServices Namespace


Run Method

 SQL Server Notification Services Books Online

IEventProvider.Run Method

Activates the event provider to begin collecting events.

[Visual Basic .NET]
Public Function Run() As Boolean
[C#]
public bool Run();
[C++]
public: bool Run();
[JScript]
public function Run() : Boolean;
Return Value

A Boolean value that indicates whether the event provider was able to run successfully.

Remarks

The provider host calls this method to tell the continuous event provider to start collecting events.

When the provider host calls the Run method, it provides a thread of execution to the event provider. The thread is handed back to the provider host when the event provider returns from the Run call.

Run returns true if the continuous event provider is prepared to have its Run method called again; otherwise Run returns false.

Example

For an example of how to implement the IEventProvider.Run method, see Implementing the Run Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IEventProvider Members

Microsoft.SqlServer.NotificationServices Namespace


Terminate Method

 SQL Server Notification Services Books Online

IEventProvider.Terminate Method

Terminates the event provider.

[Visual Basic .NET]
Public Sub Terminate()
[C#]
public void Terminate();
[C++]
public: void Terminate();
[JScript]
public function Terminate();
Remarks

The provider host calls this method to tell the continuous event provider to stop collecting events, and to release any resources it is holding.

Example

For an example of how to implement the IEventProvider.Terminate method, see Implementing the Terminate Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IEventProvider Members

Microsoft.SqlServer.NotificationServices Namespace


IHttpProtocolProvider Interface

Provides a framework for developing a custom HTTP-based delivery protocol.

For a list of all members of this type, see IHttpProtocolProvider Members.

Microsoft.SqlServer.NotificationServices.IHttpProtocolProvider

[Visual Basic .NET]
Public Interface IHttpProtocolProvider
[C#]
public interface IHttpProtocolProvider
[C++]
public __gc __interface IHttpProtocolProvider
[JScript]
public interface IHttpProtocolProvider
Remarks

This interface provides a framework for developing a custom HTTP-based delivery protocol. Because HTTP-based delivery protocols are common candidates for custom development, this class interface is provided to simplify that type of development. The IDeliveryProtocol interface is to be used for custom delivery protocols that implement other protocols, or for HTTP-based delivery protocols that require more flexibility than IHttpProtocolProvider provides.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

IHttpProtocolProvider Members

Microsoft.SqlServer.NotificationServices Namespace


IHttpProtocolProvider Members

Public Methods
Close | Notifies the delivery protocol to release any resources it is holding, and prepare for shutdown.
FormatEnvelope | Passes formatted notification data to the delivery protocol, which then uses this information to create the HTTP envelope.
Initialize | Notifies the delivery protocol that it must perform initialization.
ProcessResponse | Passes the HTTP response to the delivery protocol for processing.

See Also

IHttpProtocolProvider Interface

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

IHttpProtocolProvider Methods

Public Methods
Close | Notifies the delivery protocol to release any resources it is holding, and prepare for shutdown.
FormatEnvelope | Passes formatted notification data to the delivery protocol, which then uses this information to create the HTTP envelope.
Initialize | Notifies the delivery protocol that it must perform initialization.
ProcessResponse | Passes the HTTP response to the delivery protocol for processing.

See Also

IHttpProtocolProvider Members

Microsoft.SqlServer.NotificationServices Namespace


Close Method

 SQL Server Notification Services Books Online

IHttpProtocolProvider.Close Method

Closes the delivery protocol.

[Visual Basic .NET]
Public Sub Close()
[C#]
public void Close();
[C++]
public: void Close();
[JScript]
public function Close();
Remarks

The distributor calls this method to tell the delivery protocol to release any resources it is holding, and prepare for shutdown.

Example

For an example of how to implement the IHttpProtocolProvider.Close method, see Implementing the Close Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IHttpProtocolProvider Members

Microsoft.SqlServer.NotificationServices Namespace


IHttpProtocolProvider.FormatEnvelope Method

The distributor uses this method to pass formatted notification data to the delivery protocol, which then uses this information to create an appropriately formatted envelope.

[Visual Basic .NET]
Public Function FormatEnvelope(ByVal protocolFields As StringDictionary, ByVal requestBody As String) As String
[C#]
public string FormatEnvelope(StringDictionary protocolFields, string requestBody);
[C++]
public: String* FormatEnvelope(StringDictionary protocolFields, String* requestBody);
[JScript]
public function FormatEnvelope(protocolFields : StringDictionary, requestBody: String) : String;
Parameters

protocolFields

A StringDictionary object containing the protocol fields for the notifications to be delivered.

requestBody

The formatted notification data that comprises the body of the notification message.

Return Value

A string that contains the formatted envelope.

Remarks

You can use any appropriate mechanism to evaluate the values in the arguments and create the envelope. No send functionality needs to be coded here; this is handled by the Notification Services internal HttpExtension class in combination with the IHttpProvider interface.

Example

For an example of how to implement the IHttpProtocolProvider.FormatEnvelope method, see Implementing the FormatEnvelope Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IHttpProtocolProvider Members

Microsoft.SqlServer.NotificationServices Namespace


IHttpProtocolProvider.Initialize Method

Initializes the delivery protocol.

[Visual Basic .NET]
Public Sub Initialize(ByVal channelArguments As StringDictionary)
[C#]
public void Initialize(StringDictionary channelArguments);
[C++]
public: void Initialize(StringDictionary channelArguments);
[JScript]
public function Initialize(channelArguments : StringDictionary);
Parameters

channelArguments

A StringDictionary object containing the arguments for the delivery channel in which the delivery protocol is being used.

Remarks

The distributor calls this method to notify the delivery protocol that it must perform initialization. The arguments parameter provides the initialization arguments for the delivery protocol. The arguments parameter values are collected by the distributor from the /DeliveryChannels/DeliveryChannel/Arguments section of the configuration file for the delivery channel in which the protocol is being used. These delivery channel arguments are in turn passed to the IHttpProtocolProvider.Initialize method.

Example

For an example of how to implement the IHttpProtocolProvider.Initialize method, see Implementing the Initialize Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IHttpProtocolProvider Members

Microsoft.SqlServer.NotificationServices Namespace


IHttpProtocolProvider.ProcessResponse Method

The distributor uses this method to pass an HTTP response to the delivery protocol for processing.

[Visual Basic .NET]
Public Function ProcessResponse(ByVal httpResponseCode As HttpStatusCode, ByVal responseBody As String, postSuccess As Boolean) As Boolean
[C#]
public bool ProcessResponse(HttpStatusCode httpResponseCode, string responseBody, bool postSuccess);
[C++]
public: bool ProcessResponse(HttpStatusCode httpResponseCode, String* responseBody, bool postSuccess);
[JScript]
public function ProcessResponse(httpResponseCode : HttpStatusCode, responseBody : String, postSuccess : Boolean) : Boolean;
Parameters

httpResponseCode

An HttpStatusCode enumeration containing the HTTP response code.

responseBody

A string containing the HTTP response.

postSuccess

A Boolean value indicating whether the post was successful.

Return Value

A Boolean value indicating whether the post was successful.

Remarks

The postSuccess argument indicates whether the protocol thinks the delivery succeeded. This post status might conflict with the actual delivery status. For instance, the post might have succeeded at the HTTP level, but the delivery itself might have failed. This additional status information is supplied in the responseBody argument. You must evaluate the values of these arguments to determine the actual delivery status, and then set the return value to indicate success or failure.

The simplest implementation of the ProcessResponse method is to return the postSuccess value that is passed to the ProcessResponse as the return value. This is the case if the HTTP response code is the only success or failure indicator from the remote delivery service (the target of the HTTP post).

Example

For an example of how to implement the IDeliveryProtocol.ProcessResponse method, see Implementing the ProcessResponse Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IHttpProtocolProvider Members

Microsoft.SqlServer.NotificationServices Namespace


IScheduledEventProvider Interface

Provides a framework for developing a hosted scheduled event provider. An event provider collects events and submits them to a Notification Services application, where they are matched with subscription information to produce notifications.

For a list of all members of this type, see IScheduledEventProvider Members.

Microsoft.SqlServer.NotificationServices.IScheduledEventProvider

[Visual Basic .NET]
Public Interface IScheduledEventProvider
[C#]
public interface IScheduledEventProvider
[C++]
public __gc __interface IScheduledEventProvider
[JScript]
public interface IScheduledEventProvider
Remarks

This interface provides a framework for developing a hosted scheduled event provider. Any custom scheduled event providers that you develop must implement this interface if you want them to interact with the provider host function of the NS$instance_name service.

Requirements

Namespace: Microsoft.SqlServer.NotificationServices

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

Assembly: Microsoft.SqlServer.NotificationServices.dll

See Also

IScheduledEventProvider Members

Microsoft.SqlServer.NotificationServices Namespace


IScheduledEventProvider Members

Public Methods
Initialize | Notifies the scheduled event provider that it must perform initialization.
Run | Notifies the scheduled event provider to start collecting events.
Terminate | Notifies the scheduled event provider to stop collecting events, and to release any resources it is holding.

See Also

IScheduledEventProvider Interface

Microsoft.SqlServer.NotificationServices Namespace


Methods

 SQL Server Notification Services Books Online

IScheduledEventProvider Methods

Public Methods
Initialize | Notifies the scheduled event provider that it must perform initialization.
Run | Notifies the scheduled event provider to start collecting events.
Terminate | Notifies the scheduled event provider to stop collecting events, and to release any resources it is holding.

See Also

IScheduledEventProvider Members

Microsoft.SqlServer.NotificationServices Namespace


Initialize Method

 SQL Server Notification Services Books Online

IScheduledEventProvider.Initialize Method

Initializes the event provider.

[Visual Basic .NET]
Public Sub Initialize(ByVal instance As NSInstance, ByVal providerName As String, _ ByVal args As StringDictionary, ByVal stopDelegate As StopHandler)
[C#]
public void Initialize(NSApplication application, string providerName, StringDictionary args, StopHandler stopDelegate);
[C++]
public: void Initialize(NSApplication application, String* providerName, StringDictionary args, StopHandler stopDelegate);
[JScript]
public function Initialize(application : NSApplication, providerName : String, args : StringDictionary, stopDelegate : StopHandler);
Parameters

application

A NSApplication object that represents the Notification Services application to which this event provider delivers events.

providerName

A string containing the name of the event provider.

args

A StringDictionary object containing the names and values of the initialization arguments.

stopDelegate

A StopHandler delegate that the event provider can use to call back to the provider host to request termination.

Remarks

The provider host calls this method to notify the scheduled event provider that it must perform initialization. The args parameter provides the initialization arguments for the event provider. These arguments are defined in the /Providers/HostedProvider/Arguments section of the application definition file (ADF).

Example

For an example of how to implement the IEventProvider.Initialize method, see Implementing the Initialize Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IScheduledEventProvider Members

Microsoft.SqlServer.NotificationServices Namespace


Run Method

 SQL Server Notification Services Books Online

IScheduledEventProvider.Run Method

Activates the event provider to begin collecting events.

[Visual Basic .NET]
Public Function Run() As Boolean
[C#]
public bool Run();
[C++]
public: bool Run();
[JScript]
public function Run() : Boolean;
Return Value

A Boolean value that indicates whether the event provider was able to run successfully.

Remarks

The provider host calls this method to tell the scheduled event provider to start collecting events.

Run returns true if the scheduled event provider has completed its current schedule interval and is prepared to exit. Otherwise, Run returns false. A false return disables the event provider, no further calls to the Run method are invoked by the provider host, and the Terminate method is called to allow the event provider to release any held resources.

Example

For an example of how to implement the IEventProvider.Run method, see Implementing the Run Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IScheduledEventProvider Members

Microsoft.SqlServer.NotificationServices Namespace


Terminate Method

 SQL Server Notification Services Books Online

IScheduledEventProvider.Terminate Method

Terminates the event provider.

[Visual Basic .NET]
Public Sub Terminate()
[C#]
public void Terminate();
[C++]
public: void Terminate();
[JScript]
public function Terminate();
Remarks

The provider host calls this method to tell the scheduled event provider to stop collecting events, and to release any resources it is holding.

Example

For an example of how to implement the IEventProvider.Terminate method, see Implementing the Terminate Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

IScheduledEventProvider Members

Microsoft.SqlServer.NotificationServices Namespace


NotificationStatusCallback Delegate

Used by delivery protocols to return delivery status information back to the distributor.

[Visual Basic .NET]
Public Delegate Sub NotificationStatusCallback(ByVal ParamArray status as NotificationStatus[])
[C#]
public delegate void NotificationStatusCallback(params NotificationStatus[] status);
[C++]
public __gc __delegate void NotificationStatusCallback(NotificationStatus[] status);
[JScript]

In JScript, you can use the delegates in the Microsoft .NET Framework, but you cannot define your own.

Parameters

status

An array of NotificationStatus objects that contain notification delivery status information.

Remarks

The NotificationStatusCallback delegate allows a delivery protocol to return notification delivery status information to the distributor.

For more information about how to use this delegate in a custom delivery protocol, see Implementing the DeliverNotification Method and Implementing the Flush Method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Microsoft.SqlServer.NotificationServices Namespace


StopHandler Delegate

Allows an event provider to request termination.

[Visual Basic .NET]
Public Delegate Sub StopHandler()
[C#]
public delegate void StopHandler();
[C++]
public __gc __delegate void StopHandler();
[JScript]

In JScript, you can use the delegates in the Microsoft .NET Framework, but you cannot define your own.

Remarks

The StopHandler delegate allows an event provider to request termination. Invoking this delegate asynchronously calls the Terminate method on the event provider in question.

The StopHandler delegate is passed to the event provider as a parameter to the Initialize method.

Requirements

Platforms: Windows 2000 Server, Windows 2000 Advanced Server, Windows 2000 Data Center Server, Windows XP Professional

See Also

Microsoft.SqlServer.NotificationServices Namespace


Stored Procedure Reference

Many administrative and informational activities in Notification Services can be performed through stored procedures. The stored procedures are grouped into the categories shown in the following tables.

Debugging Stored Procedures
NSExecuteRuleFiring | NSSetQuantumClock
NSPrepareRuleFiring | NSSetQuantumClockDate
NSScheduledSubscriptionList | NSVacuum
Event Submission Stored Procedures
NSEventBeginBatch<EventClassName> | NSEventSubmitBatch<EventClassName>
NSEventFlushBatch<EventClassName> | NSEventWrite<EventClassName>
Reporting Stored Procedures
NSAdministrationHistory | NSSnapshotEvents
NSSnapshotApplications | NSSnapshotProviders
NSSnapshotDeliveryChannels | NSSnapshotSubscriptions
Troubleshooting and Analysis Stored Procedures
NSDiagnosticDeliveryChannel | NSQuantumDetails
NSDiagnosticEventClass | NSQuantumExecutionTime
NSDiagnosticEventProvider | NSQuantumFailures
NSDiagnosticFailedNotifications | NSQuantumList
NSDiagnosticNotificationClass | NSQuantumPerformance
NSDiagnosticSubscriptionClass | NSQuantumsSkipped
NSEventBatchDetails | NSScheduledSubscriptionDetails
NSNotificationBatchDetails |

Note Unless otherwise indicated, datetime values in Notification Services are in Universal Coordinated Time (UTC).

Note Unless documented otherwise, all system stored procedures return a value of 0 to indicate success. To indicate failure, a nonzero value is returned.

Other Notification Services Stored Procedures

You might notice instance and application database stored procedures that are not covered in the Stored Procedure Reference. These stored procedures are intended for internal use only. Calling them explicitly from your applications is not supported.


NSAdministrationHistory

Produces the administrative history report for a Notification Services instance. The report contains information about all applications hosted by the instance, including the events, notifications, and subscriptions processed during a defined time interval.

Syntax
NSAdministrationHistory
    [[@ApplicationName =] 'app_name'],
    [, [@ReportingIntervalInMinutes =] interval]
    [, [@StartDateTime =] 'start_date_time']
    [, [@EndDateTime =] 'end_date_time']
Arguments
[@ApplicationName =] 'app_name'
Is the name of the Notification Services application, as defined in the configuration file. app_name is nvarchar(255) and has a default value of NULL, which indicates to report on all applications hosted by the instance..
[@ReportingIntervalInMinutes =] interval
Is the number of minutes in each reporting interval. The report contains one row per interval. interval is int and has a default value of 60, which indicates 60 minutes per reporting interval.
[@StartDateTime =] 'start_date_time'
Is the report start date and time in UTC (Universal Time Coordinate or Greenwich mean time). start_date_time is datetime and has a default value of one month prior to the @EndDateTime value. The result set provides information about all data that has not been removed; the vacuumer process might have removed data after start_date_time.
[@EndDateTime =] 'end_date_time'
Is the report end date and time in UTC. The end_date_time value has a data type of datetime. The default value is the result of the GETUTCDATE function, which returns the time at which the stored procedure was invoked.
Return Code Values

None

Result Sets
Column Name | Data Type | Description
ApplicationName | nvarchar(255) | Name of the application that the row summarizes. This value is NULL for the row summarizing the instance.
IntervalStartDateTime | datetime | Starting date and time for the reporting interval in UTC.
IntervalEndDateTime | datetime | Ending date and time for the reporting interval in UTC.
EventBatchCollectedCount | int | Number of event batches collected during the reporting interval, based on the event batch EndCollectionTime value.
EventsCollectedCount | int | Number of events collected during the reporting interval, based on the event batch EndCollectionTime value.
EventsCollectedPerSecond | float | During event collection, average number of events collected per second during the reporting interval.
EventBatchesAwaitingGeneration | int | Number of event batches written to the database but not processed by the generator.
EventBatchesInCollection | int | Number of event batches in the event collection stage during the reporting interval.
NotificationBatchGeneratedCount | int | Number of notification batches written during the reporting interval, based on the notification batch EndGenerationTime value.
NotificationsGeneratedCount | int | Number of notifications generated during the reporting interval, based on the notification batch EndGenerationTime value.
NotificationsGeneratedPerSecond | float | Average number of notifications generated per second during the reporting interval.
NotificationBatchesInGeneration | int | Number of notification batches in the process of being created by the generator during the reporting interval.
NotificationBatchesAwaitingDistribution | int | Number of notification batches waiting to be picked up by the distributor during the reporting interval.
NotificationsSuccessfulDeliveredCount | int | Number of notifications successfully delivered during the reporting interval.
NotificationsFailedDeliveryCount | int | Number of notifications that failed delivery and were marked as expired during the reporting interval.
WorkItemsInProgress | int | Number of work items being distributed during the reporting interval.
SubscriptionsAddedCount | int | Number of subscriptions added to the application during the reporting interval.
ScheduledSubscriptionsAdded | int | Number of scheduled subscriptions added to the application during the reporting interval.
SubscriptionsModified | int | Number of subscriptions modified in the application during the reporting interval.
SubscribersAddedCount | int | Number of subscribers added to the instance during the reporting interval.
SubscriberDevicesAddedCount | int | Number of subscriber devices added during the reporting interval. The device is assumed to be added at the same time the subscriber is added.
SubscriberDevicesModifiedCount | int | Number of subscriber devices updated during the reporting interval. The device is assumed to be updated at the same time the subscriber is updated.
Remarks

The NSAdministrationHistory stored procedure is created when you run NSControl Create. It is located in instance databases.

The amount of data gathered by this report is limited by the vacuumer retention period specified in the <VacuumDuration> node of the application definition file (ADF). Only data that has not been removed can be analyzed.

To determine the current UTC date and time, run SELECT GETUTCDATE() in SQL Query Analyzer. The current UTC time is derived from the current local time and the time zone setting in the operating system of the computer on which Microsoft SQL Server is running.

Permissions

Execute permissions default to members of the NSAnalysis database role, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example produces the administrative history report for the Stock application. Each reporting period is 120 minutes. The report starts at 11:30 A.M. on April 22, 2002 and ends at 2:30 P.M. the same day:

EXEC NSAdministrationHistory N'Stock', 120,
    '2002-04-22 11:30:00', '2002-04-22 14:30:00'

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSDiagnosticDeliveryChannel

Produces the delivery channel report for a Notification Services application. This report can help you analyze delivery channel activity and failed notifications.

Syntax
NSDiagnosticDeliveryChannel
    [@ApplicationName =] 'app_name' ,
    [@DeliveryChannelName =] 'delivery_channel_name'
    [, [@ReportingInterval =] interval]
    [, [@StartDateTime =] 'start_date_time']
    [, [@EndDateTime =] 'end_date_time']
Arguments
[@ApplicationName =] 'app_name'
Is the name of a Notification Services application, as defined in the configuration file. app_name is nvarchar(255) and has no default value.
[@DeliveryChannelName =] 'delivery_channel_name'
Is the name of a delivery channel, as defined in the configuration file. delivery_channel_name is nvarchar(255) and has no default value.
[@ReportingInterval =] interval
Is the number of generator quanta in each reporting interval. The report contains one row per interval. interval is int and has a default value of 1, which indicates one generator quantum per interval.

The quantum duration is defined in the application definition file (ADF).

[@StartDateTime =] 'start_date_time'
Is the report start date and time in UTC (Universal Time Coordinate or Greenwich mean time). start_date_time is datetime. The default value is (5 * <QuantumDuration> * @ReportingInterval) before the @EndDateTime value. Using the default value, the result set contains at most five rows, each row representing one reporting interval.
[@EndDateTime =] 'end_date_time'
Is the report end date and time in UTC. end_date_time is datetime. The default value is the result of the GETUTCDATE function, which returns the time when the stored procedure is invoked.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column Name | Data Type | Description
IntervalStartDateTime | datetime | Starting date and time for the reporting interval in UTC.
IntervalEndDateTime | datetime | Ending date and time for the reporting interval in UTC.
NotificationBatchesDelivered | int | Number of notification batches delivered during the reporting interval.
NotificationDeliveryAttempts | int | Number of notifications the delivery channel attempted to send during the reporting interval.
NotificationSuccessfulDeliveries | int | Number of notifications the delivery channel successfully sent during the reporting interval.
NotificationAttemptsFailed | int | Number of notifications the delivery channel failed to send during the reporting interval.
NotificationToMessageRatio | float | During the reporting interval, ratio of notifications generated to messages sent. For digest or multicast delivery, one message can include multiple notifications. This column indicates how many notifications, on average, are included in digest or multicast messages.
Remarks

The NSDiagnosticDeliveryChannel stored procedure is created when you run NSControl Create. It is located in each instance database and calls a stored procedure in the application database.

To determine the current UTC date and time, run SELECT GETUTCDATE() in SQL Query Analyzer. The current UTC time is derived from the current local time and the time zone setting in the operating system of the computer on which SQL Server is running.

Permissions

Execute permissions default to members of the NSAnalysis database role, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example produces the delivery channel report for the Stock application and the FileChannel delivery channel. The report includes 50 generator quanta in each row. The report starts at 5:00 P.M. on May 23, 2002 and ends at 6:00 P.M. the same day:

EXEC NSDiagnosticDeliveryChannel N'Stock', N'FileChannel', 50,
    '2002-05-23 17:00', '2002-05-23 18:00'

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSDiagnosticEventClass

Produces the event class report for a Notification Services application. This report can help you troubleshoot event collection and can provide information about the processing of events by the application.

Syntax
NSDiagnosticEventClass
    [@ApplicationName =] 'app_name' ,
    [@EventClassName =] 'event_class_name'
    [, [@ReportingInterval =] interval]
    [, [@StartDateTime =  'start_date_time']
    [, [@EndDateTime =] 'end_date_time']
Arguments
[@ApplicationName =] 'app_name'
Is the name of an application, as defined in the configuration file. app_name is nvarchar(255) and has no default value.
[@EventClassName =] 'event_class_name'
Is the name of an event class within the application. event_class_name is nvarchar(255) and has no default value.
[@ReportingInterval =] interval
Is the number of generator quanta in each reporting interval. The report contains one row per interval. interval is int and has a default value of 1, which indicates one generator quantum per interval.

The quantum duration is defined in the application definition file (ADF).

[@StartDateTime =] 'start_date_time'
Is the report start date and time in UTC (Universal Time Coordinate or Greenwich mean time). start_date_time is datetime. The default value is (5 *<QuantumDuration> * @ReportingInterval) before the @EndDateTime value. Using the default value, the result set contains at most five rows, each row representing one reporting interval.
[@EndDateTime =] 'end_date_time'
Is the report end date and time in UTC. end_date_time is datetime. The default value is the result of the GETUTCDATE function, which returns the time when the stored procedure is invoked.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column Name | Data Type | Description
IntervalStartDateTime | datetime | Starting date and time for the reporting interval in UTC.
IntervalEndDateTime | datetime | Ending date and time for the reporting interval in UTC.
EventBatchesCollectedCount | int | Number of event batches collected within the reporting interval, based on the batch EndCollectionTime value.
UnfinishedEventBatches | int | Number of event batches started within the reporting interval that do not have an EndCollectionTime value.
AvgEventBatchEventCount | float | For event batches collected during the reporting interval, average number of events per batch.
AvgEventsCollectedPerSecond | float | For event batches collected during the reporting interval, average number of events collected per second.
AvgGeneratorPickupWaitPerBatch | float | For event batches collected during the reporting interval, average amount of time, in seconds, it took the generator to fire an event subscription rule against the event batch.
AvgEventChronicleRuleFiringTimePerBatch | float | For event batches collected during the reporting interval, average time, in seconds, it took for the event chronicle rule to run.
AvgEventSubscriptionRuleFiringTimePerBatch | float | For event batches collected during the reporting interval, average time, in seconds, it took for the event subscription rules to run.
EventNotificationBatchCount | int | From the event batches collected during the reporting interval, number of notification batches generated.
EventNotificationsGeneratedCount | int | From the event batches collected during the reporting interval, number of notifications generated.
AvgEventNotificationBatchGenerationTime | float | For the event batches collected during the reporting interval, average time, in seconds, for the generator to create a notification batch.
AvgEventNotificationBatchWaitTillDistribution | float | For the event batches collected during the reporting interval, average time, in seconds, that notification batches waited for the distributor to pick up distribution work items.
EventNotificationDeliveryAttempts | int | Number of attempts to deliver notifications created from events collected during the reporting interval.
EventNotificationSuccessfulDeliveries | int | For the event batches collected during the reporting interval, number of successful notification deliveries.
EventNotificationFailedAttempts | int | For the event batches collected during the reporting interval, number of failed notification delivery attempts.
EventNotificationsDeliveryNotAttempted | int | For the event batches collected during the reporting interval, number of notifications the distributor has not yet attempted to deliver.
EventNotificationsNotYetDelivered | int | For the event batches collected during the reporting interval, number of notifications that have not yet been delivered either due to no attempt to deliver or due to failure when attempted.
EventNotificationToMessageRatio | float | For the event batches collected during the reporting interval, the ratio of notifications generated to messages sent. For digest or multicast delivery, one message can include multiple notifications. This column indicates how many notifications, on average, are included in digest or multicast messages.
AvgEventNotificationBatchSucceedDeliveryTime | float | For the notifications generated from the interval's event batches, average time to successfully send the notifications through the distribution process.
Remarks

The NSDiagnosticEventClass stored procedure is created when you run NSControl Create. It is located in each instance database, and calls a stored procedure in the application database.

Event batches fall within the reporting interval when the EndCollectionTime value is greater than the IntervalStartDateTime value and less than or equal to the IntervalEndDateTime value.

To determine the current UTC date and time, run SELECT GETUTCDATE() in SQL Query Analyzer. The current UTC time is derived from the current local time and the time zone setting in the operating system of the computer on which SQL Server is running.

Permissions

Execute permissions default to members of the NSAnalysis database role, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example produces the event class diagnostic report for the Stock application and StockEvents event class. The report includes 40 generator quanta in each report interval. The report starts at 5:00 P.M. on May 23, 2002 and ends at 6:00 P.M. the same day:

EXEC NSDiagnosticEventClass N'Stock', N'StockEvents', 40,
    '2002-05-23 17:00', '2002-05-23 18:00'

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSDiagnosticEventProvider

Produces the event provider report for a Notification Services application. The report contains information about the events collected through a specified event provider.

Syntax
NSDiagnosticEventProvider
    [@ApplicationName =] 'app_name' ,
    [@EventProviderName =] 'event_provider_name'
    [, [@ReportingInterval =] interval]
    [, [@StartDateTime =] 'start_date_time']
    [, [@EndDateTime =] 'end_date_time']
Arguments
[@ApplicationName =] 'app_name'
Is the name of an application, as defined in the configuration file. app_name is nvarchar(255) and has no default value.
[@EventProviderName =] 'event_provider_name'
Is the name of an event provider within the application. event_provider_name is nvarchar(255) and has no default value.
[@ReportingInterval =] interval
Is the number of generator quanta in each reporting interval. The report contains one row per interval. interval is int and has a default value of 1, which indicates one generator quantum per interval.

The quantum duration is defined in the application definition file (ADF).

[@StartDateTime =] 'start_date_time'
Is the report start date and time in UTC (Universal Time Coordinate or Greenwich mean time). start_date_time is datetime. The default value is (5 * <QuantumDuration> * @ReportingInterval) before the @EndDateTime value. Using the default value, the result set contains at most five rows, each row representing one reporting interval.
[@EndDateTime =] 'end_date_time'
Is the report end date and time in UTC. end_date_time is datetime. The default value is the result of the GETUTCDATE function, which returns the time when the stored procedure is invoked.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column Name | Data Type | Description
IntervalStartDateTime | datetime | Starting date and time for the reporting interval in UTC.
IntervalEndDateTime | datetime | Ending date and time for the reporting interval in UTC.
EventBatchesSubmitted | int | Number of event batches submitted through the event provider during the reporting interval.
EventsSubmitted | int | Number of events submitted through the event provider during the reporting interval.
AvgTimeCollectingEvents | float | Average time in seconds the event provider spent collecting events during the reporting interval.
UnfinishedEventBatches | int | Number of event batches started by the event provider during the reporting interval that do not have an EndCollectionTime value.
Remarks

The NSDiagnosticEventProvider stored procedure is created when you run NSControl Create. It is located in each instance database, and calls a stored procedure in the application database.

Event batches fall within the reporting interval when the EndCollectionTime value is greater than IntervalStartDateTime and less than or equal to IntervalEndDateTime.

To determine the current UTC date and time, run SELECT GETUTCDATE() in SQL Query Analyzer. The current UTC time is derived from the current local time and the time zone setting in the operating system of the computer on which SQL Server is running.

Permissions

Execute permissions default to members of the NSAnalysis database role, the db_owner fixed database role, and the sysadmin fixed server role.

Example

This example produces the event provider diagnostic report for the Stock application and StockEP event provider. The report includes 50 generator quanta in each report interval. The report starts at 5:00 P.M. on May 23, 2002 and ends at 6:00 P.M. the same day:

EXEC NSDiagnosticEventProvider N'Stock', N'StockEP', 50,
    '2002-05-23 17:00', '2002-05-23 18:00'

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSDiagnosticFailedNotifications

Produces the failed notifications report for a Notification Services application. The report contains a list of failed notifications. Each row in the report includes the notification and subscription classes that produced the notification, the subscriber the notification would have been sent to, and information about delivery attempts. This information can be used to troubleshoot notification delivery.

Syntax
NSDiagnosticFailedNotifications
    [@ApplicationName =] 'app_name' ,
    [, [@StartDateTime =] 'start_date_time']
    [, [@EndDateTime =] 'end_date_time']
Arguments
[@ApplicationName =] 'app_name'
Is the name of an application, as defined in the configuration file. app_name is nvarchar(255) and has no default value.
[@StartDateTime =] 'start_date_time'
Is the report start date and time in UTC (Universal Time Coordinate or Greenwich mean time). start_date_time is datetime. The default value is the system start date and time.
[@EndDateTime =] 'end_date_time'
Is the report end date and time in UTC. end_date_time is datetime. The default value is the result of the GETUTCDATE function, which returns the time when the stored procedure is invoked.
Return Code Values

None

Result Sets
Column Name | Data Type | Description
ApplicationName | nvarchar(255) | Name of the application the failed notification is from.
NotificationClassName | nvarchar(255) | Name of the notification class that generated the notification.
DeliveryChannelName | nvarchar(255) | Name of the delivery channel that attempted to deliver the notification.
NotificationBatchId | bigint | ID of the notification batch that contains the failed notification.
NotificationId | bigint | ID of the failed notification.
SubscriberId | nvarchar(255) | ID number of the subscriber who should have received the notification.
SubscriberDeviceAddress | nvarchar(255) | Address, such as an e-mail address, of the device that should have received the notification.
NumberOfDeliveryAttempts | int | Number of times the distributor attempted to deliver the notification.
LastFailureTime | datetime | Date and time the notification delivery last failed.
NextRetryTime | datetime | Next date and time the distributor will attempt to deliver the message.
Remarks

The NSDiagnosticFailedNotifications stored procedure is created when you run NSControl Create. It is located in each instance database, and calls a stored procedure in the application database.

The output is ordered by ApplicationName, NotificationClassName, DeliveryChannelName, and then SubscriberId.

The report does not relate notifications to individual subscriptions because more than one subscription can contribute to a notification.

Notification Services does not store the reason for failure in the database. The delivery channel can write the reason to the event log if the delivery service supports error logging.

To determine the current UTC date and time, run SELECT GETUTCDATE() in SQL Query Analyzer. The current UTC time is derived from the current local time and the time zone setting in the operating system of the computer on which SQL Server is running.

Permissions

Execute permissions default to members of the NSAnalysis database role, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example produces the failed notifications report for the Stock application. The report includes information for all notifications that failed between 5:00 P.M. and 6:00 P.M. on May 23, 2002:

EXEC NSDiagnosticFailedNotifications N'Stock',
    '2002-05-23 17:00', '2002-05-23 18:00'

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSDiagnosticNotificationClass

Produces the notification class report for a Notification Services application. The report provides information about the number of notifications and notification batches processed by the notification class and whether the notifications are being successfully delivered.

Syntax
NSDiagnosticNotificationClass
    [@ApplicationName =] 'app_name' ,
    [@NotificationClassName =] 'notification_class_name'
    [, [@ReportingInterval =] interval]
    [, [@StartDateTime =] 'start_date_time']
    [, [@EndDateTime =] 'end_date_time']
Arguments
[@ApplicationName =] 'app_name'
Is the name of an application, as defined in the configuration file. app_name is nvarchar(255) and has no default value.
[@NotificationClassName =] 'notification_class_name'
Is the name of the notification class, as defined in the application definition file (ADF). notification_class_name is nvarchar(255) and has no default value.
[@ReportingInterval =] interval
Is the number of generator quanta in each reporting interval. The report contains one row per interval. interval is int and has a default value of 1, which indicates one generator quantum per interval.

The quantum duration is defined in the application definition file (ADF).

[@StartDateTime =] 'start_date_time'
Is the report start date and time in UTC (Universal Time Coordinate or Greenwich mean time). start_date_time is datetime. The default value is (5 * <QuantumDuration> * @ReportingInterval) before the @EndDateTime value. Using the default value, the result set contains at most five rows, each row representing one reporting interval.
[@EndDateTime =] 'end_date_time'
Is the report end date and time in UTC. end_date_time is datetime. The default value is the result of the GETUTCDATE function, which returns the time when the stored procedure is invoked.
Return Code Values

0 (success) or 1 (failure)

Result Set
Column Name | Data Type | Description
IntervalStartDateTime | datetime | Starting date and time for the reporting interval in UTC.
IntervalEndDateTime | datetime | Ending date and time for the reporting interval in UTC.
NotificationBatchesGenerated | int | Number of notification batches generated by the notification class during the reporting interval.
NotificationsGenerated | int | Number of notifications generated by the notification class during the reporting interval.
NotificationsGeneratedPerSecond | float | For the notification class, the number of notifications generated per second during the reporting interval.
AvgNotificationBatchWaitTillDistribution | float | For the notification class, average wait time before the distributor picked up a notification batch during the reporting interval.
NotificationDeliveryAttempts | int | For notification batches generated during the reporting interval, number of delivery attempts.
NotificationSuccessfulDeliveries | int | For notification batches generated during the reporting interval, number of notifications successfully delivered.
NotificationFailedAttempts | int | For notification batches generated during the reporting interval, number of notifications marked as failed.
NotificationsDeliveryNotAttempted | int | For notification batches generated during the reporting interval, number of notifications the distributor has not yet attempted to deliver.
NotificationsNotYetDelivered | int | For notification batches generated during the reporting interval, number of notifications not yet delivered either due to no attempt to deliver or due to failure when attempted.
NotificationToMessageRatio | float | For notification batches generated during the reporting interval, ratio of notifications generated to messages sent. For digest or multicast delivery, one message can include multiple notifications. This column indicates how many notifications, on average, are included in digest or multicast messages.
AvgNotificationBatchSucceedDeliveryTime | float | For notification batches generated during the reporting interval, average time to successfully send the notifications through the distribution process.
Remarks

The NSDiagnosticNotificationClass stored procedure is created when you run NSControl Create. It is located in each instance database and calls a stored procedure in the application database.

Notification batches fall within a reporting interval when the EndGenerationTime value is greater than IntervalStartDateTime and less than or equal to IntervalEndDateTime.

To determine the current UTC date and time, run SELECT GETUTCDATE() in SQL Query Analyzer. The current UTC time is derived from the current local time and the time zone setting in the operating system of the computer on which SQL Server is running.

Permissions

Execute permissions default to members of the NSAnalysis database role, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example produces the notification class diagnostic report for the Stock application and StockNotifications notification class. The report includes 60 generator quanta in each report interval. The report starts at 5:00 P.M. on May 23, 2002 and ends at 6:00 P.M. the same day:

EXEC NSDiagnosticNotificationClass N'Stock', N'StockNotifications', 60, '2002-05-23 17:00', '2002-05-23 18:00'

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSDiagnosticSubscriptionClass

Produces the subscription class diagnostic report for a Notification Services application. The report provides information, such as rule firing times and the delivery of notifications based on the subscription class, that you can use to troubleshoot subscription class processing.

Syntax
NSDiagnosticSubscriptionClass
    [@ApplicationName =] 'app_name' ,
    [@SubscriptionClassName =] 'subscription_class_name'
    [, [@ReportingInterval =] interval]
    [, [@StartDateTime =] 'start_date_time']
    [, [@EndDateTime =] 'end_date_time']
Arguments
[@ApplicationName =] 'app_name'
Is the name of an application, as defined in the configuration file. app_name is nvarchar(255) and has no default value.
[@SubscriptionClassName =] 'subscription_class_name'
Is the name of the subscription class, as defined in the application definition file (ADF). subscription_class_name is nvarchar(255) and has no default value.
[@ReportingInterval =] interval
Is the number of generator quanta in each reporting interval. The report contains one row per interval. interval is int and has a default value of 1, which indicates one generator quantum per interval.

The quantum duration is defined in the application definition file (ADF).

[@StartDateTime =] 'start_date_time'
Is the report start date and time in UTC (Universal Time Coordinate or Greenwich mean time). start_date_time is datetime. The default value is (5 * <QuantumDuration> * @ReportingInterval) before the @EndDateTime value. Using the default value, the result set contains at most five rows, each row representing one reporting interval.
[@EndDateTime =] 'end_date_time'
Is the report end date and time in UTC. end_date_time is datetime. The default value is the result of the GETUTCDATE function, which returns the time when the stored procedure is invoked.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column Name | Data Type | Description
IntervalStartDateTime | datetime | Starting date and time for the reporting interval in UTC.
IntervalEndDateTime | datetime | Ending date and time for the reporting interval in UTC.
SubscriptionsScheduledCount | int | Number of scheduled subscriptions processed during the reporting interval.
AvgScheduledSubscriptionWaitTime | float | For the subscriptions scheduled for processing during the interval, average lag time between the scheduled time for the subscription and the actual time the generator processed the subscription.
AvgScheduledNotificationGenerationTime | float | For the subscriptions scheduled for processing during the interval, average time the generator used to create raw notification data from scheduled subscriptions.
AvgScheduledSubscriptionRuleFiringTime | float | For the subscriptions scheduled for processing during the interval, average time used to run the scheduled subscription rule.
ScheduledNotificationBatchCount | int | For the subscriptions scheduled for processing during the interval, number of notification batches created.
ScheduledNotificationCount | int | For the subscriptions scheduled for processing during the interval, number of notifications created.
AvgScheduledNotificationBatchWaitTillDistribution | float | Average time a notification generated from a scheduled subscription waited until the distributor picked it up for distribution.
ScheduledNotificationDeliveryAttempts | int | For the subscriptions scheduled for processing during the interval, number of attempts to deliver notifications.
ScheduledNotificationSuccessfulDeliveries | int | For the subscriptions scheduled for processing during the interval, number of successful notification deliveries.
ScheduledNotificationFailedAttempts | int | For the subscriptions scheduled for processing during the interval, number of failed notification delivery attempts.
ScheduledNotificationsDeliveryNotAttempted | int | For the subscriptions scheduled for processing during the interval, number of notifications not yet attempted to be delivered.
ScheduledNotificationsNotYetDelivered | int | For the subscriptions scheduled for processing during the interval, number of notifications not yet delivered either due to no attempt to deliver or due to failure when attempted.
ScheduledNotificationToMessageRatio | float | For the subscriptions scheduled for processing during the interval, ratio of notifications generated to messages sent. For digest or multicast delivery, one message can include multiple notifications. This column indicates how many notifications, on average, are included in digest or multicast messages.
AvgScheduledNotificationBatchSucceedDeliveryTime | float | For the subscriptions scheduled for processing during the interval, average time to send the notifications through the distribution process successfully.
Remarks

The NSDiagnosticSubscriptionClass stored procedure is created when you run NSControl Create. It is located in each instance database, and calls a stored procedure in the application database.

Scheduled subscriptions fall within the reporting interval when the firing time for the scheduled rule is greater than IntervalStartDateTime and less than or equal to IntervalEndDateTime.

To determine the current UTC date and time, run SELECT GETUTCDATE() in SQL Query Analyzer. The current UTC time is derived from the current local time and the time zone setting in the operating system of the computer on which SQL Server is running.

Permissions

Execute permissions default to members of the NSAnalysis and db_owner database roles who have permission to run the Notifications Services extended stored procedures; this permission is granted using the GrantXPExec command. Members of the sysadmin fixed server role have all necessary permissions.

Example

The following example produces the subscription class diagnostic report for the Stock application and StockSubscriptions subscription class. The report includes 50 generator quanta in each report interval. The report starts at 5:00 P.M. on May 23, 2002 and ends at 6:00 P.M. the same day:

EXEC NSDiagnosticSubscriptionClass N'Stock', N'StockSubscriptions',
    50, '2002-05-23 17:00', '2002-05-23 18:00'

See Also

GrantXPExec Utility

Notification Services Performance Reports

Stored Procedure Reference


NSEventBatchDetails

Returns detailed information about an event batch in a Notification Services application. One result set contains general information about the event batch, such as the event provider name and the time the event batch was collected. A second result set displays the events that were submitted in the event batch.

Syntax
NSEventBatchDetails
    [@EventClassName =] 'event_class_name' ,
    [@EventBatchId =] event_batch_id
Arguments
[@EventClassName =] 'event_class_name'
Is the name of an event class. event_class_name is nvarchar(255) and has no default value.
[@EventBatchId =] event_batch_id
Is the unique identifier of an event batch. event_batch_id is bigint and has no default value.
Return Code Values

None

Result Sets

NSEventBatchDetails produces two result sets. The first result set contains general information about the event batch.

Column Name | Data Type | Description
ProviderName | nvarchar(255) | Name of the event provider that submitted the batch of events.
EventCount | bigint | Number of events in the event batch.
StartCollectionTime | datetime | Date and time that event batch collection started, in UTC (Universal Time Coordinate or Greenwich mean time).
EndCollectionTime | datetime | Date and time that event batch collection ended, in UTC.
CollectionTimeInMS | int | Total time, in milliseconds, to collect the batch of events.

The second result set contains details about the events submitted in the event batch, ordered by the EventId column.

Column Name | Data Type | Description
EventId | bigint | ID number used to identify an event.
Event_class_field_name (1-n) | user defined | Name of an event class field, as defined in the application definition file (ADF). Each field in the event class is represented by a column in the result set.
Remarks

The NSEventBatchDetails stored procedure is created when you run NSControl Create. It is located in application databases.

Permissions

Execute permissions default to members of the NSAnalysis database role, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example shows how to produce the event batch details report for the Stock sample application. The report contains two result sets. The first shows the event provider and event collection information for the event batch, and the second shows the events submitted in the event batch:

EXEC NSEventBatchDetails N'StockEvents', 1

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSEventBeginBatch<EventClassName>

 SQL Server Notification Services Books Online

NSEventBeginBatchEventClassName

Creates a new event batch for a Notification Services application. You typically use this stored procedure to open a new event batch so you can submit individual events using Transact-SQL. See the Remarks section for more information.

Syntax
NSEventBeginBatchEventClassName
    [@ProviderName =] 'event_provider_name',
    [@EventBatchId =] event_batch_variable OUTPUT
Arguments
[@ProviderName =] 'event_provider_name'
Is the name of the event provider submitting the events. event_provider_name is nvarchar(255) and has no default value.
[@EventBatchId =] event_batch_variable OUTPUT
Is the event batch identification number assigned to the event batch if created successfully. event_batch_variable is an output variable of type bigint, with no default value.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column Name | Data Type | Description
EventBatch | bigint | The event batch ID created for the new event batch.
Remarks

The NSEventBeginBatch EventClassName stored procedure is created when you run NSControl Create. It is located in application databases.

To submit individual events to an application using Transact-SQL, use NSEventBeginBatch EventClassName to open the batch, NSEventWrite EventClassName to write individual events, and NSEventFlushBatch EventClassName to close the event batch.

To use a query to obtain a set of events and then submit them to an application, use NSEventSubmitBatch EventClassName.

Permissions

Execute permissions default to members of the NSEventProvider and NSRunService database roles, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example shows how to begin an event batch, write one event, and then close the event batch. The event provider for the event batch is StockEP and the event batch ID number is returned in the @BatchID output parameter:

DECLARE @BatchID bigint
EXEC NSEventBeginBatchStockEvents N'StockEP', @BatchID OUTPUT
EXEC NSEventWriteStockEvents
   @EventBatchId=@BatchID,
   @StockSymbol=N'AWKS',
   @StockPrice=68.14
EXEC NSEventFlushBatchStockEvents @BatchID
SELECT @BatchID 'Event Batch'

This example assumes that you are using SQL Query Analyzer, because the event batch ID is returned in the SELECT statement so you can see which event batch was created.

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSEventFlushBatch<EventClassName>

 SQL Server Notification Services Books Online

NSEventFlushBatchEventClassName

Closes an event batch that was opened by NSEventBeginBatch EventClassName. This stored procedure commits the event collection transaction and then marks the event batch complete. You typically use this stored procedure if you are submitting individual events using Transact-SQL. See the Remarks section for more information.

Syntax
NSEventFlushBatchEventClassName
    [@EventBatchId =] event_batch_ID
    [, [@EventCount =] number_of_events]
Arguments
[@EventBatchId =] event_batch_ID
Is the ID number of the event batch to commit. event_batch_ID is bigint and has no default value.
[@EventCount =] number_of_events
Is the number of events submitted for the event batch. The stored procedure obtains the default value by querying the event table.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column Name | Data Type | Description
EventCount | bigint | Number of events submitted in the event batch. This number is either specified in the @EventCount argument or obtained by querying the events table.
Remarks

The NSEventFlushBatch EventClassName stored procedure is created when you run NSControl Create. It is located in application databases.

To submit individual events to an application using Transact-SQL, use NSEventBeginBatch EventClassName to open the batch, NSEventWrite EventClassName to write individual events, and NSEventFlushBatch EventClassName to close the event batch.

To use a query to obtain a set of events and then submit them to an application, use NSEventSubmitBatch EventClassName.

Permissions

Execute permissions default to members of the NSEventProvider and NSRunService database roles, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example shows how to begin an event batch, write one event, and then close the event batch. The event provider for the event batch is StockEP and the event batch ID number is returned in the @BatchID output parameter:

DECLARE @BatchID bigint
EXEC NSEventBeginBatchStockEvents N'StockEP', @BatchID OUTPUT
EXEC NSEventWriteStockEvents
   @EventBatchId=@BatchID,
   @StockSymbol=N'AWKS',
   @StockPrice=68.14
EXEC NSEventFlushBatchStockEvents @BatchID
SELECT @BatchID 'Event Batch'

This example assumes that you are using SQL Query Analyzer, because the event batch ID is returned in the SELECT statement so you can see which event batch was created.

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSEventSubmitBatch<EventClassName>

 SQL Server Notification Services Books Online

NSEventSubmitBatchEventClassName

Creates a new event batch, obtains a set of events from a query and then submits those events, optionally runs a post-processing query, and then closes the event batch. Using a query as the event source enables you to submit multiple events at one time, unlike the NSEventWrite EventClassName stored procedure.

Syntax
NSEventSubmitBatchEventClassName
    [@ProviderName =] 'event_provider_name' ,
    [@EventsQuery =] 'selection_query' ,
    [@PostQuery =] 'post_processing_query'
Arguments
[@ProviderName =] 'provider_name'
Is the name of the event provider that is submitting the events. provider_name is nvarchar(255) and must be one of the event providers specified in the application definition file (ADF).
[@EventsQuery =] 'selection_query'
Is the text of the Transact-SQL query used to select the records to be submitted as events. The schema of the records generated by the query must match the schema of the event table to which they are being submitted. selection_query is nvarchar(4000).
[@PostQuery =] 'post_processing_query'
Is the text of a Transact-SQL query used to do any post-processing cleanup or state maintenance, like updating chronicle tables or deleting any temporary objects. post_processing_query is nvarchar(4000).
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column Name | Data Type | Description
EventCount | bigint | Number of events submitted in the event batch. This number is obtained by querying the event table.
Remarks

The NSEventSubmitBatch EventClassName stored procedure is created when you run NSControl Create. It is located in application databases.

To submit individual events to an application using Transact-SQL, use NSEventBeginBatch EventClassName to open the batch, NSEventWrite EventClassName to write individual events, and NSEventFlushBatch EventClassName to close the event batch.

Permissions

Execute permissions default to members of the NSEventProvider and NSRunService database roles, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example shows how to use the NSEventSubmitBatchStockEvents stored procedure to obtain stock names and prices from the Stocks table of the Market database, and then write the data to the NSStockEventsEvents table. This query specifies an empty post-processing query:

EXEC NSEventSubmitBatchStockEvents
    @ProviderName = N'StockEP',
    @EventsQuery = 'SELECT StockSymbol, StockPrice
                    FROM Market.dbo.Stocks',
    @PostQuery = ''

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSEventWrite<EventClassName>

 SQL Server Notification Services Books Online

NSEventWriteEventClassName

Submits one event to the events table for the event class. You must use NSEventBeginBatch EventClassName to open a new batch and NSEventFlushBatch EventClassName to close the batch. You can submit multiple events before closing the batch.

Syntax
NSEventWriteEventClassName
    [@EventBatchId =] event_batch_ID ,
    [@event_class_field_name =] event_class_field_value [, ...n]
Arguments
[@EventBatchId =] event_batch_ID
Is the ID of the event batch for the event. The event batch ID number must exist in the event batches table. event_batch_ID is bigint and has no default value.
[@event_class_field_name =] event_class_field_value
Provides a name/value pair for an event class field. One event_class_field_name and event_class_field_value pair can be supplied for each column in the event table. If the column has a default value or accepts NULL, the name/value pair is not required.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

The NSEventWrite EventClassName stored procedure is created when you run NSControl Create. It is located in application databases.

To submit individual events to an application using Transact-SQL, use NSEventBeginBatch EventClassName to open the batch, NSEventWrite EventClassName to write individual events, and NSEventFlushBatch EventClassName to close the event batch.

To use a query to obtain a set of events and then submit them to an application, use NSEventSubmitBatch EventClassName.

Permissions

Execute permissions default to members of the NSEventProvider and NSRunService database roles, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example shows how to begin an event batch, write one event, and then close the event batch. The event provider for the event batch is StockEP and the event batch ID number is returned in the @BatchID output parameter:

DECLARE @BatchID bigint
EXEC NSEventBeginBatchStockEvents N'StockEP', @BatchID OUTPUT
EXEC NSEventWriteStockEvents
   @EventBatchId=@BatchID,
   @StockSymbol=N'AWKS',
   @StockPrice=68.14
EXEC NSEventFlushBatchStockEvents @BatchID
SELECT @BatchID 'Event Batch'

This example assumes that you are using SQL Query Analyzer, because the event batch ID is returned in the SELECT statement so you can see which event batch was created.

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSExecuteRuleFiring

Prepares and runs Notification Services application rules. This enables you to manually run the generator, running rules to generate notifications and manage state.

If a rule cannot be fired, the stored procedure attempts to prepare the next rule firing by creating the next quantum, materializing the appropriate event and scheduled subscription views, and scheduling rule firings.

Syntax
NSExecuteRuleFiring
    [[@ReportExecutionResults =] report_flag]
    [, [@DisableQuantumLimits =] limit_flag]
Arguments

[@ReportExecutionResults =] report_flag

Indicates whether the stored procedure reports information about the execution of the rule firing. Nonzero values result in information being returned about the rule firing. report_flag is tinyint and has a default value of 1.

[@DisableQuantumLimits =] limit_flag

Indicates whether the stored procedure observes the application-specified event chronicle quantum and subscription quantum limits. A nonzero value causes the quantum scheduling to ignore the quantum limits. limit_flag is tinyint and has a default value of 1.

Return Code Values

0 (success) or 1 (failure)

Result Sets

NSExecuteRuleFiring produces up to three result sets. The first result set contains information about any scheduled rules.

Column Name | Data Type | Description
QuantumId | int | ID number of the quantum that contains the rule.
QuantumStartTime | datetime | Starting date and time, in UTC (Universal Time Coordinate or Greenwich mean time), of the quantum containing the rule.
QuantumEndTime | datetime | Ending date and time, in UTC, of the quantum containing the rule.
RuleName | nvarchar(255) | Name assigned to the rule in the application definition file (ADF). If no rule is ready to run, this value is NULL.
EventClassName | nvarchar(255) | For event-triggered rules, name of the related event class. If the rule is a scheduled subscription rule, or if no rule is ready to run, this value is NULL.
SubscriptionClassName | nvarchar(255) | Name of the related subscription class. If the rule is an event chronicle rule, or if no rule is ready to run, the value is NULL.
RuleFiringId | int | ID number that identifies the prepared rule firing. The column is NULL if no rule firing is ready to run.
EventBatchId | bigint | ID number that identifies the related event batch. If the rule is not an event chronicle or event subscription rule, the application is not processing events in order, or there is no rule ready to run, the value is NULL.
StartScanTime | datetime | Starting date and time, in UTC, for a prepared scheduled subscription rule. The starting date and time must fall between QuantumStartTime and QuantumEndTime. If the rule is not an event chronicle or event subscription rule, the application is not processing events in order, or there is no rule ready to run, the value is NULL.
EndScanTime | datetime | Ending date and time, in UTC, for a prepared scheduled subscription rule. The ending date and time must fall between QuantumStartTime and QuantumEndTime. If the rule is not an event chronicle or event subscription rule, the application is not processing events in order, or there is no rule ready to run, the value is NULL.
RemainingQuantumRuleFirings | int | Number of remaining rule firings to complete rule firing for the quantum. This number count includes any prepared rule firings, because they have not run. If there are no rules to prepare, this value is 0.

The second result set appears only if there are possible effects to any chronicles. The result set is ordered by PossibleChronicleReferenceByRule.

Column Name | Data Type | Description
PossibleChronicleReferenceByRule | nvarchar(255) | Name of event chronicle associated with a prepared rule firing.

The third result set appears only if running the stored procedure created notifications. The result set contains information about the notifications and is grouped by the NotificationClassName value.

Column Name | Data Type | Description
NotificationClassName | nvarchar(255) | Name of the notification class that produced notifications.
NotificationBatchId | bigint | ID number of the notification batch that contains the generated notifications.
NotificationCount | bigint | Number of notifications generated by the rule firing.
StartGenerationTime | datetime | Starting date and time, in UTC, for the notification batch.
Remarks

The NSExecuteRuleFiring stored procedure is created when you run NSControl Create. It is located in application databases.

The generator must be disabled to run the NSExecuteRuleFiring stored procedure. Because this stored procedure manually operates the generator, allowing the generator to run at the same time would make using this stored procedure difficult.

Permissions

Execute permissions default to members of the NSGenerator and NSRunService database roles, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example shows how to run prepared rules, reporting on the rule firing. The rule firing does not ignore quantum limits specified in the ADF:

EXEC NSExecuteRuleFiring 0, 0

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSNotificationBatchDetails

Produces the notification batch details report for a Notification Services application. The report contains information about a specified notification batch, such as the rule firing that produced the batch and the notifications contained in the batch. Use this stored procedure to troubleshoot notification generation and to analyze the progression of notifications through the application.

Syntax
NSNotificationBatchDetails
    [@NotificationClassName =] 'notification_class_name' ,
    [@NotificationBatchId =] notification_batch_id
Arguments
[@NotificationClassName =] 'notification_class_name'
Is the name of a notification class. notification_class_name is nvarchar(255) and has no default value.
[@NotificationBatchId =] notification_batch_id
Is the unique identifier used to identify a notification batch. notification_batch_id is bigint and has no default value.
Return Code Values

None

Result Sets

NSNotificationBatchDetails produces two result sets. The first result set contains general information about the notification batch.

Column Name | Data Type | Description
RuleFiringId | int | Unique ID of the rule firing that produced the notification batch.
StartGenerationTime | datetime | Starting date and time, in UTC, of the notification batch generation.
EndGenerationTime | datetime | Ending date and time, in UTC, of the notification batch generation.
GenerationTimeInMS | int | Time, in milliseconds, to complete the notification batch.
NotificationBatchExpirationTime | datetime | Date and time, in UTC, at which the notification batch expires. Notifications are not delivered after the expiration date and time. If this value is NULL, the batch has no expiration value.
NotificationCount | int | Number of notifications in the notification batch.
StatusDescription | nvarchar(255) | Current status of the notification batch.
DistributionStartTime | datetime | Date and time, in UTC, at which the distributor started processing notifications from the batch.
NotificationsWithNoDeliveryAttempt | int | Number of notifications the distributor has not yet attempted to deliver.
NotificationsSuccessfullyDelivered | int | Number of successful notification deliveries from the notification batch.
NotificationsFailedToDeliver | int | Number of failed notification deliveries from the notification batch.
DeliveryAttempts | int | Number of attempts made to deliver notifications from the notification batch.

The second result set contains detailed information about notifications in the notification batch.

Column Name | Data Type | Description
NotificationId | bigint | ID number of the notification within the notification batch.
SubscriberId | nvarchar(255) | ID number of the subscriber for the notification.
DeviceName | nvarchar(255) | Name of the subscriber device for the notification.
SubscriberLocale | nvarchar(10) | Name of the locale for the notification.
DeliveryStatus | nvarchar(255) | Description of the current delivery status for the notification.
SentTime | datetime | Date and time, in UTC, at which the notification was successfully sent. If this value is NULL, the notification has not been successfully sent.
LinkedParentNotification | bigint | If the notification was sent in a digest or multicast message, ID of the digest or multicast message.
DeliveryChannel | nvarchar(255) | Name of the delivery channel that sent the notification.
DeliveryAttempts | int | Number of delivery attempts made for the notification.
NextRetryTime | datetime | The next available date and time for a retry attempt with the notification.
Notification_class_field_name (1-n) | user defined | The name of a notification class field, as defined in the application definition file (ADF). Each field in the notification class is represented by a column in the result set.
Remarks

The NSNotificationBatchDetails stored procedure is created when you run NSControl Create. It is located in application databases.

Permissions

Execute permissions default to members of the NSAnalysis database role, the db_owner fixed database role, and the sysadmin fixed server role.

Example

This example produces the two result sets specified earlier in this section for notification batch 1 of the StockNotifications notification class:

EXEC NSNotificationBatchDetails N'StockNotifications', 1

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSPrepareRuleFiring

Prepares the Notification Services application database for a rule firing. This preparation ensures that a quantum has been scheduled, event and scheduled subscription views are properly materialized for the quantum, and rule firings are scheduled for the quantum based on the set of events and subscriptions available.

After the stored procedure completes, the application database has a state equivalent to what exists prior to rule execution during normal generator operation.

Syntax
NSPrepareRuleFiring
    [[@ReportPossibleEventChronicleUsage =] chronical_usage_flag]
    [, [@DisableQuantumLimits =] quantum_limits_flag]
Arguments
[@ReportPossibleEventChronicleUsage =] chronical_usage_flag
Indicates whether the prepared rule firing procedure returns a list of possible event chronicles affected or used by the rule firing. A nonzero value causes the routine to return a result set listing the set of event chronicles associated with the prepared rule firing. chronical_usage_flag is tinyint and has a default value of 1.
[@DisableQuantumLimits =] quantum_limits_flag
Indicates whether the scheduling of a new quantum uses the <ChronicleQuantumLimit> and <SubscriptionQuantumLimit> application execution settings. A nonzero value indicates that the stored procedure should not use these settings to skip one or more quantum periods. quantum_limits_flag is tinyint and has a default value of 1.
Return Code Values

0 (success) or 1 (failure)

Result Sets

NSPrepareRuleFiring produces one or two result sets. The first result set contains information about the rule.

Column Name | Data Type | Description
QuantumId | int | ID number of the quantum that contains the rule.
QuantumStartTime | datetime | Starting date and time, in UTC (Universal Time Coordinate or Greenwich mean time), of the quantum containing the rule.
QuantumEndTime | datetime | Ending date and time, in UTC, of the quantum containing the rule.
RuleName | nvarchar(255) | Name assigned to the rule in the application definition file (ADF). If no rule is ready to run, this value is NULL.
EventClassName | nvarchar(255) | For event-triggered rules, name of the related event class. If the rule is a scheduled subscription rule, or if no rule is ready to run, this value is NULL.
SubscriptionClassName | nvarchar(255) | Name of the related subscription class. If the rule is an event chronicle rule, or if no rule is ready to run, the value is NULL.
RuleFiringId | int | ID number that identifies the prepared rule firing. The column is NULL if no rule firing is ready to run.
EventBatchId | bigint | ID number that identifies the related event batch. If the rule is not an event chronicle or event subscription rule, the application is not processing events in order, or there is no rule ready to run, the value is NULL.
StartScanTime | datetime | Starting date and time, in UTC, for a prepared scheduled subscription rule. The starting date and time must fall between QuantumStartTime and QuantumEndTime. If the rule is not an event chronicle or event subscription rule, the application is not processing events in order, or there is no rule ready to run, the value is NULL.
EndScanTime | datetime | Ending date and time, in UTC, for a prepared scheduled subscription rule. The ending date and time must fall between QuantumStartTime and QuantumEndTime. If the rule is not an event chronicle or event subscription rule, the application is not processing events in order, or there is no rule ready to run, the value is NULL.
RemainingQuantumRuleFirings | int | Number of remaining rule firings to complete rule firing for the quantum. This number count includes any prepared rule firings, because they have not run. If there are no rules to prepare, this value is 0.

The second result set appears only if there are possible effects on the chronicles. The result set is ordered by PossibleChronicleReferenceByRule.

Column Name | Data Type | Description
PossibleChronicleReferenceByRule | nvarchar(255) | Name of the event chronicle associated with a prepared rule firing.
Remarks

The NSPrepareRuleFiring stored procedure is created when you run NSControl Create. It is located in application databases.

This stored procedure can be executed only when the generator is in the disabled or disabled pending state.

The stored procedure can be called repetitively without calling NSExecuteRuleFiring, but the state in the application database will not be altered. The only way to move the application database state beyond a prepared rule firing is to call NSExecuteRuleFiring or to start the NS$instance_name service, if necessary.

Permissions

Execute permissions default to members of the NSGenerator and NSRunService database roles, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example shows how to prepare the database for the execution of scheduled rules, reporting on the possible use of event chronicles. The rule firing does not ignore quantum limits specified in the ADF:

EXEC NSPrepareRuleFiring 0, 0

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSQuantumDetails

Returns detailed information about a specified quantum. Use this stored procedure to troubleshoot long-running quanta or analyze quantum processing.

Syntax
NSQuantumDetails
    [@QuantumId =] quantum_id
Arguments
[@QuantumId =] quantum_id
Is the ID of a quantum for the report. quantum_id is int and has no default value. Use the NSQuantumList, NSQuantumExecutionTime, and NSQuantumFailures stored procedures to obtain quantum IDs.
Return Code Values

None

Result Sets

NSQuantumDetails produces five result sets. The first result set contains general information about the quantum.

Column Name | Data Type | Description
QuantumStartTime | datetime | Quantum starting time in UTC (Universal Time Coordinate or Greenwich mean time).
QuantumEndTime | datetime | Quantum ending time in UTC; the end time is the start time plus the quantum duration.
QuantumStatusDescription | nvarchar(255) | Text that describes the current status of the quantum.
ExecutionTimeInMS | int | Time, in milliseconds, to complete quantum processing.
ExecutionStartTime | datetime | Date and time, in UTC, at which the quantum started processing notifications.
ExecutionEndTime | datetime | Date and time, in UTC, at which the quantum stopped processing notifications.
EventNotificationsGenerated | bigint | During quantum execution, number of notifications generated from event-triggered rules.
ScheduledNotificationsGenerated | bigint | During quantum execution, number of notifications generated from scheduled subscription rules.
ChronicleRuleFiringsSkipped | nvarchar(255) | Indicates whether event chronicle rule firings were skipped due to the chronicle quantum limit for the application.
SubscriptionRuleFiringsSkipped | nvarchar(255) | Indicates whether subscription rule firings were skipped due to the subscription quantum limit for the application.

The second result set contains information about quantum rule firings.

Column Name | Data Type | Description
RuleFiringId | int | Unique ID of a rule that fired during the quantum.
RuleName | nvarchar(255) | Name of the rule, as defined in the application definition file (ADF).
ExecutionTimeInMS | int | Time, in milliseconds, to complete the rule firing.
PercentageQuantumTime | numeric(7, 4) | Percentage of overall quantum execution time used to fire the rule.
ExecutionStartTime | datetime | Starting date and time, in UTC, for the rule firing.
ExecutionEndTime | datetime | Ending date and time, in UTC, for the rule firing.
RuleTypeDescription | nvarchar(250) | Describes the type of rule that was executed; the type is event chronicle, event subscription, or scheduled subscription.
EventClassName | nvarchar(255) | Name of the event class that supplied events for the rule firing. If the rule firing type is scheduled subscription, this column is NULL, because these rules are not event triggered.
EventCount | bigint | Number of events processed by the rule.
EventBatchId | bigint | ID of the event batch containing events for the rule. If the rule firing type is scheduled subscription, or if the application is not set to process events in order, this column is NULL.
SubscriptionClassName | nvarchar(255) | Name of the subscription class that supplied subscriptions for the rule firing. If the rule firing type is event chronicle, this column is NULL.
SubscriptionCount | bigint | Estimated number of subscriptions processed by the rule. The value is estimated based on the current state of the subscriptions in the application database.
StartScanTime | datetime | Starting date and time, in UTC, for the scheduled subscriptions used by the rule. This column contains a value only when the rule type is scheduled subscription and the application processes events in order.
EndScanTime | datetime | Ending date and time, in UTC, for the scheduled subscriptions used by the rule. This column contains a value only when the rule type is scheduled subscription and the application processes events in order.
NotificationsGenerated | int | Number of notifications generated by the rule firing.

The third result set contains information about event batches collected during the quantum.

Column Name | Data Type | Description
EventClassName | nvarchar(255) | Name of an event class that submitted an event batch.
EventBatchId | bigint | ID of the event batch.
EventCount | bigint | Number of events in the event batch.
StartCollectionTime | datetime | Date and time that event batch collection started, in UTC.
EndCollectionTime | datetime | Date and time that event batch collection ended, in UTC.
CollectionTimeInMS | int | Total time, in milliseconds, to collect the batch of events.
ProviderName | nvarchar(255) | Name of the event provider that submitted the batch of events.
SystemName | nvarchar(255) | Name of the system where the event provider is running.

The fourth result set contains information about subscriptions processed during the quantum.

Column Name | Data Type | Description
SubscriptionClassName | nvarchar(255) | Name of a subscription class for which subscriptions were processed during the quantum.
EventSubscriptionCount | bigint | Estimated number of active event-triggered subscriptions for the subscription class during the quantum period.
ScheduledSubscriptionCount | bigint | Estimated number of active scheduled subscriptions for the subscription class during the quantum period.

The fifth report contains information about notifications generated during the quantum.

Column Name | Data Type | Description
NotificationClassName | nvarchar(255) | Name of the notification class that produced the notification batch.
NotificationBatchId | bigint | Unique ID of a notification batch generated by a rule firing within the quantum.
RuleFiringId | int | Unique ID of the rule firing that produced the notification batch.
NotificationCount | int | Number of notifications in the notification batch.
NotificationDeliveryAttempts | int | Number of attempts made to delivery notifications from the notification batch.
NotificationSuccessfulDeliveries | int | Number of successful notification deliveries from the notification batch.
NotificationFailedAttempts | int | Number of failed notification deliveries from the notification batch.
NotificationsDeliveryNotAttempted | int | Number of notifications the distributor has not yet attempted to deliver.
NotificationsNotYetDelivered | int | Number of notifications the distributor has not yet successfully delivered.
NotificationToMessageRatio | float | Ratio of notifications generated to messages sent. For digest or multicast delivery, one message can include multiple notifications. This column indicates how many notifications, on average, are included in digest or multicast messages.
AvgNotificationBatchSucceedDeliveryTime | float | Average time, in seconds, to send the notifications through the distribution process successfully.
Remarks

The NSQuantumDetails stored procedure is created when you run NSControl Create. It is located in application databases.

After obtaining the high-level details of a quantum, you might want to drill down into the specific events, subscriptions, or notifications within a quantum. The following stored procedures provide this information:

  • NSEventBatchDetails
  • NSNotificationBatchDetails
  • NSScheduledSubscriptionDetails
Permissions

Execute permissions default to members of the NSAnalysis and db_owner database roles who have permission to run the Notifications Services extended stored procedures; this permission is granted using the GrantXPExec command. Members of the sysadmin fixed server role have all necessary permissions.

Example

The following example produces the five result sets listed earlier in this section for the first generator quantum of an application:

EXEC NSQuantumDetails 1

See Also

GrantXPExec Utility

Notification Services Performance Reports

Stored Procedure Reference


NSQuantumExecutionTime

Returns information to help you identify long-running generator quanta, which you can then use to analyze the quanta in more detail.

Syntax
NSQuantumExecutionTime
    [@MinExecutionTime =] min_time
    [, [@MaxExecutionTime =] max_time]
    [, [@SinceQuantumInitialized =] since_init]
Arguments
[@MinExecutionTime =] min_time
Specifies the minimum execution time for a quantum to be included in the report. min_time is int, is specified in seconds, and has no default value.

[@MaxExecutionTime =] max_time

Specifies the maximum execution time for a quantum to be included in the report. max_time is int, is specified in seconds, and has a default value of min_time plus 5.

[@SinceQuantumInitialized =] since_init
Specifies whether the report includes quanta prior to the last initialization of the quantum clock. since_init is tinyint and can be either 0 or 1. The default is 1, which includes only quantum periods after the last initialization. 0 includes quantum periods prior to the last initialization.
Return Code Values

None

Result Sets
Column Name | Data Type | Description
QuantumId | int | Unique ID of a quantum. You can supply this ID to the NSQuantumDetails stored procedure to obtain additional information about the quantum.
QuantumStatusDescription | nvarchar(255) | Text that describes the current status of the quantum.
ExecutionTimeInMS | bigint | Number of milliseconds to process the quantum.
QuantumStartTime | datetime | Quantum starting time in UTC (Universal Time Coordinate or Greenwich mean time).
QuantumEndTime | datetime | Quantum ending time in UTC; the end time is the start time plus the quantum duration.
ExecutionStartTime | datetime | Date and time, in UTC, when the quantum started processing notifications.
ExecutionEndTime | datetime | Date and time, in UTC, when the quantum stopped processing notifications.
QuantumDurationLimit | nvarchar(20) | Indicates whether the quantum execution time was greater than the quantum duration defined in the application definition file (ADF).
ChronicleQuantumLimit | nvarchar(20) | Indicates whether the quantum execution time was greater than <ChronicleQuantumLimit>*<QuantumDuration> (defined in the ADF).
SubscriptionQuantumLimit | nvarchar(20) | Indicates whether the quantum execution time was greater than <SubscriptionQuantumLimit>*<QuantumDuration> (defined in the ADF).
ChronicleRuleFiringCount | int | Number of event chronicle rule firings in the quantum.
EventSubscriptionRuleFiringCount | int | Number of event subscription rule firings in the quantum.
ScheduledSubscriptionRuleFiringCount | int | Number of scheduled subscription rule firings in the quantum.
EventNotificationsGenerated | int | During quantum execution, number of notifications generated from event-triggered rules.
ScheduledNotificationsGenerated | int | During quantum execution, number of notifications generated from scheduled subscription rules.
Remarks

The NSQuantumExecutionTime stored procedure is created when you run NSControl Create. It is located in application databases.

Once you have identified a quantum of interest, you might need to do further analysis. To get details about the quantum, use the NSQuantumDetails stored procedure.

Permissions

Execute permissions default to members of the NSAnalysis database role, the db_owner fixed database role, and the sysadmin fixed server role.

Examples

The following example shows how to produce a quantum execution time report for all quanta that took between 0 and 5 seconds to execute since the last initialization:

EXEC NSQuantumExecutionTime 0

This example shows how to produce a quantum execution time report for all generator quanta that ran for longer than 30 seconds but less than 35 seconds:

EXEC NSQuantumExecutionTime 30, NULL, 0

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSQuantumFailures

Returns information about failed generator quanta. A quantum is failed if the quantum could not complete required processing.

Syntax
NSQuantumFailures
Return Code Values

None

Result Sets

The NSQuantumFailures result set is ordered by QuantumId.

Column Name | Data Type | Description
QuantumId | int | Unique ID of a quantum. You can supply this ID to the NSQuantumDetails stored procedure to obtain additional information about the quantum.
QuantumStatusDescription | nvarchar(255) | Text that describes the current status of the quantum.
QuantumStartTime | datetime | Quantum starting time in UTC (Universal Time Coordinate or Greenwich mean time).
QuantumEndTime | datetime | Quantum ending time in UTC; the end time is the start time plus the quantum duration.
ExecutionTimeInMS | int | Number of milliseconds to process the quantum.
ExecutionStartTime | datetime | Date and time, in UTC, at which the quantum started processing notifications.
ExecutionEndTime | datetime | Date and time, in UTC, at which the quantum stopped processing notifications.
Remarks

The NSQuantumFailures stored procedure is created when you run NSControl Create. It is located in application databases.

Permissions

Execute permissions default to members of the NSAnalysis database role, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example shows how to create the failed quantum report for an application:

EXEC NSQuantumFailures

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSQuantumList

Produces the quantum list report for a Notification Services application. The report contains information about quanta processed during a specified time period, and displays the quanta in the order in which they ran.

Syntax
NSQuantumList
    [@StartTime =] 'start_time' ,
    [@EndTime =] 'end_time'
Arguments
[@StartTime =] 'start_time'
Is the starting UTC (Universal Time Coordinate or Greenwich mean time) date and time for the range of generator quanta to be included in the result set. start_time is datetime and has no default value.
[@EndTime =] end_time
Is the ending UTC date and time for the range of generator quanta to be included in the result set. end_time is datetime and has no default value.
Return Code Values

None

Result Sets

The NSQuantumList result set is ordered by QuantumId.

Column Name | Data Type | Description
QuantumId | int | Unique ID of a quantum. You can supply this ID to the NSQuantumDetails stored procedure to obtain additional information about the quantum.
StartTime | datetime | Quantum starting time in UTC (Universal Time Coordinate or Greenwich mean time).
EndTime | datetime | Quantum ending time in UTC; the end time is the start time plus the quantum duration.
SkippedCount | int | Number of skipped quantum periods prior to this quantum.
QuantumStatusDescription | nvarchar(255) | Text that describes the current status of the quantum.
ExecutionTimeInMS | int | Number of milliseconds to process the quantum.
ExecutionStartTime | datetime | Date and time, in UTC, at which the quantum started processing notifications.
ExecutionEndTime | datetime | Date and time, in UTC, at which the quantum stopped processing notifications.
EventNotificationsGenerated | int | During quantum execution, number of notifications generated from event-triggered rules.
ScheduledNotificationsGenerated | int | During quantum execution, number of notifications generated from scheduled subscription rules.
EventChronicleRuleFiringsSkipped | nvarchar(255) | Indicates whether event chronicle rule firings were skipped due to the chronicle quantum limit for the application. Possible values are Yes and No.
SubscriptionRuleFiringsSkipped | nvarchar(255) | Indicates whether subscription rule firings were skipped due to the subscription quantum limit for the application. Possible values are Yes and No.
Remarks

The NSQuantumList stored procedure is created when you run NSControl Create. It is located in application databases.

To determine the current UTC date and time, run SELECT GETUTCDATE() in SQL Query Analyzer. The current UTC time is derived from the current local time and the time zone setting in the operating system of the computer on which SQL Server is running.

Permissions

Execute permissions default to members of the NSAnalysis database role, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example shows all quanta that completed between 2:30 and 3:30 A.M. on May 22, 2002.

EXEC NSQuantumList '2002-05-22 02:30:00', '2002-05-22 03:30:00'

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSQuantumPerformance

Returns information about the execution times for application quanta. The result set divides execution time into intervals, so you can see how many quanta executed within each time period. This can help you troubleshoot long-running quanta.

Syntax
NSQuantumPerformance
    [[@ReportingInterval =] interval]
    [, [@SinceQuantumInitialized =] since_init]
Arguments
[@ReportingInterval =] interval
Is the length of time, in seconds, in each reporting interval. The report contains one row per interval. interval is int and has a default value of 5, which indicates five seconds per interval.
[@SinceQuantumInitialized =] since_init
Specifies whether the report includes quanta prior to the last initialization of the quantum clock. since_init is tinyint, and can be either 0 or 1. The default is 1, which includes only quantum periods after the last initialization. Specifying 0 includes quantum periods prior to the last initialization.
Return Code Values

None

Result Sets
Column Name | Data Type | Description
MinimumExecutionTime | int | Quantum execution time, in seconds, for the lower bound of the reporting interval.
MaximumExecutionTime | int | Quantum execution time, in seconds, for the upper bound of the reporting interval.
CountOfQuantums | int | Count of quantum periods that executed for a length of time greater than or equal to the row's Minimum Execution Time value, but less than the row's Maximum Execution Time value.
QuantumDuration | nvarchar(255) | Indicates whether the time range for this row of the report includes times longer than the quantum duration defined in the application definition file (ADF). Quantum execution that takes longer than the quantum duration causes the generator to fall behind.
ChronicleQuantumLimit | nvarchar(255) | Indicates whether the time range for this row of the report includes times longer than the result of <ChronicleQuantumLimit>*<QuantumDuration> (defined in the ADF). Quantum execution that takes longer than this time can cause chronicle rule firings to be skipped. Possible values are Under, Over, and Maybe over.
SubscriptionQuantum Limit | nvarchar(255) | Indicates whether the time range for this row of the report includes times longer than the result of <SubscriptionQuantumLimit>*<QuantumDuration> (defined in the ADF). Quantum execution that takes longer than this time causes subscription rule firings to be skipped. Possible values are Under, Over, and Maybe over.
Remarks

The NSQuantumPerformance stored procedure is created when you run NSControl Create. It is located in application databases.

The ChronicleQuantumLimit and SubscriptionQuantumLimit values indicate whether the quantum durations of quanta in the reporting interval took less time or more time than that allowed for the application. The values in these columns indicate the following:

  • Over indicates that the MinimumExecutionTime value is greater than the quantum limit; all quanta reported in the row took longer than the quantum limit.
  • Under indicates that the MaximumExecutionTime value is less than the quantum limit; all quanta reported in the row took less time than the quantum limit.
  • Maybe over indicates that the MinimumExecutionTime value is less than or equal to the quantum limit and the MaximumExecutionTime value is greater than or equal to the quantum limit; some quanta might have run longer than the MaximumExecutionTime value.
Permissions

Execute permissions default to members of the NSAnalysis database role, the db_owner fixed database role, and the sysadmin fixed server role.

Example

The following example shows how to produce the quantum performance report using a reporting interval of 5 seconds, and using the default value for @SinceQuantumInitialized. This includes only the quanta processed after the last quantum initialization:

EXEC NSQuantumPerformance

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSQuantumsSkipped

Returns information about skipped quantum processing in the Notification Services application. Quanta can be skipped if the generator falls behind and quantum limits are set in the application definition file (ADF), or if limits are set for chronicle or subscription rule firings.

Syntax
NSQuantumsSkipped
Return Code Values

None

Result Sets

The NSQuantumsSkipped result set is ordered by StartSkippedInterval.

Column Name | Data Type | Description
StartSkippedInterval | datetime | Starting date and time, in UTC (Universal Time Coordinate or Greenwich mean time), of the interval skipped by the generator.
EndSkippedInterval | datetime | Ending date and time, in UTC, of the interval skipped by the generator.
SkippedIntervalInSeconds | int | Number of seconds in the skipped interval.
NumberOfQuantums | int | Number of quantum periods skipped during the interval.
EventChronicleRuleFiringsSkipped | nvarchar(255) | Indicates whether event chronicle rule firings were skipped during the interval. Possible values are Yes and No.
SubscriptionRuleFiringsSkipped | nvarchar(255) | Indicates whether subscription rule firings were skipped during the interval. Possible values are Yes and No.
Remarks

The NSQuantumsSkipped stored procedure is created when you run NSControl Create. It is located in application databases.

Permissions

Execute permissions default to members of the NSAnalysis database role, db_owner fixed database role, and sysadmin fixed server role.

Example

The following example shows how to run the NSQuantumsSkipped stored procedure for an application. The result set includes all skipped quanta since the application started:

EXEC NSQuantumsSkipped

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSScheduledSubscriptionDetails

Returns detailed information about a subscription class in a Notification Services application. To use this stored procedure, the subscription class must have scheduled subscription rules.

Syntax
NSScheduledSubscriptionDetails
    [@SubscriptionClassName =] 'sub_class_name' ,
    [@StartTime =] 'start_time' ,
    [@EndTime =] 'end_time'
Arguments
[@SubscriptionClassName =] 'sub_class_name'
Is the name of a subscription class. sub_class_name is nvarchar(255) and has no default value.
[@StartTime =] start_time
Is the starting UTC (Universal Time Coordinate or Greenwich mean time) date and time for the time period containing the subscriptions of interest. start_time is datetime and has no default value.
[@EndTime =] end_time
Is the ending UTC date and time for the time period containing the subscriptions of interest. end_time is datetime and has no default value. You cannot specify an end_time value greater than 24 hours past the start_time value.
Return Code Values

None

Result Sets

The NSScheduledSubscriptionDetails result set is ordered by ScheduleTime.

Column Name | Data Type | Description
SubscriptionId | bigint | Unique ID of the scheduled subscription.
SubscriberId | nvarchar(255) | Unique ID of the subscriber who owns the subscription.
CreationDate | datetime | Date and time, in UTC, at which the subscription was created.
UpdateDate | datetime | Date and time, in UTC, at which the subscription was last updated.
Enabled | bit | Indicates whether the subscription is currently enabled or disabled. The value 1 indicates that the subscription is enabled.
ScheduleTime | datetime | Date and time, in UTC, at which the subscription is scheduled for processing.
Subscription_Class_Field_Name (1-n) | user-defined | The name of a subscription class field, as defined in the application definition file (ADF). Each field in the subscription class is represented by a column in the result set.
Remarks

The NSScheduledSubscriptionDetails stored procedure is created when you run NSControl Create. It is located in application databases.

To determine the current UTC date and time, run SELECT GETUTCDATE() in SQL Query Analyzer. The current UTC time is derived from the current local time and the time zone setting in the operating system of the computer on which SQL Server is running.

Permissions

Execute permissions default to members of the NSAnalysis and db_owner database roles who have permission to run the Notifications Services extended stored procedures; this permission is granted using the GrantXPExec command. Members of the sysadmin fixed server role have all necessary permissions.

Example

The following example shows how to produce the scheduled subscription report for the WeatherSubscriptions subscription class of the Weather application. The report contains information about subscriptions that are scheduled to run on May 23, 2002, using the UTC time values:

EXEC NSScheduledSubscriptionDetails N'WeatherSubscriptions',
    '2002-05-23 00:00:00', '2002-05-23 23:59:59'

See Also

GrantXPExec Utility

Notification Services Performance Reports

Stored Procedure Reference


NSScheduledSubscriptionList

Produces the scheduled subscription list report for a Notification Services application. The report contains information about all scheduled subscriptions for a given subscriber.

The results handle local time conversion and take into account daylight saving time offset changes with respect to the locale. The results are useful for diagnosing why a subscription did not generate a notification at an expected time. It is common for users to configure subscription information incorrectly, which results in notifications being generated at unexpected times.

Syntax
NSScheduledSubscriptionList
    [@SubscriberId =] 'subscriber_id' ,
    [@StartDate =] 'start_date']
    [, [@EndDate =] 'end_date']
    [, [@Language =] 'language_code']
Arguments
[@SubscriberId =] 'subscriber_id'
Is the unique identifier used to represent a subscriber in the Notification Services instance. subscriber_id is nvarchar(255) and has no default value.
[@StartDate =] 'start_date'
Is the starting UTC (Universal Time Coordinate or Greenwich mean time) date and time for scheduled subscriptions. start_date is datetime and has no default value.
[@EndDate =] 'end_date'
Is the ending UTC date and time for scheduled subscriptions. If not specified (or NULL), the default value is the start_date value plus one day. end_date is datetime.
[@Language =] 'language_code'
Is one of the Notification Services languages, and specifies the language to include in the report. language_code is used to return a subset of time zones from the NSTimeZoneNames table in the instance database. language_code is nvarchar(6) and has a default value of 'en' (English).

For a complete list of language_code values, see the Language column of the instance database NSTimeZoneNames table. The following table contains the list of language_code values for the standard SQL Server 2000 languages.

Language Code | Description
de | German
en | English
es | Spanish
fr | French
it | Italian
ja | Japanese
ko | Korean
zh-CHS | Chinese (Simplified)
zh-CHT | Chinese (Traditional)
Return Code Values

0 (success) or 1 (failure)

Result Sets

The NSScheduledSubscriptionList result set is ordered by SubscriptionClassName value and then by SubscriptionId value.

Column Name | Data Type | Description
SubscriberEnabled | tinyint | Indicates whether the subscriber is currently enabled. A nonzero value indicates that the subscriber is enabled and can generate notifications. Use NSControl Enable to enable subscribers.
SubscriptionClassName | nvarchar(255) | Name of the subscription class containing the scheduled subscription for the subscriber.
SubscriptionId | bigint | ID of a subscription for the subscriber.
SubscriptionEnabled | tinyint | Indicates whether the subscription is enabled. A nonzero value indicates that the subscription is enabled and can generate notifications. Use NSControl Enable to enable subscriptions.
ScheduleText | nvarchar(2048) | User-supplied schedule text for the subscription.
UtcDateTime | datetime | Date and time, in UTC, at which the scheduled subscription is to be processed. If the value is NULL, the subscription has no scheduled time falling within the specified time range.
LocalTimeZone | nvarchar(100) | Name of the local time zone for the subscription.
Observing | nvarchar(100) | Indicates whether the subscription observes daylight saving time. The text string returned is the time zone specific string.
LocalDateTime | datetime | Local date and time for the scheduled subscription. The date and time indicates whether the time zone is in daylight saving time or standard time. If the value is NULL, the subscription has no scheduled time falling within the specified time range.
Remarks

The NSScheduledSubscriptionList stored procedure is created when you run NSControl Create. It is located in application databases.

To determine the current UTC date and time, run SELECT GETUTCDATE() in SQL Query Analyzer. The current UTC time is derived from the current local time and the time zone setting in the operating system of the computer on which SQL Server is running.

Permissions

Execute permissions default to members of the NSAnalysis and db_owner database roles who have permission to run the Notifications Services extended stored procedures; this permission is granted using the GrantXPExec command. Members of the sysadmin fixed server role have all necessary permissions.

Example

The following example shows how to produce a report of all scheduled subscriptions for May 24, 2002 in the Weather application for subscriber "karen":

EXEC NSScheduledSubscriptionList N'karen',
    '2002-05-24', '2002-05-24 23:59:59'

See Also

GrantXPExec Utility

Notification Services Performance Reports

Stored Procedure Reference


NSSetQuantumClock

Resets the Notification Services application quantum clock to the starting time of a previous quantum. A new quantum is created with the same UTC (Universal Time Coordinate or Greenwich mean time) start time as the quantum specified in the stored procedure. This allows you to replay past quanta.

The following two scenarios show how you can use this stored procedure:

  • When testing an application, you can add one scheduled subscription, and then test that subscription by resetting the quantum clock as needed.
  • When diagnosing system problems, you can reset the quantum clock and reproduce past system behavior. All processing, such as event batches and timed subscriptions, is replayed exactly as in real time, as long as the NS$instance_name service is running and the instance is enabled.
Syntax
NSSetQuantumClock
    [@QuantumId =] quantum_ID
Arguments
[@QuantumId =] quantum_ID
Is the unique identifier of a past quantum. quantum_id is bigint and has no default value.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

The NSSetQuantumClock stored procedure is created when you run NSControl Create. It is located in application databases.

You must disable the generator before running NSSetQuantumClock. When you view the status using NSControl Status, the generator status must be either disabled or disabled pending.

In the application definition file (ADF), ensure that the ChronicleQuantumLimit and SubscriptionQuantumLimit values are zero, which means there is no limit to how far back you can process quanta. If nonzero limits are specified, the generator might skip the quantum of interest.

Vacuumer processing removes data from the system. If you have removed data of interest, that processing of that data cannot be replayed.

When Notification Services tries to catch up on prior quanta, the older quanta take precedence and are processed first. When you initialize the quantum clock, be aware that new quanta might be processed later than scheduled.

Permissions

Execute permissions default to members of the NSGenerator and NSRunService database roles, db_owner fixed database role, and sysadmin fixed server role.

Example

The following example shows how to reset the quantum clock to replay starting at quantum number 1. A new quantum is entered into the NSQuantum1 table with a new quantum number, but a with StartTime value equal to the StartTime value of quantum 1:

EXEC NSSetQuantumClock 1

For example, if four quanta currently exist in the NSQuantum1 table, and quantum 1 started at 2002-05-23 17:23:37.640, when you run this example, quantum 5 is entered with a start time of 2002-05-23 17:23:37.640. When you enable the generator, the generator replays all quanta starting at quantum 1.

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSSetQuantumClockDate

Resets the Notification Services application quantum clock to a specific time, which is useful for continually running an application over the same time interval for testing purposes by setting an exact time, such as 9:00 Monday morning.

The following two scenarios show how you can use this stored procedure:

  • When testing an application, you can add one scheduled subscription, and then test that subscription by resetting the quantum clock as needed.
  • When diagnosing system problems, you can reset the quantum clock and reproduce past system behavior. All processing, such as event batches and timed subscriptions, is replayed exactly as in real time, as long as the service is running and the instance is enabled.
Syntax
NSSetQuantumClockDate
    [@QuantumStartTime =] 'start_date_time'
Arguments
[@QuantumStartTime =] 'start_date_time'
Is a previous starting datetime value, in UTC (Universal Time Coordinate or Greenwich mean time), for the quantum clock. This forces the generator to start a new quantum at a past time, replaying previous processing. Because the time is in the past, the generator processes the quantum as soon as possible.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

The NSSetQuantumClockDate stored procedure is created when you run NSControl Create. It is located in application databases.

You must disable the generator before running NSSetQuantumClockDate. The generator status must be either disabled or disabled pending.

NSSetQuantumClockDate initializes the quantum clock, so the @QuantumStartTime value is included within the first quantum processed by the generator after running the procedure.

To find a quantum start time, use the NSQuantumList stored procedure. The result set shows start-time and end-time values for each quantum in UTC.

In the application definition file (ADF), ensure that the <ChronicleQuantumLimit> and <SubscriptionQuantumLimit> values are zero, which means there is no limit to how far back you can process quanta. If nonzero limits are specified, the generator might skip the quantum of interest.

Vacuumer processing removes data from the system. If you have removed data of interest, the processing of that data cannot be replayed.

When Notification Services tries to catch up on prior quanta, the older quanta take precedence and are processed first. When you initialize the quantum clock, be aware that new quanta might be processed later than scheduled.

Permissions

Execute permissions default to members of the NSGenerator and NSRunService database roles, db_owner fixed database role, and sysadmin fixed server role.

Example

The following example shows how to reset the quantum clock to replay what occurred on April 23, 2000 at 9:00 A.M. Pacific daylight time. The equivalent UTC time is 17:00, and the EndTime column in the NSQuantum1 table shows the previous quantum ended at 16:59:

EXEC NSSetQuantumClockDate '2002-04-23 16:59'

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSSnapshotApplications

Produces the applications snapshot report, which provides information about the current state of all applications hosted by an instance.

Syntax
NSSnapshotApplications
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column Name | Data Type | Description
ApplicationName | nvarchar(255) | Name of an application.
ApplicationActivationState | nvarchar(255) | Activation state for the application. The state can be enabled or disabled.
GeneratorActivationState | nvarchar(255) | Activation state for the application generator component. The state can be enabled, enabled pending, disabled, or disabled pending.
QuantumsBehind | int | Number of quantum durations the generator is running behind. The count includes complete quantum durations that have passed, but have not yet been started for processing. For example, if the quantum duration is 5 seconds and the QuantumsBehind value is 2, at least 10 seconds but not more than 15 seconds have passed since the last quantum was processed.
GeneratorSystemName | nvarchar(255) | Name of computer system running the generator service.
NotificationClassName | nvarchar(255) | Name of a notification class within the application.
LastTimeNotificationBatchGenerated | datetime | Date and time of the last notification batch to be generated for the notification class.
SecondsSinceNotificationBatchGenerated | int | Elapsed time, in seconds, since the last notification batch was generated.
LastNotificationBatchNotificationCount | bigint | The number of notifications generated in the last batch for the notification class.
LastTimeNotificationBatchDistributed | datetime | Date and time the last notification batch was picked up for distribution.
SecondsSinceNotificationBatchDistributed | int | Elapsed time, in seconds, since a notification batch has been picked up for distribution.
VacuumerSystemName | nvarchar(255) | Name of the computer system running the vacuuming service.
LastTimeVacuumingOccurred | datetime | Date and time of the last successful vacuuming of notifications and events.
SecondsSinceLastVacuum | int | Elapsed time, in seconds, since the vacuumer has run.
LastTimeVacuumEventCount | bigint | Number of events vacuumed in the last vacuuming.
LastTimeVacuumNotificationCount | bigint | Number of notifications vacuumed in the last vacuuming.
SubscriberActivationState | nvarchar(255) | Activation state for the subscriber APIs. The state can be enabled or disabled.
LastTimeSubscriberAdded | datetime | Date and time the newest subscriber was added to the instance.
SecondsSinceSubscriberAdded | int | Elapsed time, in seconds, since the newest subscriber was added to the instance.
Remarks

The NSSnapshotApplications stored procedure is created when you run NSControl Create and is located in instance databases.

The result set is ordered by the ApplicationName value and then by the NotificationClassName value.

Permissions

Execute permissions default to members of the NSAnalysis database role, db_owner fixed database role, and sysadmin fixed server role.

Example

The following example produces the application snapshot report for all applications hosted by an instance:

EXEC NSSnapshotApplications

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSSnapshotDeliveryChannels

Produces the delivery channels report, which provides information about the current state of the delivery channels configured across a Notification Services instance.

Syntax
NSSnapshotDeliveryChannels
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column Name | Data Type | Description
ApplicationName | nvarchar(255) | Name of an application.
ApplicationActivationState | nvarchar(255) | Activation state for the application. The state can be enabled or disabled.
DistributorName | nvarchar(255) | Name of a distributor used by the application.
DistributorActivationState | nvarchar(255) | Activation state for the distributor in the application. The state can be enabled, enabled pending, disabled, or disabled pending.
SystemName | nvarchar(255) | Name of the computer system where the distributor is running.
DeliveryChannelName | nvarchar(255) | Name of a delivery channel used by the application.
LastNotificationClassDelivered | nvarchar(255) | Name of the notification class that last had notifications delivered.
LastTimeProcessedWorkItem | datetime | Date and time the last work item was processed by the delivery channel.
SecondsSinceWorkItemProcessed | int | Elapsed time, in seconds, since the last work item was processed.
AttemptedNotificationsSent | bigint | Number of notifications the delivery channel attempted to send.
SuccessfullySentNotifications | bigint | Number of notifications the delivery channel successfully sent.
FailedSendNotificationAttempts | bigint | Number of notifications the delivery channel attempted to send, but which ended as failed.
NotificationToMessageRatio | float | Ratio of notifications generated for the delivery channel to messages sent by the delivery channel. For digest or multicast delivery, one message can include multiple notifications. This column indicates how many notifications are sent, on average, in a digest or multicast message.
Remarks

The NSSnapshotDeliveryChannels stored procedure is created when you run NSControl Create. It is located in instance databases.

The result set is ordered by the ApplicationName value, then by the DeliveryChannelName value, and then by the DistributorName value.

Permissions

Execute permissions default to members of the NSAnalysis database role, db_owner fixed database role, and sysadmin fixed server role.

Example

The following example produces the delivery channels snapshot report for all applications hosted by an instance:

EXEC NSSnapshotDeliveryChannels

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSSnapshotEvents

Produces the events snapshot report for a Notification Services instance. You can use this report to determine how long it has been since an event class has received events from an event provider.

Syntax
NSSnapshotEvents
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column Name | Data Type | Description
ApplicationName | nvarchar(255) | Name of an application.
ApplicationActivationState | nvarchar(255) | Activation state for the application. The state can be enabled or disabled.
EventActivationState | nvarchar(255) | Activation state for events in the application. This value indicates whether events can be submitted programmatically, which is different from an event provider activation state. The state can be enabled or disabled.
EventClassName | nvarchar(255) | Name of an event class within the application.
LastTimeEventBatchCollected | datetime | Date and time at which the last event batch was collected for the event class.
SecondsSinceEventBatchCollected | int | Elapsed time, in seconds, since the last event class was collected for the event class.
LastEventBatchEventCount | bigint | Number of events collected in the last event batch for the event class.
LastEventBatchProvider | nvarchar(255) | Name of the event provider that submitted the last event batch for the event class.
Remarks

The NSSnapshotEvents stored procedure is created when you run NSControl Create. It is located in instance databases.

The result set is ordered by the ApplicationName value and then by the EventClassName value.

Permissions

Execute permissions default to members of the NSAnalysis database role, db_owner fixed database role, and sysadmin fixed server role.

Example

The following example produces the events snapshot report for all applications hosted by an instance:

EXEC NSSnapshotEvents

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSSnapshotProviders

Produces the event providers snapshot report for a Notification Services instance. The report contains information about each event provider configured for an instance.

Syntax
NSSnapshotProviders
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column Name | Data Type | Description
ApplicationName | nvarchar(255) | Name of an application.
ApplicationActivationState | nvarchar(255) | Activation state of the application. The state can be enabled or disabled.
ProviderName | nvarchar(255) | Name of an event provider used by the application.
ProviderActivationState | nvarchar(255) | Activation state of the event provider. The state can be enabled, enabled pending, disabled, or disabled pending.
SystemName | nvarchar(255) | Name of computer system where the event provider is running.
LastEventClassCollected | nvarchar(255) | Name of the event class that collected the last event batch for the event provider.
LastTimeEventBatchCollected | datetime | Date and time at which the last event batch was collected by the event provider.
SecondsSinceEventBatchCollected | int | Elapsed time, in seconds, since the last event batch was collected for the event provider.
NumberOfEventsInLastEventBatch | bigint | Number of events collected in the last event batch.
Remarks

The NSSnapshotProviders stored procedure is created when you run NSControl Create. It is located in instance databases.

The result set is ordered by the ApplicationName value and then by the ProviderName value.

Permissions

Execute permissions default to members of the NSAnalysis database role, db_owner fixed database role, and sysadmin fixed server role.

Example

The following example produces the providers snapshot report for all applications hosted by an instance:

EXEC NSSnapshotProviders

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSSnapshotSubscriptions

Produces the subscriptions snapshot report for a Notification Services instance. The report contains information about the most recent subscription addition for all subscription classes.

Syntax
NSSnapshotSubscriptions
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column Name | Data Type | Description
ApplicationName | nvarchar(255) | Name of an application.
ApplicationActivationState | nvarchar(255) | Activation state of the application. The state can be enabled or disabled.
SubscriptionActivationState | nvarchar(255) | Activation state of the subscription APIs for the application. The state can be enabled or disabled.
SubscriptionClassName | nvarchar(255) | Name of a subscription class within the application.
LastTimeSubscriptionAdded | datetime | Date and time of the last subscription added to the application for the subscription class.
SecondsSinceSubscriptionAdded | int | Elapsed time, in seconds, since the last subscription was added for the subscription class.
Remarks

The NSSnapshotSubscriptions stored procedure is created when you run NSControl Create. It is located in instance databases.

The result set is ordered by the ApplicationName value and then by the SubscriptionClassName value.

Permissions

Execute permissions default to members of the NSAnalysis database role, db_owner fixed database role, and sysadmin fixed server role.

Example

The following example produces the subscriptions snapshot report for all applications hosted by an instance:

EXEC NSSnapshotSubscriptions

See Also

Notification Services Performance Reports

Stored Procedure Reference


NSVacuum

Manually runs the vacuuming process, removing obsolete data from the application database. If the current vacuuming schedule as defined in the application definition file (ADF) is not adequate, it is best to modify the schedule and update the application. Running vacuuming manually is recommended only when absolutely necessary (for example, if the database is running out of disk space).

Important Do not run the vacuumer manually when the vacuumer is running or is scheduled to run. Application errors might occur, resulting in no data being removed.

Syntax
NSVacuum
    [@SecondsToRun =] max_vacuuming_time
Arguments
[@SecondsToRun =] max_vacuuming_time
Is the maximum number of seconds the vacuumer stored procedure can run. If the vacuumer removes all data before this time, vacuuming stops at that point. If the vacuumer is not finished within this time, the vacuumer stops without removing all obsolete data. The next time this stored procedure runs, vacuuming will resume at the point where it previously stopped. max_vacuuming_time is int and has no default value.
Result Set
Column Name | Data Type | Description
Status | int | The current status of vacuuming. Possible values are 0 (running), 2 (completed), and 3 (time limit exceeded). You will not receive the value 0 when running vacuuming manually.
QuantumsVacuumed | int | Number of quanta successfully removed from the database during the current vacuuming period.
QuantumsRemaining | int | Number of quanta that could have been removed, but were not removed because the time limit was exceeded.
Remarks

The NSVacuum stored procedure is created when you run NSControl Create. It is located in application databases.

Use the NSSnapshotApplications stored procedure or the NS$instance_name: Vacuumer performance object to monitor vacuuming.

Permissions

Execute permissions default to members of the NSRunService and NSVacuum database roles, db_owner fixed database role, and sysadmin fixed server role.

Example
The following example runs the vacuumer for five minutes:
EXEC NSVacuum 300

See Also

NS$instance_name: Vacuumer Object

NSSnapshotApplications

Removing Obsolete Data

<Vacuum> Node


Table and View Reference

The Table and View Reference section provides information on the SQL Server tables used by Notification Services. It also provides details on the standard views offered by Notification Services for working with the information in these tables.

The topics that this section covers are described in the following table.

Topic | Description
Notification Services Tables | Discusses how Notification Services uses SQL Server tables.
Notification Services Views | Provides details on the standard Notification Services views.

See Also

Stored Procedure Reference


Notification Services Tables

Notification Services instance and application databases contain many tables. These tables hold the following types of data:

  • Metadata, which is the data from the configuration file and the application definition file (ADF), normalized and stored in tables.
  • Application data, such as events, subscriptions, and notifications.
  • Runtime data, such as event batches and notification batches.
  • Transient data generated by Notification Services when processing information.

Do not access these tables directly. The table names and definitions can change for several reasons. In the application databases, temporary tables frequently get created and deleted as necessary. Other table names and definitions might change based on application changes. Finally, tables are likely to be changed in future versions of Notification Services.

Instead, use the stored procedures and views provided with Notification Services to look at the data in the various tables. The stored procedures and views are more efficient to use, because they combine data from different tables to show a consolidated view or report for a specific purpose.

For more information about the Notification Services reporting stored procedures, see Stored Procedure Reference. For more information about the Notification Services views, see Notification Services Views.


Notification Services Views

SQL Server views provide a consolidated look at a set of data. Notification Services offers a number of standard views that you can use to work with the data in the Notification Services tables. Microsoft strongly recommends that you use the views instead of working with the tables directly, because tables can change between applications and between Notification Services versions.

The topics that this section covers are described in the following table.

Topic | Description
NSFullTimeZones View | Describes the NSFullTimeZones view, which provides a list of the Notification Services time zones.
NSSubscriberDeviceView View | Describes the NSSubscriberDeviceView view, which shows subscriber and subscriber device information for the instance.
NSSubscriptionClassNameView View | Describes the NS SubscriptionClassName View view, which shows all subscriptions for the associated subscription class.

Additional views might appear in the instance and application databases. These views are used by Notification Services and should not be used for other purposes.

See Also

Stored Procedure Reference


NSFullTimeZones View

Provides a view of the time zone codes shipped with Notification Services. It returns one row for each time zone, in each of the nine languages in which Notification Services is shipped: Chinese (simplified), Chinese (traditional), English, French, German, Italian, Japanese, Korean, and Spanish. For example, running a query to select all records for "Greenland Time" returns nine rows, each containing the Greenland time zone information in one of the specified languages.

The information about time zones that the NSFullTimeZones view contains is shown in the following table.

Column | Data type
TimeZoneId | smallint
TimeZoneName | nchar(35)
UtcOffset | int
Language | nvarchar(6)
LocationName | nvarchar(100)
DisplayName | nvarchar(100)
DaylightName | nvarchar(100)
StandardName | nvarchar(100)
Remarks

The NSFullTimeZones view is located in the instance database.

Permissions

This view is available to members of the sysadmin and db_owner server roles.

See Also

Notification Services Views


NSSubscriberDeviceView View

Provides a view of subscriber and subscriber device information for all subscribers in the Notification Services instance.

The information about subscriber devices that the NSSubscriberDeviceView view contains is shown in the following table.

Column | Data type
SubscriberId | nvarchar(255)
Enabled | bit
Created | datetime
Updated | datetime
DeviceName | nvarchar(255)
DeviceTypeName | nvarchar(255)
DeviceAddress | nvarchar(255)
DeliveryChannelName | nvarchar(255)
Remarks

The NSSubscriberDeviceView view is located in the instance database.

Permissions

This view is available to members of the sysadmin and db_owner server roles. It is also available to the NSAnalysis, NSDistributor, NSEventProvider, NSGenerator, NSReader, NSRunService, NSSubscriberAdmin, and NSVacuum Notification Services roles.

See Also

Notification Services Views


NSSubscriptionClassNameView View

Provides a view of the subscription records for the associated subscription class. Notification Services creates one view for each subscription class, using the following naming convention: NSSubscriptionClassNameView.

For example, the Stock sample that ships with Notification Services has two subscription classes: StockSubscriptions and PortfolioSubscriptions. The associated views are named NSStockSubscriptionsView and NSPortfolioSubscriptionsView.

The information about each subscription that the NSSubscriptionClassNameView view contains is shown in the following table.

Column | Data type
SubscriberId | nvarchar(255)
Created | datetime
Updated | datetime
Enabled | nvarchar(8)
Schedule (scheduled subscriptions only) | nvarchar(2048)
Subscription_class_field_name (1-n) | user-defined
Remarks

The NSSubscriptionClassNameView views are located in application databases.

Permissions

This view is available to members of the sysadmin and db_owner server roles, and to the NSAnalysis Notification Services role.

Example

The following query selects the full set of columns from the NSStockSubscriptionsView view:

SELECT SubscriberId, Created, Updated, Enabled, DeviceName, SubscriberLocale, StockSymbol, StockTriggerValue
FROM NSStockSubscriptionsView
ORDER BY SubscriberId

See Also

Notification Services Views


Notification Services Code Reference

The Notification Services Code Reference section contains information on the standard codes and values that are used by Notification Services.

The topics that this section covers are described in the following table.

Topic | Description
Subscriber Locale Codes | Describes the subscriber locale codes for Notification Services.
Time Zone Codes | Describes the time zone codes for Notification Services.


Subscriber Locale Codes

The subscriber locale codes in the following table ship with Notification Services.

Subscriber Locale | LanguageCountryRegion
af | Afrikaans
af-ZA | Afrikaans - South Africa
ar | Arabic
ar-AE | Arabic - United Arab Emirates
ar-BH | Arabic - Bahrain
ar-DZ | Arabic - Algeria
ar-EG | Arabic - Egypt
ar-IQ | Arabic - Iraq
ar-JO | Arabic - Jordan
ar-KW | Arabic - Kuwait
ar-LB | Arabic - Lebanon
ar-LY | Arabic - Libya
ar-MA | Arabic - Morocco
ar-OM | Arabic - Oman
ar-QA | Arabic - Qatar
ar-SA | Arabic - Saudi Arabia
ar-SY | Arabic - Syria
ar-TN | Arabic - Tunisia
ar-YE | Arabic - Yemen
az | Azeri
az-AZ-Cyrl | Azeri (Cyrillic) - Azerbaijan
az-AZ-Latn | Azeri (Latin) - Azerbaijan
be | Belarusian
be-BY | Belarusian - Belarus
bg | Bulgarian
bg-BG | Bulgarian - Bulgaria
ca | Catalan
ca-ES | Catalan - Catalan
cs | Czech
cs-CZ | Czech - Czech Republic
da | Danish
da-DK | Danish - Denmark
de | German
de-AT | German - Austria
de-CH | German - Switzerland
de-DE | German - Germany
de-LI | German - Liechtenstein
de-LU | German - Luxembourg
div | Dhivehi
div-MV | Dhivehi - Maldives
el | Greek
el-GR | Greek - Greece
en | English
en-AU | English - Australia
en-BZ | English - Belize
en-CA | English - Canada
en-CB | English - Caribbean
en-GB | English - United Kingdom
en-IE | English - Ireland
en-JM | English - Jamaica
en-NZ | English - New Zealand
en-PH | English - Philippines
en-TT | English - Trinidad and Tobago
en-US | English - United States
en-ZA | English - South Africa
en-ZW | English - Zimbabwe
es | Spanish
es-AR | Spanish - Argentina
es-BO | Spanish - Bolivia
es-CL | Spanish - Chile
es-CO | Spanish - Colombia
es-CR | Spanish - Costa Rica
es-DO | Spanish - Dominican Republic
es-EC | Spanish - Ecuador
es-ES | Spanish - Spain
es-GT | Spanish - Guatemala
es-HN | Spanish - Honduras
es-MX | Spanish - Mexico
es-NI | Spanish - Nicaragua
es-PA | Spanish - Panama
es-PE | Spanish - Peru
es-PR | Spanish - Puerto Rico
es-PY | Spanish - Paraguay
es-SV | Spanish - El Salvador
es-UY | Spanish - Uruguay
es-VE | Spanish - Venezuela
et | Estonian
et-EE | Estonian - Estonia
eu | Basque
eu-ES | Basque - Basque
fa | Farsi
fa-IR | Farsi - Iran
fi | Finnish
fi-FI | Finnish - Finland
fo | Faroese
fo-FO | Faroese - Faroe Islands
fr | French
fr-BE | French - Belgium
fr-CA | French - Canada
fr-CH | French - Switzerland
fr-FR | French - France
fr-LU | French - Luxembourg
fr-MC | French - Monaco
gl | Galician
gl-ES | Galician - Galician
gu | Gujarati
gu-IN | Gujarati - India
he | Hebrew
he-IL | Hebrew - Israel
hi | Hindi
hi-IN | Hindi - India
hr | Croatian
hr-HR | Croatian - Croatia
hu | Hungarian
hu-HU | Hungarian - Hungary
hy | Armenian
hy-AM | Armenian - Armenia
id | Indonesian
id-ID | Indonesian - Indonesia
is | Icelandic
is-IS | Icelandic - Iceland
it | Italian
it-CH | Italian - Switzerland
it-IT | Italian - Italy
ja | Japanese
ja-JP | Japanese - Japan
ka | Georgian
ka-GE | Georgian - Georgia
kk | Kazakh
kk-KZ | Kazakh - Kazakhstan
kn | Kannada
kn-IN | Kannada - India
ko | Korean
kok | Konkani
kok-IN | Konkani - India
ko-KR | Korean - Korea
ky | Kyrgyz
ky-KZ | Kyrgyz - Kazakhstan
lt | Lithuanian
lt-LT | Lithuanian - Lithuania
lv | Latvian
lv-LV | Latvian - Latvia
mk | Macedonian
mk-MK | Macedonian - FYROM
mn | Mongolian
mn-MN | Mongolian - Mongolia
mr | Marathi
mr-IN | Marathi - India
ms | Malay
ms-BN | Malay - Brunei
ms-MY | Malay - Malaysia
nb-NO | Norwegian (Bokml) - Norway
nl | Dutch
nl-BE | Dutch - Belgium
nl-NL | Dutch - The Netherlands
nn-NO | Norwegian (Nynorsk) - Norway
no | Norwegian
pa | Punjabi
pa-IN | Punjabi - India
pl | Polish
pl-PL | Polish - Poland
pt | Portuguese
pt-BR | Portuguese - Brazil
pt-PT | Portuguese - Portugal
ro | Romanian
ro-RO | Romanian - Romania
ru | Russian
ru-RU | Russian - Russia
sa | Sanskrit
sa-IN | Sanskrit - India
sk | Slovak
sk-SK | Slovak - Slovakia
sl | Slovenian
sl-SI | Slovenian - Slovenia
sq | Albanian
sq-AL | Albanian - Albania
sr-SP-Cyrl | Serbian (Cyrillic) - Serbia
sr-SP-Latn | Serbian (Latin) - Serbia
sv | Swedish
sv-FI | Swedish - Finland
sv-SE | Swedish - Sweden
sw | Swahili
sw-KE | Swahili - Kenya
syr | Syriac
syr-SY | Syriac - Syria
ta | Tamil
ta-IN | Tamil - India
te | Telugu
te-IN | Telugu - India
th | Thai
th-TH | Thai - Thailand
tr | Turkish
tr-TR | Turkish - Turkey
tt | Tatar
tt-RU | Tatar - Russia
uk | Ukrainian
uk-UA | Ukrainian - Ukraine
ur | Urdu
ur-PK | Urdu - Pakistan
uz | Uzbek
uz-UZ-Cyrl | Uzbek (Cyrillic) - Uzbekistan
uz-UZ-Latn | Uzbek (Latin) - Uzbekistan
vi | Vietnamese
vi-VN | Vietnamese - Vietnam
zh-CHS | Chinese (Simplified)
zh-CHT | Chinese (Traditional)
zh-CN | Chinese - People's Republic of China
zh-HK | Chinese - Hong Kong SAR
zh-MO | Chinese - Macau SAR
zh-SG | Chinese - Singapore
zh-TW | Chinese - Taiwan

These values are stored in the NSSubscriberLocales table in the InstanceNameNSMain database for each Notification Services instance.


Time Zone Codes

The time zone codes in the following table ship with Notification Services.

Time Zone ID | Time Zone Name | UTC Offset
0 | Dateline Time | -12960000
1 | Samoa Time | -11880000
2 | Hawaiian Time | -10800000
3 | Alaskan Time | -9720000
4 | Pacific Time | -8640000
10 | Mountain Time | -7560000
15 | US Mountain Time | -7560000
20 | Central Time | -6480000
25 | Canada Central Time | -6480000
30 | Mexico Time | -6480000
33 | Central America Time | -6480000
35 | Eastern Time | -5400000
40 | US Eastern Time | -5400000
45 | SA Pacific Time | -5400000
50 | Atlantic Time | -4320000
55 | SA Western Time | -4320000
56 | Pacific SA Time | -4320000
60 | Newfoundland Time | -3780000
65 | E. South America Time | -3240000
70 | SA Eastern Time | -3240000
73 | Greenland Time | -3240000
75 | Mid-Atlantic Time | -2160000
80 | Azores Time | -1080000
83 | Cape Verde Time | -1080000
85 | GMT Time | 0
90 | Greenwich Time | 0
95 | Central Europe Time | 1080000
100 | Central European Time | 1080000
105 | Romance Time | 1080000
110 | W. Europe Time | 1080000
113 | W. Central Africa Time | 1080000
115 | E. Europe Time | 2160000
120 | Egypt Time | 2160000
125 | FLE Time | 2160000
130 | GTB Time | 2160000
135 | Jerusalem Time | 2160000
140 | South Africa Time | 2160000
145 | Russian Time | 3240000
150 | Arab Time | 3240000
155 | E. Africa Time | 3240000
158 | Arabic Time | 3240000
160 | Iran Time | 3780000
165 | Arabian Time | 4320000
170 | Caucasus Time | 4320000
175 | Afghanistan Time | 4860000
180 | Ekaterinburg Time | 5400000
185 | West Asia Time | 5400000
190 | India Time | 5940000
193 | Nepal Time | 6210000
195 | Central Asia Time | 6480000
200 | Sri Lanka Time | 6480000
201 | N. Central Asia Time | 6480000
203 | Myanmar Time | 7020000
205 | SE Asia Time | 7560000
207 | North Asia Time | 7560000
210 | China Time | 8640000
215 | Malay Peninsula Time | 8640000
220 | Taipei Time | 8640000
225 | W. Australia Time | 8640000
227 | North Asia East Time | 8640000
230 | Korea Time | 9720000
235 | Tokyo Time | 9720000
240 | Yakutsk Time | 9720000
245 | AUS Central Time | 10260000
250 | Cen. Australia Time | 10260000
255 | AUS Eastern Time | 10800000
260 | E. Australia Time | 10800000
265 | Tasmania Time | 10800000
270 | Vladivostok Time | 10800000
275 | West Pacific Time | 10800000
280 | Central Pacific Time | 11880000
285 | Fiji Islands Time | 12960000
290 | New Zealand Time | 12960000
300 | Tonga Time | 14040000
360 | Coordinated Universal Time (UTC) | 0

These values are stored in the NSTimeZones table in the NSMain database for each Notification Services instance. Additionally, related time zone information, such as location and standard names, is in the NSTimeZoneNames table.


Tools and Utilities Reference

Microsoft® SQL Server™ Notification Services has a set of tools that allow developers and administrators to install Notification Services, build applications, and administer and configure instances and applications.

The topics that this section covers are described in the following table.

Topic | Description
CopySample Utility | Copies one of the Microsoft Visual Studio® .NET programming sample solutions to a new solution.
GrantXPExec Utility | Grants permissions to execute the extended stored procedures in the Notification Services databases.
InstallXPs Utility | Adds the database components to an instance of SQL Server.
NSControl Commands | Contains reference topics for the NSControl command prompt utilities.
RemoveSamplesDB Utility | Removes the databases used by the Notification Services programming samples.
RevokeXPExec Utility | Revokes permissions to execute the extended stored procedures in the Notification Services databases.
SetupSample Utility | Configures a single Notification Services sample application after it has been copied.
SetupSamples Utility | Configures all the Notification Services programming sample applications.
UninstallXPs Utility | Removes the database components from an instance of SQL Server.

See Also

Application Definition File Reference

Configuration File Reference

Notification Services Object Model Reference

Stored Procedures


CopySample Utility

Creates a copy of an existing programming sample application in a new sample directory so that it can be used as a template when developing a new application. Developers can use the new sample to create a new Notification Services instance.

Syntax
copysample
   source_sample_name
   destination_sample_name
Arguments
source_sample_name
Is the name of the directory that contains the sample application you want to copy.
destination_sample_name
Is the name for the new application and directory that is created within the Samples directory.
Permissions

Anyone with the execute permission in the Samples directory can run the CopySample utility.

Remarks

The Notification Services programming samples are packaged as Microsoft Visual Studio .NET solutions. If you simply copy and paste the solution files from the existing samples, the solution does not get loaded correctly.

The CopySample command prompt utility copies the programming sample and makes the necessary changes to the sample files. It copies an existing sample directory structure, creates the necessary virtual roots and Internet Information Services (IIS) applications associated with the new sample, and modifies the Microsoft ASP.NET-based projects so that they can be loaded correctly by Visual Studio .NET.

Note You must run CopySample from the Samples directory.

After running CopySample.cmd, you must modify the new application's SetProjectVars.cmd script and then run the SetupSample.cmd script in order to set up the new application. These scripts are automatically placed in the new application directory.

CopySample.cmd replaces all instances of the old sample name with the new name. If the old sample name is a common phrase, such as "notification" or "application," then instances of that phrase might be incorrectly changed.

The replacement takes place on only the files common to all samples. If the source sample has any custom files, then those must be updated manually.

Always double-check your destination sample before attempting to create the new instance.

If the value for an argument contains spaces, enclose the value in quotation marks.

Example

The following example shows how to create a new directory of files for an application called MyStockApp, which is based on the Stock programming sample application:

copysample Stock MyStockApp

See Also

SetupSample Utility


GrantXPExec Utility

Grants permissions to run the Notification Services extended stored procedures. The account used by the NS$instance_name service must have permission to run the extended stored procedures.

Syntax
GrantXPExec
   userName
   [osqlArgs]
Arguments
userName
Is the name of the account to which you are granting permissions. The account name is either a Microsoft Windows domain account or local account or a SQL Server login account. The account must have a login account in the SQL Server instance and a user account in the master database. If the userName value contains spaces, enclose the argument in quotation marks.
osqlArgs
Is one or more arguments to pass to the osql utility. For example, if you must use SQL Server Authentication to connect to SQL Server, specify use a SQL Server user name and password using the -U and -P arguments of the osql utility. By default, GrantXPExec passes -E to osql, instructing osql to use a trusted connection to SQL Server. If you pass any other arguments, such as -S, the default -E argument is not passed by GrantXPExec.

For information about the osql utility, see "osql Utility" in SQL Server Books Online.

Permissions

To run the GrantXPExec utility, you must be a member of the sysadmin role on the SQL Server instance where you are granting permissions.

Remarks

If the userName account does not have access to the master database, provide access as follows:

USE master
EXEC sp_grantdbaccess 'domain\user'

The user name in the master database must match the userName value. If it does not match, GrantXPExec fails. Check the user name in the master database.

When you use GrantXPExec with the sample applications, the argument values are provided by environment variables you set with the SetupSamples utility; do not specify the argument values in this case.

Examples

The following examples illustrate how to use GrantXPExec under various circumstances.

Granting extended stored procedure permissions to a domain account using Windows Authentication

This example grants execute permissions to the domain/user_name account using Windows Authentication to connect to SQL Server:

GrantXpExec.cmd "domain\user_name"

Granting extended stored procedure permissions to a domain account on a named instance of SQL Server using Windows Authentication

This example grants execute permissions to the domain/user_name account using Windows Authentication to connect to a named instance of SQL Server:

GrantXpExec.cmd "domain\user_name" -E -S computer\sql_instance

Granting extended stored procedure permissions to a SQL Server login account using Windows Authentication

This example grants execute permissions to the NSService SQL Server login account using Windows Authentication to connect to SQL Server:

GrantXpExec.cmd "NSService"

Granting extended stored procedure permissions to a SQL Server login account using SQL Server Authentication

This example grants execute permissions to the NSService SQL Server login account using SQL Server Authentication to connect to SQL Server:

GrantXpExec "NSService" -U dba_user_name -P dba_password

Granting extended stored procedure permissions to a SQL Server login account on a named instance of SQL Server using SQL Server Authentication

This example grants execute permissions to the NSService SQL Server login account using SQL Server Authentication to connect to a named instance of SQL Server:

GrantXpExec "NSService" -U dba_user_name -P dba_password
   -S computer\sql_instance

See Also

RevokeXPExec Utility

SetupSamples Utility


InstallXPs Utility

Installs the database components to an instance of SQL Server. The InstallXPs command prompt utility is necessary because the Setup program installs the database components for only one instance of SQL Server. If you have multiple instances of SQL Server on one computer and you want to use more than one instance for Notification Services applications, you must install the database components for each instance you want to use.

Syntax
installxps
   SqlServerInstanceName
   SqlServerInstanceBinnDirectory
   [login_ID  password]
Arguments
SqlServerInstanceName
The name of the server that hosts the SQL Server instance.
SqlServerInstanceBinnDirectory
The path to the Binn directory for the SQL Server instance.
login_ID
The SQL Server login ID used to log in to SQL Server.

If you are using SQL Server Authentication to log in to SQL Server, specify the SQL Server login ID using this argument. This argument must be used together with the password argument.

If you are using Microsoft Windows Authentication, do not specify the login_ID and password arguments.

password
Is the password associated with login_ID. This argument must be used together with the login_ID argument.
Permissions

To run the InstallXPs utility, you must be a member of the sysadmin role on the SQL Server instance for which you are installing the database components.

Remarks

If the value for an argument contains spaces, enclose the value in quotation marks.

Example

The following example installs the database components to the Instance1 instance of SQL Server on the computer named MyServer using SQL Server Authentication. Because SQL Server Authentication is used, a user name and password are required (the password is revealed here):

installxps MyServer\Instance1 "C:\MS SQL$Inst1\Binn" UserXYZ N89M234

See Also

UninstallXPs Utility


NSControl Commands

NSControl is a command prompt utility for administering Notification Services. It provides commands for deploying, configuring, monitoring, and controlling Notification Services instances and applications.

Syntax Conventions

The following rules apply to all commands of the NSControl utility:

  • Commands and arguments are case insensitive.
  • Command arguments must be preceded by either a hyphen (-) or a forward slash (/). The two are equivalent.
  • A space must appear between the argument and its value.
  • If a value contains a space, enclose the value in quotation marks.
NSControl Commands

The commands presented in the following table are available in NSControl.

Topic | Description
NSControl Create | Creates a new instance of Notification Services.
NSControl Delete | Deletes an existing instance of Notification Services.
NSControl Disable | Disables the specified Notification Services components.
NSControl DisplayArgumentKey | Displays the key used to encrypt delivery channel and event provider arguments.
NSControl Enable | Enables the specified Notification Services components.
NSControl ListVersions | Displays information about the installed versions and registered instances of Notification Services.
NSControl Register | Registers an instance of Notification Services.
NSControl Status | Displays the current enabled or disabled status of instances and applications.
NSControl Unregister | Unregisters an instance of Notification Services.
NSControl Update | Updates an existing instance of Notification Services.
NSControl Upgrade | Upgrades an instance from Standard Edition to Enterprise Edition, or to a newer version of Notification Services.

See Also

Deployment Overview


NSControl Create

Creates the instance and application databases for a new instance of Notification Services.

Syntax
nscontrol create
   [-help] |
   -in configuration_filename
   [-sqlusername login_ID  -sqlpassword password]
   [-argumentkey key]
   [parameter_name=value [,...n] ]
   [-nologo]
Arguments
-help
Displays the command syntax.
-in configuration_filename
Is the path and file name of the configuration file that defines the instance. If the file is in the current directory, the path is not required.
-sqlusername login_ID
Is the SQL Server login ID used to log in to SQL Server.

If you are using SQL Server Authentication to log in to SQL Server, specify a login ID with this argument. This argument must be used together with the -sqlpassword argument.

If you are using Microsoft Windows Authentication to log in to SQL Server, do not use the -sqlusername and -sqlpassword arguments.

Important Microsoft recommends Windows integrated security.

-sqlpassword password
Is the password associated with the -sqlusername login ID. This argument must be used together with the -sqlusername argument.
-argumentkey key
Is the value used to encrypt delivery channel and event provider arguments that are stored in Notification Services databases. This argument is required if the <EncryptArguments> value in the configuration file is true. You cannot change the key value used by the instance after running NSControl Create. To use a different key, you must delete and then re-create the instance.

You must also specify the same key value when running NSControl Register and NSControl Update. NSControl Register encrypts the key value and stores it in the registry.

parameter_name=value
Is a name/value pair used to pass parameters to the configuration file from the command line.

If the configuration file contains replaceable parameters for configuration values (such as %DBSystem%), specify the parameter name and value on the command line using this argument.

For example, if the configuration file contains the following XML:

<SqlServerSystem>%DBSystem%</SqlServerSystem>

then specify the name and value using NSControl Create as follows:

nscontrol create -in config.xml DBSystem=MySQLServer

Parameters apply to values in the configuration file, but not to values in the application definition files (ADFs). To pass parameters from the command line to the ADF, add a <Parameters> node to the <Application> node in the configuration file and use replaceable parameters within that node.

In addition to specifying parameters on the command line, you also can use environment variables, such as %COMPUTERNAME%. If you use environment variables as substitution parameters, note that command-line parameters take precedence over environment variables if both are specified for a single parameter.

-nologo
Suppresses the product and version statement that appears when you run an NSControl command.
Permissions

The account used to run NSControl Create, or the SQL Server login ID specified by the -sqlusername argument, must have permission to create databases. This includes membership in the dbcreator and sysadmin fixed server roles.

Remarks

The NSControl Create command validates the configuration file and ADFs against their XSD schemas. If any of these files use a format that is not valid, NSControl Create stops without creating the instance.

If you are using Notification Services Standard Edition, and one or more elements are not supported by Standard Edition, NSControl Create stops without creating the instance.

You can run NSControl Create from any computer that has access to the SQL Server database system. NSControl requires access only to create and populate the necessary databases.

You must run NSControl Register after running NSControl Create to register the instance and create the NS$instance_name service for the instance.

To update an existing instance, use NSControl Update.

Examples

The following examples illustrate three methods for creating an instance.

Creating an instance

This example shows how to create a new instance of Notification Services that is configured in a file named StockConfig.xml and uses integrated security:

nscontrol create -in StockConfig.xml
Creating an instance using SQL Server Authentication

Important Microsoft recommends Windows integrated security.

This example shows how to create a new instance of Notification Services configured in a file named StockConfig.xml and using SQL Server Authentication. Because SQL Server Authentication is being used to log in to SQL Server, a user name and password are required (the password is revealed here):

nscontrol create -in StockConfig.xml -sqlusername User5 -sqlpassword X0dP6Ll
Creating an instance and passing parameters for configuration settings

This example shows how to pass a value to the parameter %BasePath% in the configuration file:

nscontrol create -in StockConfig.xml BasePath=C:\MyApps\Stock

See Also

<EncryptArguments> Element

NSControl Commands


NSControl Delete

Deletes the instance database and application databases for an existing Notification Services instance.

Syntax
nscontrol delete
   [-help] |
   –name instance_name
   -server database_server_name
   [-force]
   [-sqlusername login_ID -sqlpassword password]
   [-nologo]
Arguments
-help
Displays the command syntax.
-name instance_name
Is the name of the instance to delete.
-server database_server_name
Is the name of the server that hosts the instance database. If you use a named instance of SQL Server to host the instance database, you must specify both the server name and the instance name, using the format servername\instancename.
-force
Attempts to force the closure of any open database connections before deleting databases, without prompting the user. Without the -force argument, if any processes have a database open, the NSControl Delete command cannot delete that database, but does delete all other databases for the instance.

Note Using NSControl Delete without the -force argument when some databases have open connections can leave the instance in an inconsistent state.

-sqlusername login_ID
Is the SQL Server login ID used to log in to SQL Server.

If you are using SQL Server Authentication to log in to SQL Server, specify a login ID with this argument. Also specify a password using the -sqlpassword argument.

If you are using Microsoft Windows Authentication to log in to SQL Server, do not use the -sqlusername and -sqlpassword arguments.

-sqlpassword password
Is the password associated with the -sqlusername login ID. This argument must be used together with the -sqlusername argument.
-nologo
Suppresses the product and version statement that appears when you run an NSControl command.
Permissions

The account used to run NSControl Delete, or the SQL Server login ID specified by the -sqlusername argument, must have permission to drop databases. This includes membership in the dbcreator or sysadmin fixed server role.

Remarks

After running NSControl Delete, run NSControl Unregister to remove registry information, the service, and performance objects associated with the instance.

Examples

The following examples illustrate the deletion of an instance in three different circumstances.

Deleting an instance

This example shows how to delete an instance of Notification Services named StockApps using integrated security:

nscontrol delete -name StockApps -server MyServer
Deleting an instance using SQL Server Authentication

This example shows how to delete an instance of Notification Services named StockApps using SQL Server Authentication. With SQL Server Authentication, a user name and password are required (the password is revealed here):

nscontrol delete -name StockApps -server MyServer -sqlusername User5 -sqlpassword X0DP6LL

Important Microsoft recommends Windows integrated security.

Closing open connections and then deleting an instance

This example shows how to close all open connections to the instance and application databases, without prompting the user, before deleting the databases:

nscontrol delete -name StockApps -server MyServer -force

See Also

NSControl Commands


NSControl Disable

Disables the specified Notification Services instance, application, or component.

Syntax
nscontrol disable
   [-help] |
   -name instance_name
   [< component > [...n]]
   [-server database_server_name]
   [-application application_name]
   [-sqlusername login_ID -sqlpassword password]
   [-nologo]
< component > ::=
   [-distributor [distributor_system_name]
    | -events [event_system_name]
    | -generator
    | -subscriptions
    | -subscribers ]
Arguments
-help
Displays the command syntax.
-name instance_name
Is the name of the instance affected by the NSControl Disable command. See the -server argument for information about using the -name argument with the -server argument.
<component>
Specifies the component to disable.

If you do not specify a component name, all components of the application or instance are disabled. If you specify a component but do not specify an application name using the -application argument, then the specified component is disabled for all applications hosted by the instance.

<component> can be one of the following arguments:

-distributor [distributor_system_name]

Disables the distributor components for the instance or application. If you specify a distributor system name, the distributor components for only that system are disabled. Otherwise all the distributor components for the instance or application are disabled.

-events [event_system_name]

Disables the event collection components for the instance or application. If you specify -events with a system name, event collection on only that system is disabled. Otherwise all the event collection components for the instance or application are disabled.

-generator

Disables the generator component.

-subscriptions

Disables the subscription management component.

-subscribers

Disables the APIs that add and delete subscribers at the instance level. If the subscriber components are disabled, then no subscribers can be added or deleted.

-server database_server_name
Is the name of the server that hosts the instance database. Use the server name, such as MyServer. If you use a named instance of SQL Server to host the instance database, you must specify the server and instance name using the format servername\instancename.

When you run NSControl Disable on a system where the instance is registered, use the -name argument but not the -server argument. NSControl determines the database server name by reading the instance's registry information.

When you run NSControl Disable on a system where the instance is not registered, you must use both the -name and -server arguments, because NSControl needs both the system name and the instance name.

When the -server argument is specified, the registry values for the instance, if any, are ignored.

-application application_name
Is the name of the application that is having one or all components disabled. If you do not specify an application name, components are disabled for all applications hosted by the instance.
-sqlusername login_ID
Is the SQL Server login ID used to log in to SQL Server.

If you are using SQL Server Authentication to log in to SQL Server, specify the login ID using this argument. Also specify a password using the -sqlpassword argument.

If you are using Microsoft Windows Authentication, do not specify the -sqlusername and -sqlpassword arguments.

-sqlpassword password
Is the password associated with the -sqlusername login ID. This argument must be used together with the -sqlusername argument.
-nologo
Suppresses the product and version statement that appears when you run an NSControl command.
Permissions

The account used to run NSControl Disable, or the SQL Server login ID specified by the -sqlusername argument, can obtain the proper permissions through membership in the NSAdmin database role in individual application and instance databases. Members of the db_owner database role and the sysadmin and dbcreator fixed server roles also can run NSControl Disable.

Remarks

When finished, NSControl displays the current status of the instance, applications, and components.

Examples

The following examples illustrate how to disable instances, applications, and components.

Disabling a registered instance of Notification Services

This example disables an entire instance of Notification Services, named StockApps. The instance must be registered on the server where you run the following command:

nscontrol disable -name StockApps
Disabling an application

This example disables all components of the IntlStocks application hosted by the StockApps instance of Notification Services. The instance must be registered on the server where you run the following command:

nscontrol disable -name StockApps -application IntlStocks
Disabling event collection

This example disables event collection for all applications on the StockApps instance of Notification Services. The instance must be registered on the server where you run the following command:

nscontrol disable  name StockApps -events
Disabling an instance from an unregistered server using SQL Server Authentication

If you run NSControl Disable from a server where StockApps is not registered, you must supply the name of a server where the instance is registered using the -server argument. This example shows how to disable an instance that is registered on PServer14 using SQL Server Authentication (the password is revealed here):

nscontrol disable -name StockApps -server PServer14 -sqlusername User5 -sqlpassword X0DP6LL

Important Microsoft recommends Windows integrated security.

See Also

NSControl Commands


NSControl DisplayArgumentKey

Displays the value of the Notification Services key used to encrypt delivery channel and event provider arguments, if using argument encryption.

nscontrol displayargumentkey
   –name instance_name
Arguments
-name instance_name
Is the name of an instance that uses an argument key.
Permissions

The account used to run NSControl DisplayArgumentKey must be a member of the Administrators or Power Users groups in Microsoft Windows, or must run under the same account as the NS$instance_name service.

Remarks

You configure argument encryption using the <EncryptArguments> element in the configuration file. When the <EncryptArguments> value is true, Notification Services encrypts the values of delivery channel and event provider arguments before storing these values in the instance and application databases.

You initially provide the key value when you run NSControl Register or NSControl Create. You need to use the same key value with NSControl Create, NSControl Register, and NSControl Update. NSControl DisplayArgumentKey enables you to view the key.

NSControl DisplayArgumentKey returns the key value from the registry.

Examples

The following example shows how to view the argument key for the StockApps instance:

nscontrol displayargumentkey -name StockApps

See Also

<EncryptArguments> Element

NSControl Commands


NSControl Enable

Enables the specified Notification Services instance, application, or component by setting flags in the instance database.

Syntax
nscontrol enable
   [-help] |
   -name instance_name
   [< component > [...n]]
   [-server database_server_name]
   [-application application_name]
   [-sqlusername login_ID -sqlpassword password]
   [-nologo]
< component > ::=
   [-distributor [distributor_system_name]
    | -events [event_system_name]
    | -generator
    | -subscriptions
    | -subscribers ]
Arguments
-help
Displays the command syntax.
-name instance_name
Is the name of the instance affected by the NSControl Enable command. See the -server argument for information about using the -name argument with the -server argument.
<component>
Specifies the component to enable.

If you do not specify a component name, all components of the application or instance are enabled. If you specify a component but do not specify an application name using the -application argument, then the specified component is enabled for all applications hosted by the instance.

-distributor [distributor_system_name]

Enables the distributor components for the instance or application. If you specify a distributor system name, the distributor components for only that system are enabled. Otherwise all the distributor components for the instance or application are enabled.

-events [event_system_name]

Enables the event collection components for the instance or application. If you specify -events with a system name, event collection on only that system is enabled. Otherwise all the event collection components for the instance or application are enabled.

-generator

Enables the generator component.

-subscriptions

Enables the subscription management component.

-subscribers

Enables the APIs that add and delete subscribers at the instance level. If the subscriber components are enabled then subscribers can be added or deleted.

-server database_server_name
Is the name of the server that hosts the instance database. Use the server name, such as MyServer. If using a named instance of SQL Server to host the instance database, you must specify the server and instance name using the format servername\instancename.

When you run NSControl Enable on a system where the instance is registered, use the -name argument, but not the -server argument. NSControl determines the database server name by reading the instance's registry information.

When you run NSControl Enable on a system where the instance is not registered, you must use both the-name and -server arguments, because NSControl needs both the system name and the instance name.

When the -server argument is specified, the registry values for the instance, if any, are ignored.

-application application_name
Is the name of the application that is having one or all components enabled. If you do not specify an application name, components are enabled for all applications hosted by the instance.
-sqlusername login_ID
Is the SQL Server login ID used to log in to SQL Server.

If you are using SQL Server Authentication to log in to SQL Server, specify a login ID with this argument. Also specify a password using the -sqlpassword argument.

If you are using Microsoft Windows Authentication, do not specify the -sqlusername and -sqlpassword arguments.

-sqlpassword password
Is the password associated with the -sqlusername login ID. This argument must be used together with the -sqlusername argument.
-nologo
Suppresses the product and version statement that appears when you run an NSControl command.
Permissions

The account used to run NSControl Enable, or the SQL Server login ID specified by the -sqlusername argument, can obtain the proper permissions through membership in the NSAdmin database role in individual application and instance databases. Members of the db_owner database role and the sysadmin and dbcreator fixed server roles also can run NSControl Enable.

Remarks

When finished, NSControl displays the current status of the instance, applications, and components.

Examples

The following examples illustrate how to enable instances, applications, and components.

Enabling a registered instance of Notification Services

This example enables an entire instance of Notification Services, named StockApps. The instance must be registered on the server where you run the following command:

nscontrol enable -name StockApps
Enabling an application

This example enables all components of the IntlStocks application on the StockApps instance of Notification Services. The instance must be registered on the server where you run the following command:

nscontrol enable -name StockApps -application IntlStocks
Enabling event collection

This example enables event collection for all applications on the StockApps instance of Notification Services. The instance must be registered on the server where you run the following command:

nscontrol enable -name StockApps -events
Enabling an instance from an unregistered server using SQL Server Authentication

If you run NSControl Enable from a server where the StockApps instance is not registered, you must supply the name of a server where the instance is registered using the -server argument. This example shows how to enable an instance that is registered on PServer14 using SQL Server Authentication (the password is revealed here):

nscontrol enable -name StockApps -server PServer14 -sqlusername User5 -sqlpassword X0DP6LL

Important Microsoft recommends Windows integrated security.

See Also

NSControl Commands


NSControl ListVersions

Displays information about the installed versions and registered instances of Notification Services.

Syntax
nscontrol listversions
   [-help] |
   [-name instance_name]
   [-version version_number]
   [-nologo]
Arguments
-help
Displays the command syntax.
-name instance_name
Specifies an instance of Notification Services. If the -name argument is used, only the information for the specified instance is listed and no version information is listed. Otherwise, the information for all instances is listed.
-version version_number
If the -version argument is used, the information for that version is listed and all the information for all instances that use that version is listed. Otherwise, the information for all installed versions is listed.

The version number is specified in four parts, such as 1.2.3.4.

-nologo
Suppresses the product and version statement that appears when you run an NSControl command.
Permissions

The account used to run NSControl ListVersions must be a member of the local Administrators group. NSControl ListVersions obtains data from the registry that can be read only by administrators.

Remarks

If neither the -name nor the -version argument is used, then the information for all versions and instances is listed.

The version information reported refers to the installed versions of Notification Services, not the version information stored in each instance database.

Examples

The following examples illustrate two ways to display version and instance information.

Displaying all available version and instance information

This example displays information about all installed versions and instances of Notification Services that are registered on the computer:

nscontrol listversions
Displaying version information for a single instance

This example displays information for an instance of Notification Services named StockApps:

nscontrol listversions -name StockApps

See Also

NSControl Commands


NSControl Register

Registers an instance of Notification Services. NSControl Register also can create and register an NS$instance_name service for the instance and create performance objects for the instance.

Syntax
nscontrol register
   [-help] |
   -name instance_name
   [-server database_server_name]
   [-service
      [-serviceusername service_username  -servicepassword password]
      [-sqlusername login_id  -sqlpassword password]
      [-argumentkey key]
      [-nologo] ]
Arguments
-help
Displays the command syntax.
-name instance_name
Is the name of the instance to register.
-server database_server_name
Is the name of the server that hosts the instance database. If you use a named instance of SQL Server to host the instance database, you must specify both the server name and instance name, using the format servername\instancename.
-service
Creates the NS$instance_name service for the instance, registers the service, and creates performance counters for the instance.

When running NSControl Register on a server that does not run the event provider, generator, or distributor, do not specify the -service argument. For example, on a Web server that requires access to the subscriber API you need to register the instance, but you do not need to install the service.

-serviceusername service_username
Is the Microsoft Windows user name that the service uses to access local and remote objects. If the Notification Services system is composed of multiple servers, this account must have permission to access Notification Services resources on those servers.

This argument must be used together with the -servicepassword argument. In Microsoft Windows® XP, if -serviceusername and -servicepassword are not specified, the default account NT AUTHORITY\NetworkService is used. For Windows 2000, -serviceusername and -servicepassword are required.

Note For security reasons, the service account should run with minimum permissions, not as an administrator or as the LocalSystem service account. For more information, see NS$instance_name Service Account Security.

-servicepassword password
Is the password associated with -serviceusername. This argument must be used together with the -serviceusername argument.
-sqlusername login_id
Is the SQL Server login ID used by the NS$instance_name service to log in to SQL Server.

If you are using SQL Server Authentication to log in to SQL Server, you must specify both the -sqlusername and -sqlpassword arguments.

If you are using Windows Authentication, do not specify the -sqlusername and -sqlpassword arguments.

Note If you assign a SQL Server user name and password to the service, this information is encrypted and stored in the registry. To avoid storing this information, assign a Windows account as the service user name and then assign database permissions to this account.

The best practice for optimal security is to assign a Windows account to the NS$instance_name service, and then grant only the necessary permissions to that account for both network and SQL Server access.

-sqlpassword password
Is the password associated with the -sqlusername login ID. This argument must be used together with the -sqlusername argument.
-argumentkey key
Is the value is used to encrypt delivery channel and event provider arguments that are stored in Notification Services databases. This argument is required if the <EncryptArguments> value in the configuration file is true. NSControl Register encrypts the key value and stores it in the registry; this is required to allow the NS$instance_name service to read the encrypted arguments. You cannot change the key after running NSControl Create.
-nologo
Suppresses the product and version statement that appears when you run an NSControl command.
Permissions

The account used to run NSControl Register must be a member of the local Administrators group, which allows NSControl Register to update the registry and create a service.

For information about the permissions required by the NS$instance_name service for Notification Services, see Service Account Security Requirements.

Remarks

NSControl Register must be run locally. You cannot register Notification Services on a remote server.

If SQL Server Authentication is used, and the SQL Server user name or password used by the service changes, you must change the login information using NSControl Register. The user name and password are encrypted and stored in the registry where only the service has access.

If you specify a key value using the -argumentkey argument, NSControl Register encrypts the key and stores it in the registry. The key is secured so that only members of the Administrators and Power Users groups, and the account that the NS$instance_name service runs under can read the key.

Examples

The following examples illustrate three different forms of registering an instance.

Registering an instance using integrated security, without creating a service or performance objects

This example shows how to add information to the registry about the StockApps instance, but not create a service or performance objects for the instance. This can be useful if you are updating registry information, but are not renaming the service, thus keeping the existing service and performance objects, or if you are registering Notification Services to use the subscription API from a Web server:

nscontrol register -name StockApps
Registering an instance using a Windows user name and password for the service

This example shows how to define a user name and password for the NS$instance_name service account when registering the service for the StockApps instance. This is required when the service account needs different permissions than NetworkService, for example in a secure data center where services are granted minimal permissions, or in Windows 2000 where the NetworkService account does not exist (the password is revealed here):

nscontrol register -name StockApps -service -serviceusername User7 -servicepassword Sxp372Q
Registering an instance using a Windows account for Windows and network access and using a SQL Server user name and password for database access

This example shows how to define and register a service when the NS$instance_name service must use SQL Server Authentication for the StockApps instance to access databases (the password is revealed here):

nscontrol register -name StockApps -service -serviceusername User7 -servicepassword Sxp372Q -sqlusername User5 -sqlpassword XsDfCv4

Important Microsoft recommends Windows integrated security.

See Also

<EncryptArguments> Element

NSControl Commands


NSControl Status

Displays the enabled or disabled state of the specified instance, applications, and their components in Notification Services. It also displays the status of the NS$instance_name service or services associated with the instance.

Syntax
nscontrol status
   [-help] |
   -name instance_name
   [-server database_server_name]
   [-application application_name]
   [-sqlusername login_id -sqlpassword password]
   [-nologo]
Arguments
-help
Displays the command syntax.
-name instance_name
Is the name of the instance to report on.
-server database_server_name
Is the name of the server that hosts the instance of Notification Services.

When you run NSControl Status on a system where the instance is registered, use the -name argument but not the -server argument. NSControl determines the database server name by reading the instance's registry information.

When you run NSControl Status on a system where the instance is not registered, you must use both the -name and -server arguments, because NSControl needs both the server name and the instance name.

-application application_name
Is the name of the application you want status about.
-sqlusername login_id
If you are using SQL Server Authentication to log in to SQL Server, you must specify both the -sqlusername and -sqlpassword arguments.

If you are using Microsoft Windows Authentication, do not specify the -sqlusername and -sqlpassword arguments.

-sqlpassword password
Is the password associated with the -sqlusername login ID. This argument must be used together with the -sqlusername argument.
-nologo
Suppresses the product and version statement that appears when you run an NSControl command.
Permissions

The account used to run NSControl Status, or the SQL Server login ID specified by the -sqlusername argument, must be a member of one of the following database roles: NSAnalysis, NSDistributor, NSEventProvider, NSGenerator, NSReader, NSRunService, NSSubscriberAdmin, or NSVacuum.

In addition, the status of all NS$instance_name services that run the instance is displayed, so the account must be an administrator on all servers where the instance runs.

Remarks

The NSControl Status command is useful in determining which components are running. The output of the NSControl Status command is also displayed by NSControl Enable and NSControl Disable.

Examples

The following examples illustrate several types of status display.

Displaying the status of an instance

This example shows how to display the enabled or disabled status of the StockApps instance. If any individual application or component is disabled, information about the component or application is displayed:

nscontrol status -name StockApps
Displaying the status of an application when the instance is not registered locally

This example shows how to display the status of the IntlStocks application on the StockApps instance. The StockApps instance is not registered locally, but is registered on PServer07:

nscontrol status -name StockApps -server PServer07 -application IntlStocks
Displaying the status of an instance using SQL Server Authentication

This example shows how to display the enabled or disabled status of the StockApps instance if SQL Server Authentication is required to log in to SQL Server (the password is revealed here):

nscontrol status -name StockApps -sqlusername User5 -sqlpassword BtW907q

Important Microsoft recommends Windows integrated security.

See Also

NSControl Commands


NSControl Unregister

Removes the instance from the registry, uninstalls the NS$instance_name service for the instance on the local server, and removes the performance counters for the instance.

Syntax
nscontrol unregister
   [-help] |
   –name instance_name
   [-nologo]
Arguments
-help
Displays the command syntax.
-name instance_name
Specifies the instance to unregister.
-nologo
Suppresses the product and version statement that appears when you run an NSControl command.
Permissions

The account used to run NSControl Unregister must be a member of the local Administrators group, which allows NSControl Unregister to update the registry and remove a service.

Remarks

NSControl Unregister must be run locally.

Example

This example shows how to unregister a local instance named StockApps:

nscontrol unregister -name StockApps

See Also

NSControl Commands


NSControl Update

Updates the instance and application databases for an existing instance of Notification Services.

Syntax
nscontrol update
   [-help] |
   -in configuration_filename
   [-verbose]
   [-force]
   [-sqlusername login_id -sqlpassword password]
   [-argumentkey key]
   [parameter_name=value [,...n] ]
   [-nologo]
Arguments
-help
Displays the command syntax.
-in configuration_filename
Is the path and file name of the configuration file that defines the instance. If the file is in the current directory, the path is not required.
-verbose
Displays all information that has changed in the configuration file and the application definition file (ADF) as it is found. This is useful for debugging or understanding exactly what actions NSControl Update is performing.
-force
Forces NSControl Update to proceed without prompting for approval after displaying the actions that will occur.
-sqlusername login_ID
Is the SQL Server login ID used to log in to SQL Server.

If you are using SQL Server Authentication to log in to SQL Server, you must specify both the -sqlusername and -sqlpassword arguments.

If you are using Microsoft Windows Authentication, do not specify the -sqlpassword and -sqlpassword arguments.

-sqlpassword password
Is the password associated with the -sqlusername login ID. This argument must be used together with the -sqlusername argument.
-argumentkey key
Is the same key value that was specified with NSControl Register and NSControl Create. This argument is required if the <EncryptArguments> value in the configuration file is true. NSControl Update deciphers the argument values to verify that the key is the same key as specified with NSControl Create. If the key value is the same, the update continues. You cannot change the key after creating the instance.
parameter_name=value
Is a name/value pair used to pass parameters to the configuration file from the command line.

If the configuration file contains replaceable parameters for configuration values (such as %DBSystem%), specify the parameter name and value on the command line using a name/value pair.

For example, if the configuration file contains the following XML:

<SqlServerSystem>%DBSystem%</SqlServerSystem>

then specify the name and value using NSControl Update as follows:

nscontrol update -in config.xml DBSystem=MySQLServer

Parameters apply to values in the configuration file, but not to parameters in the application definition file (ADF). To pass parameters from the command line to the ADF, add a <Parameters> node to the <Application> node of the configuration file and use replaceable parameters within that node.

In addition to specifying parameters on the command line, you also can use environment variables, such as %COMPUTERNAME%. If using environment variables as substitution parameters, note that command-line parameters take precedence over environment variables if both are specified for a single parameter.

-nologo
Suppresses the product and version statement that appears when you run an NSControl command.
Permissions

The account used to run NSControl Update, or the SQL Server login specified by the -sqlusername argument, must be a member of the db_owner database role in all instance and application databases affected by the NSControl Update command, or must be a member of the sysadmin fixed server role.

Remarks

The NSControl Update command can fail before completion because of ADF or configuration file errors. This will leave the system in an inconsistent state, which means data will be lost. If the data is critical, back up your data before running NSControl Update.

Additionally, check all ADFs and configuration files before running NSControl Update to reduce the possibility of this error occurring. If an error does occur, fix the file and then run NSControl Update again.

If you are using Notification Services Standard Edition, and one or more elements are not allowed with Standard Edition, NSControl Update stops without updating the instance.

You cannot change all fields in the configuration file and the ADF. Some fields in those files specify options that cannot be changed without deleting and creating the instance again.

If you change subscription class metadata in the ADF, NSControl Update renames the existing subscription class table, NS subscription_class Subscriptions, to NS subscription_class SubscriptionsOld to save the subscription data. If you later update the same subscription class, when NSControl Update attempts to rename the table, the rename fails if NS subscription_class SubscriptionsOld still exists. To resolve this problem, rename or delete NS subscription_class SubscriptionsOld.

NSControl Update typically displays all changes made to the configuration file and ADFs while performing the update. However, if the instance uses argument encryption, NSControl Update does not display the encrypted arguments.

Updating Tables

When you explicitly define a table, view, index, or other SQL object in the ADF, you must include statements that check for and delete any existing object with the same name before you create the new SQL object. This is essential because NSControl Update does not automatically delete any existing user-defined SQL objects having the same name. By explicitly deleting the SQL object, you avoid a duplicate object error.

For example, you can use the following ADF elements and Transact-SQL statements to drop an existing SubscriptionChron table before creating the new SQL table:

<SqlSchema>
   <SqlStatement>
      IF EXISTS (SELECT name
         FROM sysobjects
         WHERE name = N'SubscriptionChron' AND xtype = 'U')
      DROP TABLE "SubscriptionChron"
      CREATE TABLE SubscriptionChron
      (
         SubscriptionId                   bigint,
         HoroscopeSign                    nvarchar(16),
         HoroscopeContent                 nvarchar(3500)
         PRIMARY KEY (HoroscopeSign)
      )
   </SqlStatement>
</SqlSchema>
Examples

The following examples illustrate how to update an instance under various circumstances.

Updating an instance using integrated security

This example shows how to create a new instance of Notification Services configured with a file named StockConfig.xml. Because Windows integrated security is used, the user name and password are not required:

nscontrol update -in StockConfig.xml
Viewing all differences and forcing an update without prompting the user

This example shows how to display all information that is changing during an update. While displaying the information, the update proceeds without prompting for confirmation:

nscontrol update -in StockConfig.xml -verbose -force
Updating an instance using SQL Server Authentication

Important Microsoft recommends Windows integrated security.

This example shows how to create a new instance of Notification Services configured with a file named StockConfig.xml. Because SQL Server Authentication is used, a user name and password are required (the password is revealed here):

nscontrol update -in StockConfig.xml -sqlusername User5 -sqlpassword X0DP6LL
Passing a value into the configuration file during update

This example shows how to pass a value to a parameter named %BasePath% in the configuration file:

nscontrol update -in StockConfig.xml BasePath=C:\MyApps\Stock

See Also

<EncryptArguments> Element

NSControl Commands


NSControl Upgrade

Upgrades an instance of Notification Services from Standard Edition to Enterprise Edition or to a newer version of Notification Services.

Syntax
nscontrol upgrade
   [-help] |
   –name instance_name
   -server database_server_name
   [-sqlusername login_ID -sqlpassword password]
   [-nologo]
Arguments
-help
Displays the command syntax.
-name instance_name
Is the name of the instance to upgrade.
-server database_server_name
Is the name of the server that hosts the instance database. If you use a named instance of SQL Server to host the instance database, you must specify both the server name and the instance name, using the format servername\instancename.
-sqlusername login_ID
Is the SQL Server login ID used by NSControl to log in to SQL Server.

If you must use SQL Server Authentication to connect to SQL Server, specify a login ID with this argument. Also specify a password using the -sqlpassword argument.

If you are using Microsoft Windows Authentication to connect to SQL Server, do not use the -sqlusername and -sqlpassword arguments.

-sqlpassword password
Is the password associated with the -sqlusername login ID. This argument must be used together with the -sqlusername argument.
-nologo
Suppresses the product and version statement that appears when you run an NSControl command.
Permissions

The account used to run NSControl Upgrade, or the SQL Server login ID specified by the -sqlusername argument, must be a member of the db_owner fixed database role or the sysadmin fixed server role.

Remarks

When you run NSControl Upgrade, the version or edition of NSControl determines the version or edition for the upgrade. For example, if an instance was created using the Standard Edition of Notification Services, and you want to upgrade the instance to Enterprise Edition, run NSControl Upgrade from the Enterprise Edition Bin folder to perform the upgrade.

NSControl Upgrade checks the instance database to determine the Notification Services version and edition the instance runs under. If the instance database reports that the existing instance is a previous version (or is Standard Edition if upgrading to Enterprise Edition), NSControl Upgrade then verifies that the instance is disabled and performs the upgrade.

After running NSControl Upgrade, run NSControl Unregister to update registry information for the instance.

Enterprise Edition supports additional options in application definition files (ADFs), such as multicast delivery. After running NSControl Upgrade to upgrade from Standard Edition to Enterprise Edition, you can update the ADFs and then update the applications using NSControl Update. For more information about the differences between Standard Edition and Enterprise Edition, see Editions of Notification Services.

Examples

The following examples illustrate how to upgrade an instance in two different circumstances.

Upgrading an instance, using Windows Authentication to connect to SQL Server

This example shows how to upgrade an instance of Notification Services named StockApps using integrated security. For example, the existing instance might use Standard Edition, and the NSControl Upgrade is run from the Bin folder of Enterprise Edition.

nscontrol upgrade -name StockApps -server MyServer
Upgrading an instance, using SQL Server Authentication to connect to SQL Server

This example shows how to upgrade an instance of Notification Services named StockApps using SQL Server Authentication. With SQL Server Authentication, a user name and password are required:

nscontrol upgrade -name StockApps -server MyServer -sqlusername User5 -sqlpassword [Password]

Important Microsoft recommends Windows integrated security.

See Also

NSControl Commands


RemoveSamplesDB Utility

Removes all default Notification Services programming samples.

Syntax
RemoveSamplesDB
Permissions

The account used to run RemoveSamplesDB must be a member of the local Administrators group (to create services) and a member of the SQL Server sysadmin fixed server role (to create databases and grant permissions).

Remarks

The RemoveSamplesDB utility unregisters the instances, drops the instance and application databases, and removes the Internet Information Services (IIS) virtual directory. It does this by calling the RunClean script (available in the BuildScripts subfolder of the AppDefinition project), running NSControl Unregister, and then making the appropriate IIS changes.

Note If you run SetupSamples.cmd more than once with different parameters, the RemoveSamplesDB utility removes only the databases of the last installed instance.

Example

The following example removes installed samples:

RemoveSamplesDB

See Also

SetupSample Utility

SetupSamples Utility


RevokeXPExec Utility

Revokes permissions to run the Notification Services extended stored procedures.

Syntax
RevokeXPExec
   userName
   [osqlArgs]
Arguments
userName
Is the name of the account for which your are revoking permissions. If the userName value contains spaces, enclose the argument in quotation marks.
osqlArgs
Is one or more osql arguments to pass to the osql utility. For example, if you must use SQL Server Authentication to connect to SQL Server, specify a SQL Server user name and password using the -U and -P arguments. By default, RevokeXPExec passes -E to osql, instructing osql to use a trusted connection to SQL Server. If you pass any other arguments, such as -S, the default -E argument is not passed by RevokeXPExec.

For information about the osql utility, see "osql Utility" in SQL Server Books Online.

Permissions

To run the RevokeXPExec utility, you must be a member of the sysadmin role on the SQL Server instance where you are revoking permissions.

Remarks

The user name in the master database must match the userName argument.

Examples

The following examples illustrate how to use RevokeXPExec under various circumstances.

Revoking extended stored procedure permissions from a domain account using Windows Authentication

This example revokes execute permissions from the domain/user_name account using Microsoft Windows Authentication to connect to SQL Server:

RevokeXpExec.cmd "domain\user_name"

Revoking extended stored procedure permissions from a domain account on a named instance of SQL Server using Windows Authentication

This example revokes execute permissions from the domain/user_name account using Windows Authentication to connect to a named instance of SQL Server:

RevokeXpExec.cmd "domain\user_name" -E -S computer\sql_instance

Revoking extended stored procedure permissions from a SQL Server login using Windows Authentication

This example revokes execute permissions from the NSService SQL Server login account using Windows Authentication to connect to SQL Server:

RevokeXpExec.cmd "NSService"

Revoking extended stored procedure permissions from a SQL Server login using SQL Server Authentication

This example revokes execute permissions from the NSService SQL Server login account using SQL Server Authentication to connect to SQL Server:

RevokeXpExec "NSService" -U dba_user_name -P dba_password

Revoking extended stored procedure permissions from a SQL Server login on a named instance of SQL Server using SQL Server Authentication

This example revokes execute permissions from the NSService SQL Server login account using SQL Server Authentication to connect to a named instance of SQL Server:

RevokeXpExec "NSService" -U dba_user_name -P dba_password
   -S computer\sql_instance

See Also

GrantXPExec Utility


SetupSample Utility

Configures a single Notification Services sample application.

Syntax
SetupSample
   ServiceUserName
   ServicePassword
   [ServiceSqlServerUserName]
   [ServiceSqlServerPassword]
Arguments
ServiceUserName
Is the account the NS$instance_name service runs under. This account is associated with the service when the service is registered. The service must have the permissions specified in NS$instance_name Service Account Security.

If using Microsoft Windows integrated security to log in to SQL Server, make sure this account has permission to log in to SQL Server.

ServicePassword
Is the password of the ServiceUserName account.
ServiceSqlServerUserName
Optional. Use only if the NS$instance_name service must connect to SQL Server using SQL Server Authentication. Make sure this account has a SQL Server login account.

This account is added to the appropriate SQL Server roles in the instance database after the database is created by the RunCreate.cmd script. If the account name or password changes, you will need to manually modify the SetGlobalVars.cmd script and run the RunRebuild.cmd script.

ServiceSqlServerPassword
Optional. Specify only if you specify a ServiceSqlServerUserName value. This is the password of the ServiceSqlServerUserName account. This password is encrypted and stored in the registry so the service can use the password when connecting to SQL Server.

Important Microsoft strongly recommends that you use Windows Authentication rather than SQL Server Authentication. Windows Authentication provides better security features, such as secure validation and encryption of passwords, auditing, password expiration, minimum password length, and account lockout after multiple invalid login requests.

Permissions

The account used to run SetupSample must be a member of the local Administrators group (to create services) and a member of the SQL Server sysadmin fixed server role (to create databases and grant permissions).

Remarks

If the value for an argument contains special characters, enclose the value in quotation marks.

If the NS$instance_name service password contains special characters (such as ^, ", >, <, | or &), you must run the SetupSamples.cmd script, and then change the password for the NS$instance_name service.

  1. In Control Panel, open Administrative Tools.
  2. Open Services.
  3. Right-click the NS$instance_name service (instance_name represents the name of the Notification Services instance), and then click Properties.
  4. On the Log On tab, type your password in the Password and Confirm Password boxes, and then click OK.
  5. Right-click the service, and then click Start.

The SetupSamples.cmd script can be used to set up a new sample after running the CopySample ultility to make a copy of an existing sample. It cannot be used as a replacement for the SetupSamples utility, which must be run initially to set up all the samples.

Examples

The following example shows how to run the service under a local account with no password. The service will access SQL Server using Windows Authentication.

SetupSample "NT AUTHORITY\NetworkService" ""

This example shows how to run the service under a domain account. The service will access the instance of SQL Server named in the SetGlobalVars.cmd file using SQL Server Authentication.

SetupSample "domain\MyServiceAccount" "MyServicePassword" "MySQLAccount" "MySQLPassword"

See Also

CopySample Utility

SetupSamples Utility


SetupSamples Utility

Configures the default Notification Services programming samples, registering the sample instances and modifying the SetGlobalVars.cmd script.

Syntax
SetupSamples
   ServiceUserName
   ServicePassword
   SqlServerInstance
   [ServiceSqlServerUserName]
   [ServiceSqlServerPassword]
   [SqlServerAdminName]
Arguments
ServiceUserName
Is the account the NS$instance_name service runs under. This account is associated with the service when the service is registered. The service must have the permissions specified in NS$instance_name Service Account Security.

If using Microsoft Windows integrated security to log in to SQL Server, make sure this account has a SQL Server login account.

ServicePassword
Is the password of the ServiceUsername account.
SqlServerInstance
Name of the SQL Server instance that is hosting the instance and application databases. If using the default SQL Server instance, specify the computer name; otherwise, specify both the computer name and instance name in the form computer\instance.
ServiceSqlServerUserName
Optional. Use only if the NS$instance_name service must connect to SQL Server using SQL Server Authentication. Make sure this account has a SQL Server login account.

This account is added to the appropriate SQL Server roles in the instance database after the database is created by the RunCreate.cmd script. If the account name or password changes, you will need to manually modify the SetGlobalVars.cmd script and run the RunRebuild.cmd script.

ServiceSqlServerPassword
Optional. Specify only if you specify a ServiceSqlServerUserName value. This is the password of the ServiceSqlServerUserName account. This password is encrypted and stored in the registry so the service can use the password when connecting to SQL Server.
SqlServerAdminName
Optional. The SQL Server account used by SetupSamples to run SQL Server tools, such as osql. Specify this parameter only if you use SQL Server Authentication. If this value is not supplied, Windows Authentication is used. This account must have the permissions required by NSControl Create and NSControl Register.

Important Microsoft strongly recommends that you use Windows Authentication rather than SQL Server Authentication. Windows Authentication provides better security features, such as secure validation and encryption of passwords, auditing, password expiration, minimum password length, and account lockout after multiple invalid login requests.

Permissions

The account used to run RemoveSamplesDB must be a member of the local Administrators group (to create services) and a member of the SQL Server sysadmin fixed server role (to create databases and grant permissions).

Remarks

If the value for an argument contains special characters, enclose the value in quotation marks.

If the NS$instance_name service password contains special characters (such as ^, ", >, <, | or &), you must run the SetupSamples.cmd script, and then change the password for the NS$instance_name service.

  1. In Control Panel, open Administrative Tools.
  2. Open Services.
  3. Right-click the NS$instance_name service (instance_name represents the name of the Notification Services instance), and then click Properties.
  4. On the Log On tab, type your password in the Password and Confirm Password boxes, and then click OK.
  5. Right-click the service, and then click Start.

    Important If any samples are added after running SetupSamples, they must be configured manually, either by using the SetupSample.cmd script in the specific sample directory, or by using the NSControl utility.

Examples

The following examples illustrate the setup of the NS$instance_name service in six different circumstances.

Domain account, default database instance

This example sets up the NS$instance_name service with a domain account and creates the Notification Services databases on the local server in the default SQL Server instance.

SetupSamples "YourDomain\YourAccount" "YourPassword" SqlServerComputerName
Domain account, named database instance

This example sets up the NS$instance_name service with a domain account and creates the Notification Services databases on the local server in the specified SQL Server instance.

SetupSamples "YourDomain\YourAccount" "YourPassword" SqlServerComputerName\SqlServerInstanceName
Local account, named database instance

This example sets up the NS$instance_name service with a local account and creates the Notification Services databases on the local server in the specified SQL Server instance.

SetupSamples "YourSystemName\YourLocalAccount" "YourPassword" SqlServerComputerName\SqlServerInstanceName
Domain account, remote default database system

This example sets up the NS$instance_name service with a domain account and creates the Notification Services databases on the default instance of a remote server.

SetupSamples "YourDomain\YourAccount" "YourPassword" "RemoteComputerName"
NetworkService account, remote database system, SQL Server Authentication, SQL Server administration account

The following example sets up the NS$instance_name service with the NetworkService account on Microsoft Windows® XP. The command creates the Notification Services databases on a remote system, and the service accesses those databases using SQL Server Authentication.

The Transact-SQL commands that configure the samples run under the SQL Server sa account. You will be prompted to enter the sa password when the script runs.

SetupSamples "NT AUTHORITY\NetworkService" "" "RemoteComputerName" "SqlUserName" "SqlPassword" "sa"
Domain account, remote database server, Windows Authentication, SQL Server administration account

The following example sets up the NS$instance_name service with a domain account and creates the Notification Services databases on the default instance of a remote server. Windows integrated security is used to log in to SQL Server, but the SQL Server sa account is used to run the NSControl administrative commands.

You are prompted to enter the sa password when the script runs.

SetupSamples "YourDomain\YourAccount" "YourPassword" "RemoteComputerName" "" "" "sa"


UninstallXPs Utility

Removes the database components from an instance of SQL Server. The UninstallXPs utility is necessary because the Setup program removes the database components from only the instance of SQL Server where the Setup program installed the components. Setup does not remove database components installed by the InstallXPs utility.

Syntax
uninstallxps
   SqlServerInstanceName
   SqlServerInstanceBinnDirectory
   [login_ID  password]
Arguments
SqlServerInstanceName
Is the name of the SQL Server instance.
SqlServerInstanceBinnDirectory
Is the path to the Binn directory for the SQL Server instance.
login_ID
Is the SQL Server login ID used to log in to SQL Server.

If you are using SQL Server Authentication to log in to SQL Server, specify the SQL Server login ID using this argument. This argument must be used together with the password argument.

If the login_ID and password arguments are not specified, integrated security is used to log in to SQL Server.

password
Is the password associated with login_ID. This argument must be used together with the login_ID argument.
Permissions

To run the UninstallXPs utility, you must be a member of the sysadmin role on the SQL Server instance from which you are removing the database components.

Remarks

If the value for an argument contains spaces, enclose the value in quotation marks.

Example

The following example removes the database components from the Instance1 instance of SQL Server on the computer named MyServer using SQL Server Authentication (the password is revealed here):

uninstallxps MyServer\Instance1 "C:\MS SQL$Inst1\Binn" UserXYZ N89M234

See Also

InstallXPs Utility


Troubleshooting

When troubleshooting a problem in Microsoft® SQL Server™ Notification Services, you might find the solution by reading the answers to frequently asked questions (FAQs), reading the solutions to common issues encountered by Notification Services users, or configuring event messages and then viewing the messages in the application log.

Other current information can be found at the Notification Services home page.

The topics that this section covers are described in the following table.

Topic | Description
Frequently Asked Questions | Provides answers to questions frequently asked of the Notification Services team during presentations and support sessions.
Notification Services Troubleshooting | Provides information to help you resolve some of the more common issues encountered when using Notification Services.
Event Messages | Provides information about configuring event logs and using event messages.


Frequently Asked Questions

Microsoft has compiled the following list of questions commonly asked by users of Notification Services.

What is the difference between Notification Services and SQL Server Agent?

Answer

SQL Server Agent was created specifically to send messages to SQL Server administrators or perform predefined tasks based on server or database conditions.

Notification Services collects data from just about any source, matches the events to subscriptions defined by many users, and sends formatted messages using almost any protocol to almost any device that can receive messages.

Although you can customize SQL Server Agent to send messages to many users based on data values using triggers, SQL Server Agent was not designed or intended to scale to thousands or millions of users. Notification Services, because of its scalability model, can scale to millions of users, sending millions of notifications per day.

Also, as a development platform Notification Services provides features that reduce the time required to get an application up and running. SQL Server Agent is not a development platform, so it does not offer similar features.

For more information about Notification Services, see Introducing SQL Server Notification Services.

Can I run multiple notification applications on one server?

Answer

Yes. You deploy instances of Notification Services; each instance can host one or more applications. You can run multiple instances on one server; you also can run multiple versions of Notification Services on one server.

To determine how many applications to run on one server, you must look at the processing load each application is likely to place on your server. If you run too many applications on one server, performance degrades.

For more information, see Planning a Notification Services System.

How long does it take to generate a notification from an event?

Answer

First, not all subscriptions are event triggered. Some subscriptions specify a schedule for notifications. In this case, notifications are sent according to the defined schedule, not when the event arrives.

For event-triggered notifications, the latency between the occurrence of an event and the delivery of the notification depends greatly on the application design. Here are the causes of notification latency:

  • Events must be submitted to Notification Services. The time between an event and when the event provider submits that event in an event batch is one cause of latency.
  • The generator must "wake up" to generate notifications. The generator wakes up on a schedule determined by the value of the <QuantumDuration> element in the <ApplicationSettings> node of the application definition file (ADF). If the quantum duration is 60 seconds, there can be a 60-second delay before an event batch is used to create notifications.
  • The generator must match events to subscriptions in order to generate notifications. The matching is performed by one or more Transact-SQL queries. The performance of these queries determines the latency involved with generating notifications. In general, the more events and subscriptions evaluated at one time, the longer this process takes. Optimized rules and well-chosen indexes can reduce matching latency.
  • The distributor must "wake up" to distribute notifications. The distributor wakes up on a schedule determined by the value of the <QuantumDuration> element in the <Distributor> node of the ADF. As with the generator, if the quantum duration is 60 seconds, there can be a 60-second delay before a notification batch is processed by the distributor.
  • The distributor must format notifications and package them for delivery. The formatting is performed by a content formatter object. Complex formatting can take longer to perform than simple formatting, and sending the formatted notification to a delivery service also takes some time. For example, posting a notification to an HTTP server can take up to 30 seconds.

After the distributor sends the notification to the delivery service, such as a Simple Mail Transfer Protocol (SMTP) server, Notification Server has no control over the latency of sending notifications.

Each sample application has several batch files in a BuildScripts folder. What are these files?

Answer

The batch files in the Samples\sample_name\AppDefinition\BuildScripts directory run project-related commands. When you deploy a Notification Services sample using Microsoft Visual Studio® .NET, you right-click a project and select commands, like Build and Rebuild. These commands run the batch files.

Microsoft recommends that you do not use these scripts when deploying an instance of Notification Services to production servers. For information about production deployment, see Deploying an Instance.

Do I need to install Microsoft Visual Studio .NET to develop Notification Services applications?

Answer

No, Visual Studio .NET is not required, but it can make development easier.

If you are developing an application that uses the standard event providers and content formatters, you can build the application by creating an XML application definition file (ADF), and then defining an instance to host the application by creating an XML configuration file. You can create these XML files using any text or XML editor.

If you are building custom event providers and content formatters, you can use the Microsoft Visual Studio .NET development environment to create these objects. However, you are not required to use Visual Studio .NET. You can use any text editor to write the code; you must install the Microsoft .NET Framework SDK and compile your code using the associated compiler.

The samples are packaged as Visual Studio .NET solutions, but you do not need to use Visual Studio to run them. The scripts to build and run the samples can be run from a command prompt. For more information, see Programming Sample Structure.

If you install the Notification Services documentation after installing Visual Studio .NET, the documentation is integrated into the Visual Studio .NET Help system. This provides context-sensitive help to the Notification Services documentation.

Comparing the hosted event provider with the independent event provider, what benefit does one provider have over the other?

Answer

Implementing a hosted provider usually means less development work because the Notification Services instance loads the Notification Services API and maintains the schedule used to activate the event provider. Hosted providers can also be enabled and disabled like other Notification Services components and service.

Independent event providers are useful if you have existing infrastructure that can submit events, such as a customer relations management application or a Web application. Independent event providers are listed in the application definition file (ADF) only so that they can be referenced by subscription classes.

I already have a subscription management application written in unmanaged code. Can I call your API from my application?

Answer

Yes. Notification Services provides COM objects that can be called from Microsoft Visual Basic® or Microsoft Visual C++®. For more information, see COM Interop with Notification Services.

See Also

Notification Services Troubleshooting


Notification Services Troubleshooting

Microsoft has compiled the following list of issues and solutions encountered by users of Notification Services.

Installation Troubleshooting

One or more components are not available on the Custom Setup page.

Solution

The Setup program analyzes the server to determine whether all prerequisites been installed for each component. If the prerequisites for a component are not installed, you cannot install the component.

For more information about software prerequisites, see Hardware and Software Requirements.

The database components are not available, even though the prerequisite software for the database components is installed.

Solution

To install the database components, run Setup on the server where SQL Server 2000 is installed. Setup must run locally to install extended stored procedures to the SQL Server Binn directory and register the extended stored procedures. You must start the SQL Server instance before installing database components to that instance. Notification Services supports only the Developer, Standard, and Enterprise editions of SQL Server 2000.

Deployment and Administration Troubleshooting

Running NSControl Create fails due to timeout error.

Solution

The NSControl Create command has time limits for each of its operations. The database creation operation tends to take more time than the other operations; the time limit for this operation is 10 minutes, which is normally more than adequate. However, if the <FileSpec> elements in your ADF and configuration file specify very large database sizes (that is, several gigabytes), NSControl Create still might time out; if it does, the following error message is displayed:

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

Caught exception: Fail to run NS_directory\bin\nscontrol.exe create -in config_file arguments

To successfully run NSControl Create, you must reduce the database file sizes in the ADF and configuration file and then run NSControl Create again. You then can increase the sizes of the database files using SQL Server Enterprise Manager or Transact-SQL code.

Running NSControl Update fails.

Solution

The NSControl Update command might fail before completion because of errors in the ADF or the configuration file. Therefore, before running NSControl Update, validate all ADFs and configuration files to reduce the possibility of this error occurring. If an error does occur, fix the file and then run NSControl Update again.

It is also possible for NSControl Update to leave the instance in an inconsistent state after a failure. The best practice is to always back up the instance and application databases before running NSControl Update, and restore the databases if NSControl Update fails.

If you change subscription class metadata in the ADF, NSControl Update renames the existing subscription class table, NSsubscription_classSubscriptions, to NSsubscription_classSubscriptionsOld to save the subscription data. If you later update the same subscription class, when NSControl Update attempts to rename the table, the rename fails if NSsubscription_classSubscriptionsOld still exists. To resolve this problem, rename or delete NSsubscription_classSubscriptionsOld.

For more information, see NSControl Update.

The NS$instance_name service does not start.

Solutions

If the NS$instance_name service does not start, the service password might be incorrect, the instance name you are trying to start might not be an exact match for the Notification Services instance name, or the Windows user account under which the service has been configured to run might not have permissions to log on as a service. Try the following to resolve the problem:
  • Reset the password. When you use the Notification Services commands to configure a service password, and the password contains special characters or was entered incorrectly, the NS$instance_name service will not start.

    To resolve this error, update the password using the Microsoft Windows Services application:

    1. In Control Panel, open Administrative Tools.
    2. Open Services.
    3. Right-click the NS$instance_name service (instance_name represents the name of the Notification Services instance), and then click Properties.
    4. On the Log On tab, type your password in the Password and Confirm Password boxes, and then click OK.
    5. Right-click the service, and then click Start.

    If the password is a valid for a domain or local account, the service should start. If the account does not have permissions to log on as a service, resetting it from the Services application will grant it the appropriate permissions.

  • Start the service from the Services application. When you start the service using the Net Start command, the characters used at the command line must match the Unicode characters used in the configuration file. If the characters do not match, the instance cannot start.

    To resolve this error, start the service using the Windows Services application:

    1. In Control Panel, open Administrative Tools.
    2. Open Services.
    3. Right-click the NS$instance_name service (instance_name represents the name of the Notification Services instance), and then click Start.

No errors appear in the event log.

Solution

If the NS$instance_name service does not start, but there are no errors in the application log to indicate the cause, your application log may be full. To reconfigure the application log, do the following:
  1. In Control Panel, open Administrative Tools.
  2. Open Event Viewer.
  3. Right-click Application, and then click Properties.
  4. Do one or both of the following:
    • Increase the Maximum log size value.
    • Under When maximum log size is reached, select Overwrite events as needed.

Unexpected errors appear in the event log.

Solution

If you receive unexpected errors in Event Viewer, try restarting the service associated with the instance of Notification Services.

For example, if you remove an application from an instance while the service is running, and you then see errors in the event log for the application you removed, restarting the service should stop these errors from appearing.

For more information, see Starting and Stopping a Service.

SSL security errors occur.

Solution

If you receive SSL security errors in the event log when creating an instance or running the NS$instance_name service, Notification Services might not be able to connect to SQL Server.

To resolve this problem, obtain the latest service pack for SQL Server 2000. For more information, search for Knowledge Base article Q302409 at the Microsoft Product Support Services Web site.

Internal query processor errors occur.

Solution

If you receive the following error in the event log, obtain the latest service pack for SQL Server 2000.

Internal Query Processor Error: The query processor could not produce a query plan.

Deadlock errors occur under stress.

Solution

When running under high volumes, you might receive the following messages in the application event log:

Notification Services Message: "The view of the event class could not be materialized."

SQL Server Message: "Transaction {} was deadlocked on {} resources with another process and has been chosen as the deadlock victim. Rerun the transaction."

The fix for this error requires either a service pack update or a hotfix. For more information, search for Knowledge Base article Q322868 at the Microsoft Product Support Services Web site.

Old events are reused, or disabled subscriptions receive notifications.

Solution

If you write subscription rules that access the events and subscriptions tables directly, obsolete events and disabled subscriptions might be used to generate notifications.

Writing queries that directly use the events, notifications, subscriptions tables is not recommended. Instead, write your queries using the class names defined in the application definition file (ADF).

For example, if the name of an event class defined in the ADF is StockEvent, use the table name StockEvent in your subscription rule, not the actual table name in the database (which would be NSStockEventEvents).

Notification Services creates temporary tables with the current set of events, notifications, and subscriptions. The static tables in the database contain obsolete data that will be removed by the vacuuming process.

For more information about writing subscription rules, see Subscription Rules.

Event Collection Troubleshooting

FileSystemWatcher event provider fails.

Solution

The FileSystemWatcher event provider might fail if the performance counters on the server become corrupted. If you receive the following error in the event log, a performance counter is corrupted:

Event ID: 2980

Description: The FileSystemWatcher event provider failed to submit events.

Description: Object reference not set to an instance of an object.

If a performance counter is corrupted, the counter will not return values. To attempt to resolve the corruption, do the following:

  1. If the NS$instance_name service is running, stop the service.
  2. Close any applications that query the Notification Service performance counters, such as System Monitor.
  3. Unregister the instance using NSControl Unregister.
  4. Re-register the instance using NSControl Register.

This re-creates the performance counters for the instance. You might need to run these steps multiple times.

Delivery Troubleshooting

Generic delivery errors occur.

Solution

Some delivery errors can in fact be configuration errors. For example, if you incorrectly configure an SMTP delivery channel, when Notification Services tries to deliver a notification using the delivery channel you might receive a message such as this:

SMTP Delivery Notification Generic Error

If you receive several errors like this, verify that your delivery channels are configured correctly. For more information, see Standard Delivery Protocols.

SMTP delivery fails.

Solution

When using the Internet Information Services (IIS) SMTP protocol, Notification Services must look in an IIS directory to determine where to deliver the notifications. Only administrators have privileges to access this information.

To use the IIS SMTP delivery protocol, which is used by the Flight, Weather, and Realtor sample applications, the account that the NS$instance_name service runs under must be a member of the Administrators group.

Distributor times out.

Solution

If you receive various timeout errors in the event log, the distributor logging level might be too high. This typically occurs only when the database system is processing high volumes of notifications, and cannot handle both the distribution and logging tasks.

To resolve the problem, set the values within the <DistributorLogging> node of the ADF to false. For more information, see Defining the <DistributorLogging> Node.

Notifications are not delivered.

Solution

If notifications are not being sent from your application, check the following:
  • Are the notifications being generated?
    Run the NSDiagnosticNotificationClass stored procedure in the instance database to verify that notifications are being generated. Look in the NotificationsGenerated column for the interval at which you expected them to be generated. If there are no notifications it is possible that there are no events or no subscriptions, or that the subscription class match rules do not insert any notifications into the notification class function. For more information about the Notify function, see Using Notification Functions.
  • Are there any events available?
    Run the NSDiagnosticEventClass stored procedure in the instance database. Look in the EventBatchesCollectedCount column to see if events arrived when you expected.
  • Are scheduled subscriptions properly scheduled?
    Run the NSScheduledSubscriptionList and NSScheduledSubscriptionDetails stored procedures in the application database to view subscription details.
  • Are notifications failing?
    Run the NSDiagnosticFailedNotifications stored procedure to check for failed notifications.
  • Are the notifications going to the correct delivery channel?
    Verify that the ADF defines the correct protocols for the notification class and that the subscriptions added to your application are using the correct delivery channel.
  • Are your delivery channels functional?
    Run the NSDiagnosticDeliveryChannel report to see if the delivery channels are operational.
  • Do the subscriber devices referred to in the notifications exist?
    When calling the Notify function in your match rule, you must pass a subscriber ID and a device name. You must create a subscriber device for this subscriber ID with this device name in your subscription management application using the SubscriberDevice class.

These methods should help you determine why notifications are not being delivered.

Web Application Troubleshooting

Cannot access SQL Server from sample application ASP.NET pages.

Solution

If you receive the following error from a Microsoft ASP.NET Web page, the account used by the Web application has not been granted access to SQL Server:

Error when loading ASP.NET subscription management page: System.Data.SqlClient.SqlException: Login failed for user 'domain\account'

To resolve this problem, do the following:

  1. Grant login access to a domain account to be used by the subscription management application. In SQL Query Analyzer, run EXEC sp_grantlogin 'domain\username'.
  2. Edit the Samples\SetGlobalVars.cmd file and make sure the SubscriptionApplicationAccount value is set to the domain account to which you granted access.
  3. Run Sample\AppDefinition\BuildScripts\GrantPermissions.cmd.

Error when loading ASP.NET subscription management page.

Solution

If you receive the following error from an ASP.NET Web page, the account used by the Web application has not been added to the NSSubscriberAdmin and NSEventProvider roles in the instance and application databases:

System.Data.SqlClient.SqlException: Cannot open database requested in login 'database'. Login fails. Login failed for user 'domain\account'.

To resolve this problem, do the following:

  1. Edit the Samples\SetGlobalVars.cmd file and make sure the SubscriptionApplicationAccount value is set to the domain account to which you granted access.
  2. Run Sample\AppDefinition\BuildScripts\GrantPermissions.cmd.

See Also

Event Messages

Frequently Asked Questions


Event Messages

Notification Services logs event messages to the application log, which is accessible from Microsoft Windows® Event Viewer. These messages can assist you when troubleshooting system errors and performance problems.

Even if you are not currently having problems with Notification Services, you should check the event log periodically. Checking the log on a regular schedule can help avoid significant system problems. For example, it is best to know as soon as possible if events are not being collected or notifications are not being distributed.

The topics in this section provide information on configuring event logging, events created by Notification Services, and obtaining more information about a particular event message. They are described in the following table.

Topic | Description
Event Logging Overview | Provides instructions for configuring logging levels for the NS$instance_name service and the distributor.
Configuring Notification Services Event Logging | Describes how to change the logging levels for Notification Services components.
Viewing Supplemental Event Message Information | Explains where to look for additional information about Notification Services event messages.

For additional information about using Event Viewer, open Event Viewer Help from the Event Viewer application.

See Also

Performance Monitoring and Reporting


Event Logging Overview

Notification Services logs event messages to the Windows application log. You can use both of these event messages to monitor the activity of an instance and its applications.

Managing the Event Log

Depending on the logging levels you configure, the application event log can grow very quickly. For example, if you log all Notification Services events and log all notification deliveries for an application that sends thousands of notifications per hour, an unmanaged event log can quickly fill up a disk.

To manage the event log, consider the following recommendations:

  • For applications on production servers (servers that are not devoted to development or testing), log only the events required by your applications, such as error messages that can help you troubleshoot application problems. Some applications might require a higher logging level because of service agreements for notification delivery; these applications require more disk space for logging.
  • If a system is performing many writes to disk to populate the event log, application performance might diminish. This is especially true for the system that hosts the Notification Services databases, since notification generation is a disk-intensive process.
  • Configure a reasonable maximum event log size and set the overwrite option to match your logging needs. For example, if you do not need events after three days, let the event log clear those events by choosing to overwrite events older than three days.
  • Use filtering to show events from specific sources, such as a Notification Services instance. You can create a new view of a log, and then define a filter for that view that shows only the events of interest. You can then export the events in the view to one of the supported formats, such as a comma-delimited text file.
  • In Microsoft Windows XP, use the Eventquery command prompt utility to manage event logs from the command line. This enables you to schedule tasks to display or save events that match specific criteria. For example, you could run the following command to save all events from the NS$StockInstance event source to a text file:
    Eventquery /l Application /fi "Source eq NS$StockInstance" >C:\Logs\NSLog.txt

    In Windows 2000, the Eventlog.pl utility provide similar functionality. For more information, search for article Q318763 in the Microsoft Knowledge Base.

For additional information about using event logs, open Event Viewer Help from Event Viewer.


Configuring Notification Services Event Logging

Most logging for Notification Services is controlled at the instance level. Each instance has a file named NSservice.exe.config. Within this file are XML elements that control logging levels for various areas of Notification Services operation, such as the NSControl utility, the NS$instance_name service, and Notification Services components. Each of these areas is represented by one XML element.

To configure logging levels for these areas of Notification Services, edit the value attribute of the XML elements in this file.

To edit the NSservice.exe.config file

  1. Open the Bin folder of the Notification Services installation.

    The default installation folder is Program Files\Microsoft SQL Server Notification Services\vn.n.n.n\Bin.

  2. Open the NSservice.exe.config file.

    You can edit this file in the Microsoft Visual Studio® XML editor or in a text editor, such as Notepad.

  3. For each of the items in the <switches> node, set the logging level by changing the value attribute.

    In the following example, the LogAdministrative logging level is set to 3, which turns on logging for error, warning, and informational events for the administrative components:

    <add name="LogAdministrative" value="3"/>

    Initially, each logging option is set to 2, which turns on logging for error and warning messages only.

  4. Restart the NS$instance_name service to apply the logging changes.
NSservice.exe.config Logging Elements

The NSservice.exe.config file contains elements that control event logging from various components of Notification Services; they are listed in the following table.

Element name | Logging category
LogAdministrative | NSControl command events
LogDistributor | Distributor events
LogEventProvider | Event provider events
LogEventCollector | Event collector object events
LogGenerator | Generator events
LogPerformanceMonitor | Performance object events
LogService | NS$instance_name service events
LogVacuumer | Vacuumer events
LogOther | Events for all other components, such as the XsltFormatter and the standard delivery protocols
Logging Level Values

Logging levels determine which types of events are written to the event log. You can control the logging level by setting the value attribute to one of the following values.

Value | Description
0 | Off
1 | Error messages only
2 | Error and warning messages
3 | Error, warning, and informational messages
4 | Verbose logging

See Also

Performance Monitoring and Reporting


Viewing Supplemental Event Message Information

Notification Services event message text and supporting information is not provided in Notification Services Books Online. Instead Notification Services uses the Web to provide updated information about event messages.

In Microsoft Windows XP, each event message in Windows Event Viewer contains a link to a Microsoft Web page that contains additional information about the message.

To locate a Web page for an event message

  1. In Event Viewer, double-click the event message.
  2. Scroll to the bottom of the Description box.
  3. After the "For more information, see Help and Support Center at" text, click the Web link.

Not all event messages have additional information on the Web. The Web pages are updated as Microsoft learns more about which event messages benefit from more information.

See Also

Performance Monitoring and Reporting


Glossary

Term | Definition
.NET Framework | An environment for building, deploying, and running XML Web services and other applications. The Microsoft® .NET Framework has two parts: the common language runtime and the class libraries, which include ASP.NET, Enterprise Services, ADO.NET, and Microsoft Windows® Forms.
acknowledged delivery | A positive confirmation from either the system or the recipient to Microsoft SQL Server™ Notification Services that a notification has been delivered to the intended recipient.
ADF | See definition for application definition file.
application | An individual solution for matching events with subscriptions and then formatting and delivering the resulting notifications.
application database | The database that stores user and system data for one application. The application database contains the events, subscriptions, and notifications for the application. It also contains system meta data including the schemas for the events, subscriptions, and notifications for the application; and the match rules for the application.
application definition file (ADF) | An XML file that fully describes a single Notification Services application. The ADF file contains the schemas for the events, subscriptions, and notifications; the rules for matching events with subscriptions; and may provide the name of the XSLT file used to format generated notifications.
argument | An initializing value passed to those components of Notification Services that can accept it, such as stored procedures, commands, event providers, delivery protocols, and content formatters.
batch | A set of data processed as a group. An event batch is a set of events that are submitted to Notification Services at one time. A notification batch is a set of notifications that are generated by one firing of a match rule.
chronicle | A table that stores state information for a single application. An example is an event chronicle, which can store event data for use with scheduled subscriptions.
component | Within Notification Services, a component is a major element of the Notification Services platform such as the event collector, the generator, the distributor, or the vacuumer.
computed field | A value in a formatted notification that has been computed using a Transact-SQL expression.
configuration file | An XML file that contains the configuration data for an instance of Notification Services. The configuration file specifies the applications that are hosted by the instance, the name of the database server, the database properties, and the delivery protocols and delivery channels.
content formatter | The part of the distributor that turns raw notification data into readable messages.
custom | Created by an application developer, as opposed to supplied as a standard part of Notification Services.
delivery channel | A pipeline between a distributor and a delivery service.
delivery channel instance | A single occurrence of a delivery channel. For example, an instance of Notification Services can use two File delivery channels; each File delivery channel instance is one use of the File delivery channel.
delivery channel type | The protocol for a delivery channel, such as Simple Mail Transfer Protocol (SMTP) or File.
delivery failure | A notification that does not reach the intended recipient.
delivery protocol | The set of communication rules used to route notification messages to external delivery systems.
destination device | A delivery location (hardware or application) to which notifications are sent.
device | A hardware or software component that can accept output from Notification Services. A hardware example is a cell phone; a software example is Microsoft Outlook®.
device name | A user-defined description of a particular device, used in conjunction with the subscriber ID to identify a specific subscriber device. A device name must be provided to the notification function as an input parameter.
device type | A value from a developer-defined list that specifies the types of devices that a given application will support. A device type corresponds to a single delivery channel.
digest delivery | A method of sending notifications that combines multiple notifications within a batch and sends the resulting message to a subscriber.
disable | To turn off a component or collection of components. A disabled component does not process data or perform other activities.
distributor | The component of Notification Services that formats notifications and sends them to external delivery services.
enable | To turn on a component or collection of components.
event | A noteworthy happening, such as a score change in a sporting event or a price change for a stock.
event batch | A set of one or more events submitted to Notification Services at one time.
event chronicle | A table that stores event state information.
event chronicle rule | One or more Transact-SQL statements that manage the data in the event chronicle. This type of rule is fired each time an event batch for the rule's event class is submitted to the system.
event class | A single class defined by one <EventClass> node in an application definition file. An <EventClass> node defines the structure and properties of a particular type of event.
Event class | A class in the Notification Services API that provides a way to encapsulate a single event.
event collection stored procedures | System-generated stored procedures that an application can call to submit events to the event table in the application database. Notification Services generates these stored procedures for each event class defined in the application data file. These stored procedures can be called from SQL Server triggers or other SQL Server stored procedures.
EventCollector class | A class in the Notification Services API that accepts Event objects as input, batches them, and then submits them to the application database.
event-driven subscription | A subscription in which notifications are generated as soon as event data arrives that matches the subscription.
EventLoader class | A class in the Notification Services API that accepts XML events and writes them to the application database.
event provider | A component that collects event data from one or more event sources and submits the events to the event tables in the application database.
event schema | A SQL-annotated XML Schema definition language (XSD) schema that maps event data to an event schema defined in the application definition file. Used by the EventLoader class.
event source | The point of origin of an event.
event table | A table in the application database that stores event data. It is automatically generated based on information in the application definition file each time NSControl Create or NSControl Update is run. Each row in the table is an event instance.
external delivery system | A system, such as Microsoft Exchange Server, that delivers formatted notifications to destination devices.
file system watcher event provider | An event provider supplied by Notification Services that monitors a directory for the arrival of XML event files, extracts XML event data from these files, and submits these events to the event table in the application database. The file system watcher uses the event loader class to submit events.
generator | The component of Notification Services that matches events to subscriptions and produces notifications.
hosted event provider | An event provider managed by the Notification Services event provider host that gathers event data from one or more event sources and submits the events to an event table in the application database.
independent event provider | An event provider running outside the process environment of Notification Services that gathers event data from one or more event sources and submits the events to an event table in the application database.
instance | A single, named configuration of Notification Services that hosts one or more notification applications. The applications share a set of subscribers and use the same database system, protocols, delivery channels, and version of Notification Services. An administrator defines an instance in a configuration file. The NS$instance_name service runs an instance of Notification Services.
instance database | The instance_name NSMain database, which stores instance-specific data, including delivery channel and subscriber information.
locale | A code that denotes a language and a country/region. For example, "fr-CA" represents the French Canadian locale; "ja-JP" represents the Japanese Japan locale. The content formatter can use the locale to format a notification in the culturally appropriate way.
message | A formatted notification that has been processed by the distributor for transmission by the delivery protocol.
multicast delivery | A method for delivering notifications that formats a notification once and sends the resulting message to multiple subscribers.
notification | The data sent to the subscriber as the result of a subscription. For event-triggered subscriptions, Notification Services produces a notification each time an input event matches the subscription. For scheduled subscriptions, Notification Services might produce a notification each time the subscription is scheduled, if an event matches the subscription.
notification class | A single class defined by one <NotificationClass> node in the application definition file. A <NotificationClass> node defines the structure and properties of a particular type of notification.
notification delivery | The transmission of a notification to a recipient.
notification formatting | The transformation of notification data from its unformatted to its formatted state. The formatted notification is delivered to the recipient.
notification function | The function generated by Notification Services that is called in a notification generation rule to write a notification to the notifications table. Notification Services generates a NotificationClassName Notify() function for each notification class defined in the application definition file.
notification table | A table that stores unformatted notification data. Notification Services creates a notification table for each notification class defined in the application definition file.
NS$instance_name | The name of the Windows service that runs an instance of Notification Services. instance_name is a placeholder for the actual instance name, such as NS$StockInstance.
NSControl | The command prompt utility for administering Notification Services instances and applications.
parameter | A value specified in the application definition file or the configuration file that is used to provide a value for another element.
platform | The Notification Services engine and the Notification Services SQL Server databases. The platform stores system data and provides functions for notification generation and distribution.
protocol | A set of rules that systems use when they communicate. Examples are SMTP and HTTP. Each protocol has specific header and body formatting requirements and a message exchange model, which are addressed by Notification Services via the delivery protocol component.
provider host | The component of Notification Services that hosts event providers within the Notification Services engine. At the application level, the provider host is optional, since event providers can run independently of Notification Services.
quantum | A period of time defined in the application definition file that sets the timing for generator firing. The plural form of quantum is quanta.
raw notification data | The data that is written to the notification table. It consists of fields of data that have not yet been formatted for delivery.
register | To configure a computer to be a part of a Notification Services instance. NSControl Register creates the NS$instance_name service, configures security for the service, and creates performance counters for the instance.
rule | One or more Transact-SQL statements used to generate notifications or to maintain data in chronicle tables.
rule firing | The process of executing one of the application rules (event chronicle rules, subscription event rules, and subscription scheduled rules) defined in the application definition file. The rules are Transact-SQL statements that process notification data.
scheduled subscription | A type of subscription in which notifications are generated according to a schedule.
SQL Server event provider | A stored procedure-based event provider that gathers data from SQL Server and submits it to the event table using the standard Notification Services event collection stored procedures.
standard | Supplied as a standard part of Notification Services, as opposed to created by an application developer (custom).
subscribe | To enroll in an instance of Notification Services and create a subscription for one or more applications hosted by that instance.
subscriber | The person or process to which notifications are delivered.
Subscriber class | A class in the Notification Services API used for submitting subscriber information.
SubscriberDevice class | A class in the Notification Services API used for submitting subscriber device information.
subscriber locale | An identifier that identifies the language and country/region of a subscriber, such as "en-US." It is often part of subscription data, but this is not required; such information can be retrieved from other sources. The subscriber locale must be provided to the notification function as an input parameter.
subscription | An application-specific request to receive notifications.
subscription chronicle | The table that stores subscription state information.
subscription class | A single class defined by the <SubscriptionClass> node in an application definition file. The <SubscriptionClass> node defines the structure and properties of a particular type of subscription.
Subscription class | A class in the Notification Services API used for submitting subscription information.
subscription event rule | A rule that processes information for event-driven subscriptions. It may contain notification generation rules or chronicle update rules. This type of rule is fired each time a corresponding batch of events is submitted.
subscription management application | The application that subscribers use to submit and manage their subscriptions. For each instance or application, a developer can create a custom interface for managing subscriptions. This application must use Notification Services APIs to submit data to the system.
subscription scheduled rule | One or more Transact-SQL statements that process information for scheduled subscriptions. The rule can contain notification generation rules or chronicle update rules. This type of rule is fired each time a scheduled subscription is due for processing.
successful delivery | A notification that has been delivered to the intended recipient.
time-out (adj, n); time out (v) | A time limit for a process, such as firing a rule; also the action of reaching the time limit. Multiple processes in Notification Services can time out, such as the rules, the vacuumer, and the delivery service.
vacuumer | The component that removes expired data from Notification Services tables.
vacuuming | The process of clearing obsolete data from a Notification Services application according to a schedule defined in the application definition file.
validation, semantic | The process of confirming that the elements of an XML file are logically valid. For example, semantic validation might confirm that a value is numeric and within a specified range.
validation, syntactic | The process of confirming that an XML file conforms to its schema.
work item | The unit of work a distributor uses. One work item constitutes all the notifications in a single batch that use the same delivery channel.
XSL; XSLT | Extensible Stylesheet Language (XSL) and Extensible Stylesheet Language transformation (XSLT).