-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
513 lines (445 loc) · 21.4 KB
/
Copy pathForm1.cs
File metadata and controls
513 lines (445 loc) · 21.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
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
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WebToolsDataMonitor
{
public partial class Form1 : Form
{
private ListView engineListView;
private Button btnStartStop;
// 🔥 NEW Toggle Controls
private CheckBox chkParallelTools;
private CheckBox chkParallelPages;
// Continuous run loop controls
private NumericUpDown numIntervalSeconds;
private Button btnStartLoop;
private Form2 monitoringDashboard = null;
private CancellationTokenSource _cts = null;
private CancellationTokenSource _loopCts = null;
private Dictionary<string, ListViewItem> _engineRows = new Dictionary<string, ListViewItem>(StringComparer.OrdinalIgnoreCase);
public Form1()
{
InitializeComponent();
SetupControlBridgeLayout();
}
private void SetupControlBridgeLayout()
{
this.Text = "Automation Engine Command Panel (Form1)";
this.Size = new Size(600, 650);
this.StartPosition = FormStartPosition.CenterScreen;
engineListView = new ListView
{
Location = new Point(15, 15),
Size = new Size(550, 140),
View = View.Details,
FullRowSelect = true,
CheckBoxes = true,
GridLines = true
};
engineListView.Columns.Add("Run", 50);
engineListView.Columns.Add("Engine Tool Name", 150);
engineListView.Columns.Add("Execution State Status", 200);
engineListView.Columns.Add("Active Workers", 100);
foreach (var tool in ToolRepository.Instance.GetAllTools())
{
RegisterOrUpdateEngineState(tool.ToolName, "Idle Ready", 0, true);
}
btnStartStop = new Button
{
Text = "START SCRAPER ENGINE",
Location = new Point(15, 165),
Size = new Size(550, 40),
BackColor = Color.LightGreen,
Font = new Font(this.Font, FontStyle.Bold)
};
btnStartStop.Click += BtnStartStop_Click;
// 🔥 NEW Checkbox Toggles Instantiation - initial state restored from app_config.yaml
var uiState = AppConfig.Instance.Data.Ui;
chkParallelTools = new CheckBox
{
Text = "Execute Selected Tools in Parallel",
Location = new Point(15, 215),
Size = new Size(250, 20),
Checked = uiState.ParallelTools
};
chkParallelTools.CheckedChanged += (s, e) =>
{
AppConfig.Instance.Data.Ui.ParallelTools = chkParallelTools.Checked;
AppConfig.Instance.Save();
};
chkParallelPages = new CheckBox
{
Text = "Execute Tool Pages in Parallel (Shared Session Cache)",
Location = new Point(275, 215),
Size = new Size(290, 20),
Checked = uiState.ParallelPages
};
chkParallelPages.CheckedChanged += (s, e) =>
{
AppConfig.Instance.Data.Ui.ParallelPages = chkParallelPages.Checked;
AppConfig.Instance.Save();
};
// 🔥 NEW Continuous Run Loop Controls
Label lblInterval = new Label
{
Text = "Continuous Run Interval (seconds):",
Location = new Point(15, 243),
Size = new Size(200, 20)
};
numIntervalSeconds = new NumericUpDown
{
Location = new Point(220, 240),
Size = new Size(70, 22),
Minimum = 1,
Maximum = 86400
};
numIntervalSeconds.Value = Math.Max(numIntervalSeconds.Minimum, Math.Min(numIntervalSeconds.Maximum, uiState.IntervalSeconds));
numIntervalSeconds.ValueChanged += (s, e) =>
{
AppConfig.Instance.Data.Ui.IntervalSeconds = (int)numIntervalSeconds.Value;
AppConfig.Instance.Save();
};
btnStartLoop = new Button
{
Text = "START CONTINUOUS RUN",
Location = new Point(15, 268),
Size = new Size(550, 36),
BackColor = Color.LightGreen,
Font = new Font(this.Font, FontStyle.Bold)
};
btnStartLoop.Click += BtnStartLoop_Click;
// Shifted down to make room for the continuous run controls above
StatusBox.Location = new Point(15, 314);
StatusBox.Size = new Size(550, 270);
StatusBox.Multiline = true;
StatusBox.ScrollBars = ScrollBars.Vertical;
StatusBox.ReadOnly = true;
StatusBox.BackColor = Color.Black;
StatusBox.ForeColor = Color.Lime;
this.Controls.Add(engineListView);
this.Controls.Add(btnStartStop);
this.Controls.Add(chkParallelTools);
this.Controls.Add(chkParallelPages);
this.Controls.Add(lblInterval);
this.Controls.Add(numIntervalSeconds);
this.Controls.Add(btnStartLoop);
}
public void RegisterOrUpdateEngineState(string toolName, string runningStatus, int threadCount, bool? setCheckedState = null)
{
if (this.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)(() => RegisterOrUpdateEngineState(toolName, runningStatus, threadCount, setCheckedState)));
return;
}
if (_engineRows.TryGetValue(toolName, out var targetRow))
{
targetRow.SubItems[2].Text = runningStatus;
targetRow.SubItems[3].Text = threadCount.ToString();
if (setCheckedState.HasValue) targetRow.Checked = setCheckedState.Value;
}
else
{
ListViewItem newRow = new ListViewItem();
newRow.SubItems.Add(toolName);
newRow.SubItems.Add(runningStatus);
newRow.SubItems.Add(threadCount.ToString());
if (setCheckedState.HasValue) newRow.Checked = setCheckedState.Value;
_engineRows[toolName] = newRow;
engineListView.Items.Add(newRow);
}
}
private void button1_Click(object sender, EventArgs e)
{
BtnStartStop_Click(sender, e);
}
// Caps the event log at MaxStatusLogLines by dropping the oldest lines (FIFO) - a long continuous
// run would otherwise grow StatusBox's text unbounded over hours/days.
private const int MaxStatusLogLines = 5000;
private void AppendStatusLine(string text)
{
StatusBox.AppendText(text);
// .Lines splits on line breaks; every appended entry here ends in \r\n, so there's always a
// trailing empty "line" after the last real one that shouldn't count toward the cap.
string[] lines = StatusBox.Lines;
int lineCount = lines.Length;
if (lineCount > 0 && lines[lineCount - 1].Length == 0) lineCount--;
if (lineCount > MaxStatusLogLines)
{
int firstKeptIndex = lineCount - MaxStatusLogLines;
string[] trimmed = new string[lines.Length - firstKeptIndex];
Array.Copy(lines, firstKeptIndex, trimmed, 0, trimmed.Length);
StatusBox.Lines = trimmed;
StatusBox.SelectionStart = StatusBox.Text.Length;
StatusBox.ScrollToCaret();
}
}
// Only the tool NAMES are captured from the checkbox selection - the actual ToolConfig objects are
// re-resolved fresh from the repositories inside RunSelectedToolsOnceAsync every time it runs (see
// below), so an edit to a tool/page/script yaml file made after checking a box still takes effect.
private List<string> GetSelectedToolNames()
{
List<string> names = new List<string>();
foreach (ListViewItem rowItem in engineListView.Items)
{
if (rowItem.Checked && rowItem.SubItems.Count > 1)
{
names.Add(rowItem.SubItems[1].Text);
}
}
return names;
}
// One full run of the selected tools to completion (or cancellation) - shared by the single manual
// run button and the continuous run loop, so both go through the exact same execution path.
private async Task RunSelectedToolsOnceAsync(List<string> toolNames, CancellationToken token)
{
// Reload tools/*.yaml, tools/pages/*.yaml and tools/scripts/*.yaml from disk fresh for every run
// (not just once at app startup) - so a fixed destinationUrl, an edited script, a tweaked delay,
// etc. takes effect on the very next run or continuous-loop cycle without restarting the app.
ToolRepository.Instance.Reload();
ScriptsRepository.Instance.Reload();
List<ToolConfig> toolsToRun = new List<ToolConfig>();
foreach (var name in toolNames)
{
var tool = ToolRepository.Instance.GetTool(name);
if (tool != null)
{
toolsToRun.Add(tool);
}
else
{
Logger.Instance.Warn("SYSTEM", $"Selected tool '{name}' no longer exists after config reload - skipping it this run.");
}
}
if (toolsToRun.Count == 0)
{
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [SYSTEM] No selected tools resolved after config reload - nothing to run.\r\n");
return;
}
ParallelScraperManager manager = new ParallelScraperManager(this, chkParallelPages.Checked);
manager.DataScraped += Manager_DataScraped;
try
{
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [SYSTEM] Run initiated. Tools Parallel={chkParallelTools.Checked}, Pages Parallel={chkParallelPages.Checked}...\r\n");
foreach (var t in toolsToRun)
{
RegisterOrUpdateEngineState(t.ToolName, "Running...", t.ScrapPages.Count);
}
// 🔥 Toggle Execution Sequence Route based on chkParallelTools state configurations
if (chkParallelTools.Checked)
{
await manager.RunAllToolsInParallelAsync(toolsToRun, token);
}
else
{
await manager.RunAllToolsInSequenceAsync(toolsToRun, token);
}
}
finally
{
foreach (var t in toolsToRun)
{
RegisterOrUpdateEngineState(t.ToolName, "Idle Ready", 0);
}
manager.DataScraped -= Manager_DataScraped;
}
}
private async void BtnStartStop_Click(object sender, EventArgs e)
{
if (_cts != null)
{
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [SYSTEM] Sending cancellation token request signals...\r\n");
_cts.Cancel();
return;
}
List<string> toolNames = GetSelectedToolNames();
if (toolNames.Count == 0)
{
MessageBox.Show("Please select at least one automation engine checkbox row to execute.", "Control Monitor Info");
return;
}
if (monitoringDashboard == null || monitoringDashboard.IsDisposed)
{
monitoringDashboard = new Form2();
monitoringDashboard.Show();
}
_cts = new CancellationTokenSource();
btnStartStop.Text = "STOP ENGINE EXECUTION";
btnStartStop.BackColor = Color.Tomato;
btnStartLoop.Enabled = false; // never run a manual run and the continuous loop at the same time - they'd share the same tools' CacheData/WebView2 profiles
try
{
await RunSelectedToolsOnceAsync(toolNames, _cts.Token);
}
catch (OperationCanceledException)
{
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [SYSTEM] Active operations successfully aborted by user.\r\n");
}
catch (Exception ex)
{
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [ERROR] Execution fault: {ex.Message}\r\n");
}
finally
{
_cts.Dispose();
_cts = null;
btnStartStop.Text = "START SCRAPER ENGINE";
btnStartStop.BackColor = Color.LightGreen;
btnStartLoop.Enabled = true;
}
}
// Repeats RunSelectedToolsOnceAsync on a fixed cadence (numIntervalSeconds), measured from the
// START of one cycle to the START of the next - never runs a new cycle while the previous one is
// still active. If a cycle takes longer than the interval, the next cycle starts immediately right
// after it finishes (no overlap, no negative wait) instead of being skipped or stacked.
private async void BtnStartLoop_Click(object sender, EventArgs e)
{
if (_loopCts != null)
{
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [SYSTEM] Stopping continuous run loop (finishing current cycle first)...\r\n");
_loopCts.Cancel();
return;
}
List<string> toolNames = GetSelectedToolNames();
if (toolNames.Count == 0)
{
MessageBox.Show("Please select at least one automation engine checkbox row to execute.", "Control Monitor Info");
return;
}
if (monitoringDashboard == null || monitoringDashboard.IsDisposed)
{
monitoringDashboard = new Form2();
monitoringDashboard.Show();
}
int intervalSeconds = (int)numIntervalSeconds.Value;
_loopCts = new CancellationTokenSource();
btnStartLoop.Text = "STOP CONTINUOUS RUN";
btnStartLoop.BackColor = Color.Tomato;
btnStartStop.Enabled = false;
numIntervalSeconds.Enabled = false;
engineListView.Enabled = false; // tool selection (which checkboxes are checked) is captured once at loop start; the underlying ToolConfig data itself is re-read from disk fresh every cycle via RunSelectedToolsOnceAsync's Reload() calls
try
{
int cycle = 0;
while (!_loopCts.Token.IsCancellationRequested)
{
cycle++;
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [SYSTEM] === Continuous run cycle #{cycle} starting (interval: {intervalSeconds}s) ===\r\n");
DateTime cycleStart = DateTime.Now;
try
{
await RunSelectedToolsOnceAsync(toolNames, _loopCts.Token);
}
catch (OperationCanceledException)
{
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [SYSTEM] Continuous run loop stopped mid-cycle by user.\r\n");
break;
}
catch (Exception ex)
{
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [ERROR] Cycle #{cycle} execution fault: {ex.Message}\r\n");
}
if (_loopCts.Token.IsCancellationRequested) break;
TimeSpan elapsed = DateTime.Now - cycleStart;
TimeSpan remaining = TimeSpan.FromSeconds(intervalSeconds) - elapsed;
if (remaining > TimeSpan.Zero)
{
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [SYSTEM] Cycle #{cycle} finished in {elapsed.TotalSeconds:F1}s - waiting {remaining.TotalSeconds:F1}s until next run...\r\n");
try
{
await Task.Delay(remaining, _loopCts.Token);
}
catch (OperationCanceledException)
{
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [SYSTEM] Continuous run loop stopped while waiting for the next cycle.\r\n");
break;
}
}
else
{
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [SYSTEM] Cycle #{cycle} took {elapsed.TotalSeconds:F1}s, longer than the {intervalSeconds}s interval - starting the next cycle immediately (no overlap).\r\n");
}
}
}
finally
{
_loopCts.Dispose();
_loopCts = null;
btnStartLoop.Text = "START CONTINUOUS RUN";
btnStartLoop.BackColor = Color.LightGreen;
btnStartStop.Enabled = true;
numIntervalSeconds.Enabled = true;
engineListView.Enabled = true;
}
}
private void Manager_DataScraped(object sender, ScrapedDataEventArgs e)
{
if (this.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)(() => Manager_DataScraped(sender, e)));
return;
}
if (!string.IsNullOrEmpty(e.LogMessage))
{
AppendStatusLine($"[{e.Timestamp:HH:mm:ss}] [{e.ToolName}] {e.LogMessage}\r\n");
return;
}
if (monitoringDashboard != null && !monitoringDashboard.IsDisposed && !string.IsNullOrEmpty(e.RawJson))
{
// 🛠️ STEP 1: Aggressively clean and unescape the raw JSON text from WebView2
string cleanJson = e.RawJson.Trim();
// Unescape the first layer of quotes if wrapped by WebView2
if (cleanJson.StartsWith("\"") && cleanJson.EndsWith("\"") && cleanJson.Length > 1)
{
cleanJson = cleanJson.Substring(1, cleanJson.Length - 2);
cleanJson = System.Text.RegularExpressions.Regex.Unescape(cleanJson);
}
// Handle double-serialized JSON strings (e.g. "\"[{\\\"name\\\":...}]\"")
if (cleanJson.StartsWith("\"") && cleanJson.EndsWith("\"") && cleanJson.Length > 1)
{
cleanJson = cleanJson.Substring(1, cleanJson.Length - 2);
cleanJson = System.Text.RegularExpressions.Regex.Unescape(cleanJson);
}
// Print a diagnostic message to track exactly what C# received
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [DEBUG UI] Processing type '{e.ReturnType}' | Sample payload: {(cleanJson.Length > 60 ? cleanJson.Substring(0, 60) : cleanJson)}...\r\n");
List<StatusLineItem> translatedRows = null;
try
{
switch (e.ReturnType?.Trim())
{
case "ActiveProblems":
translatedRows = StatusLineDto.FromActiveProblems(e.ToolName, e.PageUrl, e.ScriptName, cleanJson);
break;
case "DeviceMeta":
translatedRows = StatusLineDto.FromDeviceMeta(e.ToolName, e.PageUrl, e.ScriptName, cleanJson);
break;
default:
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [WARNING] Unhandled return type detected: '{e.ReturnType}'\r\n");
break;
}
}
catch (Exception ex)
{
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [ERROR UI] Deserialization crashed for type '{e.ReturnType}': {ex.Message}\r\n");
}
// 🛠️ STEP 2: Verify the DTO output before calling Form2
if (translatedRows != null && translatedRows.Count > 0)
{
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [SUCCESS UI] Injecting {translatedRows.Count} rows into Form2.\r\n");
monitoringDashboard.ReplaceScriptResults(e.ToolName, e.PageUrl, e.ScriptName, translatedRows);
}
else if (translatedRows != null)
{
// Still clear this script's previously-reported rows for this tool/page - a genuine
// 0-item result (e.g. all problems resolved) shouldn't leave stale rows behind. Note:
// this also clears on a transient/glitchy 0-item scrape, so a bad poll can temporarily
// blank a script's rows until the next successful run picks them back up.
AppendStatusLine($"[{DateTime.Now:HH:mm:ss}] [WARNING UI] DTO parsing completed, but returned 0 line items.\r\n");
monitoringDashboard.ReplaceScriptResults(e.ToolName, e.PageUrl, e.ScriptName, translatedRows);
}
}
}
}
}