Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.27 KB | None | 0 0
  1. using MySql.Data.MySqlClient;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using System.Windows;
  11.  
  12. namespace MySQL_DB_Listen_And_Notify_Demo
  13. {
  14. public class DbManager : ObservableObject, IDisposable
  15. {
  16. bool disposed = false;
  17. private MySqlConnection _conn;
  18. private CancellationTokenSource _cancel = new CancellationTokenSource();
  19. private Task _openAndPollTableChangeTask;
  20.  
  21. private bool _isConnected;
  22. public bool IsConnected
  23. {
  24. get { return _isConnected; }
  25. set { SetField(ref _isConnected, value, "IsConnected"); }
  26. }
  27.  
  28. private DataView _users;
  29. public DataView Users
  30. {
  31. get { return _users; }
  32. set
  33. {
  34. //SetField(ref _users, value, "Users");
  35. // class ref is the same when we update...
  36. // call the property change manually each time the value is set!
  37. _users = value;
  38. OnPropertyChanged("Users");
  39. }
  40. }
  41.  
  42. public DataSet DBDataSet = new DataSet();
  43. public MySql.Data.MySqlClient.MySqlDataAdapter UsersDataAdapter;
  44.  
  45.  
  46. public DbManager(string connectionString)
  47. {
  48. _conn = new MySqlConnection(connectionString);
  49.  
  50. _openAndPollTableChangeTask = Task.Factory.StartNew(async() =>
  51. {
  52. string users_checksum = "";
  53. string current_checksum = "";
  54. while (true)
  55. {
  56. if (_cancel.IsCancellationRequested) return;
  57. try
  58. {
  59. _conn.Open();
  60. IsConnected = _conn.State == System.Data.ConnectionState.Open;
  61.  
  62. InitDB();
  63.  
  64. MySql.Data.MySqlClient.MySqlCommand cmd = new MySqlCommand("CHECKSUM TABLE `users`", _conn);
  65. MySql.Data.MySqlClient.MySqlDataReader reader;
  66.  
  67. while (true)
  68. {
  69. if (_cancel.IsCancellationRequested) return;
  70. if (!_isConnected) throw new Exception("Database disconnection detected...");
  71.  
  72. using (reader = cmd.ExecuteReader())
  73. {
  74. var t = reader.ReadAsync();
  75. await t;
  76. if (t.Result)
  77. {
  78. current_checksum = reader.GetString(1);
  79. }
  80. }
  81. if (users_checksum != current_checksum)
  82. {
  83. await UsersDataAdapter.FillAsync(DBDataSet, "users");
  84. Users = DBDataSet.Tables["users"].DefaultView;
  85. users_checksum = current_checksum;
  86. }
  87.  
  88.  
  89. // wait 5sec or until cancel token is raised
  90. try { Task.Delay(5000, _cancel.Token).Wait(_cancel.Token); } catch { }
  91. }
  92.  
  93. }
  94. catch (Exception ex)
  95. {
  96. var exxx = ex.Message;
  97. IsConnected = false;
  98. try { _conn.Close(); } catch { }
  99. }
  100.  
  101. // retry in 5sec or quit on cancel token
  102. try { Task.Delay(5000, _cancel.Token).Wait(_cancel.Token); } catch { }
  103. }
  104.  
  105. }, _cancel.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
  106. }
  107.  
  108. ~DbManager()
  109. {
  110. Dispose();
  111. }
  112.  
  113. public void Dispose()
  114. {
  115. Dispose(true);
  116. GC.SuppressFinalize(this);
  117. }
  118.  
  119. protected virtual void Dispose(bool disposing)
  120. {
  121. if (disposed)
  122. {
  123. return;
  124. }
  125.  
  126. if (disposing)
  127. {
  128. try { _cancel.Cancel(); } catch { }
  129. try { _conn.Close(); } catch { }
  130. try { _conn.Dispose(); } catch { }
  131. }
  132. disposed = true;
  133. }
  134.  
  135. public static async Task TestDb(string connectionString)
  136. {
  137. using (var conn = new MySqlConnection(connectionString))
  138. {
  139. await conn.OpenAsync();
  140. }
  141. }
  142.  
  143. public static void ControlBlink(System.Windows.Controls.Control control, int delay, System.Windows.Media.Brush color1, System.Windows.Media.Brush color2, CancellationToken cancel)
  144. {
  145. Task.Run(async () =>
  146. {
  147. while (!cancel.IsCancellationRequested)
  148. {
  149. await Task.Delay(delay, cancel);
  150. if (cancel.IsCancellationRequested) return;
  151. App.Current.Dispatcher.Invoke(() => { control.Background = control.Background == color1 ? color2 : color1; });
  152. }
  153. });
  154. }
  155.  
  156. public static string GetDatabaseConnectionString()
  157. {
  158. return string.Format("Server={0:s};Port={1:0};Database={2:s};Uid={3:s};Pwd={4:s};",
  159. Properties.Settings.Default.SqlServerHostname,
  160. Properties.Settings.Default.SqlServerPort,
  161. Properties.Settings.Default.SqlServerDbName,
  162. Properties.Settings.Default.SqlServerUserName,
  163. System.Text.ASCIIEncoding.UTF32.GetString(System.Convert.FromBase64String(Properties.Settings.Default.SqlServerUserPassword)));
  164. }
  165.  
  166. //private async Task<System.Data.DataSet> GetUsers()
  167. //{
  168. // using (MySqlConnection conn = new MySqlConnection(GetDatabaseConnectionString()))
  169. // {
  170. // using (MySqlDataAdapter adapter = new MySqlDataAdapter())
  171. // {
  172. // string query = "SELECT * FROM `users` ORDER BY `name`";
  173. // adapter.SelectCommand = new MySqlCommand(query, conn);
  174. // System.Data.DataSet ds = new System.Data.DataSet();
  175. // await adapter.FillAsync(ds);
  176. // return ds;
  177. // }
  178. // }
  179. //}
  180.  
  181. private void InitDB()
  182. {
  183. UsersDataAdapter = new MySqlDataAdapter();
  184. UsersDataAdapter.SelectCommand = new MySqlCommand("SELECT `id`,`name`,`birthdate` FROM `users`", _conn);
  185. UsersDataAdapter.InsertCommand = new MySqlCommand("INSERT INTO `users` (`name`, `birthdate`) VALUES (@name, @birthdate)", _conn);
  186. UsersDataAdapter.UpdateCommand = new MySqlCommand("UPDATE `users` SET `name` = @name, `birthdate` = @birthdate WHERE `id` = @id", _conn);
  187. UsersDataAdapter.DeleteCommand = new MySqlCommand("DELETE `users` WHERE `id` = @id", _conn);
  188. // activate primary key
  189. UsersDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
  190. }
  191. }
  192. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement