Cycle de progression Faire (quelque chose qui marche) -> comprendre ce que l’on fait/comment cela marche -> pousser plus loin les notions
| public delegate void ChangedEventHandler(); |
| public class ContactDAO { public event ChangedEventHandler Changed; private static string connectionString = "Server=.;Database=ContactDB;Integrated Security=SSPI"; private SqlConnection sqlConnection = null; public ContactDAO() { SqlDependency.Stop(connectionString); SqlDependency.Start(connectionString); sqlConnection = new SqlConnection(connectionString); } ~ContactDAO() { SqlDependency.Stop(connectionString); } // public DataTable GetContacts() { try { DataTable dataTable = new DataTable(); // IMPORTANT : spécifier le nom des colonnes (ne pas utiliser *)!! SqlCommand sqlCommand = new SqlCommand(@"SELECT ContactName FROM dbo.[Contact]", sqlConnection); sqlCommand.Notification = null; SqlDependency sqlDependency = new SqlDependency(sqlCommand); sqlDependency.OnChange += new OnChangeEventHandler(OnChanged); if (sqlConnection.State == ConnectionState.Closed) sqlConnection.Open(); // Autre point important : il faut obligatoirement exécuter la commande (du sqldependency) dataTable.Load(sqlCommand.ExecuteReader(CommandBehavior.CloseConnection)); return dataTable; } catch (Exception ex) { throw ex; } } // evenement void OnChanged(object sender, SqlNotificationEventArgs e) { SqlDependency sqlDependency = sender as SqlDependency; sqlDependency.OnChange -= OnChanged; if (Changed != null) Changed(); } } |
| ContactDAO contactDAO = new ContactDAO(); private void button1_Click(object sender, EventArgs e) { try { SqlClientPermission sqlClientPermission = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted); sqlClientPermission.Demand(); contactDAO.Changed += new ChangedEventHandler(contactDAO_Changed); dataGridView1.DataSource = contactDAO.GetContacts(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } void contactDAO_Changed() { MessageBox.Show("données modifiées"); // évite les opérations inter threads ISynchronizeInvoke iSynchronizeInvoke = (ISynchronizeInvoke)this; if (iSynchronizeInvoke.InvokeRequired) { ChangedEventHandler changed = new ChangedEventHandler(contactDAO_Changed); iSynchronizeInvoke.BeginInvoke(changed, null); return; } // rechargement dataGridView1.DataSource = contactDAO.GetContacts(); } |