diff --git a/Common/Common.csproj b/Common/Common.csproj index d760f782b..102aae1ed 100644 --- a/Common/Common.csproj +++ b/Common/Common.csproj @@ -42,6 +42,7 @@ + diff --git a/Common/Const.cs b/Common/Const.cs new file mode 100644 index 000000000..a67d74546 --- /dev/null +++ b/Common/Const.cs @@ -0,0 +1,12 @@ +/// +/// Copyright (c) 2023 Sensus Slovensko a.s. +/// +using System; + +namespace Common +{ + public static class Const + { + public const string MySqlConnectTimeoutSec = "120"; + } +} diff --git a/Common/DBSettings.cs b/Common/DBSettings.cs index 3a8a7d8c9..8e5313f53 100644 --- a/Common/DBSettings.cs +++ b/Common/DBSettings.cs @@ -12,6 +12,7 @@ namespace Common { public DBType DbType; public string ConnectionString; + public bool IsValid { get { return (DbType != DBType.None) && !string.IsNullOrEmpty(ConnectionString); } } public DBSettings() { diff --git a/Common/DatabaseSettings.cs b/Common/DatabaseSettings.cs index ac40b30f2..5a2336ab6 100644 --- a/Common/DatabaseSettings.cs +++ b/Common/DatabaseSettings.cs @@ -15,10 +15,10 @@ namespace Common // Public fields public string BenchName; public bool IsRealBench; - public DBSettings ProceduresDBSettings; /// Configuration database settings + public DBSettings ProceduresDBSettings; /// Configuration database settings public DBSettings WaterMetersDBSettings; /// Results database settings - public DBSettings EventsDBSettings; /// Events database settings - public DBSettings UsersDBSettings; /// Shared configuration database settings + public DBSettings EventsDBSettings; /// Events database settings + public DBSettings UsersDBSettings; /// Shared configuration database settings // Constructor public DatabaseSettings() diff --git a/Common/Enums.cs b/Common/Enums.cs index 4be813892..cd328c0b6 100644 --- a/Common/Enums.cs +++ b/Common/Enums.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2013-2022 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -49,15 +49,6 @@ namespace Common Count } - /// Identifies the database based on the content - public enum DBKind - { - Config, - Results, - RemoteConfig, - Count - } - public enum ProcedureSelection { #if LANG_CS diff --git a/Config/CalendarEvent/Utils.cs b/Config/CalendarEvent/Utils.cs index 2895c28dc..9bdec2a01 100644 --- a/Config/CalendarEvent/Utils.cs +++ b/Config/CalendarEvent/Utils.cs @@ -122,7 +122,7 @@ namespace Config.CalendarEvent } - public static bool IsCalendarEventTrigerred(ICalendarEvent evnt, DateTime currentDate) + public static bool IsCalendarEventTrigerred(ICalendarEvent evnt, DateTime dateTimeNow) { DateTime evntDT = evnt.AllDay ? new DateTime(evnt.Date.Year, evnt.Date.Month, evnt.Date.Day, 0, 0, 0) @@ -133,17 +133,17 @@ namespace Config.CalendarEvent DateTime dt1 = evntDT; DateTime dt2 = evntDT + new TimeSpan(8, 0, 0); DateTime dt3 = evntDT + new TimeSpan(16, 0, 0); - return (currentDate >= dt1) || (currentDate >= dt1) || (currentDate >= dt3); + return (dateTimeNow >= dt1) || (dateTimeNow >= dt1) || (dateTimeNow >= dt3); } else if (!evnt.TriggerOnExactDayOnly) { /// Trigger after event expires - return (currentDate >= evntDT); + return (dateTimeNow >= evntDT); } else { /// Trigger event on exact date only - return (currentDate >= evntDT) && DayMatchesExactly(evnt, currentDate); + return (dateTimeNow >= evntDT) && DayMatchesExactly(evnt, dateTimeNow); } } diff --git a/Config/Entities/CustomEvent.cs b/Config/Entities/CustomEvent.cs index 30bb606c2..34057f914 100644 --- a/Config/Entities/CustomEvent.cs +++ b/Config/Entities/CustomEvent.cs @@ -46,8 +46,8 @@ namespace Config.Entities Rank = 2; Hidden = false; ReadOnly = false; - BackColor = unchecked((int)0xFFFF5050); - TextColor = unchecked((int)0xFFFFFFFF); + BackColor = unchecked((int)0xFFFF5050); /// (MSB)AARRGGBB(LSB) ... pink + TextColor = unchecked((int)0xFFFFFFFF); /// (MSB)AARRGGBB(LSB) ... white TooltipEnabled = true; CustomRecurringFunction = null; } diff --git a/Config/FluentCommon.cs b/Config/FluentCommon.cs index f9f48a4a8..028e5a5f0 100644 --- a/Config/FluentCommon.cs +++ b/Config/FluentCommon.cs @@ -1,148 +1,10 @@ /// /// Copyright (c) 2013-2018 Sensus Slovensko a.s. /// -using System; -using System.Windows.Forms; -using FluentNHibernate.Cfg; -using FluentNHibernate.Cfg.Db; -using NHibernate; -using NHibernate.Cfg; -using NHibernate.Tool.hbm2ddl; -using Config.Resources; namespace Config { public static class FluentCommon { - /// - /// NHibernate session factory (to create the database session 'SessionFactory') - /// - /// A database session - public static ISessionFactory CreateSessionFactory(Common.DBKind database, Common.DBType dbType, string connectionString, bool createDB) - { - try - { - FluentConfiguration cfg = Fluently.Configure(); - - switch (dbType) - { - default: - case Common.DBType.MySql: - cfg = cfg.Database(MySQLConfiguration.Standard.ConnectionString(connectionString)); - break; - case Common.DBType.SQLite: - cfg = cfg.Database(SQLiteConfiguration.Standard.UsingFile(connectionString)); - break; - } - - switch (database) - { - default: - case Common.DBKind.Config: - case Common.DBKind.RemoteConfig: - cfg = cfg.Mappings(m => m.FluentMappings.AddFromAssemblyOf()); - break; - case Common.DBKind.Results: - cfg = cfg.Mappings(m => m.FluentMappings.AddFromAssemblyOf()); - break; - } - - if (createDB) - { - return cfg.ExposeConfiguration(BuildSchemaCreate).BuildSessionFactory(); - } - else - { - return cfg.ExposeConfiguration(BuildSchema).BuildSessionFactory(); - } - } - catch (Exception exc) - { - MessageBox.Show(string.Format(Strings.Cannot_open_DB_Cause_0, exc.Message), - Strings.Error, - MessageBoxButtons.OK, - MessageBoxIcon.Error); - return null; - } - } - - public delegate void BuildSchemaDlgt(Configuration config); - - static void BuildSchema(Configuration config) - { - /// This NHibernate tool takes a configuration (with mapping info in) - /// and exports a database schema from it - new SchemaExport(config).SetOutputFile("db_schema"); - } - - static void BuildSchemaCreate(Configuration config) - { - /// This NHibernate tool takes a configuration (with mapping info in) - /// and exports a database schema from it - new SchemaExport(config).Create(true, true); - } - - /// - /// Create an empty users database. - /// Database contains only the user 'admin' and the control board component 'CB'. - /// - /// DBType.SQLite or DBType.MySql - /// Connection string - /// true=success, false=error - public static bool CreateEmptyConfigDB(Common.DBType dbType, string connectionString) - { - ISessionFactory sessionFactory = CreateSessionFactory(Common.DBKind.Config, dbType, connectionString, true); - if (sessionFactory == null) return false; - - /// Populate the database - using (var session = sessionFactory.OpenSession()) - { - using (var transaction = session.BeginTransaction()) - { - /// - /// Create user 'admin' - /// - var admin = new Config.Entities.User - { - UserName = Data.AdminUsername, - FullName = Strings.Administrator, - LastPwChange = DateTime.Now - }; - admin.SetPassword(Data.AdminPassword); - - /// - /// Prepare all groups, add some of them to admin - /// - for (Common.GID gid = 0; gid < Common.GID.NrOfGroups; gid++) - { - Config.Entities.Group group = new Config.Entities.Group(gid); - switch (gid) - { - case Common.GID.Testers: - case Common.GID.TestingSpecialists: - case Common.GID.HeadOfLab: - case Common.GID.MaintenanceSpecialists: - case Common.GID.Metrologists: - case Common.GID.CalibrationSpecialists: - case Common.GID.Administrators: -#if TURA_IPERL || TURA_IPERL_NEW || TURA_SPECIAL - case Common.GID.TraceabilityManagement: -#elif LANG_PL - case Common.GID.MetrologicalAuthority: - case Common.GID.WaterMeterAuthority: -#endif - admin.AddGroup(group); - session.SaveOrUpdate(group); /// Save this group - break; - } - } - - session.SaveOrUpdate(admin); /// Save user 'admin' - transaction.Commit(); - } - } - - return true; - } } } diff --git a/EventViewer/EViewerDB.cs b/EventViewer/EViewerDB.cs new file mode 100644 index 000000000..c24819127 --- /dev/null +++ b/EventViewer/EViewerDB.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using FluentNHibernate.Cfg; +using FluentNHibernate.Cfg.Db; +using NHibernate; +using NHibernate.Cfg; +using NHibernate.Tool.hbm2ddl; +using Common; +using Events; + +namespace EventViewer +{ + public static class EViewerDB + { + /// Session factory for all regular sessions, not for CreateEmptyResultsDB(). + public static ISessionFactory SessionFactory; + + /// Connection string for all sessions + static string connectionString; + /// + public static string ConnectionString + { + get { return connectionString; } + set + { + if (value != connectionString) + { + connectionString = value; + SessionFactory = null; /// Clear SessionFactory on connection string change + } + } + } + + /// Database type (MySQL or SQLite) for all sessions + private static DBType dbType; + /// + public static DBType DbType + { + get { return dbType; } + set { dbType = value; SessionFactory = null; } + } + + /// + /// NHibernate session factory (to create the database session 'SessionFactory') + /// + /// A database session + static ISessionFactory CreateSessionFactory() + { + return CreateSessionFactory(false); + } + + /// + /// NHibernate session factory (to create the database session 'SessionFactory') + /// + /// true = Create a new DB, false = Regular DB + /// A database session + public static ISessionFactory CreateSessionFactory(bool createDB) + { + FluentConfiguration cfg = Fluently.Configure(); + + switch (dbType) + { + default: + case DBType.MySql: + cfg = cfg.Database(MySQLConfiguration.Standard.ConnectionString(connectionString)); + break; + case DBType.SQLite: + cfg = cfg.Database(SQLiteConfiguration.Standard.UsingFile(connectionString)); + break; + } + + cfg = cfg.Mappings(m => m.FluentMappings.AddFromAssemblyOf()); + + if (createDB) + { + return cfg.ExposeConfiguration(BuildSchemaCreate) + .BuildConfiguration() + .SetProperty("hibernate.connection.connect_timeout", Const.MySqlConnectTimeoutSec) + .BuildSessionFactory(); + } + else + { + return cfg.ExposeConfiguration(BuildSchema) + .BuildConfiguration() + .SetProperty("hibernate.connection.connect_timeout", Const.MySqlConnectTimeoutSec) + .BuildSessionFactory(); + } + } + + static void BuildSchema(Configuration config) + { + /// This NHibernate tool takes a configuration with mapping info and exports a database schema + new SchemaExport(config).SetOutputFile("db_schema"); + } + + static void BuildSchemaCreate(Configuration config) + { + /// This NHibernate tool takes a configuration with mapping info and exports a database schema + new SchemaExport(config).Create(true, true); + } + + /// Create a NHibernate session for the given database + public static ISession CreateSession() + { + if (string.IsNullOrEmpty(connectionString)) + { + throw new Exception("Connection string was not specified"); + } + + if (SessionFactory == null) SessionFactory = CreateSessionFactory(); + + return SessionFactory.OpenSession(); + } + + + /// + /// Create an empty users database. + /// Database contains only the user 'admin' and the control board component 'CB'. + /// + /// DBType.SQLite or DBType.MySql + /// Connection string + /// true=success, false=error + public static bool CreateEmptyDB() + { + ISessionFactory sessionFactory = CreateSessionFactory(true); + if (sessionFactory == null) return false; + + /// Populate the database + using (var session = sessionFactory.OpenSession()) + { + using (var transaction = session.BeginTransaction()) + { + transaction.Commit(); + } + } + + return true; + } + } +} diff --git a/EventViewer/EventViewer.csproj b/EventViewer/EventViewer.csproj index dd4c0a1dd..0b8951890 100644 --- a/EventViewer/EventViewer.csproj +++ b/EventViewer/EventViewer.csproj @@ -66,6 +66,7 @@ EventViewerWnd.cs + Form diff --git a/EventViewer/EventViewerWnd.cs b/EventViewer/EventViewerWnd.cs index 6c33ec5fa..5a472d1fe 100644 --- a/EventViewer/EventViewerWnd.cs +++ b/EventViewer/EventViewerWnd.cs @@ -102,9 +102,9 @@ namespace EventViewer { try { - DB.DbType = DBType.MySql; - DB.ConnectionString = Program.LocalSettings.ConnectionString; - session = DB.CreateSession(); + EViewerDB.DbType = DBType.MySql; + EViewerDB.ConnectionString = Program.LocalSettings.ConnectionString; + session = EViewerDB.CreateSession(); subscribers = session.QueryOver().List(); unreadEventsRadioButton.Checked = true; } @@ -277,7 +277,7 @@ namespace EventViewer private void settingsButton_Click(object sender, EventArgs e) { //Common.GID[] groupsWithAccess = new Common.GID[] { Common.GID.Administrators }; - Users.Forms.LoginDlg dlg = new Users.Forms.LoginDlg(true); + Users.Forms.LoginDlg dlg = new Users.Forms.LoginDlg(); if (dlg.ShowDialog() == DialogResult.OK) { if ((new Forms.SettingsDlg()).ShowDialog() == DialogResult.OK) diff --git a/Events/DB.cs b/Events/DB.cs index 716c3be05..f7f65f6a6 100644 --- a/Events/DB.cs +++ b/Events/DB.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2020 Sensus Slovensko a.s. +/// Copyright (c) 2020-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -15,156 +15,6 @@ namespace Events { public static class DB { - /// Session factory for all regular sessions, not for CreateEmptyResultsDB(). - public static ISessionFactory SessionFactory; - - /// Connection string for all sessions - static string connectionString; - /// - public static string ConnectionString - { - get { return connectionString; } - set - { - if (value != connectionString) - { - connectionString = value; - SessionFactory = null; /// Clear SessionFactory on connection string change - } - } - } - - /// Database type (MySQL or SQLite) for all sessions - private static DBType dbType; - /// - public static DBType DbType - { - get { return dbType; } - set { dbType = value; SessionFactory = null; } - } - - /// - /// NHibernate session factory (to create the database session 'SessionFactory') - /// - /// A database session - static ISessionFactory CreateSessionFactory() - { - return CreateSessionFactory(false); - } - - /// - /// NHibernate session factory (to create the database session 'SessionFactory') - /// - /// true = Create a new DB, false = Regular DB - /// A database session - public static ISessionFactory CreateSessionFactory(bool createDB) - { - FluentConfiguration cfg = Fluently.Configure(); - - switch (dbType) - { - default: - case DBType.MySql: - cfg = cfg.Database(MySQLConfiguration.Standard.ConnectionString(connectionString)); - break; - case DBType.SQLite: - cfg = cfg.Database(SQLiteConfiguration.Standard.UsingFile(connectionString)); - break; - } - - cfg = cfg.Mappings(m => m.FluentMappings.AddFromAssemblyOf()); - - if (createDB) - { - return cfg.ExposeConfiguration(BuildSchemaCreate).BuildSessionFactory(); - } - else - { - return cfg.ExposeConfiguration(BuildSchema).BuildSessionFactory(); - } - } - - static void BuildSchema(Configuration config) - { - /// This NHibernate tool takes a configuration with mapping info and exports a database schema - new SchemaExport(config).SetOutputFile("db_schema"); - } - - static void BuildSchemaCreate(Configuration config) - { - /// This NHibernate tool takes a configuration with mapping info and exports a database schema - new SchemaExport(config).Create(true, true); - } - - /// Create a NHibernate session for the given database - public static ISession CreateSession() - { - if (string.IsNullOrEmpty(connectionString)) - { - throw new Exception("Connection string was not specified"); - } - - if (SessionFactory == null) SessionFactory = CreateSessionFactory(); - - return SessionFactory.OpenSession(); - } - - - public static void SaveObject(object obj) - { - SaveObject(CreateSession(), obj); - } - /// - public static void SaveObject(ISession session, object obj) - { - using (var transaction = session.BeginTransaction()) - { - session.SaveOrUpdate(obj); - try { transaction.Commit(); } - catch { } - } - } - - - public static void DeleteObject(object obj) - { - DeleteObject(CreateSession(), obj); - } - /// - public static void DeleteObject(ISession session, object obj) - { - using (var transaction = session.BeginTransaction()) - { - session.Delete(obj); - transaction.Commit(); - } - } - - - /// - /// Create an empty users database. - /// Database contains only the user 'admin' and the control board component 'CB'. - /// - /// DBType.SQLite or DBType.MySql - /// Connection string - /// true=success, false=error - public static bool CreateEmptyDB() - { - ISessionFactory sessionFactory = CreateSessionFactory(true); - if (sessionFactory == null) return false; - - /// Populate the database - using (var session = sessionFactory.OpenSession()) - { - using (var transaction = session.BeginTransaction()) - { - transaction.Commit(); - } - } - - return true; - } - /// /// Shared data (initially empty) /// @@ -180,7 +30,7 @@ namespace Events DB.BenchName = benchName; } - /// + /// /// Loads shared data from the database /// public static void LoadSubscribers(ISession session) @@ -193,6 +43,7 @@ namespace Events /// public static void LoadRecentEvents(ISession session, string benchName, int days) { + BenchName = benchName; RecentEvents = session.QueryOver() .Where(e => (e.Bench == benchName)) .And(e => (e.TimeStamp >= DateTime.Now - new TimeSpan(days, 0, 0, 0))) @@ -201,7 +52,8 @@ namespace Events public static void SaveEvent(ISession session, Event evnt, SubscriberGroup groups) { - if (allSubscribers == null) return; + if (allSubscribers == null) LoadSubscribers(session); + IList thisEventSubscribers = new List(); foreach (var s in allSubscribers) { @@ -211,10 +63,10 @@ namespace Events thisEventSubscribers.Add(s); } } - evnt.Bench = BenchName; evnt.Subscribers = thisEventSubscribers; + + evnt.Bench = BenchName; session.SaveOrUpdate(evnt); - session.Flush(); } } } diff --git a/Results/DB.cs b/Results/DB.cs index 52efe0856..4507d12ba 100644 --- a/Results/DB.cs +++ b/Results/DB.cs @@ -78,11 +78,17 @@ namespace Results if (createDB) { - return cfg.ExposeConfiguration(BuildSchemaCreate).BuildSessionFactory(); + return cfg.ExposeConfiguration(BuildSchemaCreate) + .BuildConfiguration() + .SetProperty("hibernate.connection.connect_timeout", Common.Const.MySqlConnectTimeoutSec) + .BuildSessionFactory(); } else { - return cfg.ExposeConfiguration(BuildSchema).BuildSessionFactory(); + return cfg.ExposeConfiguration(BuildSchema) + .BuildConfiguration() + .SetProperty("hibernate.connection.connect_timeout", Common.Const.MySqlConnectTimeoutSec) + .BuildSessionFactory(); } } @@ -180,29 +186,55 @@ namespace Results /// Loads shared data from the database /// /// Throws NHibernate exceptions - public static void LoadSharedData() + public static void LoadSharedData(ISession session = null) { - ISession session = DB.CreateSession(); + bool openAndCloseSession = (session == null); - TestDataList = session.QueryOver().List(); - ComponentsList = session.QueryOver().List(); - WaterMeterDataList = session.QueryOver().List(); - } + try + { + if (openAndCloseSession) session = Results.DB.CreateSession(); + TestDataList = session.QueryOver().List(); + ComponentsList = session.QueryOver().List(); + WaterMeterDataList = session.QueryOver().List(); + } + catch (Exception e) + { + log.ErrorFormat("Cannot open results DB: {0}", e.Message); + } + finally + { + if (openAndCloseSession && session != null && session.IsOpen) session.Close(); + } + } /// /// Loads shared data from the database /// /// Throws NHibernate exceptions - public static int GetMaxSavedBatchNr() + public static int GetMaxSavedBatchNr(ISession session = null) { - ISession session = DB.CreateSession(); - IList batches = session.QueryOver().List(); + bool openAndCloseSession = (session == null); + int maxBatchNr = 0; + + try + { + if (openAndCloseSession) session = Results.DB.CreateSession(); + IList batches = session.QueryOver().List(); + + foreach (var b in batches) + { + if (b.BatchNr > maxBatchNr) maxBatchNr = b.BatchNr; + } + } + catch (Exception e) + { + log.ErrorFormat("Cannot open results DB: {0}", e.Message); + } + finally + { + if (openAndCloseSession && session != null && session.IsOpen) session.Close(); + } - int maxBatchNr = 0; - foreach (var b in batches) - { - if (b.BatchNr > maxBatchNr) maxBatchNr = b.BatchNr; - } return maxBatchNr; } diff --git a/Results/DBase.cs b/Results/DBase.cs index db9ffb07c..513e47cf2 100644 --- a/Results/DBase.cs +++ b/Results/DBase.cs @@ -40,6 +40,8 @@ namespace Results .Database(MySQLConfiguration.Standard.ConnectionString(connectionString)) .Mappings(m => m.FluentMappings.AddFromAssemblyOf()) .ExposeConfiguration(BuildSchema) + .BuildConfiguration() + .SetProperty("hibernate.connection.connect_timeout", Common.Const.MySqlConnectTimeoutSec) .BuildSessionFactory(); } diff --git a/ResultsParser/Program.cs b/ResultsParser/Program.cs index 8ef444333..a01ea2f5e 100644 --- a/ResultsParser/Program.cs +++ b/ResultsParser/Program.cs @@ -31,6 +31,8 @@ namespace ResultsParser .Database(MySQLConfiguration.Standard.ConnectionString(connStr)) .Mappings(m => m.FluentMappings.AddFromAssemblyOf()) .ExposeConfiguration(BuildSchema) + .BuildConfiguration() + .SetProperty("hibernate.connection.connect_timeout", Common.Const.MySqlConnectTimeoutSec) .BuildSessionFactory() .OpenSession(); diff --git a/Statistics/Statistics.csproj b/Statistics/Statistics.csproj index 5ae871b2a..a10775265 100644 --- a/Statistics/Statistics.csproj +++ b/Statistics/Statistics.csproj @@ -133,6 +133,10 @@ + + {c8939821-ba5c-4988-a3d0-bf53b74865c7} + Common + {9D0DCC88-DC81-47EB-9FDD-4C3907871BFB} Results diff --git a/Statistics/StatisticsDlg.cs b/Statistics/StatisticsDlg.cs index 90bcd501b..83e12f29d 100644 --- a/Statistics/StatisticsDlg.cs +++ b/Statistics/StatisticsDlg.cs @@ -13,6 +13,7 @@ using NHibernate; using FluentNHibernate; using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; +using Common; using Results; using Results.Entities; using Statistics.Resources; @@ -98,6 +99,8 @@ namespace Statistics .Database(MySQLConfiguration.Standard.ConnectionString(connStr)) .Mappings(m => m.FluentMappings.AddFromAssemblyOf()) .ExposeConfiguration(BuildSchema) + .BuildConfiguration() + .SetProperty("hibernate.connection.connect_timeout", Const.MySqlConnectTimeoutSec) .BuildSessionFactory(); } catch (Exception) diff --git a/TBF/DB.cs b/TBF/DB.cs index 290562d0d..d7eb1aaab 100644 --- a/TBF/DB.cs +++ b/TBF/DB.cs @@ -1,11 +1,17 @@ /// -/// Copyright (c) 2021 Sensus Slovensko a.s. +/// Copyright (c) 2021-2023 Sensus Slovensko a.s. /// using System; +using System.Windows.Forms; using NHibernate; +using NHibernate.Cfg; +using NHibernate.Tool.hbm2ddl; +using FluentNHibernate.Cfg; +using FluentNHibernate.Cfg.Db; using Common; -using Config; -using Users.Entities; +using Events; +using TBF.Resources; +using System.Collections.Generic; namespace TBF { @@ -16,52 +22,196 @@ namespace TBF /// public static DatabaseSettings CurrentBench; - /// - /// Session factories for regular sessions. - /// - public static ISessionFactory[] SessionFactories = new ISessionFactory[(int)DBKind.Count]; + public static ISessionFactory ConfigDBSessionFactory = null; /// Configuration DB session factory (always != null) + public static ISessionFactory SharedDBSessionFactory = null; /// Shared configuration DB session factory or null + public static ISessionFactory ResultsDBSessionFactory = null; /// Results DB session factory (always != null) + public static ISessionFactory EventsDBSessionFactory = null; /// Events DB session factory or null - /// Create a NHibernate session for the given database - public static ISession CreateSession(DBKind database) + public static ISessionFactory LocalUsersDBSessionFactory = null; /// Local users DB session factory (always != null) + public static ISessionFactory SharedUsersDBSessionFactory = null; /// Shared users DB session factory or null + + public static ISessionFactory[] UserSessionFactories { - if (database < 0 || database >= DBKind.Count) return null; - - int ix = (int)database; - if (SessionFactories[ix] == null) + get { - SessionFactories[ix] = CreateSessionFactory(database); + return (SharedUsersDBSessionFactory != null) + ? new ISessionFactory[] { SharedUsersDBSessionFactory, LocalUsersDBSessionFactory } + : new ISessionFactory[] { LocalUsersDBSessionFactory }; + } + } + + /// + /// Create all database session factories + /// + public static void CreateSessionFactories(DatabaseSettings dbSettings) + { + /// Configuration database (local, always non-null) + if (dbSettings.ProceduresDBSettings != null && dbSettings.ProceduresDBSettings.IsValid) + { + ConfigDBSessionFactory = + CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf(), + dbSettings.ProceduresDBSettings.DbType, + dbSettings.ProceduresDBSettings.ConnectionString); + + LocalUsersDBSessionFactory = + CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf(), + dbSettings.ProceduresDBSettings.DbType, + dbSettings.ProceduresDBSettings.ConnectionString); } - return SessionFactories[ix].OpenSession(); + /// Shared configuration database (remote) + if (dbSettings.UsersDBSettings != null && dbSettings.UsersDBSettings.IsValid) + { + SharedDBSessionFactory = + CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf(), + dbSettings.UsersDBSettings.DbType, + dbSettings.UsersDBSettings.ConnectionString); + + SharedUsersDBSessionFactory = + CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf(), + dbSettings.UsersDBSettings.DbType, + dbSettings.UsersDBSettings.ConnectionString); + } + + /// Results database (local, always non-null) + if (dbSettings.WaterMetersDBSettings != null && dbSettings.WaterMetersDBSettings.IsValid) + { + Results.DB.SessionFactory = ResultsDBSessionFactory = + CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf(), + dbSettings.WaterMetersDBSettings.DbType, + dbSettings.WaterMetersDBSettings.ConnectionString); + } + + /// Events database (remote or local) + if (dbSettings.EventsDBSettings != null && dbSettings.EventsDBSettings.IsValid) + { + EventsDBSessionFactory = + CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf(), + dbSettings.EventsDBSettings.DbType, + dbSettings.EventsDBSettings.ConnectionString); + } } /// /// NHibernate session factory (to create the database session 'SessionFactory') /// /// A database session - static ISessionFactory CreateSessionFactory(DBKind database) + public static ISessionFactory CreateSessionFactory(Action mappings, DBType dbType, + string connectionString, bool createDB = false) { - DBType dbType; - string connectionString; - - switch (database) + try { - default: - case DBKind.Config: - dbType = CurrentBench.ProceduresDBSettings.DbType; - connectionString = CurrentBench.ProceduresDBSettings.ConnectionString; - break; - case DBKind.Results: - dbType = CurrentBench.WaterMetersDBSettings.DbType; - connectionString = CurrentBench.WaterMetersDBSettings.ConnectionString; - break; - case DBKind.RemoteConfig: - dbType = CurrentBench.UsersDBSettings.DbType; - connectionString = CurrentBench.UsersDBSettings.ConnectionString; - break; + var buildSchema = createDB ? (Action)BuildSchemaCreate : (Action)BuildSchema; + + switch (dbType) + { + default: + case DBType.MySql: + + return Fluently.Configure() + .Database(MySQLConfiguration.Standard.ConnectionString(connectionString)) + .Mappings(mappings) + .ExposeConfiguration(buildSchema) + .BuildConfiguration() + .SetProperty("hibernate.connection.connect_timeout", Const.MySqlConnectTimeoutSec) + .BuildSessionFactory(); + + case DBType.SQLite: + + return Fluently.Configure() + .Database(SQLiteConfiguration.Standard.UsingFile(connectionString)) + .Mappings(mappings) + .ExposeConfiguration(buildSchema) + .BuildSessionFactory(); + + } + } + catch (Exception exc) + { + MessageBox.Show(string.Format("{0}: {1}", Strings.Cannot_connect_to_the_database, exc.Message), + Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); + return null; + } + } + + static void BuildSchema(Configuration config) + { + /// This NHibernate tool takes a configuration (with mapping info in) + /// and exports a database schema from it + new SchemaExport(config).SetOutputFile("db_schema"); + } + + static void BuildSchemaCreate(Configuration config) + { + /// This NHibernate tool takes a configuration (with mapping info in) + /// and exports a database schema from it + new SchemaExport(config).Create(true, true); + } + + /// + /// Create an empty users database. + /// Database contains only the user 'admin' and the control board component 'CB'. + /// + /// DBType.SQLite or DBType.MySql + /// Connection string + /// true=success, false=error + public static bool CreateEmptyConfigDB(Common.DBType dbType, string connectionString) + { + ISessionFactory sessionFactory = + CreateSessionFactory(m => m.FluentMappings.AddFromAssemblyOf(), + dbType, connectionString, true); + + if (sessionFactory == null) return false; + + /// Populate the database + using (var session = sessionFactory.OpenSession()) + { + using (var transaction = session.BeginTransaction()) + { + /// + /// Create user 'admin' + /// + var admin = new Config.Entities.User + { + UserName = Config.Data.AdminUsername, + FullName = Strings.Administrator, + LastPwChange = DateTime.Now + }; + admin.SetPassword(Config.Data.AdminPassword); + + /// + /// Prepare all groups, add some of them to admin + /// + for (Common.GID gid = 0; gid < Common.GID.NrOfGroups; gid++) + { + Config.Entities.Group group = new Config.Entities.Group(gid); + switch (gid) + { + case Common.GID.Testers: + case Common.GID.TestingSpecialists: + case Common.GID.HeadOfLab: + case Common.GID.MaintenanceSpecialists: + case Common.GID.Metrologists: + case Common.GID.CalibrationSpecialists: + case Common.GID.Administrators: +#if TURA_IPERL || TURA_IPERL_NEW || TURA_SPECIAL + case Common.GID.TraceabilityManagement: +#elif KEMPNO_50 || KRAKOW_50 || TORUN_50 || WARSAW_50 || WARSAW_END + case Common.GID.MetrologicalAuthority: + case Common.GID.WaterMeterAuthority: +#endif + admin.AddGroup(group); + session.SaveOrUpdate(group); /// Save this group + break; + } + } + + session.SaveOrUpdate(admin); /// Save user 'admin' + transaction.Commit(); + } } - return Config.FluentCommon.CreateSessionFactory(database, dbType, connectionString, false); + return true; } } } diff --git a/TBF/Program.cs b/TBF/Program.cs index fb0c53f0e..298a6a66d 100644 --- a/TBF/Program.cs +++ b/TBF/Program.cs @@ -1,19 +1,19 @@ /// -/// Copyright (c) 2013-2022 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.IO; using System.Collections.Generic; +using System.Drawing; using System.Windows.Forms; using log4net; +using NHibernate; using Common; using Config.Entities; using Users; -using Users.Entities; using TBF.Resources; using TBF.Rig.Sequences; using TBF.UI.Shared; -using NHibernate; namespace TBF { @@ -214,7 +214,7 @@ namespace TBF /// Ask what to do, ask for the password, open 'DatabaseSetingsDlg' and continue on OK if ((new NoBenchOrDatabaseDlg { Message = Strings.NoBenchMsg }.ShowDialog() != DialogResult.OK) || - (new Users.Forms.LoginDlg(true).ShowDialog() == DialogResult.Cancel) || + (new Users.Forms.LoginDlg().ShowDialog() == DialogResult.Cancel) || (new TBF.UI.Settings.BenchesDlg().ShowDialog() == DialogResult.Cancel)) { return; /// Exit program @@ -229,6 +229,8 @@ namespace TBF bool retryLogin = true; /// true = stay in a login loop do { + LoadingConfigEnd(); + LoginDlgWithBenchSelection loginDlgBench; if (LocalSettings.LastBenchName != null) { @@ -251,10 +253,11 @@ namespace TBF { if (LocalSettings.TestBenches[i].BenchName == loginDlgBench.BenchName) { - log.FatalFormat("Test bench name: {0}", loginDlgBench.BenchName); + log.FatalFormat("Test bench name: {0}", loginDlgBench.BenchName); - Users.CurrentUser.RemoteUsersDB = LocalSettings.TestBenches[i].UsersDBSettings; - Users.CurrentUser.LocalUsersDB = LocalSettings.TestBenches[i].ProceduresDBSettings; + LoadingConfigStart(); + TBF.DB.CurrentBench = LocalSettings.TestBenches[i].Clone() as DatabaseSettings; + TBF.DB.CreateSessionFactories(LocalSettings.TestBenches[i]); Users.Entities.User loadedUser = null; try @@ -270,11 +273,10 @@ namespace TBF if (Users.Entities.User.IsPowerUser(loginDlgBench.Alias, loginDlgBench.Password)) { loadedUser = new Users.Entities.User(loginDlgBench.Alias, 6, true); - authorized = loadedUser.Authorize(loginDlgBench.Alias, loginDlgBench.Password, reqGrpMembership, null); - if (authorized) - { - Users.CurrentUser.AuthorizedAs = Common.AuthorizedAs.PowerUser; - } + CurrentUser.Change(loadedUser, null); + CurrentUser.LastAuthorization = DateTime.Now; + CurrentUser.AuthorizedAs = Common.AuthorizedAs.PowerUser; + authorized = true; } /// @@ -282,42 +284,57 @@ namespace TBF /// if (!authorized) { - DBSettings[] dbs = new DBSettings[] { Users.CurrentUser.RemoteUsersDB, Users.CurrentUser.LocalUsersDB }; - authorizedAs = Common.AuthorizedAs.RemoteUser; /// Try remote DB first - foreach (var db in dbs) + foreach (var sf in TBF.DB.UserSessionFactories) { /// Load and authorise user from the UsersDB database try { - if (loginDlgBench.Password == LoginDlgWithBenchSelection.UseTheTagPassword) + + if (sf != null) { - loadedUser = Users.Entities.User.LoadUserByTag(loginDlgBench.Alias, db); - if (loadedUser != null) authorized = loadedUser.AuthorizeTag(loginDlgBench.Alias, reqGrpMembership, null); - } - else - { - switch (loginDlgBench.Method) + var session = sf.OpenSession(); + + if (loginDlgBench.Password == LoginDlgWithBenchSelection.UseTheTagPassword) { - default: - case Common.LoginMethod.UserName: - loadedUser = Users.Entities.User.LoadUserByName(loginDlgBench.Alias, db); - if (loadedUser != null) authorized = loadedUser.Authorize(loginDlgBench.Alias, loginDlgBench.Password, reqGrpMembership, null); - break; - case Common.LoginMethod.FullName: - loadedUser = Users.Entities.User.LoadUserByFullName(loginDlgBench.Alias, db); - if (loadedUser != null) authorized = loadedUser.AuthorizeFullName(loginDlgBench.Alias, loginDlgBench.Password, reqGrpMembership, null); - break; - case Common.LoginMethod.Number: - int number; - if (!int.TryParse(loginDlgBench.Alias, out number)) break; - loadedUser = Users.Entities.User.LoadUserByNumber(number, db); - if (loadedUser != null) authorized = loadedUser.AuthorizeNumber(number, loginDlgBench.Password, reqGrpMembership, null); - break; + loadedUser = Users.Entities.User.LoadUserByTag(session, loginDlgBench.Alias); + if (loadedUser != null) authorized = loadedUser.AuthorizeTag(loginDlgBench.Alias, reqGrpMembership, null); } + else + { + switch (loginDlgBench.Method) + { + default: + case Common.LoginMethod.UserName: + loadedUser = Users.Entities.User.LoadUserByName(session, loginDlgBench.Alias); + if (loadedUser != null) + { + authorized = loadedUser.Authorize(session, loginDlgBench.Alias, loginDlgBench.Password, reqGrpMembership, null); + } + break; + case Common.LoginMethod.FullName: + loadedUser = Users.Entities.User.LoadUserByFullName(session, loginDlgBench.Alias); + if (loadedUser != null) + { + authorized = loadedUser.AuthorizeFullName(session, loginDlgBench.Alias, loginDlgBench.Password, reqGrpMembership, null); + } + break; + case Common.LoginMethod.Number: + int number; + if (!int.TryParse(loginDlgBench.Alias, out number)) break; + loadedUser = Users.Entities.User.LoadUserByNumber(session, number); + if (loadedUser != null) + { + authorized = loadedUser.AuthorizeNumber(session, number, loginDlgBench.Password, reqGrpMembership, null); + } + break; + } + } + + session.Close(); } - } + } catch { authorized = false; @@ -353,7 +370,11 @@ namespace TBF /// Copy the selected bench settings to CurrentBench. /// Clone() guarantees that current bench settings wont be modified /// when user modifies the database settings in DatabaseSettingsDlg. - TBF.DB.CurrentBench = (DatabaseSettings)LocalSettings.TestBenches[i].Clone(); + if (TBF.DB.CurrentBench == null) + { + TBF.DB.CurrentBench = LocalSettings.TestBenches[i].Clone() as DatabaseSettings; + TBF.DB.CreateSessionFactories(TBF.DB.CurrentBench); + } Results.DB.DbType = TBF.DB.CurrentBench.WaterMetersDBSettings.DbType; Results.DB.ConnectionString = TBF.DB.CurrentBench.WaterMetersDBSettings.ConnectionString; @@ -364,7 +385,7 @@ namespace TBF /// Connect to Config database. /// This triggers an exception in case user is a power user and there is no Config database. /// - ISession session = TBF.DB.CreateSession(DBKind.Config); + var session = TBF.DB.ConfigDBSessionFactory.OpenSession(); if (!string.IsNullOrEmpty(LocalSettings.LastProcedureName)) { @@ -380,9 +401,9 @@ namespace TBF .List(); if (components.Count > 0) { - var factory = new TBF.Rig.DataContainers.BenchInfo.Extended.ComponentFactory(); + var factory = new TBF.Rig.DataContainers.BenchInfo.Extended.ComponentFactory(); var cfg = factory.CmpntCfgFromCmpntEntity(components[0]) - as TBF.Rig.DataContainers.BenchInfo.Extended.ComponentCfg; + as TBF.Rig.DataContainers.BenchInfo.Extended.ComponentCfg; ProcessData.BenchInfo = new TBF.Rig.DataContainers.BenchInfo.Extended.Component(cfg); } else @@ -393,20 +414,20 @@ namespace TBF .List(); if (components.Count > 0) { - var factory = new TBF.Rig.DataContainers.BenchInfo.iPerl.ComponentFactory(); + var factory = new TBF.Rig.DataContainers.BenchInfo.iPerl.ComponentFactory(); var cfg = factory.CmpntCfgFromCmpntEntity(components[0]) - as TBF.Rig.DataContainers.BenchInfo.iPerl.ComponentCfg; + as TBF.Rig.DataContainers.BenchInfo.iPerl.ComponentCfg; ProcessData.BenchInfo = new TBF.Rig.DataContainers.BenchInfo.iPerl.Component(cfg); } } - session.Close(); /// /// Connect to Results database and determine the last saved batch number. /// - Results.DB.LoadSharedData(); - int maxBatchNr = Results.DB.GetMaxSavedBatchNr(); + var rsltDBSession = TBF.DB.ResultsDBSessionFactory.OpenSession(); + Results.DB.LoadSharedData(rsltDBSession); + int maxBatchNr = Results.DB.GetMaxSavedBatchNr(rsltDBSession); if (!TBF.DB.CurrentBench.IsRealBench || Program.LocalSettings.BatchNr <= maxBatchNr) { log.FatalFormat("Max. BatchNr in DB = {0}, LocalSettings.BatchNr = {1}", maxBatchNr, Program.LocalSettings.BatchNr); @@ -414,17 +435,7 @@ namespace TBF Program.LocalSettings.Save(); log.FatalFormat("LocalSettings.BatchNr updated to {0}", Program.LocalSettings.BatchNr); } - - /// - /// Connect to Events database (if any) and load recent events from this test bench. - /// - if (TBF.DB.CurrentBench.EventsDBSettings.DbType != Common.DBType.None && - !string.IsNullOrEmpty(TBF.DB.CurrentBench.EventsDBSettings.ConnectionString)) - { - Events.DB.DbType = (DBType)TBF.DB.CurrentBench.EventsDBSettings.DbType; - Events.DB.ConnectionString = TBF.DB.CurrentBench.EventsDBSettings.ConnectionString; - Events.DB.LoadRecentEvents(Events.DB.CreateSession(), loginDlgBench.BenchName, 7); /// Last 7 days - } + if (rsltDBSession != null && rsltDBSession.IsOpen) rsltDBSession.Close(); retryLogin = false; break; @@ -460,7 +471,7 @@ namespace TBF default: /// Open 'DatabaseSetingsDlg' and retry DB connect on OK - if (new Users.Forms.LoginDlg(true).ShowDialog() == DialogResult.Cancel || + if (new Users.Forms.LoginDlg().ShowDialog() == DialogResult.Cancel || new TBF.UI.Settings.BenchesDlg().ShowDialog() == DialogResult.Cancel) { return; /// Exit program @@ -482,26 +493,31 @@ namespace TBF /// if (LocalSettings.LastProcedureName != null) { - IList listOfProcedures = TBF.DB.CreateSession(Common.DBKind.Config) - .QueryOver() - .Where(x => (x.ProcedureState == Common.ProcedureState.Active)) - .And(x => (x.Name == LocalSettings.LastProcedureName)) - .List(); - - if (listOfProcedures.Count == 1) + using (var session = TBF.DB.ConfigDBSessionFactory.OpenSession()) { - log.InfoFormat("Pre-selecting the procedure {0}", LocalSettings.LastProcedureName); - SelectedProcedure = listOfProcedures[0]; + var listOfProcedures = session.QueryOver() + .Where(x => (x.ProcedureState == Common.ProcedureState.Active)) + .And(x => (x.Name == LocalSettings.LastProcedureName)) + .List(); + + if (listOfProcedures.Count == 1) + { + log.InfoFormat("Pre-selecting the procedure {0}", LocalSettings.LastProcedureName); + SelectedProcedure = listOfProcedures[0]; + } + + session.Close(); } } try - { - /// Open the main application window + { + /// Open the main application window log.Info("Creating the main window"); MainWnd = new UI.MainWnd(); log.Info("Opening the main window"); - Application.Run(MainWnd); + LoadingConfigEnd(); + Application.Run(MainWnd); log.Info("The main window was closed"); } catch (Exception e) @@ -536,5 +552,35 @@ namespace TBF log.FatalFormat("StackTrace : {0}{1}", Environment.NewLine, e.StackTrace); log.Fatal("--------------------------------------"); } - } -} \ No newline at end of file + + + static UI.Shared.ModelessActivityForm form; + static System.Threading.Thread formThread; + + static void LoadingConfigStart() + { + form = new UI.Shared.ModelessActivityForm() + { + Message = Strings.Starting_system, + FontFamily = "Arial", + FontSize = 24, + FontStyle = FontStyle.Regular, + BackgroundColor = Color.LightBlue, + }; + formThread = new System.Threading.Thread(() => form.ShowDialog()); + formThread.Start(); + System.Threading.Thread.Sleep(500); + } + + static void LoadingConfigEnd() + { + if (form != null && formThread != null) + { + form.CloseForm(null, new EventArgs()); + formThread.Join(); + } + form = null; + formThread = null; + } + } +} diff --git a/TBF/Properties/AssemblyInfo.cs b/TBF/Properties/AssemblyInfo.cs index e30cbc24a..aa8f2f325 100644 --- a/TBF/Properties/AssemblyInfo.cs +++ b/TBF/Properties/AssemblyInfo.cs @@ -29,5 +29,5 @@ using System.Runtime.InteropServices; // Build Number // Revision // -[assembly: AssemblyVersion("2.33.2034.0")] -[assembly: AssemblyFileVersion("2.33.2034.0")] +[assembly: AssemblyVersion("2.33.2057.0")] +[assembly: AssemblyFileVersion("2.33.2057.0")] diff --git a/TBF/Resources/Strings.Designer.cs b/TBF/Resources/Strings.Designer.cs index ff745e70f..e61570105 100644 --- a/TBF/Resources/Strings.Designer.cs +++ b/TBF/Resources/Strings.Designer.cs @@ -1905,6 +1905,15 @@ namespace TBF.Resources { } } + /// + /// Looks up a localized string similar to Error reading configuration database. + /// + internal static string Error_reading_configuration_database { + get { + return ResourceManager.GetString("Error_reading_configuration_database", resourceCulture); + } + } + /// /// Looks up a localized string similar to Error saving parameters of {0}. /// @@ -5415,6 +5424,15 @@ namespace TBF.Resources { } } + /// + /// Looks up a localized string similar to . + /// + internal static string String1 { + get { + return ResourceManager.GetString("String1", resourceCulture); + } + } + /// /// Looks up a localized string similar to Sun. /// diff --git a/TBF/Rig/DataContainers/BenchInfo/iPerl/Component.cs b/TBF/Rig/DataContainers/BenchInfo/iPerl/Component.cs index d5d3f9441..1137f6c8d 100644 --- a/TBF/Rig/DataContainers/BenchInfo/iPerl/Component.cs +++ b/TBF/Rig/DataContainers/BenchInfo/iPerl/Component.cs @@ -10,6 +10,7 @@ using Config; using TBF.Rig; using TBF.Rig.Generic; using TBF.Resources; +using TBF.UI.Calendar; namespace TBF.Rig.DataContainers.BenchInfo.iPerl { @@ -56,35 +57,51 @@ namespace TBF.Rig.DataContainers.BenchInfo.iPerl } - public IList GetCalendarEvents() + public List GetCalendarEvents() { - DateTime calibrationDue = myCfg.CalibValidDate; - IList calendarEvents = new List(); + var calEvents = new List(); - if (calibrationDue > TBF.UI.Constants.MinDate) + DateTime calibDue = myCfg.CalibValidDate; + if (calibDue > TBF.UI.Constants.MinDate) { - /// Calibration due date calendar event - calendarEvents.Add(new TBF.UI.Calendar.CalibrationDueDateEvent(calibrationDue.Date, Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)))); - if (DateTime.Now.Date <= calibrationDue.AddDays(-7)) + /// Five weekly notifications + foreach (var days in new int[] { -35, -28, -21, -14 }) { - /// Weekly reminders (last 5 weeks) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.Date.AddDays(-35), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - false)); + if (calibDue.Date.AddDays(days + 6) >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Notification, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } } - if (DateTime.Now.Date <= calibrationDue.Date) + + /// Five daily warnings + foreach (var days in new int[] { -7, -6, -5, -4, -3, -2, -1 }) { - /// Daily reminders (last 5 days) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.AddDays(-5), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - true)); + if (calibDue.Date.AddDays(days) >= DateTime.Now.Date) + { + /// Weekly reminders (last 5 weeks) + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Warning, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } + } + + /// Calibration due date + if (calibDue.Date >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationDueDateEvent(calibDue.Date, + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); } } - return calendarEvents; + + return calEvents; } } } diff --git a/TBF/Rig/DataContainers/Buoyancy/Component.cs b/TBF/Rig/DataContainers/Buoyancy/Component.cs index 624e15828..4b41cf838 100644 --- a/TBF/Rig/DataContainers/Buoyancy/Component.cs +++ b/TBF/Rig/DataContainers/Buoyancy/Component.cs @@ -1,10 +1,11 @@ /// -/// Copyright (c) 2019-2020 Sensus Slovensko a.s. +/// Copyright (c) 2019-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; using log4net; using TBF.Resources; +using TBF.UI.Calendar; namespace TBF.Rig.DataContainers.Buoyancy { @@ -36,35 +37,51 @@ namespace TBF.Rig.DataContainers.Buoyancy } - public IList GetCalendarEvents() + public List GetCalendarEvents() { - DateTime calibrationDue = myCfg.CalibValidDate; - IList calendarEvents = new List(); + var calEvents = new List(); - if (calibrationDue > TBF.UI.Constants.MinDate) + DateTime calibDue = myCfg.CalibValidDate; + if (calibDue > TBF.UI.Constants.MinDate) { - /// Calibration due date calendar event - calendarEvents.Add(new TBF.UI.Calendar.CalibrationDueDateEvent(calibrationDue.Date, Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)))); - if (DateTime.Now.Date <= calibrationDue.AddDays(-7)) + /// Five weekly notifications + foreach (var days in new int[] { -35, -28, -21, -14 }) { - /// Weekly reminders (last 5 weeks) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.Date.AddDays(-35), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - false)); + if (calibDue.Date.AddDays(days + 6) >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Notification, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } } - if (DateTime.Now.Date <= calibrationDue.Date) + + /// Five daily warnings + foreach (var days in new int[] { -7, -6, -5, -4, -3, -2, -1 }) { - /// Daily reminders (last 5 days) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.AddDays(-5), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - true)); + if (calibDue.Date.AddDays(days) >= DateTime.Now.Date) + { + /// Weekly reminders (last 5 weeks) + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Warning, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } + } + + /// Calibration due date + if (calibDue.Date >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationDueDateEvent(calibDue.Date, + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); } } - return calendarEvents; + + return calEvents; } } } diff --git a/TBF/Rig/DataContainers/Density/Component.cs b/TBF/Rig/DataContainers/Density/Component.cs index 93874a09d..fee77f209 100644 --- a/TBF/Rig/DataContainers/Density/Component.cs +++ b/TBF/Rig/DataContainers/Density/Component.cs @@ -1,10 +1,11 @@ /// -/// Copyright (c) 2019-2020 Sensus Slovensko a.s. +/// Copyright (c) 2019-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; using log4net; using TBF.Resources; +using TBF.UI.Calendar; namespace TBF.Rig.DataContainers.Density { @@ -39,35 +40,51 @@ namespace TBF.Rig.DataContainers.Density } - public IList GetCalendarEvents() + public List GetCalendarEvents() { - DateTime calibrationDue = myCfg.CalibValidDate; - IList calendarEvents = new List(); + var calEvents = new List(); - if (calibrationDue > TBF.UI.Constants.MinDate) + DateTime calibDue = myCfg.CalibValidDate; + if (calibDue > TBF.UI.Constants.MinDate) { - /// Calibration due date calendar event - calendarEvents.Add(new TBF.UI.Calendar.CalibrationDueDateEvent(calibrationDue.Date, Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)))); - if (DateTime.Now.Date <= calibrationDue.AddDays(-7)) + /// Five weekly notifications + foreach (var days in new int[] { -35, -28, -21, -14 }) { - /// Weekly reminders (last 5 weeks) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.Date.AddDays(-35), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - false)); + if (calibDue.Date.AddDays(days + 6) >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Notification, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } } - if (DateTime.Now.Date <= calibrationDue.Date) + + /// Five daily warnings + foreach (var days in new int[] { -7, -6, -5, -4, -3, -2, -1 }) { - /// Daily reminders (last 5 days) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.AddDays(-5), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - true)); + if (calibDue.Date.AddDays(days) >= DateTime.Now.Date) + { + /// Weekly reminders (last 5 weeks) + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Warning, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } + } + + /// Calibration due date + if (calibDue.Date >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationDueDateEvent(calibDue.Date, + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); } } - return calendarEvents; + + return calEvents; } } } diff --git a/TBF/Rig/DataContainers/Evaporation/Component.cs b/TBF/Rig/DataContainers/Evaporation/Component.cs index e38486807..0d2b65e1c 100644 --- a/TBF/Rig/DataContainers/Evaporation/Component.cs +++ b/TBF/Rig/DataContainers/Evaporation/Component.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2020 Sensus Slovensko a.s. +/// Copyright (c) 2020-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -7,6 +7,7 @@ using log4net; using Config.Entities; using TBF.Rig.GenericDevices; using TBF.Resources; +using TBF.UI.Calendar; namespace TBF.Rig.DataContainers.Evaporation { @@ -40,35 +41,51 @@ namespace TBF.Rig.DataContainers.Evaporation } - public IList GetCalendarEvents() + public List GetCalendarEvents() { - DateTime calibrationDue = myCfg.CalibValidDate; - IList calendarEvents = new List(); + var calEvents = new List(); - if (calibrationDue > TBF.UI.Constants.MinDate) + DateTime calibDue = myCfg.CalibValidDate; + if (calibDue > TBF.UI.Constants.MinDate) { - /// Calibration due date calendar event - calendarEvents.Add(new TBF.UI.Calendar.CalibrationDueDateEvent(calibrationDue.Date, Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)))); - if (DateTime.Now.Date <= calibrationDue.AddDays(-7)) + /// Five weekly notifications + foreach (var days in new int[] { -35, -28, -21, -14 }) { - /// Weekly reminders (last 5 weeks) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.Date.AddDays(-35), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - false)); + if (calibDue.Date.AddDays(days + 6) >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Notification, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } } - if (DateTime.Now.Date <= calibrationDue.Date) + + /// Five daily warnings + foreach (var days in new int[] { -7, -6, -5, -4, -3, -2, -1 }) { - /// Daily reminders (last 5 days) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.AddDays(-5), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - true)); + if (calibDue.Date.AddDays(days) >= DateTime.Now.Date) + { + /// Weekly reminders (last 5 weeks) + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Warning, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } + } + + /// Calibration due date + if (calibDue.Date >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationDueDateEvent(calibDue.Date, + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); } } - return calendarEvents; + + return calEvents; } } } diff --git a/TBF/Rig/Elde/CoverTest/CoverTestForm.cs b/TBF/Rig/Elde/CoverTest/CoverTestForm.cs index c1fc888ea..3fd38ccb9 100644 --- a/TBF/Rig/Elde/CoverTest/CoverTestForm.cs +++ b/TBF/Rig/Elde/CoverTest/CoverTestForm.cs @@ -56,7 +56,7 @@ namespace TBF.Rig.Elde.CoverTest { if (!Users.CurrentUser.IsMemberOf(bypassLevel)) { - if ((new Users.Forms.LoginDlg(bypassLevel, this)).ShowDialog() != DialogResult.OK) + if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, bypassLevel, this)).ShowDialog() != DialogResult.OK) { return; } diff --git a/TBF/Rig/Elde/Diverter/Diverter.cs b/TBF/Rig/Elde/Diverter/Diverter.cs index f1152ef31..796692b0b 100644 --- a/TBF/Rig/Elde/Diverter/Diverter.cs +++ b/TBF/Rig/Elde/Diverter/Diverter.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2013-2022 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -9,6 +9,7 @@ using Dirichlet.Numerics; using TBF.Rig.Generic; using TBF.Boxes; using TBF.Resources; +using TBF.UI.Calendar; namespace TBF.Rig.Elde.Diverter { @@ -152,35 +153,51 @@ namespace TBF.Rig.Elde.Diverter /// /// Calendar support /// - public IList GetCalendarEvents() + public List GetCalendarEvents() { - DateTime calibrationDue = diverterCfg.CalibValidDate; - IList calendarEvents = new List(); + var calEvents = new List(); - if (calibrationDue > TBF.UI.Constants.MinDate) + DateTime calibDue = diverterCfg.CalibValidDate; + if (calibDue > TBF.UI.Constants.MinDate) { - /// Calibration due date calendar event - calendarEvents.Add(new TBF.UI.Calendar.CalibrationDueDateEvent(calibrationDue.Date, Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)))); - if (DateTime.Now.Date <= calibrationDue.AddDays(-7)) + /// Five weekly notifications + foreach (var days in new int[] { -35, -28, -21, -14 }) { - /// Weekly reminders (last 5 weeks) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.Date.AddDays(-35), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - false)); + if (calibDue.Date.AddDays(days + 6) >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Notification, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } } - if (DateTime.Now.Date <= calibrationDue.Date) + + /// Five daily warnings + foreach (var days in new int[] { -7, -6, -5, -4, -3, -2, -1 }) { - /// Daily reminders (last 5 days) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.AddDays(-5), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - true)); + if (calibDue.Date.AddDays(days) >= DateTime.Now.Date) + { + /// Weekly reminders (last 5 weeks) + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Warning, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } + } + + /// Calibration due date + if (calibDue.Date >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationDueDateEvent(calibDue.Date, + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); } } - return calendarEvents; + + return calEvents; } /// diff --git a/TBF/Rig/Elde/FlowMeter/FlowMeter.cs b/TBF/Rig/Elde/FlowMeter/FlowMeter.cs index 129f47a21..f69780ddb 100644 --- a/TBF/Rig/Elde/FlowMeter/FlowMeter.cs +++ b/TBF/Rig/Elde/FlowMeter/FlowMeter.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2013-2018 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -7,6 +7,7 @@ using log4net; using Config.Entities; using TBF.Boxes; using TBF.Resources; +using TBF.UI.Calendar; namespace TBF.Rig.Elde.FlowMeter { @@ -68,7 +69,7 @@ namespace TBF.Rig.Elde.FlowMeter { for (int r = 0; r <= 5; r++) { - if (RangeEnabled(r) && flowMeterCfg.GetCalibValidDate(r) != DateTime.MinValue + if (RangeEnabled(r) && flowMeterCfg.GetCalibValidDate(r) > DateTime.MinValue && flowMeterCfg.GetCalibValidDate(r).Date < DateTime.Now.Date) { throw new Exception(string.Format("{0}/r{1}: {2}", Name, r, Strings.Calibration_certificate_validity_expired)); @@ -86,35 +87,51 @@ namespace TBF.Rig.Elde.FlowMeter /// /// Calendar support /// - public IList GetCalendarEvents() + public List GetCalendarEvents() { - DateTime calibrationDue = flowMeterCfg.CalibValidDate; - IList calendarEvents = new List(); + var calEvents = new List(); - if (calibrationDue > TBF.UI.Constants.MinDate) + DateTime calibDue = flowMeterCfg.CalibValidDate; + if (calibDue > TBF.UI.Constants.MinDate) { - /// Calibration due date calendar event - calendarEvents.Add(new TBF.UI.Calendar.CalibrationDueDateEvent(calibrationDue.Date, Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)))); - if (DateTime.Now.Date <= calibrationDue.AddDays(-7)) + /// Five weekly notifications + foreach (var days in new int[] { -35, -28, -21, -14 }) { - /// Weekly reminders (last 5 weeks) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.Date.AddDays(-35), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - false)); + if (calibDue.Date.AddDays(days + 6) >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Notification, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } } - if (DateTime.Now.Date <= calibrationDue.Date) + + /// Five daily warnings + foreach (var days in new int[] { -7, -6, -5, -4, -3, -2, -1 }) { - /// Daily reminders (last 5 days) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.AddDays(-5), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - true)); + if (calibDue.Date.AddDays(days) >= DateTime.Now.Date) + { + /// Weekly reminders (last 5 weeks) + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Warning, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } + } + + /// Calibration due date + if (calibDue.Date >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationDueDateEvent(calibDue.Date, + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); } } - return calendarEvents; + + return calEvents; } diff --git a/TBF/Rig/Elde/PressureMeter/PressureMeter.cs b/TBF/Rig/Elde/PressureMeter/PressureMeter.cs index 1e982f590..d083606c8 100644 --- a/TBF/Rig/Elde/PressureMeter/PressureMeter.cs +++ b/TBF/Rig/Elde/PressureMeter/PressureMeter.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2013-2020 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -7,6 +7,7 @@ using log4net; using TBF.Rig.Generic; using TBF.Boxes; using TBF.Resources; +using TBF.UI.Calendar; namespace TBF.Rig.Elde.PressureMeter { @@ -55,35 +56,51 @@ namespace TBF.Rig.Elde.PressureMeter } - public IList GetCalendarEvents() + public List GetCalendarEvents() { - DateTime calibrationDue = pressureMeterCfg.CalibValidDate; - IList calendarEvents = new List(); + var calEvents = new List(); - if (calibrationDue > TBF.UI.Constants.MinDate) + DateTime calibDue = pressureMeterCfg.CalibValidDate; + if (calibDue > TBF.UI.Constants.MinDate) { - /// Calibration due date calendar event - calendarEvents.Add(new TBF.UI.Calendar.CalibrationDueDateEvent(calibrationDue.Date, Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)))); - if (DateTime.Now.Date <= calibrationDue.AddDays(-7)) + /// Five weekly notifications + foreach (var days in new int[] { -35, -28, -21, -14 }) { - /// Weekly reminders (last 5 weeks) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.Date.AddDays(-35), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - false)); + if (calibDue.Date.AddDays(days + 6) >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Notification, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } } - if (DateTime.Now.Date <= calibrationDue.Date) + + /// Five daily warnings + foreach (var days in new int[] { -7, -6, -5, -4, -3, -2, -1 }) { - /// Daily reminders (last 5 days) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.AddDays(-5), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - true)); + if (calibDue.Date.AddDays(days) >= DateTime.Now.Date) + { + /// Weekly reminders (last 5 weeks) + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Warning, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } + } + + /// Calibration due date + if (calibDue.Date >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationDueDateEvent(calibDue.Date, + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); } } - return calendarEvents; + + return calEvents; } diff --git a/TBF/Rig/Elde/PressureMeterInternal/PressureMeter.cs b/TBF/Rig/Elde/PressureMeterInternal/PressureMeter.cs index 5f6fb5535..7f322ba61 100644 --- a/TBF/Rig/Elde/PressureMeterInternal/PressureMeter.cs +++ b/TBF/Rig/Elde/PressureMeterInternal/PressureMeter.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2015 Sensus Metering Systems +/// Copyright (c) 2015-2023 Sensus Slovensko a.s. /// Author: Milan Hanajik /// using System; @@ -8,6 +8,7 @@ using log4net; using TBF.Rig.Generic; using TBF.Boxes; using TBF.Resources; +using TBF.UI.Calendar; namespace TBF.Rig.Elde.PressureMeterInternal { @@ -49,35 +50,51 @@ namespace TBF.Rig.Elde.PressureMeterInternal } - public IList GetCalendarEvents() + public List GetCalendarEvents() { - DateTime calibrationDue = pressureMeterCfg.CalibValidDate; - IList calendarEvents = new List(); + var calEvents = new List(); - if (calibrationDue > TBF.UI.Constants.MinDate) + DateTime calibDue = pressureMeterCfg.CalibValidDate; + if (calibDue > TBF.UI.Constants.MinDate) { - /// Calibration due date calendar event - calendarEvents.Add(new TBF.UI.Calendar.CalibrationDueDateEvent(calibrationDue.Date, Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)))); - if (DateTime.Now.Date <= calibrationDue.AddDays(-7)) + /// Five weekly notifications + foreach (var days in new int[] { -35, -28, -21, -14 }) { - /// Weekly reminders (last 5 weeks) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.Date.AddDays(-35), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - false)); + if (calibDue.Date.AddDays(days + 6) >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Notification, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } } - if (DateTime.Now.Date <= calibrationDue.Date) + + /// Five daily warnings + foreach (var days in new int[] { -7, -6, -5, -4, -3, -2, -1 }) { - /// Daily reminders (last 5 days) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.AddDays(-5), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - true)); + if (calibDue.Date.AddDays(days) >= DateTime.Now.Date) + { + /// Weekly reminders (last 5 weeks) + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Warning, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } + } + + /// Calibration due date + if (calibDue.Date >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationDueDateEvent(calibDue.Date, + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); } } - return calendarEvents; + + return calEvents; } diff --git a/TBF/Rig/Elde/TempMeter/TempMeter.cs b/TBF/Rig/Elde/TempMeter/TempMeter.cs index 0e94b8cb7..6a33a69f9 100644 --- a/TBF/Rig/Elde/TempMeter/TempMeter.cs +++ b/TBF/Rig/Elde/TempMeter/TempMeter.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2013-2020 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -8,6 +8,7 @@ using Common; using TBF.Rig.Generic; using TBF.Boxes; using TBF.Resources; +using TBF.UI.Calendar; namespace TBF.Rig.Elde.TempMeter { @@ -52,35 +53,51 @@ namespace TBF.Rig.Elde.TempMeter } - public IList GetCalendarEvents() + public List GetCalendarEvents() { - DateTime calibrationDue = tempMtrCfg.CalibValidDate; - IList calendarEvents = new List(); + var calEvents = new List(); - if (calibrationDue > TBF.UI.Constants.MinDate) + DateTime calibDue = tempMtrCfg.CalibValidDate; + if (calibDue > TBF.UI.Constants.MinDate) { - /// Calibration due date calendar event - calendarEvents.Add(new TBF.UI.Calendar.CalibrationDueDateEvent(calibrationDue.Date, Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)))); - if (DateTime.Now.Date <= calibrationDue.AddDays(-7)) + /// Five weekly notifications + foreach (var days in new int[] { -35, -28, -21, -14 }) { - /// Weekly reminders (last 5 weeks) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.Date.AddDays(-35), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - false)); + if (calibDue.Date.AddDays(days + 6) >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Notification, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } } - if (DateTime.Now.Date <= calibrationDue.Date) + + /// Five daily warnings + foreach (var days in new int[] { -7, -6, -5, -4, -3, -2, -1 }) { - /// Daily reminders (last 5 days) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.AddDays(-5), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - true)); + if (calibDue.Date.AddDays(days) >= DateTime.Now.Date) + { + /// Weekly reminders (last 5 weeks) + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Warning, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } + } + + /// Calibration due date + if (calibDue.Date >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationDueDateEvent(calibDue.Date, + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); } } - return calendarEvents; + + return calEvents; } public double ReadTemperature() diff --git a/TBF/Rig/Elde/TempMeterInternal/TempMeter.cs b/TBF/Rig/Elde/TempMeterInternal/TempMeter.cs index 53263460c..7ae4ea4ea 100644 --- a/TBF/Rig/Elde/TempMeterInternal/TempMeter.cs +++ b/TBF/Rig/Elde/TempMeterInternal/TempMeter.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2015 Sensus Metering Systems +/// Copyright (c) 2015-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -7,6 +7,7 @@ using log4net; using TBF.Rig.Generic; using TBF.Boxes; using TBF.Resources; +using TBF.UI.Calendar; namespace TBF.Rig.Elde.TempMeterInternal { @@ -46,35 +47,51 @@ namespace TBF.Rig.Elde.TempMeterInternal } - public IList GetCalendarEvents() + public List GetCalendarEvents() { - DateTime calibrationDue = tempMtrCfg.CalibValidDate; - IList calendarEvents = new List(); + var calEvents = new List(); - if (calibrationDue > TBF.UI.Constants.MinDate) + DateTime calibDue = tempMtrCfg.CalibValidDate; + if (calibDue > TBF.UI.Constants.MinDate) { - /// Calibration due date calendar event - calendarEvents.Add(new TBF.UI.Calendar.CalibrationDueDateEvent(calibrationDue.Date, Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)))); - if (DateTime.Now.Date <= calibrationDue.AddDays(-7)) + /// Five weekly notifications + foreach (var days in new int[] { -35, -28, -21, -14 }) { - /// Weekly reminders (last 5 weeks) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.Date.AddDays(-35), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - false)); + if (calibDue.Date.AddDays(days + 6) >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Notification, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } } - if (DateTime.Now.Date <= calibrationDue.Date) + + /// Five daily warnings + foreach (var days in new int[] { -7, -6, -5, -4, -3, -2, -1 }) { - /// Daily reminders (last 5 days) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.AddDays(-5), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - true)); + if (calibDue.Date.AddDays(days) >= DateTime.Now.Date) + { + /// Weekly reminders (last 5 weeks) + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Warning, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } + } + + /// Calibration due date + if (calibDue.Date >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationDueDateEvent(calibDue.Date, + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); } } - return calendarEvents; + + return calEvents; } diff --git a/TBF/Rig/Elde/TempMeterMeret/TempMeter.cs b/TBF/Rig/Elde/TempMeterMeret/TempMeter.cs index b579ddba1..c75a05382 100644 --- a/TBF/Rig/Elde/TempMeterMeret/TempMeter.cs +++ b/TBF/Rig/Elde/TempMeterMeret/TempMeter.cs @@ -1,11 +1,12 @@ /// -/// Copyright (c) 2018 Sensus Slovensko a.s. +/// Copyright (c) 2018-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; using log4net; using TBF.Boxes; using TBF.Resources; +using TBF.UI.Calendar; namespace TBF.Rig.Elde.TempMeterMeret { @@ -39,35 +40,51 @@ namespace TBF.Rig.Elde.TempMeterMeret } - public IList GetCalendarEvents() + public List GetCalendarEvents() { - DateTime calibrationDue = tempMtrCfg.CalibValidDate; - IList calendarEvents = new List(); + var calEvents = new List(); - if (calibrationDue > TBF.UI.Constants.MinDate) + DateTime calibDue = tempMtrCfg.CalibValidDate; + if (calibDue > TBF.UI.Constants.MinDate) { - /// Calibration due date calendar event - calendarEvents.Add(new TBF.UI.Calendar.CalibrationDueDateEvent(calibrationDue.Date, Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)))); - if (DateTime.Now.Date <= calibrationDue.AddDays(-7)) + /// Five weekly notifications + foreach (var days in new int[] { -35, -28, -21, -14 }) { - /// Weekly reminders (last 5 weeks) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.Date.AddDays(-35), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - false)); + if (calibDue.Date.AddDays(days + 6) >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Notification, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } } - if (DateTime.Now.Date <= calibrationDue.Date) + + /// Five daily warnings + foreach (var days in new int[] { -7, -6, -5, -4, -3, -2, -1 }) { - /// Daily reminders (last 5 days) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.AddDays(-5), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - true)); + if (calibDue.Date.AddDays(days) >= DateTime.Now.Date) + { + /// Weekly reminders (last 5 weeks) + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Warning, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } + } + + /// Calibration due date + if (calibDue.Date >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationDueDateEvent(calibDue.Date, + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); } } - return calendarEvents; + + return calEvents; } diff --git a/TBF/Rig/GenericDevices/IHasCalendarEvents.cs b/TBF/Rig/GenericDevices/IHasCalendarEvents.cs index 32b9166c4..8cf959f2b 100644 --- a/TBF/Rig/GenericDevices/IHasCalendarEvents.cs +++ b/TBF/Rig/GenericDevices/IHasCalendarEvents.cs @@ -8,6 +8,6 @@ namespace TBF.Rig.GenericDevices { interface IHasCalendarEvents { - IList GetCalendarEvents(); + List GetCalendarEvents(); } } diff --git a/TBF/Rig/Hart/Nivotrack/Nivotrack.cs b/TBF/Rig/Hart/Nivotrack/Nivotrack.cs index 8d6d5d78c..ec08398fe 100644 --- a/TBF/Rig/Hart/Nivotrack/Nivotrack.cs +++ b/TBF/Rig/Hart/Nivotrack/Nivotrack.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2018 Sensus Slovensko a.s. +/// Copyright (c) 2018-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -10,6 +10,7 @@ using TBF.Rig.GenericDevices; using TBF.Boxes; using TBF.Rig.Hart.Common; using TBF.Resources; +using TBF.UI.Calendar; namespace TBF.Rig.Hart.Nivotrack { @@ -77,35 +78,51 @@ namespace TBF.Rig.Hart.Nivotrack /// /// Calendar support /// - public IList GetCalendarEvents() + public List GetCalendarEvents() { - DateTime calibrationDue = nivotrackCfg.CalibValidDate; - IList calendarEvents = new List(); + var calEvents = new List(); - if (calibrationDue > TBF.UI.Constants.MinDate) + DateTime calibDue = nivotrackCfg.CalibValidDate; + if (calibDue > TBF.UI.Constants.MinDate) { - /// Calibration due date calendar event - calendarEvents.Add(new TBF.UI.Calendar.CalibrationDueDateEvent(calibrationDue.Date, Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)))); - if (DateTime.Now.Date <= calibrationDue.AddDays(-7)) + /// Five weekly notifications + foreach (var days in new int[] { -35, -28, -21, -14 }) { - /// Weekly reminders (last 5 weeks) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.Date.AddDays(-35), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - false)); + if (calibDue.Date.AddDays(days + 6) >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Notification, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } } - if (DateTime.Now.Date <= calibrationDue.Date) + + /// Five daily warnings + foreach (var days in new int[] { -7, -6, -5, -4, -3, -2, -1 }) { - /// Daily reminders (last 5 days) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.AddDays(-5), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - true)); + if (calibDue.Date.AddDays(days) >= DateTime.Now.Date) + { + /// Weekly reminders (last 5 weeks) + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Warning, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } + } + + /// Calibration due date + if (calibDue.Date >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationDueDateEvent(calibDue.Date, + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); } } - return calendarEvents; + + return calEvents; } diff --git a/TBF/Rig/Keithley/TempMeter/TempMeter.cs b/TBF/Rig/Keithley/TempMeter/TempMeter.cs index f7fc0fed4..57151cd0e 100644 --- a/TBF/Rig/Keithley/TempMeter/TempMeter.cs +++ b/TBF/Rig/Keithley/TempMeter/TempMeter.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2016-2020 Sensus Metering Systems +/// Copyright (c) 2016-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -8,6 +8,7 @@ using log4net; using TBF.Boxes; using TBF.Rig.Keithley.Multimeter_2010_RS232; using TBF.Resources; +using TBF.UI.Calendar; namespace TBF.Rig.Keithley.TempMeter { @@ -49,35 +50,51 @@ namespace TBF.Rig.Keithley.TempMeter /// /// Calendar support /// - public IList GetCalendarEvents() + public List GetCalendarEvents() { - DateTime calibrationDue = tempMtrCfg.CalibValidDate; - IList calendarEvents = new List(); + var calEvents = new List(); - if (calibrationDue > TBF.UI.Constants.MinDate) + DateTime calibDue = tempMtrCfg.CalibValidDate; + if (calibDue > TBF.UI.Constants.MinDate) { - /// Calibration due date calendar event - calendarEvents.Add(new TBF.UI.Calendar.CalibrationDueDateEvent(calibrationDue.Date, Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)))); - if (DateTime.Now.Date <= calibrationDue.AddDays(-7)) + /// Five weekly notifications + foreach (var days in new int[] { -35, -28, -21, -14 }) { - /// Weekly reminders (last 5 weeks) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.Date.AddDays(-35), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - false)); + if (calibDue.Date.AddDays(days + 6) >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Notification, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } } - if (DateTime.Now.Date <= calibrationDue.Date) + + /// Five daily warnings + foreach (var days in new int[] { -7, -6, -5, -4, -3, -2, -1 }) { - /// Daily reminders (last 5 days) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.AddDays(-5), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - true)); + if (calibDue.Date.AddDays(days) >= DateTime.Now.Date) + { + /// Weekly reminders (last 5 weeks) + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Warning, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } + } + + /// Calibration due date + if (calibDue.Date >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationDueDateEvent(calibDue.Date, + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); } } - return calendarEvents; + + return calEvents; } public double ReadTemperature() diff --git a/TBF/Rig/MettlerToledo/Standard/BalanceDev.cs b/TBF/Rig/MettlerToledo/Standard/BalanceDev.cs index 9fb42b1d7..eb25554ec 100644 --- a/TBF/Rig/MettlerToledo/Standard/BalanceDev.cs +++ b/TBF/Rig/MettlerToledo/Standard/BalanceDev.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2013-2021 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -12,6 +12,7 @@ using TBF.Rig.Generic; using TBF.Rig.GenericDevices; using TBF.Boxes; using TBF.Resources; +using TBF.UI.Calendar; namespace TBF.Rig.MettlerToledo.Standard { @@ -111,7 +112,7 @@ namespace TBF.Rig.MettlerToledo.Standard Balances[nextBalanceIdx - 1] = this; } - if (balanceCfg.CalibValidDate != DateTime.MinValue && balanceCfg.CalibValidDate.Date < DateTime.Now.Date) + if (balanceCfg.CalibValidDate > DateTime.MinValue && balanceCfg.CalibValidDate.Date < DateTime.Now.Date) { throw new Exception(string.Format("{0}: {1}", Name, Strings.Calibration_certificate_validity_expired)); } @@ -137,35 +138,51 @@ namespace TBF.Rig.MettlerToledo.Standard } - public IList GetCalendarEvents() + public List GetCalendarEvents() { - DateTime calibrationDue = balanceCfg.CalibValidDate; - IList calendarEvents = new List(); + var calEvents = new List(); - if (calibrationDue > TBF.UI.Constants.MinDate) + DateTime calibDue = balanceCfg.CalibValidDate; + if (calibDue > TBF.UI.Constants.MinDate) { - /// Calibration due date calendar event - calendarEvents.Add(new TBF.UI.Calendar.CalibrationDueDateEvent(calibrationDue.Date, Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)))); - if (DateTime.Now.Date <= calibrationDue.AddDays(-7)) + /// Five weekly notifications + foreach (var days in new int[] { -35, -28, -21, -14 }) { - /// Weekly reminders (last 5 weeks) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.Date.AddDays(-35), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - false)); + if (calibDue.Date.AddDays(days + 6) >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Notification, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } } - if (DateTime.Now.Date <= calibrationDue.Date) + + /// Five daily warnings + foreach (var days in new int[] { -7, -6, -5, -4, -3, -2, -1 }) { - /// Daily reminders (last 5 days) - calendarEvents.Add(new TBF.UI.Calendar.CalibrationReminderEvent(calibrationDue.AddDays(-5), Name, - string.Format(Strings.Calibration_due_date_is_0, - calibrationDue.Date.ToString(TBF.UI.Constants.DateFormat)), - true)); + if (calibDue.Date.AddDays(days) >= DateTime.Now.Date) + { + /// Weekly reminders (last 5 weeks) + calEvents.Add(new CalibrationReminderEvent(Config.CalendarEvent.AutoAction.Warning, + calibDue.Date.AddDays(days), + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); + } + } + + /// Calibration due date + if (calibDue.Date >= DateTime.Now.Date) + { + calEvents.Add(new CalibrationDueDateEvent(calibDue.Date, + Name, + string.Format(Strings.Calibration_due_date_is_0, + calibDue.Date.ToString(TBF.UI.Constants.DateFormat)))); } } - return calendarEvents; + + return calEvents; } diff --git a/TBF/Rig/Output/DB/ProductionTracing/Tracing.cs b/TBF/Rig/Output/DB/ProductionTracing/Tracing.cs index c10924a6d..0d6c96120 100644 --- a/TBF/Rig/Output/DB/ProductionTracing/Tracing.cs +++ b/TBF/Rig/Output/DB/ProductionTracing/Tracing.cs @@ -1,11 +1,13 @@ /// -/// Copyright (c) 2018-2019 Sensus Slovensko a.s. +/// Copyright (c) 2018-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; using System.Linq; using System.Net; using log4net; +using FluentNHibernate.Cfg; +using FluentNHibernate.Cfg.Db; using NHibernate; using NHibernate.Criterion; using Common; @@ -117,39 +119,42 @@ namespace TBF.Rig.Output.DB.ProductionTracing if (tracingCfg.DebugLevel == DebugMode.Normal) { /// Session factory is used to create database sessions - sessionFactory = FluentNHibernate.Cfg.Fluently.Configure() - .Database(FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard.ConnectionString(tracingCfg.ConnStr)) - .Mappings(m => m.FluentMappings.AddFromAssemblyOf()) - .ExposeConfiguration(TracingDB.DB.BuildSchema) - .BuildSessionFactory(); + sessionFactory = Fluently.Configure() + .Database(MySQLConfiguration.Standard.ConnectionString(tracingCfg.ConnStr)) + .Mappings(m => m.FluentMappings.AddFromAssemblyOf()) + .ExposeConfiguration(TracingDB.DB.BuildSchema) + .BuildConfiguration() + .SetProperty("hibernate.connection.connect_timeout", Const.MySqlConnectTimeoutSec) + .BuildSessionFactory(); /// Session factory 2 is used to create the 2nd database sessions if (!string.IsNullOrEmpty(tracingCfg.ConnStr2)) { - sessionFactory2 = FluentNHibernate.Cfg.Fluently.Configure() - .Database(FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard.ConnectionString(tracingCfg.ConnStr2)) - .Mappings(m => m.FluentMappings.AddFromAssemblyOf()) - .ExposeConfiguration(TracingDB.DB.BuildSchema) - .BuildSessionFactory(); + sessionFactory2 = Fluently.Configure() + .Database(FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard.ConnectionString(tracingCfg.ConnStr2)) + .Mappings(m => m.FluentMappings.AddFromAssemblyOf()) + .ExposeConfiguration(TracingDB.DB.BuildSchema) + .BuildConfiguration() + .SetProperty("hibernate.connection.connect_timeout", Const.MySqlConnectTimeoutSec) + .BuildSessionFactory(); } /// Register this test bench in the tracing DB for approx. 2 weeks - ISession session = sessionFactory.OpenSession(); - + var session = sessionFactory.OpenSession(); #if !DEBUG - /// Only a release version registers a workplace - TracingDB.DB.RegisterWorkplace(session, - workplace, - Users.CurrentUser.UserName(), - (ipAddress != null) ? ipAddress.ToString() : "1.2.3.4", - "", - WorkstepName, - DateTime.Now + new TimeSpan(15, 0, 0, 0)); -#endif + /// Only a release version registers a workplace + TracingDB.DB.RegisterWorkplace(session, + workplace, + Users.CurrentUser.UserName(), + (ipAddress != null) ? ipAddress.ToString() : "1.2.3.4", + "", + WorkstepName, + DateTime.Now + new TimeSpan(15, 0, 0, 0)); session.Flush(); +#endif session.Close(); + TracingDB.DB.SessionFactory = sessionFactory; - if (session != null) session.Dispose(); log.FatalFormat("{0} initialized: {1}", Name, this); } else @@ -275,11 +280,12 @@ namespace TBF.Rig.Output.DB.ProductionTracing opCompleted = true; if (SaveTracingRecords(batch) != Retv.OK) anyError = true; - if (anyError && !string.IsNullOrEmpty(Events.DB.ConnectionString)) + if (TBF.DB.EventsDBSessionFactory != null && anyError) { + NHibernate.ISession session = null; try { - NHibernate.ISession session = Events.DB.CreateSession(); + session = TBF.DB.EventsDBSessionFactory.OpenSession(); Events.DB.LoadSubscribers(session); TBF.UiBridge.Bridge.TriggerEvent(session, Name, EventClass.ComputerResources, Severity.Error, @@ -291,17 +297,22 @@ namespace TBF.Rig.Output.DB.ProductionTracing { log.ErrorFormat("Triggering event(s) failed: {0}", exc.Message); } + finally + { + if (session != null && session.IsOpen) session.Close(); + } } return anyError ? Event.ErrorProcessingResults : Event.ResultsWritten; } else { - if (anyError && !string.IsNullOrEmpty(Events.DB.ConnectionString)) + if (TBF.DB.EventsDBSessionFactory != null && anyError) { + NHibernate.ISession session = null; try { - NHibernate.ISession session = Events.DB.CreateSession(); + session = TBF.DB.EventsDBSessionFactory.OpenSession(); Events.DB.LoadSubscribers(session); TBF.UiBridge.Bridge.TriggerEvent(session, Name, EventClass.ComputerResources, Severity.Error, @@ -313,6 +324,10 @@ namespace TBF.Rig.Output.DB.ProductionTracing { log.ErrorFormat("Triggering event(s) failed: {0}", exc.Message); } + finally + { + if (session != null && session.IsOpen) session.Close(); + } } return anyError ? Event.ErrorProcessingResults : Event.ResultsWritten; @@ -425,17 +440,8 @@ namespace TBF.Rig.Output.DB.ProductionTracing /// /// Get processId of the last record /// - int lastProcessId = 0; - DateTime lastTimeStamp = DateTime.MinValue; - foreach (var rcrd in records) - { - if (DateTime.Compare((DateTime)rcrd[3], lastTimeStamp) > 0) - { - lastTimeStamp = (DateTime)rcrd[3]; - lastProcessId = (int)rcrd[2]; - } - } - + int lastProcessId = (int)records[records.Count - 1][2]; + DateTime lastTimeStamp = (DateTime)records[records.Count - 1][3]; if (lastProcessId == 0) return Retv.Error; /// This should never happen @@ -482,7 +488,6 @@ namespace TBF.Rig.Output.DB.ProductionTracing /// This record fits verification requirements. /// As records are ordered by time, the result of the last one determines the verification result. wm.LastRecordIsNok = ((int)rcrd[4] != WorkstepRsltOK); - break; } } diff --git a/TBF/Rig/Output/DB/SaveDiverterCorrections/SaveDiverterCorr.cs b/TBF/Rig/Output/DB/SaveDiverterCorrections/SaveDiverterCorr.cs index 87df2028a..a90d88020 100644 --- a/TBF/Rig/Output/DB/SaveDiverterCorrections/SaveDiverterCorr.cs +++ b/TBF/Rig/Output/DB/SaveDiverterCorrections/SaveDiverterCorr.cs @@ -200,7 +200,7 @@ namespace TBF.Rig.Output.DB.SaveDiverterCorrections ITransaction transaction = null; try { - ISession session = TBF.DB.CreateSession(Common.DBKind.Config); + var session = TBF.DB.ConfigDBSessionFactory.OpenSession(); transaction = session.BeginTransaction(); for (int div = 1; div <= myCfg.DivertersCount(); div++) diff --git a/TBF/Rig/Output/DB/SaveFlowmeterCorrections/SaveFlowmeterCorr.cs b/TBF/Rig/Output/DB/SaveFlowmeterCorrections/SaveFlowmeterCorr.cs index b6d8b68f9..7d9657d41 100644 --- a/TBF/Rig/Output/DB/SaveFlowmeterCorrections/SaveFlowmeterCorr.cs +++ b/TBF/Rig/Output/DB/SaveFlowmeterCorrections/SaveFlowmeterCorr.cs @@ -207,7 +207,7 @@ namespace TBF.Rig.Output.DB.SaveFlowmeterCorrections ITransaction transaction = null; try { - ISession session = TBF.DB.CreateSession(Common.DBKind.Config); + var session = TBF.DB.ConfigDBSessionFactory.OpenSession(); transaction = session.BeginTransaction(); for (int fmtr = 1; fmtr <= myCfg.FlowmetersCount(); fmtr++) diff --git a/TBF/Rig/Output/DB/SensusOracle/Database.cs b/TBF/Rig/Output/DB/SensusOracle/Database.cs index d0481c8a8..b32505ed2 100644 --- a/TBF/Rig/Output/DB/SensusOracle/Database.cs +++ b/TBF/Rig/Output/DB/SensusOracle/Database.cs @@ -357,11 +357,12 @@ namespace TBF.Rig.Output.DB.SensusOracle opCompleted = true; } - if (anyError && !string.IsNullOrEmpty(Events.DB.ConnectionString)) + if (TBF.DB.EventsDBSessionFactory != null && anyError) { + NHibernate.ISession session = null; try { - NHibernate.ISession session = Events.DB.CreateSession(); + session = TBF.DB.EventsDBSessionFactory.OpenSession(); Events.DB.LoadSubscribers(session); TBF.UiBridge.Bridge.TriggerEvent(session, Name, EventClass.ComputerResources, Severity.Error, @@ -373,6 +374,10 @@ namespace TBF.Rig.Output.DB.SensusOracle { log.ErrorFormat("Triggering event(s) failed: {0}", exc.Message); } + finally + { + if (session != null && session.IsOpen) session.Close(); + } } return anyError ? Event.ErrorProcessingResults : Event.ResultsWritten; diff --git a/TBF/Rig/Output/EventTriggers/Standard/Trigger.cs b/TBF/Rig/Output/EventTriggers/Standard/Trigger.cs index a75d01957..d487724d5 100644 --- a/TBF/Rig/Output/EventTriggers/Standard/Trigger.cs +++ b/TBF/Rig/Output/EventTriggers/Standard/Trigger.cs @@ -142,9 +142,10 @@ namespace TBF.Rig.Output.EventTriggers.Standard return; } + ISession session = null; try { - ISession session = Events.DB.CreateSession(); + session = TBF.DB.EventsDBSessionFactory.OpenSession(); Events.DB.LoadSubscribers(session); /// @@ -226,15 +227,15 @@ namespace TBF.Rig.Output.EventTriggers.Standard long eFlags = batch.ErrorFlags(); long iFlags = batch.InfoFlags(); /// - if (triggerCfg.E1) OnExTriggerEvent(session, eFlags, iFlags, 1); - if (triggerCfg.E2) OnExTriggerEvent(session, eFlags, iFlags, 2); - if (triggerCfg.E3) OnExTriggerEvent(session, eFlags, iFlags, 3); - if (triggerCfg.E4) OnExTriggerEvent(session, eFlags, iFlags, 4); - if (triggerCfg.E5) OnExTriggerEvent(session, eFlags, iFlags, 5); - if (triggerCfg.E6) OnExTriggerEvent(session, eFlags, iFlags, 6); - if (triggerCfg.E7) OnExTriggerEvent(session, eFlags, iFlags, 7); - if (triggerCfg.E8) OnExTriggerEvent(session, eFlags, iFlags, 8); - if (triggerCfg.E9) OnExTriggerEvent(session, eFlags, iFlags, 9); + if (triggerCfg.E1) OnExTriggerEvent(session, eFlags, iFlags, 1); + if (triggerCfg.E2) OnExTriggerEvent(session, eFlags, iFlags, 2); + if (triggerCfg.E3) OnExTriggerEvent(session, eFlags, iFlags, 3); + if (triggerCfg.E4) OnExTriggerEvent(session, eFlags, iFlags, 4); + if (triggerCfg.E5) OnExTriggerEvent(session, eFlags, iFlags, 5); + if (triggerCfg.E6) OnExTriggerEvent(session, eFlags, iFlags, 6); + if (triggerCfg.E7) OnExTriggerEvent(session, eFlags, iFlags, 7); + if (triggerCfg.E8) OnExTriggerEvent(session, eFlags, iFlags, 8); + if (triggerCfg.E9) OnExTriggerEvent(session, eFlags, iFlags, 9); if (triggerCfg.E10) OnExTriggerEvent(session, eFlags, iFlags, 10); if (triggerCfg.E11) OnExTriggerEvent(session, eFlags, iFlags, 11); if (triggerCfg.E12) OnExTriggerEvent(session, eFlags, iFlags, 12); @@ -254,6 +255,10 @@ namespace TBF.Rig.Output.EventTriggers.Standard { log.ErrorFormat("Triggering event(s) failed: {0}", exc.Message); } + finally + { + if (session != null && session.IsOpen) session.Close(); + } } void OnExTriggerEvent(ISession session, long eFlags, long iFlags, int x) diff --git a/TBF/Rig/Output/FileWriters/IperlLogger/Writer.cs b/TBF/Rig/Output/FileWriters/IperlLogger/Writer.cs index 6733f61ed..1d5e5f400 100644 --- a/TBF/Rig/Output/FileWriters/IperlLogger/Writer.cs +++ b/TBF/Rig/Output/FileWriters/IperlLogger/Writer.cs @@ -162,11 +162,12 @@ namespace TBF.Rig.Output.FileWriters.IperlLogger opCompleted = true; } - if (anyError && !string.IsNullOrEmpty(Events.DB.ConnectionString)) + if (TBF.DB.EventsDBSessionFactory != null && anyError) { + NHibernate.ISession session = null; try { - NHibernate.ISession session = Events.DB.CreateSession(); + session = TBF.DB.EventsDBSessionFactory.OpenSession(); Events.DB.LoadSubscribers(session); TBF.UiBridge.Bridge.TriggerEvent(session, Name, EventClass.ComputerResources, Severity.Error, @@ -178,6 +179,10 @@ namespace TBF.Rig.Output.FileWriters.IperlLogger { log.ErrorFormat("Triggering event(s) failed: {0}", exc.Message); } + finally + { + if (session != null && session.IsOpen) session.Close(); + } } return anyError ? Event.ErrorProcessingResults: Event.ResultsWritten; diff --git a/TBF/Rig/Sequences/MainSeq.cs b/TBF/Rig/Sequences/MainSeq.cs index f497c3a71..abab0f805 100644 --- a/TBF/Rig/Sequences/MainSeq.cs +++ b/TBF/Rig/Sequences/MainSeq.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2013-2022 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -278,10 +278,7 @@ namespace TBF.Rig.Sequences try { - using (ISession localSession = TBF.DB.CreateSession(DBKind.Config)) - { - StateMachine.LoadPathsAndTransitions(localSession); - } + StateMachine.LoadPathsAndTransitions(); /// /// Try to load all parameters of selected or restored procedure from the respective database @@ -291,14 +288,13 @@ namespace TBF.Rig.Sequences /// User has chosen to restore an interrupted session and necessary conditions are met /// TODO: Repeate twice for DBKind.Config and DBKind.RemoteConfig - using (ISession remoteOrLocalSession = TBF.DB.CreateSession(isRemoteIntProc ? - DBKind.RemoteConfig : - DBKind.Config)) + using (var session = + (isRemoteIntProc ? TBF.DB.SharedDBSessionFactory : TBF.DB.ConfigDBSessionFactory).OpenSession()) { - StateMachine.LoadProcedure(remoteOrLocalSession, interruptedProcedureName, isRemoteIntProc); + StateMachine.LoadProcedure(session, interruptedProcedureName, isRemoteIntProc); StateMachine.LoadProcedureParams(StateMachine.Procedure); - /// This is to load Procedure.Tests and test.MoreParams for each test + /// This is to enforce the loading of Procedure.Tests and test.MoreParams for each test int a = 0; foreach (var test in StateMachine.Procedure.Tests) a += test.MoreParams.Count; } @@ -320,75 +316,31 @@ namespace TBF.Rig.Sequences } } - /// TODO: Repeate twice for DBKind.Config and DBKind.RemoteConfig - using (ISession remoteOrLocalSession = TBF.DB.CreateSession(Bridge.SelectedProcedure.IsRemote ? - DBKind.RemoteConfig : - DBKind.Config)) + /// TODO: Repeate twice for SharedDBSessionFactory and ConfigDBSessionFactory + using (var session = + (Bridge.SelectedProcedure.IsRemote ? TBF.DB.SharedDBSessionFactory : TBF.DB.ConfigDBSessionFactory).OpenSession()) { - StateMachine.LoadProcedure(remoteOrLocalSession, Bridge.SelectedProcedure.Name, Bridge.SelectedProcedure.IsRemote, testsInside); + StateMachine.LoadProcedure(session, Bridge.SelectedProcedure.Name, Bridge.SelectedProcedure.IsRemote, testsInside); StateMachine.LoadProcedureParams(StateMachine.Procedure); + log.WarnFormat("{0} procedure '{1}' selected", Bridge.SelectedProcedure.IsRemote ? "Remote" : "Local", Bridge.SelectedProcedure.Name); - /// This is to load Procedure.Tests and test.MoreParams for each test + /// This is to enforce the loading of Procedure.Tests and test.MoreParams for each test int a = 0; - foreach (var test in StateMachine.Procedure.Tests) a += test.MoreParams.Count; - -#if false - /// Debugging SensusTestInfo.GetBestMatch() - - if (selection == Selection.Cycle && OracleDB != null && OracleDB.ProductionDB != null) + foreach (var test in StateMachine.Procedure.Tests) { - try + a += test.MoreParams.Count; +#if ORACLE_DB + if (test.OraId != 0 || test.OraIdRepetMulti != 0 || test.RawDataId != 0 || test.RawDataIdRepetMulti != 0) { - OracleDB.ProductionDB.Open(); - - int wmTypeId = 170; - - /// Prepare procedure signature - IList wmTestNames = new List(); - StringBuilder procedureSignatureSB = new StringBuilder(); - foreach (var tr in BatchRslts.Batch.RegularTestRslts()) - { - if (tr.Evaluate()) - { - wmTestNames.Add(tr.Name()); - procedureSignatureSB.Append(tr.Name()); - procedureSignatureSB.Append("~"); - } - } - - int wmTypeRev = 0; - string wzTypStr; - string metroKlasse; - string zulasszeichen; - string materialNr; - double q3 = 0; - DateTime timeStamp; - string remark; - IList ti = OracleDB.GetOracleTestInfo(OracleDB.ProductionDB, wmTypeId, - out wmTypeRev, out wzTypStr, out metroKlasse, out zulasszeichen, out materialNr, out q3, out timeStamp, out remark); - - if (ti != null) - { - /// All 5 updated together - string procedureSignature = procedureSignatureSB.ToString(); - var completeTestInfo = Results.Output.SensusTestInfo.GetBestMatch(ti, wmTestNames); - - foreach (var cti in completeTestInfo) - { - log.WarnFormat("Selected test info : ID={0} Rev={1} Test={2} PrfNrDB={3} QBzDB={4} PrfNrOpto={5} QBzOpto={6} PrfNrLog={7} QBzLog={8} Range={9}", - wmTypeId, wmTypeRev, cti.TestName, cti.PruefungsNrDB, cti.QBezeichnungDB, cti.PruefungsNrOpto, - cti.QBezeichnungOpto, cti.PruefungsNrLog, cti.QBezeichnungLog, cti.Range); - } - } - - OracleDB.ProductionDB.Close(); + log.WarnFormat(" {0} OraId = {1}+{2}*(repNr-1) RawDataId = {3}+{4}*(repNr-1)", + test.Name, test.OraId, test.OraIdRepetMulti, test.RawDataId, test.RawDataIdRepetMulti); } - catch (Exception exc) + else +#endif { - string msg = exc.Message; + log.WarnFormat(" {0}", test.Name); } } -#endif } } else @@ -509,8 +461,10 @@ namespace TBF.Rig.Sequences b.EndTime = DateTime.MinValue; /// Disable the batch end time estimate Batch sampleBatch = null; - using (ISession rsltsDB = Results.DB.CreateSession()) + ISession rsltsDB = null; + try { + rsltsDB = TBF.DB.ResultsDBSessionFactory.OpenSession(); var bts = rsltsDB.QueryOver() .OrderBy(x => x.BatchNr).Desc .Where(x => x.ProcedureName == StateMachine.Procedure.Name) @@ -559,6 +513,14 @@ namespace TBF.Rig.Sequences } } } + catch (Exception exc) + { + log.ErrorFormat("Reloading result from DB failed: {0}", exc.Message); + } + finally + { + if (rsltsDB != null && rsltsDB.IsOpen) rsltsDB.Close(); + } } @@ -1578,7 +1540,9 @@ namespace TBF.Rig.Sequences return true; } - var loginDlg = new Users.Forms.PlainLoginDlg(new GID[] { GID.CalibrationSpecialists }, "Approval by legalizator"); + var loginDlg = new Users.Forms.PlainLoginDlg(TBF.DB.UserSessionFactories, + new GID[] { GID.CalibrationSpecialists }, + "Approval by legalizator"); if (loginDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { isApprovedByLegalizator = true; diff --git a/TBF/Rig/Sequences/SequenceBase.cs b/TBF/Rig/Sequences/SequenceBase.cs index 9cec6e405..a41cb33b1 100644 --- a/TBF/Rig/Sequences/SequenceBase.cs +++ b/TBF/Rig/Sequences/SequenceBase.cs @@ -1586,7 +1586,7 @@ namespace TBF.Rig.Sequences tstRslt.EndTime = DateTime.Now + new TimeSpan(0, 0, 1); tstRslt.FlowSetTime = 10; tstRslt.TestTime = tstRslt.TargetTime(); - if (outPath != null) + if (outPath != null && outPath.FlowMeter != null && outPath.Scale != null) { tstRslt.PulsesMaster = (outPath.FlowMeter.LtrPerPulse > 1E-6) ? (1.0075 * tstRslt.TargetVolume() / outPath.FlowMeter.LtrPerPulse) : 1; tstRslt.MassStartRaw = 0; diff --git a/TBF/Rig/StateMachine.cs b/TBF/Rig/StateMachine.cs index 517f7c06c..2bfeb2285 100644 --- a/TBF/Rig/StateMachine.cs +++ b/TBF/Rig/StateMachine.cs @@ -192,29 +192,28 @@ namespace TBF.Rig } /// - /// Start the state machine in the state 'label' in a desired mode of operation. - /// This method is called in the UI thread and creates a new state machine thread. - /// This method call should be embedded in: try { StateMachine.Start(...); } catch { } - /// to handle configuration problems. Calls CreateDevices(mode) and CreateStates(). + /// Load all components (entities) from the database. + /// Then create the components (derived from IComponent). + /// Do various things, fetch certain groups fo components. + /// Finally initialize COntrolBoard component. /// - /// Mode of operation - /// A copy of bench data used by the state machine - /// Identifies the initial state + /// Configuration database session + /// Control board Visual Basic component (ELDE) #if DN100 - public static void InitializeBoardEtc(ControlCom2VB.ControlCom2panel ctrlBrdComponent) + public static void InitializeBoardEtc(ISession session, ControlCom2VB.ControlCom2panel ctrlBrdComponent) #elif FUZHOU_150 || MUNICH - public static void InitializeBoardEtc(ControlComponent3Munich.UserControl1 ctrlBrdComponent) + public static void InitializeBoardEtc(ISession session, ControlComponent3Munich.UserControl1 ctrlBrdComponent) #elif FUZHOU_300 - public static void InitializeBoardEtc(ControlComponent3F300.UserControl1 ctrlBrdComponent) + public static void InitializeBoardEtc(ISession session, ControlComponent3F300.UserControl1 ctrlBrdComponent) #elif BERLIN || GELSENWASSER || GENESIS || IZRAEL_200 || PETERSBURG_200 || PUCHONG_200 || SLM_150 - public static void InitializeBoardEtc(ControlComponent_Izrael2014.UserControl1 ctrlBrdComponent) + public static void InitializeBoardEtc(ISession session, ControlComponent_Izrael2014.UserControl1 ctrlBrdComponent) #else /// all newer benches - public static void InitializeBoardEtc(ControlComponent_Torino2015.UserControl1 ctrlBrdComponent) + public static void InitializeBoardEtc(ISession session, ControlComponent_Torino2015.UserControl1 ctrlBrdComponent) #endif { /// Load the list of components (entities) from the database. /// Then create the components (derived from IComponent). - components = Rig.TbfComponents.LoadComponentsFromDB(TBF.DB.CreateSession(Common.DBKind.Config)); + components = Rig.TbfComponents.LoadComponentsFromDB(session); MasterValves = GenericDevices.ValveBase.MasterValves(components); CoupledValves = GenericDevices.ValveBase.CoupledValves(components); ExtendedValves = GenericDevices.ValveBase.ExtendedValves(components); @@ -424,33 +423,34 @@ namespace TBF.Rig /// Checks remote and local configuration DB paths and transitions for compatibility /// /// true when DB-s are compatible - public static bool IsRemoteDBCompatible(out string message) + public static bool IsRemoteDBCompatible(ISession localSession, out string message) { - IList remoteFeedingPaths; - IList remoteBenchPaths; - IList remoteOutputPaths; - IList remoteMetersPaths; - IList remoteTransitions; + IList remoteFeedingPaths = new List(); + IList remoteBenchPaths = new List(); + IList remoteOutputPaths = new List(); + IList remoteMetersPaths = new List(); + IList remoteTransitions = new List(); try { - ISession remoteSession = TBF.DB.CreateSession(Common.DBKind.RemoteConfig); + var remoteSession = TBF.DB.SharedDBSessionFactory.OpenSession(); + remoteFeedingPaths = remoteSession.QueryOver().List(); remoteBenchPaths = remoteSession.QueryOver().List(); remoteOutputPaths = remoteSession.QueryOver().List(); remoteMetersPaths = remoteSession.QueryOver().List(); remoteTransitions = remoteSession.QueryOver().List(); + + remoteSession.Close(); } catch (Exception exc) { - message = (exc.InnerException != null) ? string.Format("\r\nException:\r\n{0}\r\nInner exception:\r\n{1}", exc.Message, exc.InnerException.Message) : string.Format("\r\nException:\r\n{0}", exc.Message); return false; } - ISession localSession = TBF.DB.CreateSession(Common.DBKind.Config); var localFeedingPaths = localSession.QueryOver().List(); var localBenchPaths = localSession.QueryOver().List(); var localOutputPaths = localSession.QueryOver().List(); @@ -558,17 +558,36 @@ namespace TBF.Rig /// Loads all paths and transitions from the DB. /// Updates StatMachine.feedingPaths ... StatMachine.meterPaths, StatMachine.TransitionSequences /// - public static void LoadPathsAndTransitions(ISession session) + public static void LoadPathsAndTransitions(ISession session = null) { - feedingPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); - benchPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); - outputPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); - metersPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); - TransitionSequences = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); - TransitionSteps = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); + bool openAndCloseSession = (session == null); + try + { + if (openAndCloseSession) session = TBF.DB.ConfigDBSessionFactory.OpenSession(); + + feedingPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); + benchPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); + outputPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); + metersPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); + TransitionSequences = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); + TransitionSteps = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); #if HEAT_METERS - heatMetersPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); + heatMetersPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); #endif + } + catch (Exception e) + { + feedingPaths = new List(); + benchPaths = new List(); + outputPaths = new List(); + metersPaths = new List(); + TransitionSequences = new List(); + TransitionSteps = new List(); + } + finally + { + if (openAndCloseSession && (session != null) && session.IsOpen) session.Close(); + } } /// @@ -579,15 +598,16 @@ namespace TBF.Rig { Procedure = null; - IList selectedProcs = session.QueryOver() - .Where(x => (x.ProcedureState == Common.ProcedureState.Active)) - .And(x => (x.Name == procedureName)) - .List(); - if (selectedProcs.Count == 1) + var selectedProcedure = session.QueryOver() + .Where(x => (x.ProcedureState == Common.ProcedureState.Active)) + .And(x => (x.Name == procedureName)) + .List(); + + if (selectedProcedure.Count == 1) { IsRemoteProcedure = isRemote; - Procedure = selectedProcs[0]; - TestInstances = selectedProcs[0].UpdateTestInstances(LoopStartNames, LoopEndNames, autoTests); + Procedure = selectedProcedure[0]; + TestInstances = selectedProcedure[0].UpdateTestInstances(LoopStartNames, LoopEndNames, autoTests); return true; } else diff --git a/TBF/Rig/TbfComponents.cs b/TBF/Rig/TbfComponents.cs index fde12b39f..f6ed1a036 100644 --- a/TBF/Rig/TbfComponents.cs +++ b/TBF/Rig/TbfComponents.cs @@ -247,6 +247,8 @@ namespace TBF.Rig { CurrentlyLoadedComponentName = string.Empty; + if (session == null) return new List(); /// Handle case when session == null + /// Load the list of components from the database var cmptnEntities = session.QueryOver() .OrderBy(x => x.ItemNr).Asc @@ -263,6 +265,15 @@ namespace TBF.Rig IComponent cmpnt = cmpntFactory.GetComponent(cmpntFactory.CmpntCfgFromCmpntEntity(entity), components); + /// + /// Enforce loading Corrections and Uncertainties from the database + /// + double dummy = 0; + cmpnt.Corrections = entity.Corrections; + foreach (var corr in cmpnt.Corrections) dummy += corr.Correction; + cmpnt.Uncertainties = entity.Uncertainties; + foreach (var unc in cmpnt.Uncertainties) dummy += unc.MainUncertainty; + /// /// Inherit DebugMode from the parent (if any) /// diff --git a/TBF/Rig/TestMethods/Endurance/CycleDlg.cs b/TBF/Rig/TestMethods/Endurance/CycleDlg.cs index cae3283a9..fc096e8bd 100644 --- a/TBF/Rig/TestMethods/Endurance/CycleDlg.cs +++ b/TBF/Rig/TestMethods/Endurance/CycleDlg.cs @@ -64,19 +64,22 @@ namespace TBF.Rig.TestMethods.Endurance seqStepsCtrl = new CycleStepsCtrl() as ITabWithListViewEx; /// Prepare a list of valves for the endurance test - TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(TBF.DB.CreateSession(Common.DBKind.Config)); - Valves = new List(); - for (int bitNr = 0; bitNr < 8; bitNr++) - { - foreach (var vlv in TbfComponents) - { - if (vlv is Rig.Elde.Valve.Valve && (vlv as Rig.Elde.Valve.Valve).BitPosition == bitNr) - { - Valves.Add(vlv as IValve); - break; - } - } - } + using (var session = TBF.DB.ConfigDBSessionFactory.OpenSession()) + { + TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(session); + Valves = new List(); + for (int bitNr = 0; bitNr < 8; bitNr++) + { + foreach (var vlv in TbfComponents) + { + if (vlv is Rig.Elde.Valve.Valve && (vlv as Rig.Elde.Valve.Valve).BitPosition == bitNr) + { + Valves.Add(vlv as IValve); + break; + } + } + } + } EnduranceCycle = (cycle != null) ? cycle : new List(); /// TODO: Load from component parameters diff --git a/TBF/Rig/TestMethods/Q2CorrectionFromHistory/FromHistorySeq.cs b/TBF/Rig/TestMethods/Q2CorrectionFromHistory/FromHistorySeq.cs index 4aa049973..8f9714044 100644 --- a/TBF/Rig/TestMethods/Q2CorrectionFromHistory/FromHistorySeq.cs +++ b/TBF/Rig/TestMethods/Q2CorrectionFromHistory/FromHistorySeq.cs @@ -112,65 +112,65 @@ namespace TBF.Rig.TestMethods.Q2CorrectionFromHistory /// Invalidate any previous Q2 Pre-Corrections IsQ2PreCorrectionCalculated = false; + ISession session = null; try { - using (ISession session = Results.DB.CreateSession()) + session = TBF.DB.ResultsDBSessionFactory.OpenSession(); + + Batch btc = null; + var batches = session.QueryOver(() => btc) + .Where(bb => (bb.ProcedureName == cfg.ProcedureName)) + .List(); + + if (!string.IsNullOrEmpty(cfg.ProcedureNameAlt1)) { - Batch btc = null; - var batches = session.QueryOver(() => btc) - .Where(bb => (bb.ProcedureName == cfg.ProcedureName)) - .List(); + IList batches2 = session.QueryOver(() => btc) + .Where(bb => (bb.ProcedureName == cfg.ProcedureNameAlt1)) + .List(); + foreach (var b in batches2) batches.Add(b); + } + if (!string.IsNullOrEmpty(cfg.ProcedureNameAlt2)) + { + IList batches3 = session.QueryOver(() => btc) + .Where(bb => (bb.ProcedureName == cfg.ProcedureNameAlt2)) + .List(); + foreach (var b in batches3) batches.Add(b); + } - if (!string.IsNullOrEmpty(cfg.ProcedureNameAlt1)) - { - IList batches2 = session.QueryOver(() => btc) - .Where(bb => (bb.ProcedureName == cfg.ProcedureNameAlt1)) - .List(); - foreach (var b in batches2) batches.Add(b); - } - if (!string.IsNullOrEmpty(cfg.ProcedureNameAlt2)) - { - IList batches3 = session.QueryOver(() => btc) - .Where(bb => (bb.ProcedureName == cfg.ProcedureNameAlt2)) - .List(); - foreach (var b in batches3) batches.Add(b); - } + int samplesCount = 0; + double q2CorrLRsum = 0; + double q2CorrRLsum = 0; - int samplesCount = 0; - double q2CorrLRsum = 0; - double q2CorrRLsum = 0; - - var sortedBatches = batches.OrderByDescending(b => b.EndTime); - foreach (var b in sortedBatches) + var sortedBatches = batches.OrderByDescending(b => b.EndTime); + foreach (var b in sortedBatches) + { + foreach (var wm in b.WaterMeters) { - foreach (var wm in b.WaterMeters) + if ((wm != null) && !wm.Disabled && wm.Passed) { - if ((wm != null) && !wm.Disabled && wm.Passed) - { #if IPERL - q2CorrLRsum += wm.Q2CorrLR; - q2CorrRLsum += wm.Q2CorrRL; + q2CorrLRsum += wm.Q2CorrLR; + q2CorrRLsum += wm.Q2CorrRL; #endif - samplesCount++; - } + samplesCount++; } - - if (samplesCount >= 200) break; } - if (samplesCount >= 200) - { - IsQ2PreCorrectionCalculated = true; - CalculatedQ2PreCorrectionLR = (int)Math.Round(q2CorrLRsum / samplesCount); - CalculatedQ2PreCorrectionRL = (int)Math.Round(q2CorrRLsum / samplesCount); - log.WarnFormat("Q2 corrections calculated OK: LR = {0}, RL = {1}", CalculatedQ2PreCorrectionLR, CalculatedQ2PreCorrectionRL); - return true; - } - else - { - log.ErrorFormat("Not enough samples to calculate Q2 corrections ({0})", samplesCount); - return false; - } + if (samplesCount >= 200) break; + } + + if (samplesCount >= 200) + { + IsQ2PreCorrectionCalculated = true; + CalculatedQ2PreCorrectionLR = (int)Math.Round(q2CorrLRsum / samplesCount); + CalculatedQ2PreCorrectionRL = (int)Math.Round(q2CorrRLsum / samplesCount); + log.WarnFormat("Q2 corrections calculated OK: LR = {0}, RL = {1}", CalculatedQ2PreCorrectionLR, CalculatedQ2PreCorrectionRL); + return true; + } + else + { + log.ErrorFormat("Not enough samples to calculate Q2 corrections ({0})", samplesCount); + return false; } } catch (Exception exc) @@ -178,6 +178,10 @@ namespace TBF.Rig.TestMethods.Q2CorrectionFromHistory log.ErrorFormat("Failed to calculate Q2 corrections: {0}", exc.Message); return false; } + finally + { + if (session != null && session.IsOpen) session.Close(); + } } } } diff --git a/TBF/Rig/Various/StatisticsMonitoring/ProcessStatistics.cs b/TBF/Rig/Various/StatisticsMonitoring/ProcessStatistics.cs index 42b322460..6916db331 100644 --- a/TBF/Rig/Various/StatisticsMonitoring/ProcessStatistics.cs +++ b/TBF/Rig/Various/StatisticsMonitoring/ProcessStatistics.cs @@ -121,45 +121,52 @@ namespace TBF.Rig.Various.StatisticsMonitoring /// Take into account only batches where the 1st test in named 'RFID' and /// at least one water meter completed all tests. /// - try { - ISession session = Results.DB.CreateSession(); - - int usagesMin; - do + ISession session = null; + try { - usagesMin = 0; - IList batches = session.QueryOver() - .Where(x => x.BatchNr == batchNr) - .List(); - batchNr--; - if (batches.Count != 1 || batches[0].TestRslts.Count < 1 || batches[0].TestRslts[0].MethodClass != "TestMethods.iPerlCommunication") - { - continue; - } + session = TBF.DB.ResultsDBSessionFactory.OpenSession(); - bool isACompleteBatch = false; - foreach (var wm in batches[0].WaterMeters) + int usagesMin; + do { - int i = wm.WMPosition - 1; - if (0 <= i && i < TBF.Data.WMsCount && usages[i] < RequiredUsages && !wm.Disabled && wm.CompletedFromTests()) + usagesMin = 0; + IList batches = session.QueryOver() + .Where(x => x.BatchNr == batchNr) + .List(); + batchNr--; + if (batches.Count != 1 || batches[0].TestRslts.Count < 1 || batches[0].TestRslts[0].MethodClass != "TestMethods.iPerlCommunication") { - isACompleteBatch = true; - usages[i]++; - if (!wm.MeterTestRslts[0].Passed) failures[i]++; + continue; } + + bool isACompleteBatch = false; + foreach (var wm in batches[0].WaterMeters) + { + int i = wm.WMPosition - 1; + if (0 <= i && i < TBF.Data.WMsCount && usages[i] < RequiredUsages && !wm.Disabled && wm.CompletedFromTests()) + { + isACompleteBatch = true; + usages[i]++; + if (!wm.MeterTestRslts[0].Passed) failures[i]++; + } + } + + usagesMin = int.MaxValue; + for (int i = 0; i < TBF.Data.WMsCount; i++) if (usagesMin > usages[i]) usagesMin = usages[i]; + + if (isACompleteBatch) completeBatchesProcessed++; } - - usagesMin = int.MaxValue; - for (int i = 0; i < TBF.Data.WMsCount; i++) if (usagesMin > usages[i]) usagesMin = usages[i]; - - if (isACompleteBatch) completeBatchesProcessed++; + while ((usagesMin < RequiredUsages) && (batchNr > 0) && (completeBatchesProcessed < MaxBatches)); + } + catch (Exception exc) + { + log.ErrorFormat("Failed to calculate iPERL head usage statistics: {0}", exc.Message); + } + finally + { + if (session != null && session.IsOpen) session.Close(); } - while ((usagesMin < RequiredUsages) && (batchNr > 0) && (completeBatchesProcessed < MaxBatches)); - } - catch (Exception exc) - { - log.ErrorFormat("Failed to calculate iPERL head usage statistics: {0}", exc.Message); } /// @@ -175,14 +182,15 @@ namespace TBF.Rig.Various.StatisticsMonitoring } } - if (doTriggerEvents && !string.IsNullOrEmpty(Events.DB.ConnectionString)) + if (doTriggerEvents && TBF.DB.EventsDBSessionFactory != null) { /// /// Trigger events /// + ISession session = null; try { - ISession session = Events.DB.CreateSession(); + session = TBF.DB.EventsDBSessionFactory.OpenSession(); Events.DB.LoadSubscribers(session); for (int i = 0; i < TBF.Data.WMsCount; i++) @@ -203,6 +211,10 @@ namespace TBF.Rig.Various.StatisticsMonitoring { log.ErrorFormat("Failed to trigger events: source = {0}, message = {1}", statisticsCfg.EventSource, exc.Message); } + finally + { + if (session != null && session.IsOpen) session.Close(); + } } } } diff --git a/TBF/UI/Bench/Components/ComponentsManagerDlg.cs b/TBF/UI/Bench/Components/ComponentsManagerDlg.cs index f8a958d7e..95197e3c3 100644 --- a/TBF/UI/Bench/Components/ComponentsManagerDlg.cs +++ b/TBF/UI/Bench/Components/ComponentsManagerDlg.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2013-2021 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -24,12 +24,10 @@ namespace TBF.UI.Bench.Components /// /// List of components (=component configuration instances) /// + public ISession Session; IList cmpntEntities; - IList toBeDeletedEntities; - ISession session; - SelectComponentClassDlg selectComponentTypeDlg; /// Constructed once, the selection is kept between dialog usages CfgUpdateFlags flags; /// Or-ed from particular Flags from ComponentParametersDlg @@ -64,6 +62,14 @@ namespace TBF.UI.Bench.Components InitializeComponent(); + /// Open a database session + try { Session = TBF.DB.ConfigDBSessionFactory.OpenSession(); } + catch (Exception e) + { + MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message, + Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + } + flags = CfgUpdateFlags.None; selectComponentTypeDlg = new SelectComponentClassDlg(); @@ -121,11 +127,9 @@ namespace TBF.UI.Bench.Components sharedButtons.DisableButtons(SharedButtons.Buttons.Remove | SharedButtons.Buttons.Edit); - session = TBF.DB.CreateSession(Common.DBKind.Config); - cmpntEntities = session.QueryOver() + cmpntEntities = Session.QueryOver() .OrderBy(x => x.ItemNr).Asc .List(); - RedrawAll(); } @@ -372,7 +376,7 @@ namespace TBF.UI.Bench.Components { if ((flags & CfgUpdateFlags.AnyChange) != 0 || (flags & CfgUpdateFlags.RestartRqrd) != 0) { - SaveDBChanges(session); + SaveDBChanges(Session); flags = CfgUpdateFlags.None; /// Changes saved } @@ -696,11 +700,12 @@ namespace TBF.UI.Bench.Components MessageBoxIcon.Question); if (dr == DialogResult.Yes) { - SaveDBChanges(session); + SaveDBChanges(Session); } } if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); + if (Session != null && Session.IsOpen) Session.Close(); } diff --git a/TBF/UI/Bench/Metrology/MetrologyDlg.cs b/TBF/UI/Bench/Metrology/MetrologyDlg.cs index e0db4e2eb..5902d7526 100644 --- a/TBF/UI/Bench/Metrology/MetrologyDlg.cs +++ b/TBF/UI/Bench/Metrology/MetrologyDlg.cs @@ -18,14 +18,21 @@ namespace TBF.UI.Bench.Metrology { static readonly ILog log = LogManager.GetLogger(typeof(MetrologyDlg)); - public IList cmpntEntities; - - ISession session; + public ISession Session; + public IList cmpntEntities; public MetrologyDlg() { InitializeComponent(); + /// Open a database session + try { Session = TBF.DB.ConfigDBSessionFactory.OpenSession(); } + catch (Exception e) + { + MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message, + Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + } + /// SharedDlgButtons configuration sharedButtons.ParentForm = this; sharedButtons.RequiredGroupMembership = new GID[] { GID.Metrologists, @@ -55,11 +62,9 @@ namespace TBF.UI.Bench.Metrology int platinumTempMetersCount = 0; int evaporationsCount = 0; - session = TBF.DB.CreateSession(Common.DBKind.Config); - cmpntEntities = session.QueryOver() - .OrderBy(x => x. ItemNr).Asc - .List(); - + cmpntEntities = (Session == null) ? new List() : Session.QueryOver() + .OrderBy(x => x.ItemNr).Asc + .List(); foreach (var cmpnt in cmpntEntities) { Rig.Generic.IComponentFactory factory = TbfComponents.CmpntFactoryFromClassName(cmpnt.ClassName); @@ -229,7 +234,7 @@ namespace TBF.UI.Bench.Metrology metrologyTabControl.TabPages.Add(tabPage); } } - } + } private void unlockButton_Click(object sender, EventArgs e) { @@ -241,7 +246,7 @@ namespace TBF.UI.Bench.Metrology private void okButton_Click(object sender, EventArgs e) { - using (ITransaction transaction = session.BeginTransaction()) + using (ITransaction transaction = Session.BeginTransaction()) { try { @@ -251,12 +256,12 @@ namespace TBF.UI.Bench.Metrology if (tab != null) { tab.OkBtnClicked(); - tab.SaveEntityToDB(session); - foreach (var entity in tab.ToBeRemoved) session.Delete(entity); + tab.SaveEntityToDB(Session); + foreach (var entity in tab.ToBeRemoved) Session.Delete(entity); } } transaction.Commit(); - session.Flush(); + Session.Flush(); } catch (Exception exc) { @@ -350,6 +355,7 @@ namespace TBF.UI.Bench.Metrology private void MetrologyDlg_FormClosing(object sender, FormClosingEventArgs e) { if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); + if (Session != null && Session.IsOpen) Session.Close(); } } } diff --git a/TBF/UI/Bench/Paths/PathsDlg.cs b/TBF/UI/Bench/Paths/PathsDlg.cs index 53bb6c84d..764f0159d 100644 --- a/TBF/UI/Bench/Paths/PathsDlg.cs +++ b/TBF/UI/Bench/Paths/PathsDlg.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2013-2022 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -32,11 +32,11 @@ namespace TBF.UI.Bench.Paths /// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi public readonly int Dpi; - public IList TbfComponents; + public ISession Session; /// One common DB session passed also to the controls inside tab pages + public IList TbfComponents; public IList Valves; public IList FeedingRegValves; public IList OutputRegValves; - public ISession Session; /// One common DB session passed also to the controls inside tab pages public IList Procedures; public IList Tests; @@ -52,6 +52,14 @@ namespace TBF.UI.Bench.Paths InitializeComponent(); + /// Open a database session + try { Session = TBF.DB.ConfigDBSessionFactory.OpenSession(); } + catch (Exception e) + { + MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message, + Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + } + /// SharedDlgButtons configuration sharedButtons.ParentForm = this; sharedButtons.RequiredGroupMembership = new GID[] { GID.Metrologists }; @@ -66,15 +74,7 @@ namespace TBF.UI.Bench.Paths sharedButtons.DownClicked += downButton_Click; /// Load the list of components from the database - try - { - TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(TBF.DB.CreateSession(Common.DBKind.Config)); - } - catch - { - TbfComponents = new List(); - MessageBox.Show("Error occured when loading components"); - } + TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(Session); /// Find all master valves Valves = Rig.GenericDevices.ValveBase.MasterValves(TbfComponents); @@ -98,9 +98,6 @@ namespace TBF.UI.Bench.Paths } } - /// Create the database session for paths - Session = TBF.DB.CreateSession(DBKind.Config); - Procedures = Session.QueryOver().List(); Tests = Session.QueryOver().List(); @@ -371,6 +368,7 @@ namespace TBF.UI.Bench.Paths private void PathsDlg_FormClosing(object sender, FormClosingEventArgs e) { if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); + if (Session != null && Session.IsOpen) Session.Close(); } } } diff --git a/TBF/UI/Bench/TestProfiles/TestProfileDlg.cs b/TBF/UI/Bench/TestProfiles/TestProfileDlg.cs index 6bd966ee5..808ea7c3e 100644 --- a/TBF/UI/Bench/TestProfiles/TestProfileDlg.cs +++ b/TBF/UI/Bench/TestProfiles/TestProfileDlg.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2019-2022 Sensus Slovensko a.s. +/// Copyright (c) 2019-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -26,6 +26,7 @@ namespace TBF.UI.Bench.TestProfiles /// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi public readonly int Dpi; + readonly NHibernate.ISession session; readonly bool openUnlocked; /// @@ -52,26 +53,21 @@ namespace TBF.UI.Bench.TestProfiles openUnlocked = false; } - public TestProfileDlg(Profile profile, IList usedNames, bool openUnlocked, Form parentForm) + public TestProfileDlg(NHibernate.ISession session, Profile profile, IList usedNames, bool openUnlocked, Form parentForm) : this() { if (profile == null) throw new ArgumentNullException("profile"); + this.session = session; LoadedProfile = profile; this.usedNames = usedNames; this.openUnlocked = openUnlocked; - TestMethods = new List(); - using (NHibernate.ISession session = TBF.DB.CreateSession(DBKind.Config)) - { - /// Prepare a list of components and a list of test methods - TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(session); + /// Prepare a list of components and a list of test methods + TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(this.session); - if (TbfComponents != null) - foreach (var c in TbfComponents) - if (c is ITestMethod) - TestMethods.Add(c as ITestMethod); - } + TestMethods = new List(); + foreach (var c in TbfComponents) if (c is ITestMethod) TestMethods.Add(c as ITestMethod); /// SharedDlgButtons configuration sharedButtons.ParentForm = parentForm; diff --git a/TBF/UI/Bench/TestProfiles/TestProfileDlg.resx b/TBF/UI/Bench/TestProfiles/TestProfileDlg.resx index c8a4a70b2..250328f57 100644 --- a/TBF/UI/Bench/TestProfiles/TestProfileDlg.resx +++ b/TBF/UI/Bench/TestProfiles/TestProfileDlg.resx @@ -928,7 +928,7 @@ sharedButtons - TBF.UI.Shared.SharedButtons, TBF, Version=2.27.1917.0, Culture=neutral, PublicKeyToken=null + TBF.UI.Shared.SharedButtons, TBF, Version=2.32.2027.0, Culture=neutral, PublicKeyToken=null mainSplitContainer.Panel2 diff --git a/TBF/UI/Bench/TestProfiles/TestProfilesCtrl.cs b/TBF/UI/Bench/TestProfiles/TestProfilesCtrl.cs index 22692b032..90637d337 100644 --- a/TBF/UI/Bench/TestProfiles/TestProfilesCtrl.cs +++ b/TBF/UI/Bench/TestProfiles/TestProfilesCtrl.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2019-2022 Sensus Slovensko a.s. +/// Copyright (c) 2019-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -51,11 +51,11 @@ namespace TBF.UI.Bench.TestProfiles { if (Parent == null) return; - session = TBF.DB.CreateSession(Common.DBKind.Config); - this.parent = parent; this.parentControl = parentControl; + session = parent.Session; + SubItemClicked += new SubItemEventHandler(listViewEx_SubItemClicked); SubItemEndEditing += new SubItemEndEditingEventHandler(listViewEx_SubItemEndEditing); @@ -217,7 +217,7 @@ namespace TBF.UI.Bench.TestProfiles newProfile.CreationUser = Users.CurrentUser.UserName(); newProfile.CreationTime = DateTime.Now; - if (new TestProfileDlg(newProfile, GetUsedNames(false), true, parent).ShowDialog() == DialogResult.OK) + if (new TestProfileDlg(session, newProfile, GetUsedNames(false), true, parent).ShowDialog() == DialogResult.OK) { /// TODO: Make name uniqueness test parent.Unlock(); @@ -297,7 +297,7 @@ namespace TBF.UI.Bench.TestProfiles IList usedNames = GetUsedNames(false); usedNames.Remove(editedProfile.Name.ToLower()); /// Allow original procedure name /// - if (new TestProfileDlg(editedProfile, usedNames, false, parent).ShowDialog() == DialogResult.OK) + if (new TestProfileDlg(session, editedProfile, usedNames, false, parent).ShowDialog() == DialogResult.OK) { parent.Unlock(); @@ -342,7 +342,7 @@ namespace TBF.UI.Bench.TestProfiles newProfile.CreationUser = Users.CurrentUser.UserName(); newProfile.CreationTime = DateTime.Now; - if ((new TestProfileDlg(newProfile, GetUsedNames(false), true, parent)).ShowDialog() == DialogResult.OK) + if ((new TestProfileDlg(session, newProfile, GetUsedNames(false), true, parent)).ShowDialog() == DialogResult.OK) { /// TODO: Make name uniqueness test parent.Unlock(); @@ -391,7 +391,7 @@ namespace TBF.UI.Bench.TestProfiles newProfile.CreationUser = Users.CurrentUser.UserName(); newProfile.CreationTime = DateTime.Now; - if ((new TestProfileDlg(newProfile, GetUsedNames(false), true, parent)).ShowDialog() == DialogResult.OK) + if ((new TestProfileDlg(session, newProfile, GetUsedNames(false), true, parent)).ShowDialog() == DialogResult.OK) { /// TODO: Make name uniqueness test parent.Unlock(); diff --git a/TBF/UI/Bench/TestProfiles/TestProfilesDlg.cs b/TBF/UI/Bench/TestProfiles/TestProfilesDlg.cs index 69a93262d..8653e8f8a 100644 --- a/TBF/UI/Bench/TestProfiles/TestProfilesDlg.cs +++ b/TBF/UI/Bench/TestProfiles/TestProfilesDlg.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2019 Sensus Slovensko a.s. +/// Copyright (c) 2019-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -19,6 +19,8 @@ namespace TBF.UI.Bench.TestProfiles /// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi public readonly int Dpi; + public NHibernate.ISession Session; + public TestProfilesDlg() { /// Detect display setting: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi. @@ -26,6 +28,14 @@ namespace TBF.UI.Bench.TestProfiles InitializeComponent(); + /// Open a database session + try { Session = TBF.DB.ConfigDBSessionFactory.OpenSession(); } + catch (Exception e) + { + MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message, + Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + } + /// SharedDlgButtons configuration sharedButtons.ParentForm = this; sharedButtons.RequiredGroupMembership = new GID[] { GID.MetrologicalAuthority }; @@ -82,7 +92,7 @@ namespace TBF.UI.Bench.TestProfiles /// private void okButton_Click(object sender, EventArgs e) { - ProceduresDlg_FormClosed(sender, null); + TestProfilesDlg_FormClosed(sender, null); DialogResult = DialogResult.OK; Close(); @@ -93,7 +103,7 @@ namespace TBF.UI.Bench.TestProfiles /// /// /// - private void ProceduresDlg_FormClosed(object sender, FormClosedEventArgs e) + private void TestProfilesDlg_FormClosed(object sender, FormClosedEventArgs e) { testProfilesCtrl.OkBtnClicked(); SaveUISettings(); @@ -224,6 +234,7 @@ namespace TBF.UI.Bench.TestProfiles private void TestProfilesDlg_FormClosing(object sender, FormClosingEventArgs e) { if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); + if (Session != null && Session.IsOpen) Session.Close(); } } } diff --git a/TBF/UI/Bench/TestProfiles/TestProfilesDlg.designer.cs b/TBF/UI/Bench/TestProfiles/TestProfilesDlg.designer.cs index ad56aad2b..e56e1c26b 100644 --- a/TBF/UI/Bench/TestProfiles/TestProfilesDlg.designer.cs +++ b/TBF/UI/Bench/TestProfiles/TestProfilesDlg.designer.cs @@ -89,7 +89,7 @@ namespace TBF.UI.Bench.TestProfiles this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "TestProfilesDlg"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.TestProfilesDlg_FormClosing); - this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.ProceduresDlg_FormClosed); + this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.TestProfilesDlg_FormClosed); this.Load += new System.EventHandler(this.TestProfilesDlg_Load); this.splitContainer.Panel1.ResumeLayout(false); this.splitContainer.Panel2.ResumeLayout(false); diff --git a/TBF/UI/Bench/Transitions/TransitionsDlg.cs b/TBF/UI/Bench/Transitions/TransitionsDlg.cs index 5232d109c..e5d6641f7 100644 --- a/TBF/UI/Bench/Transitions/TransitionsDlg.cs +++ b/TBF/UI/Bench/Transitions/TransitionsDlg.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2013-2017 Sensus Metering Systems +/// Copyright (c) 2013-2023 Sensus Metering Systems /// using System; using System.Collections.Generic; @@ -66,6 +66,14 @@ namespace TBF.UI.Bench.Transitions InitializeComponent(); + /// Open a database session + try { Session = TBF.DB.ConfigDBSessionFactory.OpenSession(); } + catch (Exception e) + { + MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message, + Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + } + /// SharedDlgButtons configuration sharedButtons.ParentForm = this; sharedButtons.RequiredGroupMembership = new Common.GID[] { Common.GID.Metrologists }; @@ -90,9 +98,6 @@ namespace TBF.UI.Bench.Transitions seqStepsCtrls = new List(); - /// Open the database - Session = TBF.DB.CreateSession(Common.DBKind.Config); - /// Prepare a list of components and a list of all valves in the test bench TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(Session); Valves = Rig.GenericDevices.ValveBase.MasterValves(TbfComponents); @@ -107,10 +112,20 @@ namespace TBF.UI.Bench.Transitions /// Load the sequences /// Note: Each sequence (in both sequences together) has a unique ItemNr (0 .. N-1) - TransitionSequences = Session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); - VirtualBenchSequences = Session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); - procedures = Session.QueryOver().List(); - tests = Session.QueryOver().List(); + if (Session != null) + { + TransitionSequences = Session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); + VirtualBenchSequences = Session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); + procedures = Session.QueryOver().List(); + tests = Session.QueryOver().List(); + } + else + { + TransitionSequences = new List(); + VirtualBenchSequences = new List(); + procedures = new List(); + tests = new List(); + } RemovedTransitionSequences = new List(); RemovedVirtualBenchSequences = new List(); @@ -708,6 +723,7 @@ namespace TBF.UI.Bench.Transitions private void TransitionsDlg_FormClosing(object sender, FormClosingEventArgs e) { if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); + if (Session != null && Session.IsOpen) Session.Close(); } } } diff --git a/TBF/UI/Bench/Uncertainties/UncertaintiesDlg.cs b/TBF/UI/Bench/Uncertainties/UncertaintiesDlg.cs index 7e49e096c..bec9ac526 100644 --- a/TBF/UI/Bench/Uncertainties/UncertaintiesDlg.cs +++ b/TBF/UI/Bench/Uncertainties/UncertaintiesDlg.cs @@ -18,14 +18,21 @@ namespace TBF.UI.Bench.Uncertainties { static readonly ILog log = LogManager.GetLogger(typeof(UncertaintiesDlg)); + public ISession Session; public IList cmpntEntities; - ISession session; - public UncertaintiesDlg() { InitializeComponent(); + /// Open a database session + try { Session = TBF.DB.ConfigDBSessionFactory.OpenSession(); } + catch (Exception e) + { + MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message, + Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + } + /// SharedDlgButtons configuration sharedButtons.ParentForm = this; #if LANG_PL @@ -56,11 +63,9 @@ namespace TBF.UI.Bench.Uncertainties int tempMetersCount = 0; int evaporationsCount = 0; - session = TBF.DB.CreateSession(Common.DBKind.Config); - cmpntEntities = session.QueryOver() - .OrderBy(x => x. ItemNr).Asc - .List(); - + cmpntEntities = (Session == null) ? new List() : Session.QueryOver() + .OrderBy(x => x. ItemNr).Asc + .List(); foreach (var cmpnt in cmpntEntities) { Rig.Generic.IComponentFactory factory = TbfComponents.CmpntFactoryFromClassName(cmpnt.ClassName); @@ -202,7 +207,7 @@ namespace TBF.UI.Bench.Uncertainties private void okButton_Click(object sender, EventArgs e) { - using (ITransaction transaction = session.BeginTransaction()) + using (ITransaction transaction = Session.BeginTransaction()) { try { @@ -212,12 +217,12 @@ namespace TBF.UI.Bench.Uncertainties if (tab != null) { tab.OkBtnClicked(); - session.SaveOrUpdate(tab.MeterEntity); - foreach (var entity in tab.ToBeRemoved) session.Delete(entity); + Session.SaveOrUpdate(tab.MeterEntity); + foreach (var entity in tab.ToBeRemoved) Session.Delete(entity); } } transaction.Commit(); - session.Flush(); + Session.Flush(); } catch (Exception exc) { @@ -311,6 +316,7 @@ namespace TBF.UI.Bench.Uncertainties private void UncertaintiesDlg_FormClosing(object sender, FormClosingEventArgs e) { if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); + if (Session != null && Session.IsOpen) Session.Close(); } } } diff --git a/TBF/UI/Calendar/CalendarTabPageCtrl.cs b/TBF/UI/Calendar/CalendarTabPageCtrl.cs index 984b08678..5b38931c1 100644 --- a/TBF/UI/Calendar/CalendarTabPageCtrl.cs +++ b/TBF/UI/Calendar/CalendarTabPageCtrl.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2020 Sensus Slovensko a.s. +/// Copyright (c) 2020-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -9,9 +9,7 @@ using NHibernate; using Common; using Config.Entities; using Config.CalendarEvent; -using Events.Entities; using TBF.Resources; -using TBF.UiBridge; namespace TBF.UI.Calendar { @@ -19,16 +17,15 @@ namespace TBF.UI.Calendar { static readonly ILog log = LogManager.GetLogger(typeof(CalendarTabPageCtrl)); - IList eventsFromComponents; - IList customEvents; /// Custom events loaded from the local config DB + public IList EventsFromComponents; Timer timer; - DateTime lastTimeCalendarEventsServed; + DateTime LastTimeCalendarEventsServed; public CalendarTabPageCtrl() { InitializeComponent(); - eventsFromComponents = new List(); + EventsFromComponents = new List(); Localize(); } @@ -61,15 +58,22 @@ namespace TBF.UI.Calendar calendarEventsListViewEx.Items.Add(lvi); } - public void StartCalendar(IList eventsFromComponents) + /// + /// Initializes 'public IList<...> EventsFromComponents. + /// + /// + /// + /// + public void StartCalendar(IList eventsFromComponents, ISession session = null) { - this.eventsFromComponents = eventsFromComponents; + this.EventsFromComponents = eventsFromComponents; + bool openAndCloseSession = (session == null); try { /// Read custom events from the database - ISession session = TBF.DB.CreateSession(Common.DBKind.Config); - customEvents = session.QueryOver().List(); + if (openAndCloseSession) session = TBF.DB.ConfigDBSessionFactory.OpenSession(); + var customEvents = session.QueryOver().List(); TripplicateShiftCustomEvents(customEvents); @@ -83,14 +87,16 @@ namespace TBF.UI.Calendar foreach (var e in eventsFromComponents) if (!e.Hidden) AddOne(e); /// Serve events (determine if any event was triggered) - lastTimeCalendarEventsServed = DateTime.Now; - ServeCalendarEventsNotifWarnErrorFatal(lastTimeCalendarEventsServed, session, customEvents); + ServeCalendarEventsNotifWarnErrorFatal(DateTime.Now, session, customEvents); } catch (Exception) { - customEvents = new List(); log.ErrorFormat("Failed to load custom events from the LOCAL config database"); } + finally + { + if (openAndCloseSession && session != null && session.IsOpen) session.Close(); + } calendarCtrl1.CalendarView = CalendarViews.Month; @@ -107,34 +113,34 @@ namespace TBF.UI.Calendar /// void timer_Tick(object sender, EventArgs args) { - DateTime currentTime = DateTime.Now; + DateTime dateTimeNow = DateTime.Now; - if ((currentTime.Hour != lastTimeCalendarEventsServed.Hour) || - (currentTime.Minute % 30) != (lastTimeCalendarEventsServed.Minute % 30)) + if ((dateTimeNow.Hour != LastTimeCalendarEventsServed.Hour) || + (dateTimeNow.Minute % 30) != (LastTimeCalendarEventsServed.Minute % 30)) { /// Serve events at the beginning of each half hour - ServeCalendarEventsNotifWarnErrorFatal(currentTime); - lastTimeCalendarEventsServed = currentTime; + ServeCalendarEventsNotifWarnErrorFatal(dateTimeNow); } } - /// /// Triggers events corresponding to triggered motification.warning/error calendar events. /// - /// Current time - void ServeCalendarEventsNotifWarnErrorFatal(DateTime currentTime, ISession parentSession = null, IList customEventsFromDB = null) + /// Current time + void ServeCalendarEventsNotifWarnErrorFatal(DateTime dateTimeNow, ISession session = null, IList customEventsFromDB = null) { - IList eventsToTrigger = new List(); + LastTimeCalendarEventsServed = dateTimeNow; - for (int i = eventsFromComponents.Count - 1; i >= 0; i--) + var eventsToTrigger = new List(); + + for (int i = EventsFromComponents.Count - 1; i >= 0; i--) { - ICalendarEvent calEvent = eventsFromComponents[i]; + ICalendarEvent calEvent = EventsFromComponents[i]; AutoAction a = calEvent.AutoAction; if (a == AutoAction.Notification || a == AutoAction.Warning || a == AutoAction.Error || a == AutoAction.FatalErr) { - if (Config.CalendarEvent.Utils.IsCalendarEventTrigerred(calEvent, currentTime)) + if (Config.CalendarEvent.Utils.IsCalendarEventTrigerred(calEvent, dateTimeNow)) { eventsToTrigger.Add(new Events.Entities.Event(null, calEvent.Source, @@ -148,20 +154,23 @@ namespace TBF.UI.Calendar if (calEvent.Frequency == Frequency.Once) { - eventsFromComponents.Remove(calEvent); + EventsFromComponents.Remove(calEvent); } else { - Config.CalendarEvent.Utils.UpdateRecurringDate(calEvent, currentTime); + Config.CalendarEvent.Utils.UpdateRecurringDate(calEvent, dateTimeNow); } } } } + bool openAndCloseSession = (session == null); + /// try { - var session = (parentSession != null) ? parentSession : TBF.DB.CreateSession(Common.DBKind.Config); - var customEvents = (customEventsFromDB != null) ? customEventsFromDB : session.QueryOver() .List(); + if (openAndCloseSession) session = TBF.DB.ConfigDBSessionFactory.OpenSession(); + + var customEvents = (customEventsFromDB != null) ? customEventsFromDB : session.QueryOver().List(); for (int i = customEvents.Count - 1; i >= 0; i--) { @@ -170,7 +179,7 @@ namespace TBF.UI.Calendar AutoAction a = calEvent.AutoAction; if (a == AutoAction.Notification || a == AutoAction.Warning || a == AutoAction.Error || a == AutoAction.FatalErr) { - if (Config.CalendarEvent.Utils.IsCalendarEventTrigerred(calEvent, currentTime)) + if (Config.CalendarEvent.Utils.IsCalendarEventTrigerred(calEvent, dateTimeNow)) { eventsToTrigger.Add(new Events.Entities.Event(null, calEvent.Source, @@ -186,7 +195,7 @@ namespace TBF.UI.Calendar { session.Delete(calEvent); } - else if (calEvent.UpdateRecurringDate(currentTime)) + else if (calEvent.UpdateRecurringDate(dateTimeNow)) { session.SaveOrUpdate(calEvent); } @@ -199,27 +208,26 @@ namespace TBF.UI.Calendar { log.ErrorFormat("Failed to load or update CustomEvent-s in ServeTriggerEvtCalendarEvents(): {0}", exc.Message); } - - if (eventsToTrigger.Count > 0 && !string.IsNullOrEmpty(global::Events.DB.ConnectionString)) + finally { - try + if (openAndCloseSession && session != null && session.IsOpen) session.Close(); + } + + if (eventsToTrigger.Count > 0 && TBF.DB.EventsDBSessionFactory != null) + { + using (ISession evtDBSession = TBF.DB.EventsDBSessionFactory.OpenSession()) { - ISession session = global::Events.DB.CreateSession(); - global::Events.DB.LoadSubscribers(session); + global::Events.DB.LoadSubscribers(evtDBSession); foreach (var e in eventsToTrigger) { - TBF.UiBridge.Bridge.TriggerEvent(session, e); + TBF.UiBridge.Bridge.TriggerEvent(evtDBSession, e); } - session.Flush(); - } - catch (Exception exc) - { - log.ErrorFormat("Failed to trigger events in ServeTriggerEvtCalendarEvents(): {0}", exc.Message); + evtDBSession.Flush(); + evtDBSession.Close(); } } } - /// /// Returns an array of parameters of selected actions. /// This function is not invoked from UI thread. @@ -234,9 +242,10 @@ namespace TBF.UI.Calendar if (maxCount <= 0) return parametersList; + ISession session = null; try { - ISession session = TBF.DB.CreateSession(Common.DBKind.Config); + session = TBF.DB.ConfigDBSessionFactory.OpenSession(); var customEventsFromDB = session.QueryOver().List(); for (int i = customEventsFromDB.Count - 1; i >= 0; i--) @@ -264,6 +273,10 @@ namespace TBF.UI.Calendar { log.ErrorFormat("Failed to load or update CustomEvent-s in ServeSelectedCalendarEvents(): {0}", exc.Message); } + finally + { + if (session != null && session.IsOpen) session.Close(); + } if (parametersList.Count > 0) { @@ -273,7 +286,6 @@ namespace TBF.UI.Calendar return parametersList; } - /// /// Convert calendar event AutoAction to event Severity /// @@ -291,7 +303,6 @@ namespace TBF.UI.Calendar } } - void TripplicateShiftCustomEvents(IList customEvents) { /// Tripplicate each custom event with frequency 'EveryShift' @@ -314,39 +325,42 @@ namespace TBF.UI.Calendar } } - private void newEventButton_Click(object sender, EventArgs ea) { EventDetailsForm dlg = new EventDetailsForm(); if (dlg.ShowDialog() == DialogResult.OK && dlg.NewEvent is CustomEvent) { + ISession session = null; try { - ISession session = TBF.DB.CreateSession(Common.DBKind.Config); + session = TBF.DB.ConfigDBSessionFactory.OpenSession(); session.SaveOrUpdate(dlg.NewEvent as CustomEvent); session.Flush(); - customEvents = session.QueryOver().List(); + var customEvents = session.QueryOver().List(); TripplicateShiftCustomEvents(customEvents); /// Calendar calendarCtrl1.ClearEvents(); - foreach (var e in eventsFromComponents) calendarCtrl1.AddEvent(e); + foreach (var e in EventsFromComponents) calendarCtrl1.AddEvent(e); foreach (var e in customEvents) calendarCtrl1.AddEvent(e); /// List view in the right pane calendarEventsListViewEx.Items.Clear(); foreach (var e in customEvents) AddOne(e); - foreach (var e in eventsFromComponents) if (!e.Hidden) AddOne(e); + foreach (var e in EventsFromComponents) if (!e.Hidden) AddOne(e); } catch (Exception) { - log.ErrorFormat("Failed to save new calendar event to the local config database"); + MessageBox.Show("Cannot save the change to the database", Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + } + finally + { + if (session != null && session.IsOpen) session.Close(); } } } - private void calendarEventsListViewEx_MouseDoubleClick(object sender, MouseEventArgs mea) { if (calendarEventsListViewEx.SelectedIndices.Count != 1) return; @@ -355,10 +369,11 @@ namespace TBF.UI.Calendar EventDetailsForm dlg = new EventDetailsForm { Event = evnt }; if (dlg.ShowDialog() != DialogResult.OK) return; + ISession session = null; try { /// Re-read selected custom event from the database - ISession session = TBF.DB.CreateSession(Common.DBKind.Config); + session = TBF.DB.ConfigDBSessionFactory.OpenSession(); var cEvents = session.QueryOver() .Where(x => (x.Id == evnt.Id)) .List(); @@ -383,23 +398,27 @@ namespace TBF.UI.Calendar session.SaveOrUpdate(cEvents[0]); session.Flush(); - customEvents = session.QueryOver().List(); + var customEvents = session.QueryOver().List(); TripplicateShiftCustomEvents(customEvents); /// Calendar calendarCtrl1.ClearEvents(); - foreach (var e in eventsFromComponents) calendarCtrl1.AddEvent(e); + foreach (var e in EventsFromComponents) calendarCtrl1.AddEvent(e); foreach (var e in customEvents) calendarCtrl1.AddEvent(e); /// List view in the right pane calendarEventsListViewEx.Items.Clear(); foreach (var e in customEvents) AddOne(e); - foreach (var e in eventsFromComponents) if (!e.Hidden) AddOne(e); + foreach (var e in EventsFromComponents) if (!e.Hidden) AddOne(e); } } catch (Exception) { - MessageBox.Show("Cannot save change to the database", Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + MessageBox.Show("Cannot save the change to the database", Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + } + finally + { + if (session != null && session.IsOpen) session.Close(); } } } diff --git a/TBF/UI/Calendar/CalibrationDueDateEvent.cs b/TBF/UI/Calendar/CalibrationDueDateEvent.cs index c19d8fc9b..931ed8be1 100644 --- a/TBF/UI/Calendar/CalibrationDueDateEvent.cs +++ b/TBF/UI/Calendar/CalibrationDueDateEvent.cs @@ -11,14 +11,14 @@ namespace TBF.UI.Calendar { public DateTime Date { get; set; } /// The Date that the event occurs public Frequency Frequency { get; set; } /// A value indicating how often the event occurs - public bool AllDay { get; set; } /// True if the time component of the date can be ignored + public bool AllDay { get; set; } /// True if the time component of the date can be ignored public bool TriggerOnExactDayOnly { get; set; } /// If this is a recurring event, set this to true to make the event show up only from the day specified forward public string Source { get; set; } /// Source of this calendar event (becomes the source of the triggered event) - public string Title { get; set; } /// The name of the event (becomes the text of the triggered event) + public string Title { get; set; } /// The name of the event (becomes the text of the triggered event) public AutoAction AutoAction { get; set; } /// Automated action to be done or event to be triggered (becomes Severity) public string Parameters { get; set; } /// Automated action parameters (e.g. name of a procedure to start) public int Rank { get; set; } /// The ranking of the event that determines the order in which it is displayed on a particular day - public bool Hidden { get; set; } /// True if the event is enabled, otherwise false + public bool Hidden { get; set; } /// True if the event is enabled, otherwise false public bool ReadOnly { get; set; } /// True if the event details cannot be modified public int BackColor { get; set; } /// The color that the event show up in on the calendar: (MSB)AARRGGBB(LSB) public int TextColor { get; set; } /// The text color of the event: (MSB)AARRGGBB(LSB) diff --git a/TBF/UI/Calendar/CalibrationReminderEvent.cs b/TBF/UI/Calendar/CalibrationReminderEvent.cs index f7b183743..6b0757d48 100644 --- a/TBF/UI/Calendar/CalibrationReminderEvent.cs +++ b/TBF/UI/Calendar/CalibrationReminderEvent.cs @@ -26,29 +26,32 @@ namespace TBF.UI.Calendar public Config.CalendarEvent.CustomRecurringFrequenciesHandler CustomRecurringFunction { get; set; } + + private CalibrationReminderEvent() { } + /// /// CalibrationReminderEvent Constructor /// - public CalibrationReminderEvent(bool daily = false) + public CalibrationReminderEvent(AutoAction autoAction) { /// Date - Frequency = daily ? Frequency.Daily : Frequency.Weekly; + Frequency = Frequency.Once; AllDay = true; TriggerOnExactDayOnly = false; /// Source /// Text - AutoAction = daily ? AutoAction.Warning : AutoAction.Notification; + AutoAction = autoAction; Parameters = string.Empty; Rank = 1; Hidden = true; ReadOnly = true; - BackColor = unchecked((int)0xFFA00000); - TextColor = unchecked((int)0xFFFFFFFF); + BackColor = unchecked((int)0xFFA00000); /// (MSB)AARRGGBB(LSB) ... red + TextColor = unchecked((int)0xFFFFFFFF); /// (MSB)AARRGGBB(LSB) ... white TooltipEnabled = true; } - public CalibrationReminderEvent(DateTime date, string source, string text, bool daily = false) - : this(daily) + public CalibrationReminderEvent(AutoAction autoAction, DateTime date, string source, string text) + : this(autoAction) { Date = date; Source = source; diff --git a/TBF/UI/MainWnd.cs b/TBF/UI/MainWnd.cs index f56100464..19e229fff 100644 --- a/TBF/UI/MainWnd.cs +++ b/TBF/UI/MainWnd.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2013-2021 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -13,6 +13,7 @@ using Config.Entities; using TBF.Resources; using TBF.UiBridge; using TBF.UI.Shared; +using NHibernate; namespace TBF.UI { @@ -24,7 +25,7 @@ namespace TBF.UI static readonly ILog log = LogManager.GetLogger(typeof(MainWnd)); const string ProcSeparator = " "; /// string separating procedure number and procedure name - + public static IDictionary ProcedureNrs = new Dictionary(); /// Used in PreviousResultsDlg public BenchControlPanel BenchControlPanel; @@ -33,6 +34,11 @@ namespace TBF.UI public bool IsShutdownDisabled; public bool IsShutdownPCAfterClosingTbf; + /// + /// This local configuration DB session is opened in the constructor and closed at the end of MainWnd_Load( ) + /// + ISession startupSession; + /// /// This dialog is shown when emergency stop is activated /// @@ -134,15 +140,17 @@ namespace TBF.UI { try { + startupSession = TBF.DB.ConfigDBSessionFactory.OpenSession(); + /// Load components, initialize the control board, etc. - Rig.StateMachine.InitializeBoardEtc(ctrlBrdComponent); + Rig.StateMachine.InitializeBoardEtc(startupSession, ctrlBrdComponent); /// Check remote and local configuration DB compatibility string msg; Rig.GenericDevices.IBenchInfo benchInfo = Rig.Sequences.ProcessData.BenchInfo; RemoteDBUse remoteDbUse = (benchInfo != null) ? benchInfo.RemoteDBUse : RemoteDBUse.LocalDBOnly; log.FatalFormat("RemoteDbUse = {0}", remoteDbUse); - if ((remoteDbUse != RemoteDBUse.LocalDBOnly) && !Rig.StateMachine.IsRemoteDBCompatible(out msg)) + if ((remoteDbUse != RemoteDBUse.LocalDBOnly) && !Rig.StateMachine.IsRemoteDBCompatible(startupSession, out msg)) { log.FatalFormat("{0} {1}", Strings.Remote_db_is_not_compatible, msg); throw new Exception(string.Format("{0}{1}{2}", Strings.Remote_db_is_not_compatible, Environment.NewLine, msg)); @@ -281,10 +289,11 @@ namespace TBF.UI form.CloseForm(null, new EventArgs()); formThread.Join(); + string innerExcMsg = (exc.InnerException != null) ? Environment.NewLine + exc.InnerException.Message : string.Empty; string errMsg = string.Format(Strings.Failed_to_initialize_device_0_1_2, Rig.StateMachine.CurrentlyInitializedComponentName, - Environment.NewLine, - exc.Message); + Environment.NewLine + exc.Message, + innerExcMsg); log.Fatal(errMsg); MessageBox.Show(errMsg, Strings.Error, System.Windows.Forms.MessageBoxButtons.OK, @@ -320,16 +329,18 @@ namespace TBF.UI /// /// Populate calendar with calendar events from components /// - IList calendarEvents = new List(); + var calEvents = new List(); foreach (var cmpnt in TBF.Rig.StateMachine.Components) { - TBF.Rig.GenericDevices.IHasCalendarEvents cmpntWithCalEvents = cmpnt as TBF.Rig.GenericDevices.IHasCalendarEvents; - if (cmpntWithCalEvents != null) + var cmpntWithEvents = cmpnt as TBF.Rig.GenericDevices.IHasCalendarEvents; + if (cmpntWithEvents != null) { - foreach (var evnt in cmpntWithCalEvents.GetCalendarEvents()) calendarEvents.Add(evnt); + foreach (var evnt in cmpntWithEvents.GetCalendarEvents()) calEvents.Add(evnt); } } - calendarTabPageCtrl.StartCalendar(calendarEvents); + calendarTabPageCtrl.StartCalendar(calEvents, startupSession); + + if (startupSession != null && startupSession.IsOpen) startupSession.Close(); Rig.StateMachine.Start(); log.Info("Test bench started"); @@ -539,18 +550,24 @@ namespace TBF.UI { Users.DB.ConnectionString = TBF.DB.CurrentBench.ProceduresDBSettings.ConnectionString; Users.DB.DbType = TBF.DB.CurrentBench.ProceduresDBSettings.DbType; + using (ISession session = Users.DB.CreateSession()) + { #if TURA_IPERL || TURA_IPERL_NEW || TURA_SPECIAL - Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(Users.DB.CreateSession(), true); - string connStr = Users.DB.ConnectionString; - int len = connStr.ToUpper().IndexOf("; UID="); - if (len == -1) len = connStr.ToUpper().IndexOf("; USER="); - if (len > 0) dlg.TitleExtension = connStr.Substring(0, len); + Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(session, true); + string connStr = Users.DB.ConnectionString; + int len = connStr.ToUpper().IndexOf("; UID="); + if (len == -1) len = connStr.ToUpper().IndexOf("; USER="); + if (len > 0) dlg.TitleExtension = connStr.Substring(0, len); #else - Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(Users.DB.CreateSession(), false); + Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(session, false); #endif - dlg.ShowDialog(); + dlg.ShowDialog(); + session.Close(); + } } + private void languageTSMItem_Click(object s, EventArgs e) { new TBF.UI.Settings.LanguageDlg().ShowDialog(); } + private void databaseSettingsTSMItem_Click(object s, EventArgs e) { TBF.UI.Settings.BenchesDlg dlg = new TBF.UI.Settings.BenchesDlg(); @@ -570,9 +587,15 @@ namespace TBF.UI } } } + private void backUpConfigTSMItem_Click(object s, EventArgs e) { BackupConfiguration(); } private void backUpResultsTSMItem_Click(object s, EventArgs e) { BackupResults(); } - private void passwdTSMItem_Click(object s, EventArgs e) { new Users.Forms.PasswordChangeDlg(Users.CurrentUser.UserName()).ShowDialog(); } + + private void passwdTSMItem_Click(object s, EventArgs e) + { + new Users.Forms.PasswordChangeDlg(TBF.DB.UserSessionFactories, Users.CurrentUser.UserName()).ShowDialog(); + } + private void aboutTSMItem_Click(object s, EventArgs e) { new TBF.UI.Help.AboutDlg().ShowDialog(); } @@ -593,26 +616,26 @@ namespace TBF.UI Rig.GenericDevices.IBenchInfo benchInfo = Rig.Sequences.ProcessData.BenchInfo; RemoteDBUse remoteDbUse = (benchInfo != null) ? benchInfo.RemoteDBUse : RemoteDBUse.LocalDBOnly; - Common.DBKind[] dBase; + ISessionFactory[] dBase; string[] signature; /// switch (remoteDbUse) { default: case RemoteDBUse.LocalDBOnly: - dBase = new Common.DBKind[] { Common.DBKind.Config }; + dBase = new ISessionFactory[] { TBF.DB.ConfigDBSessionFactory }; signature = new string[] { "" }; break; case RemoteDBUse.RemoteDBOnly: - dBase = new Common.DBKind[] { Common.DBKind.RemoteConfig }; + dBase = new ISessionFactory[] { TBF.DB.SharedDBSessionFactory }; signature = new string[] { "R" }; break; case RemoteDBUse.BothDBsLocalFirst: - dBase = new Common.DBKind[] { Common.DBKind.Config, Common.DBKind.RemoteConfig }; + dBase = new ISessionFactory[] { TBF.DB.ConfigDBSessionFactory, TBF.DB.SharedDBSessionFactory }; signature = new string[] { "L", "R" }; break; case RemoteDBUse.BothDBsRemoteFirst: - dBase = new Common.DBKind[] { Common.DBKind.RemoteConfig, Common.DBKind.Config }; + dBase = new ISessionFactory[] { TBF.DB.SharedDBSessionFactory, TBF.DB.ConfigDBSessionFactory }; signature = new string[] { "R", "L" }; break; } @@ -625,23 +648,30 @@ namespace TBF.UI ProcedureNrs.Clear(); for (int i = 0; i < dBase.Length; i++) { - IList procedures = TBF.DB.CreateSession(dBase[i]) - .QueryOver() - .Where(x => (x.ProcedureState == ProcedureState.Active)) - .OrderBy(x => x.ItemNr).Asc - .List(); - foreach (var proc in procedures) + if (dBase[i] != null) { - string itemText = string.Format("{0}{1}{2}{3}", signature[i], proc.ItemNr + 1, ProcSeparator, proc.Name); - procedureComboBox.Items.Add(itemText); - if (!ProcedureNrs.ContainsKey(proc.Name)) ProcedureNrs.Add(proc.Name, proc.ItemNr + 1); + var session = dBase[i].OpenSession(); + var procedures = session.QueryOver() + .Where(x => (x.ProcedureState == ProcedureState.Active)) + .OrderBy(x => x.ItemNr).Asc + .List(); - if ((procedureNameToSelect == proc.Name) && !procedureSet) + foreach (var proc in procedures) { - procedureComboBox.Text = itemText; - SelectedProcedure = new ProcedureInfo(procedureNameToSelect, (dBase[i] == Common.DBKind.RemoteConfig)); - procedureSet = true; + string itemText = string.Format("{0}{1}{2}{3}", signature[i], proc.ItemNr + 1, ProcSeparator, proc.Name); + procedureComboBox.Items.Add(itemText); + if (!ProcedureNrs.ContainsKey(proc.Name)) ProcedureNrs.Add(proc.Name, proc.ItemNr + 1); + + if ((procedureNameToSelect == proc.Name) && !procedureSet) + { + procedureComboBox.Text = itemText; + SelectedProcedure = new ProcedureInfo(procedureNameToSelect, (dBase[i] == TBF.DB.SharedDBSessionFactory)); + BenchControlPanel.ReloadTests(session); + procedureSet = true; + } } + + session.Close(); } } @@ -652,8 +682,6 @@ namespace TBF.UI } ProceduresUpdated = false; - - if (SelectedProcedure != null) BenchControlPanel.ReloadTests(); } else { @@ -861,7 +889,7 @@ namespace TBF.UI Common.GID[] reqGrpMembership = null; #endif - if (new Users.Forms.LoginDlg(reqGrpMembership, this).ShowDialog() == DialogResult.OK) + if (new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, reqGrpMembership, this).ShowDialog() == DialogResult.OK) { UpdateUser(); } diff --git a/TBF/UI/Procedures/ProcedureDlg.cs b/TBF/UI/Procedures/ProcedureDlg.cs index e894d9528..c73f99f9d 100644 --- a/TBF/UI/Procedures/ProcedureDlg.cs +++ b/TBF/UI/Procedures/ProcedureDlg.cs @@ -11,6 +11,7 @@ using System.Linq; using System.Text; using System.Windows.Forms; using log4net; +using NHibernate; using Common; using Common.Forms; using Config.Entities; @@ -38,6 +39,11 @@ namespace TBF.UI.Procedures readonly Mode initialMode; + /// + /// Database session passed as a constructor argument + /// + public ISession Session; + /// /// Procedure to be updated by this dialog. /// Set by the constructor or updated by the parent after creation and before loading. @@ -77,9 +83,10 @@ namespace TBF.UI.Procedures Dpi = (int)this.CreateGraphics().DpiX; } - public ProcedureDlg(Procedure procedure, IList usedNames, Mode initialMode, Form parentForm) + public ProcedureDlg(ISession session, Procedure procedure, IList usedNames, Mode initialMode, Form parentForm) : this() { + this.Session = session; if (procedure == null) throw new ArgumentNullException("procedure"); LoadedProcedure = procedure; @@ -136,69 +143,66 @@ namespace TBF.UI.Procedures SelectedTestIx = -1; - using (NHibernate.ISession session = TBF.DB.CreateSession(DBKind.Config)) + /// + /// Prepare a list of components and a list of all valves in the test bench + /// + TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(Session); + Valves = Rig.GenericDevices.ValveBase.MasterValves(TbfComponents); + RegulValves = new List(); + TestMethods = new List(); + TempControllers = new List(); + dataEntryComboBox.Items.Add("---"); + printer1ComboBox.Items.Add("---"); + printer2ComboBox.Items.Add("---"); + fileWriter1ComboBox.Items.Add("---"); + fileWriter2ComboBox.Items.Add("---"); + fileWriter3ComboBox.Items.Add("---"); + fileWriter4ComboBox.Items.Add("---"); + fileWriter5ComboBox.Items.Add("---"); + eventTrigger1ComboBox.Items.Add("---"); + eventTrigger2ComboBox.Items.Add("---"); + eventTrigger3ComboBox.Items.Add("---"); + + foreach (var cmpnt in TbfComponents) { - /// - /// Prepare a list of components and a list of all valves in the test bench - /// - TbfComponents = Rig.TbfComponents.LoadComponentsFromDB(session); - Valves = Rig.GenericDevices.ValveBase.MasterValves(TbfComponents); - RegulValves = new List(); - TestMethods = new List(); - TempControllers = new List(); - dataEntryComboBox.Items.Add("---"); - printer1ComboBox.Items.Add("---"); - printer2ComboBox.Items.Add("---"); - fileWriter1ComboBox.Items.Add("---"); - fileWriter2ComboBox.Items.Add("---"); - fileWriter3ComboBox.Items.Add("---"); - fileWriter4ComboBox.Items.Add("---"); - fileWriter5ComboBox.Items.Add("---"); - eventTrigger1ComboBox.Items.Add("---"); - eventTrigger2ComboBox.Items.Add("---"); - eventTrigger3ComboBox.Items.Add("---"); - - foreach (var cmpnt in TbfComponents) - { - if (cmpnt is IRegValve) RegulValves.Add(cmpnt as IRegValve); - if (cmpnt is ITestMethod) TestMethods.Add(cmpnt as ITestMethod); - if (cmpnt is ITempControl) TempControllers.Add(cmpnt as ITempControl); - if (cmpnt is IDataEntry) dataEntryComboBox.Items.Add(cmpnt.Cfg.Name); - if (cmpnt is IResultsPrinter) - { - printer1ComboBox.Items.Add(cmpnt.Cfg.Name); - printer2ComboBox.Items.Add(cmpnt.Cfg.Name); - } - if (cmpnt is IResultsWriter) - { - fileWriter1ComboBox.Items.Add(cmpnt.Cfg.Name); - fileWriter2ComboBox.Items.Add(cmpnt.Cfg.Name); - fileWriter3ComboBox.Items.Add(cmpnt.Cfg.Name); - fileWriter4ComboBox.Items.Add(cmpnt.Cfg.Name); - fileWriter5ComboBox.Items.Add(cmpnt.Cfg.Name); - } - if (cmpnt is IEventTrigger) - { - eventTrigger1ComboBox.Items.Add(cmpnt.Cfg.Name); - eventTrigger2ComboBox.Items.Add(cmpnt.Cfg.Name); - eventTrigger3ComboBox.Items.Add(cmpnt.Cfg.Name); - } + if (cmpnt is IRegValve) RegulValves.Add(cmpnt as IRegValve); + if (cmpnt is ITestMethod) TestMethods.Add(cmpnt as ITestMethod); + if (cmpnt is ITempControl) TempControllers.Add(cmpnt as ITempControl); + if (cmpnt is IDataEntry) dataEntryComboBox.Items.Add(cmpnt.Cfg.Name); + if (cmpnt is IResultsPrinter) + { + printer1ComboBox.Items.Add(cmpnt.Cfg.Name); + printer2ComboBox.Items.Add(cmpnt.Cfg.Name); } + if (cmpnt is IResultsWriter) + { + fileWriter1ComboBox.Items.Add(cmpnt.Cfg.Name); + fileWriter2ComboBox.Items.Add(cmpnt.Cfg.Name); + fileWriter3ComboBox.Items.Add(cmpnt.Cfg.Name); + fileWriter4ComboBox.Items.Add(cmpnt.Cfg.Name); + fileWriter5ComboBox.Items.Add(cmpnt.Cfg.Name); + } + if (cmpnt is IEventTrigger) + { + eventTrigger1ComboBox.Items.Add(cmpnt.Cfg.Name); + eventTrigger2ComboBox.Items.Add(cmpnt.Cfg.Name); + eventTrigger3ComboBox.Items.Add(cmpnt.Cfg.Name); + } + } - /// - /// Loads paths, this must be done before PrepareMetrology12AndProcessTabs() call - /// - feedingPaths = session.QueryOver().List(); - benchPaths = session.QueryOver().List(); - outputPaths = session.QueryOver().List(); - metersPaths = session.QueryOver().List(); + /// + /// Loads paths, this must be done before PrepareMetrology12AndProcessTabs() call + /// + feedingPaths = Session.QueryOver().List(); + benchPaths = Session.QueryOver().List(); + outputPaths = Session.QueryOver().List(); + metersPaths = Session.QueryOver().List(); #if HEAT_METERS - heatMetersPaths = session.QueryOver().List(); + heatMetersPaths = Session.QueryOver().List(); #else - heatMetersPaths = new List(); + heatMetersPaths = new List(); #endif - transitionSequences = session.QueryOver().List(); - } + transitionSequences = Session.QueryOver().List(); transitionStartComboBox.Items.Add("---"); transitionEndComboBox.Items.Add("---"); @@ -395,41 +399,50 @@ namespace TBF.UI.Procedures lastChangedByTextBox.ReadOnly = true; lastChangedOnTextBox.ReadOnly = true; - foreach (var test in LoadedProcedure.Tests) + try { - test.VolumeUnit = TBF.Rig.Sequences.ProcessData.VolumeUnit; - test.FlowUnit = TBF.Rig.Sequences.ProcessData.FlowUnit; - test.MassUnit = TBF.Rig.Sequences.ProcessData.MassUnit; - test.TempUnit = TBF.Rig.Sequences.ProcessData.TempUnit; - test.PressUnit = TBF.Rig.Sequences.ProcessData.PressUnit; - test.LengthUnit = TBF.Rig.Sequences.ProcessData.LengthUnit; - test.ResetChngdFlags(); - } + foreach (var test in LoadedProcedure.Tests) + { + test.VolumeUnit = TBF.Rig.Sequences.ProcessData.VolumeUnit; + test.FlowUnit = TBF.Rig.Sequences.ProcessData.FlowUnit; + test.MassUnit = TBF.Rig.Sequences.ProcessData.MassUnit; + test.TempUnit = TBF.Rig.Sequences.ProcessData.TempUnit; + test.PressUnit = TBF.Rig.Sequences.ProcessData.PressUnit; + test.LengthUnit = TBF.Rig.Sequences.ProcessData.LengthUnit; + test.ResetChngdFlags(); + } - /// History tab - InitializeHistoryTab(); /// Create ListViewEx columns for 'History of changes' + /// History tab + InitializeHistoryTab(); /// Create ListViewEx columns for 'History of changes' - /// LisViewEx columns and edit controls for 'Metrology1', 'Metrology2', 'Process' and 'Parameters' tabs - PrepareMetrology1Tab(); - PrepareMetrology2Tab(); - PrepareProcess(); - PrepareParameters(); + /// LisViewEx columns and edit controls for 'Metrology1', 'Metrology2', 'Process' and 'Parameters' tabs + PrepareMetrology1Tab(); + PrepareMetrology2Tab(); + PrepareProcess(); + PrepareParameters(); - /// Now refresh the content of the dialog - RefreshGeneralTab(); - RefreshMetrology1Tab(); - RefreshMetrology2Tab(); - RefreshProcessTab(); - RefreshParametersTab(); + /// Now refresh the content of the dialog + RefreshGeneralTab(); + RefreshMetrology1Tab(); + RefreshMetrology2Tab(); + RefreshProcessTab(); + RefreshParametersTab(); - foreach (var ctrl in testParamsCtrls) - { - ctrl.Initialize(); - } - foreach (var ctrl in procedureParamsCtrls) - { - ctrl.Initialize(); - } + foreach (var ctrl in testParamsCtrls) + { + ctrl.Initialize(); + } + foreach (var ctrl in procedureParamsCtrls) + { + ctrl.Initialize(); + } + } + catch (Exception exc) + { + MessageBox.Show(string.Format("{0}:{1}{2}", + Strings.Error_reading_configuration_database, Environment.NewLine, exc.Message), + Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + } /// Optionally unlock this dialog if (initialMode == Mode.Unlocked) @@ -709,19 +722,16 @@ namespace TBF.UI.Procedures void RefreshHistoryTab() { - NHibernate.ISession session = TBF.DB.CreateSession(DBKind.Config); - IList procedures = session - .QueryOver() - .Where(x => x.ProcedureState == ProcedureState.History) - .List(); + var procedures = Session.QueryOver() + .Where(x => x.ProcedureState == ProcedureState.History) + .List(); int predecessorId = LoadedProcedure.PredecessorId; - IList oneProcedure = session - .QueryOver() - .Where(x => (x.ProcedureState == ProcedureState.Active)) - .And(x => (x.Id == predecessorId)) - .List(); + var oneProcedure = Session.QueryOver() + .Where(x => (x.ProcedureState == ProcedureState.Active)) + .And(x => (x.Id == predecessorId)) + .List(); if (oneProcedure.Count == 1) { @@ -759,7 +769,7 @@ namespace TBF.UI.Procedures } if (!found) break; } - } + } void UpdateFromHistoryTab() { @@ -3003,8 +3013,8 @@ namespace TBF.UI.Procedures break; } - using (NHibernate.ISession session = TBF.DB.CreateSession(DBKind.Config)) - { + try + { IList testsToBeUpdated = new List(); foreach (var test in LoadedProcedure.Tests) @@ -3150,6 +3160,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) @@ -3159,7 +3175,7 @@ namespace TBF.UI.Procedures if (lvi.Tag is Procedure) { - (new ProcedureDlg(lvi.Tag as Procedure, new List(), ProcedureDlg.Mode.PermanentlyLocked, sharedButtons.ParentForm)).ShowDialog(); + (new ProcedureDlg(Session, lvi.Tag as Procedure, new List(), ProcedureDlg.Mode.PermanentlyLocked, sharedButtons.ParentForm)).ShowDialog(); } } diff --git a/TBF/UI/Procedures/ProcedureDlg.resx b/TBF/UI/Procedures/ProcedureDlg.resx index 0878d8839..e6b8a33dd 100644 --- a/TBF/UI/Procedures/ProcedureDlg.resx +++ b/TBF/UI/Procedures/ProcedureDlg.resx @@ -2170,7 +2170,7 @@ sharedButtons - TBF.UI.Shared.SharedButtons, TBF, Version=2.27.1917.0, Culture=neutral, PublicKeyToken=null + TBF.UI.Shared.SharedButtons, TBF, Version=2.32.2027.0, Culture=neutral, PublicKeyToken=null mainSplitContainer.Panel2 diff --git a/TBF/UI/Procedures/ProceduresCtrl.cs b/TBF/UI/Procedures/ProceduresCtrl.cs index d66728591..2ee327177 100644 --- a/TBF/UI/Procedures/ProceduresCtrl.cs +++ b/TBF/UI/Procedures/ProceduresCtrl.cs @@ -20,6 +20,12 @@ namespace TBF.UI.Procedures { static readonly ILog log = LogManager.GetLogger(typeof(ProceduresCtrl)); + ProceduresDlg parent; /// parent form + Control parentControl; /// parent control (split container) + + /// Database session from the parent form + public ISession Session { get { return parent.Session; } } + /// /// List of all active procedures /// @@ -60,11 +66,8 @@ namespace TBF.UI.Procedures Count } - ProceduresDlg parent; - Control parentControl; Control[] editors; - ISession session; IWaterMeter waterMeterCmpnt; IErrorFlags errorFlagsCmpnt; @@ -72,7 +75,6 @@ namespace TBF.UI.Procedures { InitializeComponent(); - session = null; waterMeterCmpnt = null; errorFlagsCmpnt = null; ToBeRemovedProcedures = new List(); @@ -115,9 +117,6 @@ namespace TBF.UI.Procedures public void Initialize(ProceduresDlg parent, Control parentControl) { if (parent == null) return; - - /// Create a DB session - session = TBF.DB.CreateSession(DBKind.Config); this.parent = parent; this.parentControl = parentControl; @@ -168,7 +167,7 @@ namespace TBF.UI.Procedures if (isFirstTime) { /// Find WaterMeter and ErrorFlags components, this is done just once when AllProcedures == null - foreach (var cmpnt in TBF.Rig.TbfComponents.LoadComponentsFromDB(session)) + foreach (var cmpnt in TBF.Rig.TbfComponents.LoadComponentsFromDB(Session)) { if (waterMeterCmpnt == null && cmpnt is IWaterMeter) waterMeterCmpnt = cmpnt as IWaterMeter; if (errorFlagsCmpnt == null && cmpnt is IErrorFlags) errorFlagsCmpnt = cmpnt as IErrorFlags; @@ -176,7 +175,7 @@ namespace TBF.UI.Procedures } /// (Re)Load all procedures unconditionally - AllProcedures = session.QueryOver() + AllProcedures = Session.QueryOver() .Where(x => (x.ProcedureState == ProcedureState.Active)) .OrderBy(x => x.ItemNr).Asc .List(); @@ -269,22 +268,22 @@ namespace TBF.UI.Procedures /// public void OkBtnClicked() { - using (ITransaction transaction = session.BeginTransaction()) + using (ITransaction transaction = Session.BeginTransaction()) { try { - foreach (var entity in ToBeRemovedProcedures) session.Delete(entity); + foreach (var entity in ToBeRemovedProcedures) Session.Delete(entity); ToBeRemovedProcedures.Clear(); int itemNr = 0; foreach (var proc in AllProcedures) { (proc as Procedure).ItemNr = itemNr++; - session.SaveOrUpdate(proc); + Session.SaveOrUpdate(proc); } transaction.Commit(); - session.Flush(); + Session.Flush(); } catch (Exception exc) { @@ -328,12 +327,12 @@ namespace TBF.UI.Procedures newProcedure.CreationUser = Users.CurrentUser.UserName(); newProcedure.CreationTime = DateTime.Now; - if (new ProcedureDlg(newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent).ShowDialog() == DialogResult.OK) + if (new ProcedureDlg(Session, newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent).ShowDialog() == DialogResult.OK) { /// TODO: Make name uniqueness test parent.Unlock(); - using (var transaction = session.BeginTransaction()) + using (var transaction = Session.BeginTransaction()) { try { @@ -341,7 +340,7 @@ namespace TBF.UI.Procedures newProcedure.LastChgTime = DateTime.Now; DoAddOne(newProcedure); - session.SaveOrUpdate(newProcedure); + Session.SaveOrUpdate(newProcedure); transaction.Commit(); MessageBox.Show(string.Format(Strings.Procedure_0_added, newProcedure.Name), @@ -393,22 +392,22 @@ namespace TBF.UI.Procedures } /// Update the database - using (ITransaction transaction = session.BeginTransaction()) + using (ITransaction transaction = Session.BeginTransaction()) { try { - foreach (var entity in ToBeRemovedProcedures) session.Delete(entity); + foreach (var entity in ToBeRemovedProcedures) Session.Delete(entity); ToBeRemovedProcedures.Clear(); int itemNr = 0; foreach (var entity in Procedures) { (entity as Procedure).ItemNr = itemNr++; - session.SaveOrUpdate(entity); + Session.SaveOrUpdate(entity); } transaction.Commit(); - session.Flush(); + Session.Flush(); } catch (Exception exc) { @@ -565,11 +564,11 @@ namespace TBF.UI.Procedures IList usedNames = GetUsedNames(false); usedNames.Remove(originalProcedure.Name.ToLower()); /// Allow original procedure name /// - if (new ProcedureDlg(modifiedProcedure, usedNames, ProcedureDlg.Mode.Locked, parent).ShowDialog() == DialogResult.OK) + if (new ProcedureDlg(Session, modifiedProcedure, usedNames, ProcedureDlg.Mode.Locked, parent).ShowDialog() == DialogResult.OK) { parent.Unlock(); - using (var transaction = session.BeginTransaction()) + using (var transaction = Session.BeginTransaction()) { try { @@ -577,8 +576,8 @@ namespace TBF.UI.Procedures modifiedProcedure.LastChgUser = Users.CurrentUser.UserName(); modifiedProcedure.LastChgTime = DateTime.Now; - session.SaveOrUpdate(originalProcedure); - session.SaveOrUpdate(modifiedProcedure); + Session.SaveOrUpdate(originalProcedure); + Session.SaveOrUpdate(modifiedProcedure); transaction.Commit(); listViewEx.SelectedItems[0].Tag = modifiedProcedure; @@ -595,7 +594,7 @@ namespace TBF.UI.Procedures transaction.Rollback(); } } - session.Flush(); + Session.Flush(); } ReloadAndRedrawAll(); @@ -620,18 +619,18 @@ namespace TBF.UI.Procedures newProcedure.CreationTime = DateTime.Now; newProcedure.Protected = false; - if ((new ProcedureDlg(newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent)).ShowDialog() == DialogResult.OK) + if ((new ProcedureDlg(Session, newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent)).ShowDialog() == DialogResult.OK) { /// TODO: Make name uniqueness test parent.Unlock(); - using (var transaction = session.BeginTransaction()) + using (var transaction = Session.BeginTransaction()) { newProcedure.LastChgUser = Users.CurrentUser.UserName(); newProcedure.LastChgTime = DateTime.Now; DoAddOne(newProcedure); - session.SaveOrUpdate(newProcedure); + Session.SaveOrUpdate(newProcedure); transaction.Commit(); MessageBox.Show(string.Format(Strings.Procedure_0_added, newProcedure.Name), @@ -673,18 +672,18 @@ namespace TBF.UI.Procedures newProcedure.CreationUser = Users.CurrentUser.UserName(); newProcedure.CreationTime = DateTime.Now; - if ((new ProcedureDlg(newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent)).ShowDialog() == DialogResult.OK) + if ((new ProcedureDlg(Session, newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent)).ShowDialog() == DialogResult.OK) { /// TODO: Make name uniqueness test parent.Unlock(); - using (var transaction = session.BeginTransaction()) + using (var transaction = Session.BeginTransaction()) { newProcedure.LastChgUser = Users.CurrentUser.UserName(); newProcedure.LastChgTime = DateTime.Now; DoAddOne(newProcedure); - session.SaveOrUpdate(newProcedure); + Session.SaveOrUpdate(newProcedure); transaction.Commit(); MessageBox.Show(string.Format(Strings.Procedure_0_added, newProcedure.Name), @@ -725,12 +724,12 @@ namespace TBF.UI.Procedures try { - profiles = session.QueryOver() + profiles = Session.QueryOver() .OrderBy(x => x.ItemNr).Asc .List(); - fPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); - bPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); - oPaths = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); + fPaths = Session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); + bPaths = Session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); + oPaths = Session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); } catch (Exception) { @@ -759,11 +758,11 @@ namespace TBF.UI.Procedures IList errorFlagsParamsOfCreatedTests = new List(); IList waterMeterParamsOfNewProcedure = new List(); - IList cmpntEntities = session.QueryOver() + IList cmpntEntities = Session.QueryOver() .OrderBy(x => x.ItemNr).Asc .List(); - IList components = Rig.TbfComponents.LoadComponentsFromDB(session); + IList components = Rig.TbfComponents.LoadComponentsFromDB(Session); foreach (var cmptn in components) { if (cmptn.ClassName == "WaterMeter") @@ -845,12 +844,12 @@ namespace TBF.UI.Procedures newProcedure.CreationUser = Users.CurrentUser.UserName(); newProcedure.CreationTime = DateTime.Now; - if (new ProcedureDlg(newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent).ShowDialog() == DialogResult.OK) + if (new ProcedureDlg(Session, newProcedure, GetUsedNames(false), ProcedureDlg.Mode.Unlocked, parent).ShowDialog() == DialogResult.OK) { /// TODO: Make name uniqueness test parent.Unlock(); - using (var transaction = session.BeginTransaction()) + using (var transaction = Session.BeginTransaction()) { try { @@ -858,7 +857,7 @@ namespace TBF.UI.Procedures newProcedure.LastChgTime = DateTime.Now; DoAddOne(newProcedure); - session.SaveOrUpdate(newProcedure); + Session.SaveOrUpdate(newProcedure); foreach (var efp in errorFlagsParamsOfCreatedTests) { @@ -1086,7 +1085,7 @@ namespace TBF.UI.Procedures case MoreContent.Oracle: if (!string.IsNullOrEmpty(procedure.ResultsWriter) && procedure.ResultsWriter.Contains("Sensus-Oracle-DB")) { - var procParamsEntity = session.QueryOver() + var procParamsEntity = Session.QueryOver() .Where(x => x.Procedure == procedure) .And(x => x.CmpntName == "Sensus-Oracle-DB") .List(); diff --git a/TBF/UI/Procedures/ProceduresDlg.cs b/TBF/UI/Procedures/ProceduresDlg.cs index 414528d07..8b2f452fd 100644 --- a/TBF/UI/Procedures/ProceduresDlg.cs +++ b/TBF/UI/Procedures/ProceduresDlg.cs @@ -1,9 +1,10 @@ /// -/// Copyright (c) 2013-2022 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Windows.Forms; using log4net; +using NHibernate; using Common; using Common.Forms; using TBF.Resources; @@ -18,6 +19,8 @@ namespace TBF.UI.Procedures /// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi public readonly int Dpi; + public ISession Session; /// DB session is open in the constructor and closed in _FormClosing handler + public ProceduresDlg() { /// Detect display setting: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi. @@ -25,6 +28,14 @@ namespace TBF.UI.Procedures InitializeComponent(); + /// Open a database session + try { Session = TBF.DB.ConfigDBSessionFactory.OpenSession(); } + catch (Exception e) + { + MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message, + Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + } + /// SharedDlgButtons configuration sharedButtons.ParentForm = this; sharedButtons.RequiredGroupMembership = new GID[] { GID.TestingSpecialists, GID.Metrologists }; @@ -112,6 +123,7 @@ namespace TBF.UI.Procedures } if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); + if (Session != null && Session.IsOpen) Session.Close(); } diff --git a/TBF/UI/ResultsMI/PreviousResultCtrl.cs b/TBF/UI/ResultsMI/PreviousResultCtrl.cs index 0a19f6195..a065243b4 100644 --- a/TBF/UI/ResultsMI/PreviousResultCtrl.cs +++ b/TBF/UI/ResultsMI/PreviousResultCtrl.cs @@ -131,7 +131,7 @@ namespace TBF.UI.ResultsMI /// Access only to thise who manage production tracing GID[] rqrdGroupMembership = new GID[] { GID.TraceabilityManagement }; - if ((new Users.Forms.LoginDlg(Users.CurrentUser.UserName(), rqrdGroupMembership, parent)).ShowDialog() != DialogResult.OK) + if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, Users.CurrentUser.UserName(), rqrdGroupMembership, parent)).ShowDialog() != DialogResult.OK) { return; } diff --git a/TBF/UI/ResultsMI/PreviousResultsDlg.cs b/TBF/UI/ResultsMI/PreviousResultsDlg.cs index 14f5aa16b..14bc61f44 100644 --- a/TBF/UI/ResultsMI/PreviousResultsDlg.cs +++ b/TBF/UI/ResultsMI/PreviousResultsDlg.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2016-2021 Sensus Slovensko a.s. +/// Copyright (c) 2016-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -14,11 +14,11 @@ using Oracle.DataAccess.Client; using Common; using Results; using Results.Entities; +using TBF.Resources; using TBF.Rig.Generic; using TBF.Rig.GenericDevices; using TBF.Rig.Output.DB.SensusOracle; using TBF.Rig.Sequences; -using TBF.Resources; namespace TBF.UI.ResultsMI { @@ -33,20 +33,20 @@ namespace TBF.UI.ResultsMI { static readonly ILog log = LogManager.GetLogger(typeof(PreviousResultsDlg)); - ISession session; - int currentBatchNr; + readonly PreviousResultsMode mode; + readonly int currentBatchNr; + ISession session; IList batches; /// A list of batches selected from all batches using criteria entered in UI IList serialNrs; /// Display only watermeters with these serial numbers (null = display all) int lastDisplayedIx; /// Index of the last displayed batch from the list 'batches' const int LinesCount = 25; /// Number of batches displayed on one screen - PreviousResultsMode mode; - public PreviousResultsDlg(PreviousResultsMode mode) { InitializeComponent(); + this.mode = mode; currentBatchNr = Program.LocalSettings.BatchNr; @@ -74,7 +74,7 @@ namespace TBF.UI.ResultsMI { } - private void PreviousResultsDlg_Load(object sender, EventArgs e) + private void PreviousResultsDlg_Load(object sender, EventArgs args) { Localize(); @@ -90,14 +90,11 @@ namespace TBF.UI.ResultsMI toDateTimePicker.CustomFormat = Constants.DateFormat; toDateTimePicker.ShowUpDown = true; - try + try { session = TBF.DB.ResultsDBSessionFactory.OpenSession(); } + catch (Exception e) { - session = Results.DB.CreateSession(); - } - catch (Exception exc) - { - session = null; - log.ErrorFormat("Opening Results DB failed: {0}", exc.Message); + MessageBox.Show(Strings.Cannot_connect_to_the_database + Environment.NewLine + e.Message, + Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } batches = GetFilteredBatches(out lastDisplayedIx, out serialNrs); @@ -129,7 +126,7 @@ namespace TBF.UI.ResultsMI if (string.IsNullOrEmpty(procedureTextBox.Text) && string.IsNullOrEmpty(snTextBox.Text)) { rslt = session.QueryOver() - .Where(x => (x.StartTime >= fromDateTimePicker.Value)) + .Where(x => (x.EndTime >= fromDateTimePicker.Value)) .And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1))) .OrderBy(x => x.BatchNr).Asc .List(); @@ -137,7 +134,7 @@ namespace TBF.UI.ResultsMI else if (string.IsNullOrEmpty(snTextBox.Text)) { rslt = session.QueryOver() - .Where(x => (x.StartTime >= fromDateTimePicker.Value)) + .Where(x => (x.EndTime >= fromDateTimePicker.Value)) .And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1))) .And(x => (x.ProcedureName == procedureTextBox.Text)) .OrderBy(x => x.BatchNr).Asc @@ -146,7 +143,7 @@ namespace TBF.UI.ResultsMI else if (string.IsNullOrEmpty(procedureTextBox.Text)) { rslt = session.QueryOver() - .Where(x => (x.StartTime >= fromDateTimePicker.Value)) + .Where(x => (x.EndTime >= fromDateTimePicker.Value)) .And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1))) .OrderBy(x => x.BatchNr).Asc .JoinQueryOver(b => b.WaterMeters) @@ -156,7 +153,7 @@ namespace TBF.UI.ResultsMI else { rslt = session.QueryOver() - .Where(x => (x.StartTime >= fromDateTimePicker.Value)) + .Where(x => (x.EndTime >= fromDateTimePicker.Value)) .And(x => (x.StartTime < toDateTimePicker.Value.AddDays(1))) .And(x => (x.ProcedureName == procedureTextBox.Text)) .OrderBy(x => x.BatchNr).Asc @@ -438,7 +435,6 @@ namespace TBF.UI.ResultsMI private void closeButton_Click(object sender, EventArgs e) { - if (session != null) session.Close(); DialogResult = DialogResult.Cancel; Close(); } @@ -473,6 +469,7 @@ namespace TBF.UI.ResultsMI private void PreviousResultsDlg_FormClosing(object sender, FormClosingEventArgs e) { if (Users.CurrentUser.Restore(this)) Program.MainWnd.UpdateUser(); + if (session != null && session.IsOpen) session.Close(); } } } diff --git a/TBF/UI/ResultsMI/ResultsArrangementDlg.cs b/TBF/UI/ResultsMI/ResultsArrangementDlg.cs index 56bba4a10..18e9c432e 100644 --- a/TBF/UI/ResultsMI/ResultsArrangementDlg.cs +++ b/TBF/UI/ResultsMI/ResultsArrangementDlg.cs @@ -1,11 +1,12 @@ /// -/// Copyright (c) 2013-2017 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; using System.Windows.Forms; using Common; using Results; +using Users.Forms; using TBF.Resources; namespace TBF.UI.ResultsMI @@ -92,13 +93,14 @@ namespace TBF.UI.ResultsMI { if (!Users.CurrentUser.IsMemberOf(RequiredGroupMembership)) { - if ((new Users.Forms.LoginDlg(RequiredGroupMembership, this)).ShowDialog() != DialogResult.OK) - return; + if (DialogResult.OK != (new LoginDlg(TBF.DB.UserSessionFactories, + RequiredGroupMembership, this)).ShowDialog()) return; } else if (Program.LocalSettings.AlwaysAskPasswdWhenUnlocking) { - if ((new Users.Forms.LoginDlg(Users.CurrentUser.UserName(), RequiredGroupMembership, this)).ShowDialog() != DialogResult.OK) - return; + if (DialogResult.OK != (new LoginDlg(TBF.DB.UserSessionFactories, + Users.CurrentUser.UserName(), + RequiredGroupMembership, this)).ShowDialog()) return; } Unlocked = true; diff --git a/TBF/UI/ResultsMI/ResultsTabPageCtrl.cs b/TBF/UI/ResultsMI/ResultsTabPageCtrl.cs index e27455f10..cd2f64c6b 100644 --- a/TBF/UI/ResultsMI/ResultsTabPageCtrl.cs +++ b/TBF/UI/ResultsMI/ResultsTabPageCtrl.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2013-2019 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; @@ -8,7 +8,6 @@ using System.Windows.Forms; using log4net; using NHibernate; using Common; -using Common.Forms; using Results; using Results.Forms; using Results.Entities; @@ -647,7 +646,7 @@ namespace TBF.UI.ResultsMI var dlg = new DeleteFromOracleForm(); GID[] rqrdGroupMembership = new GID[] { GID.TraceabilityManagement }; /// Restricted access to Delete from Oracle Form - if ((new Users.Forms.LoginDlg(Users.CurrentUser.UserName(), rqrdGroupMembership, dlg)).ShowDialog() == DialogResult.OK) + if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, Users.CurrentUser.UserName(), rqrdGroupMembership, dlg)).ShowDialog() == DialogResult.OK) { if (dlg.ShowDialog() == DialogResult.OK) MessageBox.Show("Successfully deleted from Oracle"); } diff --git a/TBF/UI/Settings/DatabaseSettingsDlg.cs b/TBF/UI/Settings/DatabaseSettingsDlg.cs index 7f88b4525..c8b1ebda0 100644 --- a/TBF/UI/Settings/DatabaseSettingsDlg.cs +++ b/TBF/UI/Settings/DatabaseSettingsDlg.cs @@ -191,7 +191,7 @@ namespace TBF.UI.Settings log.ErrorFormat("Going to create an empty configuration database '{0}'", databaseName); ExecuteMySqlCmd(string.Format("DROP DATABASE `{0}`;", databaseName), userName, password); ExecuteMySqlCmd(string.Format("CREATE DATABASE `{0}` CHARACTER SET utf8 COLLATE utf8_unicode_ci;", databaseName), userName, password); - Config.FluentCommon.CreateEmptyConfigDB(bench.ProceduresDBSettings.DbType, connectionString); + TBF.DB.CreateEmptyConfigDB(bench.ProceduresDBSettings.DbType, connectionString); log.ErrorFormat("An empty configuration database '{0}' was created", databaseName); MessageBox.Show(Strings.DB_was_successfully_created, Strings.Notification); @@ -272,29 +272,31 @@ namespace TBF.UI.Settings { try { - string connectionString = bench.EventsDBSettings.ConnectionString; - string databaseName = Config.Utils.GetDBName(connectionString); - string userName = Config.Utils.GetDBUser(connectionString); - string password = Config.Utils.GetDBPassword(connectionString); /// TODO: Use password + MessageBox.Show("Not implemented yet"); - if (connectionString == currentConfigDBConnStr || connectionString == currentResultsDBConnStr || connectionString == currentEventsDBConnStr) - { - CurrentDBChanged = true; - } + //string connectionString = bench.EventsDBSettings.ConnectionString; + //string databaseName = Config.Utils.GetDBName(connectionString); + //string userName = Config.Utils.GetDBUser(connectionString); + //string password = Config.Utils.GetDBPassword(connectionString); /// TODO: Use password - Cursor.Current = Cursors.WaitCursor; + //if (connectionString == currentConfigDBConnStr || connectionString == currentResultsDBConnStr || connectionString == currentEventsDBConnStr) + //{ + // CurrentDBChanged = true; + //} - log.ErrorFormat("Going to create an empty events database '{0}'", databaseName); - ExecuteMySqlCmd(string.Format("DROP DATABASE `{0}`;", databaseName), userName, password); - ExecuteMySqlCmd(string.Format("CREATE DATABASE `{0}` CHARACTER SET utf8 COLLATE utf8_unicode_ci;", databaseName), userName, password); - global::Events.DB.DbType = (DBType)bench.EventsDBSettings.DbType; - global::Events.DB.ConnectionString = connectionString; - global::Events.DB.CreateEmptyDB(); - log.ErrorFormat("An empty events database '{0}' was created", databaseName); + //Cursor.Current = Cursors.WaitCursor; - MessageBox.Show(Strings.DB_was_successfully_created, Strings.Notification); - Cursor.Current = Cursors.Default; - DialogResult = DialogResult.None; + //log.ErrorFormat("Going to create an empty events database '{0}'", databaseName); + //ExecuteMySqlCmd(string.Format("DROP DATABASE `{0}`;", databaseName), userName, password); + //ExecuteMySqlCmd(string.Format("CREATE DATABASE `{0}` CHARACTER SET utf8 COLLATE utf8_unicode_ci;", databaseName), userName, password); + //global::Events.DB.DbType = (DBType)bench.EventsDBSettings.DbType; + //global::Events.DB.ConnectionString = connectionString; + //global::Events.DB.CreateEmptyDB(); + //log.ErrorFormat("An empty events database '{0}' was created", databaseName); + + //MessageBox.Show(Strings.DB_was_successfully_created, Strings.Notification); + //Cursor.Current = Cursors.Default; + //DialogResult = DialogResult.None; } catch (Exception exception) { diff --git a/TBF/UI/Settings/UpgradeSelectionDlg.cs b/TBF/UI/Settings/UpgradeSelectionDlg.cs index 8d82512a1..d04268fc3 100644 --- a/TBF/UI/Settings/UpgradeSelectionDlg.cs +++ b/TBF/UI/Settings/UpgradeSelectionDlg.cs @@ -116,7 +116,7 @@ namespace TBF.UI.Settings try { - session = TBF.DB.CreateSession(Common.DBKind.Config); + session = TBF.DB.ConfigDBSessionFactory.OpenSession(); var testParams = session.QueryOver() .Where(x => (x.CmpntName == errorFlagsCmpntName)) @@ -144,6 +144,7 @@ namespace TBF.UI.Settings } session.Flush(); + session.Close(); success = true; } catch (Exception exc) @@ -992,9 +993,10 @@ namespace TBF.UI.Settings ActivityStart(); + ISession session = null; try { - ISession session = Results.DB.CreateSession(); + session = TBF.DB.ResultsDBSessionFactory.OpenSession(); IList bFrom = session.QueryOver().Where(x => (x.BatchNr == batchFrom)).List(); IList bTo = session.QueryOver().Where(x => (x.BatchNr == batchTo)).List(); @@ -1041,15 +1043,20 @@ namespace TBF.UI.Settings MessageBox.Show(string.Format("Upgrade failed:\r\n{0}", exc.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Information); } + finally + { + if (session != null && session.IsOpen) session.Close(); + } } private void customButton_Click(object sender, EventArgs e) { ActivityStart(); + ISession session = null; try { - ISession session = TBF.DB.CreateSession(Common.DBKind.Config); + session = TBF.DB.ConfigDBSessionFactory.OpenSession(); var proceduresToModify = session.QueryOver() .Where(x => x.CmpntName == "Sensus-Oracle-DB") @@ -1075,6 +1082,10 @@ namespace TBF.UI.Settings MessageBox.Show(string.Format("Upgrade failed:\r\n{0}", exc.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Information); } + finally + { + if (session != null && session.IsOpen) session.Close(); + } } private void upgradeDb_226_227_Button_Click(object sender, EventArgs e) @@ -1298,7 +1309,7 @@ namespace TBF.UI.Settings ISession session = null; try { - session = TBF.DB.CreateSession(Common.DBKind.Config); + session = TBF.DB.ConfigDBSessionFactory.OpenSession(); var tests = session.QueryOver().List(); foreach (var t in tests) diff --git a/TBF/UI/Shared/BenchControlPanel.cs b/TBF/UI/Shared/BenchControlPanel.cs index 1f0f86a9f..4c4ae24b3 100644 --- a/TBF/UI/Shared/BenchControlPanel.cs +++ b/TBF/UI/Shared/BenchControlPanel.cs @@ -10,6 +10,7 @@ using Common; using Config.Entities; using TBF.UiBridge; using TBF.Resources; +using NHibernate; namespace TBF.UI.Shared { @@ -175,52 +176,72 @@ namespace TBF.UI.Shared /// Read the database and re-initialize testComboBox items. /// Try to preserve the original selection. /// - public void ReloadTests() + public void ReloadTests(ISession session = null) { if (Program.MainWnd.SelectedProcedure == null || string.IsNullOrEmpty(Program.MainWnd.SelectedProcedure.Name)) return; + bool openAndCloseSession = (session == null); + string oriTestName = testComboBox.Text; - IList procedures = TBF.DB.CreateSession(Program.MainWnd.SelectedProcedure.IsRemote ? DBKind.RemoteConfig : DBKind.Config) - .QueryOver() - .Where(x => (x.ProcedureState == ProcedureState.Active)) - .And(x => (x.Name == Program.MainWnd.SelectedProcedure.Name)) - .List(); - if (procedures.Count != 1) - { - testComboBox.Text = string.Empty; - TestName = null; - Program.MainWnd.CurrentProcedure = null; - return; - } - - Program.MainWnd.CurrentProcedure = procedures[0]; - if (procedures[0].GetTestInstances() == null) + try { - procedures[0].UpdateTestInstances(TBF.Rig.StateMachine.LoopStartNames, TBF.Rig.StateMachine.LoopEndNames, null); + if (openAndCloseSession) + { + session = Program.MainWnd.SelectedProcedure.IsRemote + ? TBF.DB.SharedDBSessionFactory.OpenSession() + : TBF.DB.ConfigDBSessionFactory.OpenSession(); + } + + var procedures = session.QueryOver() + .Where(x => (x.ProcedureState == ProcedureState.Active)) + .And(x => (x.Name == Program.MainWnd.SelectedProcedure.Name)) + .List(); + + if (procedures.Count != 1) + { + testComboBox.Text = string.Empty; + TestName = null; + Program.MainWnd.CurrentProcedure = null; + return; + } + + Program.MainWnd.CurrentProcedure = procedures[0]; + if (procedures[0].GetTestInstances() == null) + { + procedures[0].UpdateTestInstances(TBF.Rig.StateMachine.LoopStartNames, TBF.Rig.StateMachine.LoopEndNames, null); + } + + testComboBox.Items.Clear(); + foreach (var tinst in procedures[0].GetTestInstances()) + { + testComboBox.Items.Add(tinst); + } + + if (testComboBox.Items.Contains(oriTestName)) + { + testComboBox.Text = oriTestName; + TestName = oriTestName; + } + else if (testComboBox.Items.Count > 0) + { + testComboBox.Text = testComboBox.Items[0].ToString(); + TestName = testComboBox.Items[0].ToString(); + } + else + { + testComboBox.Text = string.Empty; + TestName = null; + } + } + catch (Exception e) + { + log.ErrorFormat("Cannot reload tests: {0}", e.Message); + } + finally + { + if (openAndCloseSession && session != null && session.IsOpen) session.Close(); } - - testComboBox.Items.Clear(); - foreach (var tinst in procedures[0].GetTestInstances()) - { - testComboBox.Items.Add(tinst); - } - - if (testComboBox.Items.Contains(oriTestName)) - { - testComboBox.Text = oriTestName; - TestName = oriTestName; - } - else if (testComboBox.Items.Count > 0) - { - testComboBox.Text = testComboBox.Items[0].ToString(); - TestName = testComboBox.Items[0].ToString(); - } - else - { - testComboBox.Text = string.Empty; - TestName = null; - } } private void testComboBox_SelectedIndexChanged(object sender, EventArgs e) @@ -280,7 +301,7 @@ namespace TBF.UI.Shared if (drain1Highlighted && !Users.CurrentUser.IsMemberOf(GID.TestingSpecialists)) { var dlg = new DummyDlg(); - if ((new Users.Forms.LoginDlg(new GID[] { GID.TestingSpecialists }, dlg)).ShowDialog() != DialogResult.OK) + if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, new GID[] { GID.TestingSpecialists }, dlg)).ShowDialog() != DialogResult.OK) return; Bridge.Ui2Bench(UI2BenchCmd.StopDrainingTank1); @@ -298,7 +319,7 @@ namespace TBF.UI.Shared if (drain1Highlighted && !Users.CurrentUser.IsMemberOf(GID.TestingSpecialists)) { var dlg = new DummyDlg(); - if ((new Users.Forms.LoginDlg(new GID[] { GID.TestingSpecialists }, dlg)).ShowDialog() != DialogResult.OK) + if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, new GID[] { GID.TestingSpecialists }, dlg)).ShowDialog() != DialogResult.OK) return; Bridge.Ui2Bench(UI2BenchCmd.StopDrainingTank2); @@ -316,7 +337,7 @@ namespace TBF.UI.Shared if (drain1Highlighted && !Users.CurrentUser.IsMemberOf(GID.TestingSpecialists)) { var dlg = new DummyDlg(); - if ((new Users.Forms.LoginDlg(new GID[] { GID.TestingSpecialists }, dlg)).ShowDialog() != DialogResult.OK) + if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, new GID[] { GID.TestingSpecialists }, dlg)).ShowDialog() != DialogResult.OK) return; Bridge.Ui2Bench(UI2BenchCmd.StopDrainingTank3); diff --git a/TBF/UI/Shared/LoginDlgWithBenchSelection.cs b/TBF/UI/Shared/LoginDlgWithBenchSelection.cs index e4c104ae7..bfae20232 100644 --- a/TBF/UI/Shared/LoginDlgWithBenchSelection.cs +++ b/TBF/UI/Shared/LoginDlgWithBenchSelection.cs @@ -1,12 +1,12 @@ /// -/// Copyright (c) 2013-2018 Sensus Slovensko a.s. +/// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; +using System.Drawing; using System.Windows.Forms; using log4net; -using TBF.Resources; using GemCard; -using System.Drawing; +using TBF.Resources; namespace TBF.UI.Shared diff --git a/TBF/UI/Shared/SharedButtons.cs b/TBF/UI/Shared/SharedButtons.cs index 0a0cf6171..bb476b686 100644 --- a/TBF/UI/Shared/SharedButtons.cs +++ b/TBF/UI/Shared/SharedButtons.cs @@ -233,12 +233,13 @@ namespace TBF.UI.Shared { if (!Users.CurrentUser.IsMemberOf(RequiredGroupMembership)) { - if ((new Users.Forms.LoginDlg(RequiredGroupMembership, ParentForm)).ShowDialog() != DialogResult.OK) + if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, RequiredGroupMembership, ParentForm)).ShowDialog() != DialogResult.OK) return; } else if (Program.LocalSettings.AlwaysAskPasswdWhenUnlocking) { - if ((new Users.Forms.LoginDlg(Users.CurrentUser.UserName(), RequiredGroupMembership, ParentForm)).ShowDialog() != DialogResult.OK) + if ((new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, Users.CurrentUser.UserName(), + RequiredGroupMembership, ParentForm)).ShowDialog() != DialogResult.OK) return; } diff --git a/TracingDB/DB.cs b/TracingDB/DB.cs index fe02ef979..5e36094bc 100644 --- a/TracingDB/DB.cs +++ b/TracingDB/DB.cs @@ -6,6 +6,7 @@ using NHibernate; using NHibernate.Cfg; using NHibernate.Tool.hbm2ddl; using log4net; +using Common; using TracingDB.Entities; namespace TracingDB @@ -19,9 +20,6 @@ namespace TracingDB /// public static ISessionFactory SessionFactory; - public static ISession Session; - - /// /// Connection string for all sessions /// @@ -39,16 +37,6 @@ namespace TracingDB } } - - /// - /// NHibernate session factory (to create the database session 'SessionFactory') - /// - /// A database session - static ISessionFactory CreateSessionFactory() - { - return CreateSessionFactory(false); - } - /// /// NHibernate session factory (to create the database session 'SessionFactory') /// @@ -62,11 +50,17 @@ namespace TracingDB if (createDB) { - return cfg.ExposeConfiguration(BuildSchemaCreate).BuildSessionFactory(); + return cfg.ExposeConfiguration(BuildSchemaCreate) + .BuildConfiguration() + .SetProperty("hibernate.connection.connect_timeout", Const.MySqlConnectTimeoutSec) + .BuildSessionFactory(); } else { - return cfg.ExposeConfiguration(BuildSchema).BuildSessionFactory(); + return cfg.ExposeConfiguration(BuildSchema) + .BuildConfiguration() + .SetProperty("hibernate.connection.connect_timeout", Const.MySqlConnectTimeoutSec) + .BuildSessionFactory(); } } @@ -86,17 +80,6 @@ namespace TracingDB new SchemaExport(config).Create(true, true); } - /// Create a NHibernate session for the given database - public static ISession CreateSession(string connectionString) - { - ConnectionString = connectionString; /// Clears session factory on connction string change - - if (SessionFactory == null) - SessionFactory = CreateSessionFactory(); - - return SessionFactory.OpenSession(); - } - /// /// Create an empty database. diff --git a/Users/DB.cs b/Users/DB.cs index 8a671c1d0..4e2b29ecf 100644 --- a/Users/DB.cs +++ b/Users/DB.cs @@ -20,7 +20,6 @@ namespace Users /// Session factory for all regular sessions, not for CreateEmptyResultsDB(). public static ISessionFactory SessionFactory; - public static ISession CurrentSession; /// Connection string for all sessions private static string connectionString; @@ -73,11 +72,17 @@ namespace Users if (createDB) { - return cfg.ExposeConfiguration(BuildSchemaCreate).BuildSessionFactory(); + return cfg.ExposeConfiguration(BuildSchemaCreate) + .BuildConfiguration() + .SetProperty("hibernate.connection.connect_timeout", Const.MySqlConnectTimeoutSec) + .BuildSessionFactory(); } else { - return cfg.ExposeConfiguration(BuildSchema).BuildSessionFactory(); + return cfg.ExposeConfiguration(BuildSchema) + .BuildConfiguration() + .SetProperty("hibernate.connection.connect_timeout", Const.MySqlConnectTimeoutSec) + .BuildSessionFactory(); } } @@ -103,8 +108,7 @@ namespace Users if (SessionFactory == null) SessionFactory = CreateSessionFactory(); - CurrentSession = SessionFactory.OpenSession(); - return CurrentSession; + return SessionFactory.OpenSession(); } diff --git a/Users/Entities/User.cs b/Users/Entities/User.cs index f79fc3832..cfb031f62 100644 --- a/Users/Entities/User.cs +++ b/Users/Entities/User.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Security.Cryptography; using System.Text; using log4net; +using NHibernate; using Common; using Users.Forms; using Users.Resources; @@ -228,7 +229,7 @@ namespace Users.Entities /// Password /// /// true = authorized - public virtual bool Authorize(string userName, string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm ) + public virtual bool Authorize(ISession session, string userName, string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm) { if (IsPowerUser(userName, password)) { @@ -245,7 +246,7 @@ namespace Users.Entities return false; } - return CompleteAuthorization(password, requiredGroupMembership, currentForm); + return CompleteAuthorization(session, password, requiredGroupMembership, currentForm); } /// @@ -259,7 +260,7 @@ namespace Users.Entities /// Password /// /// true = authorized - public virtual bool AuthorizeNumber(int number, string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm) + public virtual bool AuthorizeNumber(ISession session, int number, string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm) { if (Number != number) { @@ -267,7 +268,7 @@ namespace Users.Entities return false; } - return CompleteAuthorization(password, requiredGroupMembership, currentForm); + return CompleteAuthorization(session, password, requiredGroupMembership, currentForm); } /// @@ -281,7 +282,7 @@ namespace Users.Entities /// /// /// true = authorized - public virtual bool AuthorizeFullName(string fullName, string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm) + public virtual bool AuthorizeFullName(ISession session, string fullName, string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm) { if (FullName.ToLower() != fullName.ToLower()) { @@ -289,7 +290,7 @@ namespace Users.Entities return false; } - return CompleteAuthorization(password, requiredGroupMembership, currentForm); + return CompleteAuthorization(session, password, requiredGroupMembership, currentForm); } /// @@ -298,7 +299,7 @@ namespace Users.Entities /// Password /// Required group membership /// true = authorized - bool CompleteAuthorization(string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm) + bool CompleteAuthorization(ISession session, string password, GID[] requiredGroupMembership, System.Windows.Forms.Form currentForm) { if (!IsMemberOf(requiredGroupMembership) || !IsCorrectPassword(password)) { @@ -309,7 +310,7 @@ namespace Users.Entities if (IsPasswordExpired()) { /// Password expired => User has to change the password - if (new PasswordChangeDlg(UserName).ShowDialog() != System.Windows.Forms.DialogResult.OK) + if (new PasswordChangeDlg(session, UserName).ShowDialog() != System.Windows.Forms.DialogResult.OK) { /// User did not change the password => reject authorization return false; @@ -370,122 +371,58 @@ namespace Users.Entities return user; } - - /// - /// Returns a 'User' with a given username from an ARBITRARY database. - /// - /// User name for the query - /// reference to a 'User' (if it exists) or null - public static User LoadUserByName(string userName, DBSettings dbSettings) - { - if (dbSettings == null || string.IsNullOrEmpty(dbSettings.ConnectionString)) return null; - - DB.DbType = dbSettings.DbType; - DB.ConnectionString = dbSettings.ConnectionString; - return LoadUserByName(userName); - } - /// /// Returns a 'User' with a given username from the users database. /// /// User name for the query /// reference to a 'User' (if it exists) or null - public static User LoadUserByName(string userName) + public static User LoadUserByName(ISession session, string userName) { - IList listOfUsers = DB.CreateSession() - .QueryOver() - .Where(x => (x.UserName == userName)) - .List(); + var listOfUsers = session.QueryOver() + .Where(x => (x.UserName == userName)) + .List(); return (listOfUsers.Count > 0) ? listOfUsers[0] : null; } - - /// - /// Returns a 'User' with a given full name from an ARBITRARY database. - /// - /// Full name for the query - /// reference to a 'User' (if it exists) or null - public static User LoadUserByFullName(string fullName, DBSettings dbSettings) - { - if (dbSettings == null || string.IsNullOrEmpty(dbSettings.ConnectionString)) return null; - - DB.DbType = dbSettings.DbType; - DB.ConnectionString = dbSettings.ConnectionString; - return LoadUserByFullName(fullName); - } - /// /// Returns a 'User' with a given full name from the users database. /// /// Full name for the query /// reference to a 'User' (if it exists) or null - public static User LoadUserByFullName(string fullName) + public static User LoadUserByFullName(ISession session, string fullName) { - IList listOfUsers = DB.CreateSession() - .QueryOver() - .Where(x => (x.FullName == fullName)) - .List(); + var listOfUsers = session.QueryOver() + .Where(x => (x.FullName == fullName)) + .List(); return (listOfUsers.Count > 0) ? listOfUsers[0] : null; } - - /// - /// Returns a 'User' with a given username from an ARBITRARY database. - /// - /// User ID number for the query - /// reference to a 'User' (if it exists) or null - public static User LoadUserByNumber(int number, DBSettings dbSettings) - { - if (dbSettings == null || string.IsNullOrEmpty(dbSettings.ConnectionString)) return null; - - DB.DbType = dbSettings.DbType; - DB.ConnectionString = dbSettings.ConnectionString; - return LoadUserByNumber(number); - } - /// /// Returns a 'User' with a given username from the users database. /// /// User ID number for the query /// reference to a 'User' (if it exists) or null - public static User LoadUserByNumber(int number) + public static User LoadUserByNumber(ISession session, int number) { - IList listOfUsers = DB.CreateSession() - .QueryOver() - .Where(x => (x.Number == number)) - .List(); + var listOfUsers = session.QueryOver() + .Where(x => (x.Number == number)) + .List(); return (listOfUsers.Count > 0) ? listOfUsers[0] : null; } - - /// - /// Returns a 'User' with a given RFID/NFC tag s/n from an ARBITRARY database. - /// - /// Tag of a user for the query - /// reference to a 'User' (if it exists) or null - public static User LoadUserByTag(string tag, DBSettings dbSettings) - { - if (dbSettings == null || string.IsNullOrEmpty(dbSettings.ConnectionString)) return null; - - DB.DbType = dbSettings.DbType; - DB.ConnectionString = dbSettings.ConnectionString; - return LoadUserByTag(tag); - } - /// /// Returns a 'User' with a given RFID/NFC tag s/n from the users database. /// /// Tag of a user for the query /// reference to a 'User' (if it exists) or null - public static User LoadUserByTag(string tag) + public static User LoadUserByTag(ISession session, string tag) { - IList listOfUsers = DB.CreateSession() - .QueryOver() - .Where(x => (x.Tag == tag)) - .List(); + var listOfUsers = session.QueryOver() + .Where(x => (x.Tag == tag)) + .List(); return (listOfUsers.Count > 0) ? listOfUsers[0] : null; } @@ -494,9 +431,9 @@ namespace Users.Entities /// /// returns an IList of all Users /// - public static IList GetAllUsers() + public static IList GetAllUsers(ISession session) { - return DB.CreateSession().QueryOver().List(); + return session.QueryOver().List(); } diff --git a/Users/Forms/EditSelectedUser.cs b/Users/Forms/EditSelectedUser.cs index 29f27e045..d8fa4ca25 100644 --- a/Users/Forms/EditSelectedUser.cs +++ b/Users/Forms/EditSelectedUser.cs @@ -225,47 +225,46 @@ namespace Users.Forms } /// - /// returns true if the username allready exists for another user + /// Returns true if the username already exists for another user /// private bool IsUserNameAlreadyTaken(string userName) { - // Have a look into all other users - IList ListOfUsers = User.GetAllUsers(); - foreach (var person in ListOfUsers) + /// Have a look on all other users + foreach (var u in User.GetAllUsers(session)) { - if (person.Id != user.Id) + if (u.Id != user.Id) { - /// Other user then the current one - if (person.UserName.ToLower() == userName.ToLower()) + // 'u' is other user then the current one + + if (u.UserName.ToLower() == userName.ToLower()) { - return true; // Name is equal = already taken + return true; /// User name is already used by another user } } } - return false; + + return false; /// User name is stil free } /// - /// returns true if the username allready exists for another user + /// Returns true if the tag already exists for another user /// private bool IsTagAlreadyTaken(string tag) { - if (string.IsNullOrEmpty(tag)) return false; /// No tag + if (string.IsNullOrEmpty(tag)) return false; - // Have a look into all other users - IList ListOfUsers = User.GetAllUsers(); - foreach (var person in ListOfUsers) + /// Have a look on all other users + foreach (var u in User.GetAllUsers(session)) { - if (person.Id != user.Id) + if (u.Id != this.user.Id) { - // Other user then the current one - if (person.Tag == tag) - { - return true; // Tag is equal = already taken - } + // 'u' is other user then the current one + + if (u.Tag == tag) return true; /// Tag is already used by another user } } - return false; + + return false; /// Tag is stil free } diff --git a/Users/Forms/LoginDlg.cs b/Users/Forms/LoginDlg.cs index d43744993..e4fe6277a 100644 --- a/Users/Forms/LoginDlg.cs +++ b/Users/Forms/LoginDlg.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2017-2018 Sensus Slovensko a.s. +/// Copyright (c) 2017-2023 Sensus Slovensko a.s. /// using System; using System.Windows.Forms; @@ -9,6 +9,7 @@ using GemCard; using Users.Entities; using Users.Resources; using System.Drawing; +using NHibernate; namespace Users.Forms { @@ -24,11 +25,11 @@ namespace Users.Forms public string UserName { get { return user; } } /// Private fields + ISessionFactory[] sessionFactories; string user; string password; GID[] requiredGroupMembership; Form parentForm; - bool noDatabase; Color oriBackColor; /// Smart card support, card S/N is used as user.Tag @@ -44,16 +45,17 @@ namespace Users.Forms public LoginDlg() { InitializeComponent(); - + this.sessionFactories = null; oriBackColor = BackColor; } /// /// Constructor with a predefined user. /// - public LoginDlg(string predefinedUser, Form parentForm) + public LoginDlg(ISessionFactory[] sessionFactories, string predefinedUser, Form parentForm) : this() { + this.sessionFactories = sessionFactories; user = predefinedUser; userNameTextBox.Text = predefinedUser; this.parentForm = parentForm; @@ -62,18 +64,19 @@ namespace Users.Forms /// /// Constructor with 'no Database' flag. /// - public LoginDlg(bool noDatabase) + public LoginDlg(ISessionFactory[] sessionFactories) : this() { - this.noDatabase = noDatabase; - } + this.sessionFactories = sessionFactories; + } /// /// Constructor when a specific group membership is required. /// - public LoginDlg(GID[] requiredGroupMembership, Form parentForm) + public LoginDlg(ISessionFactory[] sessionFactories, GID[] requiredGroupMembership, Form parentForm) : this() { + this.sessionFactories = sessionFactories; this.requiredGroupMembership = requiredGroupMembership; this.parentForm = parentForm; #if DEBUG @@ -86,9 +89,10 @@ namespace Users.Forms /// /// Constructor with a predefined user when a specific group membership is required. /// - public LoginDlg(string predefinedUser, GID[] requiredGroupMembership, Form parentForm) + public LoginDlg(ISessionFactory[] sessionFactories, string predefinedUser, GID[] requiredGroupMembership, Form parentForm) : this() { + this.sessionFactories = sessionFactories; user = predefinedUser; userNameTextBox.Text = predefinedUser; this.requiredGroupMembership = requiredGroupMembership; @@ -198,39 +202,47 @@ namespace Users.Forms CurrentUser.Change(new Users.Entities.User(user, 6, true), parentForm); } - if (!authorized && !noDatabase) + if (!authorized && sessionFactories != null) { DBSettings[] dbs = new DBSettings[] { CurrentUser.RemoteUsersDB, CurrentUser.LocalUsersDB }; authorizedAs = AuthorizedAs.RemoteUser; - foreach (var db in dbs) + foreach (var sf in sessionFactories) { + ISession session = null; try { + session = sf.OpenSession(); switch (Method) { case LoginMethod.UserName: default: - var usr1 = Users.Entities.User.LoadUserByName(user, db); - if (usr1 != null) { authorized = usr1.Authorize(user, password, requiredGroupMembership, parentForm); } + var usr1 = Users.Entities.User.LoadUserByName(session, user); + if (usr1 != null) { authorized = usr1.Authorize(session, user, password, requiredGroupMembership, parentForm); } break; case LoginMethod.FullName: - var usr2 = Users.Entities.User.LoadUserByFullName(user, db); - if (usr2 != null) { authorized = usr2.AuthorizeFullName(user, password, requiredGroupMembership, parentForm); } + var usr2 = Users.Entities.User.LoadUserByFullName(session, user); + if (usr2 != null) { authorized = usr2.AuthorizeFullName(session, user, password, requiredGroupMembership, parentForm); } if (authorized) { user = usr2.UserName; } break; case LoginMethod.Number: int number; if (!int.TryParse(user, out number)) break; - var usr3 = Users.Entities.User.LoadUserByNumber(number, db); - if (usr3 != null) { authorized = usr3.AuthorizeNumber(number, password, requiredGroupMembership, parentForm); } + var usr3 = Users.Entities.User.LoadUserByNumber(session, number); + if (usr3 != null) { authorized = usr3.AuthorizeNumber(session, number, password, requiredGroupMembership, parentForm); } if (authorized) { user = usr3.UserName; } break; } } - catch (Exception) { } + catch (Exception) + { + } + finally + { + if (session != null && session.IsOpen) session.Close(); + } if (authorized) break; @@ -310,29 +322,30 @@ namespace Users.Forms tag = string.Empty; } - DBSettings[] dbs = new DBSettings[] { CurrentUser.RemoteUsersDB, CurrentUser.LocalUsersDB }; bool authorized = false; AuthorizedAs authorizedAs = AuthorizedAs.RemoteUser; /// - foreach (var db in dbs) + if (sessionFactories != null) { - try + foreach (var sf in sessionFactories) { - Users.Entities.User loadedUser = Users.Entities.User.LoadUserByTag(tag, db); - if (loadedUser != null) + using (ISession session = sf.OpenSession()) { - authorized = loadedUser.AuthorizeTag(tag, requiredGroupMembership, parentForm); - - if (authorized) + Users.Entities.User loadedUser = Users.Entities.User.LoadUserByTag(session, tag); + if (loadedUser != null) { - user = loadedUser.UserName; - break; + authorized = loadedUser.AuthorizeTag(tag, requiredGroupMembership, parentForm); + + if (authorized) + { + user = loadedUser.UserName; + break; + } } } - } - catch (Exception) { } - authorizedAs = AuthorizedAs.LocalUser; + authorizedAs = AuthorizedAs.LocalUser; + } } if (authorized) diff --git a/Users/Forms/PasswordChangeDlg.cs b/Users/Forms/PasswordChangeDlg.cs index ebed6302c..f3b1c559e 100644 --- a/Users/Forms/PasswordChangeDlg.cs +++ b/Users/Forms/PasswordChangeDlg.cs @@ -1,8 +1,10 @@ /// -/// Copyright (c) 2019 Sensus Slovensko a.s. +/// Copyright (c) 2019-2023 Sensus Slovensko a.s. /// using System; using System.Windows.Forms; +using log4net; +using NHibernate; using Common; using GemCard; using Users.Resources; @@ -16,10 +18,15 @@ namespace Users.Forms /// public partial class PasswordChangeDlg : Form { + private static readonly ILog log = LogManager.GetLogger(typeof(PasswordChangeDlg)); + + ISessionFactory[] sessionFactories; + ISession session; + /// /// Constructor /// - public PasswordChangeDlg() + private PasswordChangeDlg() { InitializeComponent(); } @@ -27,10 +34,23 @@ namespace Users.Forms /// /// Constructor with a predefined user. /// - public PasswordChangeDlg(string predefinedUser) + public PasswordChangeDlg(ISessionFactory[] sessionFactories, string predefinedUser = null) { InitializeComponent(); - userNameTextBox.Text = predefinedUser; + this.sessionFactories = sessionFactories; + this.session = null; + if (predefinedUser != null) userNameTextBox.Text = predefinedUser; + } + + /// + /// Constructor with a predefined user. + /// + public PasswordChangeDlg(ISession session, string predefinedUser = null) + { + InitializeComponent(); + this.sessionFactories = null; + this.session = session; + if (predefinedUser != null) userNameTextBox.Text = predefinedUser; } @@ -97,45 +117,96 @@ namespace Users.Forms bool oldPasswdOK = false; if (!oldPasswdOK) { - DBSettings[] dbs = new DBSettings[] { CurrentUser.RemoteUsersDB, CurrentUser.LocalUsersDB }; + if (sessionFactories != null) + { + foreach (var sf in sessionFactories) + { + ISession sess = null; + try + { + sess = sf.OpenSession(); + loadedUser = Users.Entities.User.LoadUserByName(sess, userName); + if (loadedUser != null) + { + oldPasswdOK = (userName == loadedUser.UserName) && loadedUser.IsCorrectPassword(oldPassword); + } - foreach (var db in dbs) - { + if (oldPasswdOK) + { + if (loadedUser.IsPasswordUsedInPast(newPasswTextBox.Text)) + { + sess.Close(); + MessageBox.Show(Strings.Password_has_been_used_in_past, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Hand); + DialogResult = DialogResult.None; + return; + } + + /// + /// Now the password is changed in database that was used to authorize the user + /// + loadedUser.SetPassword(newPasswTextBox.Text); + sess.SaveOrUpdate(loadedUser); + sess.Flush(); + sess.Close(); + + DialogResult = DialogResult.OK; + Close(); + return; + } + } + catch (Exception) + { + log.ErrorFormat("Cannot load a list of users from a database"); + } + finally + { + if (sess != null && sess.IsOpen) sess.Close(); + } + + if (oldPasswdOK) break; + + authorizedAs = AuthorizedAs.LocalUser; + } + } + else if (session != null) + { + /// This session was already open so consequently it is not closed after loading the user try { - loadedUser = Users.Entities.User.LoadUserByName(userName, db); + loadedUser = Users.Entities.User.LoadUserByName(session, userName); if (loadedUser != null) { oldPasswdOK = (userName == loadedUser.UserName) && loadedUser.IsCorrectPassword(oldPassword); } } - catch (Exception) { } + catch (Exception) + { + log.ErrorFormat("Cannot load a list of users from a database"); + } - if (oldPasswdOK) break; + authorizedAs = AuthorizedAs.LocalUser; - authorizedAs = AuthorizedAs.LocalUser; - } - } + if (oldPasswdOK && session != null && session.IsOpen) + { + if (loadedUser.IsPasswordUsedInPast(newPasswTextBox.Text)) + { + MessageBox.Show(Strings.Password_has_been_used_in_past, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Hand); + DialogResult = DialogResult.None; + return; + } - if (oldPasswdOK && (DB.CurrentSession != null) && (DB.CurrentSession.IsOpen)) - { - if (loadedUser.IsPasswordUsedInPast(newPasswTextBox.Text)) - { - MessageBox.Show(Strings.Password_has_been_used_in_past, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Hand); - DialogResult = DialogResult.None; - return; + /// + /// Now the password is changed in database that was used to authorize the user + /// + loadedUser.SetPassword(newPasswTextBox.Text); + session.SaveOrUpdate(loadedUser); + session.Flush(); + + DialogResult = DialogResult.OK; + Close(); + return; + } } - - /// - /// Now the password is changed in database that was used to authorize the user - /// - loadedUser.SetPassword(newPasswTextBox.Text); - DB.CurrentSession.SaveOrUpdate(loadedUser); - DB.CurrentSession.Flush(); - - DialogResult = DialogResult.OK; - Close(); - return; } MessageBox.Show(Strings.Invalid_username_or_password, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Hand); diff --git a/Users/Forms/PlainLoginDlg.cs b/Users/Forms/PlainLoginDlg.cs index 53f675a3d..89197070e 100644 --- a/Users/Forms/PlainLoginDlg.cs +++ b/Users/Forms/PlainLoginDlg.cs @@ -1,5 +1,5 @@ /// -/// Copyright (c) 2022 Sensus Slovensko a.s. +/// Copyright (c) 2022-2023 Sensus Slovensko a.s. /// using System; using System.Windows.Forms; @@ -9,6 +9,7 @@ using GemCard; using Users.Entities; using Users.Resources; using System.Drawing; +using NHibernate; namespace Users.Forms { @@ -25,10 +26,10 @@ namespace Users.Forms public string FullName { get { return fullName; } } /// Private fields + ISessionFactory[] sessionFactories; string user; string password; GID[] requiredGroupMembership; - bool noDatabase; Color oriBackColor; string fullName; /// Description of the selected user @@ -52,9 +53,10 @@ namespace Users.Forms /// /// Constructor with a predefined user. /// - public PlainLoginDlg(string predefinedUser, string prompt = null) + public PlainLoginDlg(ISessionFactory[] sessionFactories, string predefinedUser, string prompt = null) : this() { + this.sessionFactories = sessionFactories; user = predefinedUser; userNameTextBox.Text = predefinedUser; if (prompt != null) Text = prompt; @@ -63,19 +65,20 @@ namespace Users.Forms /// /// Constructor with 'no Database' flag. /// - public PlainLoginDlg(bool noDatabase, string prompt = null) + public PlainLoginDlg(ISessionFactory[] sessionFactories, string prompt = null) : this() { - this.noDatabase = noDatabase; + this.sessionFactories = sessionFactories; if (prompt != null) Text = prompt; } /// /// Constructor when a specific group membership is required. /// - public PlainLoginDlg(GID[] requiredGroupMembership, string prompt = null) + public PlainLoginDlg(ISessionFactory[] sessionFactories, GID[] requiredGroupMembership, string prompt = null) : this() { + this.sessionFactories = sessionFactories; this.requiredGroupMembership = requiredGroupMembership; if (prompt != null) Text = prompt; } @@ -83,9 +86,10 @@ namespace Users.Forms /// /// Constructor with a predefined user when a specific group membership is required. /// - public PlainLoginDlg(string predefinedUser, GID[] requiredGroupMembership, string prompt = null) + public PlainLoginDlg(ISessionFactory[] sessionFactories, string predefinedUser, GID[] requiredGroupMembership, string prompt = null) : this() { + this.sessionFactories = sessionFactories; user = predefinedUser; userNameTextBox.Text = predefinedUser; this.requiredGroupMembership = requiredGroupMembership; @@ -179,15 +183,15 @@ namespace Users.Forms bool authorized = Entities.User.IsPowerUser(user, password); if (authorized) fullName = "Power user"; - if (!authorized && !noDatabase) + if (!authorized && sessionFactories != null && sessionFactories.Length > 0) { - DBSettings[] dbs = new DBSettings[] { CurrentUser.RemoteUsersDB, CurrentUser.LocalUsersDB }; - - foreach (var db in dbs) + foreach (var sf in sessionFactories) { + ISession session = null; try { - var usr1 = Users.Entities.User.LoadUserByName(user, db); + session = sf.OpenSession(); + var usr1 = Users.Entities.User.LoadUserByName(session, user); if (usr1.IsMemberOf(requiredGroupMembership) && usr1.IsCorrectPassword(password)) { @@ -196,7 +200,13 @@ namespace Users.Forms break; } } - catch (Exception) { } + catch (Exception) + { + } + finally + { + if (session != null && session.IsOpen) session.Close(); + } } } @@ -263,25 +273,36 @@ namespace Users.Forms bool authorized = false; AuthorizedAs authorizedAs = AuthorizedAs.RemoteUser; /// - foreach (var db in dbs) + if (sessionFactories != null) { - try + foreach (var sf in sessionFactories) { - Users.Entities.User loadedUser = Users.Entities.User.LoadUserByTag(tag, db); - if (loadedUser != null) + ISession session = null; + try { - authorized = (tag == loadedUser.Tag && loadedUser.IsMemberOf(requiredGroupMembership)); - - if (authorized) + session = sf.OpenSession(); + Users.Entities.User loadedUser = Users.Entities.User.LoadUserByTag(session, tag); + if (loadedUser != null) { - user = loadedUser.UserName; - break; + authorized = (tag == loadedUser.Tag && loadedUser.IsMemberOf(requiredGroupMembership)); + + if (authorized) + { + user = loadedUser.UserName; + break; + } } } - } - catch (Exception) { } + catch (Exception) + { + } + finally + { + if (session != null && session.IsOpen) session.Close(); + } - authorizedAs = AuthorizedAs.LocalUser; + authorizedAs = AuthorizedAs.LocalUser; + } } if (authorized) diff --git a/Users/Forms/UserManagementDlg.cs b/Users/Forms/UserManagementDlg.cs index 3794d8e17..73cb1b2fe 100644 --- a/Users/Forms/UserManagementDlg.cs +++ b/Users/Forms/UserManagementDlg.cs @@ -238,6 +238,8 @@ namespace Users.Forms IList remoteUsers; IList remoteGroups; ITransaction transaction = null; + ISession remoteSession = null; + ISession localSession = null; try { @@ -246,7 +248,7 @@ namespace Users.Forms /// DB.DbType = CurrentUser.RemoteUsersDB.DbType; DB.ConnectionString = CurrentUser.RemoteUsersDB.ConnectionString; - ISession remoteSession = DB.CreateSession(); + remoteSession = DB.CreateSession(); remoteUsers = remoteSession.QueryOver().List(); remoteGroups = remoteSession.QueryOver().List(); @@ -255,7 +257,7 @@ namespace Users.Forms /// DB.DbType = CurrentUser.LocalUsersDB.DbType; DB.ConnectionString = CurrentUser.LocalUsersDB.ConnectionString; - ISession localSession = DB.CreateSession(); + localSession = DB.CreateSession(); transaction = localSession.BeginTransaction(); /// @@ -285,6 +287,8 @@ namespace Users.Forms } transaction.Commit(); localSession.Flush(); + localSession.Close(); + remoteSession.Close(); listOfUsers = newUsers; ListUsers(); @@ -298,6 +302,9 @@ namespace Users.Forms { if (transaction != null) transaction.Rollback(); + if (localSession != null && localSession.IsOpen) localSession.Close(); + if (remoteSession != null && remoteSession.IsOpen) remoteSession.Close(); + MessageBox.Show(Strings.Copying_remote_users_failed, Strings.Confirmation, MessageBoxButtons.OK,