Skip to content

Commit

Permalink
Backups module (#56)
Browse files Browse the repository at this point in the history
* Create backup module that runs on program startup

* Update .gitignore to include backup files

---------

Co-authored-by: Aragorn <[email protected]>
  • Loading branch information
elendil7 and elendil7 authored Jan 15, 2024
1 parent 386c99f commit 3e374d2
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,6 @@ yarn-error.log*
/vue-expenses-api/obj
*.orig
*.user

# data files
backups
5 changes: 5 additions & 0 deletions vue-expenses-api/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Data;
using System.Net.NetworkInformation;
Expand All @@ -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;

Expand All @@ -32,6 +35,8 @@ public Startup(
public void ConfigureServices(
IServiceCollection services)
{
Backup.CreateBackup(Configuration.GetConnectionString("DefaultConnection"));

services.AddControllers()
.AddNewtonsoftJson();

Expand Down
36 changes: 36 additions & 0 deletions vue-expenses-api/Util/Backup.cs
Original file line number Diff line number Diff line change
@@ -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]);
}
}
}
}

0 comments on commit 3e374d2

Please sign in to comment.