Como usar o Query Notification

Problema do aluno: Trabalho com Visual Studio 2005 (C#) e preciso criar um aplicativo windows que A CADA ALTERAÇÃO DE DADOS no SQL Server 2005, dê um refresh no datagrid. Como faço?

Solução: Primeiro, criamos um database e as tabelas, usando o script abaixo, que deve ser executado no SQL Server Management Studio.

USE MASTER

IF EXISTS(SELECT * FROM SYS.DATABASES WHERE NAME=‘EXEMPLO_QUERY_NOTIFICATION’)
DROP DATABASE EXEMPLO_QUERY_NOTIFICATION

CREATE DATABASE EXEMPLO_QUERY_NOTIFICATION
GO
USE EXEMPLO_QUERY_NOTIFICATION

CREATE TABLE PESSOA
(
      COD_PESSOA INT IDENTITY PRIMARY KEY,
      NOME_PESSOA VARCHAR(50),
      APELIDO_PESSOA VARCHAR(50),
      SEXO_PESSOA CHAR(1) CHECK (SEXO_PESSOA IN (‘M’,‘F’))
)

INSERT INTO PESSOA VALUES (‘AGNALDO’, ‘OGRO’, ‘M’)
INSERT INTO PESSOA VALUES (‘BRUNO’, NULL, ‘M’)
INSERT INTO PESSOA VALUES (‘ANTONIO’, ‘NETINHO’, ‘M’)
INSERT INTO PESSOA VALUES (‘PEDRO’, NULL, ‘M’)

SELECT * FROM PESSOA

Agora, abrimos um projeto chamado ExemploQueryNotification, do tipo Windows Application no Visual Studio 2005 e posicionamos um DataGridView e um button no formulário, como abaixo:

TELAFinalmente, crie um dalegate para “vigiar” a alteração de dados no database, implemente o método clique do button, que preencherá o grid com os dados da tabela. O código final fica assim:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
//
namespace NOTIFICATION_SERVICES
{
      public partial class Form1 : Form
     
{
            private DataSet meuDataSet = null;?
            private SqlConnection conexao = null
            private SqlCommand comando = null;?
           
private string strConexao;
//
            public Form1()
            {
                  InitializeComponent();
            }
//
            private bool EnoughPermission()
            {
                  SqlClientPermission permissoes =
new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
                  try
                  {
                        permissoes.Demand();
                        return true;
                  }
                  catch (System.Exception)
                  {
                        return false;
                 
}
            }
//
            private void getDados()
            {
                  meuDataSet.Clear();
                  comando.Notification = null;
                  SqlDependency dependencia = new SqlDependency(comando);
                  dependencia.OnChange += new OnChangeEventHandler(dependencia_OnChange);
                  using (SqlDataAdapter adapter = new SqlDataAdapter(comando))
                  
{
                        adapter.Fill(meuDataSet,
“pessoa”);dataGridView1.DataSource = meuDataSet;
                        dataGridView1.DataMember =
“pessoa”;
                 
}
            }
//
            delegate void UIDelegate();
//
            private void dependencia_OnChange(object sender, SqlNotificationEventArgs e)
           
{
                  UIDelegate uidel =
new UIDelegate(RefreshData);
                 
this.Invoke(uidel, null);
                  SqlDependency dependencia = (SqlDependency)sender;
                  dependencia.OnChange -= dependencia_OnChange;
            }
//
            private void RefreshData()
           
{
                  getDados();
            }
//
            private void button1_Click(object sender, EventArgs e)
           
{
                  strConexao =
“Data Source=NOTEBOOK;Integrated Security=SSPI;Initial Catalog=EXEMPLO_QUERY_NOTIFICATION;”;
                 
string strSQL = “SELECT * FROM PESSOA”;
//
                  SqlDependency.Stop(strConexao);
                  SqlDependency.Start(strConexao);
//
                  if (conexao == null)conexao = new SqlConnection(strConexao);
                  if (comando == null)comando = new SqlCommand(strSQL, conexao);
                  if (meuDataSet == null)meuDataSet = new DataSet();
//
                  getDados();
            }
//
            private void Form1_FormClosing(object sender, FormClosingEventArgs e)
           
{
                  SqlDependency.Stop(strConexao);
//
                  if (conexao != null)conexao.Close();
            }
      }
}