DatabaseActivityDashboard.xaml.cs 18 KB

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