Guest User

Untitled

a guest
Jan 23rd, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. public class DatabaseChangeListener
  2. {
  3. #region Constructor
  4.  
  5. public DatabaseChangeListener(string connectionString)
  6. {
  7. this.connectionString = connectionString;
  8. SqlDependency.Stop(connectionString);
  9. SqlDependency.Start(connectionString);
  10. connection = new SqlConnection(connectionString);
  11. }
  12.  
  13. #endregion Constructor
  14.  
  15. # region Finalizer
  16.  
  17. ~DatabaseChangeListener()
  18. {
  19. SqlDependency.Stop(connectionString);
  20. }
  21.  
  22. #
  23. endregion Finalizer
  24.  
  25. # region Properties
  26.  
  27. private readonly string connectionString;
  28. private readonly SqlConnection connection;
  29.  
  30. public delegate void NewMessage();
  31. public event NewMessage OnChange;
  32.  
  33. #endregion Properties
  34.  
  35. #region Methods
  36.  
  37. public DataTable Start(string changeQuery)
  38. {
  39. using(SqlCommand cmd = new SqlCommand(changeQuery, connection) {Notification = null})
  40. {
  41. SqlDependency dependency = new SqlDependency(cmd);
  42. dependency.OnChange += NotifyOnChange;
  43. if (connection.State == ConnectionState.Closed)
  44. {
  45. connection.Open();
  46. }
  47. using(DataTable dt = new DataTable())
  48. {
  49. dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection));
  50. return dt;
  51. }
  52. }
  53. }
  54.  
  55. void NotifyOnChange(object sender, SqlNotificationEventArgs e)
  56. {
  57. var dependency = sender as SqlDependency;
  58. if (dependency != null) dependency.OnChange -= NotifyOnChange;
  59. if (OnChange != null)
  60. {
  61. OnChange();
  62. }
  63. }
  64.  
  65. #endregion Methods
  66.  
  67. }
Add Comment
Please, Sign In to add comment