WIP ViewModelLocator - Messenger and Recent issues

Refactoring
Code cleanup
This commit is contained in:
Geoffroy BONNEVILLE
2020-04-23 19:00:38 +02:00
parent 2b8f9bd5f0
commit d211453553
59 changed files with 309 additions and 934 deletions

View File

@@ -1,191 +0,0 @@
using System;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using ModernKeePass.Application.Common.Interfaces;
using ModernKeePass.Application.Database.Commands.CreateDatabase;
using ModernKeePass.Application.Database.Commands.UpdateCredentials;
using ModernKeePass.Application.Database.Queries.GetDatabase;
using ModernKeePass.Application.Database.Queries.OpenDatabase;
using ModernKeePass.Application.Security.Commands.GenerateKeyFile;
using ModernKeePass.Application.Security.Queries.EstimatePasswordComplexity;
using ModernKeePass.Domain.Dtos;
namespace ModernKeePass.ViewModels
{
public class CompositeKeyVm: ObservableObject
{
public enum StatusTypes
{
Normal = 0,
Error = 1,
Warning = 3,
Success = 5
}
public bool HasPassword
{
get { return _hasPassword; }
set
{
Set(() => HasPassword, ref _hasPassword, value);
RaisePropertyChanged(nameof(IsValid));
}
}
public bool HasKeyFile
{
get { return _hasKeyFile; }
set
{
Set(() => HasKeyFile, ref _hasKeyFile, value);
RaisePropertyChanged(nameof(IsValid));
}
}
public bool IsValid => !_isOpening && (HasPassword || HasKeyFile && KeyFilePath != null);
public string Status
{
get { return _status; }
set { Set(() => Status, ref _status, value); }
}
public int StatusType
{
get { return _statusType; }
set { Set(() => StatusType, ref _statusType, value); }
}
public string Password
{
get { return _password; }
set
{
_password = value;
RaisePropertyChanged(nameof(PasswordComplexityIndicator));
StatusType = (int)StatusTypes.Normal;
Status = string.Empty;
}
}
public string KeyFilePath
{
get { return _keyFilePath; }
set
{
_keyFilePath = value;
RaisePropertyChanged(nameof(IsValid));
}
}
public string KeyFileText
{
get { return _keyFileText; }
set { Set(() => KeyFileText, ref _keyFileText, value); }
}
public string RootGroupId { get; set; }
public double PasswordComplexityIndicator => _mediator.Send(new EstimatePasswordComplexityQuery { Password = Password }).GetAwaiter().GetResult();
private bool _hasPassword;
private bool _hasKeyFile;
private bool _isOpening;
private string _password = string.Empty;
private string _status;
private int _statusType;
private string _keyFilePath;
private string _keyFileText;
private readonly IMediator _mediator;
private readonly ISettingsProxy _settings;
private readonly IResourceProxy _resource;
public CompositeKeyVm() : this(
App.Services.GetRequiredService<IMediator>(),
App.Services.GetRequiredService<ISettingsProxy>(),
App.Services.GetRequiredService<IResourceProxy>()) { }
public CompositeKeyVm(IMediator mediator, ISettingsProxy settings, IResourceProxy resource)
{
_mediator = mediator;
_settings = settings;
_resource = resource;
_keyFileText = _resource.GetResourceValue("CompositeKeyDefaultKeyFile");
}
public async Task<bool> OpenDatabase(string databaseFilePath, bool createNew)
{
try
{
_isOpening = true;
RaisePropertyChanged(nameof(IsValid));
if (createNew)
{
await _mediator.Send(new CreateDatabaseCommand
{
FilePath = databaseFilePath,
KeyFilePath = HasKeyFile ? KeyFilePath : null,
Password = HasPassword ? Password : null,
Name = "New Database",
CreateSampleData = _settings.GetSetting<bool>("Sample")
});
}
else
{
await _mediator.Send(new OpenDatabaseQuery {
FilePath = databaseFilePath,
KeyFilePath = HasKeyFile ? KeyFilePath : null,
Password = HasPassword ? Password : null,
});
}
RootGroupId = (await _mediator.Send(new GetDatabaseQuery())).RootGroupId;
return true;
}
catch (ArgumentException)
{
var errorMessage = new StringBuilder($"{_resource.GetResourceValue("CompositeKeyErrorOpen")}\n");
if (HasPassword) errorMessage.AppendLine(_resource.GetResourceValue("CompositeKeyErrorUserPassword"));
if (HasKeyFile) errorMessage.AppendLine(_resource.GetResourceValue("CompositeKeyErrorUserKeyFile"));
UpdateStatus(errorMessage.ToString(), StatusTypes.Error);
}
catch (Exception e)
{
var error = $"{_resource.GetResourceValue("CompositeKeyErrorOpen")}{e.Message}";
UpdateStatus(error, StatusTypes.Error);
}
finally
{
_isOpening = false;
RaisePropertyChanged(nameof(IsValid));
}
return false;
}
public async Task UpdateKey()
{
await _mediator.Send(new UpdateCredentialsCommand
{
KeyFilePath = HasKeyFile ? KeyFilePath : null,
Password = HasPassword ? Password : null,
});
UpdateStatus(_resource.GetResourceValue("CompositeKeyUpdated"), StatusTypes.Success);
}
public async Task CreateKeyFile(FileInfo file)
{
// TODO: implement entropy generator
await _mediator.Send(new GenerateKeyFileCommand {KeyFilePath = file.Id});
KeyFilePath = file.Path;
KeyFileText = file.Name;
}
private void UpdateStatus(string text, StatusTypes type)
{
Status = text;
StatusType = (int)type;
}
}
}

View File

@@ -6,6 +6,7 @@ using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Views;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
@@ -26,14 +27,12 @@ using ModernKeePass.Application.Group.Queries.GetGroup;
using ModernKeePass.Application.Security.Commands.GeneratePassword;
using ModernKeePass.Application.Security.Queries.EstimatePasswordComplexity;
using ModernKeePass.Domain.Enums;
using ModernKeePass.Interfaces;
using ModernKeePass.Application.Group.Models;
using ModernKeePass.Extensions;
using RelayCommand = GalaSoft.MvvmLight.Command.RelayCommand;
namespace ModernKeePass.ViewModels
{
public class EntryDetailVm : ObservableObject, IVmEntity
public class EntryDetailVm : ObservableObject
{
public bool IsRevealPasswordEnabled => !string.IsNullOrEmpty(Password);
public bool HasExpired => HasExpirationDate && ExpiryDate < DateTime.Now;
@@ -230,6 +229,7 @@ namespace ModernKeePass.ViewModels
private readonly INavigationService _navigation;
private readonly IResourceProxy _resource;
private readonly IDialogService _dialog;
private readonly INotificationService _notification;
private readonly GroupVm _parent;
private EntryVm _selectedItem;
private int _selectedIndex;
@@ -244,14 +244,16 @@ namespace ModernKeePass.ViewModels
App.Services.GetRequiredService<IMediator>(),
App.Services.GetRequiredService<INavigationService>(),
App.Services.GetRequiredService<IResourceProxy>(),
App.Services.GetRequiredService<IDialogService>()) { }
App.Services.GetRequiredService<IDialogService>(),
App.Services.GetRequiredService<INotificationService>()) { }
public EntryDetailVm(string entryId, IMediator mediator, INavigationService navigation, IResourceProxy resource, IDialogService dialog)
public EntryDetailVm(string entryId, IMediator mediator, INavigationService navigation, IResourceProxy resource, IDialogService dialog, INotificationService notification)
{
_mediator = mediator;
_navigation = navigation;
_resource = resource;
_dialog = dialog;
_notification = notification;
SelectedItem = _mediator.Send(new GetEntryQuery { Id = entryId }).GetAwaiter().GetResult();
_parent = _mediator.Send(new GetGroupQuery { Id = SelectedItem.ParentGroupId }).GetAwaiter().GetResult();
History = new ObservableCollection<EntryVm> { SelectedItem };
@@ -273,31 +275,22 @@ namespace ModernKeePass.ViewModels
{
if (IsCurrentEntry)
{
var isRecycleOnDelete = IsRecycleOnDelete;
var message = isRecycleOnDelete
? _resource.GetResourceValue("EntryRecyclingConfirmation")
: _resource.GetResourceValue("EntryDeletingConfirmation");
await _dialog.ShowMessage(message,
_resource.GetResourceValue("EntityDeleteTitle"),
_resource.GetResourceValue("EntityDeleteActionButton"),
_resource.GetResourceValue("EntityDeleteCancelButton"),
async isOk =>
{
if (isOk)
if (IsRecycleOnDelete)
{
await Delete();
_notification.Show(_resource.GetResourceValue("EntryRecyclingConfirmation"), _resource.GetResourceValue("EntryRecycled"));
}
else
{
await _dialog.ShowMessage(_resource.GetResourceValue("EntryDeletingConfirmation"),
_resource.GetResourceValue("EntityDeleteTitle"),
_resource.GetResourceValue("EntityDeleteActionButton"),
_resource.GetResourceValue("EntityDeleteCancelButton"),
async isOk =>
{
var text = isRecycleOnDelete
? _resource.GetResourceValue("EntryRecycled")
: _resource.GetResourceValue("EntryDeleted");
//ToastNotificationHelper.ShowMovedToast(Entity, _resource.GetResourceValue("EntityDeleting"), text);
await _mediator.Send(new DeleteEntryCommand
{
EntryId = Id, ParentGroupId = SelectedItem.ParentGroupId,
RecycleBinName = _resource.GetResourceValue("RecycleBinTitle")
});
_navigation.GoBack();
}
});
if (isOk) await Delete();
});
}
}
else
{
@@ -305,14 +298,11 @@ namespace ModernKeePass.ViewModels
_resource.GetResourceValue("EntityDeleteActionButton"),
_resource.GetResourceValue("EntityDeleteCancelButton"), async isOk =>
{
if (isOk)
{
//ToastNotificationHelper.ShowMovedToast(Entity, _resource.GetResourceValue("EntityDeleting"), text);
await _mediator.Send(new DeleteHistoryCommand { Entry = History[0], HistoryIndex = History.Count - SelectedIndex - 1 });
History.RemoveAt(SelectedIndex);
SelectedIndex = 0;
SaveCommand.RaiseCanExecuteChanged();
}
if (!isOk) return;
await _mediator.Send(new DeleteHistoryCommand { Entry = History[0], HistoryIndex = History.Count - SelectedIndex - 1 });
History.RemoveAt(SelectedIndex);
SelectedIndex = 0;
SaveCommand.RaiseCanExecuteChanged();
});
}
}
@@ -368,5 +358,16 @@ namespace ModernKeePass.ViewModels
SaveCommand.RaiseCanExecuteChanged();
_isDirty = false;
}
private async Task Delete()
{
await _mediator.Send(new DeleteEntryCommand
{
EntryId = Id,
ParentGroupId = SelectedItem.ParentGroupId,
RecycleBinName = _resource.GetResourceValue("RecycleBinTitle")
});
_navigation.GoBack();
}
}
}

View File

@@ -6,6 +6,7 @@ using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Views;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
@@ -29,13 +30,11 @@ using ModernKeePass.Application.Group.Queries.GetGroup;
using ModernKeePass.Application.Group.Queries.SearchEntries;
using ModernKeePass.Common;
using ModernKeePass.Domain.Enums;
using ModernKeePass.Interfaces;
using ModernKeePass.Models;
using RelayCommand = GalaSoft.MvvmLight.Command.RelayCommand;
namespace ModernKeePass.ViewModels
{
public class GroupDetailVm : ObservableObject, IVmEntity
public class GroupDetailVm : ObservableObject
{
public ObservableCollection<EntryVm> Entries { get; }
@@ -102,6 +101,7 @@ namespace ModernKeePass.ViewModels
private readonly IResourceProxy _resource;
private readonly INavigationService _navigation;
private readonly IDialogService _dialog;
private readonly INotificationService _notification;
private readonly GroupVm _group;
private readonly GroupVm _parent;
private bool _isEditMode;
@@ -113,15 +113,17 @@ namespace ModernKeePass.ViewModels
App.Services.GetRequiredService<IMediator>(),
App.Services.GetRequiredService<IResourceProxy>(),
App.Services.GetRequiredService<INavigationService>(),
App.Services.GetRequiredService<IDialogService>())
App.Services.GetRequiredService<IDialogService>(),
App.Services.GetRequiredService<INotificationService>())
{ }
public GroupDetailVm(string groupId, IMediator mediator, IResourceProxy resource, INavigationService navigation, IDialogService dialog)
public GroupDetailVm(string groupId, IMediator mediator, IResourceProxy resource, INavigationService navigation, IDialogService dialog, INotificationService notification)
{
_mediator = mediator;
_resource = resource;
_navigation = navigation;
_dialog = dialog;
_notification = notification;
_group = _mediator.Send(new GetGroupQuery { Id = groupId }).GetAwaiter().GetResult();
if (!string.IsNullOrEmpty(_group.ParentGroupId))
{
@@ -145,29 +147,21 @@ namespace ModernKeePass.ViewModels
private async Task AskForDelete()
{
var message = IsRecycleOnDelete
? _resource.GetResourceValue("GroupRecyclingConfirmation")
: _resource.GetResourceValue("GroupDeletingConfirmation");
await _dialog.ShowMessage(message, _resource.GetResourceValue("EntityDeleteTitle"),
if (IsRecycleOnDelete)
{
await Delete();
_notification.Show(_resource.GetResourceValue("GroupRecyclingConfirmation"), _resource.GetResourceValue("GroupRecycled"));
}
else
{
await _dialog.ShowMessage(_resource.GetResourceValue("GroupDeletingConfirmation"), _resource.GetResourceValue("EntityDeleteTitle"),
_resource.GetResourceValue("EntityDeleteActionButton"),
_resource.GetResourceValue("EntityDeleteCancelButton"),
async isOk =>
{
if (isOk)
{
var text = IsRecycleOnDelete
? _resource.GetResourceValue("GroupRecycled")
: _resource.GetResourceValue("GroupDeleted");
//ToastNotificationHelper.ShowMovedToast(Entity, resource.GetResourceValue("EntityDeleting"), text);
await _mediator.Send(new DeleteGroupCommand
{
GroupId = _group.Id, ParentGroupId = _group.ParentGroupId,
RecycleBinName = _resource.GetResourceValue("RecycleBinTitle")
});
_navigation.GoBack();
}
if (isOk) await Delete();
});
}
}
@@ -244,5 +238,16 @@ namespace ModernKeePass.ViewModels
RaisePropertyChanged(nameof(Groups));
SaveCommand.RaiseCanExecuteChanged();
}
private async Task Delete()
{
await _mediator.Send(new DeleteGroupCommand
{
GroupId = _group.Id,
ParentGroupId = _group.ParentGroupId,
RecycleBinName = _resource.GetResourceValue("RecycleBinTitle")
});
_navigation.GoBack();
}
}
}

View File

@@ -4,6 +4,7 @@ using Windows.ApplicationModel;
using Windows.UI.Xaml.Controls;
using GalaSoft.MvvmLight;
using MediatR;
using Messages;
using Microsoft.Extensions.DependencyInjection;
using ModernKeePass.Application.Common.Interfaces;
using ModernKeePass.Application.Database.Queries.GetDatabase;
@@ -12,11 +13,23 @@ using ModernKeePass.Domain.Interfaces;
using ModernKeePass.Models;
using ModernKeePass.ViewModels.ListItems;
using ModernKeePass.Views;
using System.Threading.Tasks;
using GalaSoft.MvvmLight.Views;
using ModernKeePass.Application.Database.Commands.CloseDatabase;
using ModernKeePass.Application.Database.Commands.SaveDatabase;
using ModernKeePass.Common;
using ModernKeePass.Domain.Exceptions;
namespace ModernKeePass.ViewModels
{
public class MainVm : ObservableObject, IHasSelectableObject
public class MainVm : ViewModelBase, IHasSelectableObject
{
private readonly IMediator _mediator;
private readonly IRecentProxy _recent;
private readonly IResourceProxy _resource;
private readonly IDialogService _dialog;
private readonly INotificationService _notification;
private readonly INavigationService _navigation;
private IOrderedEnumerable<IGrouping<string, MainMenuItemVm>> _mainMenuItems;
private ISelectableModel _selectedItem;
@@ -55,19 +68,45 @@ namespace ModernKeePass.ViewModels
destinationFrame,
App.Services.GetRequiredService<IMediator>(),
App.Services.GetRequiredService<IRecentProxy>(),
App.Services.GetRequiredService<IResourceProxy>(),
App.Services.GetRequiredService<IResourceProxy>(),
App.Services.GetRequiredService<IDialogService>(),
App.Services.GetRequiredService<INotificationService>(),
App.Services.GetRequiredService<INavigationService>(),
databaseFile)
{ }
public MainVm(Frame referenceFrame, Frame destinationFrame, IMediator mediator, IRecentProxy recent, IResourceProxy resource, FileInfo databaseFile = null)
public MainVm(
Frame referenceFrame,
Frame destinationFrame,
IMediator mediator,
IRecentProxy recent,
IResourceProxy resource,
IDialogService dialog,
INotificationService notification,
INavigationService navigation,
FileInfo databaseFile = null)
{
var database = mediator.Send(new GetDatabaseQuery()).GetAwaiter().GetResult();
_mediator = mediator;
_recent = recent;
_resource = resource;
_dialog = dialog;
_notification = notification;
_navigation = navigation;
BuildMainMenuItems(referenceFrame, destinationFrame, databaseFile);
MessengerInstance.Register<DatabaseOpenedMessage>(this, NavigateToPage);
MessengerInstance.Register<DatabaseAlreadyOpenedMessage>(this, async message => await DisplaySaveConfirmation(message));
}
private void BuildMainMenuItems(Frame referenceFrame, Frame destinationFrame, FileInfo databaseFile)
{
var database = _mediator.Send(new GetDatabaseQuery()).GetAwaiter().GetResult();
var mainMenuItems = new ObservableCollection<MainMenuItemVm>
{
new MainMenuItemVm
{
Title = resource.GetResourceValue("MainMenuItemOpen"),
Title = _resource.GetResourceValue("MainMenuItemOpen"),
PageType = typeof(OpenDatabasePage),
Destination = destinationFrame,
Parameter = databaseFile,
@@ -76,14 +115,14 @@ namespace ModernKeePass.ViewModels
},
new MainMenuItemVm
{
Title = resource.GetResourceValue("MainMenuItemNew"),
Title = _resource.GetResourceValue("MainMenuItemNew"),
PageType = typeof(NewDatabasePage),
Destination = destinationFrame,
SymbolIcon = Symbol.Add
},
new MainMenuItemVm
{
Title = resource.GetResourceValue("MainMenuItemSave"),
Title = _resource.GetResourceValue("MainMenuItemSave"),
PageType = typeof(SaveDatabasePage),
Destination = destinationFrame,
Parameter = referenceFrame,
@@ -93,31 +132,31 @@ namespace ModernKeePass.ViewModels
},
new MainMenuItemVm
{
Title = resource.GetResourceValue("MainMenuItemRecent"),
Title = _resource.GetResourceValue("MainMenuItemRecent"),
PageType = typeof(RecentDatabasesPage),
Destination = destinationFrame,
Parameter = referenceFrame,
SymbolIcon = Symbol.Copy,
IsSelected = !database.IsOpen && recent.EntryCount > 0,
IsEnabled = recent.EntryCount > 0
IsSelected = !database.IsOpen && _recent.EntryCount > 0,
IsEnabled = _recent.EntryCount > 0
},
new MainMenuItemVm
{
Title = resource.GetResourceValue("MainMenuItemSettings"),
Title = _resource.GetResourceValue("MainMenuItemSettings"),
PageType = typeof(SettingsPage),
Destination = referenceFrame,
SymbolIcon = Symbol.Setting
},
new MainMenuItemVm
{
Title = resource.GetResourceValue("MainMenuItemAbout"),
Title = _resource.GetResourceValue("MainMenuItemAbout"),
PageType = typeof(AboutPage),
Destination = destinationFrame,
SymbolIcon = Symbol.Help
},
new MainMenuItemVm
{
Title = resource.GetResourceValue("MainMenuItemDonate"),
Title = _resource.GetResourceValue("MainMenuItemDonate"),
PageType = typeof(DonatePage),
Destination = destinationFrame,
SymbolIcon = Symbol.Shop
@@ -137,8 +176,41 @@ namespace ModernKeePass.ViewModels
Group = "Databases",
SymbolIcon = Symbol.ProtectedDocument
});
MainMenuItems = from item in mainMenuItems group item by item.Group into grp orderby grp.Key select grp;
}
private void NavigateToPage(DatabaseOpenedMessage message)
{
_navigation.NavigateTo(Constants.Navigation.GroupPage, new NavigationItem { Id = message.RootGroupId });
}
private async Task DisplaySaveConfirmation(DatabaseAlreadyOpenedMessage message)
{
var database = await _mediator.Send(new GetDatabaseQuery());
await _dialog.ShowMessage(string.Format(_resource.GetResourceValue("MessageDialogDBOpenDesc"), database.Name),
_resource.GetResourceValue("MessageDialogDBOpenTitle"),
_resource.GetResourceValue("MessageDialogDBOpenButtonSave"),
_resource.GetResourceValue("MessageDialogDBOpenButtonDiscard"),
async isOk =>
{
if (isOk)
{
try
{
await _mediator.Send(new SaveDatabaseCommand());
_notification.Show(database.Name, _resource.GetResourceValue("ToastSavedMessage"));
}
catch (SaveException exception)
{
_notification.Show(exception.Source, exception.Message);
return;
}
}
await _mediator.Send(new CloseDatabaseCommand());
MessengerInstance.Send(new DatabaseClosedMessage { Parameter = message.Parameter });
});
}
}
}

View File

@@ -43,9 +43,7 @@ namespace ModernKeePass.ViewModels
}
}
}
public SettingsVm() : this(App.Services.GetRequiredService<IMediator>(), App.Services.GetRequiredService<IResourceProxy>()) { }
public SettingsVm(IMediator mediator, IResourceProxy resource)
{
var database = mediator.Send(new GetDatabaseQuery()).GetAwaiter().GetResult();