/// <summary> /// Open and displays the task form. /// </summary> /// <param name="Parent">The calling form, so the task form can be centered</param> /// <param name="WindowTitle">The task dialog window title</param> /// <param name="InstructionText">Instruction text displayed after the info icon. Leave null /// to hide the instruction text and icon.</param> /// <param name="SubMessage">Detail text that is displayed just above the progress bar</param> /// <param name="Cancelable">Specifies whether the operation can be canceled</param> /// <param name="Style">The progress bar style</param> /// <exception cref="Exception">Thrown if the Task form is already open and running. Use the IsOpen property /// to determine if the form is already running</exception> public static void Show(Form Parent, string WindowTitle, string InstructionText, string SubMessage, bool Cancelable, ProgressBarStyle Style, int ProgressBarSteps) { // Make sure we dont have an already active form if (Instance != null && !Instance.IsDisposed) { throw new Exception("Task Form is already being displayed!"); } // Create new instance Instance = new TaskForm(); Instance.Text = WindowTitle; Instance.labelInstructionText.Text = InstructionText; Instance.labelContent.Text = SubMessage; Instance.Cancelable = Cancelable; Instance.progressBar.Style = Style; // Setup progress bar if (ProgressBarSteps > 0) { Instance.progressBar.Maximum = ProgressBarSteps; } // Hide Instruction panel if Instruction Text is empty if (String.IsNullOrWhiteSpace(InstructionText)) { Instance.panelMain.Hide(); Instance.labelContent.Location = new Point(10, 15); Instance.labelContent.MaximumSize = new Size(410, 0); Instance.labelContent.Size = new Size(410, 0); Instance.progressBar.Location = new Point(10, 1); Instance.progressBar.Size = new Size(410, 18); } // Hide Cancel if (!Cancelable) { Instance.panelButton.Hide(); Instance.Padding = new Padding(0, 0, 0, 15); Instance.BackColor = Color.White; } // Set window position to center parent double H = Parent.Location.Y + (Parent.Height / 2) - (Instance.Height / 2); double W = Parent.Location.X + (Parent.Width / 2) - (Instance.Width / 2); Instance.Location = new Point((int)Math.Round(W, 0), (int)Math.Round(H, 0)); // Display the Instanced Form Instance.Show(Parent); // Wait until the Instance form is displayed while (!Instance.IsHandleCreated) { Thread.Sleep(50); } }
/// <summary> /// Reset stats button click event /// </summary> private async void ResetStatsBtn_Click(object sender, EventArgs e) { if (MessageBox.Show("Are you sure you want to reset players stats?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { try { TaskForm.Show(this, "Reset Player Stats", "Reseting Player \"" + Player["name"] + "\"'s Stats", false); await Task.Run(() => { // Delete the players using (StatsDatabase Driver = new StatsDatabase()) { // Delete old player statistics Driver.DeletePlayer(Pid, TaskForm.Progress); // Insert a new player record Driver.Execute( "INSERT INTO player(id, name, country, joined, clantag, permban, isbot) VALUES(@P0, @P1, @P2, @P3, @P4, @P5, @P6)", Pid, Player["name"], Player["country"], Player["joined"], Player["clantag"], Player["permban"], Player["isbot"] ); } }); // Reload player LoadPlayer(); Notify.Show("Player Stats Reset Successfully!", "Operation Successful", AlertType.Success); } catch (DbConnectException Ex) { HttpServer.Stop(); ExceptionForm.ShowDbConnectError(Ex); TaskForm.CloseForm(); this.Close(); return; } catch (Exception E) { // Show exception error using (ExceptionForm Form = new ExceptionForm(E, false)) { Form.Message = String.Format("Failed to reset player stats!{1}{1}Error: {0}", E.Message, Environment.NewLine); Form.ShowDialog(); } } finally { // Close task form TaskForm.CloseForm(); } } }
/// <summary> /// Import Stats Button Click Event /// </summary> private void ImportBtn_Click(object sender, EventArgs e) { // Make sure PID text box is a valid PID if (!Validator.IsValidPID(PidTextBox.Text)) { MessageBox.Show("The player ID entered is NOT a valid PID. Please try again.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Establist Database connection try { using (StatsDatabase Database = new StatsDatabase()) { // Make sure the PID doesnt exist already int Pid = Int32.Parse(PidTextBox.Text); if (Database.PlayerExists(Pid)) { MessageBox.Show("The player ID entered already exists.", "Import Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // Show Task Form TaskForm.Show(this, "Import ASP Stats", "Importing ASP Stats...", false, ProgressBarStyle.Blocks, 13); // Setup the worker bWorker = new BackgroundWorker(); bWorker.WorkerSupportsCancellation = false; bWorker.WorkerReportsProgress = true; // Run Worker bWorker.DoWork += bWorker_ImportEaStats; bWorker.ProgressChanged += (s, ea) => { TaskForm.Progress.Report(new TaskProgressUpdate(ea.UserState.ToString(), ea.ProgressPercentage)); }; bWorker.RunWorkerCompleted += bWorker_RunWorkerCompleted; bWorker.RunWorkerAsync(PidTextBox.Text); } } catch (DbConnectException Ex) { ExceptionForm.ShowDbConnectError(Ex); HttpServer.Stop(); this.Close(); return; } }
/// <summary> /// Event is fired when the Import Button is clicked /// </summary> private async void ImportBtn_Click(object sender, EventArgs e) { // List of files to process List <SnapshotFile> Files = new List <SnapshotFile>(); foreach (ListViewItem I in SnapshotView.Items) { if (I.Checked) { Files.Add(I.Tag as SnapshotFile); } } // Make sure we have a snapshot selected if (Files.Count == 0) { MessageBox.Show("You must select at least 1 snapshot to process.", "Error"); return; } // Disable this form, and show the TaskForm this.Enabled = false; TaskForm.Show(this, "Importing Snapshots", "Importing Snapshots", true, ProgressBarStyle.Continuous, Files.Count); TaskForm.Cancelled += (s, ev) => { TaskForm.Progress.Report(new TaskProgressUpdate("Cancelling....")); ImportTaskSource.Cancel(); }; // Setup cancellation ImportTaskSource = new CancellationTokenSource(); CancellationToken CancelToken = ImportTaskSource.Token; // Wrap in a Task so we dont lock the GUI await Task.Run(() => ImportSnaphotFiles(Files, CancelToken), CancelToken); // Update the snapshots found close task form BuildList(); TaskForm.CloseForm(); this.Enabled = true; this.Focus(); }
/// <summary> /// Delete Player Menu Item Click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void deletePlayerMenuItem_Click(object sender, EventArgs e) { // Get players ID and Nick int Pid = Int32.Parse(DataTable.SelectedRows[0].Cells[1].Value.ToString()); string Name = DataTable.SelectedRows[0].Cells[2].Value.ToString(); // Show confirm box before deleting DialogResult Result = MessageBox.Show( String.Format("Are you sure you want to permanently delete player \"{0}\" ({1})?", Name, Pid), "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning ); // If confirmed if (Result == DialogResult.OK) { try { TaskForm.Show(this, "Delete Player", "Deleting Player \"" + Name + "\"", false); await Task.Run(() => Driver.DeletePlayer(Pid, TaskForm.Progress)); BuildList(); } catch (Exception E) { // Show exception error using (ExceptionForm Form = new ExceptionForm(E, false)) { Form.Message = String.Format("Failed to remove player from database!{1}{1}Error: {0}", E.Message, Environment.NewLine); Form.ShowDialog(); } } finally { // Close task form TaskForm.CloseForm(); } } }
/// <summary> /// Finishes the import process /// </summary> private void bWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // Close the task form TaskForm.CloseForm(); // Close this form! if (e.Error != null) { Exception E = e.Error as Exception; MessageBox.Show( "An error occured while trying to import player stats." + Environment.NewLine + Environment.NewLine + E.Message, "Import Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); this.Close(); return; } Notify.Show("Player Imported Successfully!", "All the players stats and awards are now available on the server.", AlertType.Success); this.Close(); }
/// <summary> /// Closes the Task dialog, and clears the Cancelled event handle subscriptions /// </summary> public static void CloseForm() { // No exception here if (Instance == null || Instance.IsDisposed) { return; } // Remove all cancellation subs if (Cancelled != null) { Cancelled = (CancelEventHandler)Delegate.RemoveAll(Cancelled, Cancelled); } try { Instance.Invoke((Action) delegate() { Instance.Close(); Instance = null; }); } catch { } }
/// <summary> /// Delete Player Button Click Event /// </summary> private async void DeletePlayerBtn_Click(object sender, EventArgs e) { if (MessageBox.Show("Are you sure you want to delete player?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { try { TaskForm.Show(this, "Delete Player", "Deleting Player \"" + Player["name"] + "\"", false); // Delete the player using (StatsDatabase Driver = new StatsDatabase()) await Task.Run(() => Driver.DeletePlayer(Pid, TaskForm.Progress)); Notify.Show("Player Deleted Successfully!", "Operation Successful", AlertType.Success); } catch (DbConnectException Ex) { HttpServer.Stop(); ExceptionForm.ShowDbConnectError(Ex); } catch (Exception E) { // Show exception error using (ExceptionForm Form = new ExceptionForm(E, false)) { Form.Message = String.Format("Failed to remove player from database!{1}{1}Error: {0}", E.Message, Environment.NewLine); Form.ShowDialog(); } } finally { // Close task form TaskForm.CloseForm(); this.Close(); } } }
/// <summary> /// Event fired when the next button is clicked /// </summary> private async void NextBtn_Click(object sender, EventArgs e) { // Disable this form this.Enabled = false; string Message1 = ""; // Initiate the Task Form if (TypeSelect.SelectedIndex == 1) { TaskForm.Show(this, "Create Database", "Connecting to MySQL Database...", false); Message1 = "Successfully Connected to MySQL Database! We will attempt to create the necessary tables into the specified database. Continue?"; } else { TaskForm.Show(this, "Create Database", "Creating SQLite Database...", false); Message1 = "Successfully Created the SQLite Database! We will attempt to create the necessary tables into the specified database. Continue?"; } // Temporarily set settings if (!SetConfigSettings()) { this.Enabled = true; TaskForm.CloseForm(); return; } // Try and install the SQL try { bool PreviousInstall = true; // Run in a seperate thread, dont wanna lock up the GUI thread await Task.Run(() => { // Switch mode if (DbMode == DatabaseMode.Stats) { // Open up the database connetion using (StatsDatabase Db = new StatsDatabase()) { // We only have work to do if the tables are not installed if (!Db.TablesExist) { PreviousInstall = false; // Verify that the user wants to install DB tables DialogResult Res = MessageBox.Show(Message1, "Verify Installation", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000 // Force window on top ); // If we dont want to install tables, back out! if (Res == DialogResult.No) { return; } // Create our tables TaskForm.Progress.Report(new TaskProgressUpdate("Creating Stats Tables")); Db.CreateSqlTables(TaskForm.Progress); } } } else // Gamespy Mode { // Open up the database connetion using (GamespyDatabase Db = new GamespyDatabase()) { // We only have work to do if the tables are not installed if (!Db.TablesExist) { PreviousInstall = false; // Verify that the user wants to install DB tables DialogResult Res = MessageBox.Show(Message1, "Verify Installation", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000 // Force window on top ); // If we dont want to install tables, back out! if (Res == DialogResult.No) { return; } // Create our tables TaskForm.Progress.Report(new TaskProgressUpdate("Creating Gamespy Tables")); Db.CreateSqlTables(); } } } }); // No errors, so save the config file Program.Config.Save(); // Close the task form TaskForm.CloseForm(); // Show Success Form if (!PreviousInstall) { MessageBox.Show("Successfully installed the database tables!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000 // Force window on top ); } else { MessageBox.Show( "We've detected that the database was already installed here. Your database settings have been saved and no further setup is required.", "Existing Installation Found", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000 // Force window on top ); } // Close this form, as we are done now this.Close(); } catch (Exception Ex) { // Close the task form and re-enable this form TaskForm.CloseForm(); this.Enabled = true; // Revert the temporary config settings and show the error to the user Program.Config.Reload(); MessageBox.Show(Ex.Message, "Database Installation Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000 // Force window on top ); return; } finally { if (TaskForm.IsOpen) { TaskForm.CloseForm(); } this.Enabled = true; } }
private void TaskForm_FormClosed(object sender, FormClosedEventArgs e) { Instance = null; }
/// <summary> /// Closes the Task dialog, and clears the Cancelled event handle subscriptions /// </summary> public static void CloseForm() { // No exception here if (Instance == null || Instance.IsDisposed) return; // Remove all cancellation subs if (Cancelled != null) Cancelled = (CancelEventHandler) Delegate.RemoveAll(Cancelled, Cancelled); try { Instance.Invoke((Action)delegate() { Instance.Close(); Instance = null; }); } catch { } }
/// <summary> /// Event called when an update file has completed its download /// </summary> private static void Wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { // Close task form, and unregister for updates TaskForm.Cancelled -= TaskForm_Cancelled; TaskForm.CloseForm(); IsDownloading = false; // Dispose webclient Web.Dispose(); // If we cancelled, stop here if (e.Cancelled) { // Delete junk files if (File.Exists(UpdateFileLocation)) { File.Delete(UpdateFileLocation); } return; } // Try to start the isntaller try { // Extract setup.exe string exFile = Path.Combine(Paths.DocumentsFolder, "setup.exe"); using (ZipArchive file = ZipFile.Open(UpdateFileLocation, ZipArchiveMode.Read)) { ZipArchiveEntry setupFile = file.Entries.FirstOrDefault(x => x.FullName == "setup.exe"); if (setupFile != null) { // Extract and start the new update installer setupFile.ExtractToFile(exFile, true); Process installer = Process.Start(exFile); installer.WaitForInputIdle(); } else { MessageBox.Show( "The Setup.exe file appears to be missing from the update archive! You will need to manually apply the update.", "Installation Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } } catch (Exception Ex) { MessageBox.Show( "An Occured while trying to install the new update. You will need to manually apply the update." + Environment.NewLine.Repeat(1) + "Error Message: " + Ex.Message, "Installation Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); ExceptionHandler.GenerateExceptionLog(Ex); } // Exit the application Application.Exit(); }
/// <summary> /// Downloads the new update from Github Async. /// </summary> public static bool DownloadUpdateAsync() { // Returns if there is no update if (!UpdateAvailable) { return(false); } // Simulate some headers, Github throws a fit otherwise Web = new WebClient(); Web.Headers["User-Agent"] = "BF2Statistics Control Center v" + Program.Version; Web.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; Web.Headers["Accept-Language"] = "en-US,en;q=0.8"; Web.Proxy = null; // Disable proxy because this can cause slowdown on some machines // Github file location string Download = "https://github.com/BF2Statistics/ControlCenter/releases/download/{0}/BF2Statistics_ControlCenter_{0}.zip"; Uri FileLocation = new Uri(String.Format(Download, NewVersion)); // Path to the Downloaded file UpdateFileLocation = Path.Combine(Paths.DocumentsFolder, String.Format("BF2Statistics_ControlCenter_{0}.zip", NewVersion)); // Show Task Form IsDownloading = true; TaskForm.Cancelled += TaskForm_Cancelled; TaskForm.Show(MainForm.Instance, "Downloading Update", "Downloading Update... Please Standby", true); TaskForm.Progress.Report(new TaskProgressUpdate("Preparing the download...")); try { // Download the new version Zip file Web.DownloadProgressChanged += Wc_DownloadProgressChanged; Web.DownloadFileCompleted += Wc_DownloadFileCompleted; Web.DownloadFileAsync(FileLocation, UpdateFileLocation); } catch (Exception ex) { // Close that task form if its open! if (TaskForm.IsOpen) { TaskForm.CloseForm(); } // Create Exception Log Program.ErrorLog.Write("WARNING: Unable to Download new update archive :: Generating Exception Log"); ExceptionHandler.GenerateExceptionLog(ex); // Alert User MessageBox.Show( "Failed to download update archive! Reason: " + ex.Message + Environment.NewLine.Repeat(1) + "An exception log has been generated and created inside the My Documents/BF2Statistics folder.", "Download Failed", MessageBoxButtons.OK, MessageBoxIcon.Error ); return(false); } // Tell the mainform that we have this handled return(true); }
/// <summary> /// Open and displays the task form. /// </summary> /// <param name="Parent">The calling form, so the task form can be centered</param> /// <param name="WindowTitle">The task dialog window title</param> /// <param name="InstructionText">Instruction text displayed after the info icon. Leave null /// to hide the instruction text and icon.</param> /// <param name="SubMessage">Detail text that is displayed just above the progress bar</param> /// <param name="Cancelable">Specifies whether the operation can be canceled</param> /// <param name="Style">The progress bar style</param> /// <exception cref="Exception">Thrown if the Task form is already open and running. Use the IsOpen property /// to determine if the form is already running</exception> public static void Show(Form Parent, string WindowTitle, string InstructionText, string SubMessage, bool Cancelable, ProgressBarStyle Style, int ProgressBarSteps) { // Make sure we dont have an already active form if (Instance != null && !Instance.IsDisposed) throw new Exception("Task Form is already being displayed!"); // Create new instance Instance = new TaskForm(); Instance.Text = WindowTitle; Instance.labelInstructionText.Text = InstructionText; Instance.labelContent.Text = SubMessage; Instance.Cancelable = Cancelable; Instance.progressBar.Style = Style; // Setup progress bar if (ProgressBarSteps > 0) { double Percent = (100 / ProgressBarSteps); Instance.progressBar.Step = (int)Math.Round(Percent, 0); Instance.progressBar.Maximum = Instance.progressBar.Step * ProgressBarSteps; } // Hide Instruction panel if Instruction Text is empty if (String.IsNullOrWhiteSpace(InstructionText)) { Instance.panelMain.Hide(); Instance.labelContent.Location = new Point(10, 15); Instance.labelContent.MaximumSize = new Size(410, 0); Instance.labelContent.Size = new Size(410, 0); Instance.progressBar.Location = new Point(10, 1); Instance.progressBar.Size = new Size(410, 18); } // Hide Cancel if (!Cancelable) { Instance.panelButton.Hide(); Instance.Padding = new Padding(0, 0, 0, 15); Instance.BackColor = Color.White; } // Set window position to center parent double H = Parent.Location.Y + (Parent.Height / 2) - (Instance.Height / 2); double W = Parent.Location.X + (Parent.Width / 2) - (Instance.Width / 2); Instance.Location = new Point((int)Math.Round(W, 0), (int)Math.Round(H, 0)); // Run form in a new thread Thread thread = new Thread(new ThreadStart(ShowForm)); thread.IsBackground = true; thread.SetApartmentState(ApartmentState.STA); thread.Start(); Thread.Sleep(100); // Wait for Run to work }
/// <summary> /// Open and displays the task form. /// </summary> /// <param name="Parent">The calling form, so the task form can be centered</param> /// <param name="WindowTitle">The task dialog window title</param> /// <param name="InstructionText">Instruction text displayed after the info icon. Leave null /// to hide the instruction text and icon.</param> /// <param name="SubMessage">Detail text that is displayed just above the progress bar</param> /// <param name="Cancelable">Specifies whether the operation can be canceled</param> /// <param name="Style">The progress bar style</param> /// <exception cref="Exception">Thrown if the Task form is already open and running. Use the IsOpen property /// to determine if the form is already running</exception> public static void Show(Form Parent, string WindowTitle, string InstructionText, string SubMessage, bool Cancelable, ProgressBarStyle Style, int ProgressBarSteps) { // Make sure we dont have an already active form if (Instance != null && !Instance.IsDisposed) throw new Exception("Task Form is already being displayed!"); // Create new instance Instance = new TaskForm(); Instance.Text = WindowTitle; Instance.labelInstructionText.Text = InstructionText; Instance.labelContent.Text = SubMessage; Instance.Cancelable = Cancelable; Instance.progressBar.Style = Style; // Setup progress bar if (ProgressBarSteps > 0) Instance.progressBar.Maximum = ProgressBarSteps; // Hide Instruction panel if Instruction Text is empty if (String.IsNullOrWhiteSpace(InstructionText)) { Instance.panelMain.Hide(); Instance.labelContent.Location = new Point(10, 15); Instance.labelContent.MaximumSize = new Size(410, 0); Instance.labelContent.Size = new Size(410, 0); Instance.progressBar.Location = new Point(10, 1); Instance.progressBar.Size = new Size(410, 18); } // Hide Cancel if (!Cancelable) { Instance.panelButton.Hide(); Instance.Padding = new Padding(0, 0, 0, 15); Instance.BackColor = Color.White; } // Set window position to center parent double H = Parent.Location.Y + (Parent.Height / 2) - (Instance.Height / 2); double W = Parent.Location.X + (Parent.Width / 2) - (Instance.Width / 2); Instance.Location = new Point((int)Math.Round(W, 0), (int)Math.Round(H, 0)); // Display the Instanced Form Instance.Show(Parent); // Wait until the Instance form is displayed while (!Instance.IsHandleCreated) Thread.Sleep(50); }
/// <summary> /// Imports ASP created BAK files (Mysql Out FILE) /// </summary> private async void ImportASPBtn_Click(object sender, EventArgs e) { // Open File Select Dialog FolderSelectDialog Dialog = new FolderSelectDialog(); Dialog.Title = "Select ASP Database Backup Folder"; Dialog.InitialDirectory = Path.Combine(Paths.DocumentsFolder, "Database Backups"); if (Dialog.ShowDialog()) { // Get files list from path string path = Dialog.SelectedPath; string[] BakFiles = Directory.GetFiles(path, "*.bak"); if (BakFiles.Length > 0) { // Open the database connection StatsDatabase Database = null; try { Database = new StatsDatabase(); } catch (Exception Ex) { if (Ex is DbConnectException) { ExceptionForm.ShowDbConnectError(Ex as DbConnectException); return; } MessageBox.Show( "Unable to connect to database\r\n\r\nMessage: " + Ex.Message, "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } finally { if (Database == null) { // Stop the ASP server, and close this form HttpServer.Stop(); this.Close(); } } // Show task dialog TaskForm.Show(this, "Importing Stats", "Importing ASP Stats Bak Files...", false); this.Enabled = false; // Don't block the GUI await Task.Run(() => ImportFromBakup(BakFiles, Database)); // Alert user and close task form Notify.Show("Stats imported successfully!", "Operation Successful", AlertType.Success); TaskForm.CloseForm(); this.Enabled = true; // Displose Connection Database.Dispose(); } else { // Alert the user and tell them they failed MessageBox.Show( "Unable to locate any .bak files in this folder. Please select an ASP created database backup folder that contains backup files.", "Backup Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } }