/// /// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Threading; using System.Windows.Forms; using log4net; using Common; using Config.Entities; using TBF.Resources; using TBF.UiBridge; using TBF.UI.Shared; using NHibernate; namespace TBF.UI { /// /// Main program window /// public partial class MainWnd : Form { 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; public ProcedureInfo SelectedProcedure; public Procedure CurrentProcedure; 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 /// Shared.EmergencyStopForm emergencyStopModelessDlg; /// /// This dialog is shown when TBF program is shutting down /// Shared.ModelessActivityForm closingTbfMessageForm; TestProgressControls testProgressControls; /// /// Set when procedures are updated while the ProceduresComboBox is disabled (i.e. during a test). /// Reset when the ProceduresComboBox list of items is successfully reloaded in ReloadProcedures(). /// This flag is tested when ProcedureComboBox is being enabled in OnButtonsEtc(), /// optionaly ReloadProcedures() is called. /// public bool ProceduresUpdated = false; /// /// MainTabPage ID-s /// The order of TabPages in this enum must be the same as the order /// of their additions into the mainTabControl in MainWnd.Designer.cs /// TODO: Find a better way /// public enum MainTabPageId { Invalid = -1, Hydraulics = 0, Process, Insert, Results, Graphs, Events, Calendar, Camera, TabPagesCount } /// /// Event handlers switching between tab pages /// private void homeTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Hydraulics); } private void processTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Process); } private void resultsTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Results); } private void graphsToolStripMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Graphs); } private void eventsTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Events); } private void calendarTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Calendar); } #if CAMERA private System.Windows.Forms.ToolStripMenuItem cameraTSMItem; private void cameraTSMItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Camera); } #endif /// /// Constructor /// public MainWnd() { InitializeComponent(); Text = string.Format("Test Bench Framework ver. {0} - {1}{2}", Program.Version, TBF.DB.CurrentBench.BenchName, TBF.DB.CurrentBench.IsRealBench ? "" : Strings._offline); /// /// Customize menu items /// graphsToolStripMenuItem.Text = Strings.Graphs; eventLogsTSMenuItem.Text = Strings.Event_logs; calendarTSMenuItem.Text = Strings.Calendar; settingsTSMenuItem.Text = Strings.Settings; optoHeadsToolStripMenuItem.Text = Strings.Optical_heads; clearCountersToolStripMenuItem.Text = Strings.Clear_counters; helpTSMenuItem.Text = Strings.Help; #if CAMERA /// Add 'Camera' menu item cameraTSMItem = new System.Windows.Forms.ToolStripMenuItem(); cameraTSMItem.Name = "cameraTSMItem"; cameraTSMItem.Text = Strings.Camera; cameraTSMItem.Click += new System.EventHandler(this.cameraTSMItem_Click); mainMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {this.cameraTSMItem}); #endif UpdateMenuItemsVisibility(); optoHeadsToolStripMenuItem.Visible = true; optoHeadsToolStripMenuItem.Enabled = false; IsShutdownDisabled = true; IsShutdownPCAfterClosingTbf = false; Rig.StateMachine.MachineState = TBF.DB.CurrentBench.IsRealBench ? Rig.MachineState.StartingUp : Rig.MachineState.Disabled; TBF.Data.SetData(); /// if (Rig.StateMachine.MachineState == Rig.MachineState.StartingUp) { try { startupSession = TBF.DB.ConfigDBSessionFactory.OpenSession(); /// Load components, initialize the control board, etc. 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(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)); } testProgressControls = new TestProgressControls(progressFlowLayoutPanel); log.Fatal("Remote database is compatible"); } catch (Exception exc) { Rig.StateMachine.MachineState = Rig.MachineState.FailedToStart; string errMsg; if (string.IsNullOrEmpty(Rig.TbfComponents.CurrentlyLoadedComponentName)) { errMsg = exc.Message; } else { errMsg = string.Format(Strings.Failed_to_initialize_component_0_1_2, Rig.TbfComponents.CurrentlyLoadedComponentName, Environment.NewLine, exc.Message); } log.Fatal(errMsg); MessageBox.Show(errMsg, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } void Localize() { procedureGroupBox.Text = Strings.Procedure; activityGroupBox.Text = Strings.Activity; progressGroupBox.Text = Strings.Progress; } /// /// Initializes this window and its controls /// private void MainWnd_Load(object sender, EventArgs e) { Localize(); TBF.LocalSettings ls = Program.LocalSettings; WindowState = (ls.MainWndMaximized ? FormWindowState.Maximized : FormWindowState.Normal); //if (WindowState != FormWindowState.Normal) //{ // RestoreBounds = new Rectangle((ls.MainWndLeft != 0) ? ls.MainWndLeft : 75, // (ls.MainWndTop != 0) ? ls.MainWndTop : 5, // (ls.MainWndWidth > 0) ? ls.MainWndWidth : 1250, // (ls.MainWndHeight > 0) ? ls.MainWndHeight : 750); //} //else { Width = (ls.MainWndWidth > 0) ? ls.MainWndWidth : 1250; Height = (ls.MainWndHeight > 0) ? ls.MainWndHeight : 750; Left = (ls.MainWndLeft != 0) ? ls.MainWndLeft : 75; Top = (ls.MainWndTop != 0) ? ls.MainWndTop : 5; } if (TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.StartingUp) { var form = new Shared.ModelessActivityForm() { Message = Strings.Starting_system, FontFamily = "Arial", FontSize = 24, FontStyle = FontStyle.Regular, BackgroundColor = Color.OliveDrab, /// or Color.YellowGreen StartActivityHandler = true, }; Thread formThread = new Thread(() => form.ShowDialog()); formThread.Start(); try { string message = Rig.StateMachine.InitializeComponents(); form.CloseForm(null, new EventArgs()); formThread.Join(); #if !DEBUG && !MUNICH if (message != null) { MessageBox.Show(Strings.The_following_components_are_in_simulation_mode_ + Environment.NewLine + message, Strings.Warning, MessageBoxButtons.OK, MessageBoxIcon.Information); } #endif //emergencyStopModelessDlg = new Shared.EmergencyStopForm(); //emergencyStopModelessDlg.Show(); Bridge.ButtonsEtcHandler += delegate(object sndr, ButtonsEtcEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnButtonsEtc), sndr, args); } else OnButtonsEtc(sndr, args); }; Bridge.ActivityHandler += delegate(object sndr, UiBridge.ActivityEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnActivity), sndr, args); } else OnActivity(sndr, args); }; Bridge.StateChangedHandler += delegate(object sndr, UiBridge.StateChangedEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnStateChanged), sndr, args); } else OnStateChanged(sndr, args); }; Bridge.TestProgressHandler += delegate(object sndr, UiBridge.TestProgressEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnTestProgress), sndr, args); } else OnTestProgress(sndr, args); }; Bridge.ProcedureSelectedHandler += delegate(object sndr, UiBridge.ProcedureSelectedEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnProcedureSelected), sndr, args); } else OnProcedureSelected(sndr, args); }; Bridge.SaveSettingsHandler += delegate(object sndr, UiBridge.SaveSettingsEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnSaveSettings), sndr, args); } else OnSaveSettings(sndr, args); }; } catch (Exception exc) { TBF.Rig.StateMachine.MachineState = TBF.Rig.MachineState.FailedToStart; form.CloseForm(null, new EventArgs()); formThread.Join(); string errMsg = string.Format(Strings.Failed_to_initialize_device_0_1_2, Rig.StateMachine.CurrentlyInitializedComponentName, Environment.NewLine, exc.Message); log.Fatal(errMsg); MessageBox.Show(errMsg, Strings.Error, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); } } procedureComboBox.Text = string.Format("{0}{1}{2}", Program.LocalSettings.LastProcedureNr, ProcSeparator, Program.LocalSettings.LastProcedureName); SelectedProcedure = new ProcedureInfo(Program.LocalSettings.LastProcedureName, Program.LocalSettings.LastProcedureIsRemote); rightHorizSplitContainer.SplitterDistance = Program.LocalSettings.RightPaneHorizSplitterDistance; topVerticalSplitContainer.SplitterDistance = Program.LocalSettings.TopPaneVerticalSplitterDistance; /// Initialize bench control user interface(s) BenchControlPanel = new BenchControlPanel(); BenchControlPanel.BalancesCount = TBF.Rig.MettlerToledo.Standard.BalanceDev.BalancesCount + TBF.Rig.MettlerToledo.Multi.BalanceDev.BalancesCount + TBF.Rig.Various.TankWithLevelMsrmnt.Tank.TanksCount; new System.ComponentModel.ComponentResourceManager(typeof(MainWnd)).ApplyResources(BenchControlPanel, "benchControlPanel"); BenchControlPanel.Name = "benchControlPanel"; rightHorizSplitContainer.Panel2.Controls.Add(BenchControlPanel); ReloadProcedureComboBoxItems(); /// Select the initial tab page mainTabControl.SelectTab((int)MainTabPageId.Process); /// This is to load the 'Process screen' mainTabControl.SelectTab((int)MainTabPageId.Calendar); /// This is to load the 'Calendar screen' UpdateUser(); mainTabControl.SelectTab((int)MainTabPageId.Hydraulics); if (TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.StartingUp) { /// /// Populate calendar with calendar events from components /// var calEvents = new List(); foreach (var cmpnt in TBF.Rig.StateMachine.Components) { var cmpntWithEvents = cmpnt as TBF.Rig.GenericDevices.IHasCalendarEvents; if (cmpntWithEvents != null) { foreach (var evnt in cmpntWithEvents.GetCalendarEvents()) calEvents.Add(evnt); } } calendarTabPageCtrl.StartCalendar(calEvents, startupSession); if (startupSession != null && startupSession.IsOpen) startupSession.Close(); Rig.StateMachine.Start(); log.Info("Test bench started"); } else if (TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.FailedToStart) { BenchControlPanel.OnButtonsEtc(null, new ButtonsEtcEventArgs(ButtonsEtc.None)); MessageBox.Show(Strings.Bench_is_not_running, Strings.Warning, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); } } /// /// Pass any pressed keys to the Bench control panel. /// Note that MainWnd.KeyPreview must be set to true. /// private void MainWnd_KeyPress(object sender, KeyPressEventArgs e) { #if BADGER_MALA_TRAT || BADGER_STREDNA_TRAT || BADGER_VELKA_TRAT || GENESIS || CEVAK_200 || TURA_SPECIAL || GELSENWASSER /// Do nothing = do not process keys #else if (BenchControlPanel != null && BenchControlPanel.ProcessKey(e.KeyChar)) { e.Handled = true; log.WarnFormat("'{0}' key pressed, handled by BenchControlPanel", e.KeyChar); } else { log.WarnFormat("'{0}' key pressed, not handled", e.KeyChar); } #endif } /// /// Invoked from the UiBridge to update the activity label. /// void OnActivity(object sender, UiBridge.ActivityEventArgs args) { switch (args.Cmd) { case ActivityEventArgs.Update.Activity: activityLabel.Text = args.Activity; if (string.IsNullOrEmpty(messageLabel.Text)) messageLabel.ForeColor = Color.Black; break; case ActivityEventArgs.Update.Message: messageLabel.Text = args.Message; if (args.ErrorMsg) messageLabel.ForeColor = Color.Red; else messageLabel.ForeColor = Color.Black; break; default: activityLabel.Text = args.Activity; messageLabel.Text = args.Message; if (args.ErrorMsg) messageLabel.ForeColor = Color.Red; else messageLabel.ForeColor = Color.Black; break; } } /// /// Invoked from the UiBridge to update the current state status bar item. /// void OnStateChanged(object sender, StateChangedEventArgs args) { activityStatusLabel.Text = string.Format("{0}: {1}, {2}", TBF.Resources.Strings.Batch, TBF.Rig.Sequences.ProcessData.BatchNr, args.StateChangedMsg); } void OnTestProgress(object sender, UiBridge.TestProgressEventArgs args) { if (TBF.Rig.Sequences.ProcessData.BatchRslts != null) { var b = TBF.Rig.Sequences.ProcessData.BatchRslts.Batch; if (b != null && b.EndTime > b.StartTime) { progressGroupBox.Text = string.Format("{0} @ {1}", Strings.End, b.EndTime.ToShortTimeString()); } else { progressGroupBox.Text = Strings.Progress; } } else { progressGroupBox.Text = Strings.Progress; } mainProgressBar.Value = (int)(100.499f * args.OveralProgress); } void OnProcedureSelected(object sender, UiBridge.ProcedureSelectedEventArgs args) { mainProgressBar.Value = 0; if (TBF.Rig.Sequences.ProcessData.BatchRslts != null) { var b = TBF.Rig.Sequences.ProcessData.BatchRslts.Batch; if (b != null && b.EndTime > b.StartTime) { progressGroupBox.Text = string.Format("{0} @ {1}", Strings.End, b.EndTime.ToShortTimeString()); } } } /// /// This handler is onvoked when state of buttons changes /// /// /// void OnButtonsEtc(object sender, UiBridge.ButtonsEtcEventArgs args) { if ((args.Flags & ButtonsEtc.Shutdown) != 0) { /// /// TBF program is shutting down and the state machine was proparly stopped /// UI2Settings(); if (closingTbfMessageForm != null) closingTbfMessageForm.CloseForm(this, null); if (IsShutdownPCAfterClosingTbf) { var psi = new System.Diagnostics.ProcessStartInfo("shutdown", "/s /t 0"); psi.CreateNoWindow = true; psi.UseShellExecute = false; System.Diagnostics.Process.Start(psi); } Close(); return; } if (((args.Flags & ButtonsEtc.ShowBenchEmpty) != 0) || ((args.Flags & ButtonsEtc.ShowBenchFilled) != 0)) { return; } procedureComboBox.Enabled = ((args.Flags & ButtonsEtc.ProcedureCmbBoxEn) != 0); optoHeadsToolStripMenuItem.Enabled = ((args.Flags & ButtonsEtc.ProcedureCmbBoxEn) != 0); if (procedureComboBox.Enabled) progressGroupBox.Text = Strings.Progress; if (procedureComboBox.Enabled && ProceduresUpdated) { ReloadProcedureComboBoxItems(); } IsShutdownDisabled = ((args.Flags & ButtonsEtc.ProcedureCmbBoxEn) == 0); } void OnSaveSettings(object sender, SaveSettingsEventArgs args) { if (Program.LocalSettings != null) Program.LocalSettings.Save(); } public void UpdateUser() { userInfoStatusLabel.Text = string.Format("{0}: {1}{2}, ", Strings.User, Users.CurrentUser.UserName(), (Users.CurrentUser.AuthorizedAs == Common.AuthorizedAs.PowerUser) ? "(S)" : ((Users.CurrentUser.AuthorizedAs == Common.AuthorizedAs.LocalUser) ? "(L)" : "(R)")); UpdateMenuItemsVisibility(); } void UpdateMenuItemsVisibility() { usersTSMenuItem.Visible = Users.CurrentUser.IsMemberOf(Common.GID.Administrators) || Users.CurrentUser.IsMemberOf(Common.GID.HeadOfLab); databaseSettingsTSMenuItem.Visible = Users.CurrentUser.IsMemberOf(Common.GID.Administrators) && Users.CurrentUser.IsPowerUser(); upgradeTSMenuItem.Visible = Users.CurrentUser.IsMemberOf(Common.GID.Administrators) && Users.CurrentUser.IsPowerUser(); clearCountersToolStripMenuItem.Visible = Users.CurrentUser.IsMemberOf(Common.GID.Administrators) || Users.CurrentUser.IsMemberOf(Common.GID.HeadOfLab) || Users.CurrentUser.IsMemberOf(Common.GID.TestingSpecialists) || Users.CurrentUser.IsMemberOf(Common.GID.Metrologists); } public void UpdateStatusP(string statusPStr) { statusPStatusLabel.Text = string.Format("S={0} , ", statusPStr); /// TODO: Resolve exception } public void UpdateRoute(string routeStr) { routeStatusLabel.Text = string.Format("R={0} , ", routeStr); } /// /// Stop the bench when program closes /// /// /// private void MainWnd_FormClosed(object sender, FormClosedEventArgs e) { //Rig.StateMachine.Stop(); } private void benchComponentsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Components.ComponentsManagerDlg().ShowDialog(); Cursor = Cursors.Default; } private void benchPathsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Paths.PathsDlg().ShowDialog(); Cursor = Cursors.Default; } private void benchTransitionsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Transitions.TransitionsDlg().ShowDialog(); Cursor = Cursors.Default; } private void benchMetrologyTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Metrology.MetrologyDlg().ShowDialog(); Cursor = Cursors.Default; } private void benchUncertaintyTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Uncertainties.UncertaintiesDlg().ShowDialog(); Cursor = Cursors.Default; } private void benchTestProfilesTSMItem_Click(object s, EventArgs e){ Cursor = Cursors.WaitCursor; new TBF.UI.Bench.TestProfiles.TestProfilesDlg().ShowDialog(); Cursor = Cursors.Default; } private void proceduresTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Procedures.ProceduresDlg().ShowDialog(); Cursor = Cursors.Default; } private void usersTSMItem_Click(object s, EventArgs e) { 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(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(session, false); #endif 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(); dlg.ShowDialog(); if (dlg.CurrentDBChanged) { MessageBox.Show(Strings.Currently_used_database_was_restored + Environment.NewLine + Strings.Program_must_be_closed, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information); if (TryShutdownTBF()) { /// Save settings and exit TBF UI2Settings(); Close(); } } } 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(TBF.DB.UserSessionFactories, Users.CurrentUser.UserName()).ShowDialog(); } private void aboutTSMItem_Click(object s, EventArgs e) { new TBF.UI.Help.AboutDlg().ShowDialog(); } /// /// Read the database and re-initialize procedureComboBox items. /// Try to preserve the original selection. /// public void ReloadProcedureComboBoxItems() { int separPos = procedureComboBox.Text.IndexOf(ProcSeparator); string procName = (separPos >= 0) ? procedureComboBox.Text.Substring(separPos + ProcSeparator.Length) : string.Empty; ReloadProcedureComboBoxItems(procName); } public void ReloadProcedureComboBoxItems(string procedureNameToSelect) { Rig.GenericDevices.IBenchInfo benchInfo = Rig.Sequences.ProcessData.BenchInfo; RemoteDBUse remoteDbUse = (benchInfo != null) ? benchInfo.RemoteDBUse : RemoteDBUse.LocalDBOnly; ISessionFactory[] dBase; string[] signature; /// switch (remoteDbUse) { default: case RemoteDBUse.LocalDBOnly: dBase = new ISessionFactory[] { TBF.DB.ConfigDBSessionFactory }; signature = new string[] { "" }; break; case RemoteDBUse.RemoteDBOnly: dBase = new ISessionFactory[] { TBF.DB.SharedDBSessionFactory }; signature = new string[] { "R" }; break; case RemoteDBUse.BothDBsLocalFirst: dBase = new ISessionFactory[] { TBF.DB.ConfigDBSessionFactory, TBF.DB.SharedDBSessionFactory }; signature = new string[] { "L", "R" }; break; case RemoteDBUse.BothDBsRemoteFirst: dBase = new ISessionFactory[] { TBF.DB.SharedDBSessionFactory, TBF.DB.ConfigDBSessionFactory }; signature = new string[] { "R", "L" }; break; } if (procedureComboBox.Enabled) { bool procedureSet = false; procedureComboBox.Items.Clear(); ProcedureNrs.Clear(); for (int i = 0; i < dBase.Length; i++) { if (dBase[i] != null) { var session = dBase[i].OpenSession(); var procedures = session.QueryOver() .Where(x => (x.ProcedureState == ProcedureState.Active)) .OrderBy(x => x.ItemNr).Asc .List(); foreach (var proc in procedures) { string itemText = string.Format("{0}{1}{2}{3}", signature[i], proc.ItemNr + 1, ProcSeparator, proc.Name); 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(); } } if (!procedureSet) { procedureComboBox.Text = string.Empty; SelectedProcedure = null; } ProceduresUpdated = false; } else { ProceduresUpdated = true; } } private void procedureComboBox_SelectedIndexChanged(object sender, EventArgs e) { int startFrom; bool isRemoteProcedure; if (!string.IsNullOrEmpty(procedureComboBox.Text) && (procedureComboBox.Text[0] == 'L' || procedureComboBox.Text[0] == 'R')) { startFrom = 1; isRemoteProcedure = (procedureComboBox.Text[0] == 'R'); } else { startFrom = 0; isRemoteProcedure = false; } int separPos = procedureComboBox.Text.IndexOf(ProcSeparator); int procNr = int.Parse(procedureComboBox.Text.Substring(startFrom, separPos)); string procName = procedureComboBox.Text.Substring(separPos + ProcSeparator.Length); UpdateProcedure(procNr, procName, isRemoteProcedure); } public void UpdateProcedure(int procedureNr, string procedureName, bool isRemoteProcedure) { SelectedProcedure = new ProcedureInfo(procedureName, isRemoteProcedure); BenchControlPanel.ReloadTests(); if (CurrentProcedure != null && CurrentProcedure.Description != null) { descriptionLabel.Text = CurrentProcedure.Description; } if (CurrentProcedure != null && testProgressControls != null) { testProgressControls.ProcedureSelectedInUI(this, new UiBridge.ProcedureSelectedEventArgs(CurrentProcedure)); } if (!string.IsNullOrEmpty(procedureName)) { Program.LocalSettings.LastProcedureName = procedureName; Program.LocalSettings.LastProcedureIsRemote = isRemoteProcedure; Program.LocalSettings.LastProcedureNr = procedureNr; Program.LocalSettings.Save(); } } /// /// Save UI settings to Program.LocalSettings and save them to a file. /// UI settings are: /// MainWnd size and location and splitter distances. /// void UI2Settings() { /// Obtain MainWnd dimensions, etc. bool isMaximized = (WindowState == FormWindowState.Maximized); int left = (WindowState == FormWindowState.Normal) ? Location.X : RestoreBounds.Left; int top = (WindowState == FormWindowState.Normal) ? Location.Y : RestoreBounds.Top; int width = (WindowState == FormWindowState.Normal) ? Size.Width : RestoreBounds.Width; int height = (WindowState == FormWindowState.Normal) ? Size.Height : RestoreBounds.Height; int sd1 = rightHorizSplitContainer.SplitterDistance; int sd2 = topVerticalSplitContainer.SplitterDistance; LocalSettings ls = Program.LocalSettings; if (ls != null && (ls.MainWndMaximized != isMaximized || ls.MainWndLeft != left || ls.MainWndTop != top || ls.MainWndWidth != width || ls.MainWndHeight != height || ls.RightPaneHorizSplitterDistance != sd1 || ls.TopPaneVerticalSplitterDistance != sd2)) { /// At least one MainWnd dimension differs => Update local settings and save them ls.MainWndMaximized = isMaximized; ls.MainWndLeft = left; ls.MainWndTop = top; ls.MainWndWidth = width; ls.MainWndHeight = height; ls.RightPaneHorizSplitterDistance = sd1; ls.TopPaneVerticalSplitterDistance = sd2; ls.Save(); } } bool TryShutdownTBF() { if (TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.Undefined || TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.Disabled || TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.FailedToStart || TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.Off) { /// /// StateMachine is not running --> Shutdown immediately without displaying a message box /// if (closingTbfMessageForm != null) closingTbfMessageForm.CloseForm(this, null); return true; } if (TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.ShuttingDown) { /// /// Already shutting down --> Prevent a new shutdown without displaying a message box /// return false; } /// Save emergency stop form state bool oriEmgStopState = false; if (emergencyStopModelessDlg != null) { oriEmgStopState = emergencyStopModelessDlg.Visible; emergencyStopModelessDlg.Visible = false; } if ((messageLabel.ForeColor != Color.Red) && IsShutdownDisabled) { /// /// It is not possible to shutdown (most likely a cycle is not completed) --> Display a message and prevent shutdown now /// MessageBox.Show(Strings.Finish_the_session_please, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); if (emergencyStopModelessDlg != null) emergencyStopModelessDlg.Visible = oriEmgStopState; return false; } ClosingTbfForm closingForm = new ClosingTbfForm(); DialogResult dr = closingForm.ShowDialog(); if (dr == DialogResult.Yes) { /// /// User confirmed TBF program shutdown --> 1. Show modeless form, 2. Stop MainSeq and StateMachine, 3. Prevent TBF exit now /// IsShutdownPCAfterClosingTbf = closingForm.ShutDownPC; /// Show 'Closing_Test_Bench_Framework' modeless window in separate thread closingTbfMessageForm = new Shared.ModelessActivityForm() { Message = Strings.Closing_Test_Bench_Framework, FontFamily = "Arial", FontSize = 24, FontStyle = FontStyle.Regular, BackgroundColor = Color.PeachPuff, StartActivityHandler = true, }; Thread formThread = new Thread(() => closingTbfMessageForm.ShowDialog()); formThread.Start(); /// Stop MainSeq and StateMachine Bridge.Ui2Bench(UI2BenchCmd.Shutdown); /// Prevent TBF program exit now return false; } else { /// User aborted the shutdown --> Restore emergency stop form state and prevent shutdown now if (emergencyStopModelessDlg != null) emergencyStopModelessDlg.Visible = oriEmgStopState; return false; } } private void MainWnd_FormClosing(object sender, FormClosingEventArgs e) { if (TryShutdownTBF()) { UI2Settings(); /// Save settings and exit TBF } else { e.Cancel = true; /// Prevent TBF exit } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { if (TryShutdownTBF()) { /// Save settings and exit TBF UI2Settings(); Close(); } } private void upgradeTSMenuItem_Click(object sender, EventArgs e) { new TBF.UI.Settings.UpgradeSelectionDlg().ShowDialog(); } private void optoHeadsToolStripMenuItem_Click(object sender, EventArgs e) { new Rig.TestMethods.iPerlCommunication.iPerlCommunicationForm(true).ShowDialog(); } private void statusStrip1_DoubleClick(object sender, EventArgs e) { #if TURA_IPERL || TURA_IPERL_NEW || TURA_SPECIAL Common.GID[] reqGrpMembership = new Common.GID[] { Common.GID.Testers, Common.GID.TestingSpecialists, Common.GID.Metrologists, Common.GID.HeadOfLab }; #else Common.GID[] reqGrpMembership = null; #endif if (new Users.Forms.LoginDlg(TBF.DB.UserSessionFactories, reqGrpMembership, this).ShowDialog() == DialogResult.OK) { UpdateUser(); } } private void clearCountersToolStripMenuItem_Click(object sender, EventArgs e) { if ((Program.LocalSettings != null) && (Program.LocalSettings.Counters != null) && MessageBox.Show("Do you really want to clear counter(s)?", Strings.Confirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) { for (int i = 0; i < Program.LocalSettings.Counters.Length; i++) { Program.LocalSettings.Counters[i] = 0; } } } /// /// Configuration database export (UI) /// void BackupConfiguration() { string connectionString = TBF.DB.CurrentBench.ProceduresDBSettings.ConnectionString; string server = Config.Utils.GetDBServer(connectionString); if ((server != "localhost") && (server != "127.0.0.1")) { MessageBox.Show(Strings.Remote_database_cannot_be_exported, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (MessageBox.Show(Strings.Do_you_want_to_back_up_configuration_qm, string.Empty, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { SaveFileDialog dlg = new SaveFileDialog(); dlg.InitialDirectory = string.Format(@"C:\TBF\DbBackups\"); dlg.FileName = string.Format(@"C:\TBF\DbBackups\{0}-{1:yyMMdd-HHmm}.sql",Config.Utils.GetDBName(connectionString), DateTime.Now); if (dlg.ShowDialog() != DialogResult.OK) return; DBExportMessageStart(Strings.Saving_configuration); bool successful = ExportDatabase(connectionString, dlg.FileName); DBExportMessageEnd(); if (!successful) MessageBox.Show(Strings.Saving_configuration_failed); } } /// /// Results database export (UI) /// void BackupResults() { string connectionString = TBF.DB.CurrentBench.WaterMetersDBSettings.ConnectionString; string server = Config.Utils.GetDBServer(connectionString); if ((server != "localhost") && (server != "127.0.0.1")) { MessageBox.Show(Strings.Remote_database_cannot_be_exported, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (MessageBox.Show(Strings.Do_you_want_to_back_up_results_qm, string.Empty, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { SaveFileDialog dlg = new SaveFileDialog(); dlg.InitialDirectory = string.Format(@"C:\TBF\DbBackups\"); dlg.FileName = string.Format(@"C:\TBF\DbBackups\{0}-{1:yyMMdd-HHmm}.sql", Config.Utils.GetDBName(connectionString), DateTime.Now); if (dlg.ShowDialog() != DialogResult.OK) return; DBExportMessageStart(Strings.Saving_all_results); bool successful = ExportDatabase(connectionString, dlg.FileName); DBExportMessageEnd(); if (!successful) MessageBox.Show(Strings.Saving_results_failed); } } Shared.ModelessActivityForm form; System.Threading.Thread formThread; /// void DBExportMessageStart(string message) { form = new Shared.ModelessActivityForm() { Message = message, FontFamily = "Arial", FontSize = 24, FontStyle = FontStyle.Regular, BackgroundColor = Color.RoyalBlue, }; formThread = new System.Threading.Thread(() => form.ShowDialog()); formThread.Start(); } /// void DBExportMessageEnd() { if (form != null && formThread != null) { form.CloseForm(null, new EventArgs()); formThread.Join(); } form = null; formThread = null; } /// /// Database export (functionality) /// Invokes: mysqldump --user [userName] --default-character-set=utf8 [databaseName] -r [outputFileName] /// /// DB connection string /// Output file name bool ExportDatabase(string connectionString, string outputFileName) { string databaseName = Config.Utils.GetDBName(connectionString); string userName = Config.Utils.GetDBUser(connectionString); string password = Config.Utils.GetDBPassword(connectionString); try { const string CredFileName = "tempfile"; using (TextWriter writer = new StreamWriter(CredFileName)) { writer.WriteLine("[client]"); writer.WriteLine(string.Format("password=\"{0}\"", password)); } System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = @"C:\xampp\mysql\bin\mysqldump"; proc.StartInfo.Arguments = string.Format("--defaults-file={0} --user={1} --host=localhost --protocol=tcp --port=3306 --default-character-set=utf8 --skip-triggers \"{2}\" -r {3}", CredFileName, userName, databaseName, outputFileName); proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; proc.Start(); proc.WaitForExit(); File.Delete(CredFileName); log.ErrorFormat("Database {0} exported into file {1}", databaseName, outputFileName); return true; } catch (Exception exc) { log.FatalFormat("Failed to export database {0} to file {1}: {2}", databaseName, outputFileName, exc.Message); return false; } } } }