using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace SqlNotification { public partial class View : Form { String connections = @"Data Source=janmark-pc;Initial Catalog=NOTIFICATIONS;Integrated Security=True"; private const string statusMessage=""; private DataSet myDataSet = null; private SqlConnection connection = null; private SqlCommand command = null; private string connstr; public View() { InitializeComponent(); EnoughPermission(); } private bool EnoughPermission() { SqlClientPermission perm = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted); try { perm.Demand(); return true; } catch (System.Exception) { return false; } } private void View_Load(object sender, EventArgs e) { } private void simpleButton1_Click(object sender, EventArgs e) { ActivateAutomaticRefreshinAnyComputer(); } private void ActivateAutomaticRefreshinAnyComputer() { connstr = connections; string ssql = "SELECT * FROM NOTIFS"; SqlDependency.Stop(connstr); SqlDependency.Start(connstr); if (connection == null) connection = new SqlConnection(connstr); if (command == null) command = new SqlCommand(ssql, connection); if (myDataSet == null) myDataSet = new DataSet(); GetAdvtData(); } private void GetAdvtData() { myDataSet.Clear(); // Ensure the command object does not have a notification object. command.Notification = null; // Create and bind the SqlDependency object to the command object. SqlDependency dependency = new SqlDependency(command); dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); using (SqlDataAdapter adapter = new SqlDataAdapter(command)) { adapter.Fill(myDataSet, "Advt"); gridControl1.DataSource = myDataSet; gridControl1.DataMember = "Advt"; } } delegate void UIDelegate(); private void dependency_OnChange(object sender, SqlNotificationEventArgs e) { try { UIDelegate uidel = new UIDelegate(RefreshData); this.Invoke(uidel, null); SqlDependency dependency = (SqlDependency)sender; dependency.OnChange -= dependency_OnChange; } catch (Exception R) { } } private void RefreshData() { // Since the code is executing on the UI thread,it is safe to update the UI. label1.Text = "Database had some changes and are applied in the Grid"; // Reload the dataset that is bound to the grid. GetAdvtData(); } private void simpleButton2_Click(object sender, EventArgs e) { string connstr = connections; SqlDependency.Stop(connstr); } private void View_FormClosing(object sender, FormClosingEventArgs e) { string connstr = connections; SqlDependency.Stop(connstr); } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)