.Net Using SqlDependency To Monitor SQL Database Changes

6 Comments

In this tutorial, I will use the SqlDependency class and Query notifications to monitor SQL Server 2005 database data changes. Query Notifications allow an application to be notified when data has changed in the database.

The purpose of this class is to save you from having to continuously re-query the database to get new data. You would have probably done this by setting up a timer that executes every X amount of seconds so that your display control would be displaying the most up-to-date information. You will no longer have to do this.

We will be using a Service Broker and a QUEUE in SQL Server 2005. These were new additions to SQL Server 2005. I will assume these are also in SQL Server 2008, but can’t guarantee.

My example will be doing something very simple. I have a “Users” table in my database with two fields: FirstName and LastName. I am simply displaying these in a ListBox on one form. On a second form, I have textboxes to insert the data into the database.

So first, we need to create the Queue and the Service broker and assign the privileges to the SQL user.

USING [YourDatabaseName]

CREATE QUEUE NameChangeQueue;
CREATE SERVICE NameChangeService ON QUEUE NameChangeQueue
([http://schemas.microsoft.com/sql/notifications/postquerynotification]);

GRANT SUBSCRIBE QUERY NOTIFICATIONS TO YourUserName;

You can now see that we have a new queue and a new service.

Database

Now we move on to the code. The first thing you will need to do is to test if the connecting user has the privileges for the query notifications.

private bool DoesUserHavePermission()
{
     try
     {
           SqlClientPermission clientPermission = new SqlClientPermission(PermissionState.Unrestricted);

           // will throw an error if user does not have permissions
           clientPermission.Demand();

           return true;
     }
     catch
     {
           return false;
     }
}

Next, we have our method to get the user names from the database.

private void GetNames()
{
    if (!DoesUserHavePermission())
        return;

    lbNames.Items.Clear();

    SqlDependency.Stop(connectionString);
    SqlDependency.Start(connectionString);

    using (SqlConnection cn = new SqlConnection(connectionString))
    {
        using (SqlCommand cmd = cn.CreateCommand())
        {
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT FirstName, LastName FROM dbo.[Users]";

            cmd.Notification = null;

            SqlDependency dep = new SqlDependency(cmd);
            dep.OnChange += new OnChangeEventHandler(dep_OnChange);

            cn.Open();

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    lbNames.Items.Add(dr.GetString(0) + " " + dr.GetString(1));
                }
            }
        }
    }
}

THIS IS VERY IMPORTANT.

1. In the previous code, you will notice that my SQL query does not use the “*” wildcard to return all columns. You MUST return the exact columns that you want. If you use the “*”, it will cause you to have unwanted consequences.

2. Also in the previous code, you will notice that my SQL query contains the “two-part” table name. This is also REQUIRED. Using just “TableName” instead of “owner.TableName” will also cause unwanted consequences.

Here is the method for the OnChange event

void dep_OnChange(object sender, SqlNotificationEventArgs e)
{
    // this event is run asynchronously so you will need to invoke to run on UI thread.
    if (this.InvokeRequired)
        lbNames.BeginInvoke(new MethodInvoker(GetNames));
    else
        GetNames();

    // this will remove the event handler since the dependency is only for a single notification
    SqlDependency dep = sender as SqlDependency;
    dep.OnChange -= new OnChangeEventHandler(dep_OnChange);
}

You will also need to stop the dependency when the form closes so that it doesn’t leave it running.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    SqlDependency.Stop(connectionString);
}

The other events…

private void Form1_Load(object sender, EventArgs e)
{
    GetNames();
}

private void btnShowForm_Click(object sender, EventArgs e)
{
    Form2 f = new Form2();
    f.Show();
}

And my simple second form’s code..

private void btnSave_Click(object sender, EventArgs e)
{
    using (SqlConnection cn = new SqlConnection("Data Source=alfordr;Initial Catalog=MyTestDatabase;User Id=dev;Password=dev;"))
    {
        using (SqlCommand cmd = cn.CreateCommand())
        {
            cmd.CommandText = "INSERT INTO Users VALUES (@FirstName, @LastName)";
            cmd.CommandType = CommandType.Text;

            cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text);
            cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);

            cn.Open();

            cmd.ExecuteNonQuery();
        }
    }
}

And that is really all you have to do. Here are a couple of screenshots.

Before clicking “Save”…
BeforeSave
After clicking “Save”…..
AfterSave

As you can see from my code, I am simply inserting data into my database when the Save button is clicked.  When the data is inserted, a notification is sent to the application, which is handled by the OnChange event.  The OnChange event then invokes the GetNames method which re-queries the database to get the new information.  This makes a huge performance improvement because I ONLY query when I need to.

This works for inserts, updates, and deletes.

In this tutorial, I will use the SqlDependency class and Query notifications to monitor SQL Server 2005 database data changes. Query Notifications allow an application to be notified when data has changed in the database.

The purpose of this class is to save you from having to continuously re-query the database to get new data. You would have probably done this by setting up a timer that executes every X amount of seconds so that your display control would be displaying the most up-to-date information. You will no longer have to do this.

We will be using a Service Broker and a QUEUE in SQL Server 2005. These were new additions to SQL Server 2005. I will assume these are also in SQL Server 2008, but can’t guarantee.

My example will be doing something very simple. I have a “Users” table in my database with two fields: FirstName and LastName. I am simply displaying these in a ListBox on one form. On a second form, I have textboxes to insert the data into the database.

So first, we need to create the Queue and the Service broker and assign the privileges to the SQL user.
In this tutorial, I will use the SqlDependency class and Query notifications to monitor SQL Server 2005 database data changes. Query Notifications allow an application to be notified when data has changed in the database.

The purpose of this class is to save you from having to continuously re-query the database to get new data. You would have probably done this by setting up a timer that executes every X amount of seconds so that your display control would be displaying the most up-to-date information. You will no longer have to do this.

We will be using a Service Broker and a QUEUE in SQL Server 2005. These were new additions to SQL Server 2005. I will assume these are also in SQL Server 2008, but can’t guarantee.

My example will be doing something very simple. I have a “Users” table in my database with two fields: FirstName and LastName. I am simply displaying these in a ListBox on one form. On a second form, I have textboxes to insert the data into the database.

So first, we need to create the Queue and the Service broker and assign the privileges to the SQL user.

Tags: , ,

6 Responses to “Using SqlDependency To Monitor SQL Database Changes”

  1. Mr.Jelda Says:

    Great! I was stuck on problem since Onchange didn’t fire as it should before read this post.

    I’ve read all the posts from the internet. Finally with no hope, I compared my code to yours. Tada! How’s the hell I forgot to pass ‘cmd’ as SqlDependency constructor. Funny me ^^! Thank you.

  2. Ryan Alford Says:

    Glad to help you out.

  3. Jimmo Says:

    You create the queue and service [NameChangeQueue/Service] but your not actually using it, instead SQL is creating a queue for you, called [SqlQueryNotificationService-[GUID]]. To use the queue you initially created you need to modify your code:

    SqlDependency.Stop(connectionString, “NameChangeQueue”);
    SqlDependency.Start(connectionString, “NameChangeQueue”);

    and:

    SqlDependency dep = new SqlDependency(cmd, “service=NameChangeService; Local database=DATABASE_NAME”, 0);

    This will then use the named service and queue you created.

    cheers

  4. Ryan Alford Says:

    Thanks Jimmo. I will look into these changes and update the post.

  5. yo Says:

    You should participate in a contest for probably the greatest blogs on the web. I will suggest this site!

  6. Nana Hagge Says:

    An individual I operate with visits your website routinely and suggested it to me to examine as well. The creating style is terrific and the material is related. Thank you for your perception you deliver the viewers.I discover one thing far more difficult on entirely diverse weblogs each day. It really should continually be stimulating to understand subject matter from other writers and abide by only a small a single issue from their keep. I’d favor to make utilization of some together with the subject matter on my weblog irrespective of whether or not you never thoughts. Natually I’ll offer you you a hyperlink on your world wide web website. Thanks for sharing.!

Leave a Reply