-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindowViewModel.cs
More file actions
711 lines (568 loc) · 22.3 KB
/
MainWindowViewModel.cs
File metadata and controls
711 lines (568 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
using SkyLineSQL.Utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace SkyLineSQL
{
enum ProfilingStateEnum
{
psStopped,
psProfiling,
psPaused
}
public class SearchToken
{
public SearchToken()
{
Command = "";
Text = "";
}
private string command;
public string Command
{
get { return command.ToLower(); }
set { command = value.ToLower(); }
}
public string Text { get; set; }
}
public class PopupText
{
public string Heading { get; set; }
public string Text { get; set; }
}
public class MainWindowViewModel : INotifyPropertyChanged
{
private Visibility workInProgress = Visibility.Hidden;
public Visibility WorkInProgress
{
get { return workInProgress; }
set { workInProgress = value; OnPropertyChanged(); }
}
#region Popup
private bool isPopupOpen;
public bool IsPopupOpen
{
get { return isPopupOpen; }
set { isPopupOpen = value; OnPropertyChanged(); }
}
private bool inTab;
public bool InTab
{
get { return inTab; }
set { inTab = value; OnPropertyChanged(); }
}
private List<DataModel> tab_cols = new();
private string popupHeading;
public string PopupHeading
{
get { return popupHeading; }
set { popupHeading = value; OnPropertyChanged(); }
}
private string themeColor;
public string ThemeColor
{
get { return themeColor; }
set { themeColor = value; OnPropertyChanged(); OnPropertyChanged("ThemeColorDim"); }
}
public string ThemeColorDim
{
get { return themeColor + "FF"; }
}
#endregion
private string textBox = "";
public string TextBox
{
get { return textBox; }
set { textBox = value; OnPropertyChanged(); GenerateSearchToken(); }
}
private void GenerateSearchToken()
{
if (this.textBox.Contains(" "))
{
var parts = this.textBox.Split(" ");
var cmd = parts.First();
var txt = string.Join(" ", parts[1..]);
SearchToken.Command = cmd;
SearchToken.Text = txt;
}
else
{
SearchToken.Command = "a";
SearchToken.Text = this.textBox;
}
}
public ObservableCollection<DataModel> DatabaseObjects { get; set; }
public ObservableCollection<KPV> ColumnsOfObject { get; set; }
private Dictionary<string, int> usage = new();
public List<string> Conditions { get; set; }
private string previewText;
public string PreviewText
{
get { return previewText; }
set { previewText = value; OnPropertyChanged(); }
}
private ObservableCollection<object> tableData;
public ObservableCollection<object> TableData
{
get { return tableData; }
set { tableData = value; OnPropertyChanged(); }
}
private int selectedIndex;
public int SelectedIndex
{
get { return selectedIndex; }
set { selectedIndex = value; OnPropertyChanged(); }
}
ProfilerWindowViewModel profilerVM;
public DataManager DM { get; set; }
public SearchToken SearchToken { get; set; }
private CancellationTokenSource? cst;
public ICommand ChangeDatabaseCommand { get; }
public ICommand SearchDatabaseCommand { get; }
public ICommand ReloadDatabaseCommand { get; }
public ICommand NavigationUpCommand { get; }
public ICommand NavigationDownCommand { get; }
public ICommand SelectionCommand { get; }
public ICommand SelectionNameCommand { get; }
public ICommand PopupCommand { get; }
public ICommand ChangePreviewModeCommand { get; }
public ICommand TabClickCommand { get; }
public ICommand HideWindowCommand { get; }
public ICommand ExitCommand { get; }
string preview_mode = "External"; // "Normal" | "External" | "Table"
public MainWindowViewModel()
{
profilerVM = new();
DatabaseObjects = new();
ColumnsOfObject = new();
Conditions = new();
DM = new();
ThemeColor = DM.CurrentConnection.ThemeColor;
SearchToken = new();
//ChangeDatabaseCommand = new RelayCommand(ExecuteChangeDatabaseCommand);
ChangeDatabaseCommand = new RelayCommandAsync(ExecuteChangeDatabaseCommand);
SearchDatabaseCommand = new RelayCommandAsync(ExecuteSearchDatabaseCommand, CanExecuteSearchDatabaseCommand);
ReloadDatabaseCommand = new RelayCommand(ExecuteReloadDatabaseCommand);
NavigationUpCommand = new RelayCommandAsync(ExecuteNavigationUpCommand, CanExecuteNavigationUpCommand);
NavigationDownCommand = new RelayCommandAsync(ExecuteNavigationDownCommand, CanExecuteNavigationDownCommand);
SelectionCommand = new RelayCommandAsync(ExecuteSelectionCommand, CanExecuteSelectionCommand);
SelectionNameCommand = new RelayCommandAsync(ExecuteSelectionNameCommand, CanExecuteSelectionNameCommand);
PopupCommand = new RelayCommandAsync(ExecutePopupCommand, CanExecutePopupCommand);
ChangePreviewModeCommand = new RelayCommandAsync(ExecuteChangePreviewModeCommand, CanExecuteChangePreviewModeCommand);
TabClickCommand = new RelayCommandAsync(ExecuteTabClickCommandCommand, CanExecuteTabClickCommandCommand);
HideWindowCommand = new RelayCommand(ExecuteHideWindowCommand);
ExitCommand = new RelayCommand(ExecuteExitCommand);
}
private bool CanExecuteTabClickCommandCommand(object arg)
{
return DatabaseObjects.Count > 0 && SelectedIndex > -1 && SelectedIndex < DatabaseObjects.Count;
}
private async Task ExecuteTabClickCommandCommand(object arg)
{
cst?.Cancel(); // cancel previous search
cst = new CancellationTokenSource();
var token = cst.Token;
InTab = false;
var item = DatabaseObjects[SelectedIndex];
tab_cols.Clear();
DatabaseObjects.Clear();
ColumnsOfObject.Clear();
var cols = await DM.GetColumns(item, token);
foreach (var col in cols)
{
DataModel dm = new()
{
Name = col,
Type = Constant.Column,
ObjectId = 0
};
tab_cols.Add(dm);
DatabaseObjects.Add(dm);
}
if (DatabaseObjects.Count > 0)
{
InTab = true;
TextBox = "";
SelectedIndex = 0;
}
}
private async Task GenerateColumns(CancellationToken token)
{
Conditions.Clear();
int i = 1;
ColumnsOfObject.Clear();
var cols = await DM.GetColumns(DatabaseObjects[SelectedIndex], token);
foreach (var col in cols.Take(10))
{
ColumnsOfObject.Add(new(i, col));
i++;
}
}
private async Task GetPreviewText(CancellationToken token)
{
if (IsPopupOpen)
{
if (preview_mode.Equals("Normal"))
{
PreviewText = await DM.GetPreviewText(DatabaseObjects[SelectedIndex], token);
}
else if (preview_mode.Equals("External"))
{
PreviewText = await DM.PreviewExternalDBObject(DatabaseObjects[SelectedIndex], token);
}
else if (preview_mode.Equals("Table"))
{
PreviewText = await DM.PreviewTableObject(DatabaseObjects[SelectedIndex], "Jobs", token);
}
}
}
private async Task GetPreviewGrid(CancellationToken token)
{
if (IsPopupOpen)
TableData = new(await DM.GetPreviewGrid(DatabaseObjects[SelectedIndex], token));
}
private async Task ExecuteChangeDatabaseCommand(object param)
{
string key = param as string;
if (key.Equals("P"))
DM.ChangeDatabase(1);
else if (key.Equals("O"))
DM.ChangeDatabase(-1);
DatabaseObjects.Clear();
Conditions.Clear();
ColumnsOfObject.Clear();
ThemeColor = DM.CurrentConnection.ThemeColor;
if (!string.IsNullOrWhiteSpace(SearchToken.Text))
await ExecuteSearchDatabaseCommand(null);
}
private bool CanExecuteSearchDatabaseCommand(object param)
{
return (SearchToken.Text.Length >= 3 && SearchToken.Command.Length > 0) || InTab;
}
private async Task ExecuteSearchDatabaseCommand(object key)
{
if (InTab)
{
var cols = tab_cols.Where(x => x.Name.Contains(TextBox, StringComparison.OrdinalIgnoreCase)).ToList();
DatabaseObjects.Clear();
foreach (var col in cols)
{
DatabaseObjects.Add(col);
}
SelectedIndex = 0;
}
else
{
cst?.Cancel(); // cancel previous search
cst = new CancellationTokenSource();
var token = cst.Token;
try
{
//char keyChar = (char)key;
//if (char.IsDigit(keyChar))
//{
// int k = int.Parse(key.ToString());
// var c = ColumnsOfObject.FirstOrDefault(x => x.Key == k);
// if (c != null)
// {
// Conditions.Add(c.Value);
// return;
// }
//}
// debounce delay (tweak as needed)
await Task.Delay(300, token);
WorkInProgress = Visibility.Visible;
DatabaseObjects.Clear();
Conditions.Clear();
Dictionary<string, List<string>> SQlCommands = new()
{
{"u", new() { Constant.UserTable}},
{"p", new() { Constant.Procedure }},
{"t", new() { Constant.Trigger}},
{"f", new() { Constant.FunctionIF, Constant.FunctionFN}},
{"v", new() { Constant.View}},
{"a", new() { Constant.UserTable, Constant.Procedure, Constant.Trigger, Constant.FunctionIF, Constant.FunctionFN, Constant.View}},
};
List<string> filters = new();
bool deepSearch = false;
foreach (var cmdStr in SearchToken.Command)
{
var cmd = cmdStr.ToString().ToLower();
if (SQlCommands.ContainsKey(cmd))
{
filters.AddRange(SQlCommands[cmd]);
}
else if (cmd.Equals(Constant.DeepSearch))
{
deepSearch = true;
}
}
if (deepSearch && filters.Count == 0)
{
filters.AddRange(SQlCommands[Constant.AllSearch.ToLower()]);
}
if (deepSearch)
{
foreach (var item in await DM.SearchDeepObject(filters, SearchToken.Text, token))
{
DatabaseObjects.Add(item);
}
}
else
{
foreach (var item in await DM.SearchObject(filters, SearchToken.Text, token))
{
if (usage.ContainsKey(item.Name))
{
int count = usage[item.Name];
item.UsageCount = count;
}
if (!item.Star)
{
DatabaseObjects.Add(item);
}
else
{
var index = DatabaseObjects
.TakeWhile(x => x.Star && x.UsageCount >= item.UsageCount)
.Count();
DatabaseObjects.Insert(index, item);
}
}
}
if (DatabaseObjects.Count > 0)
{
SelectedIndex = 0;
GetPreviewText(token);
//GetPreviewGrid(token);
GenerateColumns(token);
}
}
catch (Exception)
{
// ignored
}
}
WorkInProgress = Visibility.Hidden;
}
private void ExecuteReloadDatabaseCommand(object param)
{
DM.LoadConnections();
}
private bool CanExecuteNavigationUpCommand(object param)
{
var index = (int)param;
return index > 0;
}
private async Task ExecuteNavigationUpCommand(object param)
{
cst?.Cancel(); // cancel previous search
cst = new CancellationTokenSource();
var token = cst.Token;
var index = (int)param;
SelectedIndex = index - 1;
//IsPopupOpen = false;
GetPreviewText(token);
//GetPreviewGrid(token);
GenerateColumns(token);
}
private bool CanExecuteNavigationDownCommand(object param)
{
var index = (int)param;
return index < DatabaseObjects.Count;
}
private async Task ExecuteNavigationDownCommand(object param)
{
cst?.Cancel(); // cancel previous search
cst = new CancellationTokenSource();
var token = cst.Token;
var index = (int)param;
SelectedIndex = index + 1;
//IsPopupOpen = false;
GetPreviewText(token);
//GetPreviewGrid(token);
GenerateColumns(token);
}
private bool CanExecuteSelectionCommand(object param)
{
return (SelectedIndex > -1 && SelectedIndex < DatabaseObjects.Count) || SearchToken.Command.Equals("prof") || SearchToken.Command.Equals("rpt");
}
public class MetaData
{
public string SPName;
public string TableName;
public string ColumnName;
}
private async Task ExecuteSelectionCommand(object param)
{
cst?.Cancel(); // cancel previous search
cst = new CancellationTokenSource();
var token = cst.Token;
MainWindow window = param as MainWindow;
if (window is not null)
{
window.Hide();
}
if (SearchToken.Text.Equals("prof"))
{
profilerVM.SetDataManager(DM);
ProfilerWindow profilerWindow = new($"{DM.CurrentConnection} - SQL Profiler", profilerVM);
profilerWindow.Show();
}
else if (SearchToken.Text.Equals("rpt"))
{
ColumnsOfObject.Clear();
ColumnsOfObject.Add(new(0, "Generating Report..."));
List<MetaData> list_res = new List<MetaData>();
var result = await DM.SearchObject(new List<string>() { Constant.FunctionFN, Constant.FunctionIF }, "", token);
int count = 1;
foreach (var res in result)
{
ColumnsOfObject.Add(new(1, $"{count++} / {result.Count()}"));
var str = await DM.GenerateReport(res, token);
list_res.AddRange(str);
ColumnsOfObject.Remove(ColumnsOfObject[1]);
}
await File.AppendAllLinesAsync("./output.txt", list_res.Select(x => $"{x.SPName},{x.TableName},{x.ColumnName}"));
foreach (var item in list_res.GroupBy(x => x.SPName))
{
var str = $"{item.Key} -> {item.Select(x => x.TableName).Distinct().Count()} Tables";
await File.AppendAllLinesAsync("./output_table_summery.txt", new[] { str });
}
foreach (var item in list_res.GroupBy(x => x.SPName))
{
var str = $"{item.Key} -> {item.Select(x => $"{x.TableName}.{x.ColumnName}").Distinct().Count()} Columns";
await File.AppendAllLinesAsync("./output_column_summery.txt", new[] { str });
}
foreach (var item in list_res.GroupBy(x => x.SPName))
{
var str = $"{item.Key} -> {item.Where(x => x.TableName.StartsWith("ExternalDB")).Select(x => x.TableName).Distinct().Count()} Tables";
await File.AppendAllLinesAsync("./output_external_table_summery.txt", new[] { str });
}
foreach (var item in list_res.GroupBy(x => x.SPName))
{
var str = $"{item.Key} -> {item.Where(x => x.TableName.StartsWith("ExternalDB")).Select(x => $"{x.TableName}.{x.ColumnName}").Distinct().Count()} Columns";
await File.AppendAllLinesAsync("./output_external_column_summery.txt", new[] { str });
}
ColumnsOfObject.Clear();
ColumnsOfObject.Add(new(0, "Completed"));
}
else
{
var SelectedItem = DatabaseObjects[SelectedIndex];
if (SelectedItem is not null)
{
usage.AddUpdate(SelectedItem.Name);
if (SelectedItem.Type.Equals(Constant.Column))
{
var text = SelectedItem.Name;
Clipboard.SetText(text);
Conditions.Clear();
}
else
{
var text = await DM.GetObject(SelectedItem, Conditions, token);
Clipboard.SetText(text);
Conditions.Clear();
}
InTab = false;
tab_cols.Clear();
}
}
}
private bool CanExecuteSelectionNameCommand(object param)
{
return (SelectedIndex > -1 && SelectedIndex < DatabaseObjects.Count) || SearchToken.Command.Equals("prof");
}
private async Task ExecuteSelectionNameCommand(object param)
{
MainWindow window = param as MainWindow;
if (window is not null)
{
window.Hide();
}
if (!preview_mode.Equals("Normal") && IsPopupOpen)
{
Clipboard.SetText(PreviewText);
Conditions.Clear();
}
else
{
var SelectedItem = DatabaseObjects[SelectedIndex];
if (SelectedItem is not null)
{
Clipboard.SetText(SelectedItem.Name);
}
}
}
private bool CanExecutePopupCommand(object param)
{
return true;
}
private async Task ExecutePopupCommand(object param)
{
IsPopupOpen = !IsPopupOpen;
}
private bool CanExecuteChangePreviewModeCommand(object param)
{
return true;
}
private async Task ExecuteChangePreviewModeCommand(object param)
{
if (preview_mode.Equals("Normal"))
{
preview_mode = "External";
}
else if (preview_mode.Equals("External"))
{
preview_mode = "Table";
}
else if (preview_mode.Equals("Table"))
{
preview_mode = "Normal";
}
else
{
preview_mode = "Normal";
}
cst?.Cancel(); // cancel previous search
cst = new CancellationTokenSource();
var token = cst.Token;
GetPreviewText(token);
ColumnsOfObject.Add(new(0, preview_mode));
await Task.Delay(1000);
ColumnsOfObject.Clear();
}
private void ExecuteHideWindowCommand(object param)
{
var window = param as MainWindow;
if (window is not null)
{
window.Hide();
InTab = false;
}
}
private void ExecuteExitCommand(object param) => System.Windows.Application.Current.Shutdown();
#region Notify
/// <inheritdoc cref="INotifyPropertyChanged.PropertyChanged"/>
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
ArgumentNullException.ThrowIfNull(e);
PropertyChanged?.Invoke(this, e);
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}