Notification Services—Creating a Notification Services Application and Service
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Creating a Notification Services Application and Service
This section creates a complete Notification Services application that creates file and
email notifications based on changes in a stock price. For the purpose of this example,
the stock price information is limited to a stock ticker symbol and price. Two
subscribers are created—one that is notified by entries in a text file and one that is
notified using email. Each of the two users monitors a single stock—ticker symbols
ABC and DEF.
This section shows the application that creates the StockWatch Notification Services
application and adds two subscribers and a subscription for each. Subsequent sections
discuss the different parts of the application in detail.
Follow these steps to create the StockWatch Notification Services application with two subscribers and a subscription for each, start the service, and generate notifications:
1. Create a Visual Studio 2005 C# console application in the C:\PSS2005 directory. Name the project NotificationServices.
2. Add the following references to the project:
-
Microsoft.SqlServer.ConnectionInfo
-
Microsoft.SqlServer.NotificationServices
-
Microsoft.SqlServer.Smo
-
3. Replace the code in Program.cs with the code in Example 18-1. This code is explained in detail throughout the rest of this chapter.
Example 18-1. Notification Services example
using System; using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlServer.Management.Nmo; using ns = Microsoft.SqlServer.NotificationServices; class Program { private static Instance nsi; private static Application a; private const string baseDirectoryPath = @"C:\PSS2005\NotificationServices"; private const string nsServer = "NSServerName"; private const string serviceUserName = "NSUSerName"; private const string servicePassword = "NSPassword"; static void Main(string[] args) { Server server = new Server("(local)"); // create a new instance NotificationServices ns = server.NotificationServices; nsi = new Instance(ns, "StockWatch"); CreateDeliveryChannel( ); // create a new application in the StockWatch instance a = new Application(nsi, "StockWatchApp"); a.BaseDirectoryPath = baseDirectoryPath; CreateEventClass( ); CreateSubscriptionClass( ); CreateNotificationClass( ); CreateHostedEventProvider( ); CreateGenerator( ); CreateDistributor( ); CreateVacuumSchedule( ); a.QuantumDuration = new TimeSpan(0, 0, 15); a.PerformanceQueryInterval = new TimeSpan(0, 0, 5); a.SubscriptionQuantumLimit = 1; a.ChronicleQuantumLimit = 1; a.VacuumRetentionAge = new TimeSpan(0, 0, 1); nsi.Applications.Add(a); Console.WriteLine("Added application."); nsi.Create( ); nsi.RegisterLocal(serviceUserName, servicePassword); nsi.Enable( ); Console.WriteLine("Application enabled." + Environment.NewLine); CreateSubscriber( ); CreateSubscription( ); Console.WriteLine(Environment.NewLine + "Press any key to continue."); Console.ReadKey( ); } private static void CreateDeliveryChannel( ) { DeliveryChannelArgument dca; // add file delivery channel DeliveryChannel dcFile = new DeliveryChannel(nsi, "StockWatchFileDeliveryChannel"); dcFile.ProtocolName = "File"; dca = new DeliveryChannelArgument(dcFile, "FileName"); dca.Value = baseDirectoryPath + @"\Notifications\FileNotifications.txt"; dcFile.DeliveryChannelArguments.Add(dca); nsi.DeliveryChannels.Add(dcFile); Console.WriteLine("Added delivery channel: " + dcFile.Name); //// add email delivery channel DeliveryChannel dcEmail = new DeliveryChannel(nsi, "StockWatchEmailDeliveryChannel"); dcEmail.ProtocolName = "SMTP"; nsi.DeliveryChannels.Add(dcEmail); Console.WriteLine("Added delivery channel: " + dcEmail.Name); } private static void CreateEventClass( ) { EventClass ec = new EventClass(a, "StockWatchEvents"); EventField ef; ef = new EventField(ec, "Symbol"); ef.Type = "nvarchar(6)"; ec.EventFields.Add(ef); ef = new EventField(ec, "Price"); ef.Type = "float"; ec.EventFields.Add(ef); a.EventClasses.Add(ec); Console.WriteLine("Added event class: " + ec.Name); } private static void CreateSubscriptionClass( ) { SubscriptionClass sc = new SubscriptionClass(a, "StockWatchSubscriptions"); SubscriptionField sf; sf = new SubscriptionField(sc, "DeviceName"); sf.Type = "nvarchar(255)"; sc.SubscriptionFields.Add(sf); sf = new SubscriptionField(sc, "SubscriberLocale"); sf.Type = "nvarchar(10)"; sc.SubscriptionFields.Add(sf); sf = new SubscriptionField(sc, "Symbol"); sf.Type = "nvarchar(6)"; sc.SubscriptionFields.Add(sf); sf = new SubscriptionField(sc, "Price"); sf.Type = "float"; sc.SubscriptionFields.Add(sf); SubscriptionEventRule ser = new SubscriptionEventRule(sc, "StockWatchSubscriptionsEventRule"); ser.Action = @"INSERT INTO StockWatchNotifications (" + "SubscriberId, DeviceName, SubscriberLocale, Symbol, Price) " + "SELECT s.SubscriberId, s.DeviceName, s.SubscriberLocale, " + "e.Symbol, e.Price " + "FROM StockWatchEvents e, StockWatchSubscriptions s " + "WHERE e.Symbol = s.Symbol"; ser.EventClassName = "StockWatchEvents"; sc.SubscriptionEventRules.Add(ser); a.SubscriptionClasses.Add(sc); Console.WriteLine("Added subscription class: " + sc.Name); } private static void CreateNotificationClass( ) { NotificationClass nc = new NotificationClass (a, "StockWatchNotifications"); NotificationField nf; nf = new NotificationField(nc, "Symbol"); nf.Type = "nvarchar(6)"; nc.NotificationFields.Add(nf); nf = new NotificationField(nc, "Price"); nf.Type = "float"; nc.NotificationFields.Add(nf); ContentFormatter cf = new ContentFormatter(nc, "XsltFormatter"); ContentFormatterArgument cfa; cfa = new ContentFormatterArgument(cf, "XsltBaseDirectoryPath"); cfa.Value = a.BaseDirectoryPath + @"\AppDefinition"; cf.ContentFormatterArguments.Add(cfa); cfa = new ContentFormatterArgument(cf, "XsltFileName"); cfa.Value = "StockWatch.xslt"; cf.ContentFormatterArguments.Add(cfa); nc.ContentFormatter = cf; nc.DigestDelivery = true; ProtocolField pf; // add file notification class protocol NotificationClassProtocol ncpFile = new NotificationClassProtocol(nc, "File"); pf = new ProtocolField(ncpFile, "Symbol"); pf.FieldReference = "Symbol"; ncpFile.ProtocolFields.Add(pf); pf = new ProtocolField(ncpFile, "Price"); pf.FieldReference = "Price"; ncpFile.ProtocolFields.Add(pf); nc.NotificationClassProtocols.Add(ncpFile); // add email notification class protocol NotificationClassProtocol ncpEmail = new NotificationClassProtocol(nc, "SMTP"); pf = new ProtocolField(ncpEmail, "Subject"); pf.SqlExpression = "'Stock watch: ' + CONVERT(nvarchar(30), GETDATE( ))"; ncpEmail.ProtocolFields.Add(pf); pf = new ProtocolField(ncpEmail, "BodyFormat"); pf.SqlExpression = "'html'"; ncpEmail.ProtocolFields.Add(pf); pf = new ProtocolField(ncpEmail, "From"); pf.SqlExpression = "'notification@StockWatchService.com'"; ncpEmail.ProtocolFields.Add(pf); pf = new ProtocolField(ncpEmail, "Priority"); pf.SqlExpression = "'Normal'"; ncpEmail.ProtocolFields.Add(pf); pf = new ProtocolField(ncpEmail, "To"); pf.SqlExpression = "DeviceAddress"; ncpEmail.ProtocolFields.Add(pf); nc.NotificationClassProtocols.Add(ncpEmail); nc.ExpirationAge = new TimeSpan(1, 0, 0); a.NotificationClasses.Add(nc); Console.WriteLine("Added notification class: " + nc.Name); } private static void CreateHostedEventProvider( ) { HostedEventProvider hep = new HostedEventProvider(a, "StockWatchHEP"); hep.ClassName = "FileSystemWatcherProvider"; hep.SystemName = nsServer; HostedEventProviderArgument hepa; hepa = new HostedEventProviderArgument(hep, "WatchDirectory"); hepa.Value = baseDirectoryPath + @"\Events"; hep.HostedEventProviderArguments.Add(hepa); hepa = new HostedEventProviderArgument(hep, "SchemaFile"); hepa.Value = baseDirectoryPath + @"\AppDefinition\EventsSchema.xsd"; hep.HostedEventProviderArguments.Add(hepa); hepa = new HostedEventProviderArgument(hep, "EventClassName"); hepa.Value = "StockWatchEvents"; hep.HostedEventProviderArguments.Add(hepa); a.HostedEventProviders.Add(hep); } private static void CreateGenerator( ) { // create a new generator for the application Generator g = new Generator(a, "StockWatchGenerator"); g.SystemName = nsServer; a.Generator = g; Console.WriteLine("Created generator: " + g.Name); } private static void CreateDistributor( ) { Distributor d = new Distributor(a, "StockWatchDistributor"); d.SystemName = nsServer; d.QuantumDuration = new TimeSpan(0, 0, 15); a.Distributors.Add(d); Console.WriteLine("Added distributor: " + d.Name); } private static void CreateVacuumSchedule( ) { VacuumSchedule vs = new VacuumSchedule(a, "StockWatchVacuumSchedule"); vs.StartTime = new TimeSpan(0, 0, 0); a.VacuumSchedules.Add(vs); Console.WriteLine("Added vacuum schedule: " + vs.Name); } private static void CreateSubscriber( ) { ns.NSInstance swnsi = new ns.NSInstance("StockWatch"); ns.Subscriber s; ns.SubscriberDevice sd; // create a subscriber s = new ns.Subscriber(swnsi); s.SubscriberId = @"KristinHamilton"; s.Add( ); Console.WriteLine("Added subscriber: " + s.SubscriberId); // create a file subscriber device sd = new ns.SubscriberDevice( ); sd.Initialize(swnsi); sd.DeviceName = "StockWatchSubscriberDevice"; sd.SubscriberId = "KristinHamilton"; sd.DeviceTypeName = "File"; sd.DeviceAddress = "KristinH@StockWatch.ns"; sd.DeliveryChannelName = "StockWatchFileDeliveryChannel"; sd.Add( ); Console.WriteLine("Added subscriber file device."); // create a subscriber s = new ns.Subscriber(swnsi); s.SubscriberId = @"TonyHamilton"; s.Add( ); Console.WriteLine("Added subscriber: " + s.SubscriberId); // create an email subscriber device sd = new ns.SubscriberDevice( ); sd.Initialize(swnsi); sd.DeviceName = "StockWatchSubscriberDevice"; sd.SubscriberId = "TonyHamilton"; sd.DeviceTypeName = "Email"; sd.DeviceAddress = "TonyH@StockWatchNS.ns"; sd.DeliveryChannelName = "StockWatchEmailDeliveryChannel"; sd.Add( ); Console.WriteLine("Added subscriber email device."); } private static void CreateSubscription( ) { ns.NSInstance swnsi = new ns.NSInstance("StockWatch"); ns.NSApplication a = new ns.NSApplication(swnsi, "StockWatchApp"); ns.Subscription s; // add subscriptions s = new ns.Subscription( ); s.Initialize(a, "StockWatchSubscriptions"); s.SetFieldValue("DeviceName", "StockWatchSubscriberDevice"); s.SetFieldValue("SubscriberLocale", "en-us"); s.SubscriberId = "KristinHamilton"; s.SetFieldValue("Symbol", "ABC"); s.SetFieldValue("Price", "0.00"); s.Add( ); Console.WriteLine("Added subscription: " + s.SubscriberId); s = new ns.Subscription( ); s.Initialize(a, "StockWatchSubscriptions"); s.SetFieldValue("DeviceName", "StockWatchSubscriberDevice"); s.SetFieldValue("SubscriberLocale", "en-us"); s.SubscriberId = "TonyHamilton"; s.SetFieldValue("Symbol", "DEF"); s.SetFieldValue("Price", "0.00"); s.Add( ); Console.WriteLine("Added subscription: " + s.SubscriberId); } }
|

