diff --git a/Common/DBSettings.cs b/Common/DBSettings.cs
index 3a8a7d8c9..8e5313f53 100644
--- a/Common/DBSettings.cs
+++ b/Common/DBSettings.cs
@@ -12,6 +12,7 @@ namespace Common
{
public DBType DbType;
public string ConnectionString;
+ public bool IsValid { get { return (DbType != DBType.None) && !string.IsNullOrEmpty(ConnectionString); } }
public DBSettings()
{
diff --git a/Common/DatabaseSettings.cs b/Common/DatabaseSettings.cs
index ac40b30f2..5a2336ab6 100644
--- a/Common/DatabaseSettings.cs
+++ b/Common/DatabaseSettings.cs
@@ -15,10 +15,10 @@ namespace Common
// Public fields
public string BenchName;
public bool IsRealBench;
- public DBSettings ProceduresDBSettings; /// Configuration database settings
+ public DBSettings ProceduresDBSettings; /// Configuration database settings
public DBSettings WaterMetersDBSettings; /// Results database settings
- public DBSettings EventsDBSettings; /// Events database settings
- public DBSettings UsersDBSettings; /// Shared configuration database settings
+ public DBSettings EventsDBSettings; /// Events database settings
+ public DBSettings UsersDBSettings; /// Shared configuration database settings
// Constructor
public DatabaseSettings()
diff --git a/Common/Enums.cs b/Common/Enums.cs
index 218e00588..a8baac98f 100644
--- a/Common/Enums.cs
+++ b/Common/Enums.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2013-2022 Sensus Slovensko a.s.
+/// Copyright (c) 2013-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -49,15 +49,6 @@ namespace Common
Count
}
- /// Identifies the database based on the content
- public enum DBKind
- {
- Config,
- Results,
- RemoteConfig,
- Count
- }
-
public enum ProcedureSelection
{
#if LANG_CS
diff --git a/Config/FluentCommon.cs b/Config/FluentCommon.cs
index 91f3ec906..028e5a5f0 100644
--- a/Config/FluentCommon.cs
+++ b/Config/FluentCommon.cs
@@ -1,148 +1,10 @@
///
/// Copyright (c) 2013-2018 Sensus Slovensko a.s.
///
-using System;
-using System.Windows.Forms;
-using FluentNHibernate.Cfg;
-using FluentNHibernate.Cfg.Db;
-using NHibernate;
-using NHibernate.Cfg;
-using NHibernate.Tool.hbm2ddl;
-using Config.Resources;
namespace Config
{
public static class FluentCommon
{
- ///
- /// NHibernate session factory (to create the database session 'SessionFactory')
- ///
- /// A database session
- public static ISessionFactory CreateSessionFactory(Common.DBKind database, Common.DBType dbType, string connectionString, bool createDB)
- {
- try
- {
- FluentConfiguration cfg = Fluently.Configure();
-
- switch (dbType)
- {
- default:
- case Common.DBType.MySql:
- cfg = cfg.Database(MySQLConfiguration.Standard.ConnectionString(connectionString));
- break;
- case Common.DBType.SQLite:
- cfg = cfg.Database(SQLiteConfiguration.Standard.UsingFile(connectionString));
- break;
- }
-
- switch (database)
- {
- default:
- case Common.DBKind.Config:
- case Common.DBKind.RemoteConfig:
- cfg = cfg.Mappings(m => m.FluentMappings.AddFromAssemblyOf());
- break;
- case Common.DBKind.Results:
- cfg = cfg.Mappings(m => m.FluentMappings.AddFromAssemblyOf());
- break;
- }
-
- if (createDB)
- {
- return cfg.ExposeConfiguration(BuildSchemaCreate).BuildSessionFactory();
- }
- else
- {
- return cfg.ExposeConfiguration(BuildSchema).BuildSessionFactory();
- }
- }
- catch (Exception exc)
- {
- MessageBox.Show(string.Format(Strings.Cannot_open_DB_Cause_0, exc.Message),
- Strings.Error,
- MessageBoxButtons.OK,
- MessageBoxIcon.Error);
- return null;
- }
- }
-
- public delegate void BuildSchemaDlgt(Configuration config);
-
- static void BuildSchema(Configuration config)
- {
- /// This NHibernate tool takes a configuration (with mapping info in)
- /// and exports a database schema from it
- new SchemaExport(config).SetOutputFile("db_schema");
- }
-
- static void BuildSchemaCreate(Configuration config)
- {
- /// This NHibernate tool takes a configuration (with mapping info in)
- /// and exports a database schema from it
- new SchemaExport(config).Create(true, true);
- }
-
- ///
- /// Create an empty users database.
- /// Database contains only the user 'admin' and the control board component 'CB'.
- ///
- /// DBType.SQLite or DBType.MySql
- /// Connection string
- /// true=success, false=error
- public static bool CreateEmptyConfigDB(Common.DBType dbType, string connectionString)
- {
- ISessionFactory sessionFactory = CreateSessionFactory(Common.DBKind.Config, dbType, connectionString, true);
- if (sessionFactory == null) return false;
-
- /// Populate the database
- using (var session = sessionFactory.OpenSession())
- {
- using (var transaction = session.BeginTransaction())
- {
- ///
- /// Create user 'admin'
- ///
- var admin = new Config.Entities.User
- {
- UserName = Data.AdminUsername,
- FullName = Strings.Administrator,
- LastPwChange = DateTime.Now
- };
- admin.SetPassword(Data.AdminPassword);
-
- ///
- /// Prepare all groups, add some of them to admin
- ///
- for (Common.GID gid = 0; gid < Common.GID.NrOfGroups; gid++)
- {
- Config.Entities.Group group = new Config.Entities.Group(gid);
- switch (gid)
- {
- case Common.GID.Testers:
- case Common.GID.TestingSpecialists:
- case Common.GID.HeadOfLab:
- case Common.GID.MaintenanceSpecialists:
- case Common.GID.Metrologists:
- case Common.GID.CalibrationSpecialists:
- case Common.GID.Administrators:
-#if TURA_IPERL || TURA_IPERL_NEW || TURA_SPECIAL
- case Common.GID.TraceabilityManagement:
-#elif KEMPNO_50 || KRAKOW_50 || TORUN_50 || WARSAW_50 || WARSAW_END
- case Common.GID.MetrologicalAuthority:
- case Common.GID.WaterMeterAuthority:
-#endif
- admin.AddGroup(group);
- session.SaveOrUpdate(group); /// Save this group
- break;
- }
- }
-
- session.SaveOrUpdate(admin); /// Save user 'admin'
- transaction.Commit();
- }
- }
-
- return true;
- }
}
}
diff --git a/EventViewer/EventViewerWnd.cs b/EventViewer/EventViewerWnd.cs
index 6c33ec5fa..a3718384d 100644
--- a/EventViewer/EventViewerWnd.cs
+++ b/EventViewer/EventViewerWnd.cs
@@ -277,7 +277,7 @@ namespace EventViewer
private void settingsButton_Click(object sender, EventArgs e)
{
//Common.GID[] groupsWithAccess = new Common.GID[] { Common.GID.Administrators };
- Users.Forms.LoginDlg dlg = new Users.Forms.LoginDlg(true);
+ Users.Forms.LoginDlg dlg = new Users.Forms.LoginDlg();
if (dlg.ShowDialog() == DialogResult.OK)
{
if ((new Forms.SettingsDlg()).ShowDialog() == DialogResult.OK)
diff --git a/Results/DB.cs b/Results/DB.cs
index 52efe0856..0066f18ce 100644
--- a/Results/DB.cs
+++ b/Results/DB.cs
@@ -180,29 +180,55 @@ namespace Results
/// Loads shared data from the database
///
/// Throws NHibernate exceptions
- public static void LoadSharedData()
+ public static void LoadSharedData(ISession session = null)
{
- ISession session = DB.CreateSession();
+ bool openAndCloseSession = (session == null);
- TestDataList = session.QueryOver().List();
- ComponentsList = session.QueryOver().List();
- WaterMeterDataList = session.QueryOver().List();
- }
+ try
+ {
+ if (openAndCloseSession) session = Results.DB.CreateSession();
+ TestDataList = session.QueryOver().List();
+ ComponentsList = session.QueryOver().List();
+ WaterMeterDataList = session.QueryOver().List();
+ }
+ catch (Exception e)
+ {
+ log.ErrorFormat("Cannot open results DB: {0}", e.Message);
+ }
+ finally
+ {
+ if (openAndCloseSession && session != null && session.IsOpen) session.Close();
+ }
+ }
///
/// Loads shared data from the database
///
/// Throws NHibernate exceptions
- public static int GetMaxSavedBatchNr()
+ public static int GetMaxSavedBatchNr(ISession session = null)
{
- ISession session = DB.CreateSession();
- IList batches = session.QueryOver().List();
+ bool openAndCloseSession = (session == null);
+ int maxBatchNr = 0;
+
+ try
+ {
+ if (openAndCloseSession) session = Results.DB.CreateSession();
+ IList batches = session.QueryOver().List();
+
+ foreach (var b in batches)
+ {
+ if (b.BatchNr > maxBatchNr) maxBatchNr = b.BatchNr;
+ }
+ }
+ catch (Exception e)
+ {
+ log.ErrorFormat("Cannot open results DB: {0}", e.Message);
+ }
+ finally
+ {
+ if (openAndCloseSession && session != null && session.IsOpen) session.Close();
+ }
- int maxBatchNr = 0;
- foreach (var b in batches)
- {
- if (b.BatchNr > maxBatchNr) maxBatchNr = b.BatchNr;
- }
return maxBatchNr;
}
diff --git a/TBF/DB.cs b/TBF/DB.cs
index 290562d0d..bd92e1095 100644
--- a/TBF/DB.cs
+++ b/TBF/DB.cs
@@ -1,11 +1,16 @@
///
-/// Copyright (c) 2021 Sensus Slovensko a.s.
+/// Copyright (c) 2021-2023 Sensus Slovensko a.s.
///
using System;
+using System.Windows.Forms;
using NHibernate;
+using NHibernate.Cfg;
+using NHibernate.Tool.hbm2ddl;
+using FluentNHibernate.Cfg;
+using FluentNHibernate.Cfg.Db;
using Common;
-using Config;
-using Users.Entities;
+using Events;
+using TBF.Resources;
namespace TBF
{
@@ -16,52 +21,188 @@ namespace TBF
///
public static DatabaseSettings CurrentBench;
- ///
- /// Session factories for regular sessions.
- ///
- public static ISessionFactory[] SessionFactories = new ISessionFactory[(int)DBKind.Count];
+ public static ISessionFactory ConfigDBSessionFactory = null; /// Configuration DB session factory (always != null)
+ public static ISessionFactory SharedDBSessionFactory = null; /// Shared configuration DB session factory or null
+ public static ISessionFactory ResultsDBSessionFactory = null; /// Results DB session factory (always != null)
+ public static ISessionFactory EventsDBSessionFactory = null; /// Events DB session factory or null
- /// Create a NHibernate session for the given database
- public static ISession CreateSession(DBKind database)
+ public static ISessionFactory LocalUsersDBSessionFactory = null; /// Local users DB session factory (always != null)
+ public static ISessionFactory SharedUsersDBSessionFactory = null; /// Shared users DB session factory or null
+
+ public static ISessionFactory[] UserSessionFactories
{
- if (database < 0 || database >= DBKind.Count) return null;
-
- int ix = (int)database;
- if (SessionFactories[ix] == null)
+ get
{
- SessionFactories[ix] = CreateSessionFactory(database);
+ return (SharedUsersDBSessionFactory != null)
+ ? new ISessionFactory[] { SharedUsersDBSessionFactory, LocalUsersDBSessionFactory }
+ : new ISessionFactory[] { LocalUsersDBSessionFactory };
+ }
+ }
+
+ ///
+ /// Create all database session factories
+ ///
+ public static void CreateSessionFactories(DatabaseSettings dbSettings)
+ {
+ /// Configuration database (local, always non-null)
+ if (dbSettings.ProceduresDBSettings != null && dbSettings.ProceduresDBSettings.IsValid)
+ {
+ ConfigDBSessionFactory =
+ CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf(),
+ dbSettings.ProceduresDBSettings.DbType,
+ dbSettings.ProceduresDBSettings.ConnectionString);
+
+ LocalUsersDBSessionFactory =
+ CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf(),
+ dbSettings.ProceduresDBSettings.DbType,
+ dbSettings.ProceduresDBSettings.ConnectionString);
}
- return SessionFactories[ix].OpenSession();
+ /// Shared configuration database (remote)
+ if (dbSettings.UsersDBSettings != null && dbSettings.UsersDBSettings.IsValid)
+ {
+ SharedDBSessionFactory =
+ CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf(),
+ dbSettings.UsersDBSettings.DbType,
+ dbSettings.UsersDBSettings.ConnectionString);
+
+ SharedUsersDBSessionFactory =
+ CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf(),
+ dbSettings.UsersDBSettings.DbType,
+ dbSettings.UsersDBSettings.ConnectionString);
+ }
+
+ /// Results database (local, always non-null)
+ if (dbSettings.WaterMetersDBSettings != null && dbSettings.WaterMetersDBSettings.IsValid)
+ {
+ Results.DB.SessionFactory = ResultsDBSessionFactory =
+ CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf(),
+ dbSettings.WaterMetersDBSettings.DbType,
+ dbSettings.WaterMetersDBSettings.ConnectionString);
+ }
+
+ /// Events database (remote or local)
+ if (dbSettings.EventsDBSettings != null && dbSettings.EventsDBSettings.IsValid)
+ {
+ EventsDBSessionFactory =
+ CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf(),
+ dbSettings.EventsDBSettings.DbType,
+ dbSettings.EventsDBSettings.ConnectionString);
+ }
}
///
/// NHibernate session factory (to create the database session 'SessionFactory')
///
/// A database session
- static ISessionFactory CreateSessionFactory(DBKind database)
+ public static ISessionFactory CreateSessionFactory(Action mappings, Common.DBType dbType,
+ string connectionString, bool createDB = false)
{
- DBType dbType;
- string connectionString;
-
- switch (database)
+ try
{
- default:
- case DBKind.Config:
- dbType = CurrentBench.ProceduresDBSettings.DbType;
- connectionString = CurrentBench.ProceduresDBSettings.ConnectionString;
- break;
- case DBKind.Results:
- dbType = CurrentBench.WaterMetersDBSettings.DbType;
- connectionString = CurrentBench.WaterMetersDBSettings.ConnectionString;
- break;
- case DBKind.RemoteConfig:
- dbType = CurrentBench.UsersDBSettings.DbType;
- connectionString = CurrentBench.UsersDBSettings.ConnectionString;
- break;
+ FluentConfiguration cfg;
+
+ switch (dbType)
+ {
+ default:
+ case Common.DBType.MySql:
+ cfg = Fluently.Configure().Database(MySQLConfiguration.Standard.ConnectionString(connectionString));
+ break;
+ case Common.DBType.SQLite:
+ cfg = Fluently.Configure().Database(SQLiteConfiguration.Standard.UsingFile(connectionString));
+ break;
+ }
+
+ var action = createDB ? (System.Action)BuildSchemaCreate : (System.Action)BuildSchema;
+
+ return cfg.Mappings(mappings).ExposeConfiguration(action).BuildSessionFactory();
+ }
+ catch (Exception exc)
+ {
+ MessageBox.Show(string.Format("{0}: {1}", Strings.Cannot_connect_to_the_database, exc.Message),
+ Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
+ return null;
+ }
+ }
+
+ static void BuildSchema(Configuration config)
+ {
+ /// This NHibernate tool takes a configuration (with mapping info in)
+ /// and exports a database schema from it
+ new SchemaExport(config).SetOutputFile("db_schema");
+ }
+
+ static void BuildSchemaCreate(Configuration config)
+ {
+ /// This NHibernate tool takes a configuration (with mapping info in)
+ /// and exports a database schema from it
+ new SchemaExport(config).Create(true, true);
+ }
+
+ ///
+ /// Create an empty users database.
+ /// Database contains only the user 'admin' and the control board component 'CB'.
+ ///
+ /// DBType.SQLite or DBType.MySql
+ /// Connection string
+ /// true=success, false=error
+ public static bool CreateEmptyConfigDB(Common.DBType dbType, string connectionString)
+ {
+ ISessionFactory sessionFactory =
+ CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf(),
+ dbType, connectionString, true);
+
+ if (sessionFactory == null) return false;
+
+ /// Populate the database
+ using (var session = sessionFactory.OpenSession())
+ {
+ using (var transaction = session.BeginTransaction())
+ {
+ ///
+ /// Create user 'admin'
+ ///
+ var admin = new Config.Entities.User
+ {
+ UserName = Config.Data.AdminUsername,
+ FullName = Strings.Administrator,
+ LastPwChange = DateTime.Now
+ };
+ admin.SetPassword(Config.Data.AdminPassword);
+
+ ///
+ /// Prepare all groups, add some of them to admin
+ ///
+ for (Common.GID gid = 0; gid < Common.GID.NrOfGroups; gid++)
+ {
+ Config.Entities.Group group = new Config.Entities.Group(gid);
+ switch (gid)
+ {
+ case Common.GID.Testers:
+ case Common.GID.TestingSpecialists:
+ case Common.GID.HeadOfLab:
+ case Common.GID.MaintenanceSpecialists:
+ case Common.GID.Metrologists:
+ case Common.GID.CalibrationSpecialists:
+ case Common.GID.Administrators:
+#if TURA_IPERL || TURA_IPERL_NEW || TURA_SPECIAL
+ case Common.GID.TraceabilityManagement:
+#elif KEMPNO_50 || KRAKOW_50 || TORUN_50 || WARSAW_50 || WARSAW_END
+ case Common.GID.MetrologicalAuthority:
+ case Common.GID.WaterMeterAuthority:
+#endif
+ admin.AddGroup(group);
+ session.SaveOrUpdate(group); /// Save this group
+ break;
+ }
+ }
+
+ session.SaveOrUpdate(admin); /// Save user 'admin'
+ transaction.Commit();
+ }
}
- return Config.FluentCommon.CreateSessionFactory(database, dbType, connectionString, false);
+ return true;
}
}
}
diff --git a/TBF/Program.cs b/TBF/Program.cs
index fb0c53f0e..75b77b087 100644
--- a/TBF/Program.cs
+++ b/TBF/Program.cs
@@ -1,19 +1,19 @@
///
-/// Copyright (c) 2013-2022 Sensus Slovensko a.s.
+/// Copyright (c) 2013-2023 Sensus Slovensko a.s.
///
using System;
using System.IO;
using System.Collections.Generic;
+using System.Drawing;
using System.Windows.Forms;
using log4net;
+using NHibernate;
using Common;
using Config.Entities;
using Users;
-using Users.Entities;
using TBF.Resources;
using TBF.Rig.Sequences;
using TBF.UI.Shared;
-using NHibernate;
namespace TBF
{
@@ -214,7 +214,7 @@ namespace TBF
/// Ask what to do, ask for the password, open 'DatabaseSetingsDlg' and continue on OK
if ((new NoBenchOrDatabaseDlg { Message = Strings.NoBenchMsg }.ShowDialog() != DialogResult.OK) ||
- (new Users.Forms.LoginDlg(true).ShowDialog() == DialogResult.Cancel) ||
+ (new Users.Forms.LoginDlg().ShowDialog() == DialogResult.Cancel) ||
(new TBF.UI.Settings.BenchesDlg().ShowDialog() == DialogResult.Cancel))
{
return; /// Exit program
@@ -229,6 +229,8 @@ namespace TBF
bool retryLogin = true; /// true = stay in a login loop
do
{
+ LoadingConfigEnd();
+
LoginDlgWithBenchSelection loginDlgBench;
if (LocalSettings.LastBenchName != null)
{
@@ -251,10 +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);
- Users.CurrentUser.RemoteUsersDB = LocalSettings.TestBenches[i].UsersDBSettings;
- Users.CurrentUser.LocalUsersDB = LocalSettings.TestBenches[i].ProceduresDBSettings;
+ LoadingConfigStart();
+ TBF.DB.CurrentBench = LocalSettings.TestBenches[i].Clone() as DatabaseSettings;
+ TBF.DB.CreateSessionFactories(LocalSettings.TestBenches[i]);
Users.Entities.User loadedUser = null;
try
@@ -270,11 +273,10 @@ namespace TBF
if (Users.Entities.User.IsPowerUser(loginDlgBench.Alias, loginDlgBench.Password))
{
loadedUser = new Users.Entities.User(loginDlgBench.Alias, 6, true);
- authorized = loadedUser.Authorize(loginDlgBench.Alias, loginDlgBench.Password, reqGrpMembership, null);
- if (authorized)
- {
- Users.CurrentUser.AuthorizedAs = Common.AuthorizedAs.PowerUser;
- }
+ CurrentUser.Change(loadedUser, null);
+ CurrentUser.LastAuthorization = DateTime.Now;
+ CurrentUser.AuthorizedAs = Common.AuthorizedAs.PowerUser;
+ authorized = true;
}
///
@@ -282,42 +284,57 @@ namespace TBF
///
if (!authorized)
{
- DBSettings[] dbs = new DBSettings[] { Users.CurrentUser.RemoteUsersDB, Users.CurrentUser.LocalUsersDB };
-
authorizedAs = Common.AuthorizedAs.RemoteUser; /// Try remote DB first
- foreach (var db in dbs)
+ foreach (var sf in TBF.DB.UserSessionFactories)
{
/// Load and authorise user from the UsersDB database
try
{
- if (loginDlgBench.Password == LoginDlgWithBenchSelection.UseTheTagPassword)
+
+ if (sf != null)
{
- loadedUser = Users.Entities.User.LoadUserByTag(loginDlgBench.Alias, db);
- if (loadedUser != null) authorized = loadedUser.AuthorizeTag(loginDlgBench.Alias, reqGrpMembership, null);
- }
- else
- {
- switch (loginDlgBench.Method)
+ var session = sf.OpenSession();
+
+ if (loginDlgBench.Password == LoginDlgWithBenchSelection.UseTheTagPassword)
{
- default:
- case Common.LoginMethod.UserName:
- loadedUser = Users.Entities.User.LoadUserByName(loginDlgBench.Alias, db);
- if (loadedUser != null) authorized = loadedUser.Authorize(loginDlgBench.Alias, loginDlgBench.Password, reqGrpMembership, null);
- break;
- case Common.LoginMethod.FullName:
- loadedUser = Users.Entities.User.LoadUserByFullName(loginDlgBench.Alias, db);
- if (loadedUser != null) authorized = loadedUser.AuthorizeFullName(loginDlgBench.Alias, loginDlgBench.Password, reqGrpMembership, null);
- break;
- case Common.LoginMethod.Number:
- int number;
- if (!int.TryParse(loginDlgBench.Alias, out number)) break;
- loadedUser = Users.Entities.User.LoadUserByNumber(number, db);
- if (loadedUser != null) authorized = loadedUser.AuthorizeNumber(number, loginDlgBench.Password, reqGrpMembership, null);
- break;
+ loadedUser = Users.Entities.User.LoadUserByTag(session, loginDlgBench.Alias);
+ if (loadedUser != null) authorized = loadedUser.AuthorizeTag(loginDlgBench.Alias, reqGrpMembership, null);
}
+ else
+ {
+ switch (loginDlgBench.Method)
+ {
+ default:
+ case Common.LoginMethod.UserName:
+ loadedUser = Users.Entities.User.LoadUserByName(session, loginDlgBench.Alias);
+ if (loadedUser != null)
+ {
+ authorized = loadedUser.Authorize(session, loginDlgBench.Alias, loginDlgBench.Password, reqGrpMembership, null);
+ }
+ break;
+ case Common.LoginMethod.FullName:
+ loadedUser = Users.Entities.User.LoadUserByFullName(session, loginDlgBench.Alias);
+ if (loadedUser != null)
+ {
+ authorized = loadedUser.AuthorizeFullName(session, loginDlgBench.Alias, loginDlgBench.Password, reqGrpMembership, null);
+ }
+ break;
+ case Common.LoginMethod.Number:
+ int number;
+ if (!int.TryParse(loginDlgBench.Alias, out number)) break;
+ loadedUser = Users.Entities.User.LoadUserByNumber(session, number);
+ if (loadedUser != null)
+ {
+ authorized = loadedUser.AuthorizeNumber(session, number, loginDlgBench.Password, reqGrpMembership, null);
+ }
+ break;
+ }
+ }
+
+ session.Close();
}
- }
+ }
catch
{
authorized = false;
@@ -353,7 +370,11 @@ namespace TBF
/// Copy the selected bench settings to CurrentBench.
/// Clone() guarantees that current bench settings wont be modified
/// when user modifies the database settings in DatabaseSettingsDlg.
- TBF.DB.CurrentBench = (DatabaseSettings)LocalSettings.TestBenches[i].Clone();
+ if (TBF.DB.CurrentBench == null)
+ {
+ TBF.DB.CurrentBench = LocalSettings.TestBenches[i].Clone() as DatabaseSettings;
+ TBF.DB.CreateSessionFactories(TBF.DB.CurrentBench);
+ }
Results.DB.DbType = TBF.DB.CurrentBench.WaterMetersDBSettings.DbType;
Results.DB.ConnectionString = TBF.DB.CurrentBench.WaterMetersDBSettings.ConnectionString;
@@ -364,7 +385,7 @@ namespace TBF
/// Connect to Config database.
/// This triggers an exception in case user is a power user and there is no Config database.
///
- ISession session = TBF.DB.CreateSession(DBKind.Config);
+ var session = TBF.DB.ConfigDBSessionFactory.OpenSession();
if (!string.IsNullOrEmpty(LocalSettings.LastProcedureName))
{
@@ -380,9 +401,9 @@ namespace TBF
.List();
if (components.Count > 0)
{
- var factory = new TBF.Rig.DataContainers.BenchInfo.Extended.ComponentFactory();
+ var factory = new TBF.Rig.DataContainers.BenchInfo.Extended.ComponentFactory();
var cfg = factory.CmpntCfgFromCmpntEntity(components[0])
- as TBF.Rig.DataContainers.BenchInfo.Extended.ComponentCfg;
+ as TBF.Rig.DataContainers.BenchInfo.Extended.ComponentCfg;
ProcessData.BenchInfo = new TBF.Rig.DataContainers.BenchInfo.Extended.Component(cfg);
}
else
@@ -393,20 +414,20 @@ namespace TBF
.List();
if (components.Count > 0)
{
- var factory = new TBF.Rig.DataContainers.BenchInfo.iPerl.ComponentFactory();
+ var factory = new TBF.Rig.DataContainers.BenchInfo.iPerl.ComponentFactory();
var cfg = factory.CmpntCfgFromCmpntEntity(components[0])
- as TBF.Rig.DataContainers.BenchInfo.iPerl.ComponentCfg;
+ as TBF.Rig.DataContainers.BenchInfo.iPerl.ComponentCfg;
ProcessData.BenchInfo = new TBF.Rig.DataContainers.BenchInfo.iPerl.Component(cfg);
}
}
-
session.Close();
///
/// Connect to Results database and determine the last saved batch number.
///
- Results.DB.LoadSharedData();
- int maxBatchNr = Results.DB.GetMaxSavedBatchNr();
+ var rsltDBSession = TBF.DB.ResultsDBSessionFactory.OpenSession();
+ Results.DB.LoadSharedData(rsltDBSession);
+ int maxBatchNr = Results.DB.GetMaxSavedBatchNr(rsltDBSession);
if (!TBF.DB.CurrentBench.IsRealBench || Program.LocalSettings.BatchNr <= maxBatchNr)
{
log.FatalFormat("Max. BatchNr in DB = {0}, LocalSettings.BatchNr = {1}", maxBatchNr, Program.LocalSettings.BatchNr);
@@ -414,16 +435,16 @@ namespace TBF
Program.LocalSettings.Save();
log.FatalFormat("LocalSettings.BatchNr updated to {0}", Program.LocalSettings.BatchNr);
}
+ if (rsltDBSession != null && rsltDBSession.IsOpen) rsltDBSession.Close();
///
/// Connect to Events database (if any) and load recent events from this test bench.
///
- if (TBF.DB.CurrentBench.EventsDBSettings.DbType != Common.DBType.None &&
- !string.IsNullOrEmpty(TBF.DB.CurrentBench.EventsDBSettings.ConnectionString))
+ if (TBF.DB.EventsDBSessionFactory != null)
{
- Events.DB.DbType = (DBType)TBF.DB.CurrentBench.EventsDBSettings.DbType;
- Events.DB.ConnectionString = TBF.DB.CurrentBench.EventsDBSettings.ConnectionString;
- Events.DB.LoadRecentEvents(Events.DB.CreateSession(), loginDlgBench.BenchName, 7); /// Last 7 days
+ var evntsDBsession = TBF.DB.EventsDBSessionFactory.OpenSession();
+ Events.DB.LoadRecentEvents(evntsDBsession, loginDlgBench.BenchName, 7); /// Last 7 days
+ evntsDBsession.Close();
}
retryLogin = false;
@@ -460,7 +481,7 @@ namespace TBF
default:
/// Open 'DatabaseSetingsDlg' and retry DB connect on OK
- if (new Users.Forms.LoginDlg(true).ShowDialog() == DialogResult.Cancel ||
+ if (new Users.Forms.LoginDlg().ShowDialog() == DialogResult.Cancel ||
new TBF.UI.Settings.BenchesDlg().ShowDialog() == DialogResult.Cancel)
{
return; /// Exit program
@@ -482,26 +503,31 @@ namespace TBF
///
if (LocalSettings.LastProcedureName != null)
{
- IList listOfProcedures = TBF.DB.CreateSession(Common.DBKind.Config)
- .QueryOver()
- .Where(x => (x.ProcedureState == Common.ProcedureState.Active))
- .And(x => (x.Name == LocalSettings.LastProcedureName))
- .List();
-
- if (listOfProcedures.Count == 1)
+ using (var session = TBF.DB.ConfigDBSessionFactory.OpenSession())
{
- log.InfoFormat("Pre-selecting the procedure {0}", LocalSettings.LastProcedureName);
- SelectedProcedure = listOfProcedures[0];
+ var listOfProcedures = session.QueryOver()
+ .Where(x => (x.ProcedureState == Common.ProcedureState.Active))
+ .And(x => (x.Name == LocalSettings.LastProcedureName))
+ .List();
+
+ if (listOfProcedures.Count == 1)
+ {
+ log.InfoFormat("Pre-selecting the procedure {0}", LocalSettings.LastProcedureName);
+ SelectedProcedure = listOfProcedures[0];
+ }
+
+ session.Close();
}
}
try
- {
- /// Open the main application window
+ {
+ /// Open the main application window
log.Info("Creating the main window");
MainWnd = new UI.MainWnd();
log.Info("Opening the main window");
- Application.Run(MainWnd);
+ LoadingConfigEnd();
+ Application.Run(MainWnd);
log.Info("The main window was closed");
}
catch (Exception e)
@@ -536,5 +562,35 @@ namespace TBF
log.FatalFormat("StackTrace : {0}{1}", Environment.NewLine, e.StackTrace);
log.Fatal("--------------------------------------");
}
- }
-}
\ No newline at end of file
+
+
+ static UI.Shared.ModelessActivityForm form;
+ static System.Threading.Thread formThread;
+
+ static void LoadingConfigStart()
+ {
+ form = new UI.Shared.ModelessActivityForm()
+ {
+ Message = Strings.Starting_system,
+ FontFamily = "Arial",
+ FontSize = 24,
+ FontStyle = FontStyle.Regular,
+ BackgroundColor = Color.LightBlue,
+ };
+ formThread = new System.Threading.Thread(() => form.ShowDialog());
+ formThread.Start();
+ System.Threading.Thread.Sleep(500);
+ }
+
+ static void LoadingConfigEnd()
+ {
+ if (form != null && formThread != null)
+ {
+ form.CloseForm(null, new EventArgs());
+ formThread.Join();
+ }
+ form = null;
+ formThread = null;
+ }
+ }
+}
diff --git a/TBF/Resources/Strings.Designer.cs b/TBF/Resources/Strings.Designer.cs
index 060eb17be..37ef02b75 100644
--- a/TBF/Resources/Strings.Designer.cs
+++ b/TBF/Resources/Strings.Designer.cs
@@ -1896,6 +1896,15 @@ namespace TBF.Resources {
}
}
+ ///
+ /// Looks up a localized string similar to Error reading configuration database.
+ ///
+ internal static string Error_reading_configuration_database {
+ get {
+ return ResourceManager.GetString("Error_reading_configuration_database", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Error saving parameters of {0}.
///
@@ -5442,6 +5451,15 @@ namespace TBF.Resources {
}
}
+ ///
+ /// Looks up a localized string similar to .
+ ///
+ internal static string String1 {
+ get {
+ return ResourceManager.GetString("String1", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Sun.
///
diff --git a/TBF/Resources/Strings.resx b/TBF/Resources/Strings.resx
index 8bcef85a0..87f311117 100644
--- a/TBF/Resources/Strings.resx
+++ b/TBF/Resources/Strings.resx
@@ -2323,4 +2323,7 @@
Printer selection
+
+ Error reading configuration database
+
\ No newline at end of file
diff --git a/TBF/Rig/Elde/CoverTest/CoverTestForm.cs b/TBF/Rig/Elde/CoverTest/CoverTestForm.cs
index c1fc888ea..3fd38ccb9 100644
--- a/TBF/Rig/Elde/CoverTest/CoverTestForm.cs
+++ b/TBF/Rig/Elde/CoverTest/CoverTestForm.cs
@@ -56,7 +56,7 @@ namespace TBF.Rig.Elde.CoverTest
{
if (!Users.CurrentUser.IsMemberOf(bypassLevel))
{
- if ((new Users.Forms.LoginDlg(bypassLevel, this)).ShowDialog() != DialogResult.OK)
+ if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, bypassLevel, this)).ShowDialog() != DialogResult.OK)
{
return;
}
diff --git a/TBF/Rig/Output/DB/SaveDiverterCorrections/SaveDiverterCorr.cs b/TBF/Rig/Output/DB/SaveDiverterCorrections/SaveDiverterCorr.cs
index 87df2028a..a90d88020 100644
--- a/TBF/Rig/Output/DB/SaveDiverterCorrections/SaveDiverterCorr.cs
+++ b/TBF/Rig/Output/DB/SaveDiverterCorrections/SaveDiverterCorr.cs
@@ -200,7 +200,7 @@ namespace TBF.Rig.Output.DB.SaveDiverterCorrections
ITransaction transaction = null;
try
{
- ISession session = TBF.DB.CreateSession(Common.DBKind.Config);
+ var session = TBF.DB.ConfigDBSessionFactory.OpenSession();
transaction = session.BeginTransaction();
for (int div = 1; div <= myCfg.DivertersCount(); div++)
diff --git a/TBF/Rig/Output/DB/SaveFlowmeterCorrections/SaveFlowmeterCorr.cs b/TBF/Rig/Output/DB/SaveFlowmeterCorrections/SaveFlowmeterCorr.cs
index b6d8b68f9..7d9657d41 100644
--- a/TBF/Rig/Output/DB/SaveFlowmeterCorrections/SaveFlowmeterCorr.cs
+++ b/TBF/Rig/Output/DB/SaveFlowmeterCorrections/SaveFlowmeterCorr.cs
@@ -207,7 +207,7 @@ namespace TBF.Rig.Output.DB.SaveFlowmeterCorrections
ITransaction transaction = null;
try
{
- ISession session = TBF.DB.CreateSession(Common.DBKind.Config);
+ var session = TBF.DB.ConfigDBSessionFactory.OpenSession();
transaction = session.BeginTransaction();
for (int fmtr = 1; fmtr <= myCfg.FlowmetersCount(); fmtr++)
diff --git a/TBF/Rig/Sequences/MainSeq.cs b/TBF/Rig/Sequences/MainSeq.cs
index b6e8ef83a..baa424e96 100644
--- a/TBF/Rig/Sequences/MainSeq.cs
+++ b/TBF/Rig/Sequences/MainSeq.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2013-2022 Sensus Slovensko a.s.
+/// Copyright (c) 2013-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -278,10 +278,7 @@ namespace TBF.Rig.Sequences
try
{
- using (ISession localSession = TBF.DB.CreateSession(DBKind.Config))
- {
- StateMachine.LoadPathsAndTransitions(localSession);
- }
+ StateMachine.LoadPathsAndTransitions();
///
/// Try to load all parameters of selected or restored procedure from the respective database
@@ -291,14 +288,13 @@ namespace TBF.Rig.Sequences
/// User has chosen to restore an interrupted session and necessary conditions are met
/// TODO: Repeate twice for DBKind.Config and DBKind.RemoteConfig
- using (ISession remoteOrLocalSession = TBF.DB.CreateSession(isRemoteIntProc ?
- DBKind.RemoteConfig :
- DBKind.Config))
+ using (var session =
+ (isRemoteIntProc ? TBF.DB.SharedDBSessionFactory : TBF.DB.ConfigDBSessionFactory).OpenSession())
{
- StateMachine.LoadProcedure(remoteOrLocalSession, interruptedProcedureName, isRemoteIntProc);
+ StateMachine.LoadProcedure(session, interruptedProcedureName, isRemoteIntProc);
StateMachine.LoadProcedureParams(StateMachine.Procedure);
- /// This is to load Procedure.Tests and test.MoreParams for each test
+ /// This is to enforce the loading of Procedure.Tests and test.MoreParams for each test
int a = 0;
foreach (var test in StateMachine.Procedure.Tests) a += test.MoreParams.Count;
}
@@ -320,75 +316,31 @@ namespace TBF.Rig.Sequences
}
}
- /// TODO: Repeate twice for DBKind.Config and DBKind.RemoteConfig
- using (ISession remoteOrLocalSession = TBF.DB.CreateSession(Bridge.SelectedProcedure.IsRemote ?
- DBKind.RemoteConfig :
- DBKind.Config))
+ /// TODO: Repeate twice for SharedDBSessionFactory and ConfigDBSessionFactory
+ using (var session =
+ (Bridge.SelectedProcedure.IsRemote ? TBF.DB.SharedDBSessionFactory : TBF.DB.ConfigDBSessionFactory).OpenSession())
{
- StateMachine.LoadProcedure(remoteOrLocalSession, Bridge.SelectedProcedure.Name, Bridge.SelectedProcedure.IsRemote, testsInside);
+ StateMachine.LoadProcedure(session, Bridge.SelectedProcedure.Name, Bridge.SelectedProcedure.IsRemote, testsInside);
StateMachine.LoadProcedureParams(StateMachine.Procedure);
+ log.WarnFormat("{0} procedure '{1}' selected", Bridge.SelectedProcedure.IsRemote ? "Remote" : "Local", Bridge.SelectedProcedure.Name);
- /// This is to load Procedure.Tests and test.MoreParams for each test
+ /// This is to enforce the loading of Procedure.Tests and test.MoreParams for each test
int a = 0;
- foreach (var test in StateMachine.Procedure.Tests) a += test.MoreParams.Count;
-
-#if false
- /// Debugging SensusTestInfo.GetBestMatch()
-
- if (selection == Selection.Cycle && OracleDB != null && OracleDB.ProductionDB != null)
+ foreach (var test in StateMachine.Procedure.Tests)
{
- try
+ a += test.MoreParams.Count;
+#if ORACLE_DB
+ if (test.OraId != 0 || test.OraIdRepetMulti != 0 || test.RawDataId != 0 || test.RawDataIdRepetMulti != 0)
{
- OracleDB.ProductionDB.Open();
-
- int wmTypeId = 170;
-
- /// Prepare procedure signature
- IList wmTestNames = new List();
- StringBuilder procedureSignatureSB = new StringBuilder();
- foreach (var tr in BatchRslts.Batch.RegularTestRslts())
- {
- if (tr.Evaluate())
- {
- wmTestNames.Add(tr.Name());
- procedureSignatureSB.Append(tr.Name());
- procedureSignatureSB.Append("~");
- }
- }
-
- int wmTypeRev = 0;
- string wzTypStr;
- string metroKlasse;
- string zulasszeichen;
- string materialNr;
- double q3 = 0;
- DateTime timeStamp;
- string remark;
- IList ti = OracleDB.GetOracleTestInfo(OracleDB.ProductionDB, wmTypeId,
- out wmTypeRev, out wzTypStr, out metroKlasse, out zulasszeichen, out materialNr, out q3, out timeStamp, out remark);
-
- if (ti != null)
- {
- /// All 5 updated together
- string procedureSignature = procedureSignatureSB.ToString();
- var completeTestInfo = Results.Output.SensusTestInfo.GetBestMatch(ti, wmTestNames);
-
- foreach (var cti in completeTestInfo)
- {
- log.WarnFormat("Selected test info : ID={0} Rev={1} Test={2} PrfNrDB={3} QBzDB={4} PrfNrOpto={5} QBzOpto={6} PrfNrLog={7} QBzLog={8} Range={9}",
- wmTypeId, wmTypeRev, cti.TestName, cti.PruefungsNrDB, cti.QBezeichnungDB, cti.PruefungsNrOpto,
- cti.QBezeichnungOpto, cti.PruefungsNrLog, cti.QBezeichnungLog, cti.Range);
- }
- }
-
- OracleDB.ProductionDB.Close();
+ log.WarnFormat(" {0} OraId = {1}+{2}*(repNr-1) RawDataId = {3}+{4}*(repNr-1)",
+ test.Name, test.OraId, test.OraIdRepetMulti, test.RawDataId, test.RawDataIdRepetMulti);
}
- catch (Exception exc)
+ else
+#endif
{
- string msg = exc.Message;
+ log.WarnFormat(" {0}", test.Name);
}
}
-#endif
}
}
else
@@ -509,8 +461,10 @@ namespace TBF.Rig.Sequences
b.EndTime = DateTime.MinValue; /// Disable the batch end time estimate
Batch sampleBatch = null;
- using (ISession rsltsDB = Results.DB.CreateSession())
+ ISession rsltsDB = null;
+ try
{
+ rsltsDB = TBF.DB.ResultsDBSessionFactory.OpenSession();
var bts = rsltsDB.QueryOver()
.OrderBy(x => x.BatchNr).Desc
.Where(x => x.ProcedureName == StateMachine.Procedure.Name)
@@ -559,6 +513,14 @@ namespace TBF.Rig.Sequences
}
}
}
+ catch (Exception exc)
+ {
+ log.ErrorFormat("Reloading result from DB failed: {0}", exc.Message);
+ }
+ finally
+ {
+ if (rsltsDB != null && rsltsDB.IsOpen) rsltsDB.Close();
+ }
}
@@ -1577,7 +1539,9 @@ namespace TBF.Rig.Sequences
return true;
}
- var loginDlg = new Users.Forms.PlainLoginDlg(new GID[] { GID.CalibrationSpecialists }, "Approval by legalizator");
+ var loginDlg = new Users.Forms.PlainLoginDlg(TBF.DB.UserSessionFactories,
+ new GID[] { GID.CalibrationSpecialists },
+ "Approval by legalizator");
if (loginDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
isApprovedByLegalizator = true;
diff --git a/TBF/Rig/StateMachine.cs b/TBF/Rig/StateMachine.cs
index 517f7c06c..c4a92346d 100644
--- a/TBF/Rig/StateMachine.cs
+++ b/TBF/Rig/StateMachine.cs
@@ -212,9 +212,11 @@ namespace TBF.Rig
public static void InitializeBoardEtc(ControlComponent_Torino2015.UserControl1 ctrlBrdComponent)
#endif
{
+ var session = TBF.DB.ConfigDBSessionFactory.OpenSession();
+
/// Load the list of components (entities) from the database.
/// Then create the components (derived from IComponent).
- components = Rig.TbfComponents.LoadComponentsFromDB(TBF.DB.CreateSession(Common.DBKind.Config));
+ components = Rig.TbfComponents.LoadComponentsFromDB(session);
MasterValves = GenericDevices.ValveBase.MasterValves(components);
CoupledValves = GenericDevices.ValveBase.CoupledValves(components);
ExtendedValves = GenericDevices.ValveBase.ExtendedValves(components);
@@ -297,6 +299,8 @@ namespace TBF.Rig
if ((eldeValve != null) && eldeValve.Inverted) valvesToInvert |= eldeValve.Mask;
}
+ session.Close();
+
/// Pre-initialize the control board (= buffer the arguments ctrlBrdComponent, tankCapacities)
if (ControlBoard != null)
{
@@ -426,37 +430,42 @@ namespace TBF.Rig
/// true when DB-s are compatible
public static bool IsRemoteDBCompatible(out string message)
{
- IList remoteFeedingPaths;
- IList remoteBenchPaths;
- IList remoteOutputPaths;
- IList remoteMetersPaths;
- IList remoteTransitions;
+ IList remoteFeedingPaths = new List();
+ IList remoteBenchPaths = new List();
+ IList remoteOutputPaths = new List();
+ IList remoteMetersPaths = new List();
+ IList remoteTransitions = new List();
try
{
- ISession remoteSession = TBF.DB.CreateSession(Common.DBKind.RemoteConfig);
+ var remoteSession = TBF.DB.SharedDBSessionFactory.OpenSession();
+
remoteFeedingPaths = remoteSession.QueryOver().List();
remoteBenchPaths = remoteSession.QueryOver().List();
remoteOutputPaths = remoteSession.QueryOver().List();
remoteMetersPaths = remoteSession.QueryOver().List();
remoteTransitions = remoteSession.QueryOver().List();
+
+ remoteSession.Close();
}
catch (Exception exc)
{
-
message = (exc.InnerException != null)
? string.Format("\r\nException:\r\n{0}\r\nInner exception:\r\n{1}", exc.Message, exc.InnerException.Message)
: string.Format("\r\nException:\r\n{0}", exc.Message);
return false;
}
- ISession localSession = TBF.DB.CreateSession(Common.DBKind.Config);
+ var localSession = TBF.DB.ConfigDBSessionFactory.OpenSession();
+
var localFeedingPaths = localSession.QueryOver().List();
var localBenchPaths = localSession.QueryOver().List();
var localOutputPaths = localSession.QueryOver().List();
var localMetersPaths = localSession.QueryOver().List();
var localTransitions = localSession.QueryOver().List();
+ localSession.Close();
+
string subMsg;
if (!IsCompatible(localFeedingPaths, remoteFeedingPaths, out subMsg))
{
@@ -558,17 +567,37 @@ namespace TBF.Rig
/// Loads all paths and transitions from the DB.
/// Updates StatMachine.feedingPaths ... StatMachine.meterPaths, StatMachine.TransitionSequences
///
- public static void LoadPathsAndTransitions(ISession session)
+ public static void LoadPathsAndTransitions(ISession session = null)
{
- feedingPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
- benchPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
- outputPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
- metersPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
- TransitionSequences = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
- TransitionSteps = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
+ bool openAndCloseSession = (session == null);
+ try
+ {
+ if (openAndCloseSession) session = TBF.DB.ConfigDBSessionFactory.OpenSession();
+
+ feedingPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
+ benchPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
+ outputPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
+ metersPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
+ TransitionSequences = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
+ TransitionSteps = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
#if HEAT_METERS
- heatMetersPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
+ heatMetersPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
#endif
+ session.Flush();
+ }
+ catch (Exception e)
+ {
+ feedingPaths = new List();
+ benchPaths = new List();
+ outputPaths = new List();
+ metersPaths = new List();
+ TransitionSequences = new List();
+ TransitionSteps = new List();
+ }
+ finally
+ {
+ if (openAndCloseSession && (session != null) && session.IsOpen) session.Close();
+ }
}
///
@@ -579,15 +608,16 @@ namespace TBF.Rig
{
Procedure = null;
- IList selectedProcs = session.QueryOver()
- .Where(x => (x.ProcedureState == Common.ProcedureState.Active))
- .And(x => (x.Name == procedureName))
- .List();
- if (selectedProcs.Count == 1)
+ var selectedProcedure = session.QueryOver()
+ .Where(x => (x.ProcedureState == Common.ProcedureState.Active))
+ .And(x => (x.Name == procedureName))
+ .List();
+
+ if (selectedProcedure.Count == 1)
{
IsRemoteProcedure = isRemote;
- Procedure = selectedProcs[0];
- TestInstances = selectedProcs[0].UpdateTestInstances(LoopStartNames, LoopEndNames, autoTests);
+ Procedure = selectedProcedure[0];
+ TestInstances = selectedProcedure[0].UpdateTestInstances(LoopStartNames, LoopEndNames, autoTests);
return true;
}
else
diff --git a/TBF/Rig/TbfComponents.cs b/TBF/Rig/TbfComponents.cs
index fde12b39f..f6ed1a036 100644
--- a/TBF/Rig/TbfComponents.cs
+++ b/TBF/Rig/TbfComponents.cs
@@ -247,6 +247,8 @@ namespace TBF.Rig
{
CurrentlyLoadedComponentName = string.Empty;
+ if (session == null) return new List(); /// Handle case when session == null
+
/// Load the list of components from the database
var cmptnEntities = session.QueryOver()
.OrderBy(x => x.ItemNr).Asc
@@ -263,6 +265,15 @@ namespace TBF.Rig
IComponent cmpnt = cmpntFactory.GetComponent(cmpntFactory.CmpntCfgFromCmpntEntity(entity), components);
+ ///
+ /// Enforce loading Corrections and Uncertainties from the database
+ ///
+ double dummy = 0;
+ cmpnt.Corrections = entity.Corrections;
+ foreach (var corr in cmpnt.Corrections) dummy += corr.Correction;
+ cmpnt.Uncertainties = entity.Uncertainties;
+ foreach (var unc in cmpnt.Uncertainties) dummy += unc.MainUncertainty;
+
///
/// Inherit DebugMode from the parent (if any)
///
diff --git a/TBF/Rig/TestMethods/Endurance/CycleDlg.cs b/TBF/Rig/TestMethods/Endurance/CycleDlg.cs
index cae3283a9..fc096e8bd 100644
--- a/TBF/Rig/TestMethods/Endurance/CycleDlg.cs
+++ b/TBF/Rig/TestMethods/Endurance/CycleDlg.cs
@@ -64,19 +64,22 @@ namespace TBF.Rig.TestMethods.Endurance
seqStepsCtrl = new CycleStepsCtrl() as ITabWithListViewEx;
/// Prepare a list of valves for the endurance test
- TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(TBF.DB.CreateSession(Common.DBKind.Config));
- Valves = new List();
- for (int bitNr = 0; bitNr < 8; bitNr++)
- {
- foreach (var vlv in TbfComponents)
- {
- if (vlv is Rig.Elde.Valve.Valve && (vlv as Rig.Elde.Valve.Valve).BitPosition == bitNr)
- {
- Valves.Add(vlv as IValve);
- break;
- }
- }
- }
+ using (var session = TBF.DB.ConfigDBSessionFactory.OpenSession())
+ {
+ TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(session);
+ Valves = new List();
+ for (int bitNr = 0; bitNr < 8; bitNr++)
+ {
+ foreach (var vlv in TbfComponents)
+ {
+ if (vlv is Rig.Elde.Valve.Valve && (vlv as Rig.Elde.Valve.Valve).BitPosition == bitNr)
+ {
+ Valves.Add(vlv as IValve);
+ break;
+ }
+ }
+ }
+ }
EnduranceCycle = (cycle != null) ? cycle : new List(); /// TODO: Load from component parameters
diff --git a/TBF/Rig/TestMethods/Q2CorrectionFromHistory/FromHistorySeq.cs b/TBF/Rig/TestMethods/Q2CorrectionFromHistory/FromHistorySeq.cs
index 4aa049973..8f9714044 100644
--- a/TBF/Rig/TestMethods/Q2CorrectionFromHistory/FromHistorySeq.cs
+++ b/TBF/Rig/TestMethods/Q2CorrectionFromHistory/FromHistorySeq.cs
@@ -112,65 +112,65 @@ namespace TBF.Rig.TestMethods.Q2CorrectionFromHistory
/// Invalidate any previous Q2 Pre-Corrections
IsQ2PreCorrectionCalculated = false;
+ ISession session = null;
try
{
- using (ISession session = Results.DB.CreateSession())
+ session = TBF.DB.ResultsDBSessionFactory.OpenSession();
+
+ Batch btc = null;
+ var batches = session.QueryOver(() => btc)
+ .Where(bb => (bb.ProcedureName == cfg.ProcedureName))
+ .List();
+
+ if (!string.IsNullOrEmpty(cfg.ProcedureNameAlt1))
{
- Batch btc = null;
- var batches = session.QueryOver(() => btc)
- .Where(bb => (bb.ProcedureName == cfg.ProcedureName))
- .List();
+ IList batches2 = session.QueryOver(() => btc)
+ .Where(bb => (bb.ProcedureName == cfg.ProcedureNameAlt1))
+ .List();
+ foreach (var b in batches2) batches.Add(b);
+ }
+ if (!string.IsNullOrEmpty(cfg.ProcedureNameAlt2))
+ {
+ IList batches3 = session.QueryOver(() => btc)
+ .Where(bb => (bb.ProcedureName == cfg.ProcedureNameAlt2))
+ .List();
+ foreach (var b in batches3) batches.Add(b);
+ }
- if (!string.IsNullOrEmpty(cfg.ProcedureNameAlt1))
- {
- IList batches2 = session.QueryOver(() => btc)
- .Where(bb => (bb.ProcedureName == cfg.ProcedureNameAlt1))
- .List();
- foreach (var b in batches2) batches.Add(b);
- }
- if (!string.IsNullOrEmpty(cfg.ProcedureNameAlt2))
- {
- IList batches3 = session.QueryOver(() => btc)
- .Where(bb => (bb.ProcedureName == cfg.ProcedureNameAlt2))
- .List();
- foreach (var b in batches3) batches.Add(b);
- }
+ int samplesCount = 0;
+ double q2CorrLRsum = 0;
+ double q2CorrRLsum = 0;
- int samplesCount = 0;
- double q2CorrLRsum = 0;
- double q2CorrRLsum = 0;
-
- var sortedBatches = batches.OrderByDescending(b => b.EndTime);
- foreach (var b in sortedBatches)
+ var sortedBatches = batches.OrderByDescending(b => b.EndTime);
+ foreach (var b in sortedBatches)
+ {
+ foreach (var wm in b.WaterMeters)
{
- foreach (var wm in b.WaterMeters)
+ if ((wm != null) && !wm.Disabled && wm.Passed)
{
- if ((wm != null) && !wm.Disabled && wm.Passed)
- {
#if IPERL
- q2CorrLRsum += wm.Q2CorrLR;
- q2CorrRLsum += wm.Q2CorrRL;
+ q2CorrLRsum += wm.Q2CorrLR;
+ q2CorrRLsum += wm.Q2CorrRL;
#endif
- samplesCount++;
- }
+ samplesCount++;
}
-
- if (samplesCount >= 200) break;
}
- if (samplesCount >= 200)
- {
- IsQ2PreCorrectionCalculated = true;
- CalculatedQ2PreCorrectionLR = (int)Math.Round(q2CorrLRsum / samplesCount);
- CalculatedQ2PreCorrectionRL = (int)Math.Round(q2CorrRLsum / samplesCount);
- log.WarnFormat("Q2 corrections calculated OK: LR = {0}, RL = {1}", CalculatedQ2PreCorrectionLR, CalculatedQ2PreCorrectionRL);
- return true;
- }
- else
- {
- log.ErrorFormat("Not enough samples to calculate Q2 corrections ({0})", samplesCount);
- return false;
- }
+ if (samplesCount >= 200) break;
+ }
+
+ if (samplesCount >= 200)
+ {
+ IsQ2PreCorrectionCalculated = true;
+ CalculatedQ2PreCorrectionLR = (int)Math.Round(q2CorrLRsum / samplesCount);
+ CalculatedQ2PreCorrectionRL = (int)Math.Round(q2CorrRLsum / samplesCount);
+ log.WarnFormat("Q2 corrections calculated OK: LR = {0}, RL = {1}", CalculatedQ2PreCorrectionLR, CalculatedQ2PreCorrectionRL);
+ return true;
+ }
+ else
+ {
+ log.ErrorFormat("Not enough samples to calculate Q2 corrections ({0})", samplesCount);
+ return false;
}
}
catch (Exception exc)
@@ -178,6 +178,10 @@ namespace TBF.Rig.TestMethods.Q2CorrectionFromHistory
log.ErrorFormat("Failed to calculate Q2 corrections: {0}", exc.Message);
return false;
}
+ finally
+ {
+ if (session != null && session.IsOpen) session.Close();
+ }
}
}
}
diff --git a/TBF/Rig/Various/StatisticsMonitoring/ProcessStatistics.cs b/TBF/Rig/Various/StatisticsMonitoring/ProcessStatistics.cs
index 42b322460..6916db331 100644
--- a/TBF/Rig/Various/StatisticsMonitoring/ProcessStatistics.cs
+++ b/TBF/Rig/Various/StatisticsMonitoring/ProcessStatistics.cs
@@ -121,45 +121,52 @@ namespace TBF.Rig.Various.StatisticsMonitoring
/// Take into account only batches where the 1st test in named 'RFID' and
/// at least one water meter completed all tests.
///
- try
{
- ISession session = Results.DB.CreateSession();
-
- int usagesMin;
- do
+ ISession session = null;
+ try
{
- usagesMin = 0;
- IList batches = session.QueryOver()
- .Where(x => x.BatchNr == batchNr)
- .List();
- batchNr--;
- if (batches.Count != 1 || batches[0].TestRslts.Count < 1 || batches[0].TestRslts[0].MethodClass != "TestMethods.iPerlCommunication")
- {
- continue;
- }
+ session = TBF.DB.ResultsDBSessionFactory.OpenSession();
- bool isACompleteBatch = false;
- foreach (var wm in batches[0].WaterMeters)
+ int usagesMin;
+ do
{
- int i = wm.WMPosition - 1;
- if (0 <= i && i < TBF.Data.WMsCount && usages[i] < RequiredUsages && !wm.Disabled && wm.CompletedFromTests())
+ usagesMin = 0;
+ IList batches = session.QueryOver()
+ .Where(x => x.BatchNr == batchNr)
+ .List();
+ batchNr--;
+ if (batches.Count != 1 || batches[0].TestRslts.Count < 1 || batches[0].TestRslts[0].MethodClass != "TestMethods.iPerlCommunication")
{
- isACompleteBatch = true;
- usages[i]++;
- if (!wm.MeterTestRslts[0].Passed) failures[i]++;
+ continue;
}
+
+ bool isACompleteBatch = false;
+ foreach (var wm in batches[0].WaterMeters)
+ {
+ int i = wm.WMPosition - 1;
+ if (0 <= i && i < TBF.Data.WMsCount && usages[i] < RequiredUsages && !wm.Disabled && wm.CompletedFromTests())
+ {
+ isACompleteBatch = true;
+ usages[i]++;
+ if (!wm.MeterTestRslts[0].Passed) failures[i]++;
+ }
+ }
+
+ usagesMin = int.MaxValue;
+ for (int i = 0; i < TBF.Data.WMsCount; i++) if (usagesMin > usages[i]) usagesMin = usages[i];
+
+ if (isACompleteBatch) completeBatchesProcessed++;
}
-
- usagesMin = int.MaxValue;
- for (int i = 0; i < TBF.Data.WMsCount; i++) if (usagesMin > usages[i]) usagesMin = usages[i];
-
- if (isACompleteBatch) completeBatchesProcessed++;
+ while ((usagesMin < RequiredUsages) && (batchNr > 0) && (completeBatchesProcessed < MaxBatches));
+ }
+ catch (Exception exc)
+ {
+ log.ErrorFormat("Failed to calculate iPERL head usage statistics: {0}", exc.Message);
+ }
+ finally
+ {
+ if (session != null && session.IsOpen) session.Close();
}
- while ((usagesMin < RequiredUsages) && (batchNr > 0) && (completeBatchesProcessed < MaxBatches));
- }
- catch (Exception exc)
- {
- log.ErrorFormat("Failed to calculate iPERL head usage statistics: {0}", exc.Message);
}
///
@@ -175,14 +182,15 @@ namespace TBF.Rig.Various.StatisticsMonitoring
}
}
- if (doTriggerEvents && !string.IsNullOrEmpty(Events.DB.ConnectionString))
+ if (doTriggerEvents && TBF.DB.EventsDBSessionFactory != null)
{
///
/// Trigger events
///
+ ISession session = null;
try
{
- ISession session = Events.DB.CreateSession();
+ session = TBF.DB.EventsDBSessionFactory.OpenSession();
Events.DB.LoadSubscribers(session);
for (int i = 0; i < TBF.Data.WMsCount; i++)
@@ -203,6 +211,10 @@ namespace TBF.Rig.Various.StatisticsMonitoring
{
log.ErrorFormat("Failed to trigger events: source = {0}, message = {1}", statisticsCfg.EventSource, exc.Message);
}
+ finally
+ {
+ if (session != null && session.IsOpen) session.Close();
+ }
}
}
}
diff --git a/TBF/UI/Bench/Components/ComponentsManagerDlg.cs b/TBF/UI/Bench/Components/ComponentsManagerDlg.cs
index f8a958d7e..95197e3c3 100644
--- a/TBF/UI/Bench/Components/ComponentsManagerDlg.cs
+++ b/TBF/UI/Bench/Components/ComponentsManagerDlg.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2013-2021 Sensus Slovensko a.s.
+/// Copyright (c) 2013-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -24,12 +24,10 @@ namespace TBF.UI.Bench.Components
///
/// List of components (=component configuration instances)
///
+ public ISession Session;
IList cmpntEntities;
-
IList toBeDeletedEntities;
- ISession session;
-
SelectComponentClassDlg selectComponentTypeDlg; /// Constructed once, the selection is kept between dialog usages
CfgUpdateFlags flags; /// Or-ed from particular Flags from ComponentParametersDlg
@@ -64,6 +62,14 @@ namespace TBF.UI.Bench.Components
InitializeComponent();
+ /// Open a database session
+ try { Session = TBF.DB.ConfigDBSessionFactory.OpenSession(); }
+ catch (Exception e)
+ {
+ MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message,
+ Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
+ }
+
flags = CfgUpdateFlags.None;
selectComponentTypeDlg = new SelectComponentClassDlg();
@@ -121,11 +127,9 @@ namespace TBF.UI.Bench.Components
sharedButtons.DisableButtons(SharedButtons.Buttons.Remove | SharedButtons.Buttons.Edit);
- session = TBF.DB.CreateSession(Common.DBKind.Config);
- cmpntEntities = session.QueryOver()
+ cmpntEntities = Session.QueryOver()
.OrderBy(x => x.ItemNr).Asc
.List();
-
RedrawAll();
}
@@ -372,7 +376,7 @@ namespace TBF.UI.Bench.Components
{
if ((flags & CfgUpdateFlags.AnyChange) != 0 || (flags & CfgUpdateFlags.RestartRqrd) != 0)
{
- SaveDBChanges(session);
+ SaveDBChanges(Session);
flags = CfgUpdateFlags.None; /// Changes saved
}
@@ -696,11 +700,12 @@ namespace TBF.UI.Bench.Components
MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
- SaveDBChanges(session);
+ SaveDBChanges(Session);
}
}
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
+ if (Session != null && Session.IsOpen) Session.Close();
}
diff --git a/TBF/UI/Bench/Metrology/MetrologyDlg.cs b/TBF/UI/Bench/Metrology/MetrologyDlg.cs
index bc9896fcf..3b3096eda 100644
--- a/TBF/UI/Bench/Metrology/MetrologyDlg.cs
+++ b/TBF/UI/Bench/Metrology/MetrologyDlg.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2013-2019 Sensus Slovensko a.s.
+/// Copyright (c) 2013-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -17,14 +17,21 @@ namespace TBF.UI.Bench.Metrology
{
static readonly ILog log = LogManager.GetLogger(typeof(MetrologyDlg));
- public IList cmpntEntities;
-
- ISession session;
+ public ISession Session;
+ public IList cmpntEntities;
public MetrologyDlg()
{
InitializeComponent();
+ /// Open a database session
+ try { Session = TBF.DB.ConfigDBSessionFactory.OpenSession(); }
+ catch (Exception e)
+ {
+ MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message,
+ Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
+ }
+
/// SharedDlgButtons configuration
sharedButtons.ParentForm = this;
sharedButtons.RequiredGroupMembership = new Common.GID[] { Common.GID.Metrologists, Common.GID.MetrologicalAuthority };
@@ -52,11 +59,9 @@ namespace TBF.UI.Bench.Metrology
int platinumTempMetersCount = 0;
int evaporationsCount = 0;
- session = TBF.DB.CreateSession(Common.DBKind.Config);
- cmpntEntities = session.QueryOver()
- .OrderBy(x => x. ItemNr).Asc
- .List();
-
+ cmpntEntities = (Session == null) ? new List() : Session.QueryOver()
+ .OrderBy(x => x.ItemNr).Asc
+ .List();
foreach (var cmpnt in cmpntEntities)
{
Rig.Generic.IComponentFactory factory = TbfComponents.CmpntFactoryFromClassName(cmpnt.ClassName);
@@ -226,7 +231,7 @@ namespace TBF.UI.Bench.Metrology
metrologyTabControl.TabPages.Add(tabPage);
}
}
- }
+ }
private void unlockButton_Click(object sender, EventArgs e)
{
@@ -238,7 +243,7 @@ namespace TBF.UI.Bench.Metrology
private void okButton_Click(object sender, EventArgs e)
{
- using (ITransaction transaction = session.BeginTransaction())
+ using (ITransaction transaction = Session.BeginTransaction())
{
try
{
@@ -248,12 +253,12 @@ namespace TBF.UI.Bench.Metrology
if (tab != null)
{
tab.OkBtnClicked();
- tab.SaveEntityToDB(session);
- foreach (var entity in tab.ToBeRemoved) session.Delete(entity);
+ tab.SaveEntityToDB(Session);
+ foreach (var entity in tab.ToBeRemoved) Session.Delete(entity);
}
}
transaction.Commit();
- session.Flush();
+ Session.Flush();
}
catch (Exception exc)
{
@@ -347,6 +352,7 @@ namespace TBF.UI.Bench.Metrology
private void MetrologyDlg_FormClosing(object sender, FormClosingEventArgs e)
{
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
+ if (Session != null && Session.IsOpen) Session.Close();
}
}
}
diff --git a/TBF/UI/Bench/Paths/PathsDlg.cs b/TBF/UI/Bench/Paths/PathsDlg.cs
index 53bb6c84d..764f0159d 100644
--- a/TBF/UI/Bench/Paths/PathsDlg.cs
+++ b/TBF/UI/Bench/Paths/PathsDlg.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2013-2022 Sensus Slovensko a.s.
+/// Copyright (c) 2013-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -32,11 +32,11 @@ namespace TBF.UI.Bench.Paths
/// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi
public readonly int Dpi;
- public IList TbfComponents;
+ public ISession Session; /// One common DB session passed also to the controls inside tab pages
+ public IList TbfComponents;
public IList Valves;
public IList FeedingRegValves;
public IList OutputRegValves;
- public ISession Session; /// One common DB session passed also to the controls inside tab pages
public IList Procedures;
public IList Tests;
@@ -52,6 +52,14 @@ namespace TBF.UI.Bench.Paths
InitializeComponent();
+ /// Open a database session
+ try { Session = TBF.DB.ConfigDBSessionFactory.OpenSession(); }
+ catch (Exception e)
+ {
+ MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message,
+ Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
+ }
+
/// SharedDlgButtons configuration
sharedButtons.ParentForm = this;
sharedButtons.RequiredGroupMembership = new GID[] { GID.Metrologists };
@@ -66,15 +74,7 @@ namespace TBF.UI.Bench.Paths
sharedButtons.DownClicked += downButton_Click;
/// Load the list of components from the database
- try
- {
- TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(TBF.DB.CreateSession(Common.DBKind.Config));
- }
- catch
- {
- TbfComponents = new List();
- MessageBox.Show("Error occured when loading components");
- }
+ TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(Session);
/// Find all master valves
Valves = Rig.GenericDevices.ValveBase.MasterValves(TbfComponents);
@@ -98,9 +98,6 @@ namespace TBF.UI.Bench.Paths
}
}
- /// Create the database session for paths
- Session = TBF.DB.CreateSession(DBKind.Config);
-
Procedures = Session.QueryOver().List();
Tests = Session.QueryOver().List();
@@ -371,6 +368,7 @@ namespace TBF.UI.Bench.Paths
private void PathsDlg_FormClosing(object sender, FormClosingEventArgs e)
{
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
+ if (Session != null && Session.IsOpen) Session.Close();
}
}
}
diff --git a/TBF/UI/Bench/TestProfiles/TestProfileDlg.cs b/TBF/UI/Bench/TestProfiles/TestProfileDlg.cs
index ca022db77..48dda78da 100644
--- a/TBF/UI/Bench/TestProfiles/TestProfileDlg.cs
+++ b/TBF/UI/Bench/TestProfiles/TestProfileDlg.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2019-2022 Sensus Slovensko a.s.
+/// Copyright (c) 2019-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -26,6 +26,7 @@ namespace TBF.UI.Bench.TestProfiles
/// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi
public readonly int Dpi;
+ readonly NHibernate.ISession session;
readonly bool openUnlocked;
///
@@ -52,26 +53,21 @@ namespace TBF.UI.Bench.TestProfiles
openUnlocked = false;
}
- public TestProfileDlg(Profile profile, IList usedNames, bool openUnlocked, Form parentForm)
+ public TestProfileDlg(NHibernate.ISession session, Profile profile, IList usedNames, bool openUnlocked, Form parentForm)
: this()
{
if (profile == null) throw new ArgumentNullException("profile");
+ this.session = session;
LoadedProfile = profile;
this.usedNames = usedNames;
this.openUnlocked = openUnlocked;
- TestMethods = new List();
- using (NHibernate.ISession session = TBF.DB.CreateSession(DBKind.Config))
- {
- /// Prepare a list of components and a list of test methods
- TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(session);
+ /// Prepare a list of components and a list of test methods
+ TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(this.session);
- if (TbfComponents != null)
- foreach (var c in TbfComponents)
- if (c is ITestMethod)
- TestMethods.Add(c as ITestMethod);
- }
+ TestMethods = new List();
+ foreach (var c in TbfComponents) if (c is ITestMethod) TestMethods.Add(c as ITestMethod);
/// SharedDlgButtons configuration
sharedButtons.ParentForm = parentForm;
diff --git a/TBF/UI/Bench/TestProfiles/TestProfileDlg.resx b/TBF/UI/Bench/TestProfiles/TestProfileDlg.resx
index c8a4a70b2..250328f57 100644
--- a/TBF/UI/Bench/TestProfiles/TestProfileDlg.resx
+++ b/TBF/UI/Bench/TestProfiles/TestProfileDlg.resx
@@ -928,7 +928,7 @@
sharedButtons
- TBF.UI.Shared.SharedButtons, TBF, Version=2.27.1917.0, Culture=neutral, PublicKeyToken=null
+ TBF.UI.Shared.SharedButtons, TBF, Version=2.32.2027.0, Culture=neutral, PublicKeyToken=null
mainSplitContainer.Panel2
diff --git a/TBF/UI/Bench/TestProfiles/TestProfilesCtrl.cs b/TBF/UI/Bench/TestProfiles/TestProfilesCtrl.cs
index 22692b032..90637d337 100644
--- a/TBF/UI/Bench/TestProfiles/TestProfilesCtrl.cs
+++ b/TBF/UI/Bench/TestProfiles/TestProfilesCtrl.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2019-2022 Sensus Slovensko a.s.
+/// Copyright (c) 2019-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -51,11 +51,11 @@ namespace TBF.UI.Bench.TestProfiles
{
if (Parent == null) return;
- session = TBF.DB.CreateSession(Common.DBKind.Config);
-
this.parent = parent;
this.parentControl = parentControl;
+ session = parent.Session;
+
SubItemClicked += new SubItemEventHandler(listViewEx_SubItemClicked);
SubItemEndEditing += new SubItemEndEditingEventHandler(listViewEx_SubItemEndEditing);
@@ -217,7 +217,7 @@ namespace TBF.UI.Bench.TestProfiles
newProfile.CreationUser = Users.CurrentUser.UserName();
newProfile.CreationTime = DateTime.Now;
- if (new TestProfileDlg(newProfile, GetUsedNames(false), true, parent).ShowDialog() == DialogResult.OK)
+ if (new TestProfileDlg(session, newProfile, GetUsedNames(false), true, parent).ShowDialog() == DialogResult.OK)
{
/// TODO: Make name uniqueness test
parent.Unlock();
@@ -297,7 +297,7 @@ namespace TBF.UI.Bench.TestProfiles
IList usedNames = GetUsedNames(false);
usedNames.Remove(editedProfile.Name.ToLower()); /// Allow original procedure name
///
- if (new TestProfileDlg(editedProfile, usedNames, false, parent).ShowDialog() == DialogResult.OK)
+ if (new TestProfileDlg(session, editedProfile, usedNames, false, parent).ShowDialog() == DialogResult.OK)
{
parent.Unlock();
@@ -342,7 +342,7 @@ namespace TBF.UI.Bench.TestProfiles
newProfile.CreationUser = Users.CurrentUser.UserName();
newProfile.CreationTime = DateTime.Now;
- if ((new TestProfileDlg(newProfile, GetUsedNames(false), true, parent)).ShowDialog() == DialogResult.OK)
+ if ((new TestProfileDlg(session, newProfile, GetUsedNames(false), true, parent)).ShowDialog() == DialogResult.OK)
{
/// TODO: Make name uniqueness test
parent.Unlock();
@@ -391,7 +391,7 @@ namespace TBF.UI.Bench.TestProfiles
newProfile.CreationUser = Users.CurrentUser.UserName();
newProfile.CreationTime = DateTime.Now;
- if ((new TestProfileDlg(newProfile, GetUsedNames(false), true, parent)).ShowDialog() == DialogResult.OK)
+ if ((new TestProfileDlg(session, newProfile, GetUsedNames(false), true, parent)).ShowDialog() == DialogResult.OK)
{
/// TODO: Make name uniqueness test
parent.Unlock();
diff --git a/TBF/UI/Bench/TestProfiles/TestProfilesDlg.cs b/TBF/UI/Bench/TestProfiles/TestProfilesDlg.cs
index 69a93262d..8653e8f8a 100644
--- a/TBF/UI/Bench/TestProfiles/TestProfilesDlg.cs
+++ b/TBF/UI/Bench/TestProfiles/TestProfilesDlg.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2019 Sensus Slovensko a.s.
+/// Copyright (c) 2019-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -19,6 +19,8 @@ namespace TBF.UI.Bench.TestProfiles
/// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi
public readonly int Dpi;
+ public NHibernate.ISession Session;
+
public TestProfilesDlg()
{
/// Detect display setting: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi.
@@ -26,6 +28,14 @@ namespace TBF.UI.Bench.TestProfiles
InitializeComponent();
+ /// Open a database session
+ try { Session = TBF.DB.ConfigDBSessionFactory.OpenSession(); }
+ catch (Exception e)
+ {
+ MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message,
+ Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
+ }
+
/// SharedDlgButtons configuration
sharedButtons.ParentForm = this;
sharedButtons.RequiredGroupMembership = new GID[] { GID.MetrologicalAuthority };
@@ -82,7 +92,7 @@ namespace TBF.UI.Bench.TestProfiles
///
private void okButton_Click(object sender, EventArgs e)
{
- ProceduresDlg_FormClosed(sender, null);
+ TestProfilesDlg_FormClosed(sender, null);
DialogResult = DialogResult.OK;
Close();
@@ -93,7 +103,7 @@ namespace TBF.UI.Bench.TestProfiles
///
///
///
- private void ProceduresDlg_FormClosed(object sender, FormClosedEventArgs e)
+ private void TestProfilesDlg_FormClosed(object sender, FormClosedEventArgs e)
{
testProfilesCtrl.OkBtnClicked();
SaveUISettings();
@@ -224,6 +234,7 @@ namespace TBF.UI.Bench.TestProfiles
private void TestProfilesDlg_FormClosing(object sender, FormClosingEventArgs e)
{
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
+ if (Session != null && Session.IsOpen) Session.Close();
}
}
}
diff --git a/TBF/UI/Bench/TestProfiles/TestProfilesDlg.designer.cs b/TBF/UI/Bench/TestProfiles/TestProfilesDlg.designer.cs
index ad56aad2b..e56e1c26b 100644
--- a/TBF/UI/Bench/TestProfiles/TestProfilesDlg.designer.cs
+++ b/TBF/UI/Bench/TestProfiles/TestProfilesDlg.designer.cs
@@ -89,7 +89,7 @@ namespace TBF.UI.Bench.TestProfiles
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "TestProfilesDlg";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.TestProfilesDlg_FormClosing);
- this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.ProceduresDlg_FormClosed);
+ this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.TestProfilesDlg_FormClosed);
this.Load += new System.EventHandler(this.TestProfilesDlg_Load);
this.splitContainer.Panel1.ResumeLayout(false);
this.splitContainer.Panel2.ResumeLayout(false);
diff --git a/TBF/UI/Bench/Transitions/TransitionsDlg.cs b/TBF/UI/Bench/Transitions/TransitionsDlg.cs
index 5232d109c..e5d6641f7 100644
--- a/TBF/UI/Bench/Transitions/TransitionsDlg.cs
+++ b/TBF/UI/Bench/Transitions/TransitionsDlg.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2013-2017 Sensus Metering Systems
+/// Copyright (c) 2013-2023 Sensus Metering Systems
///
using System;
using System.Collections.Generic;
@@ -66,6 +66,14 @@ namespace TBF.UI.Bench.Transitions
InitializeComponent();
+ /// Open a database session
+ try { Session = TBF.DB.ConfigDBSessionFactory.OpenSession(); }
+ catch (Exception e)
+ {
+ MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message,
+ Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
+ }
+
/// SharedDlgButtons configuration
sharedButtons.ParentForm = this;
sharedButtons.RequiredGroupMembership = new Common.GID[] { Common.GID.Metrologists };
@@ -90,9 +98,6 @@ namespace TBF.UI.Bench.Transitions
seqStepsCtrls = new List();
- /// Open the database
- Session = TBF.DB.CreateSession(Common.DBKind.Config);
-
/// Prepare a list of components and a list of all valves in the test bench
TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(Session);
Valves = Rig.GenericDevices.ValveBase.MasterValves(TbfComponents);
@@ -107,10 +112,20 @@ namespace TBF.UI.Bench.Transitions
/// Load the sequences
/// Note: Each sequence (in both sequences together) has a unique ItemNr (0 .. N-1)
- TransitionSequences = Session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
- VirtualBenchSequences = Session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
- procedures = Session.QueryOver().List();
- tests = Session.QueryOver().List();
+ if (Session != null)
+ {
+ TransitionSequences = Session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
+ VirtualBenchSequences = Session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
+ procedures = Session.QueryOver().List();
+ tests = Session.QueryOver().List();
+ }
+ else
+ {
+ TransitionSequences = new List();
+ VirtualBenchSequences = new List();
+ procedures = new List();
+ tests = new List();
+ }
RemovedTransitionSequences = new List();
RemovedVirtualBenchSequences = new List();
@@ -708,6 +723,7 @@ namespace TBF.UI.Bench.Transitions
private void TransitionsDlg_FormClosing(object sender, FormClosingEventArgs e)
{
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
+ if (Session != null && Session.IsOpen) Session.Close();
}
}
}
diff --git a/TBF/UI/Bench/Uncertainties/UncertaintiesDlg.cs b/TBF/UI/Bench/Uncertainties/UncertaintiesDlg.cs
index 178f9e3e6..c984d2afe 100644
--- a/TBF/UI/Bench/Uncertainties/UncertaintiesDlg.cs
+++ b/TBF/UI/Bench/Uncertainties/UncertaintiesDlg.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2019 Sensus Slovensko a.s.
+/// Copyright (c) 2019-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -17,14 +17,21 @@ namespace TBF.UI.Bench.Uncertainties
{
static readonly ILog log = LogManager.GetLogger(typeof(UncertaintiesDlg));
+ public ISession Session;
public IList cmpntEntities;
- ISession session;
-
public UncertaintiesDlg()
{
InitializeComponent();
+ /// Open a database session
+ try { Session = TBF.DB.ConfigDBSessionFactory.OpenSession(); }
+ catch (Exception e)
+ {
+ MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message,
+ Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
+ }
+
/// SharedDlgButtons configuration
sharedButtons.ParentForm = this;
#if KEMPNO_50
@@ -55,11 +62,9 @@ namespace TBF.UI.Bench.Uncertainties
int tempMetersCount = 0;
int evaporationsCount = 0;
- session = TBF.DB.CreateSession(Common.DBKind.Config);
- cmpntEntities = session.QueryOver()
- .OrderBy(x => x. ItemNr).Asc
- .List();
-
+ cmpntEntities = (Session == null) ? new List() : Session.QueryOver()
+ .OrderBy(x => x. ItemNr).Asc
+ .List();
foreach (var cmpnt in cmpntEntities)
{
Rig.Generic.IComponentFactory factory = TbfComponents.CmpntFactoryFromClassName(cmpnt.ClassName);
@@ -201,7 +206,7 @@ namespace TBF.UI.Bench.Uncertainties
private void okButton_Click(object sender, EventArgs e)
{
- using (ITransaction transaction = session.BeginTransaction())
+ using (ITransaction transaction = Session.BeginTransaction())
{
try
{
@@ -211,12 +216,12 @@ namespace TBF.UI.Bench.Uncertainties
if (tab != null)
{
tab.OkBtnClicked();
- session.SaveOrUpdate(tab.MeterEntity);
- foreach (var entity in tab.ToBeRemoved) session.Delete(entity);
+ Session.SaveOrUpdate(tab.MeterEntity);
+ foreach (var entity in tab.ToBeRemoved) Session.Delete(entity);
}
}
transaction.Commit();
- session.Flush();
+ Session.Flush();
}
catch (Exception exc)
{
@@ -310,6 +315,7 @@ namespace TBF.UI.Bench.Uncertainties
private void UncertaintiesDlg_FormClosing(object sender, FormClosingEventArgs e)
{
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
+ if (Session != null && Session.IsOpen) Session.Close();
}
}
}
diff --git a/TBF/UI/Calendar/CalendarTabPageCtrl.cs b/TBF/UI/Calendar/CalendarTabPageCtrl.cs
index 984b08678..f5926b27c 100644
--- a/TBF/UI/Calendar/CalendarTabPageCtrl.cs
+++ b/TBF/UI/Calendar/CalendarTabPageCtrl.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2020 Sensus Slovensko a.s.
+/// Copyright (c) 2020-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -61,14 +61,15 @@ namespace TBF.UI.Calendar
calendarEventsListViewEx.Items.Add(lvi);
}
- public void StartCalendar(IList eventsFromComponents)
+ public void StartCalendar(IList eventsFromComponents, ISession session = null)
{
+ bool openAndCloseSession = (session == null);
this.eventsFromComponents = eventsFromComponents;
try
{
/// Read custom events from the database
- ISession session = TBF.DB.CreateSession(Common.DBKind.Config);
+ if (openAndCloseSession) session = TBF.DB.ConfigDBSessionFactory.OpenSession();
customEvents = session.QueryOver().List();
TripplicateShiftCustomEvents(customEvents);
@@ -85,6 +86,7 @@ namespace TBF.UI.Calendar
/// Serve events (determine if any event was triggered)
lastTimeCalendarEventsServed = DateTime.Now;
ServeCalendarEventsNotifWarnErrorFatal(lastTimeCalendarEventsServed, session, customEvents);
+ if (openAndCloseSession) session.Close();
}
catch (Exception)
{
@@ -118,13 +120,14 @@ namespace TBF.UI.Calendar
}
}
-
///
/// Triggers events corresponding to triggered motification.warning/error calendar events.
///
/// Current time
- void ServeCalendarEventsNotifWarnErrorFatal(DateTime currentTime, ISession parentSession = null, IList customEventsFromDB = null)
+ void ServeCalendarEventsNotifWarnErrorFatal(DateTime currentTime, ISession session = null, IList customEventsFromDB = null)
{
+ bool openAndCloseSession = (session == null);
+
IList eventsToTrigger = new List();
for (int i = eventsFromComponents.Count - 1; i >= 0; i--)
@@ -160,7 +163,8 @@ namespace TBF.UI.Calendar
try
{
- var session = (parentSession != null) ? parentSession : TBF.DB.CreateSession(Common.DBKind.Config);
+ if (openAndCloseSession) session = TBF.DB.ConfigDBSessionFactory.OpenSession();
+
var customEvents = (customEventsFromDB != null) ? customEventsFromDB : session.QueryOver() .List();
for (int i = customEvents.Count - 1; i >= 0; i--)
@@ -194,32 +198,27 @@ namespace TBF.UI.Calendar
}
}
session.Flush();
+ if (openAndCloseSession) session.Close();
}
catch (Exception exc)
{
log.ErrorFormat("Failed to load or update CustomEvent-s in ServeTriggerEvtCalendarEvents(): {0}", exc.Message);
}
- if (eventsToTrigger.Count > 0 && !string.IsNullOrEmpty(global::Events.DB.ConnectionString))
+ if (eventsToTrigger.Count > 0 && TBF.DB.EventsDBSessionFactory != null)
{
- try
+ using (ISession evtDBSession = TBF.DB.EventsDBSessionFactory.OpenSession())
{
- ISession session = global::Events.DB.CreateSession();
- global::Events.DB.LoadSubscribers(session);
+ global::Events.DB.LoadSubscribers(evtDBSession);
foreach (var e in eventsToTrigger)
{
- TBF.UiBridge.Bridge.TriggerEvent(session, e);
+ TBF.UiBridge.Bridge.TriggerEvent(evtDBSession, e);
}
- session.Flush();
- }
- catch (Exception exc)
- {
- log.ErrorFormat("Failed to trigger events in ServeTriggerEvtCalendarEvents(): {0}", exc.Message);
+ evtDBSession.Close();
}
}
}
-
///
/// Returns an array of parameters of selected actions.
/// This function is not invoked from UI thread.
@@ -234,9 +233,10 @@ namespace TBF.UI.Calendar
if (maxCount <= 0) return parametersList;
+ ISession session = null;
try
{
- ISession session = TBF.DB.CreateSession(Common.DBKind.Config);
+ session = TBF.DB.ConfigDBSessionFactory.OpenSession();
var customEventsFromDB = session.QueryOver().List();
for (int i = customEventsFromDB.Count - 1; i >= 0; i--)
@@ -258,12 +258,15 @@ namespace TBF.UI.Calendar
if (parametersList.Count >= maxCount) break;
}
}
- session.Flush();
}
catch (Exception exc)
{
log.ErrorFormat("Failed to load or update CustomEvent-s in ServeSelectedCalendarEvents(): {0}", exc.Message);
}
+ finally
+ {
+ if (session != null && session.IsOpen) session.Close();
+ }
if (parametersList.Count > 0)
{
@@ -273,7 +276,6 @@ namespace TBF.UI.Calendar
return parametersList;
}
-
///
/// Convert calendar event AutoAction to event Severity
///
@@ -291,7 +293,6 @@ namespace TBF.UI.Calendar
}
}
-
void TripplicateShiftCustomEvents(IList customEvents)
{
/// Tripplicate each custom event with frequency 'EveryShift'
@@ -314,15 +315,15 @@ namespace TBF.UI.Calendar
}
}
-
private void newEventButton_Click(object sender, EventArgs ea)
{
EventDetailsForm dlg = new EventDetailsForm();
if (dlg.ShowDialog() == DialogResult.OK && dlg.NewEvent is CustomEvent)
{
+ ISession session = null;
try
{
- ISession session = TBF.DB.CreateSession(Common.DBKind.Config);
+ session = TBF.DB.ConfigDBSessionFactory.OpenSession();
session.SaveOrUpdate(dlg.NewEvent as CustomEvent);
session.Flush();
@@ -341,12 +342,15 @@ namespace TBF.UI.Calendar
}
catch (Exception)
{
- log.ErrorFormat("Failed to save new calendar event to the local config database");
+ MessageBox.Show("Cannot save the change to the database", Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
+ }
+ finally
+ {
+ if (session != null && session.IsOpen) session.Close();
}
}
}
-
private void calendarEventsListViewEx_MouseDoubleClick(object sender, MouseEventArgs mea)
{
if (calendarEventsListViewEx.SelectedIndices.Count != 1) return;
@@ -355,10 +359,11 @@ namespace TBF.UI.Calendar
EventDetailsForm dlg = new EventDetailsForm { Event = evnt };
if (dlg.ShowDialog() != DialogResult.OK) return;
+ ISession session = null;
try
{
/// Re-read selected custom event from the database
- ISession session = TBF.DB.CreateSession(Common.DBKind.Config);
+ session = TBF.DB.ConfigDBSessionFactory.OpenSession();
var cEvents = session.QueryOver()
.Where(x => (x.Id == evnt.Id))
.List();
@@ -399,7 +404,11 @@ namespace TBF.UI.Calendar
}
catch (Exception)
{
- MessageBox.Show("Cannot save change to the database", Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
+ MessageBox.Show("Cannot save the change to the database", Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
+ }
+ finally
+ {
+ if (session != null && session.IsOpen) session.Close();
}
}
}
diff --git a/TBF/UI/MainWnd.cs b/TBF/UI/MainWnd.cs
index f56100464..e9883881c 100644
--- a/TBF/UI/MainWnd.cs
+++ b/TBF/UI/MainWnd.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2013-2021 Sensus Slovensko a.s.
+/// Copyright (c) 2013-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -13,6 +13,7 @@ using Config.Entities;
using TBF.Resources;
using TBF.UiBridge;
using TBF.UI.Shared;
+using NHibernate;
namespace TBF.UI
{
@@ -539,18 +540,24 @@ namespace TBF.UI
{
Users.DB.ConnectionString = TBF.DB.CurrentBench.ProceduresDBSettings.ConnectionString;
Users.DB.DbType = TBF.DB.CurrentBench.ProceduresDBSettings.DbType;
+ using (ISession session = Users.DB.CreateSession())
+ {
#if TURA_IPERL || TURA_IPERL_NEW || TURA_SPECIAL
- Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(Users.DB.CreateSession(), true);
- string connStr = Users.DB.ConnectionString;
- int len = connStr.ToUpper().IndexOf("; UID=");
- if (len == -1) len = connStr.ToUpper().IndexOf("; USER=");
- if (len > 0) dlg.TitleExtension = connStr.Substring(0, len);
+ Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(session, true);
+ string connStr = Users.DB.ConnectionString;
+ int len = connStr.ToUpper().IndexOf("; UID=");
+ if (len == -1) len = connStr.ToUpper().IndexOf("; USER=");
+ if (len > 0) dlg.TitleExtension = connStr.Substring(0, len);
#else
- Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(Users.DB.CreateSession(), false);
+ Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(session, false);
#endif
- dlg.ShowDialog();
+ dlg.ShowDialog();
+ session.Close();
+ }
}
+
private void languageTSMItem_Click(object s, EventArgs e) { new TBF.UI.Settings.LanguageDlg().ShowDialog(); }
+
private void databaseSettingsTSMItem_Click(object s, EventArgs e)
{
TBF.UI.Settings.BenchesDlg dlg = new TBF.UI.Settings.BenchesDlg();
@@ -570,9 +577,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 Users.Forms.PasswordChangeDlg(Users.CurrentUser.UserName()).ShowDialog(); }
+
+ private void passwdTSMItem_Click(object s, EventArgs e)
+ {
+ new Users.Forms.PasswordChangeDlg(TBF.DB.UserSessionFactories, Users.CurrentUser.UserName()).ShowDialog();
+ }
+
private void aboutTSMItem_Click(object s, EventArgs e) { new TBF.UI.Help.AboutDlg().ShowDialog(); }
@@ -593,26 +606,26 @@ namespace TBF.UI
Rig.GenericDevices.IBenchInfo benchInfo = Rig.Sequences.ProcessData.BenchInfo;
RemoteDBUse remoteDbUse = (benchInfo != null) ? benchInfo.RemoteDBUse : RemoteDBUse.LocalDBOnly;
- Common.DBKind[] dBase;
+ ISessionFactory[] dBase;
string[] signature;
///
switch (remoteDbUse)
{
default:
case RemoteDBUse.LocalDBOnly:
- dBase = new Common.DBKind[] { Common.DBKind.Config };
+ dBase = new ISessionFactory[] { TBF.DB.ConfigDBSessionFactory };
signature = new string[] { "" };
break;
case RemoteDBUse.RemoteDBOnly:
- dBase = new Common.DBKind[] { Common.DBKind.RemoteConfig };
+ dBase = new ISessionFactory[] { TBF.DB.SharedDBSessionFactory };
signature = new string[] { "R" };
break;
case RemoteDBUse.BothDBsLocalFirst:
- dBase = new Common.DBKind[] { Common.DBKind.Config, Common.DBKind.RemoteConfig };
+ dBase = new ISessionFactory[] { TBF.DB.ConfigDBSessionFactory, TBF.DB.SharedDBSessionFactory };
signature = new string[] { "L", "R" };
break;
case RemoteDBUse.BothDBsRemoteFirst:
- dBase = new Common.DBKind[] { Common.DBKind.RemoteConfig, Common.DBKind.Config };
+ dBase = new ISessionFactory[] { TBF.DB.SharedDBSessionFactory, TBF.DB.ConfigDBSessionFactory };
signature = new string[] { "R", "L" };
break;
}
@@ -625,23 +638,30 @@ namespace TBF.UI
ProcedureNrs.Clear();
for (int i = 0; i < dBase.Length; i++)
{
- IList procedures = TBF.DB.CreateSession(dBase[i])
- .QueryOver()
- .Where(x => (x.ProcedureState == ProcedureState.Active))
- .OrderBy(x => x.ItemNr).Asc
- .List();
- foreach (var proc in procedures)
+ if (dBase[i] != null)
{
- string itemText = string.Format("{0}{1}{2}{3}", signature[i], proc.ItemNr + 1, ProcSeparator, proc.Name);
- procedureComboBox.Items.Add(itemText);
- if (!ProcedureNrs.ContainsKey(proc.Name)) ProcedureNrs.Add(proc.Name, proc.ItemNr + 1);
+ var session = dBase[i].OpenSession();
+ var procedures = session.QueryOver()
+ .Where(x => (x.ProcedureState == ProcedureState.Active))
+ .OrderBy(x => x.ItemNr).Asc
+ .List();
- if ((procedureNameToSelect == proc.Name) && !procedureSet)
+ foreach (var proc in procedures)
{
- procedureComboBox.Text = itemText;
- SelectedProcedure = new ProcedureInfo(procedureNameToSelect, (dBase[i] == Common.DBKind.RemoteConfig));
- procedureSet = true;
+ string itemText = string.Format("{0}{1}{2}{3}", signature[i], proc.ItemNr + 1, ProcSeparator, proc.Name);
+ procedureComboBox.Items.Add(itemText);
+ if (!ProcedureNrs.ContainsKey(proc.Name)) ProcedureNrs.Add(proc.Name, proc.ItemNr + 1);
+
+ if ((procedureNameToSelect == proc.Name) && !procedureSet)
+ {
+ procedureComboBox.Text = itemText;
+ SelectedProcedure = new ProcedureInfo(procedureNameToSelect, (dBase[i] == TBF.DB.SharedDBSessionFactory));
+ BenchControlPanel.ReloadTests(session);
+ procedureSet = true;
+ }
}
+
+ session.Close();
}
}
@@ -652,8 +672,6 @@ namespace TBF.UI
}
ProceduresUpdated = false;
-
- if (SelectedProcedure != null) BenchControlPanel.ReloadTests();
}
else
{
@@ -861,7 +879,7 @@ namespace TBF.UI
Common.GID[] reqGrpMembership = null;
#endif
- if (new Users.Forms.LoginDlg(reqGrpMembership, this).ShowDialog() == DialogResult.OK)
+ if (new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, reqGrpMembership, this).ShowDialog() == DialogResult.OK)
{
UpdateUser();
}
diff --git a/TBF/UI/Procedures/ProcedureDlg.cs b/TBF/UI/Procedures/ProcedureDlg.cs
index 77be687e1..e013e7681 100644
--- a/TBF/UI/Procedures/ProcedureDlg.cs
+++ b/TBF/UI/Procedures/ProcedureDlg.cs
@@ -19,6 +19,7 @@ using TBF.Rig.GenericDevices;
using TBF.Resources;
using TBF.UI.Shared;
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
+using NHibernate;
namespace TBF.UI.Procedures
{
@@ -47,7 +48,10 @@ namespace TBF.UI.Procedures
IList usedNames; /// Already used names
+ ///
/// Auxiliary public lists used also by user controls in tab pages
+ ///
+ public ISession Session; /// DB session from the form or control that created this form
public IList TbfComponents;
public IList Valves;
public IList RegulValves;
@@ -118,9 +122,10 @@ namespace TBF.UI.Procedures
SelectedTestIx = -1;
}
- public ProcedureDlg(Procedure procedure, IList usedNames, Mode initialMode, Form parentForm)
+ public ProcedureDlg(ISession session, Procedure procedure, IList usedNames, Mode initialMode, Form parentForm)
: this()
{
+ this.Session = session;
if (procedure == null) throw new ArgumentNullException("procedure");
LoadedProcedure = procedure;
@@ -139,69 +144,66 @@ namespace TBF.UI.Procedures
#endif
if (initialMode == Mode.PermanentlyLocked) sharedButtons.DisableUnlock();
- using (NHibernate.ISession session = TBF.DB.CreateSession(DBKind.Config))
+ ///
+ /// Prepare a list of components and a list of all valves in the test bench
+ ///
+ TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(Session);
+ Valves = Rig.GenericDevices.ValveBase.MasterValves(TbfComponents);
+ RegulValves = new List();
+ TestMethods = new List();
+ TempControllers = new List();
+ dataEntryComboBox.Items.Add("---");
+ printer1ComboBox.Items.Add("---");
+ printer2ComboBox.Items.Add("---");
+ fileWriter1ComboBox.Items.Add("---");
+ fileWriter2ComboBox.Items.Add("---");
+ fileWriter3ComboBox.Items.Add("---");
+ fileWriter4ComboBox.Items.Add("---");
+ fileWriter5ComboBox.Items.Add("---");
+ eventTrigger1ComboBox.Items.Add("---");
+ eventTrigger2ComboBox.Items.Add("---");
+ eventTrigger3ComboBox.Items.Add("---");
+
+ foreach (var cmpnt in TbfComponents)
{
- ///
- /// Prepare a list of components and a list of all valves in the test bench
- ///
- TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(session);
- Valves = Rig.GenericDevices.ValveBase.MasterValves(TbfComponents);
- RegulValves = new List();
- TestMethods = new List();
- TempControllers = new List();
- dataEntryComboBox.Items.Add("---");
- printer1ComboBox.Items.Add("---");
- printer2ComboBox.Items.Add("---");
- fileWriter1ComboBox.Items.Add("---");
- fileWriter2ComboBox.Items.Add("---");
- fileWriter3ComboBox.Items.Add("---");
- fileWriter4ComboBox.Items.Add("---");
- fileWriter5ComboBox.Items.Add("---");
- eventTrigger1ComboBox.Items.Add("---");
- eventTrigger2ComboBox.Items.Add("---");
- eventTrigger3ComboBox.Items.Add("---");
-
- foreach (var cmpnt in TbfComponents)
- {
- if (cmpnt is IRegValve) RegulValves.Add(cmpnt as IRegValve);
- if (cmpnt is ITestMethod) TestMethods.Add(cmpnt as ITestMethod);
- if (cmpnt is ITempControl) TempControllers.Add(cmpnt as ITempControl);
- if (cmpnt is IDataEntry) dataEntryComboBox.Items.Add(cmpnt.Cfg.Name);
- if (cmpnt is IResultsPrinter)
- {
- printer1ComboBox.Items.Add(cmpnt.Cfg.Name);
- printer2ComboBox.Items.Add(cmpnt.Cfg.Name);
- }
- if (cmpnt is IResultsWriter)
- {
- fileWriter1ComboBox.Items.Add(cmpnt.Cfg.Name);
- fileWriter2ComboBox.Items.Add(cmpnt.Cfg.Name);
- fileWriter3ComboBox.Items.Add(cmpnt.Cfg.Name);
- fileWriter4ComboBox.Items.Add(cmpnt.Cfg.Name);
- fileWriter5ComboBox.Items.Add(cmpnt.Cfg.Name);
- }
- if (cmpnt is IEventTrigger)
- {
- eventTrigger1ComboBox.Items.Add(cmpnt.Cfg.Name);
- eventTrigger2ComboBox.Items.Add(cmpnt.Cfg.Name);
- eventTrigger3ComboBox.Items.Add(cmpnt.Cfg.Name);
- }
+ if (cmpnt is IRegValve) RegulValves.Add(cmpnt as IRegValve);
+ if (cmpnt is ITestMethod) TestMethods.Add(cmpnt as ITestMethod);
+ if (cmpnt is ITempControl) TempControllers.Add(cmpnt as ITempControl);
+ if (cmpnt is IDataEntry) dataEntryComboBox.Items.Add(cmpnt.Cfg.Name);
+ if (cmpnt is IResultsPrinter)
+ {
+ printer1ComboBox.Items.Add(cmpnt.Cfg.Name);
+ printer2ComboBox.Items.Add(cmpnt.Cfg.Name);
}
+ if (cmpnt is IResultsWriter)
+ {
+ fileWriter1ComboBox.Items.Add(cmpnt.Cfg.Name);
+ fileWriter2ComboBox.Items.Add(cmpnt.Cfg.Name);
+ fileWriter3ComboBox.Items.Add(cmpnt.Cfg.Name);
+ fileWriter4ComboBox.Items.Add(cmpnt.Cfg.Name);
+ fileWriter5ComboBox.Items.Add(cmpnt.Cfg.Name);
+ }
+ if (cmpnt is IEventTrigger)
+ {
+ eventTrigger1ComboBox.Items.Add(cmpnt.Cfg.Name);
+ eventTrigger2ComboBox.Items.Add(cmpnt.Cfg.Name);
+ eventTrigger3ComboBox.Items.Add(cmpnt.Cfg.Name);
+ }
+ }
- ///
- /// Loads paths, this must be done before PrepareMetrology12AndProcessTabs() call
- ///
- feedingPaths = session.QueryOver().List();
- benchPaths = session.QueryOver().List();
- outputPaths = session.QueryOver().List();
- metersPaths = session.QueryOver().List();
+ ///
+ /// Loads paths, this must be done before PrepareMetrology12AndProcessTabs() call
+ ///
+ feedingPaths = Session.QueryOver().List();
+ benchPaths = Session.QueryOver().List();
+ outputPaths = Session.QueryOver().List();
+ metersPaths = Session.QueryOver().List();
#if HEAT_METERS
- heatMetersPaths = session.QueryOver().List();
+ heatMetersPaths = Session.QueryOver().List();
#else
- heatMetersPaths = new List();
+ heatMetersPaths = new List();
#endif
- transitionSequences = session.QueryOver().List();
- }
+ transitionSequences = Session.QueryOver().List();
transitionStartComboBox.Items.Add("---");
transitionEndComboBox.Items.Add("---");
@@ -398,41 +400,50 @@ namespace TBF.UI.Procedures
lastChangedByTextBox.ReadOnly = true;
lastChangedOnTextBox.ReadOnly = true;
- foreach (var test in LoadedProcedure.Tests)
+ try
{
- test.VolumeUnit = TBF.Rig.Sequences.ProcessData.VolumeUnit;
- test.FlowUnit = TBF.Rig.Sequences.ProcessData.FlowUnit;
- test.MassUnit = TBF.Rig.Sequences.ProcessData.MassUnit;
- test.TempUnit = TBF.Rig.Sequences.ProcessData.TempUnit;
- test.PressUnit = TBF.Rig.Sequences.ProcessData.PressUnit;
- test.LengthUnit = TBF.Rig.Sequences.ProcessData.LengthUnit;
- test.ResetChngdFlags();
- }
+ foreach (var test in LoadedProcedure.Tests)
+ {
+ test.VolumeUnit = TBF.Rig.Sequences.ProcessData.VolumeUnit;
+ test.FlowUnit = TBF.Rig.Sequences.ProcessData.FlowUnit;
+ test.MassUnit = TBF.Rig.Sequences.ProcessData.MassUnit;
+ test.TempUnit = TBF.Rig.Sequences.ProcessData.TempUnit;
+ test.PressUnit = TBF.Rig.Sequences.ProcessData.PressUnit;
+ test.LengthUnit = TBF.Rig.Sequences.ProcessData.LengthUnit;
+ test.ResetChngdFlags();
+ }
- /// History tab
- InitializeHistoryTab(); /// Create ListViewEx columns for 'History of changes'
+ /// History tab
+ InitializeHistoryTab(); /// Create ListViewEx columns for 'History of changes'
- /// LisViewEx columns and edit controls for 'Metrology1', 'Metrology2', 'Process' and 'Parameters' tabs
- PrepareMetrology1Tab();
- PrepareMetrology2Tab();
- PrepareProcess();
- PrepareParameters();
+ /// LisViewEx columns and edit controls for 'Metrology1', 'Metrology2', 'Process' and 'Parameters' tabs
+ PrepareMetrology1Tab();
+ PrepareMetrology2Tab();
+ PrepareProcess();
+ PrepareParameters();
- /// Now refresh the content of the dialog
- RefreshGeneralTab();
- RefreshMetrology1Tab();
- RefreshMetrology2Tab();
- RefreshProcessTab();
- RefreshParametersTab();
+ /// Now refresh the content of the dialog
+ RefreshGeneralTab();
+ RefreshMetrology1Tab();
+ RefreshMetrology2Tab();
+ RefreshProcessTab();
+ RefreshParametersTab();
- foreach (var ctrl in testParamsCtrls)
- {
- ctrl.Initialize();
- }
- foreach (var ctrl in procedureParamsCtrls)
- {
- ctrl.Initialize();
- }
+ foreach (var ctrl in testParamsCtrls)
+ {
+ ctrl.Initialize();
+ }
+ foreach (var ctrl in procedureParamsCtrls)
+ {
+ ctrl.Initialize();
+ }
+ }
+ catch (Exception exc)
+ {
+ MessageBox.Show(string.Format("{0}:{1}{2}",
+ Strings.Error_reading_configuration_database, Environment.NewLine, exc.Message),
+ Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
+ }
/// Optionally unlock this dialog
if (initialMode == Mode.Unlocked)
@@ -712,19 +723,16 @@ namespace TBF.UI.Procedures
void RefreshHistoryTab()
{
- NHibernate.ISession session = TBF.DB.CreateSession(DBKind.Config);
- IList procedures = session
- .QueryOver()
- .Where(x => x.ProcedureState == ProcedureState.History)
- .List();
+ var procedures = Session.QueryOver()
+ .Where(x => x.ProcedureState == ProcedureState.History)
+ .List();
int predecessorId = LoadedProcedure.PredecessorId;
- IList oneProcedure = session
- .QueryOver()
- .Where(x => (x.ProcedureState == ProcedureState.Active))
- .And(x => (x.Id == predecessorId))
- .List();
+ var oneProcedure = Session.QueryOver()
+ .Where(x => (x.ProcedureState == ProcedureState.Active))
+ .And(x => (x.Id == predecessorId))
+ .List();
if (oneProcedure.Count == 1)
{
@@ -762,7 +770,7 @@ namespace TBF.UI.Procedures
}
if (!found) break;
}
- }
+ }
void UpdateFromHistoryTab()
{
@@ -3002,8 +3010,8 @@ namespace TBF.UI.Procedures
break;
}
- using (NHibernate.ISession session = TBF.DB.CreateSession(DBKind.Config))
- {
+ try
+ {
IList testsToBeUpdated = new List();
foreach (var test in LoadedProcedure.Tests)
@@ -3149,6 +3157,12 @@ namespace TBF.UI.Procedures
}
}
}
+ catch (Exception exc)
+ {
+ MessageBox.Show(string.Format("{0}:{1}{2}",
+ Strings.Error_reading_configuration_database, Environment.NewLine, exc.Message),
+ Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
+ }
}
private void historyListViewEx_MouseDoubleClick(object sender, MouseEventArgs e)
@@ -3158,7 +3172,7 @@ namespace TBF.UI.Procedures
if (lvi.Tag is Procedure)
{
- (new ProcedureDlg(lvi.Tag as Procedure, new List(), ProcedureDlg.Mode.PermanentlyLocked, sharedButtons.ParentForm)).ShowDialog();
+ (new ProcedureDlg(Session, lvi.Tag as Procedure, new List(), ProcedureDlg.Mode.PermanentlyLocked, sharedButtons.ParentForm)).ShowDialog();
}
}
diff --git a/TBF/UI/Procedures/ProcedureDlg.resx b/TBF/UI/Procedures/ProcedureDlg.resx
index 0878d8839..e6b8a33dd 100644
--- a/TBF/UI/Procedures/ProcedureDlg.resx
+++ b/TBF/UI/Procedures/ProcedureDlg.resx
@@ -2170,7 +2170,7 @@
sharedButtons
- TBF.UI.Shared.SharedButtons, TBF, Version=2.27.1917.0, Culture=neutral, PublicKeyToken=null
+ TBF.UI.Shared.SharedButtons, TBF, Version=2.32.2027.0, Culture=neutral, PublicKeyToken=null
mainSplitContainer.Panel2
diff --git a/TBF/UI/Procedures/ProceduresCtrl.cs b/TBF/UI/Procedures/ProceduresCtrl.cs
index a3ea40f6d..2355d0942 100644
--- a/TBF/UI/Procedures/ProceduresCtrl.cs
+++ b/TBF/UI/Procedures/ProceduresCtrl.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2020-2022 Sensus Slovensko a.s.
+/// Copyright (c) 2020-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -20,6 +20,12 @@ namespace TBF.UI.Procedures
{
static readonly ILog log = LogManager.GetLogger(typeof(ProceduresCtrl));
+ ProceduresDlg parent; /// parent form
+ Control parentControl; /// parent control (split container)
+
+ /// Database session from the parent form
+ public ISession Session { get { return parent.Session; } }
+
///
/// List of all active procedures
///
@@ -60,11 +66,8 @@ namespace TBF.UI.Procedures
Count
}
- ProceduresDlg parent;
- Control parentControl;
Control[] editors;
- ISession session;
IWaterMeter waterMeterCmpnt;
IErrorFlags errorFlagsCmpnt;
@@ -72,7 +75,6 @@ namespace TBF.UI.Procedures
{
InitializeComponent();
- session = null;
waterMeterCmpnt = null;
errorFlagsCmpnt = null;
ToBeRemovedProcedures = new List();
@@ -115,9 +117,6 @@ namespace TBF.UI.Procedures
public void Initialize(ProceduresDlg parent, Control parentControl)
{
if (parent == null) return;
-
- /// Create a DB session
- session = TBF.DB.CreateSession(DBKind.Config);
this.parent = parent;
this.parentControl = parentControl;
@@ -168,7 +167,7 @@ namespace TBF.UI.Procedures
if (isFirstTime)
{
/// Find WaterMeter and ErrorFlags components, this is done just once when AllProcedures == null
- foreach (var cmpnt in TBF.Rig.TbfComponents.LoadComponentsFromDB(session))
+ foreach (var cmpnt in TBF.Rig.TbfComponents.LoadComponentsFromDB(Session))
{
if (waterMeterCmpnt == null && cmpnt is IWaterMeter) waterMeterCmpnt = cmpnt as IWaterMeter;
if (errorFlagsCmpnt == null && cmpnt is IErrorFlags) errorFlagsCmpnt = cmpnt as IErrorFlags;
@@ -176,7 +175,7 @@ namespace TBF.UI.Procedures
}
/// (Re)Load all procedures unconditionally
- AllProcedures = session.QueryOver()
+ AllProcedures = Session.QueryOver()
.Where(x => (x.ProcedureState == ProcedureState.Active))
.OrderBy(x => x.ItemNr).Asc
.List();
@@ -269,22 +268,22 @@ namespace TBF.UI.Procedures
///
public void OkBtnClicked()
{
- using (ITransaction transaction = session.BeginTransaction())
+ using (ITransaction transaction = Session.BeginTransaction())
{
try
{
- foreach (var entity in ToBeRemovedProcedures) session.Delete(entity);
+ foreach (var entity in ToBeRemovedProcedures) Session.Delete(entity);
ToBeRemovedProcedures.Clear();
int itemNr = 0;
foreach (var proc in AllProcedures)
{
(proc as Procedure).ItemNr = itemNr++;
- session.SaveOrUpdate(proc);
+ Session.SaveOrUpdate(proc);
}
transaction.Commit();
- session.Flush();
+ Session.Flush();
}
catch (Exception exc)
{
@@ -328,12 +327,12 @@ namespace TBF.UI.Procedures
newProcedure.CreationUser = Users.CurrentUser.UserName();
newProcedure.CreationTime = DateTime.Now;
- if (new ProcedureDlg(newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent).ShowDialog() == DialogResult.OK)
+ if (new ProcedureDlg(Session, newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent).ShowDialog() == DialogResult.OK)
{
/// TODO: Make name uniqueness test
parent.Unlock();
- using (var transaction = session.BeginTransaction())
+ using (var transaction = Session.BeginTransaction())
{
try
{
@@ -341,7 +340,7 @@ namespace TBF.UI.Procedures
newProcedure.LastChgTime = DateTime.Now;
DoAddOne(newProcedure);
- session.SaveOrUpdate(newProcedure);
+ Session.SaveOrUpdate(newProcedure);
transaction.Commit();
MessageBox.Show(string.Format(Strings.Procedure_0_added, newProcedure.Name),
@@ -393,22 +392,22 @@ namespace TBF.UI.Procedures
}
/// Update the database
- using (ITransaction transaction = session.BeginTransaction())
+ using (ITransaction transaction = Session.BeginTransaction())
{
try
{
- foreach (var entity in ToBeRemovedProcedures) session.Delete(entity);
+ foreach (var entity in ToBeRemovedProcedures) Session.Delete(entity);
ToBeRemovedProcedures.Clear();
int itemNr = 0;
foreach (var entity in Procedures)
{
(entity as Procedure).ItemNr = itemNr++;
- session.SaveOrUpdate(entity);
+ Session.SaveOrUpdate(entity);
}
transaction.Commit();
- session.Flush();
+ Session.Flush();
}
catch (Exception exc)
{
@@ -565,11 +564,11 @@ namespace TBF.UI.Procedures
IList usedNames = GetUsedNames(false);
usedNames.Remove(originalProcedure.Name.ToLower()); /// Allow original procedure name
///
- if (new ProcedureDlg(modifiedProcedure, usedNames, ProcedureDlg.Mode.Locked, parent).ShowDialog() == DialogResult.OK)
+ if (new ProcedureDlg(Session, modifiedProcedure, usedNames, ProcedureDlg.Mode.Locked, parent).ShowDialog() == DialogResult.OK)
{
parent.Unlock();
- using (var transaction = session.BeginTransaction())
+ using (var transaction = Session.BeginTransaction())
{
try
{
@@ -577,8 +576,8 @@ namespace TBF.UI.Procedures
modifiedProcedure.LastChgUser = Users.CurrentUser.UserName();
modifiedProcedure.LastChgTime = DateTime.Now;
- session.SaveOrUpdate(originalProcedure);
- session.SaveOrUpdate(modifiedProcedure);
+ Session.SaveOrUpdate(originalProcedure);
+ Session.SaveOrUpdate(modifiedProcedure);
transaction.Commit();
listViewEx.SelectedItems[0].Tag = modifiedProcedure;
@@ -595,7 +594,7 @@ namespace TBF.UI.Procedures
transaction.Rollback();
}
}
- session.Flush();
+ Session.Flush();
}
ReloadAndRedrawAll();
@@ -620,18 +619,18 @@ namespace TBF.UI.Procedures
newProcedure.CreationTime = DateTime.Now;
newProcedure.Protected = false;
- if ((new ProcedureDlg(newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent)).ShowDialog() == DialogResult.OK)
+ if ((new ProcedureDlg(Session, newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent)).ShowDialog() == DialogResult.OK)
{
/// TODO: Make name uniqueness test
parent.Unlock();
- using (var transaction = session.BeginTransaction())
+ using (var transaction = Session.BeginTransaction())
{
newProcedure.LastChgUser = Users.CurrentUser.UserName();
newProcedure.LastChgTime = DateTime.Now;
DoAddOne(newProcedure);
- session.SaveOrUpdate(newProcedure);
+ Session.SaveOrUpdate(newProcedure);
transaction.Commit();
MessageBox.Show(string.Format(Strings.Procedure_0_added, newProcedure.Name),
@@ -673,18 +672,18 @@ namespace TBF.UI.Procedures
newProcedure.CreationUser = Users.CurrentUser.UserName();
newProcedure.CreationTime = DateTime.Now;
- if ((new ProcedureDlg(newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent)).ShowDialog() == DialogResult.OK)
+ if ((new ProcedureDlg(Session, newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent)).ShowDialog() == DialogResult.OK)
{
/// TODO: Make name uniqueness test
parent.Unlock();
- using (var transaction = session.BeginTransaction())
+ using (var transaction = Session.BeginTransaction())
{
newProcedure.LastChgUser = Users.CurrentUser.UserName();
newProcedure.LastChgTime = DateTime.Now;
DoAddOne(newProcedure);
- session.SaveOrUpdate(newProcedure);
+ Session.SaveOrUpdate(newProcedure);
transaction.Commit();
MessageBox.Show(string.Format(Strings.Procedure_0_added, newProcedure.Name),
@@ -725,12 +724,12 @@ namespace TBF.UI.Procedures
try
{
- profiles = session.QueryOver()
+ profiles = Session.QueryOver()
.OrderBy(x => x.ItemNr).Asc
.List();
- fPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
- bPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
- oPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
+ fPaths = Session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
+ bPaths = Session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
+ oPaths = Session.QueryOver().OrderBy(x => x.ItemNr).Asc.List();
}
catch (Exception)
{
@@ -759,11 +758,11 @@ namespace TBF.UI.Procedures
IList errorFlagsParamsOfCreatedTests = new List();
IList waterMeterParamsOfNewProcedure = new List();
- IList cmpntEntities = session.QueryOver()
+ IList cmpntEntities = Session.QueryOver()
.OrderBy(x => x.ItemNr).Asc
.List();
- IList components = Rig.TbfComponents.LoadComponentsFromDB(session);
+ IList components = Rig.TbfComponents.LoadComponentsFromDB(Session);
foreach (var cmptn in components)
{
if (cmptn.ClassName == "WaterMeter")
@@ -845,12 +844,12 @@ namespace TBF.UI.Procedures
newProcedure.CreationUser = Users.CurrentUser.UserName();
newProcedure.CreationTime = DateTime.Now;
- if (new ProcedureDlg(newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent).ShowDialog() == DialogResult.OK)
+ if (new ProcedureDlg(Session, newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent).ShowDialog() == DialogResult.OK)
{
/// TODO: Make name uniqueness test
parent.Unlock();
- using (var transaction = session.BeginTransaction())
+ using (var transaction = Session.BeginTransaction())
{
try
{
@@ -858,7 +857,7 @@ namespace TBF.UI.Procedures
newProcedure.LastChgTime = DateTime.Now;
DoAddOne(newProcedure);
- session.SaveOrUpdate(newProcedure);
+ Session.SaveOrUpdate(newProcedure);
foreach (var efp in errorFlagsParamsOfCreatedTests)
{
@@ -1086,7 +1085,7 @@ namespace TBF.UI.Procedures
case MoreContent.Oracle:
if (!string.IsNullOrEmpty(procedure.ResultsWriter) && procedure.ResultsWriter.Contains("Sensus-Oracle-DB"))
{
- var procParamsEntity = session.QueryOver()
+ var procParamsEntity = Session.QueryOver()
.Where(x => x.Procedure == procedure)
.And(x => x.CmpntName == "Sensus-Oracle-DB")
.List();
diff --git a/TBF/UI/Procedures/ProceduresDlg.cs b/TBF/UI/Procedures/ProceduresDlg.cs
index 414528d07..8b2f452fd 100644
--- a/TBF/UI/Procedures/ProceduresDlg.cs
+++ b/TBF/UI/Procedures/ProceduresDlg.cs
@@ -1,9 +1,10 @@
///
-/// Copyright (c) 2013-2022 Sensus Slovensko a.s.
+/// Copyright (c) 2013-2023 Sensus Slovensko a.s.
///
using System;
using System.Windows.Forms;
using log4net;
+using NHibernate;
using Common;
using Common.Forms;
using TBF.Resources;
@@ -18,6 +19,8 @@ namespace TBF.UI.Procedures
/// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi
public readonly int Dpi;
+ public ISession Session; /// DB session is open in the constructor and closed in _FormClosing handler
+
public ProceduresDlg()
{
/// Detect display setting: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi.
@@ -25,6 +28,14 @@ namespace TBF.UI.Procedures
InitializeComponent();
+ /// Open a database session
+ try { Session = TBF.DB.ConfigDBSessionFactory.OpenSession(); }
+ catch (Exception e)
+ {
+ MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message,
+ Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
+ }
+
/// SharedDlgButtons configuration
sharedButtons.ParentForm = this;
sharedButtons.RequiredGroupMembership = new GID[] { GID.TestingSpecialists, GID.Metrologists };
@@ -112,6 +123,7 @@ namespace TBF.UI.Procedures
}
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
+ if (Session != null && Session.IsOpen) Session.Close();
}
diff --git a/TBF/UI/ResultsMI/PreviousResultCtrl.cs b/TBF/UI/ResultsMI/PreviousResultCtrl.cs
index 0a19f6195..a065243b4 100644
--- a/TBF/UI/ResultsMI/PreviousResultCtrl.cs
+++ b/TBF/UI/ResultsMI/PreviousResultCtrl.cs
@@ -131,7 +131,7 @@ namespace TBF.UI.ResultsMI
/// Access only to thise who manage production tracing
GID[] rqrdGroupMembership = new GID[] { GID.TraceabilityManagement };
- if ((new Users.Forms.LoginDlg(Users.CurrentUser.UserName(), rqrdGroupMembership, parent)).ShowDialog() != DialogResult.OK)
+ if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, Users.CurrentUser.UserName(), rqrdGroupMembership, parent)).ShowDialog() != DialogResult.OK)
{
return;
}
diff --git a/TBF/UI/ResultsMI/PreviousResultsDlg.cs b/TBF/UI/ResultsMI/PreviousResultsDlg.cs
index 14f5aa16b..14bc61f44 100644
--- a/TBF/UI/ResultsMI/PreviousResultsDlg.cs
+++ b/TBF/UI/ResultsMI/PreviousResultsDlg.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2016-2021 Sensus Slovensko a.s.
+/// Copyright (c) 2016-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -14,11 +14,11 @@ using Oracle.DataAccess.Client;
using Common;
using Results;
using Results.Entities;
+using TBF.Resources;
using TBF.Rig.Generic;
using TBF.Rig.GenericDevices;
using TBF.Rig.Output.DB.SensusOracle;
using TBF.Rig.Sequences;
-using TBF.Resources;
namespace TBF.UI.ResultsMI
{
@@ -33,20 +33,20 @@ namespace TBF.UI.ResultsMI
{
static readonly ILog log = LogManager.GetLogger(typeof(PreviousResultsDlg));
- ISession session;
- int currentBatchNr;
+ readonly PreviousResultsMode mode;
+ readonly int currentBatchNr;
+ ISession session;
IList batches; /// A list of batches selected from all batches using criteria entered in UI
IList serialNrs; /// Display only watermeters with these serial numbers (null = display all)
int lastDisplayedIx; /// Index of the last displayed batch from the list 'batches'
const int LinesCount = 25; /// Number of batches displayed on one screen
- PreviousResultsMode mode;
-
public PreviousResultsDlg(PreviousResultsMode mode)
{
InitializeComponent();
+
this.mode = mode;
currentBatchNr = Program.LocalSettings.BatchNr;
@@ -74,7 +74,7 @@ namespace TBF.UI.ResultsMI
{
}
- private void PreviousResultsDlg_Load(object sender, EventArgs e)
+ private void PreviousResultsDlg_Load(object sender, EventArgs args)
{
Localize();
@@ -90,14 +90,11 @@ namespace TBF.UI.ResultsMI
toDateTimePicker.CustomFormat = Constants.DateFormat;
toDateTimePicker.ShowUpDown = true;
- try
+ try { session = TBF.DB.ResultsDBSessionFactory.OpenSession(); }
+ catch (Exception e)
{
- session = Results.DB.CreateSession();
- }
- catch (Exception exc)
- {
- session = null;
- log.ErrorFormat("Opening Results DB failed: {0}", exc.Message);
+ MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message,
+ Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
batches = GetFilteredBatches(out lastDisplayedIx, out serialNrs);
@@ -129,7 +126,7 @@ namespace TBF.UI.ResultsMI
if (string.IsNullOrEmpty(procedureTextBox.Text) && string.IsNullOrEmpty(snTextBox.Text))
{
rslt = session.QueryOver()
- .Where(x => (x.StartTime >= fromDateTimePicker.Value))
+ .Where(x => (x.EndTime >= fromDateTimePicker.Value))
.And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1)))
.OrderBy(x => x.BatchNr).Asc
.List();
@@ -137,7 +134,7 @@ namespace TBF.UI.ResultsMI
else if (string.IsNullOrEmpty(snTextBox.Text))
{
rslt = session.QueryOver()
- .Where(x => (x.StartTime >= fromDateTimePicker.Value))
+ .Where(x => (x.EndTime >= fromDateTimePicker.Value))
.And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1)))
.And(x => (x.ProcedureName == procedureTextBox.Text))
.OrderBy(x => x.BatchNr).Asc
@@ -146,7 +143,7 @@ namespace TBF.UI.ResultsMI
else if (string.IsNullOrEmpty(procedureTextBox.Text))
{
rslt = session.QueryOver()
- .Where(x => (x.StartTime >= fromDateTimePicker.Value))
+ .Where(x => (x.EndTime >= fromDateTimePicker.Value))
.And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1)))
.OrderBy(x => x.BatchNr).Asc
.JoinQueryOver(b => b.WaterMeters)
@@ -156,7 +153,7 @@ namespace TBF.UI.ResultsMI
else
{
rslt = session.QueryOver()
- .Where(x => (x.StartTime >= fromDateTimePicker.Value))
+ .Where(x => (x.EndTime >= fromDateTimePicker.Value))
.And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1)))
.And(x => (x.ProcedureName == procedureTextBox.Text))
.OrderBy(x => x.BatchNr).Asc
@@ -438,7 +435,6 @@ namespace TBF.UI.ResultsMI
private void closeButton_Click(object sender, EventArgs e)
{
- if (session != null) session.Close();
DialogResult = DialogResult.Cancel;
Close();
}
@@ -473,6 +469,7 @@ namespace TBF.UI.ResultsMI
private void PreviousResultsDlg_FormClosing(object sender, FormClosingEventArgs e)
{
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
+ if (session != null && session.IsOpen) session.Close();
}
}
}
diff --git a/TBF/UI/ResultsMI/ResultsArrangementDlg.cs b/TBF/UI/ResultsMI/ResultsArrangementDlg.cs
index 56bba4a10..18e9c432e 100644
--- a/TBF/UI/ResultsMI/ResultsArrangementDlg.cs
+++ b/TBF/UI/ResultsMI/ResultsArrangementDlg.cs
@@ -1,11 +1,12 @@
///
-/// Copyright (c) 2013-2017 Sensus Slovensko a.s.
+/// Copyright (c) 2013-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Common;
using Results;
+using Users.Forms;
using TBF.Resources;
namespace TBF.UI.ResultsMI
@@ -92,13 +93,14 @@ namespace TBF.UI.ResultsMI
{
if (!Users.CurrentUser.IsMemberOf(RequiredGroupMembership))
{
- if ((new Users.Forms.LoginDlg(RequiredGroupMembership, this)).ShowDialog() != DialogResult.OK)
- return;
+ if (DialogResult.OK != (new LoginDlg(TBF.DB.UserSessionFactories,
+ RequiredGroupMembership, this)).ShowDialog()) return;
}
else if (Program.LocalSettings.AlwaysAskPasswdWhenUnlocking)
{
- if ((new Users.Forms.LoginDlg(Users.CurrentUser.UserName(), RequiredGroupMembership, this)).ShowDialog() != DialogResult.OK)
- return;
+ if (DialogResult.OK != (new LoginDlg(TBF.DB.UserSessionFactories,
+ Users.CurrentUser.UserName(),
+ RequiredGroupMembership, this)).ShowDialog()) return;
}
Unlocked = true;
diff --git a/TBF/UI/ResultsMI/ResultsTabPageCtrl.cs b/TBF/UI/ResultsMI/ResultsTabPageCtrl.cs
index e27455f10..cd2f64c6b 100644
--- a/TBF/UI/ResultsMI/ResultsTabPageCtrl.cs
+++ b/TBF/UI/ResultsMI/ResultsTabPageCtrl.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2013-2019 Sensus Slovensko a.s.
+/// Copyright (c) 2013-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
@@ -8,7 +8,6 @@ using System.Windows.Forms;
using log4net;
using NHibernate;
using Common;
-using Common.Forms;
using Results;
using Results.Forms;
using Results.Entities;
@@ -647,7 +646,7 @@ namespace TBF.UI.ResultsMI
var dlg = new DeleteFromOracleForm();
GID[] rqrdGroupMembership = new GID[] { GID.TraceabilityManagement }; /// Restricted access to Delete from Oracle Form
- if ((new Users.Forms.LoginDlg(Users.CurrentUser.UserName(), rqrdGroupMembership, dlg)).ShowDialog() == DialogResult.OK)
+ if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, Users.CurrentUser.UserName(), rqrdGroupMembership, dlg)).ShowDialog() == DialogResult.OK)
{
if (dlg.ShowDialog() == DialogResult.OK) MessageBox.Show("Successfully deleted from Oracle");
}
diff --git a/TBF/UI/Settings/DatabaseSettingsDlg.cs b/TBF/UI/Settings/DatabaseSettingsDlg.cs
index 7f88b4525..0da75deaf 100644
--- a/TBF/UI/Settings/DatabaseSettingsDlg.cs
+++ b/TBF/UI/Settings/DatabaseSettingsDlg.cs
@@ -191,7 +191,7 @@ namespace TBF.UI.Settings
log.ErrorFormat("Going to create an empty configuration database '{0}'", databaseName);
ExecuteMySqlCmd(string.Format("DROP DATABASE `{0}`;", databaseName), userName, password);
ExecuteMySqlCmd(string.Format("CREATE DATABASE `{0}` CHARACTER SET utf8 COLLATE utf8_unicode_ci;", databaseName), userName, password);
- Config.FluentCommon.CreateEmptyConfigDB(bench.ProceduresDBSettings.DbType, connectionString);
+ TBF.DB.CreateEmptyConfigDB(bench.ProceduresDBSettings.DbType, connectionString);
log.ErrorFormat("An empty configuration database '{0}' was created", databaseName);
MessageBox.Show(Strings.DB_was_successfully_created, Strings.Notification);
diff --git a/TBF/UI/Settings/UpgradeSelectionDlg.cs b/TBF/UI/Settings/UpgradeSelectionDlg.cs
index 0222b1dfb..9bcd62830 100644
--- a/TBF/UI/Settings/UpgradeSelectionDlg.cs
+++ b/TBF/UI/Settings/UpgradeSelectionDlg.cs
@@ -116,7 +116,7 @@ namespace TBF.UI.Settings
try
{
- session = TBF.DB.CreateSession(Common.DBKind.Config);
+ session = TBF.DB.ConfigDBSessionFactory.OpenSession();
var testParams = session.QueryOver()
.Where(x => (x.CmpntName == errorFlagsCmpntName))
@@ -144,6 +144,7 @@ namespace TBF.UI.Settings
}
session.Flush();
+ session.Close();
success = true;
}
catch (Exception exc)
@@ -992,9 +993,10 @@ namespace TBF.UI.Settings
ActivityStart();
+ ISession session = null;
try
{
- ISession session = Results.DB.CreateSession();
+ session = TBF.DB.ResultsDBSessionFactory.OpenSession();
IList bFrom = session.QueryOver().Where(x => (x.BatchNr == batchFrom)).List();
IList bTo = session.QueryOver().Where(x => (x.BatchNr == batchTo)).List();
@@ -1041,15 +1043,20 @@ namespace TBF.UI.Settings
MessageBox.Show(string.Format("Upgrade failed:\r\n{0}", exc.Message),
"Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
+ finally
+ {
+ if (session != null && session.IsOpen) session.Close();
+ }
}
private void customButton_Click(object sender, EventArgs e)
{
ActivityStart();
+ ISession session = null;
try
{
- ISession session = TBF.DB.CreateSession(Common.DBKind.Config);
+ session = TBF.DB.ConfigDBSessionFactory.OpenSession();
var proceduresToModify = session.QueryOver()
.Where(x => x.CmpntName == "Sensus-Oracle-DB")
@@ -1075,6 +1082,10 @@ namespace TBF.UI.Settings
MessageBox.Show(string.Format("Upgrade failed:\r\n{0}", exc.Message),
"Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
+ finally
+ {
+ if (session != null && session.IsOpen) session.Close();
+ }
}
}
}
diff --git a/TBF/UI/Shared/BenchControlPanel.cs b/TBF/UI/Shared/BenchControlPanel.cs
index 1f0f86a9f..4c4ae24b3 100644
--- a/TBF/UI/Shared/BenchControlPanel.cs
+++ b/TBF/UI/Shared/BenchControlPanel.cs
@@ -10,6 +10,7 @@ using Common;
using Config.Entities;
using TBF.UiBridge;
using TBF.Resources;
+using NHibernate;
namespace TBF.UI.Shared
{
@@ -175,52 +176,72 @@ namespace TBF.UI.Shared
/// Read the database and re-initialize testComboBox items.
/// Try to preserve the original selection.
///
- public void ReloadTests()
+ public void ReloadTests(ISession session = null)
{
if (Program.MainWnd.SelectedProcedure == null || string.IsNullOrEmpty(Program.MainWnd.SelectedProcedure.Name)) return;
+ bool openAndCloseSession = (session == null);
+
string oriTestName = testComboBox.Text;
- IList procedures = TBF.DB.CreateSession(Program.MainWnd.SelectedProcedure.IsRemote ? DBKind.RemoteConfig : DBKind.Config)
- .QueryOver()
- .Where(x => (x.ProcedureState == ProcedureState.Active))
- .And(x => (x.Name == Program.MainWnd.SelectedProcedure.Name))
- .List();
- if (procedures.Count != 1)
- {
- testComboBox.Text = string.Empty;
- TestName = null;
- Program.MainWnd.CurrentProcedure = null;
- return;
- }
-
- Program.MainWnd.CurrentProcedure = procedures[0];
- if (procedures[0].GetTestInstances() == null)
+ try
{
- procedures[0].UpdateTestInstances(TBF.Rig.StateMachine.LoopStartNames, TBF.Rig.StateMachine.LoopEndNames, null);
+ if (openAndCloseSession)
+ {
+ session = Program.MainWnd.SelectedProcedure.IsRemote
+ ? TBF.DB.SharedDBSessionFactory.OpenSession()
+ : TBF.DB.ConfigDBSessionFactory.OpenSession();
+ }
+
+ var procedures = session.QueryOver()
+ .Where(x => (x.ProcedureState == ProcedureState.Active))
+ .And(x => (x.Name == Program.MainWnd.SelectedProcedure.Name))
+ .List();
+
+ if (procedures.Count != 1)
+ {
+ testComboBox.Text = string.Empty;
+ TestName = null;
+ Program.MainWnd.CurrentProcedure = null;
+ return;
+ }
+
+ Program.MainWnd.CurrentProcedure = procedures[0];
+ if (procedures[0].GetTestInstances() == null)
+ {
+ procedures[0].UpdateTestInstances(TBF.Rig.StateMachine.LoopStartNames, TBF.Rig.StateMachine.LoopEndNames, null);
+ }
+
+ testComboBox.Items.Clear();
+ foreach (var tinst in procedures[0].GetTestInstances())
+ {
+ testComboBox.Items.Add(tinst);
+ }
+
+ if (testComboBox.Items.Contains(oriTestName))
+ {
+ testComboBox.Text = oriTestName;
+ TestName = oriTestName;
+ }
+ else if (testComboBox.Items.Count > 0)
+ {
+ testComboBox.Text = testComboBox.Items[0].ToString();
+ TestName = testComboBox.Items[0].ToString();
+ }
+ else
+ {
+ testComboBox.Text = string.Empty;
+ TestName = null;
+ }
+ }
+ catch (Exception e)
+ {
+ log.ErrorFormat("Cannot reload tests: {0}", e.Message);
+ }
+ finally
+ {
+ if (openAndCloseSession && session != null && session.IsOpen) session.Close();
}
-
- testComboBox.Items.Clear();
- foreach (var tinst in procedures[0].GetTestInstances())
- {
- testComboBox.Items.Add(tinst);
- }
-
- if (testComboBox.Items.Contains(oriTestName))
- {
- testComboBox.Text = oriTestName;
- TestName = oriTestName;
- }
- else if (testComboBox.Items.Count > 0)
- {
- testComboBox.Text = testComboBox.Items[0].ToString();
- TestName = testComboBox.Items[0].ToString();
- }
- else
- {
- testComboBox.Text = string.Empty;
- TestName = null;
- }
}
private void testComboBox_SelectedIndexChanged(object sender, EventArgs e)
@@ -280,7 +301,7 @@ namespace TBF.UI.Shared
if (drain1Highlighted && !Users.CurrentUser.IsMemberOf(GID.TestingSpecialists))
{
var dlg = new DummyDlg();
- if ((new Users.Forms.LoginDlg(new GID[] { GID.TestingSpecialists }, dlg)).ShowDialog() != DialogResult.OK)
+ if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, new GID[] { GID.TestingSpecialists }, dlg)).ShowDialog() != DialogResult.OK)
return;
Bridge.Ui2Bench(UI2BenchCmd.StopDrainingTank1);
@@ -298,7 +319,7 @@ namespace TBF.UI.Shared
if (drain1Highlighted && !Users.CurrentUser.IsMemberOf(GID.TestingSpecialists))
{
var dlg = new DummyDlg();
- if ((new Users.Forms.LoginDlg(new GID[] { GID.TestingSpecialists }, dlg)).ShowDialog() != DialogResult.OK)
+ if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, new GID[] { GID.TestingSpecialists }, dlg)).ShowDialog() != DialogResult.OK)
return;
Bridge.Ui2Bench(UI2BenchCmd.StopDrainingTank2);
@@ -316,7 +337,7 @@ namespace TBF.UI.Shared
if (drain1Highlighted && !Users.CurrentUser.IsMemberOf(GID.TestingSpecialists))
{
var dlg = new DummyDlg();
- if ((new Users.Forms.LoginDlg(new GID[] { GID.TestingSpecialists }, dlg)).ShowDialog() != DialogResult.OK)
+ if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, new GID[] { GID.TestingSpecialists }, dlg)).ShowDialog() != DialogResult.OK)
return;
Bridge.Ui2Bench(UI2BenchCmd.StopDrainingTank3);
diff --git a/TBF/UI/Shared/LoginDlgWithBenchSelection.cs b/TBF/UI/Shared/LoginDlgWithBenchSelection.cs
index e4c104ae7..bfae20232 100644
--- a/TBF/UI/Shared/LoginDlgWithBenchSelection.cs
+++ b/TBF/UI/Shared/LoginDlgWithBenchSelection.cs
@@ -1,12 +1,12 @@
///
-/// Copyright (c) 2013-2018 Sensus Slovensko a.s.
+/// Copyright (c) 2013-2023 Sensus Slovensko a.s.
///
using System;
+using System.Drawing;
using System.Windows.Forms;
using log4net;
-using TBF.Resources;
using GemCard;
-using System.Drawing;
+using TBF.Resources;
namespace TBF.UI.Shared
diff --git a/TBF/UI/Shared/SharedButtons.cs b/TBF/UI/Shared/SharedButtons.cs
index 0a0cf6171..bb476b686 100644
--- a/TBF/UI/Shared/SharedButtons.cs
+++ b/TBF/UI/Shared/SharedButtons.cs
@@ -233,12 +233,13 @@ namespace TBF.UI.Shared
{
if (!Users.CurrentUser.IsMemberOf(RequiredGroupMembership))
{
- if ((new Users.Forms.LoginDlg(RequiredGroupMembership, ParentForm)).ShowDialog() != DialogResult.OK)
+ if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, RequiredGroupMembership, ParentForm)).ShowDialog() != DialogResult.OK)
return;
}
else if (Program.LocalSettings.AlwaysAskPasswdWhenUnlocking)
{
- if ((new Users.Forms.LoginDlg(Users.CurrentUser.UserName(), RequiredGroupMembership, ParentForm)).ShowDialog() != DialogResult.OK)
+ if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, Users.CurrentUser.UserName(),
+ RequiredGroupMembership, ParentForm)).ShowDialog() != DialogResult.OK)
return;
}
diff --git a/Users/DB.cs b/Users/DB.cs
index 8a671c1d0..c217977f0 100644
--- a/Users/DB.cs
+++ b/Users/DB.cs
@@ -20,7 +20,6 @@ namespace Users
/// Session factory for all regular sessions, not for CreateEmptyResultsDB().
public static ISessionFactory SessionFactory;
- public static ISession CurrentSession;
/// Connection string for all sessions
private static string connectionString;
@@ -103,8 +102,7 @@ namespace Users
if (SessionFactory == null) SessionFactory = CreateSessionFactory();
- CurrentSession = SessionFactory.OpenSession();
- return CurrentSession;
+ return SessionFactory.OpenSession();
}
diff --git a/Users/Entities/User.cs b/Users/Entities/User.cs
index f79fc3832..cfb031f62 100644
--- a/Users/Entities/User.cs
+++ b/Users/Entities/User.cs
@@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using log4net;
+using NHibernate;
using Common;
using Users.Forms;
using Users.Resources;
@@ -228,7 +229,7 @@ namespace Users.Entities
/// Password
///
/// true = authorized
- public virtual bool Authorize(string userName, string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm )
+ public virtual bool Authorize(ISession session, string userName, string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm)
{
if (IsPowerUser(userName, password))
{
@@ -245,7 +246,7 @@ namespace Users.Entities
return false;
}
- return CompleteAuthorization(password, requiredGroupMembership, currentForm);
+ return CompleteAuthorization(session, password, requiredGroupMembership, currentForm);
}
///
@@ -259,7 +260,7 @@ namespace Users.Entities
/// Password
///
/// true = authorized
- public virtual bool AuthorizeNumber(int number, string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm)
+ public virtual bool AuthorizeNumber(ISession session, int number, string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm)
{
if (Number != number)
{
@@ -267,7 +268,7 @@ namespace Users.Entities
return false;
}
- return CompleteAuthorization(password, requiredGroupMembership, currentForm);
+ return CompleteAuthorization(session, password, requiredGroupMembership, currentForm);
}
///
@@ -281,7 +282,7 @@ namespace Users.Entities
///
///
/// true = authorized
- public virtual bool AuthorizeFullName(string fullName, string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm)
+ public virtual bool AuthorizeFullName(ISession session, string fullName, string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm)
{
if (FullName.ToLower() != fullName.ToLower())
{
@@ -289,7 +290,7 @@ namespace Users.Entities
return false;
}
- return CompleteAuthorization(password, requiredGroupMembership, currentForm);
+ return CompleteAuthorization(session, password, requiredGroupMembership, currentForm);
}
///
@@ -298,7 +299,7 @@ namespace Users.Entities
/// Password
/// Required group membership
/// true = authorized
- bool CompleteAuthorization(string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm)
+ bool CompleteAuthorization(ISession session, string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm)
{
if (!IsMemberOf(requiredGroupMembership) || !IsCorrectPassword(password))
{
@@ -309,7 +310,7 @@ namespace Users.Entities
if (IsPasswordExpired())
{
/// Password expired => User has to change the password
- if (new PasswordChangeDlg(UserName).ShowDialog() != System.Windows.Forms.DialogResult.OK)
+ if (new PasswordChangeDlg(session, UserName).ShowDialog() != System.Windows.Forms.DialogResult.OK)
{
/// User did not change the password => reject authorization
return false;
@@ -370,122 +371,58 @@ namespace Users.Entities
return user;
}
-
- ///
- /// Returns a 'User' with a given username from an ARBITRARY database.
- ///
- /// User name for the query
- /// reference to a 'User' (if it exists) or null
- public static User LoadUserByName(string userName, DBSettings dbSettings)
- {
- if (dbSettings == null || string.IsNullOrEmpty(dbSettings.ConnectionString)) return null;
-
- DB.DbType = dbSettings.DbType;
- DB.ConnectionString = dbSettings.ConnectionString;
- return LoadUserByName(userName);
- }
-
///
/// Returns a 'User' with a given username from the users database.
///
/// User name for the query
/// reference to a 'User' (if it exists) or null
- public static User LoadUserByName(string userName)
+ public static User LoadUserByName(ISession session, string userName)
{
- IList listOfUsers = DB.CreateSession()
- .QueryOver()
- .Where(x => (x.UserName == userName))
- .List();
+ var listOfUsers = session.QueryOver()
+ .Where(x => (x.UserName == userName))
+ .List();
return (listOfUsers.Count > 0) ? listOfUsers[0] : null;
}
-
- ///
- /// Returns a 'User' with a given full name from an ARBITRARY database.
- ///
- /// Full name for the query
- /// reference to a 'User' (if it exists) or null
- public static User LoadUserByFullName(string fullName, DBSettings dbSettings)
- {
- if (dbSettings == null || string.IsNullOrEmpty(dbSettings.ConnectionString)) return null;
-
- DB.DbType = dbSettings.DbType;
- DB.ConnectionString = dbSettings.ConnectionString;
- return LoadUserByFullName(fullName);
- }
-
///
/// Returns a 'User' with a given full name from the users database.
///
/// Full name for the query
/// reference to a 'User' (if it exists) or null
- public static User LoadUserByFullName(string fullName)
+ public static User LoadUserByFullName(ISession session, string fullName)
{
- IList listOfUsers = DB.CreateSession()
- .QueryOver()
- .Where(x => (x.FullName == fullName))
- .List();
+ var listOfUsers = session.QueryOver()
+ .Where(x => (x.FullName == fullName))
+ .List();
return (listOfUsers.Count > 0) ? listOfUsers[0] : null;
}
-
- ///
- /// Returns a 'User' with a given username from an ARBITRARY database.
- ///
- /// User ID number for the query
- /// reference to a 'User' (if it exists) or null
- public static User LoadUserByNumber(int number, DBSettings dbSettings)
- {
- if (dbSettings == null || string.IsNullOrEmpty(dbSettings.ConnectionString)) return null;
-
- DB.DbType = dbSettings.DbType;
- DB.ConnectionString = dbSettings.ConnectionString;
- return LoadUserByNumber(number);
- }
-
///
/// Returns a 'User' with a given username from the users database.
///
/// User ID number for the query
/// reference to a 'User' (if it exists) or null
- public static User LoadUserByNumber(int number)
+ public static User LoadUserByNumber(ISession session, int number)
{
- IList listOfUsers = DB.CreateSession()
- .QueryOver()
- .Where(x => (x.Number == number))
- .List();
+ var listOfUsers = session.QueryOver()
+ .Where(x => (x.Number == number))
+ .List();
return (listOfUsers.Count > 0) ? listOfUsers[0] : null;
}
-
- ///
- /// Returns a 'User' with a given RFID/NFC tag s/n from an ARBITRARY database.
- ///
- /// Tag of a user for the query
- /// reference to a 'User' (if it exists) or null
- public static User LoadUserByTag(string tag, DBSettings dbSettings)
- {
- if (dbSettings == null || string.IsNullOrEmpty(dbSettings.ConnectionString)) return null;
-
- DB.DbType = dbSettings.DbType;
- DB.ConnectionString = dbSettings.ConnectionString;
- return LoadUserByTag(tag);
- }
-
///
/// Returns a 'User' with a given RFID/NFC tag s/n from the users database.
///
/// Tag of a user for the query
/// reference to a 'User' (if it exists) or null
- public static User LoadUserByTag(string tag)
+ public static User LoadUserByTag(ISession session, string tag)
{
- IList listOfUsers = DB.CreateSession()
- .QueryOver()
- .Where(x => (x.Tag == tag))
- .List();
+ var listOfUsers = session.QueryOver()
+ .Where(x => (x.Tag == tag))
+ .List();
return (listOfUsers.Count > 0) ? listOfUsers[0] : null;
}
@@ -494,9 +431,9 @@ namespace Users.Entities
///
/// returns an IList of all Users
///
- public static IList GetAllUsers()
+ public static IList GetAllUsers(ISession session)
{
- return DB.CreateSession().QueryOver().List();
+ return session.QueryOver().List();
}
diff --git a/Users/Forms/EditSelectedUser.cs b/Users/Forms/EditSelectedUser.cs
index 29f27e045..d8fa4ca25 100644
--- a/Users/Forms/EditSelectedUser.cs
+++ b/Users/Forms/EditSelectedUser.cs
@@ -225,47 +225,46 @@ namespace Users.Forms
}
///
- /// returns true if the username allready exists for another user
+ /// Returns true if the username already exists for another user
///
private bool IsUserNameAlreadyTaken(string userName)
{
- // Have a look into all other users
- IList ListOfUsers = User.GetAllUsers();
- foreach (var person in ListOfUsers)
+ /// Have a look on all other users
+ foreach (var u in User.GetAllUsers(session))
{
- if (person.Id != user.Id)
+ if (u.Id != user.Id)
{
- /// Other user then the current one
- if (person.UserName.ToLower() == userName.ToLower())
+ // 'u' is other user then the current one
+
+ if (u.UserName.ToLower() == userName.ToLower())
{
- return true; // Name is equal = already taken
+ return true; /// User name is already used by another user
}
}
}
- return false;
+
+ return false; /// User name is stil free
}
///
- /// returns true if the username allready exists for another user
+ /// Returns true if the tag already exists for another user
///
private bool IsTagAlreadyTaken(string tag)
{
- if (string.IsNullOrEmpty(tag)) return false; /// No tag
+ if (string.IsNullOrEmpty(tag)) return false;
- // Have a look into all other users
- IList ListOfUsers = User.GetAllUsers();
- foreach (var person in ListOfUsers)
+ /// Have a look on all other users
+ foreach (var u in User.GetAllUsers(session))
{
- if (person.Id != user.Id)
+ if (u.Id != this.user.Id)
{
- // Other user then the current one
- if (person.Tag == tag)
- {
- return true; // Tag is equal = already taken
- }
+ // 'u' is other user then the current one
+
+ if (u.Tag == tag) return true; /// Tag is already used by another user
}
}
- return false;
+
+ return false; /// Tag is stil free
}
diff --git a/Users/Forms/LoginDlg.cs b/Users/Forms/LoginDlg.cs
index d43744993..e4fe6277a 100644
--- a/Users/Forms/LoginDlg.cs
+++ b/Users/Forms/LoginDlg.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2017-2018 Sensus Slovensko a.s.
+/// Copyright (c) 2017-2023 Sensus Slovensko a.s.
///
using System;
using System.Windows.Forms;
@@ -9,6 +9,7 @@ using GemCard;
using Users.Entities;
using Users.Resources;
using System.Drawing;
+using NHibernate;
namespace Users.Forms
{
@@ -24,11 +25,11 @@ namespace Users.Forms
public string UserName { get { return user; } }
/// Private fields
+ ISessionFactory[] sessionFactories;
string user;
string password;
GID[] requiredGroupMembership;
Form parentForm;
- bool noDatabase;
Color oriBackColor;
/// Smart card support, card S/N is used as user.Tag
@@ -44,16 +45,17 @@ namespace Users.Forms
public LoginDlg()
{
InitializeComponent();
-
+ this.sessionFactories = null;
oriBackColor = BackColor;
}
///
/// Constructor with a predefined user.
///
- public LoginDlg(string predefinedUser, Form parentForm)
+ public LoginDlg(ISessionFactory[] sessionFactories, string predefinedUser, Form parentForm)
: this()
{
+ this.sessionFactories = sessionFactories;
user = predefinedUser;
userNameTextBox.Text = predefinedUser;
this.parentForm = parentForm;
@@ -62,18 +64,19 @@ namespace Users.Forms
///
/// Constructor with 'no Database' flag.
///
- public LoginDlg(bool noDatabase)
+ public LoginDlg(ISessionFactory[] sessionFactories)
: this()
{
- this.noDatabase = noDatabase;
- }
+ this.sessionFactories = sessionFactories;
+ }
///
/// Constructor when a specific group membership is required.
///
- public LoginDlg(GID[] requiredGroupMembership, Form parentForm)
+ public LoginDlg(ISessionFactory[] sessionFactories, GID[] requiredGroupMembership, Form parentForm)
: this()
{
+ this.sessionFactories = sessionFactories;
this.requiredGroupMembership = requiredGroupMembership;
this.parentForm = parentForm;
#if DEBUG
@@ -86,9 +89,10 @@ namespace Users.Forms
///
/// Constructor with a predefined user when a specific group membership is required.
///
- public LoginDlg(string predefinedUser, GID[] requiredGroupMembership, Form parentForm)
+ public LoginDlg(ISessionFactory[] sessionFactories, string predefinedUser, GID[] requiredGroupMembership, Form parentForm)
: this()
{
+ this.sessionFactories = sessionFactories;
user = predefinedUser;
userNameTextBox.Text = predefinedUser;
this.requiredGroupMembership = requiredGroupMembership;
@@ -198,39 +202,47 @@ namespace Users.Forms
CurrentUser.Change(new Users.Entities.User(user, 6, true), parentForm);
}
- if (!authorized && !noDatabase)
+ if (!authorized && sessionFactories != null)
{
DBSettings[] dbs = new DBSettings[] { CurrentUser.RemoteUsersDB, CurrentUser.LocalUsersDB };
authorizedAs = AuthorizedAs.RemoteUser;
- foreach (var db in dbs)
+ foreach (var sf in sessionFactories)
{
+ ISession session = null;
try
{
+ session = sf.OpenSession();
switch (Method)
{
case LoginMethod.UserName:
default:
- var usr1 = Users.Entities.User.LoadUserByName(user, db);
- if (usr1 != null) { authorized = usr1.Authorize(user, password, requiredGroupMembership, parentForm); }
+ var usr1 = Users.Entities.User.LoadUserByName(session, user);
+ if (usr1 != null) { authorized = usr1.Authorize(session, user, password, requiredGroupMembership, parentForm); }
break;
case LoginMethod.FullName:
- var usr2 = Users.Entities.User.LoadUserByFullName(user, db);
- if (usr2 != null) { authorized = usr2.AuthorizeFullName(user, password, requiredGroupMembership, parentForm); }
+ var usr2 = Users.Entities.User.LoadUserByFullName(session, user);
+ if (usr2 != null) { authorized = usr2.AuthorizeFullName(session, user, password, requiredGroupMembership, parentForm); }
if (authorized) { user = usr2.UserName; }
break;
case LoginMethod.Number:
int number;
if (!int.TryParse(user, out number)) break;
- var usr3 = Users.Entities.User.LoadUserByNumber(number, db);
- if (usr3 != null) { authorized = usr3.AuthorizeNumber(number, password, requiredGroupMembership, parentForm); }
+ var usr3 = Users.Entities.User.LoadUserByNumber(session, number);
+ if (usr3 != null) { authorized = usr3.AuthorizeNumber(session, number, password, requiredGroupMembership, parentForm); }
if (authorized) { user = usr3.UserName; }
break;
}
}
- catch (Exception) { }
+ catch (Exception)
+ {
+ }
+ finally
+ {
+ if (session != null && session.IsOpen) session.Close();
+ }
if (authorized) break;
@@ -310,29 +322,30 @@ namespace Users.Forms
tag = string.Empty;
}
- DBSettings[] dbs = new DBSettings[] { CurrentUser.RemoteUsersDB, CurrentUser.LocalUsersDB };
bool authorized = false;
AuthorizedAs authorizedAs = AuthorizedAs.RemoteUser;
///
- foreach (var db in dbs)
+ if (sessionFactories != null)
{
- try
+ foreach (var sf in sessionFactories)
{
- Users.Entities.User loadedUser = Users.Entities.User.LoadUserByTag(tag, db);
- if (loadedUser != null)
+ using (ISession session = sf.OpenSession())
{
- authorized = loadedUser.AuthorizeTag(tag, requiredGroupMembership, parentForm);
-
- if (authorized)
+ Users.Entities.User loadedUser = Users.Entities.User.LoadUserByTag(session, tag);
+ if (loadedUser != null)
{
- user = loadedUser.UserName;
- break;
+ authorized = loadedUser.AuthorizeTag(tag, requiredGroupMembership, parentForm);
+
+ if (authorized)
+ {
+ user = loadedUser.UserName;
+ break;
+ }
}
}
- }
- catch (Exception) { }
- authorizedAs = AuthorizedAs.LocalUser;
+ authorizedAs = AuthorizedAs.LocalUser;
+ }
}
if (authorized)
diff --git a/Users/Forms/PasswordChangeDlg.cs b/Users/Forms/PasswordChangeDlg.cs
index ebed6302c..f3b1c559e 100644
--- a/Users/Forms/PasswordChangeDlg.cs
+++ b/Users/Forms/PasswordChangeDlg.cs
@@ -1,8 +1,10 @@
///
-/// Copyright (c) 2019 Sensus Slovensko a.s.
+/// Copyright (c) 2019-2023 Sensus Slovensko a.s.
///
using System;
using System.Windows.Forms;
+using log4net;
+using NHibernate;
using Common;
using GemCard;
using Users.Resources;
@@ -16,10 +18,15 @@ namespace Users.Forms
///
public partial class PasswordChangeDlg : Form
{
+ private static readonly ILog log = LogManager.GetLogger(typeof(PasswordChangeDlg));
+
+ ISessionFactory[] sessionFactories;
+ ISession session;
+
///
/// Constructor
///
- public PasswordChangeDlg()
+ private PasswordChangeDlg()
{
InitializeComponent();
}
@@ -27,10 +34,23 @@ namespace Users.Forms
///
/// Constructor with a predefined user.
///
- public PasswordChangeDlg(string predefinedUser)
+ public PasswordChangeDlg(ISessionFactory[] sessionFactories, string predefinedUser = null)
{
InitializeComponent();
- userNameTextBox.Text = predefinedUser;
+ this.sessionFactories = sessionFactories;
+ this.session = null;
+ if (predefinedUser != null) userNameTextBox.Text = predefinedUser;
+ }
+
+ ///
+ /// Constructor with a predefined user.
+ ///
+ public PasswordChangeDlg(ISession session, string predefinedUser = null)
+ {
+ InitializeComponent();
+ this.sessionFactories = null;
+ this.session = session;
+ if (predefinedUser != null) userNameTextBox.Text = predefinedUser;
}
@@ -97,45 +117,96 @@ namespace Users.Forms
bool oldPasswdOK = false;
if (!oldPasswdOK)
{
- DBSettings[] dbs = new DBSettings[] { CurrentUser.RemoteUsersDB, CurrentUser.LocalUsersDB };
+ if (sessionFactories != null)
+ {
+ foreach (var sf in sessionFactories)
+ {
+ ISession sess = null;
+ try
+ {
+ sess = sf.OpenSession();
+ loadedUser = Users.Entities.User.LoadUserByName(sess, userName);
+ if (loadedUser != null)
+ {
+ oldPasswdOK = (userName == loadedUser.UserName) && loadedUser.IsCorrectPassword(oldPassword);
+ }
- foreach (var db in dbs)
- {
+ if (oldPasswdOK)
+ {
+ if (loadedUser.IsPasswordUsedInPast(newPasswTextBox.Text))
+ {
+ sess.Close();
+ MessageBox.Show(Strings.Password_has_been_used_in_past, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Hand);
+ DialogResult = DialogResult.None;
+ return;
+ }
+
+ ///
+ /// Now the password is changed in database that was used to authorize the user
+ ///
+ loadedUser.SetPassword(newPasswTextBox.Text);
+ sess.SaveOrUpdate(loadedUser);
+ sess.Flush();
+ sess.Close();
+
+ DialogResult = DialogResult.OK;
+ Close();
+ return;
+ }
+ }
+ catch (Exception)
+ {
+ log.ErrorFormat("Cannot load a list of users from a database");
+ }
+ finally
+ {
+ if (sess != null && sess.IsOpen) sess.Close();
+ }
+
+ if (oldPasswdOK) break;
+
+ authorizedAs = AuthorizedAs.LocalUser;
+ }
+ }
+ else if (session != null)
+ {
+ /// This session was already open so consequently it is not closed after loading the user
try
{
- loadedUser = Users.Entities.User.LoadUserByName(userName, db);
+ loadedUser = Users.Entities.User.LoadUserByName(session, userName);
if (loadedUser != null)
{
oldPasswdOK = (userName == loadedUser.UserName) && loadedUser.IsCorrectPassword(oldPassword);
}
}
- catch (Exception) { }
+ catch (Exception)
+ {
+ log.ErrorFormat("Cannot load a list of users from a database");
+ }
- if (oldPasswdOK) break;
+ authorizedAs = AuthorizedAs.LocalUser;
- authorizedAs = AuthorizedAs.LocalUser;
- }
- }
+ if (oldPasswdOK && session != null && session.IsOpen)
+ {
+ if (loadedUser.IsPasswordUsedInPast(newPasswTextBox.Text))
+ {
+ MessageBox.Show(Strings.Password_has_been_used_in_past, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Hand);
+ DialogResult = DialogResult.None;
+ return;
+ }
- if (oldPasswdOK && (DB.CurrentSession != null) && (DB.CurrentSession.IsOpen))
- {
- if (loadedUser.IsPasswordUsedInPast(newPasswTextBox.Text))
- {
- MessageBox.Show(Strings.Password_has_been_used_in_past, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Hand);
- DialogResult = DialogResult.None;
- return;
+ ///
+ /// Now the password is changed in database that was used to authorize the user
+ ///
+ loadedUser.SetPassword(newPasswTextBox.Text);
+ session.SaveOrUpdate(loadedUser);
+ session.Flush();
+
+ DialogResult = DialogResult.OK;
+ Close();
+ return;
+ }
}
-
- ///
- /// Now the password is changed in database that was used to authorize the user
- ///
- loadedUser.SetPassword(newPasswTextBox.Text);
- DB.CurrentSession.SaveOrUpdate(loadedUser);
- DB.CurrentSession.Flush();
-
- DialogResult = DialogResult.OK;
- Close();
- return;
}
MessageBox.Show(Strings.Invalid_username_or_password, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Hand);
diff --git a/Users/Forms/PlainLoginDlg.cs b/Users/Forms/PlainLoginDlg.cs
index 53f675a3d..89197070e 100644
--- a/Users/Forms/PlainLoginDlg.cs
+++ b/Users/Forms/PlainLoginDlg.cs
@@ -1,5 +1,5 @@
///
-/// Copyright (c) 2022 Sensus Slovensko a.s.
+/// Copyright (c) 2022-2023 Sensus Slovensko a.s.
///
using System;
using System.Windows.Forms;
@@ -9,6 +9,7 @@ using GemCard;
using Users.Entities;
using Users.Resources;
using System.Drawing;
+using NHibernate;
namespace Users.Forms
{
@@ -25,10 +26,10 @@ namespace Users.Forms
public string FullName { get { return fullName; } }
/// Private fields
+ ISessionFactory[] sessionFactories;
string user;
string password;
GID[] requiredGroupMembership;
- bool noDatabase;
Color oriBackColor;
string fullName; /// Description of the selected user
@@ -52,9 +53,10 @@ namespace Users.Forms
///
/// Constructor with a predefined user.
///
- public PlainLoginDlg(string predefinedUser, string prompt = null)
+ public PlainLoginDlg(ISessionFactory[] sessionFactories, string predefinedUser, string prompt = null)
: this()
{
+ this.sessionFactories = sessionFactories;
user = predefinedUser;
userNameTextBox.Text = predefinedUser;
if (prompt != null) Text = prompt;
@@ -63,19 +65,20 @@ namespace Users.Forms
///
/// Constructor with 'no Database' flag.
///
- public PlainLoginDlg(bool noDatabase, string prompt = null)
+ public PlainLoginDlg(ISessionFactory[] sessionFactories, string prompt = null)
: this()
{
- this.noDatabase = noDatabase;
+ this.sessionFactories = sessionFactories;
if (prompt != null) Text = prompt;
}
///
/// Constructor when a specific group membership is required.
///
- public PlainLoginDlg(GID[] requiredGroupMembership, string prompt = null)
+ public PlainLoginDlg(ISessionFactory[] sessionFactories, GID[] requiredGroupMembership, string prompt = null)
: this()
{
+ this.sessionFactories = sessionFactories;
this.requiredGroupMembership = requiredGroupMembership;
if (prompt != null) Text = prompt;
}
@@ -83,9 +86,10 @@ namespace Users.Forms
///
/// Constructor with a predefined user when a specific group membership is required.
///
- public PlainLoginDlg(string predefinedUser, GID[] requiredGroupMembership, string prompt = null)
+ public PlainLoginDlg(ISessionFactory[] sessionFactories, string predefinedUser, GID[] requiredGroupMembership, string prompt = null)
: this()
{
+ this.sessionFactories = sessionFactories;
user = predefinedUser;
userNameTextBox.Text = predefinedUser;
this.requiredGroupMembership = requiredGroupMembership;
@@ -179,15 +183,15 @@ namespace Users.Forms
bool authorized = Entities.User.IsPowerUser(user, password);
if (authorized) fullName = "Power user";
- if (!authorized && !noDatabase)
+ if (!authorized && sessionFactories != null && sessionFactories.Length > 0)
{
- DBSettings[] dbs = new DBSettings[] { CurrentUser.RemoteUsersDB, CurrentUser.LocalUsersDB };
-
- foreach (var db in dbs)
+ foreach (var sf in sessionFactories)
{
+ ISession session = null;
try
{
- var usr1 = Users.Entities.User.LoadUserByName(user, db);
+ session = sf.OpenSession();
+ var usr1 = Users.Entities.User.LoadUserByName(session, user);
if (usr1.IsMemberOf(requiredGroupMembership) && usr1.IsCorrectPassword(password))
{
@@ -196,7 +200,13 @@ namespace Users.Forms
break;
}
}
- catch (Exception) { }
+ catch (Exception)
+ {
+ }
+ finally
+ {
+ if (session != null && session.IsOpen) session.Close();
+ }
}
}
@@ -263,25 +273,36 @@ namespace Users.Forms
bool authorized = false;
AuthorizedAs authorizedAs = AuthorizedAs.RemoteUser;
///
- foreach (var db in dbs)
+ if (sessionFactories != null)
{
- try
+ foreach (var sf in sessionFactories)
{
- Users.Entities.User loadedUser = Users.Entities.User.LoadUserByTag(tag, db);
- if (loadedUser != null)
+ ISession session = null;
+ try
{
- authorized = (tag == loadedUser.Tag && loadedUser.IsMemberOf(requiredGroupMembership));
-
- if (authorized)
+ session = sf.OpenSession();
+ Users.Entities.User loadedUser = Users.Entities.User.LoadUserByTag(session, tag);
+ if (loadedUser != null)
{
- user = loadedUser.UserName;
- break;
+ authorized = (tag == loadedUser.Tag && loadedUser.IsMemberOf(requiredGroupMembership));
+
+ if (authorized)
+ {
+ user = loadedUser.UserName;
+ break;
+ }
}
}
- }
- catch (Exception) { }
+ catch (Exception)
+ {
+ }
+ finally
+ {
+ if (session != null && session.IsOpen) session.Close();
+ }
- authorizedAs = AuthorizedAs.LocalUser;
+ authorizedAs = AuthorizedAs.LocalUser;
+ }
}
if (authorized)
diff --git a/Users/Forms/UserManagementDlg.cs b/Users/Forms/UserManagementDlg.cs
index 3794d8e17..73cb1b2fe 100644
--- a/Users/Forms/UserManagementDlg.cs
+++ b/Users/Forms/UserManagementDlg.cs
@@ -238,6 +238,8 @@ namespace Users.Forms
IList remoteUsers;
IList remoteGroups;
ITransaction transaction = null;
+ ISession remoteSession = null;
+ ISession localSession = null;
try
{
@@ -246,7 +248,7 @@ namespace Users.Forms
///
DB.DbType = CurrentUser.RemoteUsersDB.DbType;
DB.ConnectionString = CurrentUser.RemoteUsersDB.ConnectionString;
- ISession remoteSession = DB.CreateSession();
+ remoteSession = DB.CreateSession();
remoteUsers = remoteSession.QueryOver().List();
remoteGroups = remoteSession.QueryOver().List();
@@ -255,7 +257,7 @@ namespace Users.Forms
///
DB.DbType = CurrentUser.LocalUsersDB.DbType;
DB.ConnectionString = CurrentUser.LocalUsersDB.ConnectionString;
- ISession localSession = DB.CreateSession();
+ localSession = DB.CreateSession();
transaction = localSession.BeginTransaction();
///
@@ -285,6 +287,8 @@ namespace Users.Forms
}
transaction.Commit();
localSession.Flush();
+ localSession.Close();
+ remoteSession.Close();
listOfUsers = newUsers;
ListUsers();
@@ -298,6 +302,9 @@ namespace Users.Forms
{
if (transaction != null) transaction.Rollback();
+ if (localSession != null && localSession.IsOpen) localSession.Close();
+ if (remoteSession != null && remoteSession.IsOpen) remoteSession.Close();
+
MessageBox.Show(Strings.Copying_remote_users_failed,
Strings.Confirmation,
MessageBoxButtons.OK,