using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

namespace SqlDependencyEx
{
  class Program
  {
    static void Main(string[] args)
    {

        string connstring = GetConnectStringFromConfigFile();
        SqlDependency.Start(connstring);
        using (SqlConnection conn = new SqlConnection(connstring))
        using (SqlCommand cmd = 
         // 2-part table names, no "SELECT * FROM ..."
         new SqlCommand("SELECT au_id, au_lname FROM dbo.authors", conn))
       {
        try 
        {
          // create dependency associated with cmd
          SqlDependency depend = new SqlDependency(cmd);
          // register handler
          depend.OnChange += new OnChangeEventHandler(MyOnChange);

          conn.Open();
          SqlDataReader rdr = cmd.ExecuteReader();
          // process DataReader
          while (rdr.Read())
	          Console.WriteLine(rdr[0]);
          rdr.Close();
          // Wait for invalidation to come through
          Console.WriteLine("Press Enter to continue");
          Console.ReadLine();
          SqlDependency.Stop(connstring);
        }
        catch (Exception e)
         { Console.WriteLine(e.Message); }
       }	
      }

      static void MyOnChange(object caller, SqlNotificationEventArgs e)
      {
        Console.WriteLine("result has changed");
        Console.WriteLine("Source " + e.Source);
        Console.WriteLine("Type " + e.Type);
        Console.WriteLine("Info " + e.Info);
      }

    static string GetConnectStringFromConfigFile()
    {
      return "server=.;integrated security=true;database=pubs";
    }
  }
}
