DatabaseActivityDashboard.xaml.cs 18 KB

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