<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Eclipsed4utoo&#039;s Blog&#187; SqlDependency</title>
	<atom:link href="http://eclipsed4utoo.com/blog/tag/sqldependency/feed/" rel="self" type="application/rss+xml" />
	<link>http://eclipsed4utoo.com/blog</link>
	<description>Not Your Ordinary Programmer</description>
	<lastBuildDate>Thu, 08 Sep 2011 17:09:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Using SqlDependency To Monitor SQL Database Changes</title>
		<link>http://eclipsed4utoo.com/blog/sqldependency-monitor-sql-database/</link>
		<comments>http://eclipsed4utoo.com/blog/sqldependency-monitor-sql-database/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 22:00:34 +0000</pubDate>
		<dc:creator>Ryan Alford</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[SqlDependency]]></category>

		<guid isPermaLink="false">http://eclipsed4utoo.com/blog/?p=299</guid>
		<description><![CDATA[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. [...]]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>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.</p>
<p>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&#8217;t guarantee.</p>
<p>My example will be doing something very simple. I have a &#8220;Users&#8221; 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.</p>
<p>So first, we need to create the Queue and the Service broker and assign the privileges to the SQL user.</p>
<pre class="brush: sql;">
USING [YourDatabaseName]

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

GRANT SUBSCRIBE QUERY NOTIFICATIONS TO YourUserName;
</pre>
<p>You can now see that we have a new queue and a new service.</p>
<p><img class="alignnone size-full wp-image-300" title="Database" src="http://eclipsed4utoo.com/blog/wp-content/uploads/2010/02/Database.png" alt="Database" width="374" height="373" /></p>
<p>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.</p>
<pre class="brush: csharp;">
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;
     }
}
</pre>
<p>Next, we have our method to get the user names from the database.</p>
<pre class="brush: csharp;">
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 = &quot;SELECT FirstName, LastName FROM dbo.[Users]&quot;;

            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) + &quot; &quot; + dr.GetString(1));
                }
            }
        }
    }
}
</pre>
<p><span style="color: #ff0000;"><strong>THIS IS VERY IMPORTANT.</strong></span></p>
<p><span style="color: #ff0000;">1. In the previous code, you will notice that my SQL query does not use the &#8220;*&#8221; wildcard to return all columns. You MUST return the exact columns that you want. If you use the &#8220;*&#8221;, it will cause you to have unwanted consequences.<br />
</span></p>
<p><span style="color: #ff0000;">2. Also in the previous code, you will notice that my SQL query contains the &#8220;two-part&#8221; table name. This is also REQUIRED. Using just &#8220;TableName&#8221; instead of &#8220;owner.TableName&#8221; will also cause unwanted consequences.</span></p>
<p>Here is the method for the <strong>OnChange </strong>event</p>
<pre class="brush: csharp;">
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);
}
</pre>
<p>You will also need to stop the dependency when the form closes so that it doesn&#8217;t leave it running.</p>
<pre class="brush: csharp;">
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    SqlDependency.Stop(connectionString);
}
</pre>
<p>The other events&#8230;</p>
<pre class="brush: csharp;">
private void Form1_Load(object sender, EventArgs e)
{
    GetNames();
}

private void btnShowForm_Click(object sender, EventArgs e)
{
    Form2 f = new Form2();
    f.Show();
}
</pre>
<p>And my simple second form&#8217;s code..</p>
<pre class="brush: csharp;">
private void btnSave_Click(object sender, EventArgs e)
{
    using (SqlConnection cn = new SqlConnection(&quot;Data Source=alfordr;Initial Catalog=MyTestDatabase;User Id=dev;Password=dev;&quot;))
    {
        using (SqlCommand cmd = cn.CreateCommand())
        {
            cmd.CommandText = &quot;INSERT INTO Users VALUES (@FirstName, @LastName)&quot;;
            cmd.CommandType = CommandType.Text;

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

            cn.Open();

            cmd.ExecuteNonQuery();
        }
    }
}
</pre>
<p>And that is really all you have to do. Here are a couple of screenshots.</p>
<p>Before clicking &#8220;Save&#8221;&#8230;<br />
<img class="alignnone size-full wp-image-307" title="BeforeSave" src="http://eclipsed4utoo.com/blog/wp-content/uploads/2010/02/BeforeSave.png" alt="BeforeSave" width="657" height="367" /><br />
After clicking &#8220;Save&#8221;&#8230;..<br />
<img class="alignnone size-full wp-image-308" title="AfterSave" src="http://eclipsed4utoo.com/blog/wp-content/uploads/2010/02/AfterSave.png" alt="AfterSave" width="657" height="364" /></p>
<p>As you can see from my code, I am simply inserting data into my database when the<strong> Save</strong> button is clicked.  When the data is inserted, a notification is sent to the application, which is handled by the <strong>OnChange </strong>event.  The OnChange event then invokes the <strong>GetNames </strong>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.</p>
<p>This works for inserts, updates, and deletes.</p>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden;"><span style="border-collapse: separate; color: #000000; font-family: Arial,sans-serif; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: 2; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; font-size: medium;"><span style="border-collapse: collapse; color: #222222; font-family: Verdana,sans-serif; font-size: 14px; line-height: 21px;">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.<span> </span><br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />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.<br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />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&#8217;t guarantee.<br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />My example will be doing something very simple. I have a &#8220;Users&#8221; 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.<br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />So first, we need to create the Queue and the Service broker and assign the privileges to the SQL user.</span></span><span style="border-collapse: separate; color: #000000; font-family: Arial,sans-serif; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: 2; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; font-size: medium;"><span style="border-collapse: collapse; color: #222222; font-family: Verdana,sans-serif; font-size: 14px; line-height: 21px;">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. <br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />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.<br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />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&#8217;t guarantee.<br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />My example will be doing something very simple. I have a &#8220;Users&#8221; 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.<br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />So first, we need to create the Queue and the Service broker and assign the privileges to the SQL user.</span></span></div>
]]></content:encoded>
			<wfw:commentRss>http://eclipsed4utoo.com/blog/sqldependency-monitor-sql-database/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

