tbf/TestBenchFramework/Program.cs

260 lines
10 KiB
C#
Raw Normal View History

using System;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;
using log4net;
using TBF.Resources;
using TBF.Forms;
using TBF.ErrorHandler;
using NHibernate;
namespace TBF
{
public class Program
{
public const string AdminUsername = "admin";
public const string AdminPassword = "staratura";
public const string HomeDir = "C:\\Tbf\\"; /// Contains subdirectories Results, Logs, Images, ...
/// log4net
static readonly ILog log = LogManager.GetLogger(typeof(Program));
const string log4netConfigFName = "log4netConfig.xml";
/// Local settings
public static LocalSettings LocalSettings = new LocalSettings();
public const string LocalSettingsFileName = "config.xml";
/// Database related: This object reference is set after a successful user login
public static DatabaseSettings CurrentBench;
const string SQLiteDbFName = "SQLite.db";
#if (DN100 || MUNICH)
public const int WMsCount = 3;
#elif FUZHOU300
public const int WMsCount = 6;
#else // if FUZHOU150
public const int WMsCount = 6;
#endif
/// <summary>
/// Selected procedure data
/// - before the main program window is open, objects referenced by this variable
/// are loaded from the database.
/// - user interface displays data stored in objects referenced by this variable.
/// When user modifies procedure settings and confirms changes (choses to save them),
/// data referenced by this variable are updated and written to the database.
/// - when users starts a test procedure, state machine creates its own copy
/// of procedure data and uses them for the test. Changes of 'SelectedProcedure'
/// done during the test do not have any influence on the currently running test.
/// </summary>
public static Entities.Procedure SelectedProcedure = null;
/// <summary>
/// Main window object.
/// </summary>
public static MainWnd MainWnd;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
log.Fatal("--------------------------------------------------------------------------------");
/// Local program configuration directory including the trailing backslash
string locAppDataDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) +
Path.DirectorySeparatorChar + "TestBenchFramework" + Path.DirectorySeparatorChar;
/// Check whether local application data directory exists.
/// If not, create it and copy the initial configuration to this directory.
/// This is done only once after a clean program installation on the first program start-up
try
{
if (!Directory.Exists(locAppDataDir))
{
Directory.CreateDirectory(locAppDataDir);
Environment.CurrentDirectory = locAppDataDir;
string sampleConfig = Application.StartupPath + Path.DirectorySeparatorChar + "SampleConfig" + Path.DirectorySeparatorChar;
if (File.Exists(sampleConfig + LocalSettingsFileName)) { File.Copy(sampleConfig + LocalSettingsFileName, LocalSettingsFileName); }
if (File.Exists(sampleConfig + log4netConfigFName)) { File.Copy(sampleConfig + log4netConfigFName, log4netConfigFName); }
if (File.Exists(sampleConfig + SQLiteDbFName)) { File.Copy(sampleConfig + SQLiteDbFName, SQLiteDbFName); }
File.SetAttributes(LocalSettingsFileName, FileAttributes.Normal);
File.SetAttributes(log4netConfigFName, FileAttributes.Normal);
File.SetAttributes(SQLiteDbFName, FileAttributes.Normal);
}
else
{
Environment.CurrentDirectory = locAppDataDir;
}
}
catch (Exception e)
{
log.Error("A problem when creating the local application data directory and preparing the initial configuration", e);
return;
}
/// Configue and start logging
log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(locAppDataDir + log4netConfigFName));
log.Info("Entering application.");
/// Load the local settings
if (Program.LocalSettings == null) return; /// Fatal error
LocalSettings.Load();
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(LocalSettings.Language);
/// This belongs to Application.Run(new MainWnd()) ...
/// and should be executed before opening 'loginDlg'
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
/// Ensure that there is at least one bench in the configuration
while (Program.LocalSettings.testBenches.GetLength(0) == 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
2015-02-19 14:50:31 +00:00
if ((new Forms.NoBenchOrDatabaseDlg { Message = Strings.NoBenchMsg }.ShowDialog() != DialogResult.OK) ||
(new LoginDlg(true).ShowDialog() == DialogResult.Cancel) ||
(new BenchesDlg().ShowDialog() == DialogResult.Cancel))
{
return; /// Exit program
}
log.Warn("Loading the local settings again.");
LocalSettings.Load();
}
/// User login
bool retryLogin = true; /// true = stay in a login loop
do {
2015-02-19 14:50:31 +00:00
LoginDlgWithBenchSelection loginDlgBench;
if (LocalSettings.LastBenchName != null)
{
2015-02-19 14:50:31 +00:00
loginDlgBench = new LoginDlgWithBenchSelection(LocalSettings.LastBenchName);
}
else
{
2015-02-19 14:50:31 +00:00
loginDlgBench = new LoginDlgWithBenchSelection();
}
2015-02-19 14:50:31 +00:00
DialogResult dr = loginDlgBench.ShowDialog();
if (dr == DialogResult.Cancel)
{
return; /// Login canceled --> Exit application
}
else
{
2015-02-19 14:50:31 +00:00
for (int i = 0; i < LocalSettings.BenchesCount; i++)
{
2015-02-19 14:50:31 +00:00
if (LocalSettings.TestBenches[i].BenchName == loginDlgBench.BenchName)
{
Entities.User loadedUser = null;
try
{
bool authorized = false;
2015-02-19 14:50:31 +00:00
if (Entities.User.IsPowerUser(loginDlgBench.User, loginDlgBench.Password))
{
loadedUser = new Entities.User(loginDlgBench.User);
authorized = loadedUser.Authorize(loginDlgBench.User, loginDlgBench.Password);
}
if (!authorized)
{
2015-02-19 14:50:31 +00:00
/// Load user from the UsersAndGroupsDB database
loadedUser = Entities.User.LoadUserByName(loginDlgBench.User,
LocalSettings.TestBenches[i].UsersDBSettings);
if (loadedUser != null)
{
authorized = loadedUser.Authorize(loginDlgBench.User, loginDlgBench.Password);
}
}
if (authorized)
{
log.InfoFormat("Password accepted, bench '{0}' parameters loaded.", LocalSettings.TestBenches[i].BenchName);
/// Copy the selected bench settings to CurrentBench.
/// Clone() guarantees that current bench settings wont be modified
/// when user modifies the database settings in DatabaseSettingsDlg.
CurrentBench = (DatabaseSettings)LocalSettings.TestBenches[i].Clone();
/// Save the selection to local settings
LocalSettings.LastBenchName = CurrentBench.BenchName;
retryLogin = false;
break;
}
if (retryLogin)
{
/// Close Fluent NHibernate
MessageBox.Show(Strings.Invalid_user_password_or_bench, Strings.Error, MessageBoxButtons.OK);
}
}
catch (Exception)
{
/// Database connect failed, ask what to do
switch ((new Forms.NoBenchOrDatabaseDlg { Message = Strings.NoDatabaseMsg, ShowRetry = true }).ShowDialog())
{
case DialogResult.Abort: return; /// Exit program
case DialogResult.Retry: break; /// Retry the loop
default:
/// Open 'DatabaseSetingsDlg' and retry DB connect on OK
2015-02-19 14:50:31 +00:00
if (new LoginDlg(true).ShowDialog() == DialogResult.Cancel ||
new BenchesDlg().ShowDialog() == DialogResult.Cancel)
{
return; /// Exit program
}
LocalSettings.Load();
break; /// Retry the loop
}
}
} // if benchname is OK
} // for all benches in local settings loop
} // not Canceled
} //do
while (retryLogin);
///
/// Load the last procedure or create a new, default one
///
if (LocalSettings.LastProcedureName != null)
{
IList<Entities.Procedure> listOfProcedures = FluentCommon.CreateSession(Database.Procedures)
.CreateQuery("FROM Procedure WHERE Name = :procName")
.SetParameter("procName", LocalSettings.LastProcedureName)
.List<Entities.Procedure>();
if (listOfProcedures.Count == 1)
{
log.InfoFormat("Pre-selecting the procedure {0}", LocalSettings.LastProcedureName);
SelectedProcedure = listOfProcedures[0];
}
}
/// Open the main application window
log.Info("Creating the main window");
MainWnd = new MainWnd();
log.Info("Opening the main window");
Application.Run(MainWnd);
/// Save local settings
log.Info("The main window was closed, saving the local parameters");
LocalSettings.Save();
/// Close Fluent NHibernate
/// Todo
log.Info("Exiting application.");
}
}
}