DatabaseActivityDashboard.xaml.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. new Columns<Employee>(
  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.TypeList(
  129. AppDomain.CurrentDomain.GetAssemblies(),
  130. x => x.IsSubclassOf(typeof(Entity)) && x.GetInterfaces().Contains(typeof(IRemotable))
  131. );
  132. foreach (var type in entities.OrderBy(x => x.Name))
  133. types[type.Name] = type.Name;
  134. TypesView.ItemsSource = types;
  135. LoadCategories("");
  136. Hours.Legend = new ChartLegend
  137. {
  138. LegendPosition = LegendPosition.Outside,
  139. DockPosition = ChartDock.Right,
  140. FontSize = 11
  141. };
  142. }
  143. public void Shutdown(CancelEventArgs? cancel)
  144. {
  145. }
  146. public event DataModelUpdateEvent? OnUpdateDataModel;
  147. public void Heartbeat(TimeSpan time)
  148. {
  149. }
  150. private bool HasData(List<History> history, DatabaseAction action)
  151. {
  152. foreach (var record in history)
  153. {
  154. var hasdata = action == DatabaseAction.Read ? record.Reads > 0 : record.Writes > 0;
  155. if (hasdata)
  156. return true;
  157. }
  158. return false;
  159. }
  160. private bool IsContrasted(byte b1, byte b2, int threshold)
  161. {
  162. var bDelta = b1 > b2 ? b1 - b2 : b2 - b1;
  163. return bDelta >= threshold;
  164. }
  165. private void LoadCategories(string typename)
  166. {
  167. history.Categories.Clear();
  168. if (string.IsNullOrWhiteSpace(typename))
  169. {
  170. var entities = CoreUtils.TypeList(
  171. AppDomain.CurrentDomain.GetAssemblies(),
  172. x => x.IsSubclassOf(typeof(Entity)) && x.GetInterfaces().Contains(typeof(IRemotable))
  173. );
  174. foreach (var type in entities.OrderBy(x => x.Name))
  175. history.Categories[type.Name] = type.Name;
  176. }
  177. else
  178. {
  179. foreach (var row in _employees.Rows)
  180. history.Categories[row.Get<Employee, Guid>(x => x.UserLink.ID).ToString()] = row.Get<Employee, string>(x => x.Name);
  181. }
  182. }
  183. private void ViewStyle_SelectionChanged(object sender, SelectionChangedEventArgs e)
  184. {
  185. if (history == null)
  186. return;
  187. history.View = ViewStyle.SelectedIndex == 0 ? HistoryView.Day :
  188. ViewStyle.SelectedIndex == 1 ? HistoryView.Week :
  189. ViewStyle.SelectedIndex == 2 ? HistoryView.Month : HistoryView.Year;
  190. Refresh();
  191. }
  192. private void StaffView_SelectionChanged(object sender, SelectionChangedEventArgs e)
  193. {
  194. if (history == null)
  195. return;
  196. if (e.AddedItems.Count > 0)
  197. {
  198. var id = ((KeyValuePair<Guid, string>)e.AddedItems[0]).Key;
  199. history.UserID = id;
  200. Refresh();
  201. }
  202. }
  203. private void AllStaff_Click(object sender, RoutedEventArgs e)
  204. {
  205. StaffView.SelectedValue = Guid.Empty;
  206. }
  207. private void TypesView_SelectionChanged(object sender, SelectionChangedEventArgs e)
  208. {
  209. if (e.AddedItems.Count > 0)
  210. {
  211. var type = ((KeyValuePair<string, string>)e.AddedItems[0]).Key;
  212. LoadCategories(type);
  213. history.Type = type;
  214. Refresh();
  215. }
  216. Refresh();
  217. }
  218. private void AllTypes_Click(object sender, RoutedEventArgs e)
  219. {
  220. TypesView.SelectedValue = "";
  221. }
  222. private void ActionsView_SelectionChanged(object sender, SelectionChangedEventArgs e)
  223. {
  224. if (history == null)
  225. return;
  226. history.Action = ActionsView.SelectedIndex == 0 ? DatabaseAction.Read : DatabaseAction.Update;
  227. Refresh();
  228. }
  229. private void Search_KeyUp(object sender, KeyEventArgs e)
  230. {
  231. if (string.IsNullOrWhiteSpace(Search.Text) || e.Key == Key.Return)
  232. {
  233. history.Search = Search.Text;
  234. Refresh();
  235. }
  236. }
  237. private void PrevDay_Click(object sender, RoutedEventArgs e)
  238. {
  239. history.Back();
  240. Refresh();
  241. }
  242. private void CurrentDate_MouseDoubleClick(object sender, MouseButtonEventArgs e)
  243. {
  244. history.To = DateTime.Today;
  245. Refresh();
  246. }
  247. private void NextDay_Click(object sender, RoutedEventArgs e)
  248. {
  249. history.Forward();
  250. Refresh();
  251. }
  252. private void Export_Click(object sender, RoutedEventArgs e)
  253. {
  254. }
  255. private void Hours_SelectionChanged(object sender, ChartSelectionChangedEventArgs e)
  256. {
  257. if (e.SelectedIndex == -1 && e.PreviousSelectedIndex > -1)
  258. {
  259. var series = Hours.Series.Where(x => x.IsSeriesVisible).ToArray();
  260. var value = series.ElementAt(e.PreviousSelectedIndex).Tag as string;
  261. if (string.IsNullOrWhiteSpace(history.Type))
  262. TypesView.SelectedValue = value;
  263. else
  264. StaffView.SelectedValue = Guid.Parse(value);
  265. }
  266. }
  267. public class History : BaseObject
  268. {
  269. public string Key;
  270. public History()
  271. {
  272. Reads = double.NaN;
  273. Writes = double.NaN;
  274. }
  275. public string Name { get; set; }
  276. public double Reads { get; set; }
  277. public double Writes { get; set; }
  278. }
  279. public class HistoryViewModel
  280. {
  281. private DatabaseAction _action = DatabaseAction.Update;
  282. private string _search = "";
  283. private DateTime _to = DateTime.MinValue;
  284. private string _type = "";
  285. private Guid _userid = Guid.Empty;
  286. private HistoryView _view = HistoryView.Day;
  287. public HistoryViewModel()
  288. {
  289. Categories = new Dictionary<string, string>();
  290. Summary = new Dictionary<string, List<History>>();
  291. To = DateTime.Today;
  292. }
  293. public HistoryView View
  294. {
  295. get => _view;
  296. set
  297. {
  298. _view = value;
  299. Refresh();
  300. }
  301. }
  302. public Guid UserID
  303. {
  304. get => _userid;
  305. set
  306. {
  307. _userid = value;
  308. Refresh();
  309. }
  310. }
  311. public string Type
  312. {
  313. get => _type;
  314. set
  315. {
  316. _type = value;
  317. Refresh();
  318. }
  319. }
  320. public DatabaseAction Action
  321. {
  322. get => _action;
  323. set
  324. {
  325. _action = value;
  326. Refresh();
  327. }
  328. }
  329. public DateTime To
  330. {
  331. get => _to.Date;
  332. set
  333. {
  334. _to = value;
  335. Refresh();
  336. }
  337. }
  338. public DateTime From => _view.Equals(HistoryView.Day) ? _to :
  339. _view.Equals(HistoryView.Week) ? _to.AddDays(-6) :
  340. _view.Equals(HistoryView.Month) ? _to.AddMonths(-1).AddDays(1) : _to.AddYears(-1).AddDays(1);
  341. public Dictionary<string, string> Categories { get; }
  342. public Dictionary<string, List<History>> Summary { get; set; }
  343. public string Search
  344. {
  345. get => _search;
  346. set
  347. {
  348. _search = value;
  349. Refresh();
  350. }
  351. }
  352. public void Forward()
  353. {
  354. To = _view.Equals(HistoryView.Day) ? _to.AddDays(1) :
  355. _view.Equals(HistoryView.Week) ? _to.AddDays(7) :
  356. _view.Equals(HistoryView.Month) ? _to.AddMonths(1) : _to.AddYears(1);
  357. }
  358. public void Back()
  359. {
  360. To = _view.Equals(HistoryView.Day) ? _to.AddDays(-1) :
  361. _view.Equals(HistoryView.Week) ? _to.AddDays(-7) :
  362. _view.Equals(HistoryView.Month) ? _to.AddMonths(-1) : _to.AddYears(-1);
  363. }
  364. private void AddSearchCriteria(Filter<UserTracking> filter, string search, params Expression<Func<UserTracking, object>>[] expressions)
  365. {
  366. var comps = search.Trim().Split(' ');
  367. foreach (var comp in comps)
  368. {
  369. Filter<UserTracking> result = null;
  370. foreach (var expression in expressions)
  371. result = result == null ? new Filter<UserTracking>(expression).Contains(comp) : result.Or(expression).Contains(comp);
  372. filter.Ands.Add(result);
  373. }
  374. }
  375. private List<History> CreateHistory(DateTime from)
  376. {
  377. var result = new List<History>();
  378. if (View == HistoryView.Day)
  379. for (var i = 0; i < 24; i++)
  380. {
  381. var history = new History();
  382. history.Key = string.Format("{0:hhtt}", DateTime.MinValue.AddHours(i));
  383. history.Name = history.Key;
  384. result.Add(history);
  385. }
  386. else
  387. for (var date = from; date <= _to; date = date.AddDays(1))
  388. {
  389. var history = new History();
  390. history.Key = string.Format("{0:dd/MM}", date);
  391. history.Name = history.Key;
  392. result.Add(history);
  393. }
  394. return result;
  395. }
  396. private void UpdateHistory(List<History> list, CoreRow row, DateTime from)
  397. {
  398. if (View == HistoryView.Day)
  399. {
  400. for (var i = 0; i < 24; i++)
  401. {
  402. var reads = row.Get<int>(string.Format("Hour{0:D2}Read", i));
  403. if (reads > 0)
  404. list[i].Reads = (double.IsNaN(list[i].Reads) ? 0.00F : list[i].Reads) + reads;
  405. var writes = row.Get<int>(string.Format("Hour{0:D2}Write", i));
  406. if (writes > 0)
  407. list[i].Writes = (double.IsNaN(list[i].Writes) ? 0.00F : list[i].Writes) + writes;
  408. }
  409. }
  410. else
  411. {
  412. var index = row.Get<UserTracking, DateTime>(x => x.Date).Date.Subtract(from.Date).Days;
  413. var reads = row.Get<UserTracking, int>(x => x.TotalRead);
  414. if (reads > 0)
  415. list[index].Reads = (double.IsNaN(list[index].Reads) ? 0.00F : list[index].Reads) + reads;
  416. var writes = row.Get<UserTracking, int>(x => x.TotalWrite);
  417. if (writes > 0)
  418. list[index].Writes = (double.IsNaN(list[index].Writes) ? 0.00F : list[index].Writes) + writes;
  419. }
  420. }
  421. private void Refresh()
  422. {
  423. var from = _view.Equals(HistoryView.Day) ? _to.AddDays(-1) :
  424. _view.Equals(HistoryView.Week) ? _to.AddDays(-7) :
  425. _view.Equals(HistoryView.Month) ? _to.AddMonths(-1) : _to.AddYears(-1);
  426. var criteria = new Filter<UserTracking>(x => x.Date).IsGreaterThan(from).And(x => x.Date).IsLessThanOrEqualTo(_to);
  427. if (!_userid.Equals(Guid.Empty))
  428. criteria = criteria.And(x => x.User.ID).IsEqualTo(_userid);
  429. if (!string.IsNullOrWhiteSpace(_type))
  430. criteria = criteria.And(x => x.Type).IsEqualTo(_type);
  431. if (!string.IsNullOrWhiteSpace(_search))
  432. criteria = criteria.TextSearch(
  433. Search,
  434. x => x.User.UserID,
  435. x => x.Type
  436. );
  437. var data = new Client<UserTracking>().Query(
  438. criteria,
  439. null,
  440. new SortOrder<UserTracking>(x => x.User.UserID)
  441. );
  442. Summary.Clear();
  443. foreach (var key in Categories.Keys)
  444. Summary[key] = CreateHistory(from);
  445. foreach (var row in data.Rows)
  446. {
  447. var entity = "";
  448. if (string.IsNullOrEmpty(_type))
  449. entity = row.Get<UserTracking, string>(x => x.Type);
  450. else
  451. entity = row.Get<UserTracking, Guid>(x => x.User.ID).ToString();
  452. if (Summary.ContainsKey(entity))
  453. UpdateHistory(Summary[entity], row, from);
  454. }
  455. }
  456. }
  457. }
  458. }