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