Files
modernkeepass/ModernKeePass.Application/Database/Commands/SaveDatabase/SaveDatabaseCommand.cs

51 lines
1.6 KiB
C#
Raw Normal View History

2020-04-08 15:27:40 +02:00
using System;
using MediatR;
using System.Threading.Tasks;
using ModernKeePass.Application.Common.Interfaces;
using ModernKeePass.Domain.Exceptions;
namespace ModernKeePass.Application.Database.Commands.SaveDatabase
{
public class SaveDatabaseCommand : IRequest
{
public string FilePath { get; set; }
public class SaveDatabaseCommandHandler : IAsyncRequestHandler<SaveDatabaseCommand>
{
private readonly IDatabaseProxy _database;
private readonly IFileProxy _file;
public SaveDatabaseCommandHandler(IDatabaseProxy database, IFileProxy file)
{
_database = database;
_file = file;
}
public async Task Handle(SaveDatabaseCommand message)
{
if (!_database.IsOpen) throw new DatabaseClosedException();
2020-04-08 15:27:40 +02:00
try
{
if (!string.IsNullOrEmpty(message.FilePath))
2020-04-08 15:27:40 +02:00
{
_database.FileAccessToken = message.FilePath;
}
2020-04-08 15:27:40 +02:00
var contents = await _database.SaveDatabase();
2020-04-08 15:27:40 +02:00
// Test DB integrity
_database.CloseDatabase();
await _database.ReOpen(contents);
2020-04-08 15:27:40 +02:00
// Transactional write to file
await _file.WriteBinaryContentsToFile(_database.FileAccessToken, contents);
}
2020-04-15 19:06:13 +02:00
catch (Exception exception)
{
2020-04-08 15:27:40 +02:00
throw new SaveException(exception);
}
}
}
}
}