//---------------------------------------------------------------------------- // // Copyright © 2009-2014, Intel Corporation. All rights reserved. // // File: UserInterface.cs // //---------------------------------------------------------------------------- using System; using UCT.Forms; using System.Drawing; using System.Threading; using System.Windows.Forms; using System.ComponentModel; using System.Collections.Generic; using UCT.Utils; namespace UCT.Forms { #region ENUMS public enum ConnectionState { CONNECTED = 0, DISCONNECTED }; public enum ButtonState { START = 0, CANCEL }; #endregion /// /// The main window - the GUI layer of the tool /// public partial class UserInterface : BaseForm { #region - Consts - private const string HOST_NAME = "HostName"; private const string POWER_STATE = "PowerState"; private const string OPT_IN_POLICY = "OptInPolicy"; private const string OPT_IN_STATE = "OptInState"; private const string CODE_TIMEOUT = "CodeTimeout"; private const string DISPLAY_TIMEOUT = "DisplayTimeout"; private const string DEFAULT_MONITOR = "DefaultMonitor"; private const string CODE_VERSION = "CodeVersion"; private const string VERSION_STRING = "VersionString"; private const int ENTER_KEY_CODE = 13; private const char NULL_CHAR = '\0'; #endregion #region - Members - private Dictionary allowedPowerState = new Dictionary() { {PowerState.On, new string[] {"Reset", "Off"}}, {PowerState.Hibernate, new string[] {"On"}}, {PowerState.DeepSleep, new string[] {"On", "Off", "Reset" }}, {PowerState.LightSleep, new string[] {"On", "Off", "Reset" }}, {PowerState.MasterBusReset, new string[] {"Off"}}, {PowerState.HardOff, new string[] {"On"}}, {PowerState.SoftOff, new string[] {"On"}} }; private LogicLayer _logicLayer; private ButtonState _buttonState; private bool _isLogViewerOpen; private bool _isUserChanged; public ConnectionState connectionState { set; private get; } public bool stopProgress { set; private get; } // Indicate whether to stop running the progress bar. #endregion #region - Constructors and Initalizing Methods - /// /// Default constructor /// public UserInterface() { try { InitializeComponent(); InitiateApplicationSettings(); } catch { } } /// /// Initiate the application settings such as default propertis (settings tab) or host name /// private void InitiateApplicationSettings() { try { // Set this property to true - indicate the changes done by the application _isUserChanged = false; // Set the host name tbHostName.Text = Properties.Settings.Default.HOST_NAME; //Configuration.GetInstance().Basic.AmtHost; // Load default settings LoadDefaultApplicationSettings(); _isUserChanged = true; _isLogViewerOpen = false; } catch { } } /// /// Load the application settings /// private void LoadDefaultApplicationSettings() { try { // Create log property cbCreateLog.Checked = Properties.Settings.Default.CREATE_LOG; // Log level settings if (Properties.Settings.Default.LOG_LEVEL == (uint)LogLevel.BASIC) rbBasic.Checked = true; else rbDetailed.Checked = true; // Load the graceful use cbTryGraceful.CheckState = (Properties.Settings.Default.USE_GRACFUL_SHUTDOWN_BEFORE_AMT_REBOOT) ? CheckState.Checked : CheckState.Unchecked; // Load the timeout settings nudGraceful.Value = Properties.Settings.Default.GRACFUL_SHUTDOWN_TIMEOUT; } catch { } } /// /// Init the layers of the tool (the midiator layer = the logic layer) /// public void InitMidiator() { try { _logicLayer = new LogicLayer(); _logicLayer.RegisterUI(this); _logicLayer.RegisterTargetSystem(new TargetSystem(_logicLayer)); } catch (Exception e) { WriteToLog(string.Format(Properties.Resources.EXCEPTION_OCCURED_ERROR_CODE, e.Message, e.TargetSite.ToString()), LogInteraction.Error); DisplayMessage(e.Message, Properties.Resources.OPERATION_FAILED, MessageType.ERROR); DisplayStatusBar(Properties.Resources.CANCEL_USER_CONSENT_FAILURE); } } /// /// Update the GUI with the new connection settings /// private void InitConnectionSettings() { tbHostName.Text = Configuration.BasicSettings.GetInstance().AmtHost; // Write to the log box all the connection data if (LogManager.GetInstance().GetLogContent().Count != 0) WriteToLog(LogManager.GetInstance().GetLastLine(), LogInteraction.Connection); } #endregion #region - Methods - #region POLIING METHODS /// /// Update the power state label (depend the polling event) /// /// internal void SetPowerState(PowerState pState) { if (lblPowerState.InvokeRequired) { UpdatePowerStateDelegate del = new UpdatePowerStateDelegate(SetPowerState); lblPowerState.Invoke(del, pState); } else { // Update the main power state label and the status label lblPowerState.Text = lblPowerStateStat.Text = Utilities.GetEnumDescription(pState); } } /// /// Update the opt - in state label (depend the polling event) /// /// internal void SetOptInState(OptInState state) { if (lblOptInState.InvokeRequired) { UpdateOptInStateLabel del = new UpdateOptInStateLabel(SetOptInState); lblOptInState.Invoke(del, state); } else { lblOptInState.Text = lblOptInStateStat.Text = Utilities.GetEnumDescription(state); } } #endregion #region TABS_INITIATION_METHODS /// /// Initiate the selected tab /// /// /// private void MainTab_Click(object sender, EventArgs e) { try { if (MainTab.SelectedIndex == 1)// Advanced Tab { InitAdvancedTab(!lblOptInState.Text.Equals("Unknown")); } } catch (Exception ex) { WriteToLog(string.Format(Properties.Resources.EXCEPTION_OCCURED_ERROR_CODE, ex.Message, ex.TargetSite.ToString()), LogInteraction.Error); DisplayMessage(ex.Message, Properties.Resources.OPERATION_FAILED, MessageType.ERROR); DisplayStatusBar(ex.Message); } } /// /// Initiate the statuses tab /// /// internal void InitStatisticsTab(bool known) { if (StatisticsPanel.InvokeRequired) { StatisticsPanel_D del = new StatisticsPanel_D(InitStatisticsTab); StatisticsPanel.Invoke(del, known); } else { if (known) { Dictionary dParams = _logicLayer.GetStatisticsParams(); lblHostNameStat.Text = dParams[HOST_NAME]; lblPowerStateStat.Text = dParams[POWER_STATE]; lblOptInPolicyStat.Text = dParams[OPT_IN_POLICY]; lblOptInStateStat.Text = dParams[OPT_IN_STATE]; lblOptInTimeoutStat.Text = dParams[CODE_TIMEOUT]; lblDisplayTimeoutStat.Text = dParams[DISPLAY_TIMEOUT]; lblDefaultMonitorStat.Text = dParams[DEFAULT_MONITOR]; lblFWVersionStat.Text = dParams[CODE_VERSION]; lblBuildNumber.Text = dParams[VERSION_STRING]; } else { lblHostNameStat.Text = Properties.Resources.NOT_AVAILABLE; lblPowerStateStat.Text = Properties.Resources.NOT_AVAILABLE; lblOptInPolicyStat.Text = Properties.Resources.NOT_AVAILABLE; lblOptInStateStat.Text = Properties.Resources.NOT_AVAILABLE; lblOptInTimeoutStat.Text = Properties.Resources.TIMEOUTS_NOT_AVAILABLE; lblDisplayTimeoutStat.Text = Properties.Resources.TIMEOUTS_NOT_AVAILABLE; lblDefaultMonitorStat.Text = Properties.Resources.NOT_AVAILABLE; lblFWVersionStat.Text = Properties.Resources.TIMEOUTS_NOT_AVAILABLE; lblBuildNumber.Text = Properties.Resources.TIMEOUTS_NOT_AVAILABLE; } } } /// /// Initiate the operations tab /// /// internal void InitOperationTab(bool enablePanel) { if (OperationsPanel.InvokeRequired) { OperationPanel_D del = new OperationPanel_D(InitOperationTab); OperationsPanel.Invoke(del, enablePanel); } else { OperationsPanel.Enabled = MonitorPanel.Enabled = codePanel.Enabled = TimerPanel.Enabled = enablePanel; mtbCode.Focus(); if (!enablePanel) mtbCode.Clear(); } } /// /// Initiate the advanced tab /// /// internal void InitAdvancedTab(bool connected) { if (AdvancedPanel.InvokeRequired) { AdvancePanelDelegate del = new AdvancePanelDelegate(InitAdvancedTab); AdvancedPanel.Invoke(del, connected); } else { if (connected) { AdvancedPanel.Enabled = true; cbLinkPref.SelectedIndex = 0; EnableOptIntimeoutSetting(); Enable3Displays(); //FillOperationOptions(); } else { AdvancedPanel.Enabled = false; } } } public void FillOperationOptions(PowerState pState) { if (cbPowerOperation.InvokeRequired) { UpdatePowerStateDelegate del = new UpdatePowerStateDelegate(FillOperationOptions); cbPowerOperation.Invoke(del, pState); } else { cbPowerOperation.Items.Clear(); cbPowerOperation.Items.AddRange(allowedPowerState[pState]); cbPowerOperation.SelectedIndex = 0; } } #region ADVANCED_TAB_FUNCTIONS private void ApplyDefaultScreen() { try { // Apply the settings _logicLayer.ChangeDefaultScreen((rbPrimaryScreen.Checked) ? DefaultScreen.PrimaryScreen : (rbSecondaryScreen.Checked ? DefaultScreen.SecondaryScreen :DefaultScreen.ThirdScreen)); } catch { } } private void ApplyGracfulSettings() { try { // Apply the graceful use Properties.Settings.Default.USE_GRACFUL_SHUTDOWN_BEFORE_AMT_REBOOT = cbTryGraceful.Checked; // Apply the timeout Properties.Settings.Default.GRACFUL_SHUTDOWN_TIMEOUT = Convert.ToInt32(nudGraceful.Value); // Save the settings Properties.Settings.Default.Save(); _logicLayer.WriteLog(LogLevel.BASIC, "Graceful shutdown settings were set successfully", LogInteraction.UserOperation); } catch { } } #endregion #endregion #region EVENT_HANDLER_METHODS /// /// Windows load /// /// /// private void UserInterface_Load(object sender, EventArgs e) { try { InitializeConnection(); } catch(Exception ex) { DisplayMessage(ex.Message, Properties.Resources.OPERATION_FAILED, MessageType.ERROR); } } private void InitializeConnection() { InitMidiator(); InitOperationTab(false); InitConnectionSettings(); InitStatisticsTab(lblOptInState.Text == OptInState.Unknown.ToString()); ChangeGuiToDisconnect(ConnectionState.CONNECTED); _logicLayer.SetGUIToConnect(); } /// /// Clear log button click /// /// /// private void pbClearLog_Click(object sender, EventArgs e) { rtbLogViewer.Clear(); } /// /// View log button click /// /// /// private void pbViewLog_Click(object sender, EventArgs e) { _logicLayer.ViewLog(); } /// /// Connect button click /// /// /// private void pbConnectAddress_Click(object sender, EventArgs e) { try { ConnetWithHostName(); } catch(Exception ex) { DisplayMessage(ex.Message, Properties.Resources.CONNECTION_ERROR_OCCURED, MessageType.ERROR); } } /// /// Press "Enter" on hostname textbox /// /// /// private void tbHostName_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { try { ConnetWithHostName(); } catch (Exception ex) { DisplayMessage(ex.Message, Properties.Resources.CONNECTION_ERROR_OCCURED, MessageType.ERROR); } } } /// /// Connect to another host via the main window /// private void ConnetWithHostName() { try { string prevHost = Configuration.BasicSettings.GetInstance().AmtHost; if (ValidateHost()) { Configuration.BasicSettings.GetInstance().AmtHost = tbHostName.Text; Properties.Settings.Default.HOST_NAME = tbHostName.Text; if (!_logicLayer.ChangeConnectionAddress()) { Configuration.BasicSettings.GetInstance().AmtHost = tbHostName.Text = prevHost; } tbHostName.AutoCompleteCustomSource.Add(tbHostName.Text); InitializeConnection(); } else { Configuration.BasicSettings.GetInstance().AmtHost = tbHostName.Text = prevHost; } } catch { } } /// /// Change the hostname textbox to indicate mismatch /// /// public void ChangeSecureConnectionGUI(bool isSecure) { try { if (isSecure) { tbHostName.BackColor = Color.FromArgb(255, 174, 189); certErrorDetails.PrintDetails(); certErrorDetails.Visible = false; pbCertProblem.Visible = true; } else { tbHostName.BackColor = Color.White; pbCertProblem.Visible = certErrorDetails.Visible = false; } btnEdit.Select(); } catch { } } /// /// Text change in hostname textbox /// /// /// private void tbHostName_TextChanged(object sender, EventArgs e) { ValidateHost(); } /// /// Send the User Consent code /// private void SendOptInCode() { try { _logicLayer.SendCode(uint.Parse(mtbCode.Text.Replace(" ", string.Empty))); mtbCode.ResetText(); mtbCode.Focus(); } catch { } } /// /// Start \ Cancel the consent flow /// /// /// private void btnStart_Click(object sender, EventArgs e) { try { if (_buttonState == ButtonState.START) { _logicLayer.StartConsent(); } else { CountDownTimer.consentTimer = false; _logicLayer.CancelConsent(); } } catch (Exception ex) { DisplayMessage(ex.Message, Properties.Resources.CONNECTION_ERROR_OCCURED, MessageType.ERROR); } } /// /// "View as password" checked change /// /// /// private void cbViewAsPassword_CheckedChanged(object sender, EventArgs e) { if (cbViewAsPassword.Checked) { mtbCode.PasswordChar = NULL_CHAR; mtbCode.UseSystemPasswordChar = false; } else { mtbCode.UseSystemPasswordChar = true; } } /// /// View log button click /// /// /// private void btnViewLog_Click(object sender, EventArgs e) { if (!_isLogViewerOpen) { btnViewLog.Image = Properties.Resources.Expanded; this.Height += rtbLogViewer.Height; _isLogViewerOpen = true; normalToolTip.SetToolTip(btnViewLog, "Close Log"); } else { btnViewLog.Image = Properties.Resources.Collapsed; this.Height -= rtbLogViewer.Height; _isLogViewerOpen = false; normalToolTip.SetToolTip(btnViewLog, "Open Log"); } } /// /// Disconnect\Edit button click /// /// /// private void pbConnect_Click(object sender, EventArgs e) { try { if (connectionState == ConnectionState.DISCONNECTED) { using (ConnectionSettings con = new ConnectionSettings()) { string prevHost = Configuration.BasicSettings.GetInstance().AmtHost; if (con.ShowDialog() == DialogResult.OK) { InitializeConnection(); connectionState = ConnectionState.CONNECTED; } else { Configuration.BasicSettings.GetInstance().AmtHost = tbHostName.Text = prevHost; } } } else { _logicLayer.SetApplicationToUnknown(); connectionState = ConnectionState.DISCONNECTED; ChangeGuiToDisconnect(ConnectionState.DISCONNECTED); } } catch(Exception ex) { DisplayMessage(ex.Message, Properties.Resources.CONNECTION_ERROR_OCCURED, MessageType.ERROR); } } /// /// Send code button click /// /// /// private void btnSendCode_Click(object sender, EventArgs e) { try { SendOptInCode(); } catch(Exception ex) { DisplayMessage(ex.Message, Properties.Resources.STARTING_USER_CONSENT_FAILED_ERROR_CODE, MessageType.ERROR); } } /// /// Code text box text changed event /// /// /// private void mtbCode_TextChanged(object sender, EventArgs e) { btnSendCode.Enabled = mtbCode.MaskFull; } /// /// Switch screen click /// /// /// private void btnSwitchMonitors_Click(object sender, EventArgs e) { _logicLayer.SetDefaultMonitor(); } /// /// Perform power operation click /// /// /// private void btnPowerRun_Click(object sender, EventArgs e) { try { PowerState ps = PowerState.Unknown; switch (cbPowerOperation.Text) { case "Off": ps = PowerState.SoftOff; break; case "On": ps = PowerState.On; break; case "Reset": ps = PowerState.MasterBusReset; break; } if (cbTryRebootgracefully.Checked) _logicLayer.PerformGracefulShutdown(false, false, cbPowerOperation.Text == "Reset"); else _logicLayer.PerformAMTShutDown(ps, false, false); FillOperationOptions(_logicLayer.GetPowerState()); } catch(Exception ex) { DisplayMessage(ex.Message, Properties.Resources.OPERATION_FAILED, MessageType.ERROR); } } /// /// Apply graceful shutdown settings /// private void ApplyApplicationSettings() { try { DisplayStatusBar(Properties.Resources.SETTING_OS_GRACEFUL_SHUTDOWN); ApplyGracfulSettings(); DisplayStatusBar("Graceful shutdown preferences were set successfully"); } catch { } } /// /// Cancel consent click /// /// /// private void btnCancel_Click(object sender, EventArgs e) { try { _logicLayer.CancelConsent(); } catch (Exception ex) { DisplayMessage(ex.Message, Properties.Resources.CONNECTION_ERROR_OCCURED, MessageType.ERROR); } } /// /// Apply screen settings /// /// /// private void btnApplyScreen_Click(object sender, EventArgs e) { ApplyDefaultScreen(); } /// /// Apply the log settings /// private void ApplyLogSettings() { try { DisplayStatusBar(Properties.Resources.SETTING_LOG_PREFERENCES); Properties.Settings.Default.CREATE_LOG = cbCreateLog.Checked; if (rbBasic.Checked) { Properties.Settings.Default.LOG_LEVEL = (uint)LogLevel.BASIC; } else { Properties.Settings.Default.LOG_LEVEL = (uint)LogLevel.DETAILED; } // Save the settings Properties.Settings.Default.Save(); DisplayStatusBar("Log preferences were set successfully"); } catch { } } /// /// Code text box - Key down event /// /// /// private void mtbCode_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { // The code textbox has spaces between the chars, so using the arrows keys cause the // user to press the key twice in order to enter / delete the code. // this code check if the user press one of the arrow keys and move to the next char. char[] codeArr = mtbCode.Mask.ToCharArray(); int num = mtbCode.SelectionStart; switch (e.KeyCode) { case Keys.Back: if (num > 1) { if (codeArr[num - 1].ToString() == " " && codeArr[num - 2] != '\0') { SendKeys.Send("{BACKSPACE}"); } } break; case Keys.Right: if (num < codeArr.Length - 1) { if (codeArr[num + 1].ToString() == " ") { mtbCode.Select(num + 1, 0); } } break; case Keys.Left: if (num > 0) { if (codeArr[num - 1].ToString() == " ") { mtbCode.Select(num - 1, 0); } } break; } } /// /// Handel key press event in order to allow pressing "Enter" in the code text box /// /// /// private void mtbCode_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == ENTER_KEY_CODE && mtbCode.MaskFull) { try { SendOptInCode(); } catch(Exception ex) { DisplayMessage(ex.Message, Properties.Resources.STARTING_USER_CONSENT_FAILED_ERROR_CODE, MessageType.ERROR); } } } /// /// display the certificate problem /// /// /// private void pbCertProblem_Click(object sender, EventArgs e) { try { certErrorDetails.PrintDetails(); certErrorDetails.Visible = !certErrorDetails.Visible; } catch { } } /// /// Perform wireless operation /// /// /// private void btnApplyWirelessOperations_Click(object sender, EventArgs e) { try { LinkControl link = (LinkControl)Enum.Parse(typeof(LinkControl), cbLinkPref.Text); UInt32 timeout = (UInt32)nudLinkPrefTimeout.Value; _logicLayer.SetLinkPreference(link, timeout); } catch(Exception ex) { DisplayMessage(ex.Message, Properties.Resources.OPERATION_FAILED, MessageType.ERROR); } } /// /// Try graceful before AMT reboot check change /// /// /// private void cbTryGraceful_CheckedChanged(object sender, EventArgs e) { if (_isUserChanged) { // Save the application settings ApplyApplicationSettings(); } // Enable the graceful shutdown timeout according the check box checked EnableGracefulControls(cbTryGraceful.Checked); } /// /// Enable / Disable graceful shutdown settings /// /// private void EnableGracefulControls(bool enable) { nudGraceful.Enabled = lblGracfulHeader.Enabled = enable; } /// /// Display About box /// /// /// private void linkLabelAboutUCT_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { (new AboutUCT()).ShowDialog(this); } /// /// Set the cursor to the top of the text box /// /// /// private void mtbCode_Click(object sender, EventArgs e) { if (mtbCode.Text.Trim() == string.Empty) mtbCode.Select(0, 0); } /// /// Create log - check change /// /// /// private void cbCreateLog_CheckedChanged(object sender, EventArgs e) { if (_isUserChanged) { // Save the log settings ApplyLogSettings(); } // Enable the log options EnableLogOptionsControls(cbCreateLog.Checked); } private void EnableOptIntimeoutSetting() { bool enable = _logicLayer.CheckOptInTimeoutSupport(); if (enable == false) { errorProvider2.SetIconPadding(nudTimeout, 50); errorProvider2.SetError(nudTimeout, Properties.Resources.SET_TIMEOUT_NOTSUPPRTED_ERROR); } else errorProvider2.SetError(nudTimeout, String.Empty); OptInState state = _logicLayer.CheckOptInState(); if (state != OptInState.NotStarted) enable = false; btnApplyTimeout.Enabled = enable; nudTimeout.Enabled = enable; } private void Enable3Displays() { bool enable = _logicLayer.Check3DisplaysSupport(); rbThirdScreen.Enabled = enable; if (enable == false) { errorProvider2.SetIconPadding(rbThirdScreen, -5); errorProvider2.SetError(rbThirdScreen, Properties.Resources.THIRDSCREEN_NOTSUPPORTED_ERROR); } else errorProvider2.SetError(nudTimeout, String.Empty); } /// /// Enable\Disable the log options controls /// /// private void EnableLogOptionsControls(bool enable) { label24.Enabled = rbBasic.Enabled = rbDetailed.Enabled = enable; } /// /// Log options check change /// /// /// private void rbBasic_CheckedChanged(object sender, EventArgs e) { ApplyLogSettings(); } /// /// Reset the default application settings /// /// /// private void btnResetSettings_Click(object sender, EventArgs e) { try { // Display status bar message DisplayStatusBar("Reset default settings..."); // Reset the default settings Properties.Settings.Default.GRACFUL_SHUTDOWN_TIMEOUT = 1; Properties.Settings.Default.USE_GRACFUL_SHUTDOWN_BEFORE_AMT_REBOOT = true; Properties.Settings.Default.CREATE_LOG = true; Properties.Settings.Default.LOG_LEVEL = (uint)LogLevel.DETAILED; _isUserChanged = false; // Update the GUI LoadDefaultApplicationSettings(); // Update the log DisplayStatusBar("Default settings were set successfully"); _isUserChanged = true; } catch(Exception ex) { DisplayMessage(ex.Message, Properties.Resources.OPERATION_FAILED, MessageType.ERROR); } } /// /// Value of the graceful shutdown timeout changed /// /// /// private void nudGraceful_ValueChanged(object sender, EventArgs e) { ApplyApplicationSettings(); } /// /// Enable the "try gracefully" power operation according the selected power operation /// /// /// private void cbPowerOperation_SelectedIndexChanged(object sender, EventArgs e) { cbTryRebootgracefully.Enabled = cbPowerOperation.Text != "On"; if (cbPowerOperation.Text == "On") { cbTryRebootgracefully.Checked = false; } } /// /// Enable the link preference timeout according to the selected link preference /// /// /// private void cbLinkPref_SelectedIndexChanged(object sender, EventArgs e) { nudLinkPrefTimeout.Enabled = cbLinkPref.Text == LinkControl.ME.ToString(); } /// /// Show the hepl document /// /// /// private void btnHelp_Click(object sender, EventArgs e) { Utilities.DisplayHelpDocument(this); } #endregion #region LOG_AND_STATUS_BAR /// /// Change the status bar message /// /// internal void DisplayStatusBar(string msg) { if (statusStrip.InvokeRequired) { DisplayStatusBarDelegate del = new DisplayStatusBarDelegate(DisplayStatusBar); statusStrip.Invoke(del, msg); } else { StatusBarLabel.Text = msg; } } /// /// Clear the message from the status bar /// internal void ClearStatusBar() { if (statusStrip.InvokeRequired) { ClearStatusBarDelegate del = new ClearStatusBarDelegate(ClearStatusBar); statusStrip.Invoke(del); } else { StatusBarLbl.Text = String.Empty; } } /// /// Write operation to the log /// /// /// public void WriteToLog(String line, LogInteraction interaction) { if (this.InvokeRequired) { this.Invoke(new WriteLog_D(WriteToLogViewer), new object[] { line, interaction }); } else { WriteToLogViewer(line, interaction); } } /// /// Write operation to the log textbox (colorize it) /// /// /// private void WriteToLogViewer(String line, LogInteraction interaction) { Font fnt = new Font("Verdana", 8F, FontStyle.Italic, GraphicsUnit.Point); Color color = Color.Blue; rtbLogViewer.AppendText("\n" + line); switch (interaction) { case LogInteraction.FWOperation: color = Color.Blue; break; case LogInteraction.UserOperation: color = Color.Navy; break; case LogInteraction.Error: color = Color.Red; break; case LogInteraction.Information: color = Color.Green; break; case LogInteraction.Connection: { fnt = new Font("Verdana", 8F, FontStyle.Bold, GraphicsUnit.Point); color = Color.Black; } break; } if (rtbLogViewer.Find(line, 0, rtbLogViewer.Text.Length, RichTextBoxFinds.None) >= 0) { int firstPosition = rtbLogViewer.Find(line); rtbLogViewer.SelectionStart = firstPosition; rtbLogViewer.SelectionLength = line.Length; rtbLogViewer.SelectionFont = fnt; rtbLogViewer.SelectionColor = color; } rtbLogViewer.SelectionStart = rtbLogViewer.Text.Length; rtbLogViewer.ScrollToCaret(); } #endregion #region UTILS_METHODS private void RetrieveSettings(BackgroundWorker worker, DoWorkEventArgs e, object[] obj) { try { while (!stopProgress) { if (worker.CancellationPending) { e.Cancel = true; break; } System.Threading.Thread.Sleep(500); } DialogResult = DialogResult.OK; } catch { DialogResult = DialogResult.Abort; } } public DialogResult RunProgressBar(string message, string header, bool hasCancel, bool hasSkip) { DialogResult res; using (ProgressBarWindow progressWindow = new ProgressBarWindow(new ProgressDelegate(RetrieveSettings), header, null, message, hasCancel, hasSkip, false)) { res = progressWindow.ShowDialog(this); } return res; } internal DialogResult DisplayMessage(string message, string header, MessageType type) { DialogResult result = new DialogResult(); switch (type) { case MessageType.INFO: result = AMT_SW_GUI.MessageManager.ShowMessage(message, Properties.Resources.OPERATION_INFORMATION, this); break; case MessageType.ERROR: result = AMT_SW_GUI.MessageManager.ShowErrorMessage(message, Properties.Resources.OPERATION_FAILED, this); break; case MessageType.QUESTION: result = AMT_SW_GUI.MessageManager.ShowQuestionMessage(message, Properties.Resources.QUESTION_HEADER, this); break; } return result; } internal DialogResult DisplayWarningMessage(string message, string header, MessageBoxButtons warningMessageButtons) { return AMT_SW_GUI.MessageManager.ShowWarningMessage(message, Properties.Resources.WARNING_HEADER, warningMessageButtons, this); } private bool ValidateHost() { if ((string.IsNullOrEmpty(tbHostName.Text)) || (!Utilities.IsValidFQDN(tbHostName.Text) && !Utilities.IsValidIPV4(tbHostName.Text) && !Utilities.IsValidIPV6(tbHostName.Text))) { tbHostName.ForeColor = Color.Red; tbHostName.Font = new Font(tbHostName.Font, FontStyle.Bold); // Change status bar return false; } else { tbHostName.ForeColor = Color.Black; tbHostName.Font = new Font(tbHostName.Font, FontStyle.Regular); return true; } } #endregion #region GUI_CHANGES (According to OptIn status) /// /// Delegate change the mouse state /// /// The new mouse state private delegate void changeMouse_D(Cursor state); /// /// Change the mouse state /// /// The new mouse state public void changeMouse(Cursor state) { if (InvokeRequired) { BeginInvoke(new changeMouse_D(changeMouse), new object[] { state }); } else { this.Cursor = state; } } internal void ChangeConnectionIcon(bool connected) { if (pbConnectionIcon.InvokeRequired) { ChangeConnectionIcon_D del = new ChangeConnectionIcon_D(ChangeConnectionIcon); pbConnectionIcon.Invoke(del, connected); } else { if (connected) { pbConnectionIcon.Image = Properties.Resources.connectionstatus_on; } else { pbConnectionIcon.Image = Properties.Resources.connectionstatus_off; } } } internal void MoveFocousToCodeFrame() { if (mtbCode.InvokeRequired) { MoveFocusToCodeFrameDelagate del = new MoveFocusToCodeFrameDelagate(MoveFocousToCodeFrame); mtbCode.Invoke(del); } else { mtbCode.Focus(); } } internal void ChangeMainButtonsStatus(bool connected) { if (PanelButtons.InvokeRequired) { UpdateGUIParams_D del = new UpdateGUIParams_D(ChangeMainButtonsStatus); PanelButtons.Invoke(del, connected); } else { if (connected) { btnStartCancel.Enabled = true; btnStartCancel.ButtonColor = Color.FromArgb(29, 82, 134); } else { btnStartCancel.Enabled = false; btnStartCancel.ButtonColor = Color.LightSteelBlue; } } } internal void ChangeSendCodeStatus(bool send) { if (OperationsPanel.InvokeRequired) { CodeMonitorPanel_D del = new CodeMonitorPanel_D(ChangeSendCodeStatus); OperationsPanel.Invoke(del, send); } else { if (!send) { MonitorPanel.Enabled = false; codePanel.Enabled = false; } } } internal void SetTimerState(TimerStatus status) { uint optInTimeoot = _logicLayer.GetOptInTimeOut(); if (cdTimer.InvokeRequired) { Timer_D del = new Timer_D(SetTimerState); cdTimer.Invoke(del, status); } else { switch (status) { case TimerStatus.DISABLE: cdTimer.SetTimer(0); break; case TimerStatus.FREEZE: cdTimer.SetTimer(optInTimeoot); break; case TimerStatus.RUN: cdTimer.StartTimer(optInTimeoot.ToString()); break; } } } internal void ChangePowerStateLabel(bool p) { if (!p) { SetPowerState(PowerState.Unknown); SetOptInState(OptInState.Unknown); } } internal void ChangeTimerNote(string text) { if (lblTimerNote.InvokeRequired) { ChangeTimerNoteDelegate del = new ChangeTimerNoteDelegate(ChangeTimerNote); lblTimerNote.Invoke(del, text); } else { lblTimerNote.Text = text; } } internal void EnableWirelessCommands(bool enable) { wirelessPanel.Enabled = enable; } internal void SetConnectioDetailsToUnknown(bool unknown) { if (linkInterfaceDetails.InvokeRequired) { UpdateGUIParams_D del = new UpdateGUIParams_D(SetConnectioDetailsToUnknown); linkInterfaceDetails.Invoke(del, unknown); } else { linkInterfaceDetails.SetDetails(LinkControl.None, LinkControl.None,_logicLayer.CheckLinkProtectionSupport()); } } internal void SetWirelessDetails(LinkControl linkControl, LinkControl linkPreference) { if (linkInterfaceDetails.InvokeRequired) { UpdateWirelessStateLabel del = new UpdateWirelessStateLabel(SetWirelessDetails); linkInterfaceDetails.Invoke(del, linkControl, linkPreference); } else { linkInterfaceDetails.SetDetails(linkControl, linkPreference, _logicLayer.CheckLinkProtectionSupport()); } } public void RefreshScreen() { this.Refresh(); } public void SetStartCancelButtonState(bool isStartEnable) { if (btnStartCancel.InvokeRequired) { UpdateGUIParams_D del = new UpdateGUIParams_D(SetStartCancelButtonState); btnStartCancel.Invoke(del, isStartEnable); } else { if (isStartEnable) { btnStartCancel.ButtonText = " Start Consent"; btnStartCancel.Image = Properties.Resources.start_consent; btnStartCancel.ImageSize = new System.Drawing.Size(17, 17); _buttonState = ButtonState.START; } else { btnStartCancel.ButtonText = " Cancel Consent"; btnStartCancel.Image = Properties.Resources.cancel_consent; btnStartCancel.ImageSize = new System.Drawing.Size(16, 16); _buttonState = ButtonState.CANCEL; } } } public void ChangeGuiToDisconnect(ConnectionState state) { if (panel4.InvokeRequired) { Connection_panel_D del = new Connection_panel_D(ChangeGuiToDisconnect); panel4.Invoke(del, state); } else { if (state == ConnectionState.CONNECTED) { lblConnectTo.Text = Properties.Resources.CONNECTED_TO; btnEdit.Size = new Size(new Point(72, 22)); btnEdit.Location = new Point(292, 11); btnEdit.Text = Properties.Resources.DISCONNECT; pbDirectConnect.Location = new Point(266, 12); tbHostName.Location = new Point(142, 11); pbConnectionIcon.Image = Properties.Resources.connectionstatus_on; // Add the current client to the "history" linkInterfaceDetails.SetInterface(Configuration.InterfaceSettings.GetInstance().LinkInterface, Configuration.InterfaceSettings.GetInstance().LanID); EnableWirelessCommands(Configuration.InterfaceSettings.GetInstance().LinkInterface == LinkInterface.Wireless && !_logicLayer.CheckLinkProtectionSupport()); EnableMonitorSettingCommands(UCT.Configuration.BasicSettings.GetInstance().InitiateUserPrivileges() == UCTPermission.Admin); EnablePowerOperationCommands(UCT.Configuration.BasicSettings.GetInstance().InitiateUserPrivileges() != UCTPermission.Redirection); } else { lblConnectTo.Text = Properties.Resources.CONNECT_TO; btnEdit.Size = new Size(new Point(45, 22)); btnEdit.Location = new Point(271, 11); btnEdit.Text = Properties.Resources.EDIT; pbDirectConnect.Location = new Point(245, 12); tbHostName.Location = new Point(121, 11); pbConnectionIcon.Image = Properties.Resources.connectionstatus_off; InitOperationTab(false); } ChangeSecureConnectionGUI(CertificateUtils.UnsecureConnection); } } private void EnableMonitorSettingCommands(bool enable) { monitorSettingPanel.Enabled = enable; } private void EnablePowerOperationCommands(bool enable) { PowerOperationPanel.Enabled = enable; } #endregion private void btnApplyTimeout_Click(object sender, EventArgs e) { _logicLayer.SetOptInTimeOut((uint)nudTimeout.Value); } #endregion private void btnRefresh_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { InitStatisticsTab(lblOptInState.Text != OptInState.Unknown.ToString()); } catch (Exception ex) { WriteToLog(string.Format(Properties.Resources.EXCEPTION_OCCURED_ERROR_CODE, ex.Message, ex.TargetSite.ToString()), LogInteraction.Error); DisplayMessage(ex.Message, Properties.Resources.OPERATION_FAILED, MessageType.ERROR); DisplayStatusBar(ex.Message); } } } }