DatabaseActivityDashboard.xaml.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6. using System.Reflection;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Input;
  10. using System.Windows.Media;
  11. using System.Windows.Media.Imaging;
  12. using Comal.Classes;
  13. using InABox.Clients;
  14. using InABox.Configuration;
  15. using InABox.Core;
  16. using InABox.WPF;
  17. using InABox.Wpf;
  18. using PRSDesktop.WidgetGroups;
  19. using Syncfusion.UI.Xaml.Charts;
  20. namespace PRSDesktop
  21. {
  22. public class DatabaseActivityDashboardProperties : IUserConfigurationSettings, IDashboardProperties { }
  23. public class DatabaseActivityDashboardElement : DashboardElement<DatabaseActivityDashboard, WidgetGroups.System, DatabaseActivityDashboardProperties> { }
  24. /// <summary>
  25. /// Interaction logic for DatabaseActivityDashboard.xaml
  26. /// </summary>
  27. public partial class DatabaseActivityDashboard : UserControl, IPanel<UserTracking>, IDashboardWidget<WidgetGroups.System, DatabaseActivityDashboardProperties>
  28. {
  29. public enum DatabaseAction
  30. {
  31. Read,
  32. Update
  33. }
  34. public enum HistoryView
  35. {
  36. Day,
  37. Week,
  38. Month,
  39. Year
  40. }
  41. private CoreTable _employees;
  42. private readonly BitmapImage back = PRSDesktop.Resources.back.AsBitmapImage(32, 32);
  43. private HistoryViewModel history;
  44. private readonly BitmapImage next = PRSDesktop.Resources.next.AsBitmapImage(32, 32);
  45. public DatabaseActivityDashboard()
  46. {
  47. InitializeComponent();
  48. PrevDay.Content = new Image { Source = back };
  49. NextDay.Content = new Image { Source = next };
  50. }
  51. public bool IsReady { get; set; }
  52. public void CreateToolbarButtons(IPanelHost host)
  53. {
  54. }
  55. public string SectionName => "Database Activity";
  56. public DatabaseActivityDashboardProperties Properties { get; set; }
  57. public event LoadSettings<DatabaseActivityDashboardProperties>? LoadSettings;
  58. public event SaveSettings<DatabaseActivityDashboardProperties>? SaveSettings;
  59. public DataModel DataModel(Selection selection)
  60. {
  61. return new DatabaseActivityDataModel(history);
  62. }
  63. public void Refresh()
  64. {
  65. if (!IsReady)
  66. return;
  67. if (history.To == DateTime.MinValue)
  68. history.To = DateTime.Today;
  69. if (history.View == HistoryView.Day)
  70. CurrentDate.Text = string.Format("{0:ddd, dd MMMM yyyy}", history.To);
  71. else
  72. CurrentDate.Text = string.Format("{0:dd MMM yy} - {1:dd MMM yy}", history.From, history.To);
  73. var colors = new List<Color>();
  74. var props = typeof(Colors).GetProperties(BindingFlags.Static | BindingFlags.Public).Where(x => x.PropertyType == typeof(Color));
  75. foreach (var prop in props)
  76. {
  77. var color = (Color)prop.GetValue(null);
  78. if (color != Colors.Transparent && (color.R < 128 || color.G < 128 || color.B < 128))
  79. colors.Add(color);
  80. }
  81. Hours.Series.Clear();
  82. foreach (var key in history.Summary.Keys)
  83. {
  84. var seriesdata = history.Summary[key];
  85. if (HasData(seriesdata, history.Action))
  86. {
  87. var series = new ScatterSeries();
  88. series.ShowEmptyPoints = false;
  89. series.ShowTooltip = true;
  90. series.TooltipTemplate = Hours.Resources["tooltipTemplate"] as DataTemplate;
  91. series.ItemsSource = seriesdata;
  92. series.XBindingPath = "Name";
  93. series.YBindingPath = history.Action == DatabaseAction.Read ? "Reads" : "Writes";
  94. series.Label = history.Categories[key];
  95. series.Tag = key;
  96. var colorindex = Hours.Series.Count % colors.Count;
  97. var color = colors[colorindex];
  98. series.Stroke = new SolidColorBrush(color);
  99. series.Interior = new SolidColorBrush(color);
  100. Hours.Series.Add(series);
  101. }
  102. }
  103. AllStaff.Width = history.UserID.Equals(Guid.Empty) ? new GridLength(0) : new GridLength(70);
  104. AllTypes.Width = string.IsNullOrWhiteSpace(history.Type) ? new GridLength(0) : new GridLength(70);
  105. }
  106. public Dictionary<string, object[]> Selected()
  107. {
  108. return new Dictionary<string, object[]>();
  109. }
  110. public void Setup()
  111. {
  112. history = new HistoryViewModel();
  113. DataContext = history;
  114. var emplookups = new Dictionary<Guid, string> { { Guid.Empty, "All Staff" } };
  115. _employees = new Client<Employee>().Query(
  116. LookupFactory.DefineFilter<Employee>(),
  117. Columns.None<Employee>().Add(
  118. x => x.ID,
  119. x => x.UserLink.ID,
  120. x => x.Name
  121. ),
  122. new SortOrder<Employee>(x => x.Name)
  123. );
  124. foreach (var row in _employees.Rows)
  125. emplookups[row.Get<Employee, Guid>(x => x.UserLink.ID)] = row.Get<Employee, string>(x => x.Name);
  126. StaffView.ItemsSource = emplookups;
  127. var types = new Dictionary<string, string> { { "", "All Types" } };
  128. var entities = CoreUtils.Entities.Where(
  129. x => x.IsSubclassOf(typeof(Entity)) && x.GetInterfaces().Contains(typeof(IRemotable))
  130. );
  131. foreach (var type in entities.OrderBy(x => x.Name))
  132. types[type.Name] = type.Name;
  133. TypesView.ItemsSource = types;
  134. LoadCategories("");
  135. Hours.Legend = new ChartLegend
  136. {
  137. LegendPosition = LegendPosition.Outside,
  138. DockPosition = ChartDock.Right,
  139. FontSize = 11
  140. };
  141. }
  142. public void Shutdown(CancelEventArgs? cancel)
  143. {
  144. }
  145. public event DataModelUpdateEvent? OnUpdateDataModel;
  146. public void Heartbeat(TimeSpan time)
  147. {
  148. }
  149. private bool HasData(List<History> history, DatabaseAction action)
  150. {
  151. foreach (var record in history)
  152. {
  153. var hasdata = action == DatabaseAction.Read ? record.Reads > 0 : record.Writes > 0;
  154. if (hasdata)
  155. return true;
  156. }
  157. return false;
  158. }
  159. private bool IsContrasted(byte b1, byte b2, int threshold)
  160. {
  161. var bDelta = b1 > b2 ? b1 - b2 : b2 - b1;
  162. return bDelta >= threshold;
  163. }
  164. private void LoadCategories(string typename)
  165. {
  166. history.Categories.Clear();
  167. if (string.IsNullOrWhiteSpace(typename))
  168. {
  169. var entities = CoreUtils.Entities.Where(
  170. x => x.IsSubclassOf(typeof(Entity)) && x.GetInterfaces().Contains(typeof(IRemotable))
  171. );
  172. foreach (var type in entities.OrderBy(x => x.Name))
  173. history.Categories[type.Name] = type.Name;
  174. }
  175. else
  176. {
  177. foreach (var row in _employees.Rows)
  178. history.Categories[row.Get<Employee, Guid>(x => x.UserLink.ID).ToString()] = row.Get<Employee, string>(x => x.Name);
  179. }
  180. }
  181. private void ViewStyle_SelectionChanged(object sender, SelectionChangedEventArgs e)
  182. {
  183. if (history == null)
  184. return;
  185. history.View = ViewStyle.SelectedIndex == 0 ? HistoryView.Day :
  186. ViewStyle.SelectedIndex == 1 ? HistoryView.Week :
  187. ViewStyle.SelectedIndex == 2 ? HistoryView.Month : HistoryView.Year;
  188. Refresh();
  189. }
  190. private void StaffView_SelectionChanged(object sender, SelectionChangedEventArgs e)
  191. {
  192. if (history == null)
  193. return;
  194. if (e.AddedItems.Count > 0)
  195. {
  196. var id = ((KeyValuePair<Guid, string>)e.AddedItems[0]).Key;
  197. history.UserID = id;
  198. Refresh();
  199. }
  200. }
  201. private void AllStaff_Click(object sender, RoutedEventArgs e)
  202. {
  203. StaffView.SelectedValue = Guid.Empty;
  204. }
  205. private void TypesView_SelectionChanged(object sender, SelectionChangedEventArgs e)
  206. {
  207. if (e.AddedItems.Count > 0)
  208. {
  209. var type = ((KeyValuePair<string, string>)e.AddedItems[0]).Key;
  210. LoadCategories(type);
  211. history.Type = type;
  212. Refresh();
  213. }
  214. Refresh();
  215. }
  216. private void AllTypes_Click(object sender, RoutedEventArgs e)
  217. {
  218. TypesView.SelectedValue = "";
  219. }
  220. private void ActionsView_SelectionChanged(object sender, SelectionChangedEventArgs e)
  221. {
  222. if (history == null)
  223. return;
  224. history.Action = ActionsView.SelectedIndex == 0 ? DatabaseAction.Read : DatabaseAction.Update;
  225. Refresh();
  226. }
  227. private void Search_KeyUp(object sender, KeyEventArgs e)
  228. {
  229. if (string.IsNullOrWhiteSpace(Search.Text) || e.Key == Key.Return)
  230. {
  231. history.Search = Search.Text;
  232. Refresh();
  233. }
  234. }
  235. private void PrevDay_Click(object sender, RoutedEventArgs e)
  236. {
  237. history.Back();
  238. Refresh();
  239. }
  240. private void CurrentDate_MouseDoubleClick(object sender, MouseButtonEventArgs e)
  241. {
  242. history.To = DateTime.Today;
  243. Refresh();
  244. }
  245. private void NextDay_Click(object sender, RoutedEventArgs e)
  246. {
  247. history.Forward();
  248. Refresh();
  249. }
  250. private void Export_Click(object sender, RoutedEventArgs e)
  251. {
  252. }
  253. private void Hours_SelectionChanged(object sender, ChartSelectionChangedEventArgs e)
  254. {
  255. if (e.SelectedIndex == -1 && e.PreviousSelectedIndex > -1)
  256. {
  257. var series = Hours.Series.Where(x => x.IsSeriesVisible).ToArray();
  258. var value = series.ElementAt(e.PreviousSelectedIndex).Tag as string;
  259. if (string.IsNullOrWhiteSpace(history.Type))
  260. TypesView.SelectedValue = value;
  261. else
  262. StaffView.SelectedValue = Guid.Parse(value);
  263. }
  264. }
  265. public class History : BaseObject
  266. {
  267. public string Key;
  268. public History()
  269. {
  270. Reads = double.NaN;
  271. Writes = double.NaN;
  272. }
  273. public string Name { get; set; }
  274. public double Reads { get; set; }
  275. public double Writes { get; set; }
  276. }
  277. public class HistoryViewModel
  278. {
  279. private DatabaseAction _action = DatabaseAction.Update;
  280. private string _search = "";
  281. private DateTime _to = DateTime.MinValue;
  282. private string _type = "";
  283. private Guid _userid = Guid.Empty;
  284. private HistoryView _view = HistoryView.Day;
  285. public HistoryViewModel()
  286. {
  287. Categories = new Dictionary<string, string>();
  288. Summary = new Dictionary<string, List<History>>();
  289. To = DateTime.Today;
  290. }
  291. public HistoryView View
  292. {
  293. get => _view;
  294. set
  295. {
  296. _view = value;
  297. Refresh();
  298. }
  299. }
  300. public Guid UserID
  301. {
  302. get => _userid;
  303. set
  304. {
  305. _userid = value;
  306. Refresh();
  307. }
  308. }
  309. public string Type
  310. {
  311. get => _type;
  312. set
  313. {
  314. _type = value;
  315. Refresh();
  316. }
  317. }
  318. public DatabaseAction Action
  319. {
  320. get => _action;
  321. set
  322. {
  323. _action = value;
  324. Refresh();
  325. }
  326. }
  327. public DateTime To
  328. {
  329. get => _to.Date;
  330. set
  331. {
  332. _to = value;
  333. Refresh();
  334. }
  335. }
  336. public DateTime From => _view.Equals(HistoryView.Day) ? _to :
  337. _view.Equals(HistoryView.Week) ? _to.AddDays(-6) :
  338. _view.Equals(HistoryView.Month) ? _to.AddMonths(-1).AddDays(1) : _to.AddYears(-1).AddDays(1);
  339. public Dictionary<string, string> Categories { get; }
  340. public Dictionary<string, List<History>> Summary { get; set; }
  341. public string Search
  342. {
  343. get => _search;
  344. set
  345. {
  346. _search = value;
  347. Refresh();
  348. }
  349. }
  350. public void Forward()
  351. {
  352. To = _view.Equals(HistoryView.Day) ? _to.AddDays(1) :
  353. _view.Equals(HistoryView.Week) ? _to.AddDays(7) :
  354. _view.Equals(HistoryView.Month) ? _to.AddMonths(1) : _to.AddYears(1);
  355. }
  356. public void Back()
  357. {
  358. To = _view.Equals(HistoryView.Day) ? _to.AddDays(-1) :
  359. _view.Equals(HistoryView.Week) ? _to.AddDays(-7) :
  360. _view.Equals(HistoryView.Month) ? _to.AddMonths(-1) : _to.AddYears(-1);
  361. }
  362. private void AddSearchCriteria(Filter<UserTracking> filter, string search, params Expression<Func<UserTracking, object>>[] expressions)
  363. {
  364. var comps = search.Trim().Split(' ');
  365. foreach (var comp in comps)
  366. {
  367. Filter<UserTracking> result = null;
  368. foreach (var expression in expressions)
  369. result = result == null ? new Filter<UserTracking>(expression).Contains(comp) : result.Or(expression).Contains(comp);
  370. filter.Ands.Add(result);
  371. }
  372. }
  373. private List<History> CreateHistory(DateTime from)
  374. {
  375. var result = new List<History>();
  376. if (View == HistoryView.Day)
  377. for (var i = 0; i < 24; i++)
  378. {
  379. var history = new History();
  380. history.Key = string.Format("{0:hhtt}", DateTime.MinValue.AddHours(i));
  381. history.Name = history.Key;
  382. result.Add(history);
  383. }
  384. else
  385. for (var date = from; date <= _to; date = date.AddDays(1))
  386. {
  387. var history = new History();
  388. history.Key = string.Format("{0:dd/MM}", date);
  389. history.Name = history.Key;
  390. result.Add(history);
  391. }
  392. return result;
  393. }
  394. private void UpdateHistory(List<History> list, CoreRow row, DateTime from)
  395. {
  396. if (View == HistoryView.Day)
  397. {
  398. for (var i = 0; i < 24; i++)
  399. {
  400. var reads = row.Get<int>(string.Format("Hour{0:D2}Read", i));
  401. if (reads > 0)
  402. list[i].Reads = (double.IsNaN(list[i].Reads) ? 0.00F : list[i].Reads) + reads;
  403. var writes = row.Get<int>(string.Format("Hour{0:D2}Write", i));
  404. if (writes > 0)
  405. list[i].Writes = (double.IsNaN(list[i].Writes) ? 0.00F : list[i].Writes) + writes;
  406. }
  407. }
  408. else
  409. {
  410. var index = row.Get<UserTracking, DateTime>(x => x.Date).Date.Subtract(from.Date).Days;
  411. var reads = row.Get<UserTracking, int>(x => x.TotalRead);
  412. if (reads > 0)
  413. list[index].Reads = (double.IsNaN(list[index].Reads) ? 0.00F : list[index].Reads) + reads;
  414. var writes = row.Get<UserTracking, int>(x => x.TotalWrite);
  415. if (writes > 0)
  416. list[index].Writes = (double.IsNaN(list[index].Writes) ? 0.00F : list[index].Writes) + writes;
  417. }
  418. }
  419. private void Refresh()
  420. {
  421. var from = _view.Equals(HistoryView.Day) ? _to.AddDays(-1) :
  422. _view.Equals(HistoryView.Week) ? _to.AddDays(-7) :
  423. _view.Equals(HistoryView.Month) ? _to.AddMonths(-1) : _to.AddYears(-1);
  424. var criteria = new Filter<UserTracking>(x => x.Date).IsGreaterThan(from).And(x => x.Date).IsLessThanOrEqualTo(_to);
  425. if (!_userid.Equals(Guid.Empty))
  426. criteria = criteria.And(x => x.User.ID).IsEqualTo(_userid);
  427. if (!string.IsNullOrWhiteSpace(_type))
  428. criteria = criteria.And(x => x.Type).IsEqualTo(_type);
  429. if (!string.IsNullOrWhiteSpace(_search))
  430. criteria = criteria.TextSearch(
  431. Search,
  432. x => x.User.UserID,
  433. x => x.Type
  434. );
  435. var data = new Client<UserTracking>().Query(
  436. criteria,
  437. null,
  438. new SortOrder<UserTracking>(x => x.User.UserID)
  439. );
  440. Summary.Clear();
  441. foreach (var key in Categories.Keys)
  442. Summary[key] = CreateHistory(from);
  443. foreach (var row in data.Rows)
  444. {
  445. var entity = "";
  446. if (string.IsNullOrEmpty(_type))
  447. entity = row.Get<UserTracking, string>(x => x.Type);
  448. else
  449. entity = row.Get<UserTracking, Guid>(x => x.User.ID).ToString();
  450. if (Summary.ContainsKey(entity))
  451. UpdateHistory(Summary[entity], row, from);
  452. }
  453. }
  454. }
  455. }
  456. }