-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFullAudit.razor
More file actions
1194 lines (1084 loc) · 50 KB
/
FullAudit.razor
File metadata and controls
1194 lines (1084 loc) · 50 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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!--/* In the name of God, the Merciful, the Compassionate */-->
@page "/fullaudit"
@using SQLTriage.Data
@using SQLTriage.Data.Models
@using System.IO
@using System.Text
@using Microsoft.Extensions.Logging
@using System.Diagnostics
@using System.Text.Json
@inject DiagnosticScriptRunner ScriptRunner
@inject ServerConnectionManager ConnectionManager
@inject FullAuditStateService AuditState
@inject IJSRuntime JSRuntime
@inject ILogger<FullAudit> Logger
@inject SQLTriage.Data.ToastService Toast
@inject SQLTriage.Data.Services.ReportPageConfigService ReportPageCfg
@inject UserSettingsService UserSettings
@implements IDisposable
<PageTitle>Full Audit - SQLTriage</PageTitle>
<SQLTriage.Components.Shared.SectionEditorModal IsVisible="_faEditingSection != null"
Section="_faEditingSection"
NativeKeys="_faAvailableNativeKeys"
AvailableFields="_faFields"
OnSave="FaHandleSectionSaved"
OnCancel="() => _faEditingSection = null" />
<SQLTriage.Components.Shared.AddSectionModal IsVisible="_faShowAddSection"
NativeKeys="_faAvailableNativeKeys"
OnAdd="FaHandleSectionAdded"
OnCancel="() => _faShowAddSection = false" />
<div class="full-audit-container">
<SQLTriage.Components.Shared.EditPageToolbar EditMode="_faEditMode"
PageTitle="Full Audit"
HasUnsavedChanges="false"
OnAddSection="() => _faShowAddSection = true"
OnDone="() => _faEditMode = false"
OnReset="FaResetSections" />
<div style="display:flex; align-items:baseline; gap:12px;">
<h1>Full Audit / Diagnostic Scripts</h1>
<button class="btn-edit-page @(_faEditMode ? "btn-edit-page--active" : "")"
@onclick="() => _faEditMode = !_faEditMode" title="Edit page layout">
<i class="fa-solid fa-pen-to-square"></i> Edit Page
</button>
</div>
<p class="description">Run diagnostic scripts on SQL servers and export results to CSV</p>
@if (_isLoading)
{
<div class="loading">
<p>Loading...</p>
</div>
}
else
{
<!-- Server Connection Section -->
<SQLTriage.Components.Shared.ReportSectionWrapper Section="@FaGetSection("server-selection")" EditMode="_faEditMode"
IsFirst="@FaIsFirst("server-selection")" IsLast="@FaIsLast("server-selection")"
OnMoveUp="s => FaMoveSection(s, -1)" OnMoveDown="s => FaMoveSection(s, 1)"
OnEdit="s => _faEditingSection = s" OnDelete="s => FaDeleteSection(s)"
OnToggle="s => FaToggleSection(s)">
<div class="connection-section">
<div class="section-header">
<h2>Server Connections</h2>
<div class="header-actions">
<button class="btn btn-secondary" @onclick="TestAllConnections" disabled="@_isTesting">
@(_isTesting ? "Testing..." : "Test All")
</button>
<button class="btn btn-primary" @onclick="ShowAddConnectionDialog">
+ Add Connections
</button>
</div>
</div>
@if (_connections.Count == 0)
{
<div class="no-connections">
<p>No server connections configured. Add server names to get started.</p>
</div>
}
else
{
<div class="connection-list">
@foreach (var conn in _connections)
{
<div class="connection-card @(SelectedConnection?.Id == conn.Id ? "selected" : "")"
@onclick="() => SelectConnection(conn)">
<div class="connection-info">
<div class="connection-name">
@conn.GetServerCount() Servers
@if (conn.IsConnected)
{
<span class="badge success">@conn.SuccessfulServers.Count Connected</span>
}
else
{
<span class="badge">Not Tested</span>
}
</div>
<div class="connection-details">
Database: @conn.Database | Auth: @(conn.UseWindowsAuthentication ? "Windows" : "SQL")
</div>
@if (conn.SuccessfulServers.Count > 0)
{
<div class="successful-servers">
<small>Connected: @string.Join(", ", conn.SuccessfulServers.Take(3))@(conn.SuccessfulServers.Count > 3 ? "..." : "")</small>
</div>
}
</div>
<div class="connection-actions">
<button class="btn btn-sm" @onclick="() => EditConnection(conn)"
@onclick:stopPropagation>
Edit
</button>
<button class="btn btn-sm btn-danger" @onclick="() => DeleteConnection(conn.Id)"
@onclick:stopPropagation>
Delete
</button>
</div>
</div>
}
</div>
}
</div>
<!-- Server Selector -->
@if (AllSuccessfulServers.Count > 0)
{
<div class="server-selector">
<h3>Select Target Server</h3>
<div class="server-buttons">
@foreach (var (conn, server) in AllSuccessfulServers)
{
<button class="server-btn @(SelectedServer == server ? "selected" : "")"
@onclick="() => SelectServer(conn, server)">
@server
</button>
}
</div>
</div>
}
</SQLTriage.Components.Shared.ReportSectionWrapper>
<!-- Scripts + Progress Section -->
@if (SelectedConnection != null && SelectedServer != null)
{
<SQLTriage.Components.Shared.ReportSectionWrapper Section="@FaGetSection("progress")" EditMode="_faEditMode"
IsFirst="@FaIsFirst("progress")" IsLast="@FaIsLast("progress")"
OnMoveUp="s => FaMoveSection(s, -1)" OnMoveDown="s => FaMoveSection(s, 1)"
OnEdit="s => _faEditingSection = s" OnDelete="s => FaDeleteSection(s)"
OnToggle="s => FaToggleSection(s)">
<div class="scripts-section">
<div class="section-header">
<h2>Diagnostic Scripts - @SelectedServer</h2>
<div class="script-actions">
@if (AllSuccessfulServers.Count > 0)
{
<div class="run-all-group">
<div class="run-mode-toggle">
<button class="run-mode-btn @(_parallelMode ? "" : "active")"
@onclick="() => _parallelMode = false" disabled="@_isRunning"
title="Run each server one at a time">
<i class="fa-solid fa-list-ol"></i> Sequential
</button>
<button class="run-mode-btn @(_parallelMode ? "active" : "")"
@onclick="() => _parallelMode = true" disabled="@_isRunning"
title="Start all servers concurrently, staggered by delay">
<i class="fa-solid fa-bolt"></i> Parallel
</button>
</div>
@if (_parallelMode)
{
<div class="delay-input-group" title="Seconds to wait before starting each subsequent server">
<i class="fa-solid fa-stopwatch" style="color:var(--text-secondary);font-size:12px;"></i>
<input type="number" min="0" max="300" step="1"
@bind="_parallelDelaySeconds"
style="width:52px;padding:3px 6px;border-radius:4px;border:1px solid var(--border);background:var(--bg-secondary);color:var(--text-primary);font-size:12px;"
disabled="@_isRunning" />
<span style="font-size:11px;color:var(--text-muted);">s delay</span>
</div>
}
<button class="btn btn-warning" @onclick="RequestRunAllServers" disabled="@_isRunning">
@if (_isRunning)
{
<span>Running...</span>
}
else if (_parallelMode)
{
<i class="fa-solid fa-bolt" style="margin-right:4px;"></i><span>Run all (@AllSuccessfulServers.Count) — Parallel</span>
}
else
{
<i class="fa-solid fa-list-ol" style="margin-right:4px;"></i><span>Run all (@AllSuccessfulServers.Count) — Sequential</span>
}
</button>
</div>
}
<button class="btn btn-primary" @onclick="RunSelectedScripts" disabled="@(_isRunning || _selectedScriptIds.Count == 0)">
@(_isRunning ? "Running..." : "Run Selected (" + _selectedScriptIds.Count + ")")
</button>
<a href="/editauditscripts" class="btn btn-secondary" title="Edit script configurations">
<i class="fa-solid fa-file-pen" style="margin-right: 4px;"></i> Edit Scripts
</a>
</div>
</div>
@if (_isRunning)
{
<div class="progress-container">
<div class="progress-info">
<span>Server: @CurrentServerName</span>
<span>Script: @CurrentScriptName</span>
<span>@ProgressPercent.ToString("F0")%</span>
@if (ElapsedTime.TotalSeconds > 0)
{
<span>Elapsed: @ElapsedTime.ToString(@"mm\:ss")</span>
}
</div>
<div class="progress-bar">
<div class="progress-fill" style="width: @ProgressPercent%"></div>
</div>
<div class="progress-detail">
Server @CurrentServerIndex of @TotalServers | Script @CurrentScriptIndex of @TotalScripts
</div>
</div>
}
<div class="script-select-bar" style="display:flex; align-items:center; gap:12px; margin-bottom:8px;">
<label style="display:flex; align-items:center; gap:4px; cursor:pointer;">
<input type="checkbox" checked="@(_selectedScriptIds.Count == _scripts.Count)"
@onchange="ToggleSelectAll" />
Select All
</label>
<span class="text-muted" style="font-size:0.85em;">@_selectedScriptIds.Count of @_scripts.Count selected</span>
</div>
<div class="script-list">
@foreach (var script in _scripts)
{
var sid = script.Id;
<div class="script-card @(_selectedScriptIds.Contains(sid) ? "enabled" : "disabled")">
<div class="script-header">
<div class="script-info" style="display:flex; align-items:flex-start; gap:8px;">
<input type="checkbox" checked="@(_selectedScriptIds.Contains(sid))"
@onchange="() => ToggleScriptSelection(sid)"
style="margin-top:4px; cursor:pointer;" />
<div>
<h3>@script.Name</h3>
<p>@script.Description</p>
</div>
</div>
<div class="script-actions">
<button class="btn btn-sm" @onclick="() => RunScript(script)" disabled="@_isRunning">
@(_isRunning ? "Running..." : "Run")
</button>
<!--
@if (GetResultForScript(script.Name) != null)
{
<button class="btn btn-sm btn-secondary" @onclick="() => ExportScriptToCsv(GetResultForScript(script.Name)!)">
Export CSV
</button>
}-->
</div>
</div>
@if (GetResultForScript(script.Name) != null)
{
var result = GetResultForScript(script.Name)!;
<div class="script-result @(result.Success ? "success" : "error")">
<div class="result-header">
<span class="status">@(result.Success ? (result.StatusMessage ?? "✓ Success") : "✗ Error")</span>
<span class="execution-time">@result.ExecutionTime.TotalSeconds.ToString("F2")s</span>
<span class="rows">@result.RowsAffected rows</span>
</div>
@if (!string.IsNullOrEmpty(result.ErrorMessage))
{
<p class="error-details">@result.ErrorMessage</p>
}
@if (result.Results != null && result.Results.Count > 0)
{
<div class="result-preview">
<h4>Preview (first 5 rows):</h4>
<table class="preview-table">
<thead>
<tr>
@foreach (var key in result.Results.First().Keys)
{
<th>@key</th>
}
</tr>
</thead>
<tbody>
@foreach (var row in result.Results.Take(5))
{
<tr>
@foreach (var value in row.Values)
{
<td>@(value?.ToString() ?? "NULL")</td>
}
</tr>
}
</tbody>
</table>
</div>
}
</div>
}
</div>
}
</div>
</div>
</SQLTriage.Components.Shared.ReportSectionWrapper>
<!-- Summary / Results Section -->
@if (_executionResults.Count > 0)
{
<SQLTriage.Components.Shared.ReportSectionWrapper Section="@FaGetSection("results")" EditMode="_faEditMode"
IsFirst="@FaIsFirst("results")" IsLast="@FaIsLast("results")"
OnMoveUp="s => FaMoveSection(s, -1)" OnMoveDown="s => FaMoveSection(s, 1)"
OnEdit="s => _faEditingSection = s" OnDelete="s => FaDeleteSection(s)"
OnToggle="s => FaToggleSection(s)">
<div class="summary-section">
<div class="summary-header">
<button class="btn btn-sm btn-secondary"@onclick="() => openfolder()">
Open output folder
</button>
<button class="btn btn-sm btn-danger" @onclick="ClearResults">
Clear Results
</button>
</div>
<h2>Execution Summary</h2>
<table class="summary-table">
<thead>
<tr>
<th>Server</th>
<th>Script</th>
<th>Status</th>
<th>Execution Time</th>
<th>Rows</th>
<th>Result</th>
</tr>
</thead>
<tbody>
@foreach (var result in _executionResults)
{
<tr>
<td>@result.ServerName</td>
<td>@result.ScriptName</td>
<td>@(result.Success ? (result.StatusMessage ?? "✓ Success") : "✗ Error")</td>
<td>@result.ExecutionTime.TotalSeconds.ToString("F2")s</td>
<td>@result.RowsAffected</td>
<td>
@if (result.Success && result.Results != null)
{
<a>Exported to CSV</a>
}
</td>
</tr>
}
</tbody>
</table>
</div>
</SQLTriage.Components.Shared.ReportSectionWrapper>
}
}
else if (SelectedConnection != null)
{
<div class="no-selection">
<p>No connected servers. Click "Test All" to test server connections, or edit the connection to add/remove servers.</p>
</div>
}
}
<!-- Connection Dialog -->
<ConnectionDialog
@bind-Show="_showConnectionDialog"
EditingConnection="_editingConnection"
OnConnectionSaved="OnConnectionSaved" />
<!-- Parallel Execution Confirm Modal -->
@if (_showParallelModal)
{
<div class="fa-modal-backdrop" @onclick="CancelParallelModal">
<div class="fa-modal" @onclick:stopPropagation>
<div class="fa-modal-header">
<i class="fa-solid @(_parallelMode ? "fa-bolt" : "fa-list-ol")"
style="color:@(_parallelMode ? "var(--yellow)" : "var(--accent)");font-size:20px;"></i>
<h3 style="margin:0;">@(_parallelMode ? "Parallel" : "Sequential") Server Execution</h3>
</div>
<div class="fa-modal-body">
@if (_parallelMode)
{
<p style="margin:0 0 12px;">
Running audit scripts across all <strong>@AllSuccessfulServers.Count servers</strong> simultaneously
may <strong>improve overall completion time</strong> but will place concurrent load on each server and on this host.
</p>
<p style="color:var(--yellow);font-size:13px;margin:0;">
<i class="fa-solid fa-triangle-exclamation" style="margin-right:6px;"></i>
This may impact the underlying infrastructure's performance in large environments.
</p>
}
else
{
<p style="margin:0;">
Run audit scripts across all <strong>@AllSuccessfulServers.Count servers</strong> one at a time,
in order. Each server completes before the next begins.
</p>
}
</div>
<div class="fa-modal-footer">
<button class="btn btn-secondary" @onclick="CancelParallelModal">Cancel</button>
<button class="btn @(_parallelMode ? "btn-warning" : "btn-primary")" @onclick="ConfirmRun">
@if (_parallelMode)
{
<i class="fa-solid fa-bolt" style="margin-right:5px;"></i>
<span>Run Parallel</span>
}
else
{
<i class="fa-solid fa-list-ol" style="margin-right:5px;"></i>
<span>Run Sequential</span>
}
</button>
</div>
</div>
</div>
}
</div>
@code {
private List<ServerConnection> _connections = new();
private List<ScriptConfiguration> _scripts = new();
private HashSet<string> _selectedScriptIds = new();
private ServerConnection? SelectedConnection { get; set; }
private string? SelectedServer { get; set; }
private bool _isLoading = true;
// ── Parallel execution modal ──────────────────────────────────────────
private bool _showParallelModal;
private bool _parallelMode = false;
private int _parallelDelaySeconds = 5;
// ── Report Page Editor ────────────────────────────────────────────────
private bool _faEditMode;
private List<ReportSection> _faSections = new();
private ReportSection? _faEditingSection;
private bool _faShowAddSection;
private ReportPageDefinition? _faPageDef;
private static readonly List<string> FaAllNativeKeys =
new() { "server-selection", "progress", "results" };
private static readonly List<ReportFieldInfo> _faFields = new()
{
new() { Name = "CheckId", Type = "string", Description = "Unique check identifier", IsKey = true },
new() { Name = "DisplayName", Type = "string", Description = "Human-readable check name", IsKey = false },
new() { Name = "Category", Type = "string", Description = "Check category (Security, Performance, etc.)", IsKey = false },
new() { Name = "Severity", Type = "string", Description = "Finding severity: Critical, Warning, Info, Pass", IsKey = false },
new() { Name = "Result", Type = "string", Description = "Raw result or finding text", IsKey = false },
new() { Name = "Details", Type = "string", Description = "Extended description or recommendation", IsKey = false },
new() { Name = "ServerName", Type = "string", Description = "SQL Server instance name", IsKey = true },
new() { Name = "Database", Type = "string", Description = "Target database (if applicable)", IsKey = false },
new() { Name = "RunDateUtc", Type = "datetime", Description = "UTC time the assessment was run", IsKey = false },
new() { Name = "IsPass", Type = "bit", Description = "1 if the check passed, 0 if it raised a finding", IsKey = false },
new() { Name = "ImplementationType", Type = "string", Description = "Fix method: Script, Config, Manual, etc.", IsKey = false },
new() { Name = "SqlQuery", Type = "string", Description = "Suggested remediation SQL", IsKey = false },
};
private List<string> _faAvailableNativeKeys =>
FaAllNativeKeys.Where(k => !_faSections.Any(s => s.NativeKey == k && s.SectionType == "native")).ToList();
private ReportSection FaGetSection(string nativeKey)
{
var s = _faSections.FirstOrDefault(x => x.NativeKey == nativeKey && x.SectionType == "native");
return s ?? new ReportSection { NativeKey = nativeKey, Title = nativeKey, SectionType = "native", Enabled = true };
}
private bool FaIsFirst(string nativeKey)
{
var ordered = _faSections.OrderBy(s => s.Order).ToList();
return ordered.FindIndex(s => s.NativeKey == nativeKey && s.SectionType == "native") <= 0;
}
private bool FaIsLast(string nativeKey)
{
var ordered = _faSections.OrderBy(s => s.Order).ToList();
var idx = ordered.FindIndex(s => s.NativeKey == nativeKey && s.SectionType == "native");
return idx < 0 || idx == ordered.Count - 1;
}
private void FaLoadSections()
{
_faPageDef = ReportPageCfg.GetPage("/fullaudit");
_faSections = _faPageDef != null
? _faPageDef.Sections.OrderBy(s => s.Order).ToList()
: FaAllNativeKeys.Select((k, i) => new ReportSection { NativeKey = k, Title = k, SectionType = "native", Order = i, Enabled = true }).ToList();
}
private void FaMoveSection(ReportSection s, int dir) { if (_faPageDef != null) { ReportPageCfg.MoveSection(_faPageDef.Id, s.Id, dir); FaLoadSections(); StateHasChanged(); } }
private void FaDeleteSection(ReportSection s) { if (_faPageDef != null) { ReportPageCfg.DeleteSection(_faPageDef.Id, s.Id); FaLoadSections(); StateHasChanged(); } }
private void FaToggleSection(ReportSection s) { if (_faPageDef != null) { s.Enabled = !s.Enabled; ReportPageCfg.UpsertSection(_faPageDef.Id, s); FaLoadSections(); StateHasChanged(); } }
private void FaHandleSectionSaved(ReportSection s)
{
if (_faPageDef == null) return;
ReportPageCfg.UpsertSection(_faPageDef.Id, s);
FaLoadSections();
_faEditingSection = null;
StateHasChanged();
}
private void FaHandleSectionAdded(ReportSection s)
{
if (_faPageDef == null) return;
s.Order = _faSections.Count;
ReportPageCfg.UpsertSection(_faPageDef.Id, s);
FaLoadSections();
_faShowAddSection = false;
StateHasChanged();
}
private void FaResetSections()
{
if (_faPageDef == null) return;
foreach (var s in _faSections.ToList()) ReportPageCfg.DeleteSection(_faPageDef.Id, s.Id);
int i = 0;
foreach (var key in FaAllNativeKeys)
ReportPageCfg.UpsertSection(_faPageDef.Id, new ReportSection
{
Id = Guid.NewGuid().ToString("N")[..8],
Title = key, NativeKey = key, SectionType = "native", Enabled = true, Order = i++
});
FaLoadSections();
StateHasChanged();
}
// Progress tracking - now uses state service
private double ProgressPercent => AuditState.ProgressPercent;
private int TotalServers => AuditState.TotalServers;
private int CurrentServerIndex => AuditState.CurrentServerIndex;
private string CurrentServerName => AuditState.CurrentServerName;
private int TotalScripts => AuditState.TotalScripts;
private int CurrentScriptIndex => AuditState.CurrentScriptIndex;
private string CurrentScriptName => AuditState.CurrentScriptName;
private TimeSpan ElapsedTime => AuditState.ElapsedTime;
// Property to get all successful servers from all connections
private List<(ServerConnection Connection, string ServerName)> AllSuccessfulServers
{
get
{
var result = new List<(ServerConnection, string)>();
foreach (var conn in _connections)
{
foreach (var server in conn.SuccessfulServers)
{
result.Add((conn, server));
}
}
return result;
}
}
private bool _showConnectionDialog = false;
private ServerConnection? _editingConnection;
private string StatusMessage = string.Empty;
private string StatusMessageClass = string.Empty;
private string FiletimeStamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
// Properties that use the state service for persistence
private List<ScriptExecutionResult> _executionResults
{
get => AuditState.GetAllExecutionResults();
}
private bool _isRunning
{
get => AuditState.IsRunning;
set => AuditState.IsRunning = value;
}
private bool _isTesting
{
get => AuditState.IsTesting;
set => AuditState.IsTesting = value;
}
protected override void OnInitialized()
{
FaLoadSections();
LoadConnections();
RestoreState();
ScriptRunner.OnBlobUploadResult += OnBlobUploadResult;
}
private void OnBlobUploadResult(string fileName, bool success, string message)
{
InvokeAsync(() =>
{
if (success)
Toast.ShowSuccess($"Azure upload: {fileName}");
else
Toast.ShowError($"Azure upload failed: {fileName} — {message}");
});
}
public void Dispose()
{
ScriptRunner.OnBlobUploadResult -= OnBlobUploadResult;
}
private void RestoreState()
{
// Restore selected connection and server from state
if (!string.IsNullOrEmpty(AuditState.SelectedConnectionId))
{
var conn = _connections.FirstOrDefault(c => c.Id == AuditState.SelectedConnectionId);
if (conn != null)
{
SelectedConnection = conn;
if (!string.IsNullOrEmpty(AuditState.SelectedServer))
{
SelectedServer = AuditState.SelectedServer;
}
}
}
}
private void SaveState()
{
AuditState.SelectedConnectionId = SelectedConnection?.Id;
AuditState.SelectedServer = SelectedServer;
}
private void openfolder()
{
var outputFolder = Path.Combine(AppContext.BaseDirectory, "output");
Process.Start("explorer.exe", outputFolder);
//Process.Start(@".\output");
}
private void ClearResults()
{
AuditState.ClearExecutionResults();
}
private void LoadConnections()
{
_connections = ConnectionManager.GetConnections();
if (SelectedConnection == null && _connections.Count > 0)
{
SelectedConnection = _connections.First();
if (SelectedConnection.SuccessfulServers.Count > 0)
{
SelectedServer = SelectedConnection.SuccessfulServers.First();
}
}
LoadScripts();
}
private void LoadScripts()
{
try
{
_scripts = ScriptRunner.LoadScriptConfigurations();
_selectedScriptIds = new HashSet<string>(_scripts.Where(s => s.Enabled).Select(s => s.Id));
}
catch (Exception ex)
{
Logger.LogError(ex, "Error loading script configurations");
}
_isLoading = false;
}
private void SelectConnection(ServerConnection connection)
{
SelectedConnection = connection;
SelectedServer = null;
AuditState.ClearExecutionResults();
if (connection.SuccessfulServers.Count > 0)
{
SelectedServer = connection.SuccessfulServers.First();
}
SaveState();
}
private void SelectServer(ServerConnection connection, string server)
{
SelectedConnection = connection;
SelectedServer = server;
AuditState.ClearExecutionResults();
SaveState();
}
private void ShowAddConnectionDialog()
{
_editingConnection = null;
_showConnectionDialog = true;
}
private void EditConnection(ServerConnection connection)
{
_editingConnection = connection;
_showConnectionDialog = true;
}
private void DeleteConnection(string id)
{
if (SelectedConnection?.Id == id)
{
SelectedConnection = null;
SelectedServer = null;
}
ConnectionManager.RemoveConnection(id);
_connections = ConnectionManager.GetConnections();
}
private async Task OnConnectionSaved()
{
_connections = ConnectionManager.GetConnections();
if (_editingConnection != null)
{
var updated = ConnectionManager.GetConnection(_editingConnection.Id);
if (updated != null)
{
SelectedConnection = updated;
SelectedServer = null;
if (updated.SuccessfulServers.Count > 0)
{
SelectedServer = updated.SuccessfulServers.First();
}
}
}
else if (SelectedConnection == null && _connections.Count > 0)
{
SelectedConnection = _connections.First();
if (SelectedConnection.SuccessfulServers.Count > 0)
{
SelectedServer = SelectedConnection.SuccessfulServers.First();
}
}
SaveState();
await Task.CompletedTask;
}
private async Task TestAllConnections()
{
_isTesting = true;
foreach (var conn in _connections)
{
var successfulServers = new List<string>();
foreach (var server in conn.GetServerList())
{
try
{
await Task.Run(() =>
{
// Use master database for connection test to allow testing before SQLWATCH is deployed
using var connection = new Microsoft.Data.SqlClient.SqlConnection(conn.GetConnectionString(server, "master"));
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = "SELECT @@VERSION";
var version = command.ExecuteScalar();
if (version != null)
{
successfulServers.Add(server);
}
});
}
catch (Exception ex)
{
Logger.LogError(ex, "Connection test failed for {Server}", server);
}
}
conn.SuccessfulServers = successfulServers;
conn.IsConnected = successfulServers.Count > 0;
conn.LastConnected = successfulServers.Count > 0 ? DateTime.Now : null;
}
// Update all connections' successful servers in ConnectionManager
foreach (var conn in _connections)
{
ConnectionManager.UpdateSuccessfulServers(conn.Id, conn.SuccessfulServers);
}
if (SelectedConnection != null && SelectedConnection.SuccessfulServers.Count > 0)
{
SelectedServer = SelectedConnection.SuccessfulServers.First();
}
_isTesting = false;
}
private void ToggleScriptSelection(string scriptId)
{
if (!_selectedScriptIds.Remove(scriptId))
_selectedScriptIds.Add(scriptId);
}
private void ToggleSelectAll()
{
if (_selectedScriptIds.Count == _scripts.Count)
_selectedScriptIds.Clear();
else
_selectedScriptIds = new HashSet<string>(_scripts.Select(s => s.Id));
}
private List<ScriptConfiguration> GetSelectedScripts() =>
_scripts.Where(s => _selectedScriptIds.Contains(s.Id)).OrderBy(s => s.ExecutionOrder).ToList();
private async Task RunSelectedScripts()
{
if (SelectedServer == null || SelectedConnection == null) return;
var selected = GetSelectedScripts();
if (selected.Count == 0) return;
AuditState.StartExecution(1, selected.Count, false);
AuditState.UpdateProgress(1, SelectedServer, 0, "Running...");
AuditState.ClearExecutionResults();
StateHasChanged();
try
{
var results = new List<ScriptExecutionResult>();
int idx = 0;
foreach (var script in selected)
{
idx++;
AuditState.UpdateProgress(1, SelectedServer, idx, script.Name);
StateHasChanged();
var result = await ScriptRunner.ExecuteScriptAsync(script, SelectedConnection, SelectedServer);
results.Add(result);
AuditState.AddExecutionResult(result);
}
AuditState.UpdateProgress(1, SelectedServer, selected.Count, "Complete");
Toast.ShowSuccess("Full Audit complete: " + SelectedServer + " — " + results.Count + " script(s) run");
await AutoExportAuditResults(results, SelectedServer);
}
finally
{
AuditState.IsRunning = false;
}
}
private void RequestRunAllServers()
{
if (GetSelectedScripts().Count == 0) return;
_showParallelModal = true;
}
private void CancelParallelModal() => _showParallelModal = false;
private async Task ConfirmRun()
{
_showParallelModal = false;
if (_parallelMode)
await RunAgainstAllServersParallel();
else
await RunAgainstAllServers();
}
/// <summary>
/// Starts each server's audit concurrently, staggered by _parallelDelaySeconds.
/// Each server executes its scripts serially in order; results stream back as they complete.
/// </summary>
private async Task RunAgainstAllServersParallel()
{
var allServers = AllSuccessfulServers;
if (allServers.Count == 0) return;
var selected = GetSelectedScripts();
if (selected.Count == 0) return;
AuditState.StartExecution(allServers.Count, selected.Count, true);
AuditState.ClearExecutionResults();
try
{
var tasks = new List<Task>();
int serverIndex = 0;
foreach (var (conn, server) in allServers)
{
serverIndex++;
var capturedIndex = serverIndex;
var capturedConn = conn;
var capturedServer = server;
// Stagger start: each server waits delay × (index-1) before beginning
var startDelay = TimeSpan.FromSeconds(_parallelDelaySeconds * (capturedIndex - 1));
tasks.Add(Task.Run(async () =>
{
if (startDelay > TimeSpan.Zero)
await Task.Delay(startDelay);
await InvokeAsync(() =>
{
AuditState.UpdateProgress(capturedIndex, capturedServer, 0, "");
StateHasChanged();
});
var results = new List<ScriptExecutionResult>();
int scriptIndex = 0;
foreach (var script in selected)
{
scriptIndex++;
await InvokeAsync(() =>
{
AuditState.UpdateProgress(capturedIndex, capturedServer, scriptIndex, script.Name);
StateHasChanged();
});
var result = await ScriptRunner.ExecuteScriptAsync(script, capturedConn, capturedServer);
result.ScriptName = "[" + capturedServer + "] " + result.ScriptName;
results.Add(result);
await InvokeAsync(() =>
{
AuditState.AddExecutionResult(result);
StateHasChanged();
});
}
await InvokeAsync(() =>
{
Toast.ShowInfo("Full Audit: " + capturedServer + " complete (" + results.Count + " scripts, " + capturedIndex + "/" + allServers.Count + ")");
StateHasChanged();
});
await AutoExportAuditResults(results, capturedServer);
}));
}
await Task.WhenAll(tasks);
}
finally
{
AuditState.IsRunning = false;
await InvokeAsync(StateHasChanged);
}
}
private async Task RunAgainstAllServers()
{
var allServers = AllSuccessfulServers;
if (allServers.Count == 0) return;
var selected = GetSelectedScripts();
if (selected.Count == 0) return;
AuditState.StartExecution(allServers.Count, selected.Count, true);
AuditState.ClearExecutionResults();
try
{
var groupedByConnection = allServers.GroupBy(s => s.Connection.Id);
int serverIndex = 0;
foreach (var group in groupedByConnection)
{
var connection = group.First().Connection;
foreach (var (conn, server) in group)
{
serverIndex++;
AuditState.UpdateProgress(serverIndex, server, 0, "");
var results = new List<ScriptExecutionResult>();
int scriptIndex = 0;
foreach (var script in selected)
{
scriptIndex++;
AuditState.UpdateProgress(serverIndex, server, scriptIndex, script.Name);
StateHasChanged();
var result = await ScriptRunner.ExecuteScriptAsync(script, conn, server);
result.ScriptName = "[" + server + "] " + result.ScriptName;
results.Add(result);
AuditState.AddExecutionResult(result);
}
Toast.ShowInfo("Full Audit: " + server + " complete (" + results.Count + " scripts, " + serverIndex + "/" + allServers.Count + ")");
await AutoExportAuditResults(results, server);
}
}
}
finally
{
AuditState.IsRunning = false;
}
}
private async Task RunScript(ScriptConfiguration script)
{
if (SelectedServer == null || SelectedConnection == null) return;
AuditState.StartExecution(1, 1, false);