TBF.DB with 4 static session factories, sessions in UI rewritten, TODO: keep session that loads components open, etc.

This commit is contained in:
Milan Hanajik 2023-03-28 13:03:38 +02:00
parent 0d47578441
commit 78d05fb1b9
51 changed files with 1314 additions and 1025 deletions

View File

@ -12,6 +12,7 @@ namespace Common
{ {
public DBType DbType; public DBType DbType;
public string ConnectionString; public string ConnectionString;
public bool IsValid { get { return (DbType != DBType.None) && !string.IsNullOrEmpty(ConnectionString); } }
public DBSettings() public DBSettings()
{ {

View File

@ -15,10 +15,10 @@ namespace Common
// Public fields // Public fields
public string BenchName; public string BenchName;
public bool IsRealBench; public bool IsRealBench;
public DBSettings ProceduresDBSettings; /// Configuration database settings public DBSettings ProceduresDBSettings; /// Configuration database settings
public DBSettings WaterMetersDBSettings; /// Results database settings public DBSettings WaterMetersDBSettings; /// Results database settings
public DBSettings EventsDBSettings; /// Events database settings public DBSettings EventsDBSettings; /// Events database settings
public DBSettings UsersDBSettings; /// Shared configuration database settings public DBSettings UsersDBSettings; /// Shared configuration database settings
// Constructor // Constructor
public DatabaseSettings() public DatabaseSettings()

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2013-2022 Sensus Slovensko a.s. /// Copyright (c) 2013-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -49,15 +49,6 @@ namespace Common
Count Count
} }
/// <summary> Identifies the database based on the content </summary>
public enum DBKind
{
Config,
Results,
RemoteConfig,
Count
}
public enum ProcedureSelection public enum ProcedureSelection
{ {
#if LANG_CS #if LANG_CS

View File

@ -1,148 +1,10 @@
/// ///
/// Copyright (c) 2013-2018 Sensus Slovensko a.s. /// 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 namespace Config
{ {
public static class FluentCommon public static class FluentCommon
{ {
/// <summary>
/// NHibernate session factory (to create the database session 'SessionFactory')
/// </summary>
/// <returns>A database session</returns>
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<Data>());
break;
case Common.DBKind.Results:
cfg = cfg.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Data>());
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);
}
/// <summary>
/// Create an empty users database.
/// Database contains only the user 'admin' and the control board component 'CB'.
/// </summary>
/// <param name="dbType">DBType.SQLite or DBType.MySql</param>
/// <param name="connectionString">Connection string</param>
/// <returns>true=success, false=error</returns>
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;
}
} }
} }

View File

@ -277,7 +277,7 @@ namespace EventViewer
private void settingsButton_Click(object sender, EventArgs e) private void settingsButton_Click(object sender, EventArgs e)
{ {
//Common.GID[] groupsWithAccess = new Common.GID[] { Common.GID.Administrators }; //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 (dlg.ShowDialog() == DialogResult.OK)
{ {
if ((new Forms.SettingsDlg()).ShowDialog() == DialogResult.OK) if ((new Forms.SettingsDlg()).ShowDialog() == DialogResult.OK)

View File

@ -180,29 +180,55 @@ namespace Results
/// Loads shared data from the database /// Loads shared data from the database
/// </summary> /// </summary>
/// <exception>Throws NHibernate exceptions</exception> /// <exception>Throws NHibernate exceptions</exception>
public static void LoadSharedData() public static void LoadSharedData(ISession session = null)
{ {
ISession session = DB.CreateSession(); bool openAndCloseSession = (session == null);
TestDataList = session.QueryOver<TestData>().List(); try
ComponentsList = session.QueryOver<Components>().List(); {
WaterMeterDataList = session.QueryOver<WaterMeterData>().List(); if (openAndCloseSession) session = Results.DB.CreateSession();
} TestDataList = session.QueryOver<TestData>().List();
ComponentsList = session.QueryOver<Components>().List();
WaterMeterDataList = session.QueryOver<WaterMeterData>().List();
}
catch (Exception e)
{
log.ErrorFormat("Cannot open results DB: {0}", e.Message);
}
finally
{
if (openAndCloseSession && session != null && session.IsOpen) session.Close();
}
}
/// <summary> /// <summary>
/// Loads shared data from the database /// Loads shared data from the database
/// </summary> /// </summary>
/// <exception>Throws NHibernate exceptions</exception> /// <exception>Throws NHibernate exceptions</exception>
public static int GetMaxSavedBatchNr() public static int GetMaxSavedBatchNr(ISession session = null)
{ {
ISession session = DB.CreateSession(); bool openAndCloseSession = (session == null);
IList<Entities.Batch> batches = session.QueryOver<Batch>().List(); int maxBatchNr = 0;
try
{
if (openAndCloseSession) session = Results.DB.CreateSession();
IList<Entities.Batch> batches = session.QueryOver<Batch>().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; return maxBatchNr;
} }

209
TBF/DB.cs
View File

@ -1,11 +1,16 @@
/// ///
/// Copyright (c) 2021 Sensus Slovensko a.s. /// Copyright (c) 2021-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Windows.Forms;
using NHibernate; using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using Common; using Common;
using Config; using Events;
using Users.Entities; using TBF.Resources;
namespace TBF namespace TBF
{ {
@ -16,52 +21,188 @@ namespace TBF
/// ///
public static DatabaseSettings CurrentBench; public static DatabaseSettings CurrentBench;
/// <summary> public static ISessionFactory ConfigDBSessionFactory = null; /// Configuration DB session factory (always != null)
/// Session factories for regular sessions. public static ISessionFactory SharedDBSessionFactory = null; /// Shared configuration DB session factory or null
/// </summary> public static ISessionFactory ResultsDBSessionFactory = null; /// Results DB session factory (always != null)
public static ISessionFactory[] SessionFactories = new ISessionFactory[(int)DBKind.Count]; public static ISessionFactory EventsDBSessionFactory = null; /// Events DB session factory or null
/// Create a NHibernate session for the given database public static ISessionFactory LocalUsersDBSessionFactory = null; /// Local users DB session factory (always != null)
public static ISession CreateSession(DBKind database) public static ISessionFactory SharedUsersDBSessionFactory = null; /// Shared users DB session factory or null
public static ISessionFactory[] UserSessionFactories
{ {
if (database < 0 || database >= DBKind.Count) return null; get
int ix = (int)database;
if (SessionFactories[ix] == null)
{ {
SessionFactories[ix] = CreateSessionFactory(database); return (SharedUsersDBSessionFactory != null)
? new ISessionFactory[] { SharedUsersDBSessionFactory, LocalUsersDBSessionFactory }
: new ISessionFactory[] { LocalUsersDBSessionFactory };
}
}
/// <summary>
/// Create all database session factories
/// </summary>
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<Config.Entities.Procedure>(),
dbSettings.ProceduresDBSettings.DbType,
dbSettings.ProceduresDBSettings.ConnectionString);
LocalUsersDBSessionFactory =
CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf<Users.Entities.User>(),
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<Config.Entities.Procedure>(),
dbSettings.UsersDBSettings.DbType,
dbSettings.UsersDBSettings.ConnectionString);
SharedUsersDBSessionFactory =
CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf<Users.Entities.User>(),
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<Results.Entities.Batch>(),
dbSettings.WaterMetersDBSettings.DbType,
dbSettings.WaterMetersDBSettings.ConnectionString);
}
/// Events database (remote or local)
if (dbSettings.EventsDBSettings != null && dbSettings.EventsDBSettings.IsValid)
{
EventsDBSessionFactory =
CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf<Events.Entities.Event>(),
dbSettings.EventsDBSettings.DbType,
dbSettings.EventsDBSettings.ConnectionString);
}
} }
/// <summary> /// <summary>
/// NHibernate session factory (to create the database session 'SessionFactory') /// NHibernate session factory (to create the database session 'SessionFactory')
/// </summary> /// </summary>
/// <returns>A database session</returns> /// <returns>A database session</returns>
static ISessionFactory CreateSessionFactory(DBKind database) public static ISessionFactory CreateSessionFactory(Action<MappingConfiguration> mappings, Common.DBType dbType,
string connectionString, bool createDB = false)
{ {
DBType dbType; try
string connectionString;
switch (database)
{ {
default: FluentConfiguration cfg;
case DBKind.Config:
dbType = CurrentBench.ProceduresDBSettings.DbType; switch (dbType)
connectionString = CurrentBench.ProceduresDBSettings.ConnectionString; {
break; default:
case DBKind.Results: case Common.DBType.MySql:
dbType = CurrentBench.WaterMetersDBSettings.DbType; cfg = Fluently.Configure().Database(MySQLConfiguration.Standard.ConnectionString(connectionString));
connectionString = CurrentBench.WaterMetersDBSettings.ConnectionString; break;
break; case Common.DBType.SQLite:
case DBKind.RemoteConfig: cfg = Fluently.Configure().Database(SQLiteConfiguration.Standard.UsingFile(connectionString));
dbType = CurrentBench.UsersDBSettings.DbType; break;
connectionString = CurrentBench.UsersDBSettings.ConnectionString; }
break;
var action = createDB ? (System.Action<Configuration>)BuildSchemaCreate : (System.Action<Configuration>)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);
}
/// <summary>
/// Create an empty users database.
/// Database contains only the user 'admin' and the control board component 'CB'.
/// </summary>
/// <param name="dbType">DBType.SQLite or DBType.MySql</param>
/// <param name="connectionString">Connection string</param>
/// <returns>true=success, false=error</returns>
public static bool CreateEmptyConfigDB(Common.DBType dbType, string connectionString)
{
ISessionFactory sessionFactory =
CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf<Config.Entities.Procedure>(),
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;
} }
} }
} }

View File

@ -1,19 +1,19 @@
/// ///
/// Copyright (c) 2013-2022 Sensus Slovensko a.s. /// Copyright (c) 2013-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.IO; using System.IO;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using log4net; using log4net;
using NHibernate;
using Common; using Common;
using Config.Entities; using Config.Entities;
using Users; using Users;
using Users.Entities;
using TBF.Resources; using TBF.Resources;
using TBF.Rig.Sequences; using TBF.Rig.Sequences;
using TBF.UI.Shared; using TBF.UI.Shared;
using NHibernate;
namespace TBF namespace TBF
{ {
@ -214,7 +214,7 @@ namespace TBF
/// Ask what to do, ask for the password, open 'DatabaseSetingsDlg' and continue on OK /// Ask what to do, ask for the password, open 'DatabaseSetingsDlg' and continue on OK
if ((new NoBenchOrDatabaseDlg { Message = Strings.NoBenchMsg }.ShowDialog() != DialogResult.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)) (new TBF.UI.Settings.BenchesDlg().ShowDialog() == DialogResult.Cancel))
{ {
return; /// Exit program return; /// Exit program
@ -229,6 +229,8 @@ namespace TBF
bool retryLogin = true; /// true = stay in a login loop bool retryLogin = true; /// true = stay in a login loop
do do
{ {
LoadingConfigEnd();
LoginDlgWithBenchSelection loginDlgBench; LoginDlgWithBenchSelection loginDlgBench;
if (LocalSettings.LastBenchName != null) if (LocalSettings.LastBenchName != null)
{ {
@ -251,10 +253,11 @@ namespace TBF
{ {
if (LocalSettings.TestBenches[i].BenchName == loginDlgBench.BenchName) 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; LoadingConfigStart();
Users.CurrentUser.LocalUsersDB = LocalSettings.TestBenches[i].ProceduresDBSettings; TBF.DB.CurrentBench = LocalSettings.TestBenches[i].Clone() as DatabaseSettings;
TBF.DB.CreateSessionFactories(LocalSettings.TestBenches[i]);
Users.Entities.User loadedUser = null; Users.Entities.User loadedUser = null;
try try
@ -270,11 +273,10 @@ namespace TBF
if (Users.Entities.User.IsPowerUser(loginDlgBench.Alias, loginDlgBench.Password)) if (Users.Entities.User.IsPowerUser(loginDlgBench.Alias, loginDlgBench.Password))
{ {
loadedUser = new Users.Entities.User(loginDlgBench.Alias, 6, true); loadedUser = new Users.Entities.User(loginDlgBench.Alias, 6, true);
authorized = loadedUser.Authorize(loginDlgBench.Alias, loginDlgBench.Password, reqGrpMembership, null); CurrentUser.Change(loadedUser, null);
if (authorized) CurrentUser.LastAuthorization = DateTime.Now;
{ CurrentUser.AuthorizedAs = Common.AuthorizedAs.PowerUser;
Users.CurrentUser.AuthorizedAs = Common.AuthorizedAs.PowerUser; authorized = true;
}
} }
/// ///
@ -282,42 +284,57 @@ namespace TBF
/// ///
if (!authorized) if (!authorized)
{ {
DBSettings[] dbs = new DBSettings[] { Users.CurrentUser.RemoteUsersDB, Users.CurrentUser.LocalUsersDB };
authorizedAs = Common.AuthorizedAs.RemoteUser; /// Try remote DB first 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 /// Load and authorise user from the UsersDB database
try try
{ {
if (loginDlgBench.Password == LoginDlgWithBenchSelection.UseTheTagPassword)
if (sf != null)
{ {
loadedUser = Users.Entities.User.LoadUserByTag(loginDlgBench.Alias, db); var session = sf.OpenSession();
if (loadedUser != null) authorized = loadedUser.AuthorizeTag(loginDlgBench.Alias, reqGrpMembership, null);
} if (loginDlgBench.Password == LoginDlgWithBenchSelection.UseTheTagPassword)
else
{
switch (loginDlgBench.Method)
{ {
default: loadedUser = Users.Entities.User.LoadUserByTag(session, loginDlgBench.Alias);
case Common.LoginMethod.UserName: if (loadedUser != null) authorized = loadedUser.AuthorizeTag(loginDlgBench.Alias, reqGrpMembership, null);
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;
} }
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 catch
{ {
authorized = false; authorized = false;
@ -353,7 +370,11 @@ namespace TBF
/// Copy the selected bench settings to CurrentBench. /// Copy the selected bench settings to CurrentBench.
/// Clone() guarantees that current bench settings wont be modified /// Clone() guarantees that current bench settings wont be modified
/// when user modifies the database settings in DatabaseSettingsDlg. /// 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.DbType = TBF.DB.CurrentBench.WaterMetersDBSettings.DbType;
Results.DB.ConnectionString = TBF.DB.CurrentBench.WaterMetersDBSettings.ConnectionString; Results.DB.ConnectionString = TBF.DB.CurrentBench.WaterMetersDBSettings.ConnectionString;
@ -364,7 +385,7 @@ namespace TBF
/// Connect to Config database. /// Connect to Config database.
/// This triggers an exception in case user is a power user and there is no 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)) if (!string.IsNullOrEmpty(LocalSettings.LastProcedureName))
{ {
@ -380,9 +401,9 @@ namespace TBF
.List(); .List();
if (components.Count > 0) 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]) 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); ProcessData.BenchInfo = new TBF.Rig.DataContainers.BenchInfo.Extended.Component(cfg);
} }
else else
@ -393,20 +414,20 @@ namespace TBF
.List(); .List();
if (components.Count > 0) 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]) 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); ProcessData.BenchInfo = new TBF.Rig.DataContainers.BenchInfo.iPerl.Component(cfg);
} }
} }
session.Close(); session.Close();
/// ///
/// Connect to Results database and determine the last saved batch number. /// Connect to Results database and determine the last saved batch number.
/// ///
Results.DB.LoadSharedData(); var rsltDBSession = TBF.DB.ResultsDBSessionFactory.OpenSession();
int maxBatchNr = Results.DB.GetMaxSavedBatchNr(); Results.DB.LoadSharedData(rsltDBSession);
int maxBatchNr = Results.DB.GetMaxSavedBatchNr(rsltDBSession);
if (!TBF.DB.CurrentBench.IsRealBench || Program.LocalSettings.BatchNr <= maxBatchNr) if (!TBF.DB.CurrentBench.IsRealBench || Program.LocalSettings.BatchNr <= maxBatchNr)
{ {
log.FatalFormat("Max. BatchNr in DB = {0}, LocalSettings.BatchNr = {1}", maxBatchNr, Program.LocalSettings.BatchNr); log.FatalFormat("Max. BatchNr in DB = {0}, LocalSettings.BatchNr = {1}", maxBatchNr, Program.LocalSettings.BatchNr);
@ -414,16 +435,16 @@ namespace TBF
Program.LocalSettings.Save(); Program.LocalSettings.Save();
log.FatalFormat("LocalSettings.BatchNr updated to {0}", Program.LocalSettings.BatchNr); 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. /// Connect to Events database (if any) and load recent events from this test bench.
/// ///
if (TBF.DB.CurrentBench.EventsDBSettings.DbType != Common.DBType.None && if (TBF.DB.EventsDBSessionFactory != null)
!string.IsNullOrEmpty(TBF.DB.CurrentBench.EventsDBSettings.ConnectionString))
{ {
Events.DB.DbType = (DBType)TBF.DB.CurrentBench.EventsDBSettings.DbType; var evntsDBsession = TBF.DB.EventsDBSessionFactory.OpenSession();
Events.DB.ConnectionString = TBF.DB.CurrentBench.EventsDBSettings.ConnectionString; Events.DB.LoadRecentEvents(evntsDBsession, loginDlgBench.BenchName, 7); /// Last 7 days
Events.DB.LoadRecentEvents(Events.DB.CreateSession(), loginDlgBench.BenchName, 7); /// Last 7 days evntsDBsession.Close();
} }
retryLogin = false; retryLogin = false;
@ -460,7 +481,7 @@ namespace TBF
default: default:
/// Open 'DatabaseSetingsDlg' and retry DB connect on OK /// 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) new TBF.UI.Settings.BenchesDlg().ShowDialog() == DialogResult.Cancel)
{ {
return; /// Exit program return; /// Exit program
@ -482,26 +503,31 @@ namespace TBF
/// ///
if (LocalSettings.LastProcedureName != null) if (LocalSettings.LastProcedureName != null)
{ {
IList<Procedure> listOfProcedures = TBF.DB.CreateSession(Common.DBKind.Config) using (var session = TBF.DB.ConfigDBSessionFactory.OpenSession())
.QueryOver<Procedure>()
.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); var listOfProcedures = session.QueryOver<Procedure>()
SelectedProcedure = listOfProcedures[0]; .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 try
{ {
/// Open the main application window /// Open the main application window
log.Info("Creating the main window"); log.Info("Creating the main window");
MainWnd = new UI.MainWnd(); MainWnd = new UI.MainWnd();
log.Info("Opening the main window"); log.Info("Opening the main window");
Application.Run(MainWnd); LoadingConfigEnd();
Application.Run(MainWnd);
log.Info("The main window was closed"); log.Info("The main window was closed");
} }
catch (Exception e) catch (Exception e)
@ -536,5 +562,35 @@ namespace TBF
log.FatalFormat("StackTrace : {0}{1}", Environment.NewLine, e.StackTrace); log.FatalFormat("StackTrace : {0}{1}", Environment.NewLine, e.StackTrace);
log.Fatal("--------------------------------------"); log.Fatal("--------------------------------------");
} }
}
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;
}
}
} }

View File

@ -1896,6 +1896,15 @@ namespace TBF.Resources {
} }
} }
/// <summary>
/// Looks up a localized string similar to Error reading configuration database.
/// </summary>
internal static string Error_reading_configuration_database {
get {
return ResourceManager.GetString("Error_reading_configuration_database", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to Error saving parameters of {0}. /// Looks up a localized string similar to Error saving parameters of {0}.
/// </summary> /// </summary>
@ -5442,6 +5451,15 @@ namespace TBF.Resources {
} }
} }
/// <summary>
/// Looks up a localized string similar to .
/// </summary>
internal static string String1 {
get {
return ResourceManager.GetString("String1", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to Sun. /// Looks up a localized string similar to Sun.
/// </summary> /// </summary>

View File

@ -2323,4 +2323,7 @@
<data name="Printer_selection" xml:space="preserve"> <data name="Printer_selection" xml:space="preserve">
<value>Printer selection</value> <value>Printer selection</value>
</data> </data>
<data name="Error_reading_configuration_database" xml:space="preserve">
<value>Error reading configuration database</value>
</data>
</root> </root>

View File

@ -56,7 +56,7 @@ namespace TBF.Rig.Elde.CoverTest
{ {
if (!Users.CurrentUser.IsMemberOf(bypassLevel)) 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; return;
} }

View File

@ -200,7 +200,7 @@ namespace TBF.Rig.Output.DB.SaveDiverterCorrections
ITransaction transaction = null; ITransaction transaction = null;
try try
{ {
ISession session = TBF.DB.CreateSession(Common.DBKind.Config); var session = TBF.DB.ConfigDBSessionFactory.OpenSession();
transaction = session.BeginTransaction(); transaction = session.BeginTransaction();
for (int div = 1; div <= myCfg.DivertersCount(); div++) for (int div = 1; div <= myCfg.DivertersCount(); div++)

View File

@ -207,7 +207,7 @@ namespace TBF.Rig.Output.DB.SaveFlowmeterCorrections
ITransaction transaction = null; ITransaction transaction = null;
try try
{ {
ISession session = TBF.DB.CreateSession(Common.DBKind.Config); var session = TBF.DB.ConfigDBSessionFactory.OpenSession();
transaction = session.BeginTransaction(); transaction = session.BeginTransaction();
for (int fmtr = 1; fmtr <= myCfg.FlowmetersCount(); fmtr++) for (int fmtr = 1; fmtr <= myCfg.FlowmetersCount(); fmtr++)

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2013-2022 Sensus Slovensko a.s. /// Copyright (c) 2013-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -278,10 +278,7 @@ namespace TBF.Rig.Sequences
try try
{ {
using (ISession localSession = TBF.DB.CreateSession(DBKind.Config)) StateMachine.LoadPathsAndTransitions();
{
StateMachine.LoadPathsAndTransitions(localSession);
}
/// ///
/// Try to load all parameters of selected or restored procedure from the respective database /// 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 /// User has chosen to restore an interrupted session and necessary conditions are met
/// TODO: Repeate twice for DBKind.Config and DBKind.RemoteConfig /// TODO: Repeate twice for DBKind.Config and DBKind.RemoteConfig
using (ISession remoteOrLocalSession = TBF.DB.CreateSession(isRemoteIntProc ? using (var session =
DBKind.RemoteConfig : (isRemoteIntProc ? TBF.DB.SharedDBSessionFactory : TBF.DB.ConfigDBSessionFactory).OpenSession())
DBKind.Config))
{ {
StateMachine.LoadProcedure(remoteOrLocalSession, interruptedProcedureName, isRemoteIntProc); StateMachine.LoadProcedure(session, interruptedProcedureName, isRemoteIntProc);
StateMachine.LoadProcedureParams(StateMachine.Procedure); 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; int a = 0;
foreach (var test in StateMachine.Procedure.Tests) a += test.MoreParams.Count; 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 /// TODO: Repeate twice for SharedDBSessionFactory and ConfigDBSessionFactory
using (ISession remoteOrLocalSession = TBF.DB.CreateSession(Bridge.SelectedProcedure.IsRemote ? using (var session =
DBKind.RemoteConfig : (Bridge.SelectedProcedure.IsRemote ? TBF.DB.SharedDBSessionFactory : TBF.DB.ConfigDBSessionFactory).OpenSession())
DBKind.Config))
{ {
StateMachine.LoadProcedure(remoteOrLocalSession, Bridge.SelectedProcedure.Name, Bridge.SelectedProcedure.IsRemote, testsInside); StateMachine.LoadProcedure(session, Bridge.SelectedProcedure.Name, Bridge.SelectedProcedure.IsRemote, testsInside);
StateMachine.LoadProcedureParams(StateMachine.Procedure); 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; int a = 0;
foreach (var test in StateMachine.Procedure.Tests) a += test.MoreParams.Count; foreach (var test in StateMachine.Procedure.Tests)
#if false
/// Debugging SensusTestInfo.GetBestMatch()
if (selection == Selection.Cycle && OracleDB != null && OracleDB.ProductionDB != null)
{ {
try a += test.MoreParams.Count;
#if ORACLE_DB
if (test.OraId != 0 || test.OraIdRepetMulti != 0 || test.RawDataId != 0 || test.RawDataIdRepetMulti != 0)
{ {
OracleDB.ProductionDB.Open(); log.WarnFormat(" {0} OraId = {1}+{2}*(repNr-1) RawDataId = {3}+{4}*(repNr-1)",
test.Name, test.OraId, test.OraIdRepetMulti, test.RawDataId, test.RawDataIdRepetMulti);
int wmTypeId = 170;
/// Prepare procedure signature
IList<string> wmTestNames = new List<string>();
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<Results.Output.SensusTestInfo> 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();
} }
catch (Exception exc) else
#endif
{ {
string msg = exc.Message; log.WarnFormat(" {0}", test.Name);
} }
} }
#endif
} }
} }
else else
@ -509,8 +461,10 @@ namespace TBF.Rig.Sequences
b.EndTime = DateTime.MinValue; /// Disable the batch end time estimate b.EndTime = DateTime.MinValue; /// Disable the batch end time estimate
Batch sampleBatch = null; Batch sampleBatch = null;
using (ISession rsltsDB = Results.DB.CreateSession()) ISession rsltsDB = null;
try
{ {
rsltsDB = TBF.DB.ResultsDBSessionFactory.OpenSession();
var bts = rsltsDB.QueryOver<Batch>() var bts = rsltsDB.QueryOver<Batch>()
.OrderBy(x => x.BatchNr).Desc .OrderBy(x => x.BatchNr).Desc
.Where(x => x.ProcedureName == StateMachine.Procedure.Name) .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; 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) if (loginDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{ {
isApprovedByLegalizator = true; isApprovedByLegalizator = true;

View File

@ -212,9 +212,11 @@ namespace TBF.Rig
public static void InitializeBoardEtc(ControlComponent_Torino2015.UserControl1 ctrlBrdComponent) public static void InitializeBoardEtc(ControlComponent_Torino2015.UserControl1 ctrlBrdComponent)
#endif #endif
{ {
var session = TBF.DB.ConfigDBSessionFactory.OpenSession();
/// Load the list of components (entities) from the database. /// Load the list of components (entities) from the database.
/// Then create the components (derived from IComponent). /// 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); MasterValves = GenericDevices.ValveBase.MasterValves(components);
CoupledValves = GenericDevices.ValveBase.CoupledValves(components); CoupledValves = GenericDevices.ValveBase.CoupledValves(components);
ExtendedValves = GenericDevices.ValveBase.ExtendedValves(components); ExtendedValves = GenericDevices.ValveBase.ExtendedValves(components);
@ -297,6 +299,8 @@ namespace TBF.Rig
if ((eldeValve != null) && eldeValve.Inverted) valvesToInvert |= eldeValve.Mask; if ((eldeValve != null) && eldeValve.Inverted) valvesToInvert |= eldeValve.Mask;
} }
session.Close();
/// Pre-initialize the control board (= buffer the arguments ctrlBrdComponent, tankCapacities) /// Pre-initialize the control board (= buffer the arguments ctrlBrdComponent, tankCapacities)
if (ControlBoard != null) if (ControlBoard != null)
{ {
@ -426,37 +430,42 @@ namespace TBF.Rig
/// <returns>true when DB-s are compatible</returns> /// <returns>true when DB-s are compatible</returns>
public static bool IsRemoteDBCompatible(out string message) public static bool IsRemoteDBCompatible(out string message)
{ {
IList<Config.Entities.FeedingPath> remoteFeedingPaths; IList<Config.Entities.FeedingPath> remoteFeedingPaths = new List<Config.Entities.FeedingPath>();
IList<Config.Entities.BenchPath> remoteBenchPaths; IList<Config.Entities.BenchPath> remoteBenchPaths = new List<Config.Entities.BenchPath>();
IList<Config.Entities.OutputPath> remoteOutputPaths; IList<Config.Entities.OutputPath> remoteOutputPaths = new List<Config.Entities.OutputPath>();
IList<Config.Entities.MetersPath> remoteMetersPaths; IList<Config.Entities.MetersPath> remoteMetersPaths = new List<Config.Entities.MetersPath>();
IList<Config.Entities.TransitionSequence> remoteTransitions; IList<Config.Entities.TransitionSequence> remoteTransitions = new List<Config.Entities.TransitionSequence>();
try try
{ {
ISession remoteSession = TBF.DB.CreateSession(Common.DBKind.RemoteConfig); var remoteSession = TBF.DB.SharedDBSessionFactory.OpenSession();
remoteFeedingPaths = remoteSession.QueryOver<Config.Entities.FeedingPath>().List(); remoteFeedingPaths = remoteSession.QueryOver<Config.Entities.FeedingPath>().List();
remoteBenchPaths = remoteSession.QueryOver<Config.Entities.BenchPath>().List(); remoteBenchPaths = remoteSession.QueryOver<Config.Entities.BenchPath>().List();
remoteOutputPaths = remoteSession.QueryOver<Config.Entities.OutputPath>().List(); remoteOutputPaths = remoteSession.QueryOver<Config.Entities.OutputPath>().List();
remoteMetersPaths = remoteSession.QueryOver<Config.Entities.MetersPath>().List(); remoteMetersPaths = remoteSession.QueryOver<Config.Entities.MetersPath>().List();
remoteTransitions = remoteSession.QueryOver<Config.Entities.TransitionSequence>().List(); remoteTransitions = remoteSession.QueryOver<Config.Entities.TransitionSequence>().List();
remoteSession.Close();
} }
catch (Exception exc) catch (Exception exc)
{ {
message = (exc.InnerException != null) 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}\r\nInner exception:\r\n{1}", exc.Message, exc.InnerException.Message)
: string.Format("\r\nException:\r\n{0}", exc.Message); : string.Format("\r\nException:\r\n{0}", exc.Message);
return false; return false;
} }
ISession localSession = TBF.DB.CreateSession(Common.DBKind.Config); var localSession = TBF.DB.ConfigDBSessionFactory.OpenSession();
var localFeedingPaths = localSession.QueryOver<Config.Entities.FeedingPath>().List(); var localFeedingPaths = localSession.QueryOver<Config.Entities.FeedingPath>().List();
var localBenchPaths = localSession.QueryOver<Config.Entities.BenchPath>().List(); var localBenchPaths = localSession.QueryOver<Config.Entities.BenchPath>().List();
var localOutputPaths = localSession.QueryOver<Config.Entities.OutputPath>().List(); var localOutputPaths = localSession.QueryOver<Config.Entities.OutputPath>().List();
var localMetersPaths = localSession.QueryOver<Config.Entities.MetersPath>().List(); var localMetersPaths = localSession.QueryOver<Config.Entities.MetersPath>().List();
var localTransitions = localSession.QueryOver<Config.Entities.TransitionSequence>().List(); var localTransitions = localSession.QueryOver<Config.Entities.TransitionSequence>().List();
localSession.Close();
string subMsg; string subMsg;
if (!IsCompatible(localFeedingPaths, remoteFeedingPaths, out subMsg)) if (!IsCompatible(localFeedingPaths, remoteFeedingPaths, out subMsg))
{ {
@ -558,17 +567,37 @@ namespace TBF.Rig
/// Loads all paths and transitions from the DB. /// Loads all paths and transitions from the DB.
/// Updates StatMachine.feedingPaths ... StatMachine.meterPaths, StatMachine.TransitionSequences /// Updates StatMachine.feedingPaths ... StatMachine.meterPaths, StatMachine.TransitionSequences
/// </summary> /// </summary>
public static void LoadPathsAndTransitions(ISession session) public static void LoadPathsAndTransitions(ISession session = null)
{ {
feedingPaths = session.QueryOver<Config.Entities.FeedingPath>().OrderBy(x => x.ItemNr).Asc.List(); bool openAndCloseSession = (session == null);
benchPaths = session.QueryOver<Config.Entities.BenchPath>().OrderBy(x => x.ItemNr).Asc.List(); try
outputPaths = session.QueryOver<Config.Entities.OutputPath>().OrderBy(x => x.ItemNr).Asc.List(); {
metersPaths = session.QueryOver<Config.Entities.MetersPath>().OrderBy(x => x.ItemNr).Asc.List(); if (openAndCloseSession) session = TBF.DB.ConfigDBSessionFactory.OpenSession();
TransitionSequences = session.QueryOver<TransitionSequence>().OrderBy(x => x.ItemNr).Asc.List();
TransitionSteps = session.QueryOver<TransitionStep>().OrderBy(x => x.ItemNr).Asc.List(); feedingPaths = session.QueryOver<Config.Entities.FeedingPath>().OrderBy(x => x.ItemNr).Asc.List();
benchPaths = session.QueryOver<Config.Entities.BenchPath>().OrderBy(x => x.ItemNr).Asc.List();
outputPaths = session.QueryOver<Config.Entities.OutputPath>().OrderBy(x => x.ItemNr).Asc.List();
metersPaths = session.QueryOver<Config.Entities.MetersPath>().OrderBy(x => x.ItemNr).Asc.List();
TransitionSequences = session.QueryOver<TransitionSequence>().OrderBy(x => x.ItemNr).Asc.List();
TransitionSteps = session.QueryOver<TransitionStep>().OrderBy(x => x.ItemNr).Asc.List();
#if HEAT_METERS #if HEAT_METERS
heatMetersPaths = session.QueryOver<Config.Entities.HeatMetersPath>().OrderBy(x => x.ItemNr).Asc.List(); heatMetersPaths = session.QueryOver<Config.Entities.HeatMetersPath>().OrderBy(x => x.ItemNr).Asc.List();
#endif #endif
session.Flush();
}
catch (Exception e)
{
feedingPaths = new List<Config.Entities.FeedingPath>();
benchPaths = new List<Config.Entities.BenchPath>();
outputPaths = new List<Config.Entities.OutputPath>();
metersPaths = new List<Config.Entities.MetersPath>();
TransitionSequences = new List<TransitionSequence>();
TransitionSteps = new List<TransitionStep>();
}
finally
{
if (openAndCloseSession && (session != null) && session.IsOpen) session.Close();
}
} }
/// <summary> /// <summary>
@ -579,15 +608,16 @@ namespace TBF.Rig
{ {
Procedure = null; Procedure = null;
IList<Procedure> selectedProcs = session.QueryOver<Procedure>() var selectedProcedure = session.QueryOver<Procedure>()
.Where(x => (x.ProcedureState == Common.ProcedureState.Active)) .Where(x => (x.ProcedureState == Common.ProcedureState.Active))
.And(x => (x.Name == procedureName)) .And(x => (x.Name == procedureName))
.List(); .List();
if (selectedProcs.Count == 1)
if (selectedProcedure.Count == 1)
{ {
IsRemoteProcedure = isRemote; IsRemoteProcedure = isRemote;
Procedure = selectedProcs[0]; Procedure = selectedProcedure[0];
TestInstances = selectedProcs[0].UpdateTestInstances(LoopStartNames, LoopEndNames, autoTests); TestInstances = selectedProcedure[0].UpdateTestInstances(LoopStartNames, LoopEndNames, autoTests);
return true; return true;
} }
else else

View File

@ -247,6 +247,8 @@ namespace TBF.Rig
{ {
CurrentlyLoadedComponentName = string.Empty; CurrentlyLoadedComponentName = string.Empty;
if (session == null) return new List<IComponent>(); /// Handle case when session == null
/// Load the list of components from the database /// Load the list of components from the database
var cmptnEntities = session.QueryOver<Config.Entities.Component>() var cmptnEntities = session.QueryOver<Config.Entities.Component>()
.OrderBy(x => x.ItemNr).Asc .OrderBy(x => x.ItemNr).Asc
@ -263,6 +265,15 @@ namespace TBF.Rig
IComponent cmpnt = cmpntFactory.GetComponent(cmpntFactory.CmpntCfgFromCmpntEntity(entity), components); 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) /// Inherit DebugMode from the parent (if any)
/// ///

View File

@ -64,19 +64,22 @@ namespace TBF.Rig.TestMethods.Endurance
seqStepsCtrl = new CycleStepsCtrl() as ITabWithListViewEx; seqStepsCtrl = new CycleStepsCtrl() as ITabWithListViewEx;
/// Prepare a list of valves for the endurance test /// Prepare a list of valves for the endurance test
TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(TBF.DB.CreateSession(Common.DBKind.Config)); using (var session = TBF.DB.ConfigDBSessionFactory.OpenSession())
Valves = new List<IValve>(); {
for (int bitNr = 0; bitNr < 8; bitNr++) TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(session);
{ Valves = new List<IValve>();
foreach (var vlv in TbfComponents) for (int bitNr = 0; bitNr < 8; bitNr++)
{ {
if (vlv is Rig.Elde.Valve.Valve && (vlv as Rig.Elde.Valve.Valve).BitPosition == bitNr) foreach (var vlv in TbfComponents)
{ {
Valves.Add(vlv as IValve); if (vlv is Rig.Elde.Valve.Valve && (vlv as Rig.Elde.Valve.Valve).BitPosition == bitNr)
break; {
} Valves.Add(vlv as IValve);
} break;
} }
}
}
}
EnduranceCycle = (cycle != null) ? cycle : new List<CycleStep>(); /// TODO: Load from component parameters EnduranceCycle = (cycle != null) ? cycle : new List<CycleStep>(); /// TODO: Load from component parameters

View File

@ -112,65 +112,65 @@ namespace TBF.Rig.TestMethods.Q2CorrectionFromHistory
/// Invalidate any previous Q2 Pre-Corrections /// Invalidate any previous Q2 Pre-Corrections
IsQ2PreCorrectionCalculated = false; IsQ2PreCorrectionCalculated = false;
ISession session = null;
try try
{ {
using (ISession session = Results.DB.CreateSession()) session = TBF.DB.ResultsDBSessionFactory.OpenSession();
Batch btc = null;
var batches = session.QueryOver<Batch>(() => btc)
.Where(bb => (bb.ProcedureName == cfg.ProcedureName))
.List();
if (!string.IsNullOrEmpty(cfg.ProcedureNameAlt1))
{ {
Batch btc = null; IList<Batch> batches2 = session.QueryOver<Batch>(() => btc)
var batches = session.QueryOver<Batch>(() => btc) .Where(bb => (bb.ProcedureName == cfg.ProcedureNameAlt1))
.Where(bb => (bb.ProcedureName == cfg.ProcedureName)) .List();
.List(); foreach (var b in batches2) batches.Add(b);
}
if (!string.IsNullOrEmpty(cfg.ProcedureNameAlt2))
{
IList<Batch> batches3 = session.QueryOver<Batch>(() => btc)
.Where(bb => (bb.ProcedureName == cfg.ProcedureNameAlt2))
.List();
foreach (var b in batches3) batches.Add(b);
}
if (!string.IsNullOrEmpty(cfg.ProcedureNameAlt1)) int samplesCount = 0;
{ double q2CorrLRsum = 0;
IList<Batch> batches2 = session.QueryOver<Batch>(() => btc) double q2CorrRLsum = 0;
.Where(bb => (bb.ProcedureName == cfg.ProcedureNameAlt1))
.List();
foreach (var b in batches2) batches.Add(b);
}
if (!string.IsNullOrEmpty(cfg.ProcedureNameAlt2))
{
IList<Batch> batches3 = session.QueryOver<Batch>(() => btc)
.Where(bb => (bb.ProcedureName == cfg.ProcedureNameAlt2))
.List();
foreach (var b in batches3) batches.Add(b);
}
int samplesCount = 0; var sortedBatches = batches.OrderByDescending(b => b.EndTime);
double q2CorrLRsum = 0; foreach (var b in sortedBatches)
double q2CorrRLsum = 0; {
foreach (var wm in b.WaterMeters)
var sortedBatches = batches.OrderByDescending(b => b.EndTime);
foreach (var b in sortedBatches)
{ {
foreach (var wm in b.WaterMeters) if ((wm != null) && !wm.Disabled && wm.Passed)
{ {
if ((wm != null) && !wm.Disabled && wm.Passed)
{
#if IPERL #if IPERL
q2CorrLRsum += wm.Q2CorrLR; q2CorrLRsum += wm.Q2CorrLR;
q2CorrRLsum += wm.Q2CorrRL; q2CorrRLsum += wm.Q2CorrRL;
#endif #endif
samplesCount++; samplesCount++;
}
} }
if (samplesCount >= 200) break;
} }
if (samplesCount >= 200) if (samplesCount >= 200) break;
{ }
IsQ2PreCorrectionCalculated = true;
CalculatedQ2PreCorrectionLR = (int)Math.Round(q2CorrLRsum / samplesCount); if (samplesCount >= 200)
CalculatedQ2PreCorrectionRL = (int)Math.Round(q2CorrRLsum / samplesCount); {
log.WarnFormat("Q2 corrections calculated OK: LR = {0}, RL = {1}", CalculatedQ2PreCorrectionLR, CalculatedQ2PreCorrectionRL); IsQ2PreCorrectionCalculated = true;
return true; CalculatedQ2PreCorrectionLR = (int)Math.Round(q2CorrLRsum / samplesCount);
} CalculatedQ2PreCorrectionRL = (int)Math.Round(q2CorrRLsum / samplesCount);
else log.WarnFormat("Q2 corrections calculated OK: LR = {0}, RL = {1}", CalculatedQ2PreCorrectionLR, CalculatedQ2PreCorrectionRL);
{ return true;
log.ErrorFormat("Not enough samples to calculate Q2 corrections ({0})", samplesCount); }
return false; else
} {
log.ErrorFormat("Not enough samples to calculate Q2 corrections ({0})", samplesCount);
return false;
} }
} }
catch (Exception exc) catch (Exception exc)
@ -178,6 +178,10 @@ namespace TBF.Rig.TestMethods.Q2CorrectionFromHistory
log.ErrorFormat("Failed to calculate Q2 corrections: {0}", exc.Message); log.ErrorFormat("Failed to calculate Q2 corrections: {0}", exc.Message);
return false; return false;
} }
finally
{
if (session != null && session.IsOpen) session.Close();
}
} }
} }
} }

View File

@ -121,45 +121,52 @@ namespace TBF.Rig.Various.StatisticsMonitoring
/// Take into account only batches where the 1st test in named 'RFID' and /// Take into account only batches where the 1st test in named 'RFID' and
/// at least one water meter completed all tests. /// at least one water meter completed all tests.
/// ///
try
{ {
ISession session = Results.DB.CreateSession(); ISession session = null;
try
int usagesMin;
do
{ {
usagesMin = 0; session = TBF.DB.ResultsDBSessionFactory.OpenSession();
IList<Batch> batches = session.QueryOver<Batch>()
.Where(x => x.BatchNr == batchNr)
.List();
batchNr--;
if (batches.Count != 1 || batches[0].TestRslts.Count < 1 || batches[0].TestRslts[0].MethodClass != "TestMethods.iPerlCommunication")
{
continue;
}
bool isACompleteBatch = false; int usagesMin;
foreach (var wm in batches[0].WaterMeters) do
{ {
int i = wm.WMPosition - 1; usagesMin = 0;
if (0 <= i && i < TBF.Data.WMsCount && usages[i] < RequiredUsages && !wm.Disabled && wm.CompletedFromTests()) IList<Batch> batches = session.QueryOver<Batch>()
.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; continue;
usages[i]++;
if (!wm.MeterTestRslts[0].Passed) failures[i]++;
} }
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++;
} }
while ((usagesMin < RequiredUsages) && (batchNr > 0) && (completeBatchesProcessed < MaxBatches));
usagesMin = int.MaxValue; }
for (int i = 0; i < TBF.Data.WMsCount; i++) if (usagesMin > usages[i]) usagesMin = usages[i]; catch (Exception exc)
{
if (isACompleteBatch) completeBatchesProcessed++; 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 /// Trigger events
/// ///
ISession session = null;
try try
{ {
ISession session = Events.DB.CreateSession(); session = TBF.DB.EventsDBSessionFactory.OpenSession();
Events.DB.LoadSubscribers(session); Events.DB.LoadSubscribers(session);
for (int i = 0; i < TBF.Data.WMsCount; i++) 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); log.ErrorFormat("Failed to trigger events: source = {0}, message = {1}", statisticsCfg.EventSource, exc.Message);
} }
finally
{
if (session != null && session.IsOpen) session.Close();
}
} }
} }
} }

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2013-2021 Sensus Slovensko a.s. /// Copyright (c) 2013-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -24,12 +24,10 @@ namespace TBF.UI.Bench.Components
/// <summary> /// <summary>
/// List of components (=component configuration instances) /// List of components (=component configuration instances)
/// </summary> /// </summary>
public ISession Session;
IList<Component> cmpntEntities; IList<Component> cmpntEntities;
IList<Component> toBeDeletedEntities; IList<Component> toBeDeletedEntities;
ISession session;
SelectComponentClassDlg selectComponentTypeDlg; /// Constructed once, the selection is kept between dialog usages SelectComponentClassDlg selectComponentTypeDlg; /// Constructed once, the selection is kept between dialog usages
CfgUpdateFlags flags; /// Or-ed from particular Flags from ComponentParametersDlg CfgUpdateFlags flags; /// Or-ed from particular Flags from ComponentParametersDlg
@ -64,6 +62,14 @@ namespace TBF.UI.Bench.Components
InitializeComponent(); 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; flags = CfgUpdateFlags.None;
selectComponentTypeDlg = new SelectComponentClassDlg(); selectComponentTypeDlg = new SelectComponentClassDlg();
@ -121,11 +127,9 @@ namespace TBF.UI.Bench.Components
sharedButtons.DisableButtons(SharedButtons.Buttons.Remove | SharedButtons.Buttons.Edit); sharedButtons.DisableButtons(SharedButtons.Buttons.Remove | SharedButtons.Buttons.Edit);
session = TBF.DB.CreateSession(Common.DBKind.Config); cmpntEntities = Session.QueryOver<Component>()
cmpntEntities = session.QueryOver<Component>()
.OrderBy(x => x.ItemNr).Asc .OrderBy(x => x.ItemNr).Asc
.List<Component>(); .List<Component>();
RedrawAll(); RedrawAll();
} }
@ -372,7 +376,7 @@ namespace TBF.UI.Bench.Components
{ {
if ((flags & CfgUpdateFlags.AnyChange) != 0 || (flags & CfgUpdateFlags.RestartRqrd) != 0) if ((flags & CfgUpdateFlags.AnyChange) != 0 || (flags & CfgUpdateFlags.RestartRqrd) != 0)
{ {
SaveDBChanges(session); SaveDBChanges(Session);
flags = CfgUpdateFlags.None; /// Changes saved flags = CfgUpdateFlags.None; /// Changes saved
} }
@ -696,11 +700,12 @@ namespace TBF.UI.Bench.Components
MessageBoxIcon.Question); MessageBoxIcon.Question);
if (dr == DialogResult.Yes) if (dr == DialogResult.Yes)
{ {
SaveDBChanges(session); SaveDBChanges(Session);
} }
} }
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
if (Session != null && Session.IsOpen) Session.Close();
} }

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2013-2019 Sensus Slovensko a.s. /// Copyright (c) 2013-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -17,14 +17,21 @@ namespace TBF.UI.Bench.Metrology
{ {
static readonly ILog log = LogManager.GetLogger(typeof(MetrologyDlg)); static readonly ILog log = LogManager.GetLogger(typeof(MetrologyDlg));
public IList<Component> cmpntEntities; public ISession Session;
public IList<Component> cmpntEntities;
ISession session;
public MetrologyDlg() public MetrologyDlg()
{ {
InitializeComponent(); 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 /// SharedDlgButtons configuration
sharedButtons.ParentForm = this; sharedButtons.ParentForm = this;
sharedButtons.RequiredGroupMembership = new Common.GID[] { Common.GID.Metrologists, Common.GID.MetrologicalAuthority }; sharedButtons.RequiredGroupMembership = new Common.GID[] { Common.GID.Metrologists, Common.GID.MetrologicalAuthority };
@ -52,11 +59,9 @@ namespace TBF.UI.Bench.Metrology
int platinumTempMetersCount = 0; int platinumTempMetersCount = 0;
int evaporationsCount = 0; int evaporationsCount = 0;
session = TBF.DB.CreateSession(Common.DBKind.Config); cmpntEntities = (Session == null) ? new List<Component>() : Session.QueryOver<Component>()
cmpntEntities = session.QueryOver<Component>() .OrderBy(x => x.ItemNr).Asc
.OrderBy(x => x. ItemNr).Asc .List();
.List();
foreach (var cmpnt in cmpntEntities) foreach (var cmpnt in cmpntEntities)
{ {
Rig.Generic.IComponentFactory factory = TbfComponents.CmpntFactoryFromClassName(cmpnt.ClassName); Rig.Generic.IComponentFactory factory = TbfComponents.CmpntFactoryFromClassName(cmpnt.ClassName);
@ -226,7 +231,7 @@ namespace TBF.UI.Bench.Metrology
metrologyTabControl.TabPages.Add(tabPage); metrologyTabControl.TabPages.Add(tabPage);
} }
} }
} }
private void unlockButton_Click(object sender, EventArgs e) 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) private void okButton_Click(object sender, EventArgs e)
{ {
using (ITransaction transaction = session.BeginTransaction()) using (ITransaction transaction = Session.BeginTransaction())
{ {
try try
{ {
@ -248,12 +253,12 @@ namespace TBF.UI.Bench.Metrology
if (tab != null) if (tab != null)
{ {
tab.OkBtnClicked(); tab.OkBtnClicked();
tab.SaveEntityToDB(session); tab.SaveEntityToDB(Session);
foreach (var entity in tab.ToBeRemoved) session.Delete(entity); foreach (var entity in tab.ToBeRemoved) Session.Delete(entity);
} }
} }
transaction.Commit(); transaction.Commit();
session.Flush(); Session.Flush();
} }
catch (Exception exc) catch (Exception exc)
{ {
@ -347,6 +352,7 @@ namespace TBF.UI.Bench.Metrology
private void MetrologyDlg_FormClosing(object sender, FormClosingEventArgs e) private void MetrologyDlg_FormClosing(object sender, FormClosingEventArgs e)
{ {
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
if (Session != null && Session.IsOpen) Session.Close();
} }
} }
} }

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2013-2022 Sensus Slovensko a.s. /// Copyright (c) 2013-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; 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 /// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi
public readonly int Dpi; public readonly int Dpi;
public IList<Rig.Generic.IComponent> TbfComponents; public ISession Session; /// One common DB session passed also to the controls inside tab pages
public IList<Rig.Generic.IComponent> TbfComponents;
public IList<IValve> Valves; public IList<IValve> Valves;
public IList<IRegValve> FeedingRegValves; public IList<IRegValve> FeedingRegValves;
public IList<IRegValve> OutputRegValves; public IList<IRegValve> OutputRegValves;
public ISession Session; /// One common DB session passed also to the controls inside tab pages
public IList<Procedure> Procedures; public IList<Procedure> Procedures;
public IList<Test> Tests; public IList<Test> Tests;
@ -52,6 +52,14 @@ namespace TBF.UI.Bench.Paths
InitializeComponent(); 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 /// SharedDlgButtons configuration
sharedButtons.ParentForm = this; sharedButtons.ParentForm = this;
sharedButtons.RequiredGroupMembership = new GID[] { GID.Metrologists }; sharedButtons.RequiredGroupMembership = new GID[] { GID.Metrologists };
@ -66,15 +74,7 @@ namespace TBF.UI.Bench.Paths
sharedButtons.DownClicked += downButton_Click; sharedButtons.DownClicked += downButton_Click;
/// Load the list of components from the database /// Load the list of components from the database
try TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(Session);
{
TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(TBF.DB.CreateSession(Common.DBKind.Config));
}
catch
{
TbfComponents = new List<Rig.Generic.IComponent>();
MessageBox.Show("Error occured when loading components");
}
/// Find all master valves /// Find all master valves
Valves = Rig.GenericDevices.ValveBase.MasterValves(TbfComponents); 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<Procedure>().List(); Procedures = Session.QueryOver<Procedure>().List();
Tests = Session.QueryOver<Test>().List(); Tests = Session.QueryOver<Test>().List();
@ -371,6 +368,7 @@ namespace TBF.UI.Bench.Paths
private void PathsDlg_FormClosing(object sender, FormClosingEventArgs e) private void PathsDlg_FormClosing(object sender, FormClosingEventArgs e)
{ {
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
if (Session != null && Session.IsOpen) Session.Close();
} }
} }
} }

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2019-2022 Sensus Slovensko a.s. /// Copyright (c) 2019-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; 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 /// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi
public readonly int Dpi; public readonly int Dpi;
readonly NHibernate.ISession session;
readonly bool openUnlocked; readonly bool openUnlocked;
/// <summary> /// <summary>
@ -52,26 +53,21 @@ namespace TBF.UI.Bench.TestProfiles
openUnlocked = false; openUnlocked = false;
} }
public TestProfileDlg(Profile profile, IList<string> usedNames, bool openUnlocked, Form parentForm) public TestProfileDlg(NHibernate.ISession session, Profile profile, IList<string> usedNames, bool openUnlocked, Form parentForm)
: this() : this()
{ {
if (profile == null) throw new ArgumentNullException("profile"); if (profile == null) throw new ArgumentNullException("profile");
this.session = session;
LoadedProfile = profile; LoadedProfile = profile;
this.usedNames = usedNames; this.usedNames = usedNames;
this.openUnlocked = openUnlocked; this.openUnlocked = openUnlocked;
TestMethods = new List<ITestMethod>(); /// Prepare a list of components and a list of test methods
using (NHibernate.ISession session = TBF.DB.CreateSession(DBKind.Config)) TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(this.session);
{
/// Prepare a list of components and a list of test methods
TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(session);
if (TbfComponents != null) TestMethods = new List<ITestMethod>();
foreach (var c in TbfComponents) foreach (var c in TbfComponents) if (c is ITestMethod) TestMethods.Add(c as ITestMethod);
if (c is ITestMethod)
TestMethods.Add(c as ITestMethod);
}
/// SharedDlgButtons configuration /// SharedDlgButtons configuration
sharedButtons.ParentForm = parentForm; sharedButtons.ParentForm = parentForm;

View File

@ -928,7 +928,7 @@
<value>sharedButtons</value> <value>sharedButtons</value>
</data> </data>
<data name="&gt;&gt;sharedButtons.Type" xml:space="preserve"> <data name="&gt;&gt;sharedButtons.Type" xml:space="preserve">
<value>TBF.UI.Shared.SharedButtons, TBF, Version=2.27.1917.0, Culture=neutral, PublicKeyToken=null</value> <value>TBF.UI.Shared.SharedButtons, TBF, Version=2.32.2027.0, Culture=neutral, PublicKeyToken=null</value>
</data> </data>
<data name="&gt;&gt;sharedButtons.Parent" xml:space="preserve"> <data name="&gt;&gt;sharedButtons.Parent" xml:space="preserve">
<value>mainSplitContainer.Panel2</value> <value>mainSplitContainer.Panel2</value>

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2019-2022 Sensus Slovensko a.s. /// Copyright (c) 2019-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -51,11 +51,11 @@ namespace TBF.UI.Bench.TestProfiles
{ {
if (Parent == null) return; if (Parent == null) return;
session = TBF.DB.CreateSession(Common.DBKind.Config);
this.parent = parent; this.parent = parent;
this.parentControl = parentControl; this.parentControl = parentControl;
session = parent.Session;
SubItemClicked += new SubItemEventHandler(listViewEx_SubItemClicked); SubItemClicked += new SubItemEventHandler(listViewEx_SubItemClicked);
SubItemEndEditing += new SubItemEndEditingEventHandler(listViewEx_SubItemEndEditing); SubItemEndEditing += new SubItemEndEditingEventHandler(listViewEx_SubItemEndEditing);
@ -217,7 +217,7 @@ namespace TBF.UI.Bench.TestProfiles
newProfile.CreationUser = Users.CurrentUser.UserName(); newProfile.CreationUser = Users.CurrentUser.UserName();
newProfile.CreationTime = DateTime.Now; 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 /// TODO: Make name uniqueness test
parent.Unlock(); parent.Unlock();
@ -297,7 +297,7 @@ namespace TBF.UI.Bench.TestProfiles
IList<string> usedNames = GetUsedNames(false); IList<string> usedNames = GetUsedNames(false);
usedNames.Remove(editedProfile.Name.ToLower()); /// Allow original procedure name 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(); parent.Unlock();
@ -342,7 +342,7 @@ namespace TBF.UI.Bench.TestProfiles
newProfile.CreationUser = Users.CurrentUser.UserName(); newProfile.CreationUser = Users.CurrentUser.UserName();
newProfile.CreationTime = DateTime.Now; 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 /// TODO: Make name uniqueness test
parent.Unlock(); parent.Unlock();
@ -391,7 +391,7 @@ namespace TBF.UI.Bench.TestProfiles
newProfile.CreationUser = Users.CurrentUser.UserName(); newProfile.CreationUser = Users.CurrentUser.UserName();
newProfile.CreationTime = DateTime.Now; 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 /// TODO: Make name uniqueness test
parent.Unlock(); parent.Unlock();

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2019 Sensus Slovensko a.s. /// Copyright (c) 2019-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; 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 /// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi
public readonly int Dpi; public readonly int Dpi;
public NHibernate.ISession Session;
public TestProfilesDlg() public TestProfilesDlg()
{ {
/// Detect display setting: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi. /// Detect display setting: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi.
@ -26,6 +28,14 @@ namespace TBF.UI.Bench.TestProfiles
InitializeComponent(); 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 /// SharedDlgButtons configuration
sharedButtons.ParentForm = this; sharedButtons.ParentForm = this;
sharedButtons.RequiredGroupMembership = new GID[] { GID.MetrologicalAuthority }; sharedButtons.RequiredGroupMembership = new GID[] { GID.MetrologicalAuthority };
@ -82,7 +92,7 @@ namespace TBF.UI.Bench.TestProfiles
/// <param name="e"></param> /// <param name="e"></param>
private void okButton_Click(object sender, EventArgs e) private void okButton_Click(object sender, EventArgs e)
{ {
ProceduresDlg_FormClosed(sender, null); TestProfilesDlg_FormClosed(sender, null);
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
Close(); Close();
@ -93,7 +103,7 @@ namespace TBF.UI.Bench.TestProfiles
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ProceduresDlg_FormClosed(object sender, FormClosedEventArgs e) private void TestProfilesDlg_FormClosed(object sender, FormClosedEventArgs e)
{ {
testProfilesCtrl.OkBtnClicked(); testProfilesCtrl.OkBtnClicked();
SaveUISettings(); SaveUISettings();
@ -224,6 +234,7 @@ namespace TBF.UI.Bench.TestProfiles
private void TestProfilesDlg_FormClosing(object sender, FormClosingEventArgs e) private void TestProfilesDlg_FormClosing(object sender, FormClosingEventArgs e)
{ {
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
if (Session != null && Session.IsOpen) Session.Close();
} }
} }
} }

View File

@ -89,7 +89,7 @@ namespace TBF.UI.Bench.TestProfiles
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "TestProfilesDlg"; this.Text = "TestProfilesDlg";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.TestProfilesDlg_FormClosing); 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.Load += new System.EventHandler(this.TestProfilesDlg_Load);
this.splitContainer.Panel1.ResumeLayout(false); this.splitContainer.Panel1.ResumeLayout(false);
this.splitContainer.Panel2.ResumeLayout(false); this.splitContainer.Panel2.ResumeLayout(false);

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2013-2017 Sensus Metering Systems /// Copyright (c) 2013-2023 Sensus Metering Systems
/// ///
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -66,6 +66,14 @@ namespace TBF.UI.Bench.Transitions
InitializeComponent(); 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 /// SharedDlgButtons configuration
sharedButtons.ParentForm = this; sharedButtons.ParentForm = this;
sharedButtons.RequiredGroupMembership = new Common.GID[] { Common.GID.Metrologists }; sharedButtons.RequiredGroupMembership = new Common.GID[] { Common.GID.Metrologists };
@ -90,9 +98,6 @@ namespace TBF.UI.Bench.Transitions
seqStepsCtrls = new List<ITabWithListViewEx>(); seqStepsCtrls = new List<ITabWithListViewEx>();
/// 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 /// Prepare a list of components and a list of all valves in the test bench
TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(Session); TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(Session);
Valves = Rig.GenericDevices.ValveBase.MasterValves(TbfComponents); Valves = Rig.GenericDevices.ValveBase.MasterValves(TbfComponents);
@ -107,10 +112,20 @@ namespace TBF.UI.Bench.Transitions
/// Load the sequences /// Load the sequences
/// Note: Each sequence (in both sequences together) has a unique ItemNr (0 .. N-1) /// Note: Each sequence (in both sequences together) has a unique ItemNr (0 .. N-1)
TransitionSequences = Session.QueryOver<TransitionSequence>().OrderBy(x => x.ItemNr).Asc.List(); if (Session != null)
VirtualBenchSequences = Session.QueryOver<VirtualBenchSequence>().OrderBy(x => x.ItemNr).Asc.List(); {
procedures = Session.QueryOver<Procedure>().List(); TransitionSequences = Session.QueryOver<TransitionSequence>().OrderBy(x => x.ItemNr).Asc.List();
tests = Session.QueryOver<Test>().List(); VirtualBenchSequences = Session.QueryOver<VirtualBenchSequence>().OrderBy(x => x.ItemNr).Asc.List();
procedures = Session.QueryOver<Procedure>().List();
tests = Session.QueryOver<Test>().List();
}
else
{
TransitionSequences = new List<TransitionSequence>();
VirtualBenchSequences = new List<VirtualBenchSequence>();
procedures = new List<Procedure>();
tests = new List<Test>();
}
RemovedTransitionSequences = new List<TransitionSequence>(); RemovedTransitionSequences = new List<TransitionSequence>();
RemovedVirtualBenchSequences = new List<VirtualBenchSequence>(); RemovedVirtualBenchSequences = new List<VirtualBenchSequence>();
@ -708,6 +723,7 @@ namespace TBF.UI.Bench.Transitions
private void TransitionsDlg_FormClosing(object sender, FormClosingEventArgs e) private void TransitionsDlg_FormClosing(object sender, FormClosingEventArgs e)
{ {
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
if (Session != null && Session.IsOpen) Session.Close();
} }
} }
} }

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2019 Sensus Slovensko a.s. /// Copyright (c) 2019-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -17,14 +17,21 @@ namespace TBF.UI.Bench.Uncertainties
{ {
static readonly ILog log = LogManager.GetLogger(typeof(UncertaintiesDlg)); static readonly ILog log = LogManager.GetLogger(typeof(UncertaintiesDlg));
public ISession Session;
public IList<Component> cmpntEntities; public IList<Component> cmpntEntities;
ISession session;
public UncertaintiesDlg() public UncertaintiesDlg()
{ {
InitializeComponent(); 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 /// SharedDlgButtons configuration
sharedButtons.ParentForm = this; sharedButtons.ParentForm = this;
#if KEMPNO_50 #if KEMPNO_50
@ -55,11 +62,9 @@ namespace TBF.UI.Bench.Uncertainties
int tempMetersCount = 0; int tempMetersCount = 0;
int evaporationsCount = 0; int evaporationsCount = 0;
session = TBF.DB.CreateSession(Common.DBKind.Config); cmpntEntities = (Session == null) ? new List<Component>() : Session.QueryOver<Component>()
cmpntEntities = session.QueryOver<Component>() .OrderBy(x => x. ItemNr).Asc
.OrderBy(x => x. ItemNr).Asc .List();
.List();
foreach (var cmpnt in cmpntEntities) foreach (var cmpnt in cmpntEntities)
{ {
Rig.Generic.IComponentFactory factory = TbfComponents.CmpntFactoryFromClassName(cmpnt.ClassName); 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) private void okButton_Click(object sender, EventArgs e)
{ {
using (ITransaction transaction = session.BeginTransaction()) using (ITransaction transaction = Session.BeginTransaction())
{ {
try try
{ {
@ -211,12 +216,12 @@ namespace TBF.UI.Bench.Uncertainties
if (tab != null) if (tab != null)
{ {
tab.OkBtnClicked(); tab.OkBtnClicked();
session.SaveOrUpdate(tab.MeterEntity); Session.SaveOrUpdate(tab.MeterEntity);
foreach (var entity in tab.ToBeRemoved) session.Delete(entity); foreach (var entity in tab.ToBeRemoved) Session.Delete(entity);
} }
} }
transaction.Commit(); transaction.Commit();
session.Flush(); Session.Flush();
} }
catch (Exception exc) catch (Exception exc)
{ {
@ -310,6 +315,7 @@ namespace TBF.UI.Bench.Uncertainties
private void UncertaintiesDlg_FormClosing(object sender, FormClosingEventArgs e) private void UncertaintiesDlg_FormClosing(object sender, FormClosingEventArgs e)
{ {
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
if (Session != null && Session.IsOpen) Session.Close();
} }
} }
} }

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2020 Sensus Slovensko a.s. /// Copyright (c) 2020-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -61,14 +61,15 @@ namespace TBF.UI.Calendar
calendarEventsListViewEx.Items.Add(lvi); calendarEventsListViewEx.Items.Add(lvi);
} }
public void StartCalendar(IList<ICalendarEvent> eventsFromComponents) public void StartCalendar(IList<ICalendarEvent> eventsFromComponents, ISession session = null)
{ {
bool openAndCloseSession = (session == null);
this.eventsFromComponents = eventsFromComponents; this.eventsFromComponents = eventsFromComponents;
try try
{ {
/// Read custom events from the database /// Read custom events from the database
ISession session = TBF.DB.CreateSession(Common.DBKind.Config); if (openAndCloseSession) session = TBF.DB.ConfigDBSessionFactory.OpenSession();
customEvents = session.QueryOver<CustomEvent>().List(); customEvents = session.QueryOver<CustomEvent>().List();
TripplicateShiftCustomEvents(customEvents); TripplicateShiftCustomEvents(customEvents);
@ -85,6 +86,7 @@ namespace TBF.UI.Calendar
/// Serve events (determine if any event was triggered) /// Serve events (determine if any event was triggered)
lastTimeCalendarEventsServed = DateTime.Now; lastTimeCalendarEventsServed = DateTime.Now;
ServeCalendarEventsNotifWarnErrorFatal(lastTimeCalendarEventsServed, session, customEvents); ServeCalendarEventsNotifWarnErrorFatal(lastTimeCalendarEventsServed, session, customEvents);
if (openAndCloseSession) session.Close();
} }
catch (Exception) catch (Exception)
{ {
@ -118,13 +120,14 @@ namespace TBF.UI.Calendar
} }
} }
/// <summary> /// <summary>
/// Triggers events corresponding to triggered motification.warning/error calendar events. /// Triggers events corresponding to triggered motification.warning/error calendar events.
/// </summary> /// </summary>
/// <param name="currentTime">Current time</param> /// <param name="currentTime">Current time</param>
void ServeCalendarEventsNotifWarnErrorFatal(DateTime currentTime, ISession parentSession = null, IList<CustomEvent> customEventsFromDB = null) void ServeCalendarEventsNotifWarnErrorFatal(DateTime currentTime, ISession session = null, IList<CustomEvent> customEventsFromDB = null)
{ {
bool openAndCloseSession = (session == null);
IList<Events.Entities.Event> eventsToTrigger = new List<Events.Entities.Event>(); IList<Events.Entities.Event> eventsToTrigger = new List<Events.Entities.Event>();
for (int i = eventsFromComponents.Count - 1; i >= 0; i--) for (int i = eventsFromComponents.Count - 1; i >= 0; i--)
@ -160,7 +163,8 @@ namespace TBF.UI.Calendar
try 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<CustomEvent>() .List(); var customEvents = (customEventsFromDB != null) ? customEventsFromDB : session.QueryOver<CustomEvent>() .List();
for (int i = customEvents.Count - 1; i >= 0; i--) for (int i = customEvents.Count - 1; i >= 0; i--)
@ -194,32 +198,27 @@ namespace TBF.UI.Calendar
} }
} }
session.Flush(); session.Flush();
if (openAndCloseSession) session.Close();
} }
catch (Exception exc) catch (Exception exc)
{ {
log.ErrorFormat("Failed to load or update CustomEvent-s in ServeTriggerEvtCalendarEvents(): {0}", exc.Message); 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(evtDBSession);
global::Events.DB.LoadSubscribers(session);
foreach (var e in eventsToTrigger) foreach (var e in eventsToTrigger)
{ {
TBF.UiBridge.Bridge.TriggerEvent(session, e); TBF.UiBridge.Bridge.TriggerEvent(evtDBSession, e);
} }
session.Flush(); evtDBSession.Close();
}
catch (Exception exc)
{
log.ErrorFormat("Failed to trigger events in ServeTriggerEvtCalendarEvents(): {0}", exc.Message);
} }
} }
} }
/// <summary> /// <summary>
/// Returns an array of parameters of selected actions. /// Returns an array of parameters of selected actions.
/// This function is not invoked from UI thread. /// This function is not invoked from UI thread.
@ -234,9 +233,10 @@ namespace TBF.UI.Calendar
if (maxCount <= 0) return parametersList; if (maxCount <= 0) return parametersList;
ISession session = null;
try try
{ {
ISession session = TBF.DB.CreateSession(Common.DBKind.Config); session = TBF.DB.ConfigDBSessionFactory.OpenSession();
var customEventsFromDB = session.QueryOver<CustomEvent>().List(); var customEventsFromDB = session.QueryOver<CustomEvent>().List();
for (int i = customEventsFromDB.Count - 1; i >= 0; i--) for (int i = customEventsFromDB.Count - 1; i >= 0; i--)
@ -258,12 +258,15 @@ namespace TBF.UI.Calendar
if (parametersList.Count >= maxCount) break; if (parametersList.Count >= maxCount) break;
} }
} }
session.Flush();
} }
catch (Exception exc) catch (Exception exc)
{ {
log.ErrorFormat("Failed to load or update CustomEvent-s in ServeSelectedCalendarEvents(): {0}", exc.Message); 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) if (parametersList.Count > 0)
{ {
@ -273,7 +276,6 @@ namespace TBF.UI.Calendar
return parametersList; return parametersList;
} }
/// <summary> /// <summary>
/// Convert calendar event AutoAction to event Severity /// Convert calendar event AutoAction to event Severity
/// </summary> /// </summary>
@ -291,7 +293,6 @@ namespace TBF.UI.Calendar
} }
} }
void TripplicateShiftCustomEvents(IList<CustomEvent> customEvents) void TripplicateShiftCustomEvents(IList<CustomEvent> customEvents)
{ {
/// Tripplicate each custom event with frequency 'EveryShift' /// Tripplicate each custom event with frequency 'EveryShift'
@ -314,15 +315,15 @@ namespace TBF.UI.Calendar
} }
} }
private void newEventButton_Click(object sender, EventArgs ea) private void newEventButton_Click(object sender, EventArgs ea)
{ {
EventDetailsForm dlg = new EventDetailsForm(); EventDetailsForm dlg = new EventDetailsForm();
if (dlg.ShowDialog() == DialogResult.OK && dlg.NewEvent is CustomEvent) if (dlg.ShowDialog() == DialogResult.OK && dlg.NewEvent is CustomEvent)
{ {
ISession session = null;
try try
{ {
ISession session = TBF.DB.CreateSession(Common.DBKind.Config); session = TBF.DB.ConfigDBSessionFactory.OpenSession();
session.SaveOrUpdate(dlg.NewEvent as CustomEvent); session.SaveOrUpdate(dlg.NewEvent as CustomEvent);
session.Flush(); session.Flush();
@ -341,12 +342,15 @@ namespace TBF.UI.Calendar
} }
catch (Exception) 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) private void calendarEventsListViewEx_MouseDoubleClick(object sender, MouseEventArgs mea)
{ {
if (calendarEventsListViewEx.SelectedIndices.Count != 1) return; if (calendarEventsListViewEx.SelectedIndices.Count != 1) return;
@ -355,10 +359,11 @@ namespace TBF.UI.Calendar
EventDetailsForm dlg = new EventDetailsForm { Event = evnt }; EventDetailsForm dlg = new EventDetailsForm { Event = evnt };
if (dlg.ShowDialog() != DialogResult.OK) return; if (dlg.ShowDialog() != DialogResult.OK) return;
ISession session = null;
try try
{ {
/// Re-read selected custom event from the database /// 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<CustomEvent>() var cEvents = session.QueryOver<CustomEvent>()
.Where(x => (x.Id == evnt.Id)) .Where(x => (x.Id == evnt.Id))
.List(); .List();
@ -399,7 +404,11 @@ namespace TBF.UI.Calendar
} }
catch (Exception) 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();
} }
} }
} }

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2013-2021 Sensus Slovensko a.s. /// Copyright (c) 2013-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -13,6 +13,7 @@ using Config.Entities;
using TBF.Resources; using TBF.Resources;
using TBF.UiBridge; using TBF.UiBridge;
using TBF.UI.Shared; using TBF.UI.Shared;
using NHibernate;
namespace TBF.UI namespace TBF.UI
{ {
@ -539,18 +540,24 @@ namespace TBF.UI
{ {
Users.DB.ConnectionString = TBF.DB.CurrentBench.ProceduresDBSettings.ConnectionString; Users.DB.ConnectionString = TBF.DB.CurrentBench.ProceduresDBSettings.ConnectionString;
Users.DB.DbType = TBF.DB.CurrentBench.ProceduresDBSettings.DbType; Users.DB.DbType = TBF.DB.CurrentBench.ProceduresDBSettings.DbType;
using (ISession session = Users.DB.CreateSession())
{
#if TURA_IPERL || TURA_IPERL_NEW || TURA_SPECIAL #if TURA_IPERL || TURA_IPERL_NEW || TURA_SPECIAL
Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(Users.DB.CreateSession(), true); Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(session, true);
string connStr = Users.DB.ConnectionString; string connStr = Users.DB.ConnectionString;
int len = connStr.ToUpper().IndexOf("; UID="); int len = connStr.ToUpper().IndexOf("; UID=");
if (len == -1) len = connStr.ToUpper().IndexOf("; USER="); if (len == -1) len = connStr.ToUpper().IndexOf("; USER=");
if (len > 0) dlg.TitleExtension = connStr.Substring(0, len); if (len > 0) dlg.TitleExtension = connStr.Substring(0, len);
#else #else
Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(Users.DB.CreateSession(), false); Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(session, false);
#endif #endif
dlg.ShowDialog(); dlg.ShowDialog();
session.Close();
}
} }
private void languageTSMItem_Click(object s, EventArgs e) { new TBF.UI.Settings.LanguageDlg().ShowDialog(); } private void languageTSMItem_Click(object s, EventArgs e) { new TBF.UI.Settings.LanguageDlg().ShowDialog(); }
private void databaseSettingsTSMItem_Click(object s, EventArgs e) private void databaseSettingsTSMItem_Click(object s, EventArgs e)
{ {
TBF.UI.Settings.BenchesDlg dlg = new TBF.UI.Settings.BenchesDlg(); 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 backUpConfigTSMItem_Click(object s, EventArgs e) { BackupConfiguration(); }
private void backUpResultsTSMItem_Click(object s, EventArgs e) { BackupResults(); } 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(); } 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; Rig.GenericDevices.IBenchInfo benchInfo = Rig.Sequences.ProcessData.BenchInfo;
RemoteDBUse remoteDbUse = (benchInfo != null) ? benchInfo.RemoteDBUse : RemoteDBUse.LocalDBOnly; RemoteDBUse remoteDbUse = (benchInfo != null) ? benchInfo.RemoteDBUse : RemoteDBUse.LocalDBOnly;
Common.DBKind[] dBase; ISessionFactory[] dBase;
string[] signature; string[] signature;
/// ///
switch (remoteDbUse) switch (remoteDbUse)
{ {
default: default:
case RemoteDBUse.LocalDBOnly: case RemoteDBUse.LocalDBOnly:
dBase = new Common.DBKind[] { Common.DBKind.Config }; dBase = new ISessionFactory[] { TBF.DB.ConfigDBSessionFactory };
signature = new string[] { "" }; signature = new string[] { "" };
break; break;
case RemoteDBUse.RemoteDBOnly: case RemoteDBUse.RemoteDBOnly:
dBase = new Common.DBKind[] { Common.DBKind.RemoteConfig }; dBase = new ISessionFactory[] { TBF.DB.SharedDBSessionFactory };
signature = new string[] { "R" }; signature = new string[] { "R" };
break; break;
case RemoteDBUse.BothDBsLocalFirst: 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" }; signature = new string[] { "L", "R" };
break; break;
case RemoteDBUse.BothDBsRemoteFirst: 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" }; signature = new string[] { "R", "L" };
break; break;
} }
@ -625,23 +638,30 @@ namespace TBF.UI
ProcedureNrs.Clear(); ProcedureNrs.Clear();
for (int i = 0; i < dBase.Length; i++) for (int i = 0; i < dBase.Length; i++)
{ {
IList<Procedure> procedures = TBF.DB.CreateSession(dBase[i]) if (dBase[i] != null)
.QueryOver<Procedure>()
.Where(x => (x.ProcedureState == ProcedureState.Active))
.OrderBy(x => x.ItemNr).Asc
.List();
foreach (var proc in procedures)
{ {
string itemText = string.Format("{0}{1}{2}{3}", signature[i], proc.ItemNr + 1, ProcSeparator, proc.Name); var session = dBase[i].OpenSession();
procedureComboBox.Items.Add(itemText); var procedures = session.QueryOver<Procedure>()
if (!ProcedureNrs.ContainsKey(proc.Name)) ProcedureNrs.Add(proc.Name, proc.ItemNr + 1); .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; string itemText = string.Format("{0}{1}{2}{3}", signature[i], proc.ItemNr + 1, ProcSeparator, proc.Name);
SelectedProcedure = new ProcedureInfo(procedureNameToSelect, (dBase[i] == Common.DBKind.RemoteConfig)); procedureComboBox.Items.Add(itemText);
procedureSet = true; 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; ProceduresUpdated = false;
if (SelectedProcedure != null) BenchControlPanel.ReloadTests();
} }
else else
{ {
@ -861,7 +879,7 @@ namespace TBF.UI
Common.GID[] reqGrpMembership = null; Common.GID[] reqGrpMembership = null;
#endif #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(); UpdateUser();
} }

View File

@ -19,6 +19,7 @@ using TBF.Rig.GenericDevices;
using TBF.Resources; using TBF.Resources;
using TBF.UI.Shared; using TBF.UI.Shared;
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead; using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
using NHibernate;
namespace TBF.UI.Procedures namespace TBF.UI.Procedures
{ {
@ -47,7 +48,10 @@ namespace TBF.UI.Procedures
IList<string> usedNames; /// Already used names IList<string> usedNames; /// Already used names
///
/// Auxiliary public lists used also by user controls in tab pages /// 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<Rig.Generic.IComponent> TbfComponents; public IList<Rig.Generic.IComponent> TbfComponents;
public IList<IValve> Valves; public IList<IValve> Valves;
public IList<IRegValve> RegulValves; public IList<IRegValve> RegulValves;
@ -118,9 +122,10 @@ namespace TBF.UI.Procedures
SelectedTestIx = -1; SelectedTestIx = -1;
} }
public ProcedureDlg(Procedure procedure, IList<string> usedNames, Mode initialMode, Form parentForm) public ProcedureDlg(ISession session, Procedure procedure, IList<string> usedNames, Mode initialMode, Form parentForm)
: this() : this()
{ {
this.Session = session;
if (procedure == null) throw new ArgumentNullException("procedure"); if (procedure == null) throw new ArgumentNullException("procedure");
LoadedProcedure = procedure; LoadedProcedure = procedure;
@ -139,69 +144,66 @@ namespace TBF.UI.Procedures
#endif #endif
if (initialMode == Mode.PermanentlyLocked) sharedButtons.DisableUnlock(); 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<IRegValve>();
TestMethods = new List<ITestMethod>();
TempControllers = new List<ITempControl>();
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);
/// Prepare a list of components and a list of all valves in the test bench if (cmpnt is ITestMethod) TestMethods.Add(cmpnt as ITestMethod);
/// if (cmpnt is ITempControl) TempControllers.Add(cmpnt as ITempControl);
TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(session); if (cmpnt is IDataEntry) dataEntryComboBox.Items.Add(cmpnt.Cfg.Name);
Valves = Rig.GenericDevices.ValveBase.MasterValves(TbfComponents); if (cmpnt is IResultsPrinter)
RegulValves = new List<IRegValve>(); {
TestMethods = new List<ITestMethod>(); printer1ComboBox.Items.Add(cmpnt.Cfg.Name);
TempControllers = new List<ITempControl>(); printer2ComboBox.Items.Add(cmpnt.Cfg.Name);
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 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 /// Loads paths, this must be done before PrepareMetrology12AndProcessTabs() call
/// ///
feedingPaths = session.QueryOver<FeedingPath>().List(); feedingPaths = Session.QueryOver<FeedingPath>().List();
benchPaths = session.QueryOver<BenchPath>().List(); benchPaths = Session.QueryOver<BenchPath>().List();
outputPaths = session.QueryOver<OutputPath>().List(); outputPaths = Session.QueryOver<OutputPath>().List();
metersPaths = session.QueryOver<MetersPath>().List(); metersPaths = Session.QueryOver<MetersPath>().List();
#if HEAT_METERS #if HEAT_METERS
heatMetersPaths = session.QueryOver<HeatMetersPath>().List(); heatMetersPaths = Session.QueryOver<HeatMetersPath>().List();
#else #else
heatMetersPaths = new List<HeatMetersPath>(); heatMetersPaths = new List<HeatMetersPath>();
#endif #endif
transitionSequences = session.QueryOver<TransitionSequence>().List(); transitionSequences = Session.QueryOver<TransitionSequence>().List();
}
transitionStartComboBox.Items.Add("---"); transitionStartComboBox.Items.Add("---");
transitionEndComboBox.Items.Add("---"); transitionEndComboBox.Items.Add("---");
@ -398,41 +400,50 @@ namespace TBF.UI.Procedures
lastChangedByTextBox.ReadOnly = true; lastChangedByTextBox.ReadOnly = true;
lastChangedOnTextBox.ReadOnly = true; lastChangedOnTextBox.ReadOnly = true;
foreach (var test in LoadedProcedure.Tests) try
{ {
test.VolumeUnit = TBF.Rig.Sequences.ProcessData.VolumeUnit; foreach (var test in LoadedProcedure.Tests)
test.FlowUnit = TBF.Rig.Sequences.ProcessData.FlowUnit; {
test.MassUnit = TBF.Rig.Sequences.ProcessData.MassUnit; test.VolumeUnit = TBF.Rig.Sequences.ProcessData.VolumeUnit;
test.TempUnit = TBF.Rig.Sequences.ProcessData.TempUnit; test.FlowUnit = TBF.Rig.Sequences.ProcessData.FlowUnit;
test.PressUnit = TBF.Rig.Sequences.ProcessData.PressUnit; test.MassUnit = TBF.Rig.Sequences.ProcessData.MassUnit;
test.LengthUnit = TBF.Rig.Sequences.ProcessData.LengthUnit; test.TempUnit = TBF.Rig.Sequences.ProcessData.TempUnit;
test.ResetChngdFlags(); 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'
/// 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();
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);
} }
/// 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();
/// 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();
}
/// Optionally unlock this dialog /// Optionally unlock this dialog
if (initialMode == Mode.Unlocked) if (initialMode == Mode.Unlocked)
@ -712,19 +723,16 @@ namespace TBF.UI.Procedures
void RefreshHistoryTab() void RefreshHistoryTab()
{ {
NHibernate.ISession session = TBF.DB.CreateSession(DBKind.Config); var procedures = Session.QueryOver<Procedure>()
IList<Procedure> procedures = session .Where(x => x.ProcedureState == ProcedureState.History)
.QueryOver<Procedure>() .List();
.Where(x => x.ProcedureState == ProcedureState.History)
.List();
int predecessorId = LoadedProcedure.PredecessorId; int predecessorId = LoadedProcedure.PredecessorId;
IList<Procedure> oneProcedure = session var oneProcedure = Session.QueryOver<Procedure>()
.QueryOver<Procedure>() .Where(x => (x.ProcedureState == ProcedureState.Active))
.Where(x => (x.ProcedureState == ProcedureState.Active)) .And(x => (x.Id == predecessorId))
.And(x => (x.Id == predecessorId)) .List();
.List();
if (oneProcedure.Count == 1) if (oneProcedure.Count == 1)
{ {
@ -762,7 +770,7 @@ namespace TBF.UI.Procedures
} }
if (!found) break; if (!found) break;
} }
} }
void UpdateFromHistoryTab() void UpdateFromHistoryTab()
{ {
@ -3002,8 +3010,8 @@ namespace TBF.UI.Procedures
break; break;
} }
using (NHibernate.ISession session = TBF.DB.CreateSession(DBKind.Config)) try
{ {
IList<Test> testsToBeUpdated = new List<Test>(); IList<Test> testsToBeUpdated = new List<Test>();
foreach (var test in LoadedProcedure.Tests) 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) private void historyListViewEx_MouseDoubleClick(object sender, MouseEventArgs e)
@ -3158,7 +3172,7 @@ namespace TBF.UI.Procedures
if (lvi.Tag is Procedure) if (lvi.Tag is Procedure)
{ {
(new ProcedureDlg(lvi.Tag as Procedure, new List<string>(), ProcedureDlg.Mode.PermanentlyLocked, sharedButtons.ParentForm)).ShowDialog(); (new ProcedureDlg(Session, lvi.Tag as Procedure, new List<string>(), ProcedureDlg.Mode.PermanentlyLocked, sharedButtons.ParentForm)).ShowDialog();
} }
} }

View File

@ -2170,7 +2170,7 @@
<value>sharedButtons</value> <value>sharedButtons</value>
</data> </data>
<data name="&gt;&gt;sharedButtons.Type" xml:space="preserve"> <data name="&gt;&gt;sharedButtons.Type" xml:space="preserve">
<value>TBF.UI.Shared.SharedButtons, TBF, Version=2.27.1917.0, Culture=neutral, PublicKeyToken=null</value> <value>TBF.UI.Shared.SharedButtons, TBF, Version=2.32.2027.0, Culture=neutral, PublicKeyToken=null</value>
</data> </data>
<data name="&gt;&gt;sharedButtons.Parent" xml:space="preserve"> <data name="&gt;&gt;sharedButtons.Parent" xml:space="preserve">
<value>mainSplitContainer.Panel2</value> <value>mainSplitContainer.Panel2</value>

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2020-2022 Sensus Slovensko a.s. /// Copyright (c) 2020-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -20,6 +20,12 @@ namespace TBF.UI.Procedures
{ {
static readonly ILog log = LogManager.GetLogger(typeof(ProceduresCtrl)); 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; } }
/// <summary> /// <summary>
/// List of all active procedures /// List of all active procedures
/// </summary> /// </summary>
@ -60,11 +66,8 @@ namespace TBF.UI.Procedures
Count Count
} }
ProceduresDlg parent;
Control parentControl;
Control[] editors; Control[] editors;
ISession session;
IWaterMeter waterMeterCmpnt; IWaterMeter waterMeterCmpnt;
IErrorFlags errorFlagsCmpnt; IErrorFlags errorFlagsCmpnt;
@ -72,7 +75,6 @@ namespace TBF.UI.Procedures
{ {
InitializeComponent(); InitializeComponent();
session = null;
waterMeterCmpnt = null; waterMeterCmpnt = null;
errorFlagsCmpnt = null; errorFlagsCmpnt = null;
ToBeRemovedProcedures = new List<Procedure>(); ToBeRemovedProcedures = new List<Procedure>();
@ -116,9 +118,6 @@ namespace TBF.UI.Procedures
{ {
if (parent == null) return; if (parent == null) return;
/// Create a DB session
session = TBF.DB.CreateSession(DBKind.Config);
this.parent = parent; this.parent = parent;
this.parentControl = parentControl; this.parentControl = parentControl;
@ -168,7 +167,7 @@ namespace TBF.UI.Procedures
if (isFirstTime) if (isFirstTime)
{ {
/// Find WaterMeter and ErrorFlags components, this is done just once when AllProcedures == null /// 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 (waterMeterCmpnt == null && cmpnt is IWaterMeter) waterMeterCmpnt = cmpnt as IWaterMeter;
if (errorFlagsCmpnt == null && cmpnt is IErrorFlags) errorFlagsCmpnt = cmpnt as IErrorFlags; if (errorFlagsCmpnt == null && cmpnt is IErrorFlags) errorFlagsCmpnt = cmpnt as IErrorFlags;
@ -176,7 +175,7 @@ namespace TBF.UI.Procedures
} }
/// (Re)Load all procedures unconditionally /// (Re)Load all procedures unconditionally
AllProcedures = session.QueryOver<Procedure>() AllProcedures = Session.QueryOver<Procedure>()
.Where(x => (x.ProcedureState == ProcedureState.Active)) .Where(x => (x.ProcedureState == ProcedureState.Active))
.OrderBy(x => x.ItemNr).Asc .OrderBy(x => x.ItemNr).Asc
.List(); .List();
@ -269,22 +268,22 @@ namespace TBF.UI.Procedures
/// </summary> /// </summary>
public void OkBtnClicked() public void OkBtnClicked()
{ {
using (ITransaction transaction = session.BeginTransaction()) using (ITransaction transaction = Session.BeginTransaction())
{ {
try try
{ {
foreach (var entity in ToBeRemovedProcedures) session.Delete(entity); foreach (var entity in ToBeRemovedProcedures) Session.Delete(entity);
ToBeRemovedProcedures.Clear(); ToBeRemovedProcedures.Clear();
int itemNr = 0; int itemNr = 0;
foreach (var proc in AllProcedures) foreach (var proc in AllProcedures)
{ {
(proc as Procedure).ItemNr = itemNr++; (proc as Procedure).ItemNr = itemNr++;
session.SaveOrUpdate(proc); Session.SaveOrUpdate(proc);
} }
transaction.Commit(); transaction.Commit();
session.Flush(); Session.Flush();
} }
catch (Exception exc) catch (Exception exc)
{ {
@ -328,12 +327,12 @@ namespace TBF.UI.Procedures
newProcedure.CreationUser = Users.CurrentUser.UserName(); newProcedure.CreationUser = Users.CurrentUser.UserName();
newProcedure.CreationTime = DateTime.Now; 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 /// TODO: Make name uniqueness test
parent.Unlock(); parent.Unlock();
using (var transaction = session.BeginTransaction()) using (var transaction = Session.BeginTransaction())
{ {
try try
{ {
@ -341,7 +340,7 @@ namespace TBF.UI.Procedures
newProcedure.LastChgTime = DateTime.Now; newProcedure.LastChgTime = DateTime.Now;
DoAddOne(newProcedure); DoAddOne(newProcedure);
session.SaveOrUpdate(newProcedure); Session.SaveOrUpdate(newProcedure);
transaction.Commit(); transaction.Commit();
MessageBox.Show(string.Format(Strings.Procedure_0_added, newProcedure.Name), MessageBox.Show(string.Format(Strings.Procedure_0_added, newProcedure.Name),
@ -393,22 +392,22 @@ namespace TBF.UI.Procedures
} }
/// Update the database /// Update the database
using (ITransaction transaction = session.BeginTransaction()) using (ITransaction transaction = Session.BeginTransaction())
{ {
try try
{ {
foreach (var entity in ToBeRemovedProcedures) session.Delete(entity); foreach (var entity in ToBeRemovedProcedures) Session.Delete(entity);
ToBeRemovedProcedures.Clear(); ToBeRemovedProcedures.Clear();
int itemNr = 0; int itemNr = 0;
foreach (var entity in Procedures) foreach (var entity in Procedures)
{ {
(entity as Procedure).ItemNr = itemNr++; (entity as Procedure).ItemNr = itemNr++;
session.SaveOrUpdate(entity); Session.SaveOrUpdate(entity);
} }
transaction.Commit(); transaction.Commit();
session.Flush(); Session.Flush();
} }
catch (Exception exc) catch (Exception exc)
{ {
@ -565,11 +564,11 @@ namespace TBF.UI.Procedures
IList<string> usedNames = GetUsedNames(false); IList<string> usedNames = GetUsedNames(false);
usedNames.Remove(originalProcedure.Name.ToLower()); /// Allow original procedure name 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(); parent.Unlock();
using (var transaction = session.BeginTransaction()) using (var transaction = Session.BeginTransaction())
{ {
try try
{ {
@ -577,8 +576,8 @@ namespace TBF.UI.Procedures
modifiedProcedure.LastChgUser = Users.CurrentUser.UserName(); modifiedProcedure.LastChgUser = Users.CurrentUser.UserName();
modifiedProcedure.LastChgTime = DateTime.Now; modifiedProcedure.LastChgTime = DateTime.Now;
session.SaveOrUpdate(originalProcedure); Session.SaveOrUpdate(originalProcedure);
session.SaveOrUpdate(modifiedProcedure); Session.SaveOrUpdate(modifiedProcedure);
transaction.Commit(); transaction.Commit();
listViewEx.SelectedItems[0].Tag = modifiedProcedure; listViewEx.SelectedItems[0].Tag = modifiedProcedure;
@ -595,7 +594,7 @@ namespace TBF.UI.Procedures
transaction.Rollback(); transaction.Rollback();
} }
} }
session.Flush(); Session.Flush();
} }
ReloadAndRedrawAll(); ReloadAndRedrawAll();
@ -620,18 +619,18 @@ namespace TBF.UI.Procedures
newProcedure.CreationTime = DateTime.Now; newProcedure.CreationTime = DateTime.Now;
newProcedure.Protected = false; 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 /// TODO: Make name uniqueness test
parent.Unlock(); parent.Unlock();
using (var transaction = session.BeginTransaction()) using (var transaction = Session.BeginTransaction())
{ {
newProcedure.LastChgUser = Users.CurrentUser.UserName(); newProcedure.LastChgUser = Users.CurrentUser.UserName();
newProcedure.LastChgTime = DateTime.Now; newProcedure.LastChgTime = DateTime.Now;
DoAddOne(newProcedure); DoAddOne(newProcedure);
session.SaveOrUpdate(newProcedure); Session.SaveOrUpdate(newProcedure);
transaction.Commit(); transaction.Commit();
MessageBox.Show(string.Format(Strings.Procedure_0_added, newProcedure.Name), MessageBox.Show(string.Format(Strings.Procedure_0_added, newProcedure.Name),
@ -673,18 +672,18 @@ namespace TBF.UI.Procedures
newProcedure.CreationUser = Users.CurrentUser.UserName(); newProcedure.CreationUser = Users.CurrentUser.UserName();
newProcedure.CreationTime = DateTime.Now; 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 /// TODO: Make name uniqueness test
parent.Unlock(); parent.Unlock();
using (var transaction = session.BeginTransaction()) using (var transaction = Session.BeginTransaction())
{ {
newProcedure.LastChgUser = Users.CurrentUser.UserName(); newProcedure.LastChgUser = Users.CurrentUser.UserName();
newProcedure.LastChgTime = DateTime.Now; newProcedure.LastChgTime = DateTime.Now;
DoAddOne(newProcedure); DoAddOne(newProcedure);
session.SaveOrUpdate(newProcedure); Session.SaveOrUpdate(newProcedure);
transaction.Commit(); transaction.Commit();
MessageBox.Show(string.Format(Strings.Procedure_0_added, newProcedure.Name), MessageBox.Show(string.Format(Strings.Procedure_0_added, newProcedure.Name),
@ -725,12 +724,12 @@ namespace TBF.UI.Procedures
try try
{ {
profiles = session.QueryOver<Profile>() profiles = Session.QueryOver<Profile>()
.OrderBy(x => x.ItemNr).Asc .OrderBy(x => x.ItemNr).Asc
.List(); .List();
fPaths = session.QueryOver<FeedingPath>().OrderBy(x => x.ItemNr).Asc.List(); fPaths = Session.QueryOver<FeedingPath>().OrderBy(x => x.ItemNr).Asc.List();
bPaths = session.QueryOver<BenchPath>().OrderBy(x => x.ItemNr).Asc.List(); bPaths = Session.QueryOver<BenchPath>().OrderBy(x => x.ItemNr).Asc.List();
oPaths = session.QueryOver<OutputPath>().OrderBy(x => x.ItemNr).Asc.List(); oPaths = Session.QueryOver<OutputPath>().OrderBy(x => x.ItemNr).Asc.List();
} }
catch (Exception) catch (Exception)
{ {
@ -759,11 +758,11 @@ namespace TBF.UI.Procedures
IList<IParamsProvider> errorFlagsParamsOfCreatedTests = new List<IParamsProvider>(); IList<IParamsProvider> errorFlagsParamsOfCreatedTests = new List<IParamsProvider>();
IList<IParamsProvider> waterMeterParamsOfNewProcedure = new List<IParamsProvider>(); IList<IParamsProvider> waterMeterParamsOfNewProcedure = new List<IParamsProvider>();
IList<Component> cmpntEntities = session.QueryOver<Component>() IList<Component> cmpntEntities = Session.QueryOver<Component>()
.OrderBy(x => x.ItemNr).Asc .OrderBy(x => x.ItemNr).Asc
.List<Component>(); .List<Component>();
IList<Rig.Generic.IComponent> components = Rig.TbfComponents.LoadComponentsFromDB(session); IList<Rig.Generic.IComponent> components = Rig.TbfComponents.LoadComponentsFromDB(Session);
foreach (var cmptn in components) foreach (var cmptn in components)
{ {
if (cmptn.ClassName == "WaterMeter") if (cmptn.ClassName == "WaterMeter")
@ -845,12 +844,12 @@ namespace TBF.UI.Procedures
newProcedure.CreationUser = Users.CurrentUser.UserName(); newProcedure.CreationUser = Users.CurrentUser.UserName();
newProcedure.CreationTime = DateTime.Now; 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 /// TODO: Make name uniqueness test
parent.Unlock(); parent.Unlock();
using (var transaction = session.BeginTransaction()) using (var transaction = Session.BeginTransaction())
{ {
try try
{ {
@ -858,7 +857,7 @@ namespace TBF.UI.Procedures
newProcedure.LastChgTime = DateTime.Now; newProcedure.LastChgTime = DateTime.Now;
DoAddOne(newProcedure); DoAddOne(newProcedure);
session.SaveOrUpdate(newProcedure); Session.SaveOrUpdate(newProcedure);
foreach (var efp in errorFlagsParamsOfCreatedTests) foreach (var efp in errorFlagsParamsOfCreatedTests)
{ {
@ -1086,7 +1085,7 @@ namespace TBF.UI.Procedures
case MoreContent.Oracle: case MoreContent.Oracle:
if (!string.IsNullOrEmpty(procedure.ResultsWriter) && procedure.ResultsWriter.Contains("Sensus-Oracle-DB")) if (!string.IsNullOrEmpty(procedure.ResultsWriter) && procedure.ResultsWriter.Contains("Sensus-Oracle-DB"))
{ {
var procParamsEntity = session.QueryOver<ComponentProcedure>() var procParamsEntity = Session.QueryOver<ComponentProcedure>()
.Where(x => x.Procedure == procedure) .Where(x => x.Procedure == procedure)
.And(x => x.CmpntName == "Sensus-Oracle-DB") .And(x => x.CmpntName == "Sensus-Oracle-DB")
.List(); .List();

View File

@ -1,9 +1,10 @@
/// ///
/// Copyright (c) 2013-2022 Sensus Slovensko a.s. /// Copyright (c) 2013-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Windows.Forms; using System.Windows.Forms;
using log4net; using log4net;
using NHibernate;
using Common; using Common;
using Common.Forms; using Common.Forms;
using TBF.Resources; using TBF.Resources;
@ -18,6 +19,8 @@ namespace TBF.UI.Procedures
/// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi /// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi
public readonly int Dpi; public readonly int Dpi;
public ISession Session; /// DB session is open in the constructor and closed in _FormClosing handler
public ProceduresDlg() public ProceduresDlg()
{ {
/// Detect display setting: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi. /// Detect display setting: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi.
@ -25,6 +28,14 @@ namespace TBF.UI.Procedures
InitializeComponent(); 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 /// SharedDlgButtons configuration
sharedButtons.ParentForm = this; sharedButtons.ParentForm = this;
sharedButtons.RequiredGroupMembership = new GID[] { GID.TestingSpecialists, GID.Metrologists }; 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 (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
if (Session != null && Session.IsOpen) Session.Close();
} }

View File

@ -131,7 +131,7 @@ namespace TBF.UI.ResultsMI
/// Access only to thise who manage production tracing /// Access only to thise who manage production tracing
GID[] rqrdGroupMembership = new GID[] { GID.TraceabilityManagement }; 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; return;
} }

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2016-2021 Sensus Slovensko a.s. /// Copyright (c) 2016-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -14,11 +14,11 @@ using Oracle.DataAccess.Client;
using Common; using Common;
using Results; using Results;
using Results.Entities; using Results.Entities;
using TBF.Resources;
using TBF.Rig.Generic; using TBF.Rig.Generic;
using TBF.Rig.GenericDevices; using TBF.Rig.GenericDevices;
using TBF.Rig.Output.DB.SensusOracle; using TBF.Rig.Output.DB.SensusOracle;
using TBF.Rig.Sequences; using TBF.Rig.Sequences;
using TBF.Resources;
namespace TBF.UI.ResultsMI namespace TBF.UI.ResultsMI
{ {
@ -33,20 +33,20 @@ namespace TBF.UI.ResultsMI
{ {
static readonly ILog log = LogManager.GetLogger(typeof(PreviousResultsDlg)); static readonly ILog log = LogManager.GetLogger(typeof(PreviousResultsDlg));
ISession session; readonly PreviousResultsMode mode;
int currentBatchNr; readonly int currentBatchNr;
ISession session;
IList<Batch> batches; /// A list of batches selected from all batches using criteria entered in UI IList<Batch> batches; /// A list of batches selected from all batches using criteria entered in UI
IList<string> serialNrs; /// Display only watermeters with these serial numbers (null = display all) IList<string> serialNrs; /// Display only watermeters with these serial numbers (null = display all)
int lastDisplayedIx; /// Index of the last displayed batch from the list 'batches' int lastDisplayedIx; /// Index of the last displayed batch from the list 'batches'
const int LinesCount = 25; /// Number of batches displayed on one screen const int LinesCount = 25; /// Number of batches displayed on one screen
PreviousResultsMode mode;
public PreviousResultsDlg(PreviousResultsMode mode) public PreviousResultsDlg(PreviousResultsMode mode)
{ {
InitializeComponent(); InitializeComponent();
this.mode = mode; this.mode = mode;
currentBatchNr = Program.LocalSettings.BatchNr; 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(); Localize();
@ -90,14 +90,11 @@ namespace TBF.UI.ResultsMI
toDateTimePicker.CustomFormat = Constants.DateFormat; toDateTimePicker.CustomFormat = Constants.DateFormat;
toDateTimePicker.ShowUpDown = true; toDateTimePicker.ShowUpDown = true;
try try { session = TBF.DB.ResultsDBSessionFactory.OpenSession(); }
catch (Exception e)
{ {
session = Results.DB.CreateSession(); MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message,
} Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
catch (Exception exc)
{
session = null;
log.ErrorFormat("Opening Results DB failed: {0}", exc.Message);
} }
batches = GetFilteredBatches(out lastDisplayedIx, out serialNrs); batches = GetFilteredBatches(out lastDisplayedIx, out serialNrs);
@ -129,7 +126,7 @@ namespace TBF.UI.ResultsMI
if (string.IsNullOrEmpty(procedureTextBox.Text) && string.IsNullOrEmpty(snTextBox.Text)) if (string.IsNullOrEmpty(procedureTextBox.Text) && string.IsNullOrEmpty(snTextBox.Text))
{ {
rslt = session.QueryOver<Batch>() rslt = session.QueryOver<Batch>()
.Where(x => (x.StartTime >= fromDateTimePicker.Value)) .Where(x => (x.EndTime >= fromDateTimePicker.Value))
.And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1))) .And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1)))
.OrderBy(x => x.BatchNr).Asc .OrderBy(x => x.BatchNr).Asc
.List(); .List();
@ -137,7 +134,7 @@ namespace TBF.UI.ResultsMI
else if (string.IsNullOrEmpty(snTextBox.Text)) else if (string.IsNullOrEmpty(snTextBox.Text))
{ {
rslt = session.QueryOver<Batch>() rslt = session.QueryOver<Batch>()
.Where(x => (x.StartTime >= fromDateTimePicker.Value)) .Where(x => (x.EndTime >= fromDateTimePicker.Value))
.And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1))) .And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1)))
.And(x => (x.ProcedureName == procedureTextBox.Text)) .And(x => (x.ProcedureName == procedureTextBox.Text))
.OrderBy(x => x.BatchNr).Asc .OrderBy(x => x.BatchNr).Asc
@ -146,7 +143,7 @@ namespace TBF.UI.ResultsMI
else if (string.IsNullOrEmpty(procedureTextBox.Text)) else if (string.IsNullOrEmpty(procedureTextBox.Text))
{ {
rslt = session.QueryOver<Batch>() rslt = session.QueryOver<Batch>()
.Where(x => (x.StartTime >= fromDateTimePicker.Value)) .Where(x => (x.EndTime >= fromDateTimePicker.Value))
.And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1))) .And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1)))
.OrderBy(x => x.BatchNr).Asc .OrderBy(x => x.BatchNr).Asc
.JoinQueryOver<WaterMeter>(b => b.WaterMeters) .JoinQueryOver<WaterMeter>(b => b.WaterMeters)
@ -156,7 +153,7 @@ namespace TBF.UI.ResultsMI
else else
{ {
rslt = session.QueryOver<Batch>() rslt = session.QueryOver<Batch>()
.Where(x => (x.StartTime >= fromDateTimePicker.Value)) .Where(x => (x.EndTime >= fromDateTimePicker.Value))
.And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1))) .And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1)))
.And(x => (x.ProcedureName == procedureTextBox.Text)) .And(x => (x.ProcedureName == procedureTextBox.Text))
.OrderBy(x => x.BatchNr).Asc .OrderBy(x => x.BatchNr).Asc
@ -438,7 +435,6 @@ namespace TBF.UI.ResultsMI
private void closeButton_Click(object sender, EventArgs e) private void closeButton_Click(object sender, EventArgs e)
{ {
if (session != null) session.Close();
DialogResult = DialogResult.Cancel; DialogResult = DialogResult.Cancel;
Close(); Close();
} }
@ -473,6 +469,7 @@ namespace TBF.UI.ResultsMI
private void PreviousResultsDlg_FormClosing(object sender, FormClosingEventArgs e) private void PreviousResultsDlg_FormClosing(object sender, FormClosingEventArgs e)
{ {
if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser();
if (session != null && session.IsOpen) session.Close();
} }
} }
} }

View File

@ -1,11 +1,12 @@
/// ///
/// Copyright (c) 2013-2017 Sensus Slovensko a.s. /// Copyright (c) 2013-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Windows.Forms; using System.Windows.Forms;
using Common; using Common;
using Results; using Results;
using Users.Forms;
using TBF.Resources; using TBF.Resources;
namespace TBF.UI.ResultsMI namespace TBF.UI.ResultsMI
@ -92,13 +93,14 @@ namespace TBF.UI.ResultsMI
{ {
if (!Users.CurrentUser.IsMemberOf(RequiredGroupMembership)) if (!Users.CurrentUser.IsMemberOf(RequiredGroupMembership))
{ {
if ((new Users.Forms.LoginDlg(RequiredGroupMembership, this)).ShowDialog() != DialogResult.OK) if (DialogResult.OK != (new LoginDlg(TBF.DB.UserSessionFactories,
return; RequiredGroupMembership, this)).ShowDialog()) return;
} }
else if (Program.LocalSettings.AlwaysAskPasswdWhenUnlocking) else if (Program.LocalSettings.AlwaysAskPasswdWhenUnlocking)
{ {
if ((new Users.Forms.LoginDlg(Users.CurrentUser.UserName(), RequiredGroupMembership, this)).ShowDialog() != DialogResult.OK) if (DialogResult.OK != (new LoginDlg(TBF.DB.UserSessionFactories,
return; Users.CurrentUser.UserName(),
RequiredGroupMembership, this)).ShowDialog()) return;
} }
Unlocked = true; Unlocked = true;

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2013-2019 Sensus Slovensko a.s. /// Copyright (c) 2013-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -8,7 +8,6 @@ using System.Windows.Forms;
using log4net; using log4net;
using NHibernate; using NHibernate;
using Common; using Common;
using Common.Forms;
using Results; using Results;
using Results.Forms; using Results.Forms;
using Results.Entities; using Results.Entities;
@ -647,7 +646,7 @@ namespace TBF.UI.ResultsMI
var dlg = new DeleteFromOracleForm(); var dlg = new DeleteFromOracleForm();
GID[] rqrdGroupMembership = new GID[] { GID.TraceabilityManagement }; /// Restricted access to Delete from Oracle Form 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"); if (dlg.ShowDialog() == DialogResult.OK) MessageBox.Show("Successfully deleted from Oracle");
} }

View File

@ -191,7 +191,7 @@ namespace TBF.UI.Settings
log.ErrorFormat("Going to create an empty configuration database '{0}'", databaseName); log.ErrorFormat("Going to create an empty configuration database '{0}'", databaseName);
ExecuteMySqlCmd(string.Format("DROP DATABASE `{0}`;", databaseName), userName, password); 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); 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); log.ErrorFormat("An empty configuration database '{0}' was created", databaseName);
MessageBox.Show(Strings.DB_was_successfully_created, Strings.Notification); MessageBox.Show(Strings.DB_was_successfully_created, Strings.Notification);

View File

@ -116,7 +116,7 @@ namespace TBF.UI.Settings
try try
{ {
session = TBF.DB.CreateSession(Common.DBKind.Config); session = TBF.DB.ConfigDBSessionFactory.OpenSession();
var testParams = session.QueryOver<Config.Entities.ComponentTest>() var testParams = session.QueryOver<Config.Entities.ComponentTest>()
.Where(x => (x.CmpntName == errorFlagsCmpntName)) .Where(x => (x.CmpntName == errorFlagsCmpntName))
@ -144,6 +144,7 @@ namespace TBF.UI.Settings
} }
session.Flush(); session.Flush();
session.Close();
success = true; success = true;
} }
catch (Exception exc) catch (Exception exc)
@ -992,9 +993,10 @@ namespace TBF.UI.Settings
ActivityStart(); ActivityStart();
ISession session = null;
try try
{ {
ISession session = Results.DB.CreateSession(); session = TBF.DB.ResultsDBSessionFactory.OpenSession();
IList<Batch> bFrom = session.QueryOver<Batch>().Where(x => (x.BatchNr == batchFrom)).List<Batch>(); IList<Batch> bFrom = session.QueryOver<Batch>().Where(x => (x.BatchNr == batchFrom)).List<Batch>();
IList<Batch> bTo = session.QueryOver<Batch>().Where(x => (x.BatchNr == batchTo)).List<Batch>(); IList<Batch> bTo = session.QueryOver<Batch>().Where(x => (x.BatchNr == batchTo)).List<Batch>();
@ -1041,15 +1043,20 @@ namespace TBF.UI.Settings
MessageBox.Show(string.Format("Upgrade failed:\r\n{0}", exc.Message), MessageBox.Show(string.Format("Upgrade failed:\r\n{0}", exc.Message),
"Error", MessageBoxButtons.OK, MessageBoxIcon.Information); "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
finally
{
if (session != null && session.IsOpen) session.Close();
}
} }
private void customButton_Click(object sender, EventArgs e) private void customButton_Click(object sender, EventArgs e)
{ {
ActivityStart(); ActivityStart();
ISession session = null;
try try
{ {
ISession session = TBF.DB.CreateSession(Common.DBKind.Config); session = TBF.DB.ConfigDBSessionFactory.OpenSession();
var proceduresToModify = session.QueryOver<Config.Entities.ComponentProcedure>() var proceduresToModify = session.QueryOver<Config.Entities.ComponentProcedure>()
.Where(x => x.CmpntName == "Sensus-Oracle-DB") .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), MessageBox.Show(string.Format("Upgrade failed:\r\n{0}", exc.Message),
"Error", MessageBoxButtons.OK, MessageBoxIcon.Information); "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
finally
{
if (session != null && session.IsOpen) session.Close();
}
} }
} }
} }

View File

@ -10,6 +10,7 @@ using Common;
using Config.Entities; using Config.Entities;
using TBF.UiBridge; using TBF.UiBridge;
using TBF.Resources; using TBF.Resources;
using NHibernate;
namespace TBF.UI.Shared namespace TBF.UI.Shared
{ {
@ -175,52 +176,72 @@ namespace TBF.UI.Shared
/// Read the database and re-initialize testComboBox items. /// Read the database and re-initialize testComboBox items.
/// Try to preserve the original selection. /// Try to preserve the original selection.
/// </summary> /// </summary>
public void ReloadTests() public void ReloadTests(ISession session = null)
{ {
if (Program.MainWnd.SelectedProcedure == null || string.IsNullOrEmpty(Program.MainWnd.SelectedProcedure.Name)) return; if (Program.MainWnd.SelectedProcedure == null || string.IsNullOrEmpty(Program.MainWnd.SelectedProcedure.Name)) return;
bool openAndCloseSession = (session == null);
string oriTestName = testComboBox.Text; string oriTestName = testComboBox.Text;
IList<Procedure> procedures = TBF.DB.CreateSession(Program.MainWnd.SelectedProcedure.IsRemote ? DBKind.RemoteConfig : DBKind.Config) try
.QueryOver<Procedure>()
.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); if (openAndCloseSession)
{
session = Program.MainWnd.SelectedProcedure.IsRemote
? TBF.DB.SharedDBSessionFactory.OpenSession()
: TBF.DB.ConfigDBSessionFactory.OpenSession();
}
var procedures = session.QueryOver<Procedure>()
.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) private void testComboBox_SelectedIndexChanged(object sender, EventArgs e)
@ -280,7 +301,7 @@ namespace TBF.UI.Shared
if (drain1Highlighted && !Users.CurrentUser.IsMemberOf(GID.TestingSpecialists)) if (drain1Highlighted && !Users.CurrentUser.IsMemberOf(GID.TestingSpecialists))
{ {
var dlg = new DummyDlg(); 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; return;
Bridge.Ui2Bench(UI2BenchCmd.StopDrainingTank1); Bridge.Ui2Bench(UI2BenchCmd.StopDrainingTank1);
@ -298,7 +319,7 @@ namespace TBF.UI.Shared
if (drain1Highlighted && !Users.CurrentUser.IsMemberOf(GID.TestingSpecialists)) if (drain1Highlighted && !Users.CurrentUser.IsMemberOf(GID.TestingSpecialists))
{ {
var dlg = new DummyDlg(); 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; return;
Bridge.Ui2Bench(UI2BenchCmd.StopDrainingTank2); Bridge.Ui2Bench(UI2BenchCmd.StopDrainingTank2);
@ -316,7 +337,7 @@ namespace TBF.UI.Shared
if (drain1Highlighted && !Users.CurrentUser.IsMemberOf(GID.TestingSpecialists)) if (drain1Highlighted && !Users.CurrentUser.IsMemberOf(GID.TestingSpecialists))
{ {
var dlg = new DummyDlg(); 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; return;
Bridge.Ui2Bench(UI2BenchCmd.StopDrainingTank3); Bridge.Ui2Bench(UI2BenchCmd.StopDrainingTank3);

View File

@ -1,12 +1,12 @@
/// ///
/// Copyright (c) 2013-2018 Sensus Slovensko a.s. /// Copyright (c) 2013-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using log4net; using log4net;
using TBF.Resources;
using GemCard; using GemCard;
using System.Drawing; using TBF.Resources;
namespace TBF.UI.Shared namespace TBF.UI.Shared

View File

@ -233,12 +233,13 @@ namespace TBF.UI.Shared
{ {
if (!Users.CurrentUser.IsMemberOf(RequiredGroupMembership)) 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; return;
} }
else if (Program.LocalSettings.AlwaysAskPasswdWhenUnlocking) 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; return;
} }

View File

@ -20,7 +20,6 @@ namespace Users
/// <summary> Session factory for all regular sessions, not for CreateEmptyResultsDB(). </summary> /// <summary> Session factory for all regular sessions, not for CreateEmptyResultsDB(). </summary>
public static ISessionFactory SessionFactory; public static ISessionFactory SessionFactory;
public static ISession CurrentSession;
/// <summary> Connection string for all sessions </summary> /// <summary> Connection string for all sessions </summary>
private static string connectionString; private static string connectionString;
@ -103,8 +102,7 @@ namespace Users
if (SessionFactory == null) SessionFactory = CreateSessionFactory(); if (SessionFactory == null) SessionFactory = CreateSessionFactory();
CurrentSession = SessionFactory.OpenSession(); return SessionFactory.OpenSession();
return CurrentSession;
} }

View File

@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using log4net; using log4net;
using NHibernate;
using Common; using Common;
using Users.Forms; using Users.Forms;
using Users.Resources; using Users.Resources;
@ -228,7 +229,7 @@ namespace Users.Entities
/// <param name="password">Password</param> /// <param name="password">Password</param>
/// <param name="requiredGrupMembership"></param> /// <param name="requiredGrupMembership"></param>
/// <returns>true = authorized</returns> /// <returns>true = authorized</returns>
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)) if (IsPowerUser(userName, password))
{ {
@ -245,7 +246,7 @@ namespace Users.Entities
return false; return false;
} }
return CompleteAuthorization(password, requiredGroupMembership, currentForm); return CompleteAuthorization(session, password, requiredGroupMembership, currentForm);
} }
/// <summary> /// <summary>
@ -259,7 +260,7 @@ namespace Users.Entities
/// <param name="password">Password</param> /// <param name="password">Password</param>
/// <param name="requiredGrupMembership"></param> /// <param name="requiredGrupMembership"></param>
/// <returns>true = authorized</returns> /// <returns>true = authorized</returns>
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) if (Number != number)
{ {
@ -267,7 +268,7 @@ namespace Users.Entities
return false; return false;
} }
return CompleteAuthorization(password, requiredGroupMembership, currentForm); return CompleteAuthorization(session, password, requiredGroupMembership, currentForm);
} }
/// <summary> /// <summary>
@ -281,7 +282,7 @@ namespace Users.Entities
/// <param name="password"></param> /// <param name="password"></param>
/// <param name="requiredGrupMembership"></param> /// <param name="requiredGrupMembership"></param>
/// <returns>true = authorized</returns> /// <returns>true = authorized</returns>
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()) if (FullName.ToLower() != fullName.ToLower())
{ {
@ -289,7 +290,7 @@ namespace Users.Entities
return false; return false;
} }
return CompleteAuthorization(password, requiredGroupMembership, currentForm); return CompleteAuthorization(session, password, requiredGroupMembership, currentForm);
} }
/// <summary> /// <summary>
@ -298,7 +299,7 @@ namespace Users.Entities
/// <param name="password">Password</param> /// <param name="password">Password</param>
/// <param name="requiredGroupMembership">Required group membership</param> /// <param name="requiredGroupMembership">Required group membership</param>
/// <returns>true = authorized</returns> /// <returns>true = authorized</returns>
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)) if (!IsMemberOf(requiredGroupMembership) || !IsCorrectPassword(password))
{ {
@ -309,7 +310,7 @@ namespace Users.Entities
if (IsPasswordExpired()) if (IsPasswordExpired())
{ {
/// Password expired => User has to change the password /// 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 /// User did not change the password => reject authorization
return false; return false;
@ -370,122 +371,58 @@ namespace Users.Entities
return user; return user;
} }
/// <summary>
/// Returns a 'User' with a given username from an ARBITRARY database.
/// </summary>
/// <param name="username">User name for the query</param>
/// <returns>reference to a 'User' (if it exists) or null</returns>
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);
}
/// <summary> /// <summary>
/// Returns a 'User' with a given username from the users database. /// Returns a 'User' with a given username from the users database.
/// </summary> /// </summary>
/// <param name="username">User name for the query</param> /// <param name="username">User name for the query</param>
/// <returns>reference to a 'User' (if it exists) or null</returns> /// <returns>reference to a 'User' (if it exists) or null</returns>
public static User LoadUserByName(string userName) public static User LoadUserByName(ISession session, string userName)
{ {
IList<User> listOfUsers = DB.CreateSession() var listOfUsers = session.QueryOver<User>()
.QueryOver<User>() .Where(x => (x.UserName == userName))
.Where(x => (x.UserName == userName)) .List();
.List();
return (listOfUsers.Count > 0) ? listOfUsers[0] : null; return (listOfUsers.Count > 0) ? listOfUsers[0] : null;
} }
/// <summary>
/// Returns a 'User' with a given full name from an ARBITRARY database.
/// </summary>
/// <param name="fullName">Full name for the query</param>
/// <returns>reference to a 'User' (if it exists) or null</returns>
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);
}
/// <summary> /// <summary>
/// Returns a 'User' with a given full name from the users database. /// Returns a 'User' with a given full name from the users database.
/// </summary> /// </summary>
/// <param name="fullName">Full name for the query</param> /// <param name="fullName">Full name for the query</param>
/// <returns>reference to a 'User' (if it exists) or null</returns> /// <returns>reference to a 'User' (if it exists) or null</returns>
public static User LoadUserByFullName(string fullName) public static User LoadUserByFullName(ISession session, string fullName)
{ {
IList<User> listOfUsers = DB.CreateSession() var listOfUsers = session.QueryOver<User>()
.QueryOver<User>() .Where(x => (x.FullName == fullName))
.Where(x => (x.FullName == fullName)) .List();
.List();
return (listOfUsers.Count > 0) ? listOfUsers[0] : null; return (listOfUsers.Count > 0) ? listOfUsers[0] : null;
} }
/// <summary>
/// Returns a 'User' with a given username from an ARBITRARY database.
/// </summary>
/// <param name="number">User ID number for the query</param>
/// <returns>reference to a 'User' (if it exists) or null</returns>
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);
}
/// <summary> /// <summary>
/// Returns a 'User' with a given username from the users database. /// Returns a 'User' with a given username from the users database.
/// </summary> /// </summary>
/// <param name="number">User ID number for the query</param> /// <param name="number">User ID number for the query</param>
/// <returns>reference to a 'User' (if it exists) or null</returns> /// <returns>reference to a 'User' (if it exists) or null</returns>
public static User LoadUserByNumber(int number) public static User LoadUserByNumber(ISession session, int number)
{ {
IList<User> listOfUsers = DB.CreateSession() var listOfUsers = session.QueryOver<User>()
.QueryOver<User>() .Where(x => (x.Number == number))
.Where(x => (x.Number == number)) .List();
.List();
return (listOfUsers.Count > 0) ? listOfUsers[0] : null; return (listOfUsers.Count > 0) ? listOfUsers[0] : null;
} }
/// <summary>
/// Returns a 'User' with a given RFID/NFC tag s/n from an ARBITRARY database.
/// </summary>
/// <param name="tag">Tag of a user for the query</param>
/// <returns>reference to a 'User' (if it exists) or null</returns>
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);
}
/// <summary> /// <summary>
/// Returns a 'User' with a given RFID/NFC tag s/n from the users database. /// Returns a 'User' with a given RFID/NFC tag s/n from the users database.
/// </summary> /// </summary>
/// <param name="tag">Tag of a user for the query</param> /// <param name="tag">Tag of a user for the query</param>
/// <returns>reference to a 'User' (if it exists) or null</returns> /// <returns>reference to a 'User' (if it exists) or null</returns>
public static User LoadUserByTag(string tag) public static User LoadUserByTag(ISession session, string tag)
{ {
IList<User> listOfUsers = DB.CreateSession() var listOfUsers = session.QueryOver<User>()
.QueryOver<User>() .Where(x => (x.Tag == tag))
.Where(x => (x.Tag == tag)) .List();
.List();
return (listOfUsers.Count > 0) ? listOfUsers[0] : null; return (listOfUsers.Count > 0) ? listOfUsers[0] : null;
} }
@ -494,9 +431,9 @@ namespace Users.Entities
/// <summary> /// <summary>
/// returns an IList of all Users /// returns an IList of all Users
/// </summary> /// </summary>
public static IList<User> GetAllUsers() public static IList<User> GetAllUsers(ISession session)
{ {
return DB.CreateSession().QueryOver<User>().List(); return session.QueryOver<User>().List();
} }

View File

@ -225,47 +225,46 @@ namespace Users.Forms
} }
/// <summary> /// <summary>
/// returns true if the username allready exists for another user /// Returns true if the username already exists for another user
/// </summary> /// </summary>
private bool IsUserNameAlreadyTaken(string userName) private bool IsUserNameAlreadyTaken(string userName)
{ {
// Have a look into all other users /// Have a look on all other users
IList<User> ListOfUsers = User.GetAllUsers(); foreach (var u in User.GetAllUsers(session))
foreach (var person in ListOfUsers)
{ {
if (person.Id != user.Id) if (u.Id != user.Id)
{ {
/// Other user then the current one // 'u' is other user then the current one
if (person.UserName.ToLower() == userName.ToLower())
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
} }
/// <summary> /// <summary>
/// returns true if the username allready exists for another user /// Returns true if the tag already exists for another user
/// </summary> /// </summary>
private bool IsTagAlreadyTaken(string tag) 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 /// Have a look on all other users
IList<User> ListOfUsers = User.GetAllUsers(); foreach (var u in User.GetAllUsers(session))
foreach (var person in ListOfUsers)
{ {
if (person.Id != user.Id) if (u.Id != this.user.Id)
{ {
// Other user then the current one // 'u' is other user then the current one
if (person.Tag == tag)
{ if (u.Tag == tag) return true; /// Tag is already used by another user
return true; // Tag is equal = already taken
}
} }
} }
return false;
return false; /// Tag is stil free
} }

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2017-2018 Sensus Slovensko a.s. /// Copyright (c) 2017-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Windows.Forms; using System.Windows.Forms;
@ -9,6 +9,7 @@ using GemCard;
using Users.Entities; using Users.Entities;
using Users.Resources; using Users.Resources;
using System.Drawing; using System.Drawing;
using NHibernate;
namespace Users.Forms namespace Users.Forms
{ {
@ -24,11 +25,11 @@ namespace Users.Forms
public string UserName { get { return user; } } public string UserName { get { return user; } }
/// Private fields /// Private fields
ISessionFactory[] sessionFactories;
string user; string user;
string password; string password;
GID[] requiredGroupMembership; GID[] requiredGroupMembership;
Form parentForm; Form parentForm;
bool noDatabase;
Color oriBackColor; Color oriBackColor;
/// Smart card support, card S/N is used as user.Tag /// Smart card support, card S/N is used as user.Tag
@ -44,16 +45,17 @@ namespace Users.Forms
public LoginDlg() public LoginDlg()
{ {
InitializeComponent(); InitializeComponent();
this.sessionFactories = null;
oriBackColor = BackColor; oriBackColor = BackColor;
} }
/// <summary> /// <summary>
/// Constructor with a predefined user. /// Constructor with a predefined user.
/// </summary> /// </summary>
public LoginDlg(string predefinedUser, Form parentForm) public LoginDlg(ISessionFactory[] sessionFactories, string predefinedUser, Form parentForm)
: this() : this()
{ {
this.sessionFactories = sessionFactories;
user = predefinedUser; user = predefinedUser;
userNameTextBox.Text = predefinedUser; userNameTextBox.Text = predefinedUser;
this.parentForm = parentForm; this.parentForm = parentForm;
@ -62,18 +64,19 @@ namespace Users.Forms
/// <summary> /// <summary>
/// Constructor with 'no Database' flag. /// Constructor with 'no Database' flag.
/// </summary> /// </summary>
public LoginDlg(bool noDatabase) public LoginDlg(ISessionFactory[] sessionFactories)
: this() : this()
{ {
this.noDatabase = noDatabase; this.sessionFactories = sessionFactories;
} }
/// <summary> /// <summary>
/// Constructor when a specific group membership is required. /// Constructor when a specific group membership is required.
/// </summary> /// </summary>
public LoginDlg(GID[] requiredGroupMembership, Form parentForm) public LoginDlg(ISessionFactory[] sessionFactories, GID[] requiredGroupMembership, Form parentForm)
: this() : this()
{ {
this.sessionFactories = sessionFactories;
this.requiredGroupMembership = requiredGroupMembership; this.requiredGroupMembership = requiredGroupMembership;
this.parentForm = parentForm; this.parentForm = parentForm;
#if DEBUG #if DEBUG
@ -86,9 +89,10 @@ namespace Users.Forms
/// <summary> /// <summary>
/// Constructor with a predefined user when a specific group membership is required. /// Constructor with a predefined user when a specific group membership is required.
/// </summary> /// </summary>
public LoginDlg(string predefinedUser, GID[] requiredGroupMembership, Form parentForm) public LoginDlg(ISessionFactory[] sessionFactories, string predefinedUser, GID[] requiredGroupMembership, Form parentForm)
: this() : this()
{ {
this.sessionFactories = sessionFactories;
user = predefinedUser; user = predefinedUser;
userNameTextBox.Text = predefinedUser; userNameTextBox.Text = predefinedUser;
this.requiredGroupMembership = requiredGroupMembership; this.requiredGroupMembership = requiredGroupMembership;
@ -198,39 +202,47 @@ namespace Users.Forms
CurrentUser.Change(new Users.Entities.User(user, 6, true), parentForm); 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 }; DBSettings[] dbs = new DBSettings[] { CurrentUser.RemoteUsersDB, CurrentUser.LocalUsersDB };
authorizedAs = AuthorizedAs.RemoteUser; authorizedAs = AuthorizedAs.RemoteUser;
foreach (var db in dbs) foreach (var sf in sessionFactories)
{ {
ISession session = null;
try try
{ {
session = sf.OpenSession();
switch (Method) switch (Method)
{ {
case LoginMethod.UserName: case LoginMethod.UserName:
default: default:
var usr1 = Users.Entities.User.LoadUserByName(user, db); var usr1 = Users.Entities.User.LoadUserByName(session, user);
if (usr1 != null) { authorized = usr1.Authorize(user, password, requiredGroupMembership, parentForm); } if (usr1 != null) { authorized = usr1.Authorize(session, user, password, requiredGroupMembership, parentForm); }
break; break;
case LoginMethod.FullName: case LoginMethod.FullName:
var usr2 = Users.Entities.User.LoadUserByFullName(user, db); var usr2 = Users.Entities.User.LoadUserByFullName(session, user);
if (usr2 != null) { authorized = usr2.AuthorizeFullName(user, password, requiredGroupMembership, parentForm); } if (usr2 != null) { authorized = usr2.AuthorizeFullName(session, user, password, requiredGroupMembership, parentForm); }
if (authorized) { user = usr2.UserName; } if (authorized) { user = usr2.UserName; }
break; break;
case LoginMethod.Number: case LoginMethod.Number:
int number; int number;
if (!int.TryParse(user, out number)) break; if (!int.TryParse(user, out number)) break;
var usr3 = Users.Entities.User.LoadUserByNumber(number, db); var usr3 = Users.Entities.User.LoadUserByNumber(session, number);
if (usr3 != null) { authorized = usr3.AuthorizeNumber(number, password, requiredGroupMembership, parentForm); } if (usr3 != null) { authorized = usr3.AuthorizeNumber(session, number, password, requiredGroupMembership, parentForm); }
if (authorized) { user = usr3.UserName; } if (authorized) { user = usr3.UserName; }
break; break;
} }
} }
catch (Exception) { } catch (Exception)
{
}
finally
{
if (session != null && session.IsOpen) session.Close();
}
if (authorized) break; if (authorized) break;
@ -310,29 +322,30 @@ namespace Users.Forms
tag = string.Empty; tag = string.Empty;
} }
DBSettings[] dbs = new DBSettings[] { CurrentUser.RemoteUsersDB, CurrentUser.LocalUsersDB };
bool authorized = false; bool authorized = false;
AuthorizedAs authorizedAs = AuthorizedAs.RemoteUser; 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); using (ISession session = sf.OpenSession())
if (loadedUser != null)
{ {
authorized = loadedUser.AuthorizeTag(tag, requiredGroupMembership, parentForm); Users.Entities.User loadedUser = Users.Entities.User.LoadUserByTag(session, tag);
if (loadedUser != null)
if (authorized)
{ {
user = loadedUser.UserName; authorized = loadedUser.AuthorizeTag(tag, requiredGroupMembership, parentForm);
break;
if (authorized)
{
user = loadedUser.UserName;
break;
}
} }
} }
}
catch (Exception) { }
authorizedAs = AuthorizedAs.LocalUser; authorizedAs = AuthorizedAs.LocalUser;
}
} }
if (authorized) if (authorized)

View File

@ -1,8 +1,10 @@
/// ///
/// Copyright (c) 2019 Sensus Slovensko a.s. /// Copyright (c) 2019-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Windows.Forms; using System.Windows.Forms;
using log4net;
using NHibernate;
using Common; using Common;
using GemCard; using GemCard;
using Users.Resources; using Users.Resources;
@ -16,10 +18,15 @@ namespace Users.Forms
/// </summary> /// </summary>
public partial class PasswordChangeDlg : Form public partial class PasswordChangeDlg : Form
{ {
private static readonly ILog log = LogManager.GetLogger(typeof(PasswordChangeDlg));
ISessionFactory[] sessionFactories;
ISession session;
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public PasswordChangeDlg() private PasswordChangeDlg()
{ {
InitializeComponent(); InitializeComponent();
} }
@ -27,10 +34,23 @@ namespace Users.Forms
/// <summary> /// <summary>
/// Constructor with a predefined user. /// Constructor with a predefined user.
/// </summary> /// </summary>
public PasswordChangeDlg(string predefinedUser) public PasswordChangeDlg(ISessionFactory[] sessionFactories, string predefinedUser = null)
{ {
InitializeComponent(); InitializeComponent();
userNameTextBox.Text = predefinedUser; this.sessionFactories = sessionFactories;
this.session = null;
if (predefinedUser != null) userNameTextBox.Text = predefinedUser;
}
/// <summary>
/// Constructor with a predefined user.
/// </summary>
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; bool oldPasswdOK = false;
if (!oldPasswdOK) 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 try
{ {
loadedUser = Users.Entities.User.LoadUserByName(userName, db); loadedUser = Users.Entities.User.LoadUserByName(session, userName);
if (loadedUser != null) if (loadedUser != null)
{ {
oldPasswdOK = (userName == loadedUser.UserName) && loadedUser.IsCorrectPassword(oldPassword); 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)) ///
{ /// Now the password is changed in database that was used to authorize the user
if (loadedUser.IsPasswordUsedInPast(newPasswTextBox.Text)) ///
{ loadedUser.SetPassword(newPasswTextBox.Text);
MessageBox.Show(Strings.Password_has_been_used_in_past, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Hand); session.SaveOrUpdate(loadedUser);
DialogResult = DialogResult.None; session.Flush();
return;
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); MessageBox.Show(Strings.Invalid_username_or_password, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Hand);

View File

@ -1,5 +1,5 @@
/// ///
/// Copyright (c) 2022 Sensus Slovensko a.s. /// Copyright (c) 2022-2023 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Windows.Forms; using System.Windows.Forms;
@ -9,6 +9,7 @@ using GemCard;
using Users.Entities; using Users.Entities;
using Users.Resources; using Users.Resources;
using System.Drawing; using System.Drawing;
using NHibernate;
namespace Users.Forms namespace Users.Forms
{ {
@ -25,10 +26,10 @@ namespace Users.Forms
public string FullName { get { return fullName; } } public string FullName { get { return fullName; } }
/// Private fields /// Private fields
ISessionFactory[] sessionFactories;
string user; string user;
string password; string password;
GID[] requiredGroupMembership; GID[] requiredGroupMembership;
bool noDatabase;
Color oriBackColor; Color oriBackColor;
string fullName; /// Description of the selected user string fullName; /// Description of the selected user
@ -52,9 +53,10 @@ namespace Users.Forms
/// <summary> /// <summary>
/// Constructor with a predefined user. /// Constructor with a predefined user.
/// </summary> /// </summary>
public PlainLoginDlg(string predefinedUser, string prompt = null) public PlainLoginDlg(ISessionFactory[] sessionFactories, string predefinedUser, string prompt = null)
: this() : this()
{ {
this.sessionFactories = sessionFactories;
user = predefinedUser; user = predefinedUser;
userNameTextBox.Text = predefinedUser; userNameTextBox.Text = predefinedUser;
if (prompt != null) Text = prompt; if (prompt != null) Text = prompt;
@ -63,19 +65,20 @@ namespace Users.Forms
/// <summary> /// <summary>
/// Constructor with 'no Database' flag. /// Constructor with 'no Database' flag.
/// </summary> /// </summary>
public PlainLoginDlg(bool noDatabase, string prompt = null) public PlainLoginDlg(ISessionFactory[] sessionFactories, string prompt = null)
: this() : this()
{ {
this.noDatabase = noDatabase; this.sessionFactories = sessionFactories;
if (prompt != null) Text = prompt; if (prompt != null) Text = prompt;
} }
/// <summary> /// <summary>
/// Constructor when a specific group membership is required. /// Constructor when a specific group membership is required.
/// </summary> /// </summary>
public PlainLoginDlg(GID[] requiredGroupMembership, string prompt = null) public PlainLoginDlg(ISessionFactory[] sessionFactories, GID[] requiredGroupMembership, string prompt = null)
: this() : this()
{ {
this.sessionFactories = sessionFactories;
this.requiredGroupMembership = requiredGroupMembership; this.requiredGroupMembership = requiredGroupMembership;
if (prompt != null) Text = prompt; if (prompt != null) Text = prompt;
} }
@ -83,9 +86,10 @@ namespace Users.Forms
/// <summary> /// <summary>
/// Constructor with a predefined user when a specific group membership is required. /// Constructor with a predefined user when a specific group membership is required.
/// </summary> /// </summary>
public PlainLoginDlg(string predefinedUser, GID[] requiredGroupMembership, string prompt = null) public PlainLoginDlg(ISessionFactory[] sessionFactories, string predefinedUser, GID[] requiredGroupMembership, string prompt = null)
: this() : this()
{ {
this.sessionFactories = sessionFactories;
user = predefinedUser; user = predefinedUser;
userNameTextBox.Text = predefinedUser; userNameTextBox.Text = predefinedUser;
this.requiredGroupMembership = requiredGroupMembership; this.requiredGroupMembership = requiredGroupMembership;
@ -179,15 +183,15 @@ namespace Users.Forms
bool authorized = Entities.User.IsPowerUser(user, password); bool authorized = Entities.User.IsPowerUser(user, password);
if (authorized) fullName = "Power user"; 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 sf in sessionFactories)
foreach (var db in dbs)
{ {
ISession session = null;
try 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)) if (usr1.IsMemberOf(requiredGroupMembership) && usr1.IsCorrectPassword(password))
{ {
@ -196,7 +200,13 @@ namespace Users.Forms
break; break;
} }
} }
catch (Exception) { } catch (Exception)
{
}
finally
{
if (session != null && session.IsOpen) session.Close();
}
} }
} }
@ -263,25 +273,36 @@ namespace Users.Forms
bool authorized = false; bool authorized = false;
AuthorizedAs authorizedAs = AuthorizedAs.RemoteUser; 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); ISession session = null;
if (loadedUser != null) try
{ {
authorized = (tag == loadedUser.Tag && loadedUser.IsMemberOf(requiredGroupMembership)); session = sf.OpenSession();
Users.Entities.User loadedUser = Users.Entities.User.LoadUserByTag(session, tag);
if (authorized) if (loadedUser != null)
{ {
user = loadedUser.UserName; authorized = (tag == loadedUser.Tag && loadedUser.IsMemberOf(requiredGroupMembership));
break;
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) if (authorized)

View File

@ -238,6 +238,8 @@ namespace Users.Forms
IList<User> remoteUsers; IList<User> remoteUsers;
IList<Group> remoteGroups; IList<Group> remoteGroups;
ITransaction transaction = null; ITransaction transaction = null;
ISession remoteSession = null;
ISession localSession = null;
try try
{ {
@ -246,7 +248,7 @@ namespace Users.Forms
/// ///
DB.DbType = CurrentUser.RemoteUsersDB.DbType; DB.DbType = CurrentUser.RemoteUsersDB.DbType;
DB.ConnectionString = CurrentUser.RemoteUsersDB.ConnectionString; DB.ConnectionString = CurrentUser.RemoteUsersDB.ConnectionString;
ISession remoteSession = DB.CreateSession(); remoteSession = DB.CreateSession();
remoteUsers = remoteSession.QueryOver<User>().List(); remoteUsers = remoteSession.QueryOver<User>().List();
remoteGroups = remoteSession.QueryOver<Group>().List(); remoteGroups = remoteSession.QueryOver<Group>().List();
@ -255,7 +257,7 @@ namespace Users.Forms
/// ///
DB.DbType = CurrentUser.LocalUsersDB.DbType; DB.DbType = CurrentUser.LocalUsersDB.DbType;
DB.ConnectionString = CurrentUser.LocalUsersDB.ConnectionString; DB.ConnectionString = CurrentUser.LocalUsersDB.ConnectionString;
ISession localSession = DB.CreateSession(); localSession = DB.CreateSession();
transaction = localSession.BeginTransaction(); transaction = localSession.BeginTransaction();
/// ///
@ -285,6 +287,8 @@ namespace Users.Forms
} }
transaction.Commit(); transaction.Commit();
localSession.Flush(); localSession.Flush();
localSession.Close();
remoteSession.Close();
listOfUsers = newUsers; listOfUsers = newUsers;
ListUsers(); ListUsers();
@ -298,6 +302,9 @@ namespace Users.Forms
{ {
if (transaction != null) transaction.Rollback(); 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, MessageBox.Show(Strings.Copying_remote_users_failed,
Strings.Confirmation, Strings.Confirmation,
MessageBoxButtons.OK, MessageBoxButtons.OK,