Export (0) Print
Expand All

Using SqlDependency in a Windows Application 

.NET Framework 2.0

The following scenario shows how to use the SqlDependency class in a Windows Forms application. To demonstrate how notifications work, you will create two applications: a watcher to process query notifications, and an updater to modify the data that the watcher is monitoring.

NoteNote

The sample code assumes that you have enabled query notifications by executing the scripts in Enabling Query Notifications.

Creating the Watcher Application

The watcher application is a Windows Forms application that loads product data into a DataSet from the AdventureWorks SQL Server 2005 sample database. The DataSet is filled using a SqlDataAdapter object that is bound to a DataGridView control. In order to receive notifications, a SqlDependency object is created and bound to the SqlCommand object used by the SqlDataAdapter. The SqlDependency object exposes a single event, OnChange. The handler that is registered to process the notifications performs the necessary actions to switch from the notifying thread pool thread to the UI thread and then re-registers to receive notifications.

To create the watcher application

  1. Create a new Windows Application project named "Data Watcher".

  2. In Forms Designer, select the default form. Change the Text property to Inventory Watcher.

  3. Add a Label control to the form. Dock the label control to the bottom of the form.

  4. Add a ListBox control in the upper left of the form. Size it for approximately three lines of text.

  5. Add a DataGridView below the ListBox control.

  6. Add a Button control to the form and position it to the right of the ListBox control. Change its Text property to Get Data.

  7. Open the form's class module and add the following code to the top of the file, above the class definition.

    Option Strict On
    Option Explicit On
    
    Imports System.ComponentModel
    Imports System.Data.SqlClient
    Imports System.Security.Permissions
    
    using System.Data.SqlClient;
    using System.Security.Permissions;
    
  8. In the declaration section of the class, add the following items:

    private int changeCount = 0;
    
    private const string tableName = "Inventory";
    private const string statusMessage = "{0} changes have occurred.";
    
    // The following objects are reused
    // for the lifetime of the application.
    private DataSet dataToWatch = null;
    private SqlConnection connection = null;
    private SqlCommand command = null;
    
    
  9. In the form, create a new method called CanRequestNotifications. This method will verify the application has permissions to request notifications from the server.

    private bool CanRequestNotifications()
    {
        // In order to use the callback feature of the
        // SqlDependency, the application must have
        // the SqlClientPermission permission.
        try
        {
            SqlClientPermission perm =
                new SqlClientPermission(
                PermissionState.Unrestricted);
    
            perm.Demand();
    
            return true;
        }
        catch
        {
            return false;
        }
    }
    
    
  10. In the form's Load event, use the return value from CanRequestNotifications to set the Enabled property of the form's only button.

    private void Form1_Load(object sender, EventArgs e)
    {
        Button1.Enabled = CanRequestNotifications();
    }
    
    
  11. Add two helper methods, GetConnectionString and GetSQL. The defined connection string uses integrated security. You will need to verify that the account you are using has the necessary database permissions and that the sample database, AdventureWorks, has notifications enabled. For more information, see Enabling Query Notifications.

    private string GetConnectionString()
    {
        // To avoid storing the connection string in your code,
        // you can retrive it from a configuration file.
        return "Data Source=(local);Integrated Security=true;" +
          "Initial Catalog=AdventureWorks;Pooling=False;";
    }
    
    private string GetSQL()
    {
        return "SELECT Production.Product.ProductID, " +
        "Production.Product.Name, Production.Location.Name AS Location, " +
        "Production.ProductInventory.Quantity FROM " +
        "Production.Product INNER JOIN Production.ProductInventory " +
        "ON Production.Product.ProductID = " +
        "Production.ProductInventory.ProductID " +
        "INNER JOIN Production.Location " +
        "ON Production.ProductInventory.LocationID = " +
        "Production.Location.LocationID " +
        "WHERE ( Production.ProductInventory.Quantity <= @Quantity ) " +
        "ORDER BY Production.ProductInventory.Quantity, " +
        "Production.Product.Name;";
    }
    
    
  12. In order to receive notifications when data on the server changes, the application needs an event handler that matches the signature of the OnChangeEventHandler delegate. The procedure needs to catch the event and switch from the worker thread to the UI thread. Add the following code to the form's module:

    private void dependency_OnChange(
       object sender, SqlNotificationEventArgs e)
    {
        // This event will occur on a thread pool thread.
        // Updating the UI from a worker thread is not permitted.
        // The following code checks to see if it is safe to
        // update the UI.
        ISynchronizeInvoke i = (ISynchronizeInvoke)this;
    
        // If InvokeRequired returns True, the code
        // is executing on a worker thread.
        if (i.InvokeRequired)
        {
            // Create a delegate to perform the thread switch.
            OnChangeEventHandler tempDelegate =
                new OnChangeEventHandler(dependency_OnChange);
    
            object[] args = { sender, e };
    
            // Marshal the data from the worker thread
            // to the UI thread.
            i.BeginInvoke(tempDelegate, args);
    
            return;
        }
    
        // Remove the handler, since it is only good
        // for a single notification.
        SqlDependency dependency =
            (SqlDependency)sender;
    
        dependency.OnChange -= dependency_OnChange;
    
        // At this point, the code is executing on the
        // UI thread, so it is safe to update the UI.
        ++changeCount;
        label1.Text = String.Format(statusMessage, changeCount);
    
        // Add information from the event arguments to the list box
        // for debugging purposes only.
        listBox1.Items.Clear();
        listBox1.Items.Add("Info:   " + e.Info.ToString());
        listBox1.Items.Add("Source: " + e.Source.ToString());
        listBox1.Items.Add("Type:   " + e.Type.ToString());
    
        // Reload the dataset that is bound to the grid.
        GetData();
    }
    
    
  13. In order to receive notifications, the application must register a SqlDependency object with the SqlCommand object used to obtain the application's data. Add a method called GetData as follows:

    private void GetData()
    {
        // Empty the dataset so that there is only
        // one batch of data displayed.
        dataToWatch.Clear();
    
        // Make sure the command object does not already have
        // a notification object associated with it.
        command.Notification = null;
    
        // Create and bind the SqlDependency object
        // to the command object.
        SqlDependency dependency =
            new SqlDependency(command);
        dependency.OnChange += new
            OnChangeEventHandler(dependency_OnChange);
    
        using (SqlDataAdapter adapter =
            new SqlDataAdapter(command))
        {
            adapter.Fill(dataToWatch, tableName);
    
            dataGridView1.DataSource = dataToWatch;
            dataGridView1.DataMember = tableName;
        }
    }
    
    
  14. Add an event handler for the Click event in the form's only button, and put the following code in the handler body:

    private void button1_Click(object sender, EventArgs e)
    {
        changeCount = 0;
        label1.Text = String.Format(statusMessage, changeCount);
    
        // Remove any existing dependency connection, then create a new one.
        SqlDependency.Stop(GetConnectionString());
        SqlDependency.Start(GetConnectionString());
    
        if (connection == null)
        {
            connection = new SqlConnection(GetConnectionString());
        }
    
        if (command == null)
        {
            // GetSQL is a local procedure that returns
            // a paramaterized SQL string. You might want
            // to use a stored procedure in your application.
            command = new SqlCommand(GetSQL(), connection);
    
            SqlParameter prm =
                new SqlParameter("@Quantity", SqlDbType.Int);
            prm.Direction = ParameterDirection.Input;
            prm.DbType = DbType.Int32;
            prm.Value = 100;
            command.Parameters.Add(prm);
        }
        if (dataToWatch == null)
        {
            dataToWatch = new DataSet();
        }
    
        GetData();
    }
    
    
  15. In the form's FormClosed event, add the following code to clean up the dependency and database connections:

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        SqlDependency.Stop(GetConnectionString());
        if (connection != null)
        {
            connection.Close();
        }
    }
    
    

With the watcher application completed, you will need to create the updater application and then run them together.

Creating the Updater Application

The updater application provides a simple interface to modify the set of data that is being monitored by the watcher application. The updater in this example is also a Windows Application, but any type of application can be used to update the data. Follow these steps to create the updater application:

  1. Create a new Windows Application project called "Data Updater".

  2. In Forms Designer, select the default form. In the property grid, change the Text property to "Inventory Updater".

  3. Add a Label control and a TextBox control to form. Change the Text property of the label to Product ID and the Name property of the text box to "txtProductID".

  4. Add another label and text box. Change the Text property of the label to Quantity and the Name property of the text box to "txtQuantity".

  5. Add a Button control and set its Text property to "Update".

  6. Add the following directives to the form class:

    Option Strict On
    Option Explicit On
    
    Imports System.Data
    Imports System.Data.SqlClient
    
    using System.Data
    using System.Data.SqlClient;
    
  7. In the declaration section of the class, add the following items:

    // The following objects are reused
    // for the lifetime of the application.
    private SqlConnection connection = null;
    private SqlCommand command = null;
    
    
  8. Add two helper methods, GetConnectionString and GetSQL, to the form. They should look like the following:

    private string GetConnectionString()
    {
        // To avoid storing the connection string in your code,
        // you can retrive it from a configuration file.
        return "Data Source=(local);Integrated Security=true;" +
          "Initial Catalog=AdventureWorks;";
    }
    
    private string GetSQL()
    {
        return "UPDATE Production.ProductInventory " +
        "SET Production.ProductInventory.Quantity = @Quantity " +
        "WHERE Production.ProductInventory.ProductID = @ProductID;";
    }
    
    
  9. In the Click event of the Get Data button, add the following code:

    private void button1_Click(object sender, EventArgs e)
    {
        int productID = Convert.ToInt32(txtProductID.Text);
        int quantity = Convert.ToInt32(txtQuantity.Text);
    
        if (connection == null)
        {
            connection = new SqlConnection(GetConnectionString());
            connection.Open();
        }
    
        if (command == null)
        {
            // GetSQL is a local procedure that returns
            // a paramaterized SQL string. You might want
            // to use a stored procedure in your application.
            command = new SqlCommand(GetSQL(), connection);
    
            SqlParameter param = new
                SqlParameter("@Quantity", SqlDbType.Int);
            param.Direction = ParameterDirection.Input;
            param.DbType = DbType.Int32;
            command.Parameters.Add(param);
    
            param = new SqlParameter("@ProductID", SqlDbType.Int);
            param.Direction = ParameterDirection.Input;
            param.DbType = DbType.Int32;
            command.Parameters.Add(param);
        }
    
        command.Parameters["@Quantity"].Value = quantity;
        command.Parameters["@ProductID"].Value = productID;
    
        int rowsAffected = command.ExecuteNonQuery();
    
        MessageBox.Show(rowsAffected + " records updated.", "Update");
    }
    
    
  10. Finally, add the following code to the form's FormClosed event handler:

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        if (connection != null)
        {
            connection.Close();
        }
    }
    
    

Testing the Application

Compile and run both applications. Click Get Data on the watcher application to fill the application's grid with data and register a notification request. Examine the data in the grid to find a product ID with an inventory quantity of zero. Switch to the updater application, enter the product ID and a new quantity of one, and click Update. You should see the watcher application automatically update itself moments after the updater changes the data on the server. Observe that the ListBox control displays information about the update.

See Also

Community Additions

ADD
Show:
© 2014 Microsoft