-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormulaPersistenceManager.cs
More file actions
210 lines (184 loc) · 10.4 KB
/
Copy pathFormulaPersistenceManager.cs
File metadata and controls
210 lines (184 loc) · 10.4 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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
namespace WebToolsDataMonitor
{
public class CustomFormula
{
public string Tool { get; set; }
public string DeviceName { get; set; }
public string MetricName { get; set; }
public string CheckMethod { get; set; } // ">", "<", "=", "contains"
public string TargetDataType { get; set; } // "Int", "Float", "Double", "String"
public string ComparisonValue { get; set; }
public string AssignedStatus { get; set; } // "disaster-bg", "average-bg", "warning-bg", "info-bg"
}
public static class FormulaPersistenceManager
{
private static readonly string FilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "formulas.json");
private static List<CustomFormula> _formulas = new List<CustomFormula>();
static FormulaPersistenceManager()
{
LoadFormulas();
}
public static void LoadFormulas()
{
try
{
if (File.Exists(FilePath))
{
string json = File.ReadAllText(FilePath);
_formulas = JsonConvert.DeserializeObject<List<CustomFormula>>(json) ?? new List<CustomFormula>();
}
}
catch { _formulas = new List<CustomFormula>(); }
}
public static void SaveFormula(CustomFormula formula)
{
// Remove existing match if overwriting a rule for the same specific target
_formulas.RemoveAll(f => f.Tool == formula.Tool && f.DeviceName == formula.DeviceName && f.MetricName == formula.MetricName);
_formulas.Add(formula);
try
{
string json = JsonConvert.SerializeObject(_formulas, Formatting.Indented);
File.WriteAllText(FilePath, json);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Failed to write formula matrix maps: {ex.Message}");
}
}
// Evaluates incoming data against stored rule sets. Convenience overload for callers that don't
// need the human-readable match description (e.g. existing tests) - delegates to the full overload.
public static string EvaluateMetric(string tool, string device, string metricName, string rawValue)
{
return EvaluateMetric(tool, device, metricName, rawValue, out _);
}
// Same as above, but also reports a human-readable description of what matched (e.g. "230 is below
// 250") when a rule fires - used to speak the actual triggering condition, not just the metric
// name, for alerts driven by a custom rule (see Form2.TriggerAlert). Null when no rule matched, or
// when it matched via "any" (there's no meaningful value comparison to describe for that operator).
public static string EvaluateMetric(string tool, string device, string metricName, string rawValue, out string matchDescription)
{
matchDescription = null;
var match = _formulas.Find(f => f.Tool == tool && f.DeviceName == device && f.MetricName == metricName);
if (match == null) return null; // No custom user override exists
// 🔥 ADDED: If operator is set to 'any', return the assigned status immediately
if (string.Equals(match.CheckMethod, "any", StringComparison.OrdinalIgnoreCase))
{
return match.AssignedStatus;
}
try
{
// 🔥 FIXED: rawValue/ComparisonValue can legitimately be null (a script returning
// value: null for a metric, or a hand-edited formulas.json) - these used to be Trim()'d
// outside the try/catch, so a null here threw an uncaught NullReferenceException that
// unwound the entire calling foreach loop in StatusLineDto.FromDeviceMeta, silently
// dropping every remaining metric in that batch, not just the one with the bad value.
string cleanInput = (rawValue ?? string.Empty).Trim();
string cleanTarget = (match.ComparisonValue ?? string.Empty).Trim();
switch (match.CheckMethod)
{
case "contains":
if (cleanInput.IndexOf(cleanTarget, StringComparison.OrdinalIgnoreCase) < 0) return null;
matchDescription = $"{cleanInput} contains {cleanTarget}";
return match.AssignedStatus;
case "=":
if (match.TargetDataType == "String")
{
if (!string.Equals(cleanInput, cleanTarget, StringComparison.OrdinalIgnoreCase)) return null;
matchDescription = $"{cleanInput} equals {cleanTarget}";
return match.AssignedStatus;
}
return EvaluateNumeric(cleanInput, cleanTarget, match.TargetDataType, match.CheckMethod, out matchDescription) ? match.AssignedStatus : null;
case "!=":
if (match.TargetDataType == "String")
{
if (string.Equals(cleanInput, cleanTarget, StringComparison.OrdinalIgnoreCase)) return null;
matchDescription = $"{cleanInput} is not {cleanTarget}";
return match.AssignedStatus;
}
return EvaluateNumeric(cleanInput, cleanTarget, match.TargetDataType, match.CheckMethod, out matchDescription) ? match.AssignedStatus : null;
case ">":
case "<":
return EvaluateNumeric(cleanInput, cleanTarget, match.TargetDataType, match.CheckMethod, out matchDescription) ? match.AssignedStatus : null;
}
}
catch { /* Gracefully skip corrupt comparison conversions */ }
return null;
}
private static bool EvaluateNumeric(string input, string target, string type, string op, out string matchDescription)
{
matchDescription = null;
// Extract decimal numbers out of raw string structures (e.g., "93 %" -> "93", "230.4 V" -> "230.4")
string cleanIn = Regex.Match(input, @"[0-9.-]+").Value;
string cleanTar = Regex.Match(target, @"[0-9.-]+").Value;
if (string.IsNullOrEmpty(cleanIn) || string.IsNullOrEmpty(cleanTar)) return false;
// 🔥 FIXED: every TryParse below used to run against CultureInfo.CurrentCulture (the implicit
// default). Scraped device values and the extracted regex fragment always use "." as the
// decimal point (English/technical convention), but on a machine whose OS culture uses "," as
// the decimal separator (e.g. uk-UA), double.TryParse("230.4") silently returns false under
// that culture - it expects "230,4". This made every single numeric rule with a fractional
// value fail on exactly the locale this app is actually deployed on, regardless of the
// Int-truncation fix above. NumberStyles.Float here explicitly allows a leading sign and a
// decimal point (but not a culture-specific group separator), paired with InvariantCulture so
// "." is always read as the decimal point no matter what the OS is configured for.
const NumberStyles NumStyle = NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint;
if (type == "Int")
{
// int.TryParse rejects any string with a decimal point, but scraped values almost always
// have one ("230.4 V", "12.3 %") - this made every Int-type rule silently never match
// against a real-world reading. Parse as double first and truncate, same as BtnSave_Click
// already does for the saved comparison value, so both sides are handled consistently.
if (double.TryParse(cleanIn, NumStyle, CultureInfo.InvariantCulture, out double di) &&
double.TryParse(cleanTar, NumStyle, CultureInfo.InvariantCulture, out double dt))
{
int i = (int)Math.Truncate(di);
int t = (int)Math.Truncate(dt);
bool isMatch;
string verb;
if (op == ">") { isMatch = i > t; verb = "is above"; }
else if (op == "<") { isMatch = i < t; verb = "is below"; }
else if (op == "!=") { isMatch = i != t; verb = "is not"; }
else { isMatch = i == t; verb = "equals"; }
if (isMatch) matchDescription = $"{i} {verb} {t}";
return isMatch;
}
}
else if (type == "Float")
{
if (float.TryParse(cleanIn, NumStyle, CultureInfo.InvariantCulture, out float i) &&
float.TryParse(cleanTar, NumStyle, CultureInfo.InvariantCulture, out float t))
{
bool isMatch;
string verb;
if (op == ">") { isMatch = i > t; verb = "is above"; }
else if (op == "<") { isMatch = i < t; verb = "is below"; }
else if (op == "!=") { isMatch = i != t; verb = "is not"; }
else { isMatch = i == t; verb = "equals"; }
if (isMatch) matchDescription = $"{i} {verb} {t}";
return isMatch;
}
}
else if (type == "Double")
{
if (double.TryParse(cleanIn, NumStyle, CultureInfo.InvariantCulture, out double i) &&
double.TryParse(cleanTar, NumStyle, CultureInfo.InvariantCulture, out double t))
{
bool isMatch;
string verb;
if (op == ">") { isMatch = i > t; verb = "is above"; }
else if (op == "<") { isMatch = i < t; verb = "is below"; }
else if (op == "!=") { isMatch = i != t; verb = "is not"; }
else { isMatch = i == t; verb = "equals"; }
if (isMatch) matchDescription = $"{i} {verb} {t}";
return isMatch;
}
}
return false;
}
}
}