Have you ever thought of a scenario in an ASP.NET website that if something is inserted, updated or deleted from the database the ASPX page should auto-reflect it without explicitly refreshing the page? Well reading the preceding lines you will think of using an ajax timer and database polling can easily accomplish the mission, right? Give it a second thought; is it really a good practice to poll the database periodically ? No, its not, because every database call will increase the load on the website. What if we put the data into a cache and poll it periodically for a change in data? A question then comes of how will the cache know when the data in the database has changed? The answer of the question is QueryNotification and SQLCacheDependency. To use them we first need to set up our database by executing the following scipts:
- ALTER DATABASE Ahmar_DB SET ENABLE_BROKER
- GRANT SUBSCRIBE QUERY NOTIFICATIONS TO Mst;
- GRANT RECEIVE ON QueryNotificationErrorsQueue TO Mst;
- GRANT REFERENCES ON CONTRACT::[http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification] TO Mst;
Note
- Ahmar_DB is the database name
- Mst is the Schema Name
Service Broker in Microsoft SQL Server 2005 is a new technology that provides messaging and queuing functions among instances. The basic functions of sending and receiving messages forms a part of a “conversation.” Each conversation is considered to be a complete channel of communication. Each Service Broker conversation is considered to be a dialog where two participants are involved.
Query notification is a feature that lets us subscribe to a query such that when the results of the query change a message is passed to the subscriber.
To read more about Service Broker and query notification please refer to the MSDN.
Let's get back to C#. Until now we have set up query notification that will provide notificationof a change in data residing in the cache. Let's see how to implement sqlcachedependency.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
- using System.Web.Caching;
-
- public partial class _Default : System.Web.UI.Page
- {
- string con = "Data Source=IKSL_2-PC;Initial Catalog=Ahmar_DB;User ID=Junk;Password=JunkPassword";
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- getdata();
- }
- }
-
- public void getdata()
- {
- if (HttpRuntime.Cache["Hello"] == null)
- {
- SqlConnection c = new SqlConnection(con);
- SqlCommand cmd = new SqlCommand("SELECT [Sno],[Name] FROM [Mst].[EMP_Name]", c);
- cmd.Notification = null;
- cmd.NotificationAutoEnlist = true;
- SqlCacheDependency cac1 = new SqlCacheDependency(cmd);
- c.Open();
- DataTable dt = new DataTable();
- SqlDataAdapter sda = new SqlDataAdapter(cmd);
- sda.Fill(dt);
- c.Close();
- HttpRuntime.Cache.Insert("Hello", dt, cac1);
- }
- Load();
- }
- public void Load()
- {
- DataTable dt = (DataTable)HttpRuntime.Cache.Get("Hello");
- GridView1.DataSource = dt;
- GridView1.DataBind();
- }
- protected void Timer1_Tick(object sender, EventArgs e)
- {
- getdata();
- }
- }
- ---------------------------ASPX--------------------------
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
-
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <asp:ScriptManager runat="server"></asp:ScriptManager>
-
- <asp:UpdatePanel runat="server" ID="upd" UpdateMode="Conditional">
- <ContentTemplate>
- <asp:Timer ID="Timer1" runat="server" Interval="1500" OnTick="Timer1_Tick"></asp:Timer>
- <div>
- <asp:GridView ID="GridView1" runat="server"></asp:GridView>
- </div>
- </ContentTemplate>
- </asp:UpdatePanel>
- </form>
- </body>
- </html>
The preceding written code is simple enough to understand but I will try to briefly explain what I am doing here. In the getdata() function I am executing a select command and populating the data table with the results and assigning it to a cache. If you will see I have created an object of sqlCacheDependency and passed a command object into its constructor. Later this dependency object has been passed to the Cache.Insert method. A timer is periodically checking whether the cache is empty or not. If the cache is empty it will be populated back from the database.Query Notifier that we enabled will notify whether the data has changed or not as soon as the data is changed our the cache will be Null and the freshly changed data will be shown in the grid.
There are the following limitations of SQL Cache Dependency:
- Works on plain query not SP
- No support of * in the query
- Query should not contain UNION, INTERSECT, EXCEPT operators
- Query should not contain Distinct Keyword
- Limited use of AGGREGATE functions