<Feat>: Add universal NLog diagnostics and improve AppDiagnostic UI

Cause:

- Live diagnostics required logging from multiple applications without blocking TBF.
- Shared nlog.config files caused configuration conflicts.
- The original viewer lacked configurable colors and practical log controls.
- Inconsistent diagnostic deployment caused log transfer failures and locked shared DLLs during builds.

Solution:

1. Added universal diagnostic transport
   - Added AppDiagnostic.Logging with an NLog target and named-pipe communication.
   - Added background buffering and automatic reconnection.
   - Registered the diagnostic connector programmatically.

2. Separated diagnostic window lifecycle
   - Run AppDiagnostic as an independent process.
   - Activate the existing window on repeated launches.
   - Keep TBF running when the diagnostic window closes.

3. Corrected diagnostic deployment
   - Copy the complete diagnostic output into a dedicated AppDiagnostic subdirectory during build.
   - Overwrite existing deployment files to prevent inconsistent versions.
   - Validate and launch the executable from that subdirectory with an explicit working directory.

4. Improved the log viewer
   - Added configurable substring colors with a palette and live preview.
   - Added text, level and application filters.
   - Added line wrapping, clipboard actions and log export.
   - Added Pause/Resume, Refresh, Clear, auto-scroll and Always on top.
   - Added connection and log counters.
   - Persist color rules between sessions.

5. Removed legacy dependencies
   - Replaced LiveLogCache with structured diagnostic storage.
   - Removed AppDiagnostic dependencies on log4net and SharedComponents.

Validation:

- Confirmed successful log transfer when launching AppDiagnostic from TBF.
This commit is contained in:
2026-09-10 17:45:29 +02:00
parent 1c6f9af2bb
commit 8c77df207a
60 changed files with 2803 additions and 900 deletions
+159 -156
View File
@@ -19,32 +19,32 @@ namespace TBF
{
public class Program
{
public const string HomeDir = "C:\\Tbf\\"; /// Contains subdirectories Results, Logs, Images, ...
public const string ConfigDir = "C:\\Tbf\\Cfg\\";
public const string HomeDir = "C:\\Tbf\\"; /// Contains subdirectories Results, Logs, Images, ...
public const string ConfigDir = "C:\\Tbf\\Cfg\\";
public const string GraphsDir = "C:\\Tbf\\Graphs\\";
public const string ImagesDir = "C:\\Tbf\\Images\\";
public const string TempImagesDir = "C:\\Tbf\\Images\\Temp\\";
public const string TempImagesDir = "C:\\Tbf\\Images\\Temp\\";
public static string ExecutableDir;
/// log4net
static ILog log;
const string log4netConfigFName = "log4netConfig.xml";
/// log4net
static ILog log;
const string log4netConfigFName = "log4netConfig.xml";
/// Program information
public static string Version; /// version string
public static DateTime BuildDateTime; /// date and time of program build
public static DateTime BuildDateTime; /// date and time of program build
/// Local settings
public static LocalSettings LocalSettings;
public const string LocalSettingsFileName = "config.xml";
public const string LocalSettingsBackupName = "config.backup.xml";
/// Local settings
public static LocalSettings LocalSettings;
public const string LocalSettingsFileName = "config.xml";
public const string LocalSettingsBackupName = "config.backup.xml";
public static System.Globalization.CultureInfo AltCulture;
public static System.Globalization.CultureInfo AltCulture;
static IList<Procedure> listOfProcedures;
/// <summary>
/// <summary>
/// Selected procedure data
/// - before the main program window is open, objects referenced by this variable
/// are loaded from the database.
@@ -69,18 +69,18 @@ namespace TBF
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
/// Program version string
System.Reflection.Assembly thisAssembly = System.Reflection.Assembly.GetExecutingAssembly();
ExecutableDir = Path.GetDirectoryName(thisAssembly.Location);
Version ver = thisAssembly.GetName().Version;
Version = string.Format("{0}.{1}.{2}", ver.Major, ver.Minor, ver.Build);
BuildDateTime = new System.IO.FileInfo(thisAssembly.Location).LastWriteTime;
BuildDateTime = new System.IO.FileInfo(thisAssembly.Location).LastWriteTime;
/// Local program configuration directory including the trailing backslash
string locAppDataDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) +
Path.DirectorySeparatorChar + "TestBenchFramework" + Path.DirectorySeparatorChar;
Path.DirectorySeparatorChar + "TestBenchFramework" + Path.DirectorySeparatorChar;
string sampleConfigDir = Application.StartupPath + Path.DirectorySeparatorChar + "SampleConfig" + Path.DirectorySeparatorChar;
@@ -108,7 +108,7 @@ namespace TBF
if (File.Exists(locAppDataDir + LocalSettingsBackupName))
File.Copy(locAppDataDir + LocalSettingsBackupName, LocalSettingsBackupName);
if (File.Exists(locAppDataDir + log4netConfigFName))
File.Copy(locAppDataDir + log4netConfigFName, log4netConfigFName);
else if (File.Exists(sampleConfigDir + log4netConfigFName))
@@ -138,67 +138,67 @@ namespace TBF
Environment.CurrentDirectory = ConfigDir;
}
if (!Directory.Exists(ImagesDir)) Directory.CreateDirectory(ImagesDir);
if (!Directory.Exists(TempImagesDir)) Directory.CreateDirectory(TempImagesDir);
if (!Directory.Exists(ImagesDir)) Directory.CreateDirectory(ImagesDir);
if (!Directory.Exists(TempImagesDir)) Directory.CreateDirectory(TempImagesDir);
IEnumerable<string> files = Directory.EnumerateFiles(TempImagesDir); /// TODO: Implement recursive directory delete
IEnumerable<string> files = Directory.EnumerateFiles(TempImagesDir); /// TODO: Implement recursive directory delete
foreach (var file in files) File.Delete(file);
}
}
catch (Exception)
{
MessageBox.Show("Error creating a local application data directory and preparing an initial configuration", "Fatal error");
return; /// Fatal error
return; /// Fatal error
}
/// Configure and start logging
/// Configure and start logging
log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(ConfigDir + log4netConfigFName));
log = LogManager.GetLogger(typeof(Program));
log.Fatal("--------------------------------------------------------------------------------");
log.Fatal(string.Format("TBF ver.{0}", Version));
log = LogManager.GetLogger(typeof(Program));
log.Fatal("--------------------------------------------------------------------------------");
log.Fatal(string.Format("TBF ver.{0}", Version));
///
///
/// Load the local settings
///
Program.LocalSettings = LocalSettings.Load(Program.LocalSettingsFileName);
if (Program.LocalSettings == null || Program.LocalSettings.TestBenches == null)
{
/// Loading local seetings from regular config file failed. Use the backup
Program.LocalSettings = LocalSettings.Load(Program.LocalSettingsBackupName);
if (Program.LocalSettings == null || Program.LocalSettings.TestBenches == null)
{
log.Fatal("Application terminated.");
MessageBox.Show(string.Format("Could not load file {0}, nor {1}.", Program.LocalSettingsFileName, Program.LocalSettingsBackupName), "Fatal error");
return; /// Fatal error
///
Program.LocalSettings = LocalSettings.Load(Program.LocalSettingsFileName);
if (Program.LocalSettings == null || Program.LocalSettings.TestBenches == null)
{
/// Loading local seetings from regular config file failed. Use the backup
Program.LocalSettings = LocalSettings.Load(Program.LocalSettingsBackupName);
if (Program.LocalSettings == null || Program.LocalSettings.TestBenches == null)
{
log.Fatal("Application terminated.");
MessageBox.Show(string.Format("Could not load file {0}, nor {1}.", Program.LocalSettingsFileName, Program.LocalSettingsBackupName), "Fatal error");
return; /// Fatal error
}
else
{
LocalSettings.Save(); /// Save the settings to overwrite the wrong file
else
{
LocalSettings.Save(); /// Save the settings to overwrite the wrong file
log.FatalFormat("BatchNr = {0}", LocalSettings.BatchNr);
}
}
else
{
/// Loading local seetings from the regular config file was successful. Update the backup
File.Copy(Program.LocalSettingsFileName, Program.LocalSettingsBackupName, true);
log.FatalFormat("BatchNr = {0}", LocalSettings.BatchNr);
}
}
}
else
{
/// Loading local seetings from the regular config file was successful. Update the backup
File.Copy(Program.LocalSettingsFileName, Program.LocalSettingsBackupName, true);
log.FatalFormat("BatchNr = {0}", LocalSettings.BatchNr);
}
try
{
string culture = LocalSettings.Language.Replace('_', '-');
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(culture);
}
catch (Exception e)
{
string msg = e.Message;
MessageBox.Show("Selected language not supported.\nUsing English.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
System.Threading.Thread.CurrentThread.CurrentUICulture =
new System.Globalization.CultureInfo("en");
}
try
{
string culture = LocalSettings.Language.Replace('_', '-');
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(culture);
}
catch (Exception e)
{
string msg = e.Message;
MessageBox.Show("Selected language not supported.\nUsing English.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
System.Threading.Thread.CurrentThread.CurrentUICulture =
new System.Globalization.CultureInfo("en");
}
//AltCulture = null;
AltCulture = new System.Globalization.CultureInfo("SK");
//AltCulture = null;
AltCulture = new System.Globalization.CultureInfo("SK");
/// This belongs to Application.Run(new MainWnd()) ...
@@ -207,28 +207,28 @@ namespace TBF
Application.SetCompatibleTextRenderingDefault(false);
/// Ensure that there is at least one bench in the configuration
while (Program.LocalSettings.BenchesCount == 0)
{
log.Warn("No test benches in the local configuration -> display an appropriate dialog.");
/// Ensure that there is at least one bench in the configuration
while (Program.LocalSettings.BenchesCount == 0)
{
log.Warn("No test benches in the local configuration -> display an appropriate dialog.");
/// Ask what to do, ask for the password, open 'DatabaseSetingsDlg' and continue on OK
if ((new NoBenchOrDatabaseDlg { Message = Strings.NoBenchMsg }.ShowDialog() != DialogResult.OK) ||
(new SharedDatabase.Forms.LoginDlg(true).ShowDialog() == DialogResult.Cancel) ||
/// Ask what to do, ask for the password, open 'DatabaseSetingsDlg' and continue on OK
if ((new NoBenchOrDatabaseDlg { Message = Strings.NoBenchMsg }.ShowDialog() != DialogResult.OK) ||
(new SharedDatabase.Forms.LoginDlg(true).ShowDialog() == DialogResult.Cancel) ||
(new TBF.UI.Settings.BenchesDlg().ShowDialog() == DialogResult.Cancel))
{
return; /// Exit program
{
return; /// Exit program
}
log.Warn("Loading the local settings again.");
Program.LocalSettings = LocalSettings.Load(Program.LocalSettingsFileName);
if (Program.LocalSettings == null) return; /// Fatal error
log.Warn("Loading the local settings again.");
Program.LocalSettings = LocalSettings.Load(Program.LocalSettingsFileName);
if (Program.LocalSettings == null) return; /// Fatal error
}
/// User login
bool retryLogin = true; /// true = stay in a login loop
do
{
{
LoadingConfigEnd();
LoginDlgWithBenchSelection loginDlgBench;
@@ -240,8 +240,8 @@ namespace TBF
{
loginDlgBench = new LoginDlgWithBenchSelection();
}
loginDlgBench.Method = LocalSettings.LoginMethod;
DialogResult dr = loginDlgBench.ShowDialog();
loginDlgBench.Method = LocalSettings.LoginMethod;
DialogResult dr = loginDlgBench.ShowDialog();
if (dr == DialogResult.Cancel)
{
@@ -253,11 +253,11 @@ namespace TBF
{
if (LocalSettings.TestBenches[i].BenchName == loginDlgBench.BenchName)
{
log.FatalFormat("Test bench name: {0}", loginDlgBench.BenchName);
log.FatalFormat("Test bench name: {0}", loginDlgBench.BenchName);
LoadingConfigStart();
CurrentUser.RemoteUsersDB = LocalSettings.TestBenches[i].UsersDBSettings;
CurrentUser.LocalUsersDB = LocalSettings.TestBenches[i].ProceduresDBSettings;
CurrentUser.RemoteUsersDB = LocalSettings.TestBenches[i].UsersDBSettings;
CurrentUser.LocalUsersDB = LocalSettings.TestBenches[i].ProceduresDBSettings;
SharedDatabase.Entities.User loadedUser = null;
try
@@ -268,32 +268,32 @@ namespace TBF
GID[] reqGrpMembership = null;
#endif
bool authorized = false;
AuthorizedAs authorizedAs = AuthorizedAs.PowerUser;
AuthorizedAs authorizedAs = AuthorizedAs.PowerUser;
if (Common.Utils.IsPowerUser(loginDlgBench.Alias, loginDlgBench.Password))
{
loadedUser = new SharedDatabase.Entities.User(loginDlgBench.Alias, 6, true);
{
loadedUser = new SharedDatabase.Entities.User(loginDlgBench.Alias, 6, true);
authorized = loadedUser.Authorize(loginDlgBench.Alias, loginDlgBench.Password, reqGrpMembership, null);
if (authorized)
{
CurrentUser.AuthorizedAs = AuthorizedAs.PowerUser;
}
}
}
///
/// Authorisation using databases
///
if (!authorized)
{
DBSettings[] dbs = new DBSettings[] { CurrentUser.RemoteUsersDB, CurrentUser.LocalUsersDB };
{
DBSettings[] dbs = new DBSettings[] { CurrentUser.RemoteUsersDB, CurrentUser.LocalUsersDB };
authorizedAs = AuthorizedAs.RemoteUser; /// Try remote DB first
authorizedAs = AuthorizedAs.RemoteUser; /// Try remote DB first
foreach (var db in dbs)
{
/// Load and authorise user from the UsersDB database
try
{
foreach (var db in dbs)
{
/// Load and authorise user from the UsersDB database
try
{
if (loginDlgBench.Password == LoginDlgWithBenchSelection.UseTheTagPassword)
{
loadedUser = SharedDatabase.Entities.User.LoadUserByTag(loginDlgBench.Alias, db);
@@ -320,24 +320,24 @@ namespace TBF
break;
}
}
}
catch
{
authorized = false;
}
}
catch
{
authorized = false;
}
if (authorized) break;
if (authorized) break;
authorizedAs = AuthorizedAs.LocalUser; /// Try local DB afterwards
authorizedAs = AuthorizedAs.LocalUser; /// Try local DB afterwards
}
}
}
if (authorized)
if (authorized)
{
loadedUser.SetLegalizator(loginDlgBench.Legalizator);
CurrentUser.AuthorizedAs = authorizedAs;
LocalSettings.LoginMethod = loginDlgBench.Method; /// Save the login method actually used
LocalSettings.LoginMethod = loginDlgBench.Method; /// Save the login method actually used
if (LocalSettings.TestBenches[i].IsRealBench)
{
@@ -349,9 +349,9 @@ namespace TBF
return;
}
}
log.InfoFormat("Password accepted, bench '{0}' parameters loaded.",
LocalSettings.TestBenches[i].BenchName);
LocalSettings.TestBenches[i].BenchName);
/// Copy the selected bench settings to CurrentBench.
/// Clone() guarantees that current bench settings wont be modified
@@ -448,31 +448,31 @@ namespace TBF
/// Ask what to do
switch ((new NoBenchOrDatabaseDlg { Message = Strings.NoDatabaseMsg, ShowRetry = true }).ShowDialog())
{
case DialogResult.Abort:
{
case DialogResult.Abort:
return; /// Exit program
case DialogResult.Retry:
case DialogResult.Retry:
break; /// Retry connection to the database, stay inside the loop
case DialogResult.Yes:
new TBF.UI.Settings.UpgradeSelectionDlg().ShowDialog();
break; /// Stay inside the loop
default:
/// Open 'DatabaseSetingsDlg' and retry DB connect on OK
default:
/// Open 'DatabaseSetingsDlg' and retry DB connect on OK
if (new SharedDatabase.Forms.LoginDlg(true).ShowDialog() == DialogResult.Cancel ||
new TBF.UI.Settings.BenchesDlg().ShowDialog() == DialogResult.Cancel)
{
return; /// Exit program
{
return; /// Exit program
}
if (Program.LocalSettings == null)
if (Program.LocalSettings == null)
return; /// Fatal error -> Exit program
else
break; /// Stay inside the loop
break; /// Stay inside the loop
}
}
} // if benchname is OK
}
} // if benchname is OK
} // for all benches in local settings loop
} // not Canceled
} //do
@@ -485,53 +485,56 @@ namespace TBF
{
if (listOfProcedures != null && listOfProcedures.Count == 1)
{
log.InfoFormat("Pre-selecting the procedure {0}", LocalSettings.LastProcedureName);
SelectedProcedure = listOfProcedures[0];
log.InfoFormat("Pre-selecting the procedure {0}", LocalSettings.LastProcedureName);
SelectedProcedure = listOfProcedures[0];
}
}
try
{
//AppDiagnostic SDK - nlog connector registration
AppDiagnostic.Logging.AppDiagnosticConnector.Register();
try
{
/// Open the main application window
log.Info("Creating the main window");
MainWnd = new UI.MainWnd();
log.Info("Opening the main window");
MainWnd = new UI.MainWnd();
log.Info("Opening the main window");
LoadingConfigEnd();
Application.Run(MainWnd);
log.Info("The main window was closed");
}
catch (Exception e)
{
LogException(log, "Exception in Application.Run(MainWnd)", e);
}
finally
{
/// Save local settings
LocalSettings.Save();
}
log.Info("The main window was closed");
}
catch (Exception e)
{
LogException(log, "Exception in Application.Run(MainWnd)", e);
}
finally
{
/// Save local settings
LocalSettings.Save();
}
/// Close Fluent NHibernate
/// Todo
log.Info("Exiting application.");
log.Info("Exiting application.");
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
LogException(log, "Unhandled exception", (Exception)args.ExceptionObject);
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
LogException(log, "Unhandled exception", (Exception)args.ExceptionObject);
}
static void LogException(ILog log, string description, Exception e)
{
log.FatalFormat("---------------( {0} )---------------", description);
log.FatalFormat("Message : {0}", e.Message);
if (e.InnerException != null)
{
log.FatalFormat("InnerMessage : {0}", e.InnerException.Message);
}
log.FatalFormat("StackTrace : {0}{1}", Environment.NewLine, e.StackTrace);
log.Fatal("--------------------------------------");
}
static void LogException(ILog log, string description, Exception e)
{
log.FatalFormat("---------------( {0} )---------------", description);
log.FatalFormat("Message : {0}", e.Message);
if (e.InnerException != null)
{
log.FatalFormat("InnerMessage : {0}", e.InnerException.Message);
}
log.FatalFormat("StackTrace : {0}{1}", Environment.NewLine, e.StackTrace);
log.Fatal("--------------------------------------");
}
static UI.Shared.ModelessActivityForm form;
@@ -562,5 +565,5 @@ namespace TBF
form = null;
formThread = null;
}
}
}
}
+8 -3
View File
@@ -4595,9 +4595,9 @@
<Project>{5954d496-caab-4f7a-bde2-bdc8f47dab19}</Project>
<Name>NfcS5_DLL</Name>
</ProjectReference>
<ProjectReference Include="..\AppDiagnostic\AppDiagnostic.csproj">
<Project>{fa9abad1-7184-4295-ade8-d44f2e3de6b2}</Project>
<Name>AppDiagnostic</Name>
<ProjectReference Include="..\AppDiagnostic.Logging\AppDiagnostic.Logging.csproj">
<Project>{a7af8ed2-362e-4dbb-b607-eba2820719ec}</Project>
<Name>AppDiagnostic.Logging</Name>
</ProjectReference>
<ProjectReference Include="..\Common\Common.csproj">
<Project>{c8939821-ba5c-4988-a3d0-bf53b74865c7}</Project>
@@ -4694,4 +4694,9 @@
<ItemGroup>
<Compile Include="Rig\TestMethods\GenesisCommunication\GenesisCalibrationFactors.cs" />
</ItemGroup>
<PropertyGroup>
<PostBuildEvent>if not exist "$(TargetDir)AppDiagnostic\" mkdir "$(TargetDir)AppDiagnostic\"
xcopy /Y /E /I "$(SolutionDir)AppDiagnostic\bin\$(ConfigurationName)\*" "$(TargetDir)AppDiagnostic\"
if errorlevel 1 exit /b 1</PostBuildEvent>
</PropertyGroup>
</Project>
+189 -169
View File
@@ -22,6 +22,8 @@ using SharedComponents;
using System.Diagnostics;
using TBF.Rig.TestMethods.iPerlCommunication;
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication;
using System.Diagnostics;
using System.IO;
namespace TBF.UI
{
@@ -31,6 +33,7 @@ namespace TBF.UI
public partial class MainWnd : Form
{
static readonly ILog log = LogManager.GetLogger(typeof(MainWnd));
private static readonly NLog.Logger diagnosticLogger = NLog.LogManager.GetCurrentClassLogger();
/// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi
public static int Dpi;
@@ -49,7 +52,7 @@ namespace TBF.UI
IList<SharedDatabase.Entities.OrderInfo> tracingDBOrders; /// Production orders loaded from the production tracing DB
IList<TBF.Rig.Output.DB.SensusOracle.OrderDetails> oracleOrders; /// Production orders loaded from the Oracle DB
IList<ProcedureInfo> procedureInfos; /// Composed procedure infos
///
///
public ProcedureInfo SelectedProcedure;
public Procedure CurrentProcedure;
@@ -58,7 +61,7 @@ namespace TBF.UI
/// </summary>
Shared.ModelessActivityForm closingTbfMessageForm;
TestProgressControls testProgressControls;
TestProgressControls testProgressControls;
/// <summary>
/// Set when procedures are updated while the ProceduresComboBox is disabled (i.e. during a test).
@@ -78,36 +81,36 @@ namespace TBF.UI
{
Invalid = -1,
Hydraulics = 0,
Process,
Process,
Insert,
Results,
Results,
Graphs,
Events,
Calendar,
Camera,
TabPagesCount
TabPagesCount
}
/// <summary>
/// Event handlers switching between tab pages
/// </summary>
private void homeTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Hydraulics); }
private void processTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Process); }
private void resultsTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Results); }
private void graphsToolStripMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Graphs); }
private void eventsTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Events); }
private void processTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Process); }
private void resultsTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Results); }
private void graphsToolStripMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Graphs); }
private void eventsTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Events); }
private void calendarTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Calendar); }
#if CAMERA
private System.Windows.Forms.ToolStripMenuItem cameraTSMItem;
private void cameraTSMItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Camera); }
private System.Windows.Forms.ToolStripMenuItem cameraTSMItem;
private void cameraTSMItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Camera); }
#endif
/// DB entities of components loaded in the MainWnd constructor
IList<Config.Entities.Component> cmpntEntities;
/// <summary>
/// <summary>
/// Constructor
/// </summary>
public MainWnd()
@@ -130,24 +133,24 @@ namespace TBF.UI
procedureInfos = new List<ProcedureInfo>();
SelectedProcedure = null;
CurrentProcedure = null;
///
/// Customize menu items
///
#if CAMERA
/// Add 'Camera' menu item
cameraTSMItem = new System.Windows.Forms.ToolStripMenuItem();
cameraTSMItem.Name = "cameraTSMItem";
cameraTSMItem.Text = Strings.Camera;
cameraTSMItem.Click += new System.EventHandler(this.cameraTSMItem_Click);
mainMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {this.cameraTSMItem});
///
/// Customize menu items
///
#if CAMERA
/// Add 'Camera' menu item
cameraTSMItem = new System.Windows.Forms.ToolStripMenuItem();
cameraTSMItem.Name = "cameraTSMItem";
cameraTSMItem.Text = Strings.Camera;
cameraTSMItem.Click += new System.EventHandler(this.cameraTSMItem_Click);
mainMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.cameraTSMItem });
#endif
UpdateMenuItemsVisibility();
optoHeadsToolStripMenuItem.Visible = true;
optoHeadsToolStripMenuItem.Enabled = false;
optoHeadsToolStripMenuItem.Enabled = false;
IsShutdownDisabled = true;
IsShutdownPCAfterClosingTbf = false;
@@ -166,11 +169,11 @@ namespace TBF.UI
Rig.StateMachine.MachineState = TBF.DB.CurrentBench.IsRealBench ? Rig.MachineState.StartingUp : Rig.MachineState.Disabled;
#if DEBUG
#if DEBUG
//define always valid for printer test - BUMI
Rig.StateMachine.MachineState = Rig.MachineState.StartingUp;
#endif
#endif
///
if (Rig.StateMachine.MachineState == Rig.MachineState.StartingUp)
{
@@ -230,20 +233,20 @@ namespace TBF.UI
}
}
void Localize()
{
void Localize()
{
///
/// Menu
///
benchTSMenuItem.Text = Strings.Bench;
benchComponentsTSMenuItem.Text = Strings.Components;
benchPathsTSMenuItem.Text = Strings.Paths;
benchTransitionsToolStripMenuItem.Text = Strings.Transitions;
benchMetrologyTSMenuItem.Text = Strings.Metrology;
benchUncertaintyTSMItem.Text = Strings.Uncertainty;
benchTestProfilesTSMItem.Text = Strings.Test_profiles;
editSchDrawingTSMItem.Text = Strings.Edit_schematic_drawing;
exitToolStripMenuItem.Text = Strings.Exit;
benchComponentsTSMenuItem.Text = Strings.Components;
benchPathsTSMenuItem.Text = Strings.Paths;
benchTransitionsToolStripMenuItem.Text = Strings.Transitions;
benchMetrologyTSMenuItem.Text = Strings.Metrology;
benchUncertaintyTSMItem.Text = Strings.Uncertainty;
benchTestProfilesTSMItem.Text = Strings.Test_profiles;
editSchDrawingTSMItem.Text = Strings.Edit_schematic_drawing;
exitToolStripMenuItem.Text = Strings.Exit;
proceduresToolStripMenuItem.Text = Strings.Procedures;
homeTSMenuItem.Text = Strings.Home;
processToolStripMenuItem.Text = Strings.Process;
@@ -252,31 +255,31 @@ namespace TBF.UI
eventLogsTSMenuItem.Text = Strings.Event_logs;
calendarTSMenuItem.Text = Strings.Calendar;
settingsTSMenuItem.Text = Strings.Settings;
usersTSMenuItem.Text = Strings.Users;
languageTSMItem.Text = Strings.Language;
databaseSettingsTSMenuItem.Text = Strings.Database;
backUpTSMItem.Text = Strings.Backup;
backUpConfigTSMItem.Text = Strings.Configuration;
backUpResultsTSMItem.Text = Strings.Results;
passwdTSMItem.Text = Strings.Password;
upgradeTSMenuItem.Text = Strings.Upgrade_DB;
usersTSMenuItem.Text = Strings.Users;
languageTSMItem.Text = Strings.Language;
databaseSettingsTSMenuItem.Text = Strings.Database;
backUpTSMItem.Text = Strings.Backup;
backUpConfigTSMItem.Text = Strings.Configuration;
backUpResultsTSMItem.Text = Strings.Results;
passwdTSMItem.Text = Strings.Password;
upgradeTSMenuItem.Text = Strings.Upgrade_DB;
appDiagnosticMenuItem.Text = Strings.Application_Diagnostic;
optoHeadsToolStripMenuItem.Text = Strings.Optical_heads;
clearCountersToolStripMenuItem.Text = Strings.Clear_counters;
clearCountersToolStripMenuItem.Text = Strings.Clear_counters;
helpTSMenuItem.Text = Strings.Help;
aboutTSMenuItem.Text = Strings.About;
aboutTSMenuItem.Text = Strings.About;
procedureGroupBox.Text = Strings.Procedure;
activityGroupBox.Text = Strings.Activity;
progressGroupBox.Text = Strings.Progress;
}
activityGroupBox.Text = Strings.Activity;
progressGroupBox.Text = Strings.Progress;
}
/// <summary>
/// Initializes this window and its controls
/// </summary>
private void MainWnd_Load(object sender, EventArgs e)
{
Localize();
Localize();
TBF.LocalSettings ls = Program.LocalSettings;
WindowState = (ls.MainWndMaximized ? FormWindowState.Maximized : FormWindowState.Normal);
@@ -297,23 +300,23 @@ namespace TBF.UI
if (TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.StartingUp)
{
var form = new Shared.ModelessActivityForm()
{
Message = Strings.Starting_system,
FontFamily = "Arial",
FontSize = 24,
FontStyle = FontStyle.Regular,
BackgroundColor = Color.OliveDrab, /// or Color.YellowGreen
StartActivityHandler = true,
};
Thread formThread = new Thread(() => form.ShowDialog());
formThread.Start();
var form = new Shared.ModelessActivityForm()
{
Message = Strings.Starting_system,
FontFamily = "Arial",
FontSize = 24,
FontStyle = FontStyle.Regular,
BackgroundColor = Color.OliveDrab, /// or Color.YellowGreen
StartActivityHandler = true,
};
Thread formThread = new Thread(() => form.ShowDialog());
formThread.Start();
try
{
string message = Rig.StateMachine.InitializeDevices();
form.CloseForm(null, new EventArgs());
formThread.Join();
form.CloseForm(null, new EventArgs());
formThread.Join();
#if !DEBUG
if (message != null)
{
@@ -324,43 +327,43 @@ namespace TBF.UI
}
#endif
Bridge.ButtonsEtcHandler += delegate(object sndr, ButtonsEtcEventArgs args)
Bridge.ButtonsEtcHandler += delegate (object sndr, ButtonsEtcEventArgs args)
{
if (InvokeRequired) { Invoke(new EventHandler<ButtonsEtcEventArgs>(OnButtonsEtc), sndr, args); }
else OnButtonsEtc(sndr, args);
};
Bridge.ActivityHandler += delegate(object sndr, UiBridge.ActivityEventArgs args)
Bridge.ActivityHandler += delegate (object sndr, UiBridge.ActivityEventArgs args)
{
if (InvokeRequired) { Invoke(new EventHandler<UiBridge.ActivityEventArgs>(OnActivity), sndr, args); }
else OnActivity(sndr, args);
};
Bridge.StateChangedHandler += delegate(object sndr, UiBridge.StateChangedEventArgs args)
Bridge.StateChangedHandler += delegate (object sndr, UiBridge.StateChangedEventArgs args)
{
if (InvokeRequired) { Invoke(new EventHandler<UiBridge.StateChangedEventArgs>(OnStateChanged), sndr, args); }
else OnStateChanged(sndr, args);
};
Bridge.StateMachineTickHandler += delegate(object sndr, UiBridge.StateMachineTickEventArgs args)
Bridge.StateMachineTickHandler += delegate (object sndr, UiBridge.StateMachineTickEventArgs args)
{
if (InvokeRequired) { Invoke(new EventHandler<UiBridge.StateMachineTickEventArgs>(OnStateMachineTick), sndr, args); }
else OnStateMachineTick(sndr, args);
};
Bridge.TestProgressHandler += delegate(object sndr, UiBridge.TestProgressEventArgs args)
Bridge.TestProgressHandler += delegate (object sndr, UiBridge.TestProgressEventArgs args)
{
if (InvokeRequired) { Invoke(new EventHandler<UiBridge.TestProgressEventArgs>(OnTestProgress), sndr, args); }
else OnTestProgress(sndr, args);
};
Bridge.ProcedureSelectedHandler += delegate(object sndr, UiBridge.ProcedureSelectedEventArgs args)
Bridge.ProcedureSelectedHandler += delegate (object sndr, UiBridge.ProcedureSelectedEventArgs args)
{
if (InvokeRequired) { Invoke(new EventHandler<UiBridge.ProcedureSelectedEventArgs>(OnProcedureSelected), sndr, args); }
else OnProcedureSelected(sndr, args);
};
Bridge.SaveSettingsHandler += delegate(object sndr, UiBridge.SaveSettingsEventArgs args)
Bridge.SaveSettingsHandler += delegate (object sndr, UiBridge.SaveSettingsEventArgs args)
{
if (InvokeRequired) { Invoke(new EventHandler<UiBridge.SaveSettingsEventArgs>(OnSaveSettings), sndr, args); }
else OnSaveSettings(sndr, args);
@@ -370,10 +373,10 @@ namespace TBF.UI
{
TBF.Rig.StateMachine.MachineState = TBF.Rig.MachineState.FailedToStart;
form.CloseForm(null, new EventArgs());
formThread.Join();
form.CloseForm(null, new EventArgs());
formThread.Join();
string errMsg = string.Format(Strings.Failed_to_initialize_device_0_1_2,
string errMsg = string.Format(Strings.Failed_to_initialize_device_0_1_2,
Rig.StateMachine.CurrentlyInitializedComponentName,
Environment.NewLine,
exc.Message);
@@ -390,26 +393,26 @@ namespace TBF.UI
SelectedProcedure = new ProcedureInfo(ls.LastProcedureSource, ls.LastProcedureNr, ls.LastProcedureName, signature);
procedureComboBox.Text = SelectedProcedure.ToString();
rightHorizSplitContainer.SplitterDistance = Program.LocalSettings.RightPaneHorizSplitterDistance;
topVerticalSplitContainer.SplitterDistance = Program.LocalSettings.TopPaneVerticalSplitterDistance;
rightHorizSplitContainer.SplitterDistance = Program.LocalSettings.RightPaneHorizSplitterDistance;
topVerticalSplitContainer.SplitterDistance = Program.LocalSettings.TopPaneVerticalSplitterDistance;
/// Initialize bench control user interface(s)
BenchControlPanel = new BenchControlPanel();
/// Initialize bench control user interface(s)
BenchControlPanel = new BenchControlPanel();
BenchControlPanel.BalancesCount = TBF.Rig.StateMachine.Tank3 != null ? 3
: TBF.Rig.StateMachine.Tank2 != null ? 2
: TBF.Rig.StateMachine.Tank1 != null ? 1
: 0;
new System.ComponentModel.ComponentResourceManager(typeof(MainWnd)).ApplyResources(BenchControlPanel, "benchControlPanel");
BenchControlPanel.Name = "benchControlPanel";
rightHorizSplitContainer.Panel2.Controls.Add(BenchControlPanel);
new System.ComponentModel.ComponentResourceManager(typeof(MainWnd)).ApplyResources(BenchControlPanel, "benchControlPanel");
BenchControlPanel.Name = "benchControlPanel";
rightHorizSplitContainer.Panel2.Controls.Add(BenchControlPanel);
ReloadProcedureComboBoxItems();
ReloadProcedureComboBoxItems();
/// Select the initial tab page
mainTabControl.SelectTab((int)MainTabPageId.Process); /// This is to load the 'Process screen'
mainTabControl.SelectTab((int)MainTabPageId.Calendar); /// This is to load the 'Calendar screen'
UpdateUser();
mainTabControl.SelectTab((int)MainTabPageId.Hydraulics);
mainTabControl.SelectTab((int)MainTabPageId.Hydraulics);
processTabPageCtrl.Settings2UI();
@@ -422,10 +425,10 @@ namespace TBF.UI
string[] edgesLcfg = null;
string[] edgesXLcfg = null;
///
var schDrawingCmpnts = (TBF.DB.CurrentBench.IsRealBench && Rig.StateMachine.Components != null)
var schDrawingCmpnts = (TBF.DB.CurrentBench.IsRealBench && Rig.StateMachine.Components != null)
? Rig.StateMachine.Components
: TBF.Rig.TbfComponents.LoadComponentsFromDB(cmpntEntities);
foreach (var component in schDrawingCmpnts)
{
TBF.Rig.Generic.IComponentCfg cmpCfg = component.Cfg;
@@ -488,11 +491,11 @@ namespace TBF.UI
topVerticalSplitContainer.SplitterDistance = topVerticalSplitContainer.Width / 2;
}
/// <summary>
/// Pass any pressed keys to the Bench control panel.
/// Note that MainWnd.KeyPreview must be set to true.
/// </summary>
private void MainWnd_KeyPress(object sender, KeyPressEventArgs e)
/// <summary>
/// Pass any pressed keys to the Bench control panel.
/// Note that MainWnd.KeyPreview must be set to true.
/// </summary>
private void MainWnd_KeyPress(object sender, KeyPressEventArgs e)
{
#if BADGER_MALA_TRAT || BADGER_STREDNA_TRAT || BADGER_VELKA_TRAT || GENESIS || CEVAK_200 || TURA_SPECIAL || TURA_IPERL || TURA_IPERL_NEW
/// Do nothing = do not process keys
@@ -514,24 +517,24 @@ namespace TBF.UI
/// </summary>
void OnActivity(object sender, UiBridge.ActivityEventArgs args)
{
switch (args.Cmd)
{
case ActivityEventArgs.Update.Activity:
activityLabel.Text = args.Activity;
if (string.IsNullOrEmpty(messageLabel.Text)) messageLabel.ForeColor = Color.Black;
break;
case ActivityEventArgs.Update.Message:
messageLabel.Text = args.Message;
if (args.ErrorMsg) messageLabel.ForeColor = Color.Red;
else messageLabel.ForeColor = Color.Black;
break;
default:
activityLabel.Text = args.Activity;
messageLabel.Text = args.Message;
if (args.ErrorMsg) messageLabel.ForeColor = Color.Red;
else messageLabel.ForeColor = Color.Black;
break;
}
switch (args.Cmd)
{
case ActivityEventArgs.Update.Activity:
activityLabel.Text = args.Activity;
if (string.IsNullOrEmpty(messageLabel.Text)) messageLabel.ForeColor = Color.Black;
break;
case ActivityEventArgs.Update.Message:
messageLabel.Text = args.Message;
if (args.ErrorMsg) messageLabel.ForeColor = Color.Red;
else messageLabel.ForeColor = Color.Black;
break;
default:
activityLabel.Text = args.Activity;
messageLabel.Text = args.Message;
if (args.ErrorMsg) messageLabel.ForeColor = Color.Red;
else messageLabel.ForeColor = Color.Black;
break;
}
}
/// <summary>
@@ -563,7 +566,7 @@ namespace TBF.UI
drawingCtrl.MsrmntAvailableFlags = new bool[args.MsrmntAvailableFlags.Length];
}
for (int i = 0; i < args.MsrmntAvailableFlags.Length; i++) drawingCtrl.MsrmntAvailableFlags[i] = args.MsrmntAvailableFlags[i];
/// Duplicate measured values
if (drawingCtrl.MeasuredValues == null || drawingCtrl.MeasuredValues.Length != args.MeasuredValues.Length)
{
@@ -577,7 +580,7 @@ namespace TBF.UI
drawingCtrl.AltStrings = new string[args.AltStrings.Length];
}
for (int i = 0; i < args.AltStrings.Length; i++) drawingCtrl.AltStrings[i] = args.AltStrings[i];
/// Duplicate setpoints
if (drawingCtrl.Setpoints == null || drawingCtrl.Setpoints.Length != args.Setpoints.Length)
{
@@ -591,7 +594,7 @@ namespace TBF.UI
drawingCtrl.CustomBitmaps = new DrawingShape[args.CustomBitmaps.Length];
}
for (int i = 0; i < args.CustomBitmaps.Length; i++) drawingCtrl.CustomBitmaps[i] = args.CustomBitmaps[i];
drawingCtrl.SupressRedraws = false;
}
catch (Exception e)
@@ -602,10 +605,10 @@ namespace TBF.UI
}
}
void OnTestProgress(object sender, UiBridge.TestProgressEventArgs args)
{
mainProgressBar.Value = (int)(100.499f * args.OveralProgress);
}
void OnTestProgress(object sender, UiBridge.TestProgressEventArgs args)
{
mainProgressBar.Value = (int)(100.499f * args.OveralProgress);
}
void OnProcedureSelected(object sender, UiBridge.ProcedureSelectedEventArgs args)
{
@@ -671,18 +674,18 @@ namespace TBF.UI
public void UpdateUser()
{
userInfoStatusLabel.Text = string.Format("{0}: {1}{2}, ", Strings.User, CurrentUser.UserName(),
(CurrentUser.AuthorizedAs == AuthorizedAs.PowerUser) ? "(S)" :
(CurrentUser.AuthorizedAs == AuthorizedAs.LocalUser) ? "(L)" : "(R)");
userInfoStatusLabel.Text = string.Format("{0}: {1}{2}, ", Strings.User, CurrentUser.UserName(),
(CurrentUser.AuthorizedAs == AuthorizedAs.PowerUser) ? "(S)" :
(CurrentUser.AuthorizedAs == AuthorizedAs.LocalUser) ? "(L)" : "(R)");
UpdateMenuItemsVisibility();
}
void UpdateMenuItemsVisibility()
{
usersTSMenuItem.Visible = CurrentUser.IsMemberOf(GID.Administrators) || CurrentUser.IsMemberOf(GID.HeadOfLab);
databaseSettingsTSMenuItem.Visible = CurrentUser.IsMemberOf(GID.Administrators) && CurrentUser.IsPowerUser();
upgradeTSMenuItem.Visible = CurrentUser.IsMemberOf(GID.Administrators) && CurrentUser.IsPowerUser();
usersTSMenuItem.Visible = CurrentUser.IsMemberOf(GID.Administrators) || CurrentUser.IsMemberOf(GID.HeadOfLab);
databaseSettingsTSMenuItem.Visible = CurrentUser.IsMemberOf(GID.Administrators) && CurrentUser.IsPowerUser();
upgradeTSMenuItem.Visible = CurrentUser.IsMemberOf(GID.Administrators) && CurrentUser.IsPowerUser();
clearCountersToolStripMenuItem.Visible = CurrentUser.IsMemberOf(GID.Administrators) ||
CurrentUser.IsMemberOf(GID.HeadOfLab) ||
CurrentUser.IsMemberOf(GID.TestingSpecialists) ||
@@ -710,14 +713,14 @@ namespace TBF.UI
//Rig.StateMachine.Stop();
}
private void benchComponentsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Components.ComponentsManagerDlg().ShowDialog(); Cursor = Cursors.Default; }
private void benchPathsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Paths.PathsDlg().ShowDialog(); Cursor = Cursors.Default; }
private void benchTransitionsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Transitions.TransitionsDlg().ShowDialog(); Cursor = Cursors.Default; }
private void benchMetrologyTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Metrology.MetrologyDlg().ShowDialog(); Cursor = Cursors.Default; }
private void benchUncertaintyTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Uncertainties.UncertaintiesDlg().ShowDialog(); Cursor = Cursors.Default; }
private void benchTestProfilesTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.TestProfiles.TestProfilesDlg().ShowDialog(); Cursor = Cursors.Default; }
private void editSchDrawingTSMItem_Click(object sender, EventArgs e){ Cursor = Cursors.WaitCursor; new TBF.UI.Bench.EditSchDrawing.EditSchDrawingDlg().ShowDialog();Cursor = Cursors.Default; }
private void proceduresTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Procedures.ProceduresDlg().ShowDialog(); Cursor = Cursors.Default; }
private void benchComponentsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Components.ComponentsManagerDlg().ShowDialog(); Cursor = Cursors.Default; }
private void benchPathsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Paths.PathsDlg().ShowDialog(); Cursor = Cursors.Default; }
private void benchTransitionsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Transitions.TransitionsDlg().ShowDialog(); Cursor = Cursors.Default; }
private void benchMetrologyTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Metrology.MetrologyDlg().ShowDialog(); Cursor = Cursors.Default; }
private void benchUncertaintyTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Uncertainties.UncertaintiesDlg().ShowDialog(); Cursor = Cursors.Default; }
private void benchTestProfilesTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.TestProfiles.TestProfilesDlg().ShowDialog(); Cursor = Cursors.Default; }
private void editSchDrawingTSMItem_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.EditSchDrawing.EditSchDrawingDlg().ShowDialog(); Cursor = Cursors.Default; }
private void proceduresTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Procedures.ProceduresDlg().ShowDialog(); Cursor = Cursors.Default; }
private void usersTSMItem_Click(object s, EventArgs e)
{
@@ -754,15 +757,15 @@ namespace TBF.UI
}
}
}
private void backUpConfigTSMItem_Click(object s, EventArgs e) { BackupConfiguration(); }
private void backUpResultsTSMItem_Click(object s, EventArgs e) { BackupResults(); }
private void passwdTSMItem_Click(object s, EventArgs e) { new SharedDatabase.Forms.PasswordChangeDlg(CurrentUser.UserName()).ShowDialog(); }
private void aboutTSMItem_Click(object s, EventArgs e) { new TBF.UI.Help.AboutDlg().ShowDialog(); }
private void backUpConfigTSMItem_Click(object s, EventArgs e) { BackupConfiguration(); }
private void backUpResultsTSMItem_Click(object s, EventArgs e) { BackupResults(); }
private void passwdTSMItem_Click(object s, EventArgs e) { new SharedDatabase.Forms.PasswordChangeDlg(CurrentUser.UserName()).ShowDialog(); }
private void aboutTSMItem_Click(object s, EventArgs e) { new TBF.UI.Help.AboutDlg().ShowDialog(); }
/// <summary>
/// Read the database and re-initialize procedureComboBox items.
/// Try to preserve the original selection.
/// </summary>
/// <summary>
/// Read the database and re-initialize procedureComboBox items.
/// Try to preserve the original selection.
/// </summary>
public void ReloadProcedureComboBoxItems()
{
int separPos = procedureComboBox.Text.IndexOf(ProcSeparator);
@@ -771,7 +774,7 @@ namespace TBF.UI
}
public void ReloadProcedureComboBoxItems(string procedureNameToSelect)
{
{
if (!procedureComboBox.Enabled)
{
/// Test cycle in progress, reload combo box items when the session is finished
@@ -915,7 +918,7 @@ namespace TBF.UI
if (SelectedProcedure != null) BenchControlPanel.ReloadTests();
}
}
}
/// <summary>
/// To each unresolved procedure finds the first native procedure that matches teh unresolved procedure
@@ -977,8 +980,8 @@ namespace TBF.UI
return true;
}
private void procedureComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
private void procedureComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (var item in procedureComboBox.Items)
{
var procInfo = item as ProcedureInfo;
@@ -1004,7 +1007,7 @@ namespace TBF.UI
}
}
}
}
}
private void procedureComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
@@ -1162,39 +1165,56 @@ namespace TBF.UI
private void appDiagnosticMenuItem_Click(object sender, EventArgs e)
{
/*diagApi = new DiagApi(liveLogCache);
//diagApi.AddLog("ahoj, toto je prvy log");
ILog loger = LogManager.GetLogger("logCache");
log.Debug("ahoj, ideme");*/
LiveLogCache.Instance.AddLog("=== Live diagnostic entry ===");
DiagApi liveDiagApi = new DiagApi();
/*try
try
{
// Predpoklad�me, �e ApplicationDiagnostic.exe je v rovnakom adres�ri ako hlavn� aplik�cia
string exePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppDiagnostic.exe");
string exePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppDiagnostic", "AppDiagnostic.exe");
if (File.Exists(exePath))
if (!File.Exists(exePath))
{
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = exePath,
UseShellExecute = true // Spust� aplik�ciu ako samostatn� proces
};
System.Diagnostics.Process.Start(startInfo);
MessageBox.Show($"AppDiagnostic.exe not found:\n{exePath}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
MessageBox.Show("ApplicationDiagnostic.exe not found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
FileName = exePath,
WorkingDirectory = Path.GetDirectoryName(exePath),
UseShellExecute = true
});
// Temporary diagnostic test.
SendDiagnosticTestLogs();
}
catch (Exception ex)
{
MessageBox.Show($"Failed to start ApplicationDiagnostic: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}*/
MessageBox.Show($"Failed to start AppDiagnostic or send test logs: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void SendDiagnosticTestLogs()
{
NLog.Logger deviceLogger = NLog.LogManager.GetLogger("TBF.TestBench.DeviceSimulation");
deviceLogger.Trace("TRACE: Communication cycle started.");
deviceLogger.Debug("DEBUG: Device configuration loaded.");
deviceLogger.Info("INFO: Test bench started.");
deviceLogger.Warn("WARN: Simulated pressure is approaching the limit.");
for (int position = 1; position <= 10; position++)
{
deviceLogger.Debug($"Reading simulated device at position {position}.");
}
try
{
throw new InvalidOperationException("Simulated device communication failure.");
}
catch (Exception ex)
{
deviceLogger.Error(ex, "ERROR: Unable to communicate with simulated device.");
}
deviceLogger.Fatal("FATAL: Simulated emergency stop.");
}
private void optoHeadsToolStripMenuItem_Click(object sender, EventArgs e)
@@ -1246,7 +1266,7 @@ namespace TBF.UI
MessageBox.Show(Strings.Remote_database_cannot_be_exported, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (MessageBox.Show(Strings.Do_you_want_to_back_up_configuration_qm,
string.Empty,
MessageBoxButtons.YesNo,
+38
View File
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
internalLogLevel="Trace"
internalLogFile="${basedir}/nlog-internal.log"
throwConfigExceptions="true">
<extensions>
<add assembly="Xylem.Common.Utils.Logging" />
<add assembly="AppDiagnostic.Logging" />
</extensions>
<targets>
<target name="uiTrace"
xsi:type="UiTarget"
layout="${time}|${level:uppercase=true:padding=-5}|${message}" />
<target name="appDiagnostic"
xsi:type="AppDiagnostic"
pipeName="Sensus.AppDiagnostic.LogPipe"
queueLimit="10000"
reconnectDelayMilliseconds="500"
connectTimeoutMilliseconds="250"
layout="${message}" />
<target name="logfile"
xsi:type="File"
fileName="${basedir}/GenesisCordonelInterfaceLogger.log"
layout="${longdate}|${level:uppercase=true:padding=-5}|${logger}|${message}|${exception:format=tostring}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="appDiagnostic" />
<logger name="GenesisCordonelInterface*" minlevel="Trace" writeTo="uiTrace" />
<logger name="GenesisCordonelInterface*" minlevel="Trace" writeTo="logfile" />
</rules>
</nlog>
+14 -1
View File
@@ -1,9 +1,13 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
internalLogLevel="Trace"
internalLogFile="${basedir}/nlog-internal.log"
throwConfigExceptions="true">
<extensions>
<add assembly="Xylem.Common.Utils.Logging" />
<add assembly="AppDiagnostic.Logging" />
</extensions>
<targets>
@@ -11,6 +15,14 @@
xsi:type="UiTarget"
layout="${time}|${level:uppercase=true:padding=-5}|${message}" />
<target name="appDiagnostic"
xsi:type="AppDiagnostic"
pipeName="Sensus.AppDiagnostic.LogPipe"
queueLimit="10000"
reconnectDelayMilliseconds="500"
connectTimeoutMilliseconds="250"
layout="${message}" />
<target name="logfile"
xsi:type="File"
fileName="${basedir}/GenesisCordonelInterfaceLogger.log"
@@ -18,6 +30,7 @@
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="appDiagnostic" />
<logger name="GenesisCordonelInterface*" minlevel="Trace" writeTo="uiTrace" />
<logger name="GenesisCordonelInterface*" minlevel="Trace" writeTo="logfile" />
</rules>