<pre>namespace WebMessage { public partial class WebForm1 : System.Web.UI.Page { static string connectionString = @"Data Source=PBA-PC\SQLEXPRESS; Initial Catalog = MyDB; Integrated Security=SSPI;"; public WebForm1() { } public void Page_Load(object sender, EventArgs e) { SqlDependency.Start(connectionString); getDataWithSqlDependency(); HttpContext.Current.Response.Write("Waiting for Data Changes"); // Console.WriteLine("Waiting for data changes"); //Console.WriteLine("Press enter to quit"); // Console.WriteLine(CanRequestNotifications().ToString()); //Console.ReadLine(); SqlDependency.Stop(connectionString); } static DataTable getDataWithSqlDependency() { //Console.WriteLine("getDataWithSqlDependency"); using (var connection = new SqlConnection(connectionString)) using (var cmd = new SqlCommand("SELECT ID,UserName,Email FROM dbo.[myUser]", connection)) { var dt = new DataTable(); // Create dependency for this command and add event handler var dependency = new SqlDependency(cmd); dependency.OnChange += new OnChangeEventHandler(OnChange); // execute command to get data connection.Open(); dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection)); HttpContext.Current.Response.Write(dt.Rows.Count.ToString()); for (int i = 0; i < dt.Rows.Count; i++) { HttpContext.Current.Response.Write(dt.Rows[i]["UserName"].ToString()); HttpContext.Current.Response.Write(dt.Rows[i]["Email"].ToString()); } return dt; } } static void OnChange(object sender, SqlNotificationEventArgs e) { HttpContext.Current.Response.Write($"OnChange Event fired. SqlNotificationEventArgs: Info={e.Info}, Source={e.Source}, Type={e.Type}."); if ((e.Info != SqlNotificationInfo.Invalid) && (e.Type != SqlNotificationType.Subscribe)) { //resubscribe var dt = getDataWithSqlDependency(); HttpContext.Current.Response.Write($"Data changed. {dt.Rows.Count} rows returned."); } else { HttpContext.Current.Response.Write("SqlDependency not restarted"); } } } }
SqlDependency.Stop
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)