/// /// Copyright (c) 2013-2019 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 Config.Entities; using TBF.Resources; using TBF.UiBridge; using TBF.UI.Shared; 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 BenchControlPanel BenchControlPanel; public ProcedureInfo SelectedProcedure; public Procedure CurrentProcedure; public bool IsShutdownDisabled; public bool IsShutdownPCAfterClosingTbf; /// /// 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, Logs, 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 logsTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Logs); } #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, Config.Data.CurrentBench.BenchName, Config.Data.CurrentBench.IsRealBench ? "" : Strings._offline); /// /// Customize menu items /// #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 #if NO_GRAPHS graphsToolStripMenuItem.Visible = false; #else graphsToolStripMenuItem.Text = Strings.Graphs; #endif usersTSMenuItem.Visible = Users.GlobalData.CurrentUser.IsMemberOf(Users.Grp.GID.Administrators) || Users.GlobalData.CurrentUser.IsMemberOf(Users.Grp.GID.HeadOfLab); upgradeTSMenuItem.Visible = Users.GlobalData.CurrentUser.IsMemberOf(Users.Grp.GID.Administrators) && Users.GlobalData.CurrentUser.IsPowerUser(); #if IPERL iPerlHeadsToolStripMenuItem.Visible = true; iPerlHeadsToolStripMenuItem.Enabled = false; #else iPerlHeadsToolStripMenuItem.Visible = false; #endif IsShutdownDisabled = true; IsShutdownPCAfterClosingTbf = false; BenchControl.StateMachine.MachineState = Config.Data.CurrentBench.IsRealBench ? BenchControl.MachineState.StartingUp : BenchControl.MachineState.Disabled; /// if (BenchControl.StateMachine.MachineState == BenchControl.MachineState.StartingUp) { try { /// Load components, initialize the control board, etc. BenchControl.StateMachine.InitializeBoardEtc(ctrlBrdComponent); /// Check remote and local configuration DB compatibility string msg; BenchControl.GenericDevices.IBenchInfo benchInfo = BenchControl.Sequences.ProcessData.BenchInfo; RemoteDBUse remoteDbUse = (benchInfo != null) ? benchInfo.RemoteDBUse : RemoteDBUse.LocalDBOnly; log.FatalFormat("RemoteDbUse = {0}", remoteDbUse); if ((remoteDbUse != RemoteDBUse.LocalDBOnly) && !BenchControl.StateMachine.IsRemoteDBCompatible(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) { BenchControl.StateMachine.MachineState = BenchControl.MachineState.FailedToStart; string errMsg; if (string.IsNullOrEmpty(BenchControl.TbfComponents.CurrentlyLoadedComponentName)) { errMsg = exc.Message; } else { errMsg = string.Format(Strings.Failed_to_initialize_component_0_1_2, BenchControl.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.BenchControl.StateMachine.MachineState == TBF.BenchControl.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 = BenchControl.StateMachine.InitializeDevices(); 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.BenchControl.StateMachine.MachineState = TBF.BenchControl.MachineState.FailedToStart; form.CloseForm(null, new EventArgs()); formThread.Join(); string errMsg = string.Format(Strings.Failed_to_initialize_device_0_1_2, BenchControl.StateMachine.CurrentlyInitializedDeviceName, 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.LastProcedureDB); rightHorizSplitContainer.SplitterDistance = Program.LocalSettings.RightPaneHorizSplitterDistance; topVerticalSplitContainer.SplitterDistance = Program.LocalSettings.TopPaneVerticalSplitterDistance; /// Initialize bench control user interface(s) BenchControlPanel = new BenchControlPanel(); BenchControlPanel.BalancesCount = TBF.BenchControl.MettlerToledo.Standard.BalanceDev.BalancesCount + TBF.BenchControl.MettlerToledo.Multi.BalanceDev.BalancesCount + TBF.BenchControl.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' UpdateUser(); mainTabControl.SelectTab((int)MainTabPageId.Hydraulics); if (TBF.BenchControl.StateMachine.MachineState == TBF.BenchControl.MachineState.StartingUp) { BenchControl.StateMachine.Start(); log.Info("Test bench started"); } else if (TBF.BenchControl.StateMachine.MachineState == TBF.BenchControl.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 /// 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 = args.StateChangedMsg; } void OnTestProgress(object sender, UiBridge.TestProgressEventArgs args) { mainProgressBar.Value = (int)(100.499f * args.OveralProgress); } void OnProcedureSelected(object sender, UiBridge.ProcedureSelectedEventArgs args) { mainProgressBar.Value = 0; } /// /// 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); iPerlHeadsToolStripMenuItem.Enabled = ((args.Flags & ButtonsEtc.ProcedureCmbBoxEn) != 0); 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.GlobalData.CurrentUser.UserName, (Users.GlobalData.AuthorizedAs == Users.Entities.AuthorizedAs.PowerUser) ? "(S)" : ((Users.GlobalData.AuthorizedAs == Users.Entities.AuthorizedAs.LocalUser) ? "(L)" : "(R)")); } 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) { //BenchControl.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 benchConditionsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Conditions.ConditionsDlg().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 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 = Config.Data.CurrentBench.ProceduresDBSettings.ConnectionString; Users.DB.DbType = Config.Data.CurrentBench.ProceduresDBSettings.DbType; #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); #else Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(Users.DB.CreateSession(), false); #endif dlg.ShowDialog(); } 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(Users.GlobalData.GetCurrentUserName()).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) { BenchControl.GenericDevices.IBenchInfo benchInfo = BenchControl.Sequences.ProcessData.BenchInfo; RemoteDBUse remoteDbUse = (benchInfo != null) ? benchInfo.RemoteDBUse : RemoteDBUse.LocalDBOnly; Users.Entities.DBKind[] dBase; string[] signature; /// switch (remoteDbUse) { default: case RemoteDBUse.LocalDBOnly: dBase = new Users.Entities.DBKind[] { Users.Entities.DBKind.Config }; signature = new string[] { "" }; break; case RemoteDBUse.RemoteDBOnly: dBase = new Users.Entities.DBKind[] { Users.Entities.DBKind.RemoteConfig }; signature = new string[] { "R" }; break; case RemoteDBUse.BothDBsLocalFirst: dBase = new Users.Entities.DBKind[] { Users.Entities.DBKind.Config, Users.Entities.DBKind.RemoteConfig }; signature = new string[] { "L", "R" }; break; case RemoteDBUse.BothDBsRemoteFirst: dBase = new Users.Entities.DBKind[] { Users.Entities.DBKind.RemoteConfig, Users.Entities.DBKind.Config }; signature = new string[] { "R", "L" }; break; } if (procedureComboBox.Enabled) { bool procedureSet = false; procedureComboBox.Items.Clear(); IList allProcedures = new List(); for (int i = 0; i < dBase.Length; i++) { IList procedures = Config.FluentCommon.CreateSession(dBase[i]) .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 ((procedureNameToSelect == proc.Name) && !procedureSet) { procedureComboBox.Text = itemText; SelectedProcedure = new ProcedureInfo(procedureNameToSelect, dBase[i]); procedureSet = true; } } } if (!procedureSet) { if (allProcedures.Count > 0) { procedureComboBox.Text = string.Format("{0}{1}{2}", allProcedures[0].ItemNr + 1, ProcSeparator, allProcedures[0].Name); Users.Entities.DBKind dbKind = ((remoteDbUse == RemoteDBUse.BothDBsRemoteFirst) || (remoteDbUse == RemoteDBUse.RemoteDBOnly)) ? Users.Entities.DBKind.RemoteConfig : Users.Entities.DBKind.Config; SelectedProcedure = new ProcedureInfo(allProcedures[0].Name, dbKind); procedureSet = true; } else { procedureComboBox.Text = string.Empty; SelectedProcedure = null; } } ProceduresUpdated = false; if (SelectedProcedure != null) BenchControlPanel.ReloadTests(); } else { ProceduresUpdated = true; } } private void procedureComboBox_SelectedIndexChanged(object sender, EventArgs e) { int startFrom; Users.Entities.DBKind dbKind; if (!string.IsNullOrEmpty(procedureComboBox.Text) && (procedureComboBox.Text[0] == 'L' || procedureComboBox.Text[0] == 'R')) { startFrom = 1; dbKind = (procedureComboBox.Text[0] == 'L') ? Users.Entities.DBKind.Config : Users.Entities.DBKind.RemoteConfig; } else { startFrom = 0; dbKind = Users.Entities.DBKind.Config; } 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, dbKind); } public void UpdateProcedure(int procedureNr, string procedureName, Users.Entities.DBKind dbKind) { SelectedProcedure = new ProcedureInfo(procedureName, dbKind); 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.LastProcedureDB = dbKind; 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.BenchControl.StateMachine.MachineState == TBF.BenchControl.MachineState.Undefined || TBF.BenchControl.StateMachine.MachineState == TBF.BenchControl.MachineState.Disabled || TBF.BenchControl.StateMachine.MachineState == TBF.BenchControl.MachineState.FailedToStart || TBF.BenchControl.StateMachine.MachineState == TBF.BenchControl.MachineState.Off) { /// /// StateMachine is not running --> Shutdown immediately without displaying a message box /// if (closingTbfMessageForm != null) closingTbfMessageForm.CloseForm(this, null); return true; } if (TBF.BenchControl.StateMachine.MachineState == TBF.BenchControl.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().Show(); } private void iPerlHeadsToolStripMenuItem_Click(object sender, EventArgs e) { new BenchControl.TestMethods.iPerlCommunication.iPerlCommunicationForm(true).ShowDialog(); } private void statusStrip1_DoubleClick(object sender, EventArgs e) { #if TURA_IPERL || TURA_IPERL_NEW || TURA_SPECIAL Users.Grp.GID[] reqGrpMembership = new Users.Grp.GID[] { Users.Grp.GID.Testers, Users.Grp.GID.TestingSpecialists, Users.Grp.GID.Metrologists, Users.Grp.GID.HeadOfLab }; #else Users.Grp.GID[] reqGrpMembership = null; #endif if (new Users.Forms.LoginDlg(reqGrpMembership).ShowDialog() == DialogResult.OK) { UpdateUser(); } } private void clearCountersToolStripMenuItem_Click(object sender, EventArgs e) { Users.Grp.GID[] reqGrpMembership = new Users.Grp.GID[] { Users.Grp.GID.TestingSpecialists, Users.Grp.GID.Metrologists, Users.Grp.GID.HeadOfLab, Users.Grp.GID.Administrators, }; if (new Users.Forms.LoginDlg(reqGrpMembership).ShowDialog() == DialogResult.OK) { if ((Program.LocalSettings != null) && (Program.LocalSettings.Counters != null)) { for (int i = 0; i < Program.LocalSettings.Counters.Length; i++) { Program.LocalSettings.Counters[i] = 0; } } } } /// /// Configuration database export (UI) /// void BackupConfiguration() { string connectionString = Config.Data.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 = Config.Data.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); /// TODO: Use password try { System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = @"C:\xampp\mysql\bin\mysqldump"; proc.StartInfo.Arguments = string.Format("--user {0} --quick --default-character-set=utf8 {2} -r {3}", userName, password, databaseName, outputFileName); proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; //proc.StartInfo.Verb = "runas"; /// To run mysqldump.exe as administrator proc.Start(); proc.WaitForExit(); 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; } } } }