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 your database. Ensure 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:
 
Syntax: 
 
ALTER DATABASE DATABASE_NAME SET ENABLE_BROKER  
 
Example:
  1. 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 primary storage for messages that are transferred between two services. The following SQL statements create a queue and service in your database.
 
Syntax  
  1. CREATE QUEUE QUEUE_NAME  
  2. CREATE SERVICE SERVICE_NAME ON QUEUE QUEUE_NAME  
  3.   ([http: //schemas.microsoft.com/SQL/Notification/PostQueryNotification])    
  4.       Example  
  5.   
  6.       CREATE QUEUE MarketRateChangeMessage  
  7.       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 ensures that a user has complete security-level permission to access a data source. The following is an example of the SqlClientPermission class.
  1. private bool HasPermission() {  
  2.     SqlClientPermission sqlClientPermission = new SqlClientPermission(PermissionState.Unrestricted);  
  3.     try {  
  4.         sqlClientPermission.Demand();  
  5.         return true;  
  6.     } catch {  
  7.         return false;  
  8.     }  
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 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.     public class Program {  
  10.         static void Main(string[] args) {  
  11.             NotificationExample ne = new NotificationExample();  
  12.             ne.StartNotification();  
  13.             ne.StopNotification();  
  14.         }  
  15.     }  
  16.     public class NotificationExample {  
  17.         private delegate void RateChangeNotification(DataTable table);  
  18.         private SqlDependency dependency;  
  19.         string ConnectionString = "database sonnection string";  
  20.   
  21.         public void StartNotification() {  
  22.             SqlDependency.Start(this.ConnectionString, "QueueName");  
  23.             SqlConnection connection = new SqlConnection(this.ConnectionString);  
  24.             connection.Open();  
  25.   
  26.             SqlCommand command = new SqlCommand();  
  27.             command.CommandText = "SQL Statement";  
  28.             command.Connection = connection;  
  29.             command.CommandType = CommandType.Text;  
  30.   
  31.             this.dependency = new SqlDependency(command);  
  32.             dependency.OnChange += new OnChangeEventHandler(OnRateChange);  
  33.   
  34.         }  
  35.         private void OnRateChange(object s, SqlNotificationEventArgs e) {  
  36.             //Write code for you task    
  37.         }  
  38.         public void StopNotification() {  
  39.             SqlDependency.Stop(this.ConnectionString, "QueueName");  
  40.         }  
  41.     }  

Summary

 
This article is just a quick introduction to enabling Notification Services and how it may be used in an application.


Similar Articles