Skip to content

Commit

Permalink
chore: clean code (#184)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexsee authored Mar 19, 2023
1 parent a69c0bb commit b0b996e
Show file tree
Hide file tree
Showing 28 changed files with 584 additions and 667 deletions.
1 change: 1 addition & 0 deletions src/BSH.Engine/BSH.Engine.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<Title>Backup Service Home</Title>
<Platforms>x64</Platforms>
<Configurations>Debug;Release;Windows 10</Configurations>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<OutputPath>bin\x64\Debug\</OutputPath>
Expand Down
58 changes: 28 additions & 30 deletions src/BSH.Engine/ConfigurationManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -392,57 +392,55 @@ public ConfigurationManager(DbClientFactory dbClientFactory)

public async Task LoadConfigurationAsync()
{
using (var dbClient = dbClientFactory.CreateDbClient())
using var dbClient = dbClientFactory.CreateDbClient();

foreach (var configEntry in GetType().GetProperties())
{
foreach (var configEntry in GetType().GetProperties())
if (configEntry == null)
{
if (configEntry == null)
{
continue;
}
continue;
}

var parameters = new IDataParameter[] {
var parameters = new IDataParameter[] {
dbClient.CreateParameter("value", DbType.String, 1024, configEntry.Name.Replace("_", ""))
};

var result = await dbClient.ExecuteScalarAsync(CommandType.Text, "SELECT confValue FROM configuration WHERE confProperty LIKE @value LIMIT 1", parameters);
var result = await dbClient.ExecuteScalarAsync(CommandType.Text, "SELECT confValue FROM configuration WHERE confProperty LIKE @value LIMIT 1", parameters);

if (result == null || result.Equals(DBNull.Value))
{
continue;
}
if (result == null || result.Equals(DBNull.Value))
{
continue;
}

if (configEntry.Name == "Status" || configEntry.Name == "TaskType" || configEntry.Name == "Compression" || configEntry.Name == "Encrypt" || configEntry.Name == "MediumType")
{
if (int.TryParse(result.ToString(), out int val))
{
configEntry.SetValue(this, val);
}
}
else
if (configEntry.Name == "Status" || configEntry.Name == "TaskType" || configEntry.Name == "Compression" || configEntry.Name == "Encrypt" || configEntry.Name == "MediumType")
{
if (int.TryParse(result.ToString(), out int val))
{
configEntry.SetValue(this, result);
configEntry.SetValue(this, val);
}
}
else
{
configEntry.SetValue(this, result);
}
}
}

private void SaveProperty(string property, string value)
{
using (var dbClient = dbClientFactory.CreateDbClient())
using var dbClient = dbClientFactory.CreateDbClient();

var parameters = new IDataParameter[]
{
var parameters = new IDataParameter[]
{
dbClient.CreateParameter("value", DbType.String, 255, value),
dbClient.CreateParameter("prop", DbType.String, 255, property.ToLower())
};
};

var result = dbClient.ExecuteNonQuery(CommandType.Text, "UPDATE configuration SET confValue = @value WHERE confProperty = @prop", parameters);
var result = dbClient.ExecuteNonQuery(CommandType.Text, "UPDATE configuration SET confValue = @value WHERE confProperty = @prop", parameters);

if (result == 0)
{
dbClient.ExecuteNonQuery(CommandType.Text, "INSERT INTO configuration VALUES (@prop, @value)", parameters);
}
if (result == 0)
{
dbClient.ExecuteNonQuery(CommandType.Text, "INSERT INTO configuration VALUES (@prop, @value)", parameters);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/BSH.Engine/Database/DbClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class DbClient : IDisposable
DbConnection _connection;
DbTransaction _transaction;
DbProviderFactory _factory;
readonly Dictionary<string, DbCommand> _commands = new Dictionary<string, DbCommand>();
readonly Dictionary<string, DbCommand> _commands = new();

#endregion

Expand Down
8 changes: 5 additions & 3 deletions src/BSH.Engine/Jobs/BackupJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public class BackupJob : Job
{
private static readonly ILogger _logger = Log.ForContext<BackupJob>();

private readonly HashSet<string> junctionFolders = new HashSet<string>();
private readonly HashSet<string> junctionFolders = new();

public string Title { get; set; }

Expand Down Expand Up @@ -371,8 +371,10 @@ public async Task BackupAsync(CancellationToken token)
queryManager.Configuration.LastBackupDone = newVersionDate;
queryManager.Configuration.LastVersionDate = "";

int.TryParse(queryManager.Configuration.OldBackupPrevent, out int databaseVersion);
queryManager.Configuration.OldBackupPrevent = (databaseVersion + 1).ToString();
if (int.TryParse(queryManager.Configuration.OldBackupPrevent, out int databaseVersion))
{
queryManager.Configuration.OldBackupPrevent = (databaseVersion + 1).ToString();
}
}

// refresh free diskspace
Expand Down
40 changes: 19 additions & 21 deletions src/BSH.Engine/Jobs/DeleteJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,8 @@ public async Task DeleteAsync()
{
queryManager.Configuration.FreeSpace = storage.GetFreeSpace().ToString();

using (var dbClient = dbClientFactory.CreateDbClient())
{
queryManager.Configuration.BackupSize = (await dbClient.ExecuteScalarAsync("SELECT SUM(FileSize) FROM fileversiontable")).ToString();
}
using var dbClient = dbClientFactory.CreateDbClient();
queryManager.Configuration.BackupSize = (await dbClient.ExecuteScalarAsync("SELECT SUM(FileSize) FROM fileversiontable")).ToString();
}
catch (Exception ex)
{
Expand All @@ -180,30 +178,30 @@ public async Task DeleteAsync()
// clean storage folders
if (storage is FileSystemStorage)
{
using (var dbClient = dbClientFactory.CreateDbClient())
using (var reader = await dbClient.ExecuteDataReaderAsync(CommandType.Text, "SELECT versiondate FROM versiontable WHERE versionid NOT IN (SELECT filepackage FROM fileversiontable)", null))
using var dbClient = dbClientFactory.CreateDbClient();
using var reader = await dbClient.ExecuteDataReaderAsync(CommandType.Text, "SELECT versiondate FROM versiontable WHERE versionid NOT IN (SELECT filepackage FROM fileversiontable)", null);

while (reader.Read())
{
while (reader.Read())
try
{
try
{
var remoteFolder = reader.GetString("versiondate");
storage.DeleteDirectory(remoteFolder);
}
catch
{
// not necessary to handle this error
}
var remoteFolder = reader.GetString("versiondate");
storage.DeleteDirectory(remoteFolder);
}
catch
{
// not necessary to handle this error
}

reader.Close();
}

reader.Close();
}

// store database version
int.TryParse(queryManager.Configuration.OldBackupPrevent, out int databaseVersion);

queryManager.Configuration.OldBackupPrevent = (databaseVersion + 1).ToString();
if (int.TryParse(queryManager.Configuration.OldBackupPrevent, out int databaseVersion))
{
queryManager.Configuration.OldBackupPrevent = (databaseVersion + 1).ToString();
}

// refresh free diskspace
await UpdateFreeDiskSpaceAsync();
Expand Down
77 changes: 38 additions & 39 deletions src/BSH.Engine/Jobs/DeleteSingleJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,54 +128,52 @@ public async Task DeleteSingleAsync(string fileFilter, string pathFilter)
dbClient.CreateParameter("fileId", DbType.Int32, 0, fileId)
};

using (var reader = await dbClient.ExecuteDataReaderAsync(CommandType.Text,
using var reader = await dbClient.ExecuteDataReaderAsync(CommandType.Text,
"SELECT * FROM fileVersionTable AS fvt " +
"INNER JOIN fileTable AS ft ON " +
" ft.fileID = fvt.fileID " +
"INNER JOIN versionTable AS vt ON " +
" fvt.filePackage = vt.versionID " +
"WHERE fvt.fileID = @fileId",
deleteFileParams))
deleteFileParams);
int i = 0;
while (reader.Read())
{
int i = 0;
while (reader.Read())
{
// get file name
var fileName = reader.GetString("filePath") + reader.GetString("fileName");
// get file name
var fileName = reader.GetString("filePath") + reader.GetString("fileName");

ReportFileProgress(fileName);
ReportProgress(fileIds.Count, i);
i++;
ReportFileProgress(fileName);
ReportProgress(fileIds.Count, i);
i++;

// delete file
try
{
DeleteFileFromDevice(
reader.GetString("fileName"),
reader.GetString("filePath"),
reader.GetString("longfilename"),
reader.GetString("versionDate"),
reader.GetInt32("fileType").ToString()
);
}
catch (FileNotProcessedException ex)
// delete file
try
{
DeleteFileFromDevice(
reader.GetString("fileName"),
reader.GetString("filePath"),
reader.GetString("longfilename"),
reader.GetString("versionDate"),
reader.GetInt32("fileType").ToString()
);
}
catch (FileNotProcessedException ex)
{
// file not deleted
FileErrorList.Add(new FileExceptionEntry()
{
// file not deleted
FileErrorList.Add(new FileExceptionEntry()
{
File = new FileTableRow() { FileName = reader.GetString("fileName"), FilePath = reader.GetString("filePath") },
Exception = ex
});

_logger.Error(ex.InnerException, "File {fileName} could not be deleted.", reader.GetString("fileName"));
}

// add to deleted id list
fileVersionIds.Add(reader.GetInt32(reader.GetOrdinal("fileversionid")));
File = new FileTableRow() { FileName = reader.GetString("fileName"), FilePath = reader.GetString("filePath") },
Exception = ex
});

_logger.Error(ex.InnerException, "File {fileName} could not be deleted.", reader.GetString("fileName"));
}

reader.Close();
// add to deleted id list
fileVersionIds.Add(reader.GetInt32(reader.GetOrdinal("fileversionid")));
}

reader.Close();
}

// delete metadata from database
Expand All @@ -199,7 +197,7 @@ public async Task DeleteSingleAsync(string fileFilter, string pathFilter)
// delete metadata
await dbClient.ExecuteNonQueryAsync(CommandType.Text, "DELETE FROM fileLink WHERE fileversionid IN (SELECT fileversionid FROM fileversiontable AS fvt WHERE fvt.fileID IN (" + subQuerySQL + "))", deleteParams.ToArray());
await dbClient.ExecuteNonQueryAsync(CommandType.Text, "DELETE FROM fileversiontable WHERE fileID IN (" + subQuerySQL + ")", deleteParams.ToArray());
await dbClient.ExecuteNonQueryAsync(CommandType.Text, "DELETE FROM fileTable AS ft WHERE " + subQuerySQL.Substring(subQuerySQL.IndexOf("WHERE ") + 6), deleteParams.ToArray());
await dbClient.ExecuteNonQueryAsync(CommandType.Text, "DELETE FROM fileTable AS ft WHERE " + subQuerySQL[(subQuerySQL.IndexOf("WHERE ") + 6)..], deleteParams.ToArray());

dbClient.CommitTransaction();
}
Expand All @@ -214,9 +212,10 @@ public async Task DeleteSingleAsync(string fileFilter, string pathFilter)
await UpdateFreeDiskSpaceAsync();

// store database version
int.TryParse(queryManager.Configuration.OldBackupPrevent, out int databaseVersion);

queryManager.Configuration.OldBackupPrevent = (databaseVersion + 1).ToString();
if (int.TryParse(queryManager.Configuration.OldBackupPrevent, out int databaseVersion))
{
queryManager.Configuration.OldBackupPrevent = (databaseVersion + 1).ToString();
}

// close all database connections
DbClientFactory.ClosePool();
Expand Down
8 changes: 3 additions & 5 deletions src/BSH.Engine/Jobs/Job.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public abstract class Job

protected readonly bool silent;

private readonly List<IJobReport> observers = new List<IJobReport>();
private readonly List<IJobReport> observers = new();

protected Job(IStorage storage, DbClientFactory dbClientFactory, QueryManager queryManager, bool silent = false)
{
Expand Down Expand Up @@ -207,10 +207,8 @@ protected async Task UpdateFreeDiskSpaceAsync()
{
queryManager.Configuration.FreeSpace = storage.GetFreeSpace().ToString();

using (var dbClient = dbClientFactory.CreateDbClient())
{
queryManager.Configuration.BackupSize = (await dbClient.ExecuteScalarAsync("SELECT SUM(FileSize) FROM fileversiontable")).ToString();
}
using var dbClient = dbClientFactory.CreateDbClient();
queryManager.Configuration.BackupSize = (await dbClient.ExecuteScalarAsync("SELECT SUM(FileSize) FROM fileversiontable")).ToString();
}
catch (Exception ex)
{
Expand Down
8 changes: 4 additions & 4 deletions src/BSH.Engine/Jobs/RestoreJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -200,15 +200,15 @@ public async Task RestoreAsync(CancellationToken token)
{
var idx = fileDest.ToLower().IndexOf(("\\" + Path.GetFileName(folder) + "\\").ToLower());

fileDest = folder + "\\" + fileDest.Substring(idx + Path.GetFileName(folder).Length + 2);
fileDest = folder + "\\" + fileDest[(idx + Path.GetFileName(folder).Length + 2)..];
break;
}
}
}
else
{
// path found
fileDest = fileDest.Substring(fileDest.IndexOf("\\", 2) + 1);
fileDest = fileDest[(fileDest.IndexOf("\\", 2) + 1)..];
fileDest = destFolders[0] + "\\" + fileDest;
}

Expand Down Expand Up @@ -277,15 +277,15 @@ public async Task RestoreAsync(CancellationToken token)
{
var idx = fileDest.ToLower().IndexOf(("\\" + Path.GetFileName(folder) + "\\").ToLower());

fileDest = folder + "\\" + fileDest.Substring(idx + Path.GetFileName(folder).Length + 2);
fileDest = folder + "\\" + fileDest[(idx + Path.GetFileName(folder).Length + 2)..];
break;
}
}
}
else
{
// path found
fileDest = fileDest.Substring(fileDest.IndexOf("\\", 2) + 1);
fileDest = fileDest[(fileDest.IndexOf("\\", 2) + 1)..];
fileDest = destFolders[0] + "\\" + fileDest;
}

Expand Down
Loading

0 comments on commit b0b996e

Please sign in to comment.