I am currenty making an application for my university project. App should send out some form of notification via email after changes in the database.
There is an .mdf
file of database to which I connect with (localdb)
, viewing and editing done with dataset tables and SQLDataAdapter
s (if it matters or not, I don't know). I am trying to setup SqlDependency
so it performs checks on table for new flags so it could sent email about rows with those flags.
The problem is that I can't make sqlDependency.OnChange
event to trigger, Service Broker
is enabled. After I boot the app, I start SqlDependency
, after that I edit and save data in one of my SqlAdapter
methods, data changes in database (in mdf file), but no event triggers. I tried multiple tutorials and none seem to work for me. Here's the code:
public void StartWatching()
{
SqlDependency.Stop(con.ConnectionString);
SqlDependency.Start(con.ConnectionString);
ExecuteWatchingQuery();
}
private void ExecuteWatchingQuery()
{
using (SqlConnection connection = new SqlConnection(con.ConnectionString))
{
connection.Open();
using (var command = new SqlCommand(
"select [id], [subject] from dbo.lots", connection))
{
var sqlDependency = new SqlDependency(command);
sqlDependency.OnChange += new OnChangeEventHandler(OnDatabaseChange);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
Log_Text.AppendText("Watching... \n");
}
else
{
Log_Text.AppendText("No rows found.");
}
}
}
}
private void OnDatabaseChange(object sender, SqlNotificationEventArgs args)
{[enter image description here][1]
SqlNotificationInfo info = args.Info;
if (SqlNotificationInfo.Insert.Equals(info)
|| SqlNotificationInfo.Update.Equals(info)
|| SqlNotificationInfo.Delete.Equals(info))
{
Log_Text.AppendText("Saw changes: \n");
Watching();
}
ExecuteWatchingQuery();
}
Source: http://ts-soft.ru/blog/mssql-database-watching
[1]: https://i.stack.imgur.com/jyBOf.png The table
The problem was in the fact, that both editing and monitoring were done in the same app, I'm not sure if not on the same connection. I devided app into two (one - database editing, other - console app for monitoring), and all started working.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.