/// <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> /// Reset Unlocks Button Click Event /// </summary> private void ResetUnlocksBtn_Click(object sender, EventArgs e) { try { // Create New Player Unlock Data StringBuilder Query = new StringBuilder("INSERT INTO unlocks VALUES "); // Normal unlocks for (int i = 11; i < 100; i += 11) { Query.AppendFormat("({0}, {1}, 'n'), ", Pid, i); } // Sf Unlocks for (int i = 111; i < 556; i += 111) { Query.AppendFormat("({0}, {1}, 'n')", Pid, i); if (i != 555) { Query.Append(", "); } } // Do driver queries using (StatsDatabase Driver = new StatsDatabase()) using (DbTransaction T = Driver.BeginTransaction()) { try { // Perform queries Driver.Execute("DELETE FROM unlocks WHERE id = " + Pid); Driver.Execute("UPDATE player SET usedunlocks = 0 WHERE id = " + Pid); Driver.Execute(Query.ToString()); T.Commit(); // Notify user Notify.Show("Player Unlocks Have Been Reset", "This player will be able to select his new unlocks upon logging in.", AlertType.Success); } catch { T.Rollback(); throw; } } } catch (DbConnectException Ex) { HttpServer.Stop(); ExceptionForm.ShowDbConnectError(Ex); this.Close(); } }
/// <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> /// 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; } }
public AccountListForm() { InitializeComponent(); SortedCol = DataTable.Columns[0]; // Try to connect to the database try { using (GamespyDatabase Driver = new GamespyDatabase()) { } } catch (DbConnectException Ex) { ExceptionForm.ShowDbConnectError(Ex); Load += (s, e) => Close(); // Close form return; } // Setting the limit will build the inital list LimitSelect.SelectedIndex = 2; }
/// <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> /// Constructor /// </summary> public PlayerSearchForm() { InitializeComponent(); // Establish DB connection try { Driver = new StatsDatabase(); } catch (DbConnectException Ex) { HttpServer.Stop(); ExceptionForm.ShowDbConnectError(Ex); Load += (s, e) => Close(); // Close form return; } // Initialize sorting SortedCol = DataTable.Columns[1]; SortedCol.HeaderCell.SortGlyphDirection = SortOrder.Ascending; LimitSelect.SelectedIndex = 2; }
/// <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 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> /// 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> /// 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 { if (StatsEnabled) { Directory.Delete(Paths.ServerPythonPath, true); System.Threading.Thread.Sleep(750); DirectoryExt.Copy(Path.Combine(Program.RootPath, "Python", "Ranked", "Original"), Paths.ServerPythonPath, true); } else { Directory.Delete(Paths.RankedPythonPath, true); System.Threading.Thread.Sleep(750); DirectoryExt.Copy(Path.Combine(Program.RootPath, "Python", "Ranked", "Original"), Paths.RankedPythonPath, true); } // Show Success Message Notify.Show("Stats Python Files Have Been Restored!", "Operation Successful", AlertType.Success); } catch (Exception E) { ExceptionForm EForm = new ExceptionForm(E, false); EForm.Message = "Failed to restore stats python files!"; EForm.Show(); } finally { this.Enabled = true; LoadingForm.CloseForm(); } } }
/// <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> /// 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> /// This button restores the clients Ranked Python files to the original state /// </summary> private void BF2sRestoreBtn_Click(object sender, EventArgs e) { 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) { try { // Lock the console to prevent errors! this.Enabled = false; if (StatsEnabled) { Directory.Delete(Paths.ServerPythonPath, true); DirectoryExt.Copy(Path.Combine(MainForm.Root, "Python", "Ranked", "Original"), Paths.ServerPythonPath, true); } else { Directory.Delete(Paths.RankedPythonPath, true); DirectoryExt.Copy(Path.Combine(MainForm.Root, "Python", "Ranked", "Original"), Paths.RankedPythonPath, true); } // Show Success Message Notify.Show("Stats Python Files Have Been Restored!", AlertType.Success); this.Enabled = true; // Unlock Form } catch (Exception E) { ExceptionForm EForm = new ExceptionForm(E, false); EForm.Message = "Failed to restore stats python files!"; EForm.Show(); this.Enabled = true; } } }
/// <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> /// 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> /// 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> /// 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> /// Save Button Click Event /// </summary> private void SaveBtn_Click(object sender, EventArgs e) { try { using (StatsDatabase Driver = new StatsDatabase()) { bool Changes = false; UpdateQueryBuilder Query = new UpdateQueryBuilder("player", Driver); int Rank = Int32.Parse(Player["rank"].ToString()); // Update clantag if (Player["clantag"].ToString() != ClanTagBox.Text.Trim()) { Player["clantag"] = ClanTagBox.Text.Trim(); Query.SetField("clantag", ClanTagBox.Text.Trim()); Changes = true; } // Update Rank if (Rank != RankSelect.SelectedIndex) { if (Rank > RankSelect.SelectedIndex) { Query.SetField("decr", 1); Query.SetField("chng", 0); } else { Query.SetField("decr", 0); Query.SetField("chng", 1); } Player["rank"] = RankSelect.SelectedIndex; Query.SetField("rank", RankSelect.SelectedIndex); Changes = true; } // update perm ban status if (Int32.Parse(Player["permban"].ToString()) != PermBanSelect.SelectedIndex) { Player["permban"] = PermBanSelect.SelectedIndex; Query.SetField("permban", PermBanSelect.SelectedIndex); Changes = true; } // If no changes made, just return if (!Changes) { MessageBox.Show("Unable to save player because no changes were made.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // Preform Query Query.AddWhere("id", Comparison.Equals, Pid); Query.Execute(); this.Close(); } } catch (DbConnectException Ex) { HttpServer.Stop(); ExceptionForm.ShowDbConnectError(Ex); return; } }
/// <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> /// Loads the players stats from the database, and fills out the forms /// labels with the current information /// </summary> private void LoadPlayer() { StatsDatabase Driver; // Establish DB connection try { Driver = new StatsDatabase(); } catch (DbConnectException Ex) { ExceptionForm.ShowDbConnectError(Ex); HttpServer.Stop(); Load += (s, e) => Close(); // Close form return; } // Fetch Player from database SelectQueryBuilder Builder = new SelectQueryBuilder(Driver); Builder.SelectFromTable("player"); Builder.SelectColumns( "name", "score", "cmdscore", "skillscore", "teamscore", "joined", "country", "rank", "wins", "losses", "permban", "clantag", "isbot"); Builder.AddWhere("id", Comparison.Equals, Pid); List <Dictionary <string, object> > Rows = Driver.ExecuteReader(Builder.BuildCommand()); Player = Rows[0]; // Set window title this.Text = String.Concat(Player["name"].ToString().Trim(), " (", Pid, ")"); // Set country flag try { string Country = String.IsNullOrEmpty(Player["country"].ToString()) ? "XX" : Player["country"].ToString(); CountryPicture.Image = Image.FromStream(Program.GetResource("BF2Statistics.Resources." + Country.ToUpper() + ".png")); } catch { } // Joined Label int Joind = Int32.Parse(Player["joined"].ToString()); DateTime D = DateTime.UtcNow.FromUnixTimestamp(Joind); LabelJoined.Text = String.Concat(D.ToString("yyyy-MM-dd HH:mm"), " GMT"); Tipsy.SetToolTip(LabelJoined, String.Concat(D.ToLocalTime().ToString("yyyy-MM-dd HH:mm"), " Local Time.")); // Fill out the rest of the labels LabelNick.Text = Player["name"].ToString().Trim(); ClanTagBox.Text = Player["clantag"].ToString(); RankSelect.SelectedIndex = Int32.Parse(Player["rank"].ToString()); PermBanSelect.SelectedIndex = Int32.Parse(Player["permban"].ToString()); LabelGlobalScore.Text = Player["score"].ToString(); LabelWinLoss.Text = String.Concat(Player["wins"], " / ", Player["losses"]); LabelTeamScore.Text = Player["teamscore"].ToString(); LabelCombatScore.Text = Player["skillscore"].ToString(); LabelCommandScore.Text = Player["cmdscore"].ToString(); // Get Leaderboard Position Rows = Driver.Query("SELECT COUNT(id) as count FROM player WHERE score > @P0", Int32.Parse(Player["score"].ToString())); int Position = Int32.Parse(Rows[0]["count"].ToString()) + 1; LabelPosition.Text = Position.ToString(); SaveBtn.Enabled = false; // Lock unlocks button if player is Bot if (Int32.Parse(Player["isbot"].ToString()) > 0) { ResetUnlocksBtn.Enabled = false; } // Close Connection Driver.Dispose(); }
/// <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> /// 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 ); } } }
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(); } }