/// <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> /// 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> /// 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 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> /// 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 ); } } }
/// <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; } }