I am trying SqlDepenedency for the first time. I do not receive any database update notifications.
I set a breakpoint inside:
OnChange(object sender, SqlNotificationEventArgs e),
but he never hits.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Cache Refresh: " + DateTime.Now.ToLongTimeString();
DateTime.Now.ToLongTimeString();
SqlDependency.Start(GetConnectionString());
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
using (SqlCommand command = new SqlCommand(GetSQL(), connection))
{
SqlDependency dependency =
new SqlDependency(command);
connection.Open();
dgHomeRequests.DataSource = command.ExecuteReader();
dgHomeRequests.DataBind();
}
}
}
private string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["TestData"].ConnectionString;
}
private string GetSQL()
{
return "Select [Address] From [UserAccount1]";
}
void OnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency = sender as SqlDependency;
dependency.OnChange -= OnChange;
}
I also put some code in the Global.asax file:
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
SqlDependency.Start(ConfigurationManager.ConnectionStrings["TestData"].ConnectionString);
}
protected void Application_End()
{
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["TestData"].ConnectionString);
}
}
The SQL server is located on the local machine. I am running the code through Visual Studio (IIS Express).
To enable a service broker in the database:
ALTER DATABASE SET ENABLE_BROKER GO
In order to sign up for a request notification, we need to grant permission to an IIS account
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO "<serviceAccount>"
, , . . , , , . env. .
, , :
alter authorization on database::<dbName> to [sa];
.