Working With SQL Notification

Introduction

This article explains how SQL Notification can be enabled in SQL Server to build an application that uses notification. An application that involves SQL Notification requires a common set of tasks to be performed. The data source must be configured to support query notifications and the user must have the required and server-side permissions.

To use notifications, first you need to enable a server broker of you database. Insure that your user id should have the necessary permission. A SQL Server database does not have a Service Broker enabled by default. You need to enable a Service Broker. A Service Broker can be enabled using a SQL statement. The following code enables the Service Broker of a database:
  1. Syntax: ALTER DATABASE DATABASE_NAME SET ENABLE_BROKER  
  2. Example: ALTER DATABASE MyDatabase SET ENABLE_BROKER  
The SQL keyword "ENABLE_BROKER" activates the Service Broker of the database you have given. After activating the Service Broker on your database, you need to create a queue for storing messages and a service for delivering messages to the correct queue. A queue is the primary storage for messages that are transferred between two services. The following SQL statements create a queue and service in your database.
  1. Syntax  
  2. CREATE QUEUE QUEUE_NAME  
  3. CREATE SERVICE SERVICE_NAME ON QUEUE QUEUE_NAME    
  4. ([http://schemas.microsoft.com/SQL/Notification/PostQueryNotification])  
  5. Example  
  6.   
  7. CREATE QUEUE MarketRateChangeMessage  
  8. CREATE SERVICE MarketRateChangeNotificationService ON QUEUE MarketRateChangeMessage ([http://schemas.microsoft.com/SQL/Notification/PostQueryNotification])   
Now set the permissions for the query notifications, the client-side code requires necessary permission to execute SQL Notification. This can be done by the SqlClientPermission class. The following SQL statement grants permissions for query notification.
 
SQL Statement: GRANT SUBSCRIBE QUERY NOTIFICATIONS TO DATABASE_PRINCIPAL

The SqlClientPermission insures that a user has complete security-level permission to access a data source. The following is the example of the SqlClientPermission class.

  1. Private bool HasPermission()  
  2. {  
  3. SqlClientPermission sqlClientPermission= new SqlClientPermission(PermissionState.Unrestricted);  
  4. Try  
  5. {  
  6.         sqlClientPermission.Demand();  
  7.         return true;  
  8. }  
  9. catch  
  10. {  
  11.   
  12. Return false;  
  13. }  
  14. }  

The preceding code creates an object of the SqlClientPremission class, there are two types of permission states available in the .Net framework, one is None and the is Unrestricted. The value of None gives no access and Unrestricted gives full access. The method Demand forces a SecurityException at runtime if all callers higher in the call stack have not been granted the permission. PermissionState is an enumeration and is available in the System.Security.Permissions namespace.

Now we will execute the notification. The SqlDependency class is used to process notifications; this class automatically starts a worker thread to process the notifications as they are posted to the queue and also parses the Service Broker message and exposes the message as event argument data.

The SqlDependency class has the two static classes, Start and Stop, that take a measure role. The SqlDependency class initializes by calling the start method. The start method is a static method, it only needs to be called once for each database collection.

The following code snippet contains the full of code for SQL Notification:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.SqlClient;  
  5. using System.Linq;  
  6. using System.Text;  
  7.   
  8. namespace ConsoleDemo  
  9. {  
  10.     public class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             NotificationExample ne = new NotificationExample();  
  15.             ne.StartNotification();  
  16.             ne.StopNotification(();  
  17.         }  
  18.     }  
  19.     public class NotificationExample  
  20.     {  
  21.         private delegate void RateChangeNotification(DataTable table);  
  22.         private SqlDependency dependency;  
  23.         string ConnectionString = "database sonnection string";  
  24.          
  25.         public void StartNotification()  
  26.         {  
  27.             SqlDependency.Start(this.ConnectionString,"QueueName");  
  28.             SqlConnection connection = new SqlConnection(this.ConnectionString);  
  29.             connection.Open();  
  30.   
  31.             SqlCommand command=new SqlCommand();  
  32.             command.CommandText="SQL Statement";  
  33.             command.Connection = connection;  
  34.             command.CommandType = CommandType.Text;  
  35.   
  36.             this.dependency = new SqlDependency(command);  
  37.             dependency.OnChange += new OnChangeEventHandler(OnRateChange);  
  38.   
  39.         }  
  40.         private void OnRateChange(object s,SqlNotificationEventArgs e)  
  41.         {  
  42.           //Write code for you task  
  43.         }  
  44.         public void StopNotification()  
  45.         {  
  46.             SqlDependency.Stop(this.ConnectionString,"QueueName");  
  47.         }  
  48.     }  
  49. }  
Summary
This article is  just a quick introduction to enabling Notification Services and how it may be used in an application.
 

Up Next
    Ebook Download
    View all
    Learn
    View all