tbf/UniControlBoardTest/Program.cs

183 lines
7.7 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;
using log4net;
namespace UniControlBoardTest
{
static class Program
{
/// Constants
public const string ConfigFName = "config.xml";
public const string BackupConfigFName = "config.backup.xml";
public const string Log4NetConfigFName = "log4netConfig.xml";
/// Program information
public static readonly string ProcessName;
public static readonly string Version; /// version string
public static readonly DateTime BuildDateTime; /// date and time of program build
public static readonly string ExeDirectory;
public static readonly string ConfigDirectory;
public static readonly string LogDirectory;
public static readonly string LocalSettingsFileName;
public static readonly string LocalSettingsBackupName;
/// Local settings
public static LocalSettings LocalSettings;
/// log4net
static ILog log;
static Program()
{
/// Program version string
Assembly thisAssembly = Assembly.GetExecutingAssembly();
ProcessName = Path.GetFileNameWithoutExtension(thisAssembly.Location);
Version ver = thisAssembly.GetName().Version;
Version = string.Format("{0}.{1}.{2}", ver.Major, ver.Minor, ver.Build);
BuildDateTime = new FileInfo(thisAssembly.Location).LastWriteTime;
/// Local program configuration directory including the trailing backslash
ExeDirectory = Path.GetDirectoryName(thisAssembly.Location);
ConfigDirectory = Path.Combine(ExeDirectory, "..", "Cfg");
LogDirectory = Path.Combine(ExeDirectory, "..", "Logs");
LocalSettingsFileName = Path.Combine(ConfigDirectory, ConfigFName);
LocalSettingsBackupName = Path.Combine(ConfigDirectory, BackupConfigFName);
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
/// Check if another instance is running
if (System.Diagnostics.Process.GetProcessesByName(ProcessName).Length > 1)
{
MessageBox.Show(string.Format("Another instance of {0} is already running", ProcessName));
return;
}
bool configDirectoryCreated = false;
if (!Directory.Exists(ConfigDirectory))
{
MessageBox.Show("Program is running for the 1st time on this PC\r\nDefault settings are used",
"Warning",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
///
/// Create a new config subdirectory
///
configDirectoryCreated = true;
Directory.CreateDirectory(ConfigDirectory);
Program.LocalSettings = new LocalSettings(true);
Program.LocalSettings.Save();
if (File.Exists(Path.Combine(ExeDirectory, "SampleConfig", Log4NetConfigFName)))
{
File.Copy(Path.Combine(ExeDirectory, "SampleConfig", Log4NetConfigFName),
Path.Combine(ConfigDirectory, Log4NetConfigFName));
}
File.SetAttributes(Path.Combine(ConfigDirectory, Log4NetConfigFName), FileAttributes.Normal);
}
///
/// Configue and start logging
///
log4net.Config.XmlConfigurator.Configure(new FileInfo(Path.Combine(ConfigDirectory, Log4NetConfigFName)));
log = LogManager.GetLogger(typeof(Program));
log.Fatal("--------------------------------------------------------------------------------");
log.FatalFormat("{0} ver.{1}", ProcessName, Version);
log.FatalFormat("Executable directory is {0}", ExeDirectory);
if (configDirectoryCreated)
{
log.Fatal("A new config directory and configuration files created !");
}
///
/// Load the local settings (logging not available yet)
///
LocalSettings = LocalSettings.Load(Path.Combine(ConfigDirectory, ConfigFName));
if (LocalSettings == null)
{
/// Loading local seetings from regular config file failed. Use the backup
LocalSettings = LocalSettings.Load(Path.Combine(ConfigDirectory, BackupConfigFName));
if (LocalSettings == null)
{
log.FatalFormat("Local settings: Could not load file {0}, nor {1}.", ConfigFName, BackupConfigFName);
log.Fatal("Application terminated.");
MessageBox.Show(string.Format("Could not load file {0}, nor {1}.", ConfigFName, BackupConfigFName), "Fatal error");
return; /// Fatal error
}
else
{
LocalSettings.Save(); /// Save the settings to overwrite the wrong file
log.FatalFormat("Local settings: Could not load file {0}, successfully loaded {1}", ConfigFName, BackupConfigFName);
}
}
else
{
/// Loading local seetings from the regular config file was successful. Update the backup
File.Copy(Path.Combine(ConfigDirectory, ConfigFName), Path.Combine(ConfigDirectory, BackupConfigFName), true);
}
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new UniCBTestDlg());
}
catch (Exception e)
{
LogException(log, "Exception in Application.Run(new UniCBTestDlg())", e);
MessageBox.Show("Program crashed:" +
Environment.NewLine + Environment.NewLine + e.Message +
((e.InnerException == null) ? string.Empty : (Environment.NewLine + e.InnerException.Message)) +
Environment.NewLine + e.StackTrace,
"Fatal error",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = args.ExceptionObject as Exception;
if (e == null) return;
LogException(log, "Unhandled exception", e);
MessageBox.Show("Program crashed:" +
Environment.NewLine + Environment.NewLine + e.Message +
((e.InnerException == null) ? string.Empty : (Environment.NewLine + e.InnerException.Message)) +
Environment.NewLine + e.StackTrace,
"Fatal error",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
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("--------------------------------------");
}
}
}