-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm2.cs
More file actions
795 lines (681 loc) · 35.3 KB
/
Copy pathForm2.cs
File metadata and controls
795 lines (681 loc) · 35.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
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
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Reflection;
using System.Speech.Synthesis;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Newtonsoft.Json;
namespace WebToolsDataMonitor
{
public partial class Form2 : Form
{
private ListView statusListView;
private ToolStrip topToolStrip;
private StatusStrip bottomStatusStrip;
private ToolStripStatusLabel countStatusLabel;
private List<StatusLineItem> _masterItems = new List<StatusLineItem>();
private bool _showImportantOnly = false;
private ToolStripButton btnFilterToggle;
private const int HashColumnIndex = 5; // "Hash" is the 6th column (0-based) - see Columns.Add order in SetupCustomControls
private ToolTip _hashCellToolTip;
// Tracks which (Tool, Device, Metric) alert keys currently have an armed/played alert, so a
// persisting bad status doesn't replay the sound on every scrape, but a resolved-then-recurring one
// does. Lives for this Form2 instance's lifetime - a fresh dashboard starts with no memory of prior
// alerts (see ProcessAlerts).
private readonly HashSet<string> _activeAlertKeys = new HashSet<string>();
private readonly SpeechSynthesizer _speechSynthesizer = new SpeechSynthesizer();
// Session-only (not saved to app_config.yaml) - whether ActiveProblems alerts get their detail
// text spoken. Defaults checked every time the dashboard opens.
private CheckBox chkSpeakProblemDetails;
public Form2()
{
InitializeComponent();
SetupCustomControls();
}
private void SetupCustomControls()
{
this.Text = "Matrix Operational Command Center";
this.Size = new Size(1000, 550);
this.StartPosition = FormStartPosition.CenterScreen;
// 1. Initialize Toolbar layout
topToolStrip = new ToolStrip();
btnFilterToggle = new ToolStripButton("Filter: Show All", null, OnFilterToggleClick)
{
CheckOnClick = true,
BackColor = Color.LightGray
};
// 🔥 NEW Sound/Speech Alert Controls - state restored from app_config.yaml, saved on change
var alertsState = AppConfig.Instance.Data.Alerts;
ToolStripLabel lblAlertThreshold = new ToolStripLabel("Sound Alert From:");
ToolStripComboBox cboAlertThreshold = new ToolStripComboBox { DropDownStyle = ComboBoxStyle.DropDownList };
cboAlertThreshold.Items.AddRange(new object[] { "Off", "Info", "Warning", "Average", "Disaster" });
cboAlertThreshold.SelectedItem = cboAlertThreshold.Items.Cast<string>().Contains(alertsState.Threshold)
? alertsState.Threshold
: "Warning";
cboAlertThreshold.SelectedIndexChanged += (s, e) =>
{
AppConfig.Instance.Data.Alerts.Threshold = cboAlertThreshold.SelectedItem?.ToString() ?? "Off";
AppConfig.Instance.Save();
};
CheckBox chkSpeakAlerts = new CheckBox
{
Text = "Speak Device/Metric",
AutoSize = true,
Checked = alertsState.SpeakDeviceAndMetric
};
chkSpeakAlerts.CheckedChanged += (s, e) =>
{
AppConfig.Instance.Data.Alerts.SpeakDeviceAndMetric = chkSpeakAlerts.Checked;
AppConfig.Instance.Save();
};
// Not persisted to app_config.yaml by design - always defaults to checked on a fresh dashboard.
chkSpeakProblemDetails = new CheckBox
{
Text = "Speak Problem Details",
AutoSize = true,
Checked = true
};
CheckBox chkAlwaysOnTop = new CheckBox
{
Text = "Always On Top",
AutoSize = true,
Checked = this.TopMost
};
chkAlwaysOnTop.CheckedChanged += (s, e) => this.TopMost = chkAlwaysOnTop.Checked;
topToolStrip.Items.Add(btnFilterToggle);
topToolStrip.Items.Add(new ToolStripSeparator());
topToolStrip.Items.Add(lblAlertThreshold);
topToolStrip.Items.Add(cboAlertThreshold);
topToolStrip.Items.Add(new ToolStripControlHost(chkSpeakAlerts));
topToolStrip.Items.Add(new ToolStripControlHost(chkSpeakProblemDetails));
topToolStrip.Items.Add(new ToolStripSeparator());
topToolStrip.Items.Add(new ToolStripControlHost(chkAlwaysOnTop));
// 2. Initialize Statusbar layout
bottomStatusStrip = new StatusStrip();
countStatusLabel = new ToolStripStatusLabel("Total Managed Traces: 0 Rows");
bottomStatusStrip.Items.Add(countStatusLabel);
// 3. Initialize Checked Columns Matrix ListView
statusListView = new ListView
{
Dock = DockStyle.Fill,
View = View.Details,
FullRowSelect = true,
CheckBoxes = true,
GridLines = true,
OwnerDraw = true
};
statusListView.Columns.Add("Check", 50);
statusListView.Columns.Add("Engine Tool", 100);
statusListView.Columns.Add("Device Endpoint Node", 160);
statusListView.Columns.Add("Target Metric Track / Context", 180);
statusListView.Columns.Add("Operational State Current Value", 420);
statusListView.Columns.Add("Hash", 40); // Compact display ("..."); hover to see the underlying identity via tooltip
_hashCellToolTip = new ToolTip();
statusListView.DrawColumnHeader += (s, e) => e.DrawDefault = true;
statusListView.DrawItem += StatusListView_DrawItem;
statusListView.DrawSubItem += StatusListView_DrawSubItem;
statusListView.KeyDown += StatusListView_KeyDown;
statusListView.MouseMove += StatusListView_MouseMove;
ContextMenuStrip rowContextMenu = new ContextMenuStrip();
ToolStripMenuItem editFormulaItem = new ToolStripMenuItem("Define Custom Rule Threshold...", null, OnEditFormulaClick);
ToolStripMenuItem copyRowsItem = new ToolStripMenuItem("Copy Selected Rows (Ctrl+C)", null, (s, e) => CopySelectedRowsToClipboard());
rowContextMenu.Items.Add(editFormulaItem);
rowContextMenu.Items.Add(copyRowsItem);
statusListView.ContextMenuStrip = rowContextMenu;
this.Controls.Add(statusListView);
this.Controls.Add(topToolStrip);
this.Controls.Add(bottomStatusStrip);
// SpeechSynthesizer holds an OS audio resource - release it when this dashboard closes rather
// than leaking one per Form2 instance over a long continuous-run session that reopens it.
this.FormClosed += (s, e) => _speechSynthesizer.Dispose();
}
private void StatusListView_DrawItem(object sender, DrawListViewItemEventArgs e)
{
e.DrawBackground();
}
private void StatusListView_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
if (e.Item.Tag is StatusLineItem model)
{
Color backColor = Color.White;
Color textColor = Color.Black;
switch (model.ConditionSource.ToLower())
{
case "disaster-bg":
case "metadisaster":
backColor = Color.DarkRed;
textColor = Color.White;
break;
case "average-bg":
case "metaaverage":
case "high-bg": // 🔥 FIXED: Zabbix's own severity CSS class for its "High" level (ExtractActiveProblems reads Zabbix's *-bg class directly) - was never mapped, so High problems showed with no color at all instead of being treated as Average
backColor = Color.OrangeRed;
textColor = Color.White;
break;
case "warning-bg":
case "metawarning": // 🔥 FIXED: was "metawning" (typo) - never matched the real "MetaWarning" value produced by StatusLineDto's fallback rules, so warning rows never actually got highlighted
backColor = Color.Khaki;
textColor = Color.DarkSlateBlue;
break;
case "info-bg":
case "metainfo":
backColor = Color.LightSkyBlue;
textColor = Color.Black;
break;
}
if (e.ColumnIndex == 0)
{
e.DrawDefault = true;
return;
}
using (SolidBrush brush = new SolidBrush(backColor))
{
e.Graphics.FillRectangle(brush, e.Bounds);
}
if (e.Item.Selected)
{
using (SolidBrush selectBrush = new SolidBrush(Color.FromArgb(50, Color.Blue)))
{
e.Graphics.FillRectangle(selectBrush, e.Bounds);
}
}
TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis;
TextRenderer.DrawText(e.Graphics, e.SubItem.Text, e.Item.Font, e.Bounds, textColor, flags);
}
}
// Replaces all previously-reported rows for this exact (tool, page, script) triple with the fresh
// batch, instead of appending - a script's rows are keyed by which script/page/tool produced them,
// so re-running it updates existing rows in place (by value, since they're rebuilt from _masterItems)
// rather than accumulating duplicates, and rows the latest run no longer reports (e.g. a resolved
// problem or an extension that disappeared) get cleared instead of staying behind as dead rows.
// Which rows belong to this batch is decided by a single precomputed RowHash (see RowHasher) instead
// of comparing the three fields separately each time.
public void ReplaceScriptResults(string tool, string pageUrl, string scriptName, List<StatusLineItem> items)
{
if (this.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)(() => ReplaceScriptResults(tool, pageUrl, scriptName, items)));
return;
}
string batchHash = RowHasher.ComputeHash(tool, pageUrl, scriptName);
// Alert keys of the rows being replaced, captured before removal, so ProcessAlerts can tell
// which previously-alerting metrics simply vanished from this batch (the script stopped
// reporting them) - those un-arm too, exactly like a resolved-then-recurring problem.
var oldRowKeys = new HashSet<string>(
_masterItems.Where(i => string.Equals(i.RowHash, batchHash, StringComparison.Ordinal))
.Select(GetAlertKey));
_masterItems.RemoveAll(existing => string.Equals(existing.RowHash, batchHash, StringComparison.Ordinal));
// Insert at the front (not appended) so RefreshListViewGrid's top-to-bottom rebuild keeps the
// freshest batch at the top of the grid, matching the previous "newest on top" insert-at-0 behavior.
_masterItems.InsertRange(0, items);
ProcessAlerts(items, oldRowKeys);
RefreshListViewGrid();
}
// Sound/speech alerting: a row "arms" the first time its severity qualifies (rank <= the configured
// threshold) and hasn't already been alerted; it stays armed (no replay) while it keeps qualifying,
// and un-arms the moment it stops qualifying - whether it recovers to a normal value or simply
// disappears from this batch entirely - so a later recurrence alerts again instead of staying silent.
private void ProcessAlerts(List<StatusLineItem> newItems, HashSet<string> oldRowKeys)
{
int threshold = GetAlertThresholdRank();
if (threshold < 0) return; // "Off"
var newItemKeys = new HashSet<string>();
foreach (var item in newItems)
{
string key = GetAlertKey(item);
newItemKeys.Add(key);
bool qualifies = GetSeverityRank(item.ConditionSource) <= threshold;
if (qualifies)
{
if (_activeAlertKeys.Add(key)) // true only if this key wasn't already armed
{
TriggerAlert(item);
}
}
else
{
_activeAlertKeys.Remove(key);
}
}
foreach (var oldKey in oldRowKeys)
{
if (!newItemKeys.Contains(oldKey))
{
_activeAlertKeys.Remove(oldKey);
}
}
}
// Includes ProblemId (Zabbix event id) when present so multiple simultaneous problems on the same
// device - which all share the same generic MetricOrIssueName ("Active Incident") - get distinct
// alert keys instead of colliding into one, which used to mean only the first one ever sounded.
// DeviceMeta rows have no ProblemId (empty string), so their key is unchanged.
private static string GetAlertKey(StatusLineItem item) =>
RowHasher.ComputeHash(item.Tool, item.DeviceName, item.MetricOrIssueName, item.ProblemId ?? string.Empty);
private static int GetAlertThresholdRank()
{
switch (AppConfig.Instance.Data.Alerts.Threshold?.Trim().ToLowerInvariant())
{
case "disaster": return 0;
case "average": return 1;
case "warning": return 2;
case "info": return 3;
default: return -1; // "Off" or unrecognized
}
}
// Best-effort: a sound/speech failure (no voices installed, audio device unavailable, etc.) should
// never break the scrape/UI pipeline.
private void TriggerAlert(StatusLineItem item)
{
try
{
SystemSounds.Exclamation.Play();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Alert sound playback failed: {ex.Message}");
}
if (!AppConfig.Instance.Data.Alerts.SpeakDeviceAndMetric) return;
// ActiveProblems rows all share the generic MetricOrIssueName ("Active Incident") - the actual
// issue text lives in Value instead. "Speak Problem Details" (session-only, defaults checked)
// controls only whether that detail is included - unchecking it still announces the device, it
// just omits the issue text, rather than skipping the problem announcement entirely.
string phrase;
if (item.IsProblemType)
{
phrase = chkSpeakProblemDetails.Checked
? $"Alert. {item.DeviceName}. {item.Value}."
: $"Alert. {item.DeviceName}.";
}
else
{
// CustomRuleDescription (e.g. "230 is below 250") is only set when this status came from a
// saved custom rule, not the built-in fallback rules - announce the actual triggering
// condition alongside the metric name, not just that something changed.
phrase = string.IsNullOrEmpty(item.CustomRuleDescription)
? $"Alert. {item.DeviceName}. {item.MetricOrIssueName}."
: $"Alert. {item.DeviceName}. {item.MetricOrIssueName}. {item.CustomRuleDescription}.";
}
try
{
// SpeakAsync queues rather than interrupting, so a burst of several alerts from one scrape
// all get announced in turn instead of only the last one being heard.
_speechSynthesizer.SpeakAsync(phrase);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Alert text-to-speech failed: {ex.Message}");
}
}
private void OnFilterToggleClick(object sender, EventArgs e)
{
_showImportantOnly = btnFilterToggle.Checked;
if (_showImportantOnly)
{
btnFilterToggle.Text = "Filter: Important Only";
btnFilterToggle.BackColor = Color.Orange;
}
else
{
btnFilterToggle.Text = "Filter: Show All";
btnFilterToggle.BackColor = Color.LightGray;
}
RefreshListViewGrid();
}
private bool IsLineUnimportant(StatusLineItem item)
{
if (string.IsNullOrEmpty(item.ConditionSource)) return true;
string status = item.ConditionSource.ToLower();
return status == "metanormal" || status == "none" || status == "information";
}
private void RefreshListViewGrid()
{
statusListView.BeginUpdate();
statusListView.Items.Clear();
// Disaster-severity rows float to the top, non-status rows sink to the bottom. OrderBy is a
// stable sort, so within the same severity tier rows keep their existing relative order
// (newest-first, per ReplaceScriptResults inserting fresh batches at the front of _masterItems).
var orderedItems = _masterItems.OrderBy(item => GetSeverityRank(item.ConditionSource));
foreach (var item in orderedItems)
{
if (_showImportantOnly && IsLineUnimportant(item))
{
continue;
}
ListViewItem rowItem = new ListViewItem { Tag = item };
rowItem.SubItems.Add(item.Tool);
rowItem.SubItems.Add(item.DeviceName);
rowItem.SubItems.Add(item.MetricOrIssueName);
rowItem.SubItems.Add(item.Value);
rowItem.SubItems.Add("..."); // Hash column - appended last so it never shifts the fixed SubItems[1..4] indices OnEditFormulaClick/InlineDeleteFormula rely on. Actual hash shown via tooltip (StatusListView_MouseMove), not as cell text.
statusListView.Items.Add(rowItem);
}
statusListView.EndUpdate();
countStatusLabel.Text = $"Visible Traces: {statusListView.Items.Count} | Total Cached: {_masterItems.Count}";
}
// Same severity categories StatusListView_DrawSubItem colors by - kept in sync with that switch so
// sort order and row highlighting always agree. Disaster = 0 (top) ... unrecognized/no status = 4 (bottom).
private static int GetSeverityRank(string conditionSource)
{
if (string.IsNullOrEmpty(conditionSource)) return 4;
switch (conditionSource.ToLower())
{
case "disaster-bg":
case "metadisaster":
return 0;
case "average-bg":
case "metaaverage":
case "high-bg": // 🔥 FIXED: see StatusListView_DrawSubItem - Zabbix's native "High" severity was unranked (fell to the default case), so it never sorted near the top and never qualified for a sound alert either
return 1;
case "warning-bg":
case "metawarning":
return 2;
case "info-bg":
case "metainfo":
return 3;
default:
return 4; // MetaNormal, none, information, or anything unrecognized
}
}
private void StatusListView_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C)
{
CopySelectedRowsToClipboard();
e.Handled = true;
}
}
// ListView only supports one tooltip per-item natively (ShowItemToolTips), not per-cell/column -
// this approximates a per-cell tooltip by retargeting a single ToolTip bound to the whole control
// as the mouse crosses in and out of the Hash column specifically.
private void StatusListView_MouseMove(object sender, MouseEventArgs e)
{
ListViewHitTestInfo hit = statusListView.HitTest(e.Location);
if (hit.Item != null && hit.SubItem != null && hit.Item.Tag is StatusLineItem model)
{
int subItemIndex = -1;
for (int i = 0; i < hit.Item.SubItems.Count; i++)
{
if (hit.Item.SubItems[i] == hit.SubItem)
{
subItemIndex = i;
break;
}
}
if (subItemIndex == HashColumnIndex)
{
string tooltipText = $"Hash: {model.RowHash}\nTool: {model.Tool}\nPage: {model.PageUrl}\nScript: {model.ScriptName}";
if (_hashCellToolTip.GetToolTip(statusListView) != tooltipText)
{
_hashCellToolTip.SetToolTip(statusListView, tooltipText);
}
return;
}
}
if (!string.IsNullOrEmpty(_hashCellToolTip.GetToolTip(statusListView)))
{
_hashCellToolTip.SetToolTip(statusListView, string.Empty);
}
}
// Tab-separated with a header row - pastes directly into Excel/CSV editors as proper columns.
private void CopySelectedRowsToClipboard()
{
if (statusListView.SelectedItems.Count == 0) return;
var sb = new StringBuilder();
sb.AppendLine("Tool\tDevice\tMetric\tValue");
foreach (ListViewItem row in statusListView.SelectedItems)
{
string tool = row.SubItems.Count > 1 ? row.SubItems[1].Text : "";
string device = row.SubItems.Count > 2 ? row.SubItems[2].Text : "";
string metric = row.SubItems.Count > 3 ? row.SubItems[3].Text : "";
string val = row.SubItems.Count > 4 ? row.SubItems[4].Text : "";
sb.AppendLine($"{tool}\t{device}\t{metric}\t{val}");
}
Clipboard.SetText(sb.ToString());
}
private void OnEditFormulaClick(object sender, EventArgs e)
{
if (statusListView.SelectedItems.Count == 0) return;
ListViewItem selectedRow = statusListView.SelectedItems[0];
// Bulletproof extraction mapping directly from the row layout nodes if a Tag is missing
string tool = selectedRow.SubItems.Count > 1 ? selectedRow.SubItems[1].Text : "";
string device = selectedRow.SubItems.Count > 2 ? selectedRow.SubItems[2].Text : "";
string metric = selectedRow.SubItems.Count > 3 ? selectedRow.SubItems[3].Text : "";
string val = selectedRow.SubItems.Count > 4 ? selectedRow.SubItems[4].Text : "";
bool isProblemType = false;
if (selectedRow.Tag is StatusLineItem model)
{
tool = model.Tool;
device = model.DeviceName;
metric = model.MetricOrIssueName;
val = model.Value;
isProblemType = model.IsProblemType;
}
else
{
if (metric.ToLower().Contains("error") || metric.ToLower().Contains("exception") || string.IsNullOrEmpty(val))
{
isProblemType = true;
}
}
if (isProblemType)
{
MessageBox.Show("Custom scalar condition bounds can only be mapped to telemetry matrix metadata lines.", "Context Selector Alert");
return;
}
using (var dlg = new FormulaBuilderDialog(tool, device, metric, val))
{
// 🔥 FIXED: when Form2 is TopMost ("Always On Top" checked), a non-TopMost dialog can end up
// behind it in the OS z-order even though it's shown modally - the dialog needs to be in the
// same TopMost band to reliably render above its TopMost owner.
dlg.TopMost = this.TopMost;
var showResult = dlg.ShowDialog(this);
if (showResult == DialogResult.OK)
{
if (dlg.DeleteRequested)
{
InlineDeleteFormula(tool, device, metric);
if (selectedRow.Tag is StatusLineItem m) m.ConditionSource = "MetaNormal";
selectedRow.BackColor = Color.White;
selectedRow.ForeColor = Color.Black;
statusListView.Invalidate();
MessageBox.Show("Custom rule threshold configuration wiped successfully.", "Engine Rule Cleared");
}
else if (dlg.ResultFormula != null)
{
FormulaPersistenceManager.SaveFormula(dlg.ResultFormula);
string newStatus = FormulaPersistenceManager.EvaluateMetric(tool, device, metric, val);
if (newStatus != null)
{
if (selectedRow.Tag is StatusLineItem m) m.ConditionSource = newStatus;
statusListView.Invalidate();
}
MessageBox.Show("Rule successfully saved and committed to formulas.json config database maps.", "Engine Update Center");
}
}
}
}
private void InlineDeleteFormula(string tool, string device, string metric)
{
try
{
FieldInfo field = typeof(FormulaPersistenceManager).GetField("_formulas", BindingFlags.Static | BindingFlags.NonPublic);
if (field != null && field.GetValue(null) is List<CustomFormula> list)
{
list.RemoveAll(f => f.Tool == tool && f.DeviceName == device && f.MetricName == metric);
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "formulas.json");
string json = JsonConvert.SerializeObject(list, Formatting.Indented);
File.WriteAllText(filePath, json);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Inline delete routine failed: {ex.Message}");
}
}
}
// --- Dynamic Rule Dialog Modal Wrapper Window ---
public class FormulaBuilderDialog : Form
{
public CustomFormula ResultFormula { get; private set; }
public bool DeleteRequested { get; private set; } = false;
private ComboBox cbMethod, cbType, cbStatus;
private TextBox txtValue;
private Button btnDelete;
private Button btnSave;
private readonly string _tool;
private readonly string _device;
private readonly string _metric;
private readonly string _currentValue;
public FormulaBuilderDialog(string tool, string device, string metric, string currentValue)
{
_tool = tool;
_device = device;
_metric = metric;
_currentValue = currentValue;
InitializeComponentLayout();
LoadExistingFormulaIfAny();
}
private void InitializeComponentLayout()
{
this.Text = $"Define Status Rule: {_metric}";
this.Size = new Size(420, 320);
this.FormBorderStyle = FormBorderStyle.FixedDialog;
this.StartPosition = FormStartPosition.CenterParent;
this.MaximizeBox = false;
Label lblInfo = new Label { Text = $"Target: {_tool} -> {_device}\nRaw Sample: {_currentValue}", Location = new Point(20, 15), Size = new Size(360, 40), Font = new Font(this.Font, FontStyle.Bold) };
Label lblType = new Label { Text = "Data Casting Type:", Location = new Point(20, 65), Size = new Size(120, 20) };
cbType = new ComboBox { Location = new Point(150, 65), Size = new Size(220, 25), DropDownStyle = ComboBoxStyle.DropDownList };
cbType.Items.AddRange(new object[] { "String", "Int", "Float", "Double" });
cbType.SelectedIndex = 0;
cbType.SelectedIndexChanged += CbType_SelectedIndexChanged;
Label lblMethod = new Label { Text = "Check Operator:", Location = new Point(20, 100), Size = new Size(120, 20) };
cbMethod = new ComboBox { Location = new Point(150, 100), Size = new Size(220, 25), DropDownStyle = ComboBoxStyle.DropDownList };
Label lblValue = new Label { Text = "Comparison Value:", Location = new Point(20, 135), Size = new Size(120, 20) };
txtValue = new TextBox { Location = new Point(150, 135), Size = new Size(220, 20) };
cbMethod.SelectedIndexChanged += (s, e) => {
if (cbMethod.SelectedItem == null) return;
bool isAny = string.Equals(cbMethod.SelectedItem.ToString(), "any", StringComparison.OrdinalIgnoreCase);
cbType.Enabled = !isAny;
txtValue.Enabled = !isAny;
if (isAny)
{
txtValue.Text = "*";
}
};
Label lblStatus = new Label { Text = "Trigger Color:", Location = new Point(20, 170), Size = new Size(120, 20) };
cbStatus = new ComboBox { Location = new Point(150, 170), Size = new Size(220, 25), DropDownStyle = ComboBoxStyle.DropDownList };
cbStatus.Items.AddRange(new object[] { "disaster-bg", "average-bg", "warning-bg", "info-bg" });
cbStatus.SelectedIndex = 2;
btnDelete = new Button { Text = "Delete Rule", Location = new Point(20, 220), Size = new Size(110, 32), BackColor = Color.MistyRose, Visible = false };
btnDelete.Click += (s, e) => {
DeleteRequested = true;
this.DialogResult = DialogResult.OK;
this.Close();
};
btnSave = new Button { Text = "Save Formula", Location = new Point(260, 220), Size = new Size(110, 32), BackColor = Color.LightBlue };
btnSave.Click += BtnSave_Click;
this.Controls.AddRange(new Control[] { lblInfo, lblType, cbType, lblMethod, cbMethod, lblValue, txtValue, lblStatus, cbStatus, btnSave, btnDelete });
CbType_SelectedIndexChanged(this, EventArgs.Empty);
}
private void LoadExistingFormulaIfAny()
{
try
{
FieldInfo field = typeof(FormulaPersistenceManager).GetField("_formulas", BindingFlags.Static | BindingFlags.NonPublic);
if (field != null && field.GetValue(null) is List<CustomFormula> list)
{
CustomFormula formula = list.Find(f => f.Tool == _tool && f.DeviceName == _device && f.MetricName == _metric);
if (formula != null)
{
cbType.SelectedItem = formula.TargetDataType;
CbType_SelectedIndexChanged(this, EventArgs.Empty);
cbMethod.SelectedItem = formula.CheckMethod;
txtValue.Text = formula.ComparisonValue;
cbStatus.SelectedItem = formula.AssignedStatus;
btnDelete.Visible = true;
btnSave.Text = "Update Formula";
}
}
}
catch { /* Protection fallback safely catches anomalous data faults */ }
}
private void CbType_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedType = cbType.SelectedItem?.ToString();
string previousSelection = cbMethod.SelectedItem?.ToString();
cbMethod.Items.Clear();
if (selectedType == "String")
{
cbMethod.Items.AddRange(new object[] { "contains", "=", "!=", "any" });
}
else
{
cbMethod.Items.AddRange(new object[] { ">", "<", "=", "!=", "any" });
}
// 🔥 FIX: Check string.IsNullOrEmpty to guard against ArgumentNullException inside WinForms Contains collections
if (!string.IsNullOrEmpty(previousSelection) && cbMethod.Items.Contains(previousSelection))
{
cbMethod.SelectedItem = previousSelection;
}
else
{
cbMethod.SelectedIndex = 0;
}
}
private void BtnSave_Click(object sender, EventArgs e)
{
string targetType = cbType.SelectedItem.ToString();
string selectedOp = cbMethod.SelectedItem.ToString();
string rawInput = txtValue.Text.Trim();
if (!string.Equals(selectedOp, "any", StringComparison.OrdinalIgnoreCase))
{
if (targetType != "String")
{
string numbersOnly = Regex.Match(rawInput, @"-?\d+(\.\d+)?")?.Value;
if (string.IsNullOrEmpty(numbersOnly))
{
MessageBox.Show("Please specify a valid numeric threshold parameter input value.", "Validation Error");
return;
}
if (targetType == "Int")
{
// 🔥 FIXED: double.TryParse was using the implicit CurrentCulture - on a machine
// whose OS culture uses "," as the decimal separator (e.g. uk-UA), a value like
// "250.5" (the "." decimal notation this app's regex above always extracts) would
// fail to parse here, wrongly rejecting valid input. Force InvariantCulture so "."
// is always read as the decimal point, matching what FormulaPersistenceManager
// expects when evaluating this saved value later.
if (double.TryParse(numbersOnly, NumberStyles.Float, CultureInfo.InvariantCulture, out double testVal))
{
numbersOnly = Math.Truncate(testVal).ToString(CultureInfo.InvariantCulture);
}
else
{
MessageBox.Show("Value target cannot be cleanly parsed into an Integer format context.", "Validation Error");
return;
}
}
txtValue.Text = numbersOnly;
}
}
ResultFormula = new CustomFormula
{
Tool = _tool,
DeviceName = _device,
MetricName = _metric,
CheckMethod = cbMethod.SelectedItem.ToString(),
TargetDataType = cbType.SelectedItem.ToString(),
ComparisonValue = txtValue.Text.Trim(),
AssignedStatus = cbStatus.SelectedItem.ToString()
};
this.DialogResult = DialogResult.OK;
this.Close();
}
}
}