Raphnika
Raphnika

Reputation: 62

SQLDependency does not update

I have used Microsofts guide to create a test webapplication using sqldependency. For my database I am using the Northwind database. It seems, that the dependency is not working, since I am expecting an imidiate update to the table and the label. Also, the broker is enabled.

here my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Caching;


namespace WebDependency
{
public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = "Cache Refresh: " + DateTime.Now.ToLongTimeString();

        SqlDependency.Start(GetConnectionString());

        using (SqlConnection connection = new SqlConnection(GetConnectionString()))
        {
            using (SqlCommand command = new SqlCommand(GetSQL(), connection))
            {
                SqlCacheDependency dependency = new SqlCacheDependency(command);

                int numberOfSeconds = 3;
                DateTime expires = DateTime.Now.AddSeconds(numberOfSeconds);

                Response.Cache.SetExpires(expires);
                Response.Cache.SetCacheability(HttpCacheability.Public);
                Response.Cache.SetValidUntilExpires(true);

                Response.AddCacheDependency(dependency);

                connection.Open();

                GridView1.DataSource = command.ExecuteReader();
                GridView1.DataBind();
            }
        }
    }
    private string GetConnectionString()
    {
        return "Data Source=(LocalDB)\\MSSqlLocalDB;Initial Catalog=Northwind;Integrated Security=True";
    }

    private string GetSQL()
    {
        return "Select CategoryName, Description from dbo.Categories";
    }
}
}

Upvotes: 0

Views: 479

Answers (1)

Kelso Sharp
Kelso Sharp

Reputation: 972

  1. You need to start the sqlDependency in the Application_Start of the global.asa
  2. You have no event handler for when the trigger actually fires.

This has a full example of what I think you are looking for.

Polling for database changes: SqlDependency, SignalR is Good

Upvotes: 1

Related Questions