tbf/LabelPrinting/Program.cs

252 lines
10 KiB
C#
Raw Normal View History

///
/// Copyright (c) 2021-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using log4net;
using NHibernate;
using Common;
using SharedDatabase;
using SharedDatabase.Entities;
using LabelPrinting.Resources;
namespace LabelPrinting
{
static class Program
{
/// Constants
public static GID[] SettingsAccessLevel = new GID[] { GID.TraceabilityManagement }; /// Group membership to access settings
public const string ProgramName = "LabelPrinting";
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 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();
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
///
Assembly thisAssembly = Assembly.GetExecutingAssembly();
string processName = Path.GetFileNameWithoutExtension(thisAssembly.Location);
if (System.Diagnostics.Process.GetProcessesByName(processName).Length > 1)
{
MessageBox.Show(string.Format("{0}{1}{2}", string.Format(Strings.Program_0_is_running_already, ProgramName),
Environment.NewLine,
Strings.Close_it_please),
Strings.Error,
MessageBoxButtons.OK,
MessageBoxIcon.Asterisk);
return;
}
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
bool configDirectoryCreated = false;
if (!Directory.Exists(ConfigDirectory) || new DirectoryInfo(ConfigDirectory).GetFileSystemInfos().Length == 0)
{
MessageBox.Show(string.Format("{0}{1}{2}", Strings.Program_is_running_for_the_1st_time_on_this_PC,
Environment.NewLine,
Strings.Default_settings_are_used),
Strings.Warning,
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
///
/// Create a new config subdirectory
///
Directory.CreateDirectory(ConfigDirectory);
configDirectoryCreated = true;
LocalSettings = new LocalSettings(true);
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}", ProgramName, Version);
log.FatalFormat("Executable directory is {0}", ExeDirectory);
if (configDirectoryCreated)
{
log.Fatal("A new config directory and configuration files created !");
}
///
/// Load the local settings
///
LocalSettings = LocalSettings.Load(LocalSettingsFileName);
if (LocalSettings == null)
{
/// Loading local seetings from regular config file failed. Use the backup
LocalSettings = LocalSettings.Load(LocalSettingsBackupName);
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(LocalSettingsFileName, LocalSettingsBackupName, true);
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
///
/// User login
///
if (LocalSettings.IsUserLoginRequired && !string.IsNullOrEmpty(LocalSettings.UsersDBConnString))
{
try
{
UsersDB.ConnectionString = LocalSettings.UsersDBConnString;
UsersDB.DbType = DBType.MySql;
DialogResult dr = new SharedDatabase.Forms.LoginDlg().ShowDialog();
if (dr != DialogResult.OK) return;
}
catch (Exception exc)
{
log.ErrorFormat("Failed to connect to database of users: {0}", exc.Message);
}
}
IList<OrderInfo> orderInfos = null;
while (LocalSettings.Mode == Mode.WithDatabase)
{
try
{
ISession session = TracingDB.CreateSession(LocalSettings.TracingDBConnString);
orderInfos = session.QueryOver<OrderInfo>().List();
break;
}
catch (Exception exc)
{
log.FatalFormat("Failed to connect to production tracing database: {0}", exc.Message);
if (exc.InnerException != null)
{
log.FatalFormat("InnerException: {0}", exc.InnerException.Message);
}
MessageBox.Show(string.Format("Failed to connect to production tracing database:{0}{1}", Environment.NewLine, exc.Message));
if (new SettingsDlg(LocalSettings).ShowDialog() == DialogResult.OK)
{
LocalSettings.Save();
}
else
{
return;
}
}
}
try
{
MainWnd dlg = new MainWnd(orderInfos);
Application.Run(dlg);
}
catch (Exception e)
{
LogException(log, "Exception in Application.Run(MainWnd)", 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("--------------------------------------");
}
}
}