From 3e374d24b0690a390fee6948be3e6e434f3d6aed Mon Sep 17 00:00:00 2001 From: Aragorn <80429382+elendil7@users.noreply.github.com> Date: Mon, 15 Jan 2024 06:45:07 +0000 Subject: [PATCH] Backups module (#56) * Create backup module that runs on program startup * Update .gitignore to include backup files --------- Co-authored-by: Aragorn <80429382+AragornElessar1973@users.noreply.github.com> --- .gitignore | 3 +++ vue-expenses-api/Startup.cs | 5 +++++ vue-expenses-api/Util/Backup.cs | 36 +++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) create mode 100644 vue-expenses-api/Util/Backup.cs diff --git a/.gitignore b/.gitignore index 0d7264c..20af9f9 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,6 @@ yarn-error.log* /vue-expenses-api/obj *.orig *.user + +# data files +backups \ No newline at end of file diff --git a/vue-expenses-api/Startup.cs b/vue-expenses-api/Startup.cs index 98fe9c8..12d4b96 100644 --- a/vue-expenses-api/Startup.cs +++ b/vue-expenses-api/Startup.cs @@ -1,3 +1,5 @@ +using System; +using System.IO; using System.Collections.Generic; using System.Data; using System.Net.NetworkInformation; @@ -16,6 +18,7 @@ using vue_expenses_api.Infrastructure; using vue_expenses_api.Infrastructure.Security; using vue_expenses_api.Infrastructure.Validation; +using static Backup; namespace vue_expenses_api; @@ -32,6 +35,8 @@ public Startup( public void ConfigureServices( IServiceCollection services) { + Backup.CreateBackup(Configuration.GetConnectionString("DefaultConnection")); + services.AddControllers() .AddNewtonsoftJson(); diff --git a/vue-expenses-api/Util/Backup.cs b/vue-expenses-api/Util/Backup.cs new file mode 100644 index 0000000..9c46143 --- /dev/null +++ b/vue-expenses-api/Util/Backup.cs @@ -0,0 +1,36 @@ +using System; +using System.IO; + +public class Backup{ + public Backup(){ + + } + + public static void CreateBackup(string expensesFilePath){ + string backupDirectory = "App_Data/backups"; + if (!Directory.Exists(backupDirectory)) + { + Directory.CreateDirectory(backupDirectory); + } + + expensesFilePath = expensesFilePath.Replace("Data Source=", ""); + + string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss"); + + string backupFilePath = Path.Combine(backupDirectory, $"{timestamp}.expenses.db"); + + File.Copy(expensesFilePath, backupFilePath, true); + + int maxBackups = 5; + string[] backupFiles = Directory.GetFiles(backupDirectory, "*.expenses.db"); + + if (backupFiles.Length > maxBackups) + { + Array.Sort(backupFiles); + for (int i = 0; i < backupFiles.Length - maxBackups; i++) + { + File.Delete(backupFiles[i]); + } + } + } +} \ No newline at end of file