using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using SafeMobileLib; using System.Threading; using System.Diagnostics; using System.Threading.Tasks; namespace MotoRepeater { public partial class LoginForm : Form { private Boolean shouldHideForm = false; private List gateways = new List(); public LoginForm() { InitializeComponent(); if (LOGS.WRITE_LOGS) { new Thread(new ThreadStart(delegate () { MotoRepeater_GW.hLog = new LOGS(); })).Start(); } // check if the application is already running if (testIfAlreadyRunning()) { Process[] processlist = Process.GetProcesses(); Process curentP = Process.GetCurrentProcess(); Utils.WriteLine("App already running!!!"); MessageBox.Show("Aplication already running!!", "error", MessageBoxButtons.OK); foreach (Process theprocess in processlist) { if (theprocess.ProcessName.Equals(curentP.ProcessName) && !curentP.ProcessName.Contains("vshost")) { Utils.WriteLine(String.Format("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id)); Utils.WriteLine(String.Format("Curent Process: {0} ID: {1}", curentP.ProcessName, curentP.Id)); if (theprocess.Id != curentP.Id) { Utils.WriteLine(String.Format("Killing Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id)); theprocess.Kill(); } } } Thread.Sleep(1000); } UpdateUIFromConfig(); // skip the login form if signed in checked if (MotoRepeater_GW.cfg.SIGNEDIN && MotoRepeater_GW.cfg.GWCODE > 0) { shouldHideForm = false; //Load += (s, e) => Hide(); //return; } } private void LoginForm_Load(object sender, EventArgs e) { /* if (shouldHideForm) { this.Hide(); GetRepeaterGatwayConfig(MotoRepeater_GW.cfg.GWCODE); } */ } private void LoginForm_Shown(object sender, EventArgs e) { UpdateUIFromConfig(); // skip the login form if signed in checked if (ShouldAutoConnect()) { shouldHideForm = false; btLogin.PerformClick(); //Load += (s, e) => Hide(); //return; } } private bool ShouldAutoConnect() { return MotoRepeater_GW.cfg.SIGNEDIN && MotoRepeater_GW.cfg.GWCODE > 0; } /// /// Check if the application is already running in order to prevent it from running multiple /// private bool testIfAlreadyRunning() { Process[] processlist = Process.GetProcesses(); Process curentP = Process.GetCurrentProcess(); int count = 0; foreach (Process theprocess in processlist) { if (theprocess.ProcessName.Equals(curentP.ProcessName) && !curentP.ProcessName.Contains("vshost")) { count++; } } if (count > 1) { return true; } return false; } private void UpdateUIFromConfig() { LoadConfig(); gateways = new List(); btLogin.Text = "Login"; lbState.Text = ""; tbPassword.Text = MotoRepeater_GW.cfg.PASSWORD; tbUsername.Text = MotoRepeater_GW.cfg.USERNAME; // hide the gateway codes ChangeGatewayCodesState(false); tbPassword.GotFocus += delegate (object senderD, EventArgs eD) { tbPassword.SelectAll(); }; tbUsername.GotFocus += delegate (object senderD, EventArgs eD) { tbUsername.SelectAll(); }; Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; lbVersion.Text = ("Version: " + v.ToString()); if (shouldHideForm) this.Hide(); } /// /// Load the configuration parameters for the DataBase /// /// A confirmation that the configurations were successfully loaded, or a negativ /// response in case something went wrong private bool LoadConfig() { bool ret = false; try { MotoRepeater_GW.cfg = new Config(); MotoRepeater_GW.cfg.OnConfigFileWasBroken += delegate () { MessageBox.Show("Something was wrong with your configuration file. " + System.Environment.NewLine + "Now you're running a default configuration. Please reconfigure it or contact " + "support@safemobil.com. " + System.Environment.NewLine + System.Environment.NewLine + "Thank you!", "Reconfiguration needed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); //System.Environment.Exit(0); }; MotoRepeater_GW.cfg.LoadConfig(MotoRepeater_GW.appType); ret = true; } catch (Exception ex) { Utils.WriteLine("Unable to parse Config File: " + ex.ToString(), ConsoleColor.Red); } return ret; } private System.Threading.Timer reconnectTimer; private void StartReconnectTimer() { StopReconnectTimer(); reconnectTimer = new System.Threading.Timer(ReconnectTask, null, new TimeSpan(0, 0, 10), new TimeSpan(10, 0, 10)); } private void StopReconnectTimer() { if (reconnectTimer != null) reconnectTimer.Dispose(); } private void ReconnectTask(Object state) { this.Invoke((MethodInvoker)delegate { btLogin.PerformClick(); }); } private async void button1_Click(object sender, EventArgs e) { MotoRepeater_GW.isRunning = true; if (!btLogin.Text.Equals("Connect")) { // disable form lbState.Text = "»»» Authenticating..."; ChangeUIState(false); DBhandle DB = new DBhandle(MotoRepeater_GW.cfg.DB_SERVER, MotoRepeater_GW.cfg.DB_DATABASE, MotoRepeater_GW.cfg.DB_USERNAME, MotoRepeater_GW.cfg.DB_PASSWORD); await Task.Factory.StartNew(() => DB.StartDB()); // Get the Gateway Configuration from the Database //List gatewayCodes = DB.GetGatewayIDForCredentials("AceBoatLifts", "AceBoatLifts"); gateways = DB.GetRepeaterGatewayIDForCredentials(tbUsername.Text, tbPassword.Text); if (gateways.Count == 0) { lbState.Text = "login error "; ChangeUIState(true); if (!ShouldAutoConnect()) MessageBox.Show("The username and/or password are invalid or there is no configured gateway assigned to this user", "Login Error"); else StartReconnectTimer(); return; } else if (gateways.Count == 1) { //MessageBox.Show("GATEWAY ID IS " + gateways[0].Id + " with Code " + gateways[0].Code); Config.UpdateConfigParameter("CREDENTIALS", "USER", tbUsername.Text); Config.UpdateConfigParameter("CREDENTIALS", "PASSWORD", TESEncryption.Encrypt(tbPassword.Text, "safemobileTriple")); Config.UpdateConfigParameter("GATEWAY", "CODE", gateways[0].Code + ""); MotoRepeater_GW.cfg.USERNAME = tbUsername.Text; MotoRepeater_GW.cfg.PASSWORD = TESEncryption.Encrypt(tbPassword.Text, "safemobileTriple"); GetRepeaterGatwayConfig(gateways[0].Code); } else { // add gateways to the combobox cbGatewayCodes.Items.Clear(); foreach (SafenetGatewayIdent gw in gateways) { cbGatewayCodes.Items.Add(gw.Code + ""); } cbGatewayCodes.SelectedIndex = 0; lbGatewayCode.Text = cbGatewayCodes.Text; ChangeGatewayCodesState(true); //MessageBox.Show("MANY GATEWAY CODES | FIRST IS " + gateways[0].Id); Config.UpdateConfigParameter("CREDENTIALS", "USER", tbUsername.Text); Config.UpdateConfigParameter("CREDENTIALS", "PASSWORD", TESEncryption.Encrypt(tbPassword.Text, "safemobileTriple")); MotoRepeater_GW.cfg.USERNAME = tbUsername.Text; MotoRepeater_GW.cfg.PASSWORD = tbPassword.Text; DB.StopDB(); btLogin.Text = "Connect"; ChangeUIState(true); lbState.Text = "select gateway code"; //MessageBox.Show("Please select a gateway from the below list and then press Connect"); } } else { GetRepeaterGatwayConfig(gateways[cbGatewayCodes.SelectedIndex].Code); } } /// /// Get the repeater configuration from the database for the selected repeater /// /// Gateway code as received from the database and selected private async void GetRepeaterGatwayConfig(Int64 gatewayCode) { DBhandle DB = new DBhandle(MotoRepeater_GW.cfg.DB_SERVER, MotoRepeater_GW.cfg.DB_DATABASE, MotoRepeater_GW.cfg.DB_USERNAME, MotoRepeater_GW.cfg.DB_PASSWORD); await Task.Factory.StartNew(() => DB.StartDB()); RepeaterConfig repeaterConfig = null; repeaterConfig = DB.GetRepeaterGatewayConfiguration(gatewayCode); if (repeaterConfig == null) { ChangeUIState(true); if (!ShouldAutoConnect()) MessageBox.Show("You don't have any repeater configuration for this Gateway. Please go into SafeNet Admin and " + "insert this gateway with the proper configuration.", "No Gateway Configuration"); else StartReconnectTimer(); return; } // update config file with the one received from the Database MotoRepeater_GW.cfg.UpdateRepeaterConfig(repeaterConfig); DB.StopDB(); Config.UpdateConfigParameter("GATEWAY", "CODE", repeaterConfig.GatewayCode + ""); this.Hide(); StopReconnectTimer(); SafeNetForm mf = new SafeNetForm(); mf.FormClosed += new FormClosedEventHandler(delegate (object sender, FormClosedEventArgs e) { if (mf.DialogResult != System.Windows.Forms.DialogResult.OK) Application.Exit(); else { // reset the UI because a logout was made UpdateUIFromConfig(); shouldHideForm = false; // show login form this.Show(); } }); mf.Show(); } /// /// Event Handler for when the text inside the textBox had changed. This /// handler has the role to enable or disable the LoginButton if the /// validation of the textboxes is passed or failed /// /// TextBox object which raised the event /// Event args containing the new value of text private void label_TextChanged(object sender, EventArgs e) { if (cbGatewayCodes.Visible) { ChangeGatewayCodesState(false); btLogin.Text = "Login"; lbState.Text = ""; } if (tbPassword.Text.Length > 0 && tbUsername.Text.Length > 0) ChangeLoginButtonStatus(true); else ChangeLoginButtonStatus(false); } /// /// Event Handler which will intercept any Enter pressed in any textbox and /// will start the login procedure /// /// TextBox object which raised the event /// Event Args containing which key was pressed private void tb_KeyPress(object sender, KeyPressEventArgs e) { // skip the case when any other key, except Enter, was pressed if (e.KeyChar != (char)Keys.Enter) return; // fake the click if (tbPassword.Text.Length > 0 && tbUsername.Text.Length > 0) button1_Click(btLogin, null); } /// /// Change properties for the Login Button in order for it to be /// enabled or disabled /// /// Login Button desired UI state private void ChangeLoginButtonStatus(Boolean isEnabled) { if (isEnabled) { btLogin.Enabled = true; btLogin.BackColor = Color.FromArgb(32, 49, 51); } else { btLogin.Enabled = false; btLogin.BackColor = Color.DimGray; } } /// /// Change the UI state to enabled or disabled /// /// UI Form state private void ChangeUIState(Boolean isEnabled) { tbUsername.Enabled = isEnabled; tbPassword.Enabled = isEnabled; ChangeLoginButtonStatus(isEnabled); } /// /// Change the Gateway Codes state to enabled or disabled /// /// UI Form state private void ChangeGatewayCodesState(Boolean isEnabled) { pbGatewayCodes.Visible = isEnabled; lbGatewayCode.Visible = isEnabled; lbGatewayCodes.Visible = isEnabled; cbGatewayCodes.Visible = isEnabled; } private void cbGatewayCodes_SelectedIndexChanged(object sender, EventArgs e) { lbGatewayCode.Text = cbGatewayCodes.Text; lbState.Text = "press connect"; } private void pbGatewayCodes_Click(object sender, EventArgs e) { cbGatewayCodes.DroppedDown = !cbGatewayCodes.DroppedDown; } private void controlGateway_MouseEnter(object sender, EventArgs e) { pbGatewayCodes.Image = MotoRepeater.Properties.Resources.comboBox_over; lbGatewayCode.BackColor = Color.FromArgb(17, 61, 66); } private void controlGateway_MouseLeave(object sender, EventArgs e) { pbGatewayCodes.Image = MotoRepeater.Properties.Resources.comboBox; lbGatewayCode.BackColor = Color.FromArgb(32, 49, 51); } } }