/// <summary> /// Handles cross thread exceptions, that are unrecoverable /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { // Create Trace Log string FileName = GenerateFileName(); Exception Ex = e.ExceptionObject as Exception; using (ExceptionForm EForm = new ExceptionForm(Ex, false)) { try { // Try to generate a trace log GenerateExceptionLog(FileName, Ex); // Display the Exception Form EForm.Message = "An unhandled exception was thrown while trying to preform the requested task.\r\n" + "A trace log was generated under the \"My Documents/BF2Stastistics\" folder, to " + "assist with debugging, and getting help with this error."; EForm.TraceLog = FileName; } catch { EForm.Message = "An unhandled exception was thrown while trying to preform the requested task.\r\n" + "A trace log was unable to be generated because that threw another exception :(. The error message " + "for the trace log was stored in the program error log for debugging purposes."; } finally { EForm.ShowDialog(); Application.Exit(); } } }
/// <summary> /// Exports player XML sheet /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void fromPlayerExportSheetMenuItem_Click(object sender, EventArgs e) { // Create export directory if it doesnt exist yet string sPath = Path.Combine(Paths.DocumentsFolder, "Player Backups"); if (!Directory.Exists(sPath)) { Directory.CreateDirectory(sPath); } // Show dialog OpenFileDialog Dialog = new OpenFileDialog(); Dialog.InitialDirectory = sPath; Dialog.Title = "Select Player Import File"; if (Dialog.ShowDialog() == DialogResult.OK) { try { StatsManager.ImportPlayerXml(Dialog.FileName); Notify.Show("Player Imported Successfully", "Operation Successful", AlertType.Success); BuildList(); } catch (Exception E) { using (ExceptionForm EForm = new ExceptionForm(E, false)) { EForm.Message = "Unable to import player because an exception was thrown!"; EForm.ShowDialog(); } } } }
/// <summary> /// Handles an exception on the main thread. /// </summary> /// <param name="sender"></param> /// <param name="t"></param> public static void OnThreadException(object sender, ThreadExceptionEventArgs t) { // Create Trace Log string FileName = GenerateFileName(); try { // Try to generate a trace log GenerateExceptionLog(FileName, t.Exception); } catch { } // Display the Exception Form using (ExceptionForm EForm = new ExceptionForm(t.Exception, true)) { EForm.Message = "An unhandled exception was thrown while trying to preform the requested task.\r\n" + "If you click Continue, the application will attempt to ignore this error, and continue. " + "If you click Quit, the application will close immediatly."; EForm.TraceLog = FileName; DialogResult Result = EForm.ShowDialog(); // Kill the form on abort if (Result == DialogResult.Abort) { Application.Exit(); } } }
/// <summary> /// Export player menu item click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void exportPlayerMenuItem_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(); // Create export directory if it doesnt exist yet string sPath = Path.Combine(Paths.DocumentsFolder, "Player Backups"); if (!Directory.Exists(sPath)) { Directory.CreateDirectory(sPath); } // Have user select folder FolderSelect.FolderSelectDialog Dialog = new FolderSelect.FolderSelectDialog(); Dialog.InitialDirectory = sPath; Dialog.Title = "Select folder to export player to"; if (Dialog.ShowDialog()) { try { StatsManager.ExportPlayerXml(sPath, Pid, Name); Notify.Show("Player Exported Successfully", String.Format("{0} ({1})", Name, Pid), AlertType.Success); } catch (Exception E) { using (ExceptionForm EForm = new ExceptionForm(E, false)) { EForm.Message = "Unable to export player because an exception was thrown!"; EForm.ShowDialog(); } } } }
/// <summary> /// This method imports a list of .Bak files into the database /// </summary> /// <param name="BakFiles">A list of Backfiles to import into the database</param> /// <param name="Database">The opened database connection</param> private void ImportFromBakup(string[] BakFiles, StatsDatabase Database) { // Clear old database records TaskForm.Progress.Report(new TaskProgressUpdate("Removing old stats data")); Database.Truncate(); // Let the database update itself Thread.Sleep(500); // Begin transaction using (DbTransaction Transaction = Database.BeginTransaction()) { // import each table foreach (string file in BakFiles) { // Get table name string table = Path.GetFileNameWithoutExtension(file); TaskForm.Progress.Report(new TaskProgressUpdate("Processing stats table: " + table)); // Import table data try { // Sqlite kinda sucks... no import methods if (Database.DatabaseEngine == DatabaseEngine.Sqlite) { string[] Lines = File.ReadAllLines(file); foreach (string line in Lines) { string[] Values = line.Split('\t'); Database.Execute( String.Format("INSERT INTO {0} VALUES({1})", table, "\"" + String.Join("\", \"", Values) + "\"") ); } } else { Database.Execute(String.Format("LOAD DATA LOCAL INFILE '{0}' INTO TABLE {1};", file.Replace('\\', '/'), table)); } } catch (Exception Ex) { // Show exception error using (ExceptionForm Form = new ExceptionForm(Ex, false)) { Form.Message = String.Format("Failed to import data into table {0}!{2}{2}Error: {1}", table, Ex.Message, Environment.NewLine); DialogResult Result = Form.ShowDialog(); // Rollback! TaskForm.Progress.Report(new TaskProgressUpdate("Rolling back stats data")); Transaction.Rollback(); return; } } } // Commit the transaction Transaction.Commit(); } }
/// <summary> /// Displays a custom version of this form to display database connection errors /// </summary> /// <param name="e"></param> public static void ShowDbConnectError(DbConnectException e) { using (ExceptionForm F = new ExceptionForm(e, true)) { F.WindowTitle = "Database Connect Error"; F.HeaderText = "Database Connect Error"; F.Message = "Unable to establish a connection to the database."; F.ImgIcon = Properties.Resources.vistaWarning; F.ShowDialog(); } }
/// <summary> /// Handles an exception on the main thread. /// </summary> /// <param name="sender"></param> /// <param name="t"></param> public static void OnThreadException(object sender, ThreadExceptionEventArgs t) { // Display the Exception Form ExceptionForm EForm = new ExceptionForm(t.Exception, true); EForm.Message = "An unhandled exception was thrown while trying to preform the requested task.\r\n" + "If you click Continue, the application will attempt to ignore this error, and continue. " + "If you click Quit, the application will close immediatly."; DialogResult Result = EForm.ShowDialog(); // Kill the form on abort if (Result == DialogResult.Abort) Application.Exit(); }
/// <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> /// Displays a custom version of this form to display Razor template compile errors /// </summary> public static DialogResult ShowTemplateError(TemplateCompilationException E, string TemplateFile) { using (ExceptionForm F = new ExceptionForm(E, true)) { // Get our relative path from the program root string fileRelativePath = TemplateFile.Replace(Program.RootPath, ""); // Set the window properties F.WindowTitle = "Compile Error"; F.HeaderText = "Template Compile Error"; F.Message = "An error occured while trying to compile the file \"" + Path.GetFileName(fileRelativePath) + "\""; F.ImgIcon = Properties.Resources.vistaWarning; if (E.CompilerErrors.Count > 0) { StringBuilder builder = new StringBuilder(); // Append each error's details into the Details stringbuilder foreach (RazorEngineCompilerError error in E.CompilerErrors) { builder.AppendLine("Compile Error:"); builder.AppendLine(error.ErrorText); builder.AppendLine(); builder.AppendLine("Error #: " + error.ErrorNumber); builder.AppendLine("File: " + fileRelativePath); builder.AppendLine("Line: " + error.Line); builder.AppendLine("Column: " + error.Column); builder.AppendLine(); } // Set the Details pane contents F.ExceptionDetails.Text = builder.ToString(); } else { F.ExceptionDetails.Text = E.Message; } return(F.ShowDialog(false)); } }
/// <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> /// Export Player Button Click Event /// </summary> private void ExportPlayerBtn_Click(object sender, EventArgs e) { // Create export directory if it doesnt exist yet string sPath = Path.Combine(Paths.DocumentsFolder, "Player Backups"); if (!Directory.Exists(sPath)) { Directory.CreateDirectory(sPath); } // Have user select folder FolderSelect.FolderSelectDialog Dialog = new FolderSelect.FolderSelectDialog(); Dialog.InitialDirectory = sPath; Dialog.Title = "Select folder to export player to"; if (Dialog.ShowDialog()) { try { StatsManager.ExportPlayerXml(sPath, Pid, Player["name"].ToString()); Notify.Show("Player Exported Successfully", String.Format("{0} ({1})", Player["name"].ToString(), Pid), AlertType.Success); } catch (DbConnectException Ex) { HttpServer.Stop(); ExceptionForm.ShowDbConnectError(Ex); this.Close(); } catch (Exception E) { using (ExceptionForm EForm = new ExceptionForm(E, false)) { EForm.Message = "Unable to export player because an exception was thrown!"; EForm.ShowDialog(); } } } }
/// <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> /// Displays a custom version of this form to display database connection errors /// </summary> /// <param name="e"></param> public static void ShowDbConnectError(DbConnectException e) { using (ExceptionForm F = new ExceptionForm(e, true)) { F.WindowTitle = "Database Connect Error"; F.HeaderText = "Database Connect Error"; F.Message = "Unable to establish a connection to the database."; F.ImgIcon = Properties.Resources.vistaWarning; F.ShowDialog(); } }
/// <summary> /// Imports the provided snapshot files into the stats database /// </summary> /// <param name="Files">List of snapshot file paths to import</param> /// <param name="CancelToken">Cancellation token, to cancel the import</param> private void ImportSnaphotFiles(List <SnapshotFile> Files, CancellationToken CancelToken) { // Number of snapshots we have processed int processed = 0; // Do Work foreach (SnapshotFile SnapshotFile in Files) { // If we have a cancelation request if (CancelToken.IsCancellationRequested) { break; } // Make sure we arent processing twice if (SnapshotFile.IsProcessed) { continue; } // Process the snapshot try { // Update status and run snapshot TaskForm.Progress.Report(new TaskProgressUpdate(String.Format("Processing: \"{0}\"", SnapshotFile))); Snapshot Snapshot = new Snapshot(File.ReadAllText(SnapshotFile.FilePath)); // Avoid processing exception if (Snapshot.IsProcessed) { continue; } else // Do snapshot { Snapshot.ProcessData(); } // Move the Temp snapshot to the Processed folder File.Move( Path.Combine(Paths.SnapshotTempPath, SnapshotFile.FileName), Path.Combine(Paths.SnapshotProcPath, SnapshotFile.FileName) ); } catch (Exception E) { using (ExceptionForm Form = new ExceptionForm(E, true)) { Form.Message = "An exception was thrown while trying to import the snapshot." + "If you click Continue, the application will continue proccessing the remaining " + "snapshot files. If you click Quit, the operation will be aborted."; DialogResult Result = Form.ShowDialog(); // User Abort if (Result == DialogResult.Abort) { break; } } } // Whether we failed or succeeded, we are finished with this step // and should move the progress bar 1 step TaskForm.Progress.Report(new TaskProgressUpdate(++processed)); } // Let progress bar update to 100% TaskForm.Progress.Report(new TaskProgressUpdate("Done! Cleaning up...")); Thread.Sleep(250); }
/// <summary> /// Exports player XML sheet /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void fromPlayerExportSheetMenuItem_Click(object sender, EventArgs e) { // Create export directory if it doesnt exist yet string sPath = Path.Combine(Paths.DocumentsFolder, "Player Exports"); if (!Directory.Exists(sPath)) Directory.CreateDirectory(sPath); // Show dialog OpenFileDialog Dialog = new OpenFileDialog(); Dialog.InitialDirectory = sPath; Dialog.Title = "Select Player Import File"; if (Dialog.ShowDialog() == DialogResult.OK) { try { ASPServer.Database.ImportPlayerXml(Dialog.FileName); Notify.Show("Player Imported Successfully", AlertType.Success); BuildList(); } catch (Exception E) { ExceptionForm EForm = new ExceptionForm(E, false); EForm.Message = "Unable to import player because an exception was thrown!"; EForm.ShowDialog(); } } }
/// <summary> /// Export player menu item click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void exportPlayerMenuItem_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(); // Create export directory if it doesnt exist yet string sPath = Path.Combine(Paths.DocumentsFolder, "Player Exports"); if (!Directory.Exists(sPath)) Directory.CreateDirectory(sPath); // Have user select folder FolderSelect.FolderSelectDialog Dialog = new FolderSelect.FolderSelectDialog(); Dialog.InitialDirectory = sPath; Dialog.Title = "Select folder to export player to"; if (Dialog.ShowDialog()) { try { ASPServer.Database.ExportPlayerXml(sPath, Pid, Name); Notify.Show("Player Exported Successfully", String.Format("{0} ({1})", Name, Pid), AlertType.Success); } catch (Exception E) { ExceptionForm EForm = new ExceptionForm(E, false); EForm.Message = "Unable to export player because an exception was thrown!"; EForm.ShowDialog(); } } }
/// <summary> /// Delete Player Menu Item Click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private 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); ASPServer.Database.DeletePlayer(Pid, true); BuildList(); } catch (Exception E) { // Show exception error 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> /// Backs up the asp database /// </summary> private void ExportAsASPBtn_Click(object sender, EventArgs e) { // Define backup folder for this backup, and create it if it doesnt exist string Folder = Path.Combine(Paths.DocumentsFolder, "Backups", "bak_" + DateTime.Now.ToString("yyyyMMdd_HHmm")); if (!Directory.Exists(Folder)) Directory.CreateDirectory(Folder); // Abortion indicator bool Aborted = false; // Show loading screen LoadingForm.ShowScreen(this); // Backup each table into its own bak file foreach (string Table in StatsDatabase.StatsTables) { // Create file path string BakFile = Path.Combine(Folder, Table + ".bak"); // Backup tables try { // fetch the data from the table if (Db.Driver.DatabaseEngine == DatabaseEngine.Sqlite) { // Use a memory efficient way to export this stuff StringBuilder Data = new StringBuilder(); foreach(Dictionary<string, object> Row in Db.Driver.QueryReader("SELECT * FROM " + Table)) Data.AppendLine(String.Join("\t", Row.Values)); // Write to file File.AppendAllText(BakFile, Data.ToString()); } else Db.Driver.Execute(String.Format("SELECT * INTO OUTFILE '{0}' FROM {1}", BakFile.Replace('\\', '/'), Table)); } catch (Exception Ex) { // Close loading form LoadingForm.CloseForm(); // Display the Exception Form ExceptionForm Form = new ExceptionForm(Ex, false); Form.Message = "An error occured while trying to backup the \"" + Table + "\" table. " + "The backup operation will now be cancelled."; DialogResult Result = Form.ShowDialog(); Aborted = true; // Try and remove backup folder try { DirectoryInfo Dir = new DirectoryInfo(Folder); Dir.Delete(true); } catch { } } if (Aborted) break; } // Only display success message if we didnt abort if (!Aborted) { // Close loading form LoadingForm.CloseForm(); string NL = Environment.NewLine; MessageBox.Show( String.Concat("Backup has been completed successfully!", NL, NL, "Backup files have been saved to:", NL, Folder), "Backup Success", MessageBoxButtons.OK, MessageBoxIcon.Information ); } }
/// <summary> /// Backs up the asp database /// </summary> private void ExportAsASPBtn_Click(object sender, EventArgs e) { // Define backup folder for this backup, and create it if it doesnt exist string Folder = Path.Combine(Paths.DocumentsFolder, "Backups", "bak_" + DateTime.Now.ToString("yyyyMMdd_HHmm")); if (!Directory.Exists(Folder)) Directory.CreateDirectory(Folder); // Abortion indicator bool Aborted = false; // Open the database connection StatsDatabase Database; try { Database = new StatsDatabase(); } catch (Exception Ex) { MessageBox.Show( "Unable to connect to database\r\n\r\nMessage: " + Ex.Message, "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); // Stop the ASP server, and close this form ASP.ASPServer.Stop(); this.Close(); return; } // Show loading screen LoadingForm.ShowScreen(this); // Backup each table into its own bak file foreach (string Table in StatsDatabase.StatsTables) { // Create file path string BakFile = Path.Combine(Folder, Table + ".bak"); // Backup tables try { using (Stream Str = File.Open(BakFile, FileMode.Create)) using (StreamWriter Wtr = new StreamWriter(Str)) { // Use a memory efficient way to export this stuff foreach (Dictionary<string, object> Row in Database.QueryReader("SELECT * FROM " + Table)) Wtr.WriteLine(String.Join("\t", Row.Values)); Wtr.Flush(); } } catch (Exception Ex) { // Close loading form LoadingForm.CloseForm(); // Display the Exception Form ExceptionForm Form = new ExceptionForm(Ex, false); Form.Message = "An error occured while trying to backup the \"" + Table + "\" table. " + "The backup operation will now be cancelled."; DialogResult Result = Form.ShowDialog(); Aborted = true; // Try and remove backup folder try { DirectoryInfo Dir = new DirectoryInfo(Folder); Dir.Delete(true); } catch { } } if (Aborted) break; } // Only display success message if we didnt abort if (!Aborted) { // Close loading form LoadingForm.CloseForm(); string NL = Environment.NewLine; MessageBox.Show( String.Concat("Backup has been completed successfully!", NL, NL, "Backup files have been saved to:", NL, Folder), "Backup Success", MessageBoxButtons.OK, MessageBoxIcon.Information ); } // Close the connection Database.Dispose(); }
/// <summary> /// Delete Player Button Click Event /// </summary> private 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); ASPServer.Database.DeletePlayer(Pid, true); Notify.Show("Player Deleted Successfully!", AlertType.Success); } catch (Exception E) { // Show exception error 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> /// Backs up the asp database /// </summary> private void ExportAsASPBtn_Click(object sender, EventArgs e) { // Define backup folder for this backup, and create it if it doesnt exist string Folder = Path.Combine(Paths.DocumentsFolder, "Database Backups", "bak_" + DateTime.Now.ToString("yyyyMMdd_HHmm")); if (!Directory.Exists(Folder)) { Directory.CreateDirectory(Folder); } // Abortion indicator bool Aborted = false; // Open the database connection StatsDatabase Database; try { Database = new StatsDatabase(); } catch (Exception Ex) { MessageBox.Show( "Unable to connect to database\r\n\r\nMessage: " + Ex.Message, "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); // Stop the ASP server, and close this form HttpServer.Stop(); this.Close(); return; } // Show loading screen LoadingForm.ShowScreen(this); // Backup each table into its own bak file foreach (string Table in StatsDatabase.StatsTables) { // Create file path string BakFile = Path.Combine(Folder, Table + ".bak"); // Backup tables try { using (Stream Str = File.Open(BakFile, FileMode.OpenOrCreate)) using (StreamWriter Wtr = new StreamWriter(Str)) { // Use a memory efficient way to export this stuff foreach (Dictionary <string, object> Row in Database.QueryReader("SELECT * FROM " + Table)) { Wtr.WriteLine(String.Join("\t", Row.Values)); } Wtr.Flush(); } } catch (Exception Ex) { // Close loading form LoadingForm.CloseForm(); // Display the Exception Form using (ExceptionForm Form = new ExceptionForm(Ex, false)) { Form.Message = "An error occured while trying to backup the \"" + Table + "\" table. " + "The backup operation will now be cancelled."; DialogResult Result = Form.ShowDialog(); } Aborted = true; // Try and remove backup folder try { DirectoryInfo Dir = new DirectoryInfo(Folder); Dir.Delete(true); } catch { } } if (Aborted) { break; } } // Only display success message if we didnt abort if (!Aborted) { // Close loading form LoadingForm.CloseForm(); string NL = Environment.NewLine; MessageBox.Show( String.Concat("Backup has been completed successfully!", NL, NL, "Backup files have been saved to:", NL, Folder), "Backup Success", MessageBoxButtons.OK, MessageBoxIcon.Information ); } // Close the connection Database.Dispose(); }
/// <summary> /// Imports the provided snapshot files into the stats database /// </summary> /// <param name="Files">List of snapshot file paths to import</param> /// <param name="CancelToken">Cancellation token, to cancel the import</param> private void ImportSnaphotFiles(List<SnapshotFile> Files, CancellationToken CancelToken) { // Number of snapshots we have processed int processed = 0; // Do Work foreach (SnapshotFile SnapshotFile in Files) { // If we have a cancelation request if (CancelToken.IsCancellationRequested) break; // Make sure we arent processing twice if (SnapshotFile.IsProcessed) continue; // Process the snapshot try { // Update status and run snapshot TaskForm.Progress.Report(new TaskProgressUpdate(String.Format("Processing: \"{0}\"", SnapshotFile))); Snapshot Snapshot = new Snapshot(File.ReadAllText(SnapshotFile.FilePath)); // Avoid processing exception if (Snapshot.IsProcessed) continue; else // Do snapshot Snapshot.ProcessData(); // Move the Temp snapshot to the Processed folder File.Move( Path.Combine(Paths.SnapshotTempPath, SnapshotFile.FileName), Path.Combine(Paths.SnapshotProcPath, SnapshotFile.FileName) ); } catch (Exception E) { using (ExceptionForm Form = new ExceptionForm(E, true)) { Form.Message = "An exception was thrown while trying to import the snapshot." + "If you click Continue, the application will continue proccessing the remaining " + "snapshot files. If you click Quit, the operation will be aborted."; DialogResult Result = Form.ShowDialog(); // User Abort if (Result == DialogResult.Abort) break; } } // Whether we failed or succeeded, we are finished with this step // and should move the progress bar 1 step TaskForm.Progress.Report(new TaskProgressUpdate(++processed)); } // Let progress bar update to 100% TaskForm.Progress.Report(new TaskProgressUpdate("Done! Cleaning up...")); Thread.Sleep(250); }
/// <summary> /// Handles cross thread exceptions, that are unrecoverable /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { // Create Trace Log string FileName = Path.Combine(Paths.DocumentsFolder, "traceLog_" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".txt"); Exception Ex = e.ExceptionObject as Exception; GenerateTraceLog(FileName, Ex); // Display the Exception Form ExceptionForm EForm = new ExceptionForm(Ex, false); EForm.Message = "An unhandled exception was thrown while trying to preform the requested task.\r\n" + "A trace log was generated under the \"My Documents/BF2Stastistics\" folder, to " + "assist with debugging, and getting help with this error."; EForm.LogFile = FileName; EForm.ShowDialog(); Application.Exit(); }
/// <summary> /// Displays a custom version of this form to display Razor template compile errors /// </summary> public static DialogResult ShowTemplateError(TemplateCompilationException E, string TemplateFile) { using (ExceptionForm F = new ExceptionForm(E, true)) { // Get our relative path from the program root string fileRelativePath = TemplateFile.Replace(Program.RootPath, ""); // Set the window properties F.WindowTitle = "Compile Error"; F.HeaderText = "Template Compile Error"; F.Message = "An error occured while trying to compile the file \"" + Path.GetFileName(fileRelativePath) + "\""; F.ImgIcon = Properties.Resources.vistaWarning; if (E.CompilerErrors.Count > 0) { StringBuilder builder = new StringBuilder(); // Append each error's details into the Details stringbuilder foreach (RazorEngineCompilerError error in E.CompilerErrors) { builder.AppendLine("Compile Error:"); builder.AppendLine(error.ErrorText); builder.AppendLine(); builder.AppendLine("Error #: " + error.ErrorNumber); builder.AppendLine("File: " + fileRelativePath); builder.AppendLine("Line: " + error.Line); builder.AppendLine("Column: " + error.Column); builder.AppendLine(); } // Set the Details pane contents F.ExceptionDetails.Text = builder.ToString(); } else { F.ExceptionDetails.Text = E.Message; } return F.ShowDialog(false); } }
/// <summary> /// Reset stats button click event /// </summary> private 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); ASPServer.Database.DeletePlayer(Pid, true); // 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"] ); LoadPlayer(); Notify.Show("Player Stats Reset Successfully!", AlertType.Success); } catch (Exception E) { // Show exception error 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> /// 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> /// Handles an exception on the main thread. /// </summary> /// <param name="sender"></param> /// <param name="t"></param> public static void OnThreadException(object sender, ThreadExceptionEventArgs t) { // Create Trace Log string FileName = Path.Combine(Paths.DocumentsFolder, "ExceptionLog_" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".txt"); try { // Try to generate a trace log GenerateExceptionLog(FileName, t.Exception); } catch { } // Display the Exception Form ExceptionForm EForm = new ExceptionForm(t.Exception, true); EForm.Message = "An unhandled exception was thrown while trying to preform the requested task.\r\n" + "If you click Continue, the application will attempt to ignore this error, and continue. " + "If you click Quit, the application will close immediatly."; EForm.TraceLog = FileName; DialogResult Result = EForm.ShowDialog(); // Kill the form on abort if (Result == DialogResult.Abort) Application.Exit(); }
/// <summary> /// This button restores the clients Ranked Python files to the original state /// </summary> private void BF2sRestoreBtn_Click(object sender, EventArgs e) { // Confirm that the user wants to do this if (MessageBox.Show( "Restoring the BF2Statistics python files will erase any and all modifications to the BF2Statistics " + "python files. Are you sure you want to continue?", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) { // Lock the console to prevent errors! this.Enabled = false; LoadingForm.ShowScreen(this); // Replace files with the originals try { StatsPython.RestoreRankedPyFiles(); // Reset medal data profile if (StatsPython.Installed) { StatsPython.Config.MedalDataProfile = ""; StatsPython.Config.Save(); } // Show Success Message Notify.Show("Stats Python Files Have Been Restored!", "Operation Successful", AlertType.Success); } catch (Exception E) { using (ExceptionForm EForm = new ExceptionForm(E, false)) { EForm.Message = "Failed to restore stats python files!"; EForm.ShowDialog(); } } finally { this.Enabled = true; LoadingForm.CloseForm(); } } }
/// <summary> /// Handles cross thread exceptions, that are unrecoverable /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { // Create Trace Log string FileName = Path.Combine(Paths.DocumentsFolder, "ExceptionLog_" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".txt"); Exception Ex = e.ExceptionObject as Exception; ExceptionForm EForm = new ExceptionForm(Ex, false); try { // Try to generate a trace log GenerateExceptionLog(FileName, Ex); // Display the Exception Form EForm.Message = "An unhandled exception was thrown while trying to preform the requested task.\r\n" + "A trace log was generated under the \"My Documents/BF2Stastistics\" folder, to " + "assist with debugging, and getting help with this error."; EForm.TraceLog = FileName; } catch { EForm.Message = "An unhandled exception was thrown while trying to preform the requested task.\r\n" + "A trace log was unable to be generated because that threw another exception :(. The error message " + "for the trace log was stored in the program error log for debugging purposes."; } finally { EForm.ShowDialog(); Application.Exit(); } }
/// <summary> /// Export Player Button Click Event /// </summary> private void ExportPlayerBtn_Click(object sender, EventArgs e) { // Create export directory if it doesnt exist yet string sPath = Path.Combine(Paths.DocumentsFolder, "Player Backups"); if (!Directory.Exists(sPath)) Directory.CreateDirectory(sPath); // Have user select folder FolderSelect.FolderSelectDialog Dialog = new FolderSelect.FolderSelectDialog(); Dialog.InitialDirectory = sPath; Dialog.Title = "Select folder to export player to"; if (Dialog.ShowDialog()) { try { StatsManager.ExportPlayerXml(sPath, Pid, Player["name"].ToString()); Notify.Show("Player Exported Successfully", String.Format("{0} ({1})", Player["name"].ToString(), Pid), AlertType.Success); } catch (DbConnectException Ex) { HttpServer.Stop(); ExceptionForm.ShowDbConnectError(Ex); this.Close(); } catch (Exception E) { using (ExceptionForm EForm = new ExceptionForm(E, false)) { EForm.Message = "Unable to export player because an exception was thrown!"; EForm.ShowDialog(); } } } }
/// <summary> /// Imports ASP created BAK files (Mysql Out FILE) /// </summary> private 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, "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; try { Database = new StatsDatabase(); } catch (Exception Ex) { MessageBox.Show( "Unable to connect to database\r\n\r\nMessage: " + Ex.Message, "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); // Stop the ASP server, and close this form ASP.ASPServer.Stop(); this.Close(); return; } // Show task dialog TaskForm.Show(this, "Importing Stats", "Importing ASP Stats Bak Files...", false); TaskForm.UpdateStatus("Removing old stats data"); // Clear old database records Database.Truncate(); Thread.Sleep(500); // Begin transaction DbTransaction Transaction = Database.BeginTransaction(); // import each table foreach (string file in BakFiles) { // Get table name string table = Path.GetFileNameWithoutExtension(file); // Update progress TaskForm.UpdateStatus("Processing stats table: " + table); // Import table data try { // Sqlite kinda sucks... no import methods if (Database.DatabaseEngine == DatabaseEngine.Sqlite) { string[] Lines = File.ReadAllLines(file); foreach (string line in Lines) { string[] Values = line.Split('\t'); Database.Execute( String.Format("INSERT INTO {0} VALUES({1})", table, "\"" + String.Join("\", \"", Values) + "\"") ); } } else Database.Execute(String.Format("LOAD DATA LOCAL INFILE '{0}' INTO TABLE {1};", file.Replace('\\', '/'), table)); } catch (Exception Ex) { // Show exception error ExceptionForm Form = new ExceptionForm(Ex, false); Form.Message = String.Format("Failed to import data into table {0}!{2}{2}Error: {1}", table, Ex.Message, Environment.NewLine); DialogResult Result = Form.ShowDialog(); // Rollback! TaskForm.UpdateStatus("Rolling back stats data"); Transaction.Rollback(); // Update message TaskForm.CloseForm(); return; } } // Commit the transaction, and alert the user Transaction.Commit(); TaskForm.CloseForm(); Notify.Show("Stats imported successfully!", "Operation Successful", AlertType.Success); // 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> /// 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(); } } }
private void bWorker_DoWork(object sender, DoWorkEventArgs e) { // Loop through each snapshot, and process it List<string> Files = e.Argument as List<string>; TaskForm.Show(this, "Importing Snapshots", "Importing Snapshots", true, ProgressBarStyle.Blocks, Files.Count); int Selected = Files.Count; int i = 1; // Order snapshots by timestamp var Sorted = from _File in Files let parts = _File.Split('_') let date = int.Parse(parts[parts.Length - 2]) let time = int.Parse(parts[parts.Length - 1].Replace(".txt", "")) orderby date, time ascending select _File; // Do Work foreach (string Snapshot in Sorted) { // If we have a cancelation request if (bWorker.CancellationPending) { e.Cancel = true; break; } try { // Parse date of snapshot string[] Parts = Snapshot.Split('_'); string D = Parts[Parts.Length - 2] + "_" + Parts[Parts.Length - 1].Replace(".txt", ""); DateTime Date = DateTime.ParseExact(D, "yyyyMMdd_HHmm", CultureInfo.InvariantCulture).ToUniversalTime(); // Update status and run snapshot TaskForm.UpdateStatus(String.Format("Processing: \"{0}\"", Snapshot)); Snapshot Snap = new Snapshot(File.ReadAllText(Path.Combine(Paths.SnapshotTempPath, Snapshot)), Date); // Start Timer Stopwatch Timer = new Stopwatch(); Timer.Start(); // Do snapshot Snap.Process(); // Move the Temp snapshot to the Processed folder File.Move(Path.Combine(Paths.SnapshotTempPath, Snapshot), Path.Combine(Paths.SnapshotProcPath, Snapshot)); // increment i++; // Update progress TaskForm.ProgressBarStep(); // Slow thread to let progress update Thread.Sleep(250); } catch (Exception E) { ExceptionForm Form = new ExceptionForm(E, true); Form.Message = "An exception was thrown while trying to import the snapshot." + "If you click Continue, the application will continue proccessing the remaining " + "snapshot files. If you click Quit, the operation will be aborted."; DialogResult Result = Form.ShowDialog(); if (Result == System.Windows.Forms.DialogResult.Abort) break; } } // Let progress bar update to 100% TaskForm.UpdateStatus("Done! Cleaning up..."); Thread.Sleep(500); }
/// <summary> /// This method imports a list of .Bak files into the database /// </summary> /// <param name="BakFiles">A list of Backfiles to import into the database</param> /// <param name="Database">The opened database connection</param> private void ImportFromBakup(string[] BakFiles, StatsDatabase Database) { // Clear old database records TaskForm.Progress.Report(new TaskProgressUpdate("Removing old stats data")); Database.Truncate(); // Let the database update itself Thread.Sleep(500); // Begin transaction using (DbTransaction Transaction = Database.BeginTransaction()) { // import each table foreach (string file in BakFiles) { // Get table name string table = Path.GetFileNameWithoutExtension(file); TaskForm.Progress.Report(new TaskProgressUpdate("Processing stats table: " + table)); // Import table data try { // Sqlite kinda sucks... no import methods if (Database.DatabaseEngine == DatabaseEngine.Sqlite) { string[] Lines = File.ReadAllLines(file); foreach (string line in Lines) { string[] Values = line.Split('\t'); Database.Execute( String.Format("INSERT INTO {0} VALUES({1})", table, "\"" + String.Join("\", \"", Values) + "\"") ); } } else Database.Execute(String.Format("LOAD DATA LOCAL INFILE '{0}' INTO TABLE {1};", file.Replace('\\', '/'), table)); } catch (Exception Ex) { // Show exception error using (ExceptionForm Form = new ExceptionForm(Ex, false)) { Form.Message = String.Format("Failed to import data into table {0}!{2}{2}Error: {1}", table, Ex.Message, Environment.NewLine); DialogResult Result = Form.ShowDialog(); // Rollback! TaskForm.Progress.Report(new TaskProgressUpdate("Rolling back stats data")); Transaction.Rollback(); return; } } } // Commit the transaction Transaction.Commit(); } }