This commit is contained in:
2025-10-21 15:46:28 +01:00
parent cfe8a57a9d
commit aa28a43347
4 changed files with 136 additions and 246 deletions

View File

@@ -1,9 +1,6 @@
using AiQ_GUI.Microsoft; using Newtonsoft.Json;
using Newtonsoft.Json;
using System.ComponentModel; using System.ComponentModel;
using System.Data.OleDb;
using System.Diagnostics; using System.Diagnostics;
using System.Numerics;
using System.Reflection; using System.Reflection;
namespace AiQ_GUI namespace AiQ_GUI
@@ -28,8 +25,6 @@ namespace AiQ_GUI
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public static MainForm? Instance { get; private set; } public static MainForm? Instance { get; private set; }
// For Access Stats
const string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\Shared drives\MAV Production GUI's\AiQ\GUI's\AiQ_Final_Test.accdb;Persist Security Info=False;OLE DB Services=-1;";
public MainForm() public MainForm()
{ {
@@ -219,7 +214,7 @@ namespace AiQ_GUI
LED.CheckLEDs(DiagsAPI.LedCurrent, LblLEDI, "mA", CameraAccessInfo.LED_I); // Current LED.CheckLEDs(DiagsAPI.LedCurrent, LblLEDI, "mA", CameraAccessInfo.LED_I); // Current
this.Refresh(); // Make sure all labels are updated before checking them this.Refresh(); // Make sure all labels are updated before checking them
// If there are any actions identified then fail the test. // If there are any actions identified then fail the test.
// If any labels are red then fail. Only labels in panel so can foreach on labels not controls // If any labels are red then fail. Only labels in panel so can foreach on labels not controls
if (RhTxBxActions.Text.Length > 2 || PnlLbls.Controls.OfType<Label>().Any(c => c.ForeColor == Color.Red) == true) if (RhTxBxActions.Text.Length > 2 || PnlLbls.Controls.OfType<Label>().Any(c => c.ForeColor == Color.Red) == true)
@@ -231,75 +226,6 @@ namespace AiQ_GUI
await TestPassed(PCTime); await TestPassed(PCTime);
} }
public void Stats(string TypeOfTest)
{
Stats([TypeOfTest]);
}
public void Stats(string[] TypeOfTest)
{
using OleDbConnection conn = new(connString); // Opens connection to Access database
try
{
conn.Open(); // Opens DB
string modelNumber = CbBxCameraType.Text.Substring(0, 6); // Get model number from combobox and make sure it is only 6 characters.
foreach (string type in TypeOfTest)
{
string query = $"UPDATE AiQ SET [{type}] = [{type}] + 1 WHERE [ModelNumber] = ?"; // Add one for every test ran of this type for this model number
using OleDbCommand cmd = new(query, conn); // Create command
cmd.Parameters.AddWithValue("?", modelNumber); // Add model number to prevent injection
int rowsAffected = cmd.ExecuteNonQuery();
// Execute the command and get the number of rows affected
//if (rowsAffected > 0) // If one or more rows were updated
// AddToActionsList($"Updated {TypeOfTest} for {modelNumber}");
//else
// AddToActionsList($"No rows found for {modelNumber}");
}
}
catch
{
AddToActionsList("Could not access Access in Google Drive. Is it running?");
return;
}
}
public void StatsDiags(string redDiagLabels, string RhTxBxActionsText)
{
using OleDbConnection conn = new(connString);
conn.Open();
// Null checks
string redVal = string.IsNullOrWhiteSpace(redDiagLabels) ? "-" : redDiagLabels;
string actVal = string.IsNullOrWhiteSpace(RhTxBxActionsText) ? "-" : RhTxBxActionsText;
string model = string.IsNullOrWhiteSpace(CamOnTest?.Model) ? "-" : CamOnTest.Model;
string sql = @"
INSERT INTO DiagsStats ([Date], [Model], [Red Diags Labels], [RhTxBxActions Contents])
VALUES (?, ?, ?, ?)";
using OleDbCommand cmd = new(sql, conn);
cmd.Parameters.Add(new OleDbParameter
{
OleDbType = OleDbType.Date,
Value = DateTime.Now
});
cmd.Parameters.AddWithValue("?", model);
cmd.Parameters.AddWithValue("?", redVal);
cmd.Parameters.AddWithValue("?", actVal);
int rows = cmd.ExecuteNonQuery();
//if (rows > 0)
// AddToActionsList($"DiagsStats inserted ({rows} row) for model '{model}' on {DateTime.Now:yyyy-MM-dd}");
//else
// AddToActionsList("No rows inserted into DiagsStats (unexpected).");
}
private async void BtnPreTest_Click(object sender, EventArgs e) private async void BtnPreTest_Click(object sender, EventArgs e)
{ {
// Show user test has started // Show user test has started
@@ -358,8 +284,8 @@ namespace AiQ_GUI
{ {
await PreTestFailed("Diagnostic Failure"); await PreTestFailed("Diagnostic Failure");
} }
} }
// ***** Pass/Fails ***** // ***** Pass/Fails *****
@@ -410,11 +336,11 @@ namespace AiQ_GUI
Logging.LogMessage("Final Test Passed"); Logging.LogMessage("Final Test Passed");
if (CamOnTest.RMANum == 0) // Yap to check if it is not a RMA if (CamOnTest.RMANum == 0) // Yap to check if it is not a RMA
{ {
Stats("Final Tests Passed"); Access.Stats("Final Tests Passed", CamOnTest.Model);
} }
else else
{ {
Stats("RMA Final Tests Passed"); Access.Stats("RMA Final Tests Passed", CamOnTest.Model);
} }
} }
@@ -426,11 +352,11 @@ namespace AiQ_GUI
Btn.Text = "Test Failed"; Btn.Text = "Test Failed";
if (!(CamOnTest.RMANum != 0)) // Yap to check if it is not a RMA if (!(CamOnTest.RMANum != 0)) // Yap to check if it is not a RMA
{ {
Stats( ["Final Tests Failed", ErrMssg]); Access.Stats(["Final Tests Failed", ErrMssg], CamOnTest.Model);
} }
else else
{ {
Stats("RMA Final Tests Failed"); Access.Stats("RMA Final Tests Failed", CamOnTest.Model);
} }
AddToActionsList(ErrMssg); AddToActionsList(ErrMssg);
@@ -440,7 +366,7 @@ namespace AiQ_GUI
.Select(lbl => lbl.Text)); // Extract text .Select(lbl => lbl.Text)); // Extract text
string FullFailureValues = RhTxBxActions.Text + Environment.NewLine + RedLbls; string FullFailureValues = RhTxBxActions.Text + Environment.NewLine + RedLbls;
StatsDiags(RedLbls, RhTxBxActions.Text); // Log to Access database Access.StatsDiags(RedLbls, RhTxBxActions.Text, CamOnTest.Model); // Log to Access database
if (await DisplayQuestion("Test failed, appeal?" + Environment.NewLine + "See Actions textbox for details.")) if (await DisplayQuestion("Test failed, appeal?" + Environment.NewLine + "See Actions textbox for details."))
@@ -516,11 +442,11 @@ namespace AiQ_GUI
Logging.LogMessage("Pre Test Passed"); Logging.LogMessage("Pre Test Passed");
if (CamOnTest.RMANum == 0) // Yap to check if it is not a RMA if (CamOnTest.RMANum == 0) // Yap to check if it is not a RMA
{ {
Stats("Pre Tests Passed"); Access.Stats("Pre Tests Passed", CamOnTest.Model);
} }
else else
{ {
Stats("RMA Pre Tests Passed"); Access.Stats("RMA Pre Tests Passed", CamOnTest.Model);
} }
if (await DisplayQuestion("Test passed, restart?")) if (await DisplayQuestion("Test passed, restart?"))
@@ -537,11 +463,11 @@ namespace AiQ_GUI
if (CamOnTest.RMANum == 0) // Yap to check if it is not a RMA if (CamOnTest.RMANum == 0) // Yap to check if it is not a RMA
{ {
Stats(["Pre Tests Failed", ErrMssg]); Access.Stats(["Pre Tests Failed", ErrMssg], CamOnTest.Model);
} }
else else
{ {
Stats("RMA Pre Tests Failed"); Access.Stats("RMA Pre Tests Failed", CamOnTest.Model);
} }
string RedLbls = string.Join(Environment.NewLine, PnlLbls.Controls string RedLbls = string.Join(Environment.NewLine, PnlLbls.Controls
@@ -550,7 +476,7 @@ namespace AiQ_GUI
.Select(lbl => lbl.Text)); // Extract text .Select(lbl => lbl.Text)); // Extract text
string FullFailureValues = RhTxBxActions.Text + Environment.NewLine + RedLbls; string FullFailureValues = RhTxBxActions.Text + Environment.NewLine + RedLbls;
StatsDiags(RedLbls, RhTxBxActions.Text); // Log to Access database Access.StatsDiags(RedLbls, RhTxBxActions.Text, CamOnTest.Model); // Log to Access database
if (await DisplayQuestion("Test failed, restart?" + Environment.NewLine + "See Actions textbox for details.")) if (await DisplayQuestion("Test failed, restart?" + Environment.NewLine + "See Actions textbox for details."))
Helper.RestartApp(); Helper.RestartApp();
@@ -680,7 +606,7 @@ namespace AiQ_GUI
CamOnTest.RMANum = Convert.ToInt32(await DisplayInput("What is the RMA number?")); CamOnTest.RMANum = Convert.ToInt32(await DisplayInput("What is the RMA number?"));
if (CamOnTest.RMANum == -1) // Means they chose the 'I don't know' option if (CamOnTest.RMANum == -1) // Means they chose the 'I don't know' option
{ {
await TestFailed(BtnStartTest, "Please get RMA number from operations team before continuing"); await TestFailed(BtnStartTest, "Please get RMA number from operations team before continuing");
} }
} }
@@ -747,11 +673,11 @@ namespace AiQ_GUI
string ProdcutKeyID = await DisplayInput("What is the Key ID?", false); string ProdcutKeyID = await DisplayInput("What is the Key ID?", false);
if (RegexCache.VaxtorRegex().IsMatch(ProdcutKeyID)) // Means they chose the 'I don't know' option or isn't valid Key ID if (RegexCache.VaxtorRegex().IsMatch(ProdcutKeyID)) // Means they chose the 'I don't know' option or isn't valid Key ID
{ {
Stats("Please Get A Valid Vaxtor Product Key Before Continuing"); Access.Stats("Please Get A Valid Vaxtor Product Key Before Continuing", CamOnTest.Model);
await TestFailed(BtnStartTest, "Please get a valid Vaxtor Product Key before continuing"); await TestFailed(BtnStartTest, "Please get a valid Vaxtor Product Key before continuing");
} }
DiagsAPI.licenses.raptorKeyID = TxBxProductKey.Text; DiagsAPI.licenses.raptorKeyID = TxBxProductKey.Text;
lblVaxtor.Text += DiagsAPI.licenses.raptorKeyID; lblVaxtor.Text += DiagsAPI.licenses.raptorKeyID;
@@ -1785,105 +1711,16 @@ namespace AiQ_GUI
BtnFactoryDefault.BackColor = Color.Green; BtnFactoryDefault.BackColor = Color.Green;
} }
// Constants
const double RealPlateWidthMeters = 0.52; // UK standard plate width
// const double FocalLengthPixels = (50 * 1280) / 14.111224; // focal mm * pixel width / sensor width for IQ
const double FocalLengthPixels = (35 * 1920) / 6.95; // focal mm * pixel width / sensor width for AiQ
const double FrameRate = 25.0; // Frames per second
public class FrameData
{
public long FrameID;
public int PlatePosX;
public int PlatePosY;
public int PlateWidthPixels;
}
public double EstimateSpeed(List<FrameData> frames)
{
double TimeElapsed = 0;
int frameCount = frames.Count;
for (int i = 1; i < frameCount; i++)
{
double time = (frames[i].FrameID - frames[i - 1].FrameID) / FrameRate;
TimeElapsed += time;
}
double FarDist = (FocalLengthPixels * RealPlateWidthMeters) / frames[0].PlateWidthPixels;
double CloseDist = (FocalLengthPixels * RealPlateWidthMeters) / frames[frameCount - 1].PlateWidthPixels;
double speedMph = (Math.Abs(FarDist - CloseDist) / TimeElapsed) * 2.237;
return speedMph;
}
// ***** Test & Debug ***** // ***** Test & Debug *****
private async void BtnTest_Click(object sender, EventArgs e) private void BtnTest_Click(object sender, EventArgs e)
{ {
Stopwatch stopWatchTest = Stopwatch.StartNew(); Stopwatch stopWatchTest = Stopwatch.StartNew();
//string[,] GOD_JSON = { { "propURI", "rtsp://ADMIN:1234@192.168.0.49:554/live/main" } };
//string str = FlexiAPI.BuildJsonUpdate(GOD_JSON, "CameraA");
//AddToActionsList(str);
// To estimate speed
//List<FrameData> frames = new List<FrameData>
//{
// new FrameData { FrameID = 60192555, PlatePosX = 1172, PlatePosY = 393, PlateWidthPixels = 108 },
// new FrameData { FrameID = 60192556, PlatePosX = 1103, PlatePosY = 361, PlateWidthPixels = 105 },
// new FrameData { FrameID = 60192558, PlatePosX = 983, PlatePosY = 331, PlateWidthPixels = 99 },
// new FrameData { FrameID = 60192559, PlatePosX = 930, PlatePosY = 301, PlateWidthPixels = 95 },
// new FrameData { FrameID = 60192560, PlatePosX = 880, PlatePosY = 304, PlateWidthPixels = 93 },
// new FrameData { FrameID = 60192561, PlatePosX = 834, PlatePosY = 278, PlateWidthPixels = 89 },
// new FrameData { FrameID = 60192562, PlatePosX = 792, PlatePosY = 229, PlateWidthPixels = 87 },
// new FrameData { FrameID = 60192563, PlatePosX = 752, PlatePosY = 208, PlateWidthPixels = 85 },
// new FrameData { FrameID = 60192565, PlatePosX = 680, PlatePosY = 187, PlateWidthPixels = 81 },
// new FrameData { FrameID = 60192566, PlatePosX = 648, PlatePosY = 167, PlateWidthPixels = 78 },
// new FrameData { FrameID = 60192567, PlatePosX = 617, PlatePosY = 149, PlateWidthPixels = 76 },
// new FrameData { FrameID = 60192568, PlatePosX = 588, PlatePosY = 132, PlateWidthPixels = 75 },
// new FrameData { FrameID = 60192569, PlatePosX = 561, PlatePosY = 100, PlateWidthPixels = 70 },
// new FrameData { FrameID = 60192570, PlatePosX = 535, PlatePosY = 85, PlateWidthPixels = 72 },
// new FrameData { FrameID = 60192572, PlatePosX = 488, PlatePosY = 70, PlateWidthPixels = 69 },
// new FrameData { FrameID = 60192573, PlatePosX = 466, PlatePosY = 55, PlateWidthPixels = 67 }
//};
//double Spd = EstimateSpeed(frames);
//AddToActionsList("Estimated Speed: " + Spd.ToString("F2") + " MPH");
StatsExcel excelExporter = new(); StatsExcel excelExporter = new();
excelExporter.ExportDatabaseToExcel(); excelExporter.ExportDatabaseToExcel();
// FakeCamera fakeCamera = new FakeCamera(80); // Create an instance of FakeCamera
// //CamOnTest.IP = CbBxFoundCams.Text;
// _ = fakeCamera.StartAsync(CAMTYPE.BAD).ContinueWith(task =>
// {
// //Network.Initialize("developer", "Pass123");
// if (task.IsFaulted)
// {
// AddToActionsList("Error starting FakeCamera: " + task.Exception?.Message);
// }
// else
// {
// AddToActionsList($"FakeCamera started successfully. IP: {fakeCamera}", false);
// }
// });
// await Task.Delay(3000); // Wait for server to start
// CbBxFoundCams.Text = "localhost"; // Should force update in creds an network reinit
// CmBoFoundCams_TextChanged(sender, e);
// CbBxCameraType.SelectedIndex = CbBxCameraType.Items.Count - 1; // Selects AB12CD as model number
// await Task.Delay(3000); // Wait for server to start
//BtnPreTest_Click(sender, e);
AddToActionsList("Estimated Speed: " + Spd.ToString("F2") + " MPH");
stopWatchTest.Stop(); stopWatchTest.Stop();
//AddToActionsList("RunTime " + stopWatchTest.Elapsed.ToString(@"hh\:mm\:ss\.ff")); AddToActionsList("RunTime " + stopWatchTest.Elapsed.ToString(@"hh\:mm\:ss\.ff"));
} }
} }
} }

View File

@@ -77,15 +77,15 @@ namespace AiQ_GUI
{ {
foreach (int ShuffleOrder in Shuffle()) foreach (int ShuffleOrder in Shuffle())
{ {
switch (ShuffleOrder) switch (ShuffleOrder)
{ {
case 0: case 0:
if (!await MainForm.Instance.DisplayQuestion("Is the sleeve aligned correctly?")) if (!await MainForm.Instance.DisplayQuestion("Is the sleeve aligned correctly?"))
{ {
await MainForm.Instance.TestFailed(Btn, "Visual Test Fail - Sleeve not aligned"); await MainForm.Instance.TestFailed(Btn, "Visual Test Fail - Sleeve not aligned");
} }
break; break;
case 1: case 1:
if (!await MainForm.Instance.DisplayQuestion("Are all the screws fitted in the front?")) if (!await MainForm.Instance.DisplayQuestion("Are all the screws fitted in the front?"))
@@ -101,7 +101,7 @@ namespace AiQ_GUI
break; break;
case 3: case 3:
if (await MainForm.Instance.DisplayQuestion("Shake unit, does it rattle?")) if (await MainForm.Instance.DisplayQuestion("Shake unit, does it rattle?"))
{ {
await MainForm.Instance.TestFailed(Btn, "Visual Test Fail - Unit rattles"); await MainForm.Instance.TestFailed(Btn, "Visual Test Fail - Unit rattles");
} }
break; break;

View File

@@ -4,7 +4,7 @@ namespace AiQ_GUI
{ {
class Access class Access
{ {
const string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\Shared drives\MAV Production GUI's\AiQ\GUI's\AiQ_Final_Test.accdb;Persist Security Info=False;OLE DB Services=-1;"; public const string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\Shared drives\MAV Production GUI's\AiQ\GUI's\AiQ_Final_Test.accdb;Persist Security Info=False;OLE DB Services=-1;";
// Reads camera model numbers and descriptions from the database, sorts them alphabetically by model number (except "AB12CD", which appears last), and formats each entry as "ModelNumber - Description". // Reads camera model numbers and descriptions from the database, sorts them alphabetically by model number (except "AB12CD", which appears last), and formats each entry as "ModelNumber - Description".
public static string[] ReadCamTypes() public static string[] ReadCamTypes()
@@ -101,11 +101,74 @@ namespace AiQ_GUI
CameraAccessInfo.SpreadsheetID = Convert.ToString(reader["SSID"]); CameraAccessInfo.SpreadsheetID = Convert.ToString(reader["SSID"]);
conn.Close(); conn.Close();
} }
public static void Stats(string TypeOfTest, string modelNumber)
{
Stats([TypeOfTest], modelNumber);
}
public static void Stats(string[] TypeOfTest, string modelNumber)
{
using OleDbConnection conn = new(connString); // Opens connection to Access database
try
{
conn.Open(); // Opens DB
foreach (string type in TypeOfTest)
{
string query = $"UPDATE AiQ SET [{type}] = [{type}] + 1 WHERE [ModelNumber] = ?"; // Add one for every test ran of this type for this model number
using OleDbCommand cmd = new(query, conn); // Create command
cmd.Parameters.AddWithValue("?", modelNumber); // Add model number to prevent injection
int rowsAffected = cmd.ExecuteNonQuery();
// Execute the command and get the number of rows affected
//if (rowsAffected > 0) // If one or more rows were updated
// AddToActionsList($"Updated {TypeOfTest} for {modelNumber}");
//else
// AddToActionsList($"No rows found for {modelNumber}");
}
conn.Close();
}
catch
{
MainForm.Instance.AddToActionsList("Could not access Access in Google Drive. Is it running?");
return;
}
}
public static void StatsDiags(string redDiagLabels, string RhTxBxActionsText, string ModelNumber)
{
using OleDbConnection conn = new(connString);
conn.Open();
// Null checks
string redVal = string.IsNullOrWhiteSpace(redDiagLabels) ? "-" : redDiagLabels;
string actVal = string.IsNullOrWhiteSpace(RhTxBxActionsText) ? "-" : RhTxBxActionsText;
string model = string.IsNullOrWhiteSpace(ModelNumber) ? "-" : ModelNumber;
const string sql = @"INSERT INTO DiagsStats ([Date], [Model], [Red Diags Labels], [RhTxBxActions Contents]) VALUES (?, ?, ?, ?)";
using OleDbCommand cmd = new(sql, conn);
cmd.Parameters.Add(new OleDbParameter
{
OleDbType = OleDbType.Date,
Value = DateTime.Now
});
cmd.Parameters.AddWithValue("?", model);
cmd.Parameters.AddWithValue("?", redVal);
cmd.Parameters.AddWithValue("?", actVal);
int rows = cmd.ExecuteNonQuery();
conn.Close();
//if (rows > 0)
// AddToActionsList($"DiagsStats inserted ({rows} row) for model '{model}' on {DateTime.Now:yyyy-MM-dd}");
//else
// AddToActionsList("No rows inserted into DiagsStats (unexpected).");
}
} }
// Expected universal data for the GUI, read from the database // Expected universal data for the GUI, read from the database
public class UniversalData public class UniversalData
{ {

View File

@@ -1,17 +1,12 @@
using System; using ClosedXML.Excel;
using System.Data; using System.Data;
using System.Data.OleDb; using System.Data.OleDb;
using ClosedXML.Excel;
namespace AiQ_GUI.Microsoft namespace AiQ_GUI
{ {
internal class StatsExcel internal class StatsExcel
{ {
private const string connString = private const string exportPath = @"G:\Shared drives\MAV Production GUI's\AiQ\GUI's\AiQ_Test_Stats.xlsx";
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\Shared drives\MAV Production GUI's\AiQ\GUI's\AiQ_Final_Test.accdb;Persist Security Info=False;OLE DB Services=-1;";
private readonly string exportPath =
@"C:\Users\BradleyBorn\OneDrive - MAV Systems Ltd\Desktop\AiQ_Test_Stats.xlsx";
public void ExportDatabaseToExcel() public void ExportDatabaseToExcel()
{ {
@@ -19,11 +14,10 @@ namespace AiQ_GUI.Microsoft
{ {
MainForm.Instance.AddToActionsList("=== ExportDatabaseToExcel START ==="); MainForm.Instance.AddToActionsList("=== ExportDatabaseToExcel START ===");
using (OleDbConnection conn = new(connString)) using (OleDbConnection conn = new(Access.connString))
{ {
conn.Open(); conn.Open();
MainForm.Instance.AddToActionsList("Connected to Access database."); MainForm.Instance.AddToActionsList("Connected to Access database.");
DateTime now = DateTime.Now; DateTime now = DateTime.Now;
// ==================== MAIN STATS EXPORT ==================== // ==================== MAIN STATS EXPORT ====================
@@ -51,10 +45,7 @@ namespace AiQ_GUI.Microsoft
[Visual Test Fail - Not All Rear Screws Fitted], [Visual Test Fail - Not All Rear Screws Fitted],
[Visual Test Fail - Unit rattles]"; [Visual Test Fail - Unit rattles]";
string query = $@" string query = $@"SELECT {selectColumns} FROM AiQ";
SELECT
{selectColumns}
FROM AiQ";
OleDbDataAdapter adapter = new(query, conn); OleDbDataAdapter adapter = new(query, conn);
DataTable dataTable = new(); DataTable dataTable = new();
@@ -72,7 +63,7 @@ namespace AiQ_GUI.Microsoft
MainForm.Instance.AddToActionsList($"Adding sheet: {sheetName}"); MainForm.Instance.AddToActionsList($"Adding sheet: {sheetName}");
XLWorkbook workbook; XLWorkbook workbook;
if (System.IO.File.Exists(exportPath)) if (File.Exists(exportPath))
{ {
workbook = new XLWorkbook(exportPath); workbook = new XLWorkbook(exportPath);
MainForm.Instance.AddToActionsList("Opened existing workbook."); MainForm.Instance.AddToActionsList("Opened existing workbook.");
@@ -89,7 +80,7 @@ namespace AiQ_GUI.Microsoft
MainForm.Instance.AddToActionsList($"Deleted old sheet: {sheetName}"); MainForm.Instance.AddToActionsList($"Deleted old sheet: {sheetName}");
} }
var ws = workbook.Worksheets.Add(sheetName); IXLWorksheet ws = workbook.Worksheets.Add(sheetName);
ws.Cell(1, 1).InsertTable(dataTable, "AiQ_Stats", true); ws.Cell(1, 1).InsertTable(dataTable, "AiQ_Stats", true);
ws.Columns().AdjustToContents(); ws.Columns().AdjustToContents();
@@ -99,7 +90,7 @@ namespace AiQ_GUI.Microsoft
// ==================== DIAGS STATS EXPORT (CURRENT MONTH ONLY) ==================== // ==================== DIAGS STATS EXPORT (CURRENT MONTH ONLY) ====================
MainForm.Instance.AddToActionsList("Exporting DiagsStats for current month..."); MainForm.Instance.AddToActionsList("Exporting DiagsStats for current month...");
DateTime monthStart = new DateTime(now.Year, now.Month, 1); DateTime monthStart = new(now.Year, now.Month, 1);
DateTime nextMonth = monthStart.AddMonths(1); DateTime nextMonth = monthStart.AddMonths(1);
string diagsQuery = @" string diagsQuery = @"
@@ -154,9 +145,10 @@ namespace AiQ_GUI.Microsoft
{selectColumns} {selectColumns}
INTO [{backupTableName}] INTO [{backupTableName}]
FROM AiQ"; FROM AiQ";
try try
{ {
using (var cmdBackup = new OleDbCommand(backupSql, conn)) using (OleDbCommand cmdBackup = new(backupSql, conn))
{ {
cmdBackup.ExecuteNonQuery(); cmdBackup.ExecuteNonQuery();
} }
@@ -169,11 +161,10 @@ namespace AiQ_GUI.Microsoft
return; return;
} }
using (var tx = conn.BeginTransaction()) using OleDbTransaction tx = conn.BeginTransaction();
try
{ {
try string resetSql = @"
{
string resetSql = @"
UPDATE AiQ SET UPDATE AiQ SET
[Total Tests Run] = 0, [Total Tests Run] = 0,
[Pre Tests Passed] = 0, [Pre Tests Passed] = 0,
@@ -197,42 +188,41 @@ namespace AiQ_GUI.Microsoft
[Visual Test Fail - Not All Rear Screws Fitted] = 0, [Visual Test Fail - Not All Rear Screws Fitted] = 0,
[Visual Test Fail - Unit rattles] = 0;"; [Visual Test Fail - Unit rattles] = 0;";
using (var cmdReset = new OleDbCommand(resetSql, conn, tx)) using (OleDbCommand cmdReset = new(resetSql, conn, tx))
{
int affected = cmdReset.ExecuteNonQuery();
MainForm.Instance.AddToActionsList($"Zeroed counters on AiQ rows: {affected} row(s).");
}
int updatedRows;
using (var cmdUpd = new OleDbCommand("UPDATE UniversalData SET LastStatsRun = ?", conn, tx))
{
cmdUpd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.Date, Value = now });
updatedRows = cmdUpd.ExecuteNonQuery();
}
if (updatedRows == 0)
{
using (var cmdIns = new OleDbCommand("INSERT INTO UniversalData (LastStatsRun) VALUES (?)", conn, tx))
{
cmdIns.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.Date, Value = now });
cmdIns.ExecuteNonQuery();
MainForm.Instance.AddToActionsList("Inserted LastStatsRun row.");
}
}
else
{
MainForm.Instance.AddToActionsList("Updated LastStatsRun successfully.");
}
tx.Commit();
MainForm.Instance.AddToActionsList("Reset committed.");
}
catch (Exception resetEx)
{ {
tx.Rollback(); int affected = cmdReset.ExecuteNonQuery();
MainForm.Instance.AddToActionsList($"ERROR during reset, rolled back. Details: {resetEx.Message}"); MainForm.Instance.AddToActionsList($"Zeroed counters on AiQ rows: {affected} row(s).");
} }
int updatedRows;
using (OleDbCommand cmdUpd = new("UPDATE UniversalData SET LastStatsRun = ?", conn, tx))
{
cmdUpd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.Date, Value = now });
updatedRows = cmdUpd.ExecuteNonQuery();
}
if (updatedRows == 0)
{
using OleDbCommand cmdIns = new("INSERT INTO UniversalData (LastStatsRun) VALUES (?)", conn, tx);
cmdIns.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.Date, Value = now });
cmdIns.ExecuteNonQuery();
MainForm.Instance.AddToActionsList("Inserted LastStatsRun row.");
}
else
{
MainForm.Instance.AddToActionsList("Updated LastStatsRun successfully.");
}
tx.Commit();
MainForm.Instance.AddToActionsList("Reset committed.");
} }
catch (Exception resetEx)
{
tx.Rollback();
MainForm.Instance.AddToActionsList($"ERROR during reset, rolled back. Details: {resetEx.Message}");
}
conn.Close();
} }
MainForm.Instance.AddToActionsList("=== ExportDatabaseToExcel END ==="); MainForm.Instance.AddToActionsList("=== ExportDatabaseToExcel END ===");