I am trying to figure out how to use SQL Dependency (C # 4.0) to "listen" for database changes. I saw a lot of things on the Internet, but they seem to be adapted (naturally) to use the dependency to pull out the same data that the SQL dependency depends on. For example, in this article .
What I'm trying to do is create a dependency that, when launched, leads to many different SQL Select queries (which I can store in other methods, etc.). For example: I'm trying to establish a dependency that tracks the number of rows in a table. When the number of lines increases, then do x, y, z (i.e. my program does not care about the number of lines, it just increased, and when it does a bunch of things).
Any thoughts on what would be the best way to do this?
EDIT: I added my code as it is now. I am trying to figure out how to separate the SqlDependency setting from the GetData () process. Currently, however, I think I am entering an infinite loop, since after removing the event handler and re-running "SetupSqlDependency ()" it returns to the event handler
private void SetupSQLDependency() { // Tutorial for this found at: // http://www.dreamincode.net/forums/topic/156991-using-sqldependency-to-monitor-sql-database-changes/ SqlDependency.Stop(connectionString); SqlDependency.Start(connectionString); sqlCmd.Notification = null; // create new dependency for SqlCommand SqlDependency sqlDep = new SqlDependency(sqlCmd); sqlDep.OnChange += new OnChangeEventHandler(sqlDep_OnChange); SqlDataReader reader = sqlCmd.ExecuteReader(); } private void sqlDep_OnChange(object sender, SqlNotificationEventArgs e) { // FROM: http://msdn.microsoft.com/en-us/a52dhwx7.aspx
source share