Restore Main and Settings Page

Entry and Group delete events converted to commands
Code cleanup
This commit is contained in:
Geoffroy BONNEVILLE
2020-04-22 11:58:06 +02:00
parent 1df9cbce1c
commit a88051bc0c
13 changed files with 144 additions and 164 deletions

View File

@@ -10,10 +10,8 @@ using Windows.Storage.Pickers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Views;
using MediatR;
using Messages;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.HockeyApp;
using ModernKeePass.Application;
@@ -41,8 +39,8 @@ namespace ModernKeePass
private readonly IMediator _mediator;
private readonly ISettingsProxy _settings;
private readonly INavigationService _navigation;
private readonly IMessenger _messenger;
private readonly IHockeyClient _hockey;
private readonly IDialogService _dialog;
public static IServiceProvider Services { get; private set; }
@@ -65,47 +63,15 @@ namespace ModernKeePass
_resource = Services.GetService<IResourceProxy>();
_settings = Services.GetService<ISettingsProxy>();
_navigation = Services.GetService<INavigationService>();
_messenger = Services.GetService<IMessenger>();
_dialog = Services.GetService<IDialogService>();
_hockey = Services.GetService<IHockeyClient>();
InitializeComponent();
Suspending += OnSuspending;
Resuming += OnResuming;
UnhandledException += OnUnhandledException;
ReceiveGlobalMessage();
}
#region Messages
private void ReceiveGlobalMessage()
{
_messenger.Register<DatabaseAlreadyOpenedMessage>(this, async action => await ShowDatabaseOpenedDialog(action));
}
private async Task ShowDatabaseOpenedDialog(DatabaseAlreadyOpenedMessage message)
{
await MessageDialogHelper.ShowActionDialog(_resource.GetResourceValue("MessageDialogDBOpenTitle"),
string.Format(_resource.GetResourceValue("MessageDialogDBOpenDesc"), message.OpenedDatabase.Name),
_resource.GetResourceValue("MessageDialogDBOpenButtonSave"),
_resource.GetResourceValue("MessageDialogDBOpenButtonDiscard"),
async command =>
{
await _mediator.Send(new SaveDatabaseCommand());
ToastNotificationHelper.ShowGenericToast(
message.OpenedDatabase.Name,
_resource.GetResourceValue("ToastSavedMessage"));
await _mediator.Send(new CloseDatabaseCommand());
_messenger.Send(new DatabaseClosedMessage());
},
async command =>
{
await _mediator.Send(new CloseDatabaseCommand());
_messenger.Send(new DatabaseClosedMessage());
});
}
#endregion
#region Event Handlers
private async void OnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
@@ -123,28 +89,32 @@ namespace ModernKeePass
var innerException = realException.InnerException;
unhandledExceptionEventArgs.Handled = true;
_hockey.TrackException(innerException);
await MessageDialogHelper.ShowActionDialog(_resource.GetResourceValue("MessageDialogSaveErrorTitle"),
innerException?.Message,
await _dialog.ShowMessage(innerException?.Message,
_resource.GetResourceValue("MessageDialogSaveErrorTitle"),
_resource.GetResourceValue("MessageDialogSaveErrorButtonSaveAs"),
_resource.GetResourceValue("MessageDialogSaveErrorButtonDiscard"),
async command =>
async isOk =>
{
var database = await _mediator.Send(new GetDatabaseQuery());
var savePicker = new FileSavePicker
if (isOk)
{
SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
SuggestedFileName = $"{database.Name} - copy"
};
savePicker.FileTypeChoices.Add(_resource.GetResourceValue("MessageDialogSaveErrorFileTypeDesc"),
new List<string> {".kdbx"});
var database = await _mediator.Send(new GetDatabaseQuery());
var savePicker = new FileSavePicker
{
SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
SuggestedFileName = $"{database.Name} - copy"
};
savePicker.FileTypeChoices.Add(
_resource.GetResourceValue("MessageDialogSaveErrorFileTypeDesc"),
new List<string> {".kdbx"});
var file = await savePicker.PickSaveFileAsync().AsTask();
if (file != null)
{
var token = StorageApplicationPermissions.FutureAccessList.Add(file);
await _mediator.Send(new SaveDatabaseCommand { FilePath = token });
var file = await savePicker.PickSaveFileAsync().AsTask();
if (file != null)
{
var token = StorageApplicationPermissions.FutureAccessList.Add(file);
await _mediator.Send(new SaveDatabaseCommand {FilePath = token});
}
}
}, null);
});
}
}
@@ -183,7 +153,7 @@ namespace ModernKeePass
// Load state from previously terminated application
await SuspensionManager.RestoreAsync();
#if DEBUG
await MessageDialogHelper.ShowNotificationDialog("App terminated", "Windows or an error made the app terminate");
await _dialog.ShowMessage("Windows or an error made the app terminate", "App terminated");
#endif
}

View File

@@ -5,10 +5,10 @@ using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Views;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using ModernKeePass.Application.Common.Interfaces;
using ModernKeePass.Application.Database.Commands.SaveDatabase;
using ModernKeePass.Application.Database.Models;
using ModernKeePass.Application.Database.Queries.GetDatabase;
@@ -29,6 +29,7 @@ using ModernKeePass.Interfaces;
using ModernKeePass.Application.Group.Models;
using ModernKeePass.Domain.AOP;
using ModernKeePass.Extensions;
using RelayCommand = GalaSoft.MvvmLight.Command.RelayCommand;
namespace ModernKeePass.ViewModels
{
@@ -227,6 +228,8 @@ namespace ModernKeePass.ViewModels
private readonly IMediator _mediator;
private readonly INavigationService _navigation;
private readonly IResourceProxy _resource;
private readonly IDialogService _dialog;
private readonly GroupVm _parent;
private EntryVm _selectedItem;
private int _selectedIndex;
@@ -237,12 +240,18 @@ namespace ModernKeePass.ViewModels
public EntryDetailVm() { }
internal EntryDetailVm(string entryId) : this(entryId, App.Services.GetRequiredService<IMediator>(), App.Services.GetRequiredService<INavigationService>()) { }
internal EntryDetailVm(string entryId) : this(entryId,
App.Services.GetRequiredService<IMediator>(),
App.Services.GetRequiredService<INavigationService>(),
App.Services.GetRequiredService<IResourceProxy>(),
App.Services.GetRequiredService<IDialogService>()) { }
public EntryDetailVm(string entryId, IMediator mediator, INavigationService navigation)
public EntryDetailVm(string entryId, IMediator mediator, INavigationService navigation, IResourceProxy resource, IDialogService dialog)
{
_mediator = mediator;
_navigation = navigation;
_resource = resource;
_dialog = dialog;
SelectedItem = _mediator.Send(new GetEntryQuery { Id = entryId }).GetAwaiter().GetResult();
_parent = _mediator.Send(new GetGroupQuery { Id = SelectedItem.ParentGroupId }).GetAwaiter().GetResult();
History = new ObservableCollection<EntryVm> { SelectedItem };
@@ -262,7 +271,50 @@ namespace ModernKeePass.ViewModels
private async Task AskForDelete()
{
throw new NotImplementedException();
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)
{
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();
}
});
}
else
{
await _dialog.ShowMessage(_resource.GetResourceValue("HistoryDeleteDescription"), _resource.GetResourceValue("HistoryDeleteTitle"),
_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();
}
});
}
}
public async Task GeneratePassword()
@@ -282,11 +334,6 @@ namespace ModernKeePass.ViewModels
});
OnPropertyChanged(nameof(IsRevealPasswordEnabled));
}
public async Task MarkForDelete(string recycleBinTitle)
{
await _mediator.Send(new DeleteEntryCommand {EntryId = Id, ParentGroupId = SelectedItem.ParentGroupId, RecycleBinName = recycleBinTitle});
}
public async Task Move(GroupVm destination)
{
@@ -308,20 +355,12 @@ namespace ModernKeePass.ViewModels
private async Task RestoreHistory()
{
await _mediator.Send(new RestoreHistoryCommand { Entry = History[0], HistoryIndex = History.Count - SelectedIndex });
await _mediator.Send(new RestoreHistoryCommand { Entry = History[0], HistoryIndex = History.Count - SelectedIndex - 1 });
History.Insert(0, SelectedItem);
SelectedIndex = 0;
SaveCommand.RaiseCanExecuteChanged();
}
public async Task DeleteHistory()
{
await _mediator.Send(new DeleteHistoryCommand { Entry = History[0], HistoryIndex = History.Count - SelectedIndex });
History.RemoveAt(SelectedIndex);
SelectedIndex = 0;
SaveCommand.RaiseCanExecuteChanged();
}
private async Task SaveChanges()
{
await AddHistory();

View File

@@ -154,10 +154,19 @@ namespace ModernKeePass.ViewModels
_resource.GetResourceValue("EntityDeleteCancelButton"),
async isOk =>
{
var text = IsRecycleOnDelete ? _resource.GetResourceValue("GroupRecycled") : _resource.GetResourceValue("GroupDeleted");
//ToastNotificationHelper.ShowMovedToast(Entity, resource.GetResourceValue("EntityDeleting"), text);
await MarkForDelete(_resource.GetResourceValue("RecycleBinTitle"));
_navigation.GoBack();
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();
}
});
}
@@ -181,11 +190,6 @@ namespace ModernKeePass.ViewModels
IsNew = true
});
}
public async Task MarkForDelete(string recycleBinTitle)
{
await _mediator.Send(new DeleteGroupCommand { GroupId = _group.Id, ParentGroupId = _group.ParentGroupId, RecycleBinName = recycleBinTitle });
}
public async Task Move(GroupVm destination)
{

View File

@@ -10,7 +10,6 @@
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
xmlns:actions="using:ModernKeePass.Actions"
xmlns:userControls="using:ModernKeePass.Views.UserControls"
x:Name="PageRoot"
x:Class="ModernKeePass.Views.EntryDetailPage"
mc:Ignorable="d"
SizeChanged="EntryDetailPage_OnSizeChanged">
@@ -538,7 +537,7 @@
SaveCommand="{Binding SaveCommand}"
MoveCommand="{Binding MoveCommand}"
RestoreCommand="{Binding RestoreCommand}"
DeleteButtonClick="TopMenu_OnDeleteButtonClick">
DeleteCommand="{Binding DeleteCommand}">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="EditButtonClick">
<actions:SetupFocusAction TargetObject="{Binding ElementName=TitleTextBox}" />

View File

@@ -1,8 +1,5 @@
using Windows.UI.Xaml;
using Windows.UI.Xaml.Navigation;
using Microsoft.Extensions.DependencyInjection;
using ModernKeePass.Application.Common.Interfaces;
using ModernKeePass.Common;
using ModernKeePass.Models;
using ModernKeePass.ViewModels;
@@ -16,14 +13,11 @@ namespace ModernKeePass.Views
/// </summary>
public sealed partial class EntryDetailPage
{
private readonly IResourceProxy _resource;
public EntryDetailVm Model => (EntryDetailVm) DataContext;
public EntryDetailPage(): this(App.Services.GetRequiredService<IResourceProxy>()) { }
public EntryDetailPage(IResourceProxy resource)
public EntryDetailPage()
{
InitializeComponent();
_resource = resource;
}
#region Inscription de NavigationHelper
@@ -59,36 +53,5 @@ namespace ModernKeePass.Views
VisualStateManager.GoToState(this, e.NewSize.Width < 700 ? "Small" : "Large", true);
VisualStateManager.GoToState(TopMenu, e.NewSize.Width < 800 ? "Collapsed" : "Overflowed", true);
}
private async void TopMenu_OnDeleteButtonClick(object sender, RoutedEventArgs e)
{
if (Model.IsCurrentEntry)
{
var isRecycleOnDelete = Model.IsRecycleOnDelete;
var message = isRecycleOnDelete
? _resource.GetResourceValue("EntryRecyclingConfirmation")
: _resource.GetResourceValue("EntryDeletingConfirmation");
await MessageDialogHelper.ShowActionDialog(_resource.GetResourceValue("EntityDeleteTitle"), message,
_resource.GetResourceValue("EntityDeleteActionButton"),
_resource.GetResourceValue("EntityDeleteCancelButton"), async a =>
{
var text = isRecycleOnDelete ? _resource.GetResourceValue("EntryRecycled") : _resource.GetResourceValue("EntryDeleted");
//ToastNotificationHelper.ShowMovedToast(Entity, _resource.GetResourceValue("EntityDeleting"), text);
await Model.MarkForDelete(_resource.GetResourceValue("RecycleBinTitle"));
//NavigationHelper.GoBack();
}, null);
}
else
{
await MessageDialogHelper.ShowActionDialog(_resource.GetResourceValue("HistoryDeleteTitle"), _resource.GetResourceValue("HistoryDeleteDescription"),
_resource.GetResourceValue("EntityDeleteActionButton"),
_resource.GetResourceValue("EntityDeleteCancelButton"), async a =>
{
//ToastNotificationHelper.ShowMovedToast(Entity, _resource.GetResourceValue("EntityDeleting"), text);
await Model.DeleteHistory();
}, null);
}
}
}
}

View File

@@ -250,7 +250,7 @@
MoveCommand="{Binding MoveCommand}"
SortEntriesCommand="{Binding SortEntriesCommand}"
SortGroupsCommand="{Binding SortGroupsCommand}"
DeleteButtonClick="TopMenu_OnDeleteButtonClick">
DeleteCommand="{Binding DeleteCommand}">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="EditButtonClick">
<actions:SetupFocusAction TargetObject="{Binding ElementName=TitleTextBox}" />

View File

@@ -120,25 +120,7 @@ namespace ModernKeePass.Views
VisualStateManager.GoToState(this, e.NewSize.Width < 800 ? "Small" : "Large", true);
VisualStateManager.GoToState(TopMenu, e.NewSize.Width < 800 ? "Collapsed" : "Overflowed", true);
}
private async void TopMenu_OnDeleteButtonClick(object sender, RoutedEventArgs e)
{
var isRecycleOnDelete = Model.IsRecycleOnDelete;
var message = isRecycleOnDelete
? _resource.GetResourceValue("GroupRecyclingConfirmation")
: _resource.GetResourceValue("GroupDeletingConfirmation");
var text = isRecycleOnDelete ? _resource.GetResourceValue("GroupRecycled") : _resource.GetResourceValue("GroupDeleted");
await MessageDialogHelper.ShowActionDialog(_resource.GetResourceValue("EntityDeleteTitle"), message,
_resource.GetResourceValue("EntityDeleteActionButton"),
_resource.GetResourceValue("EntityDeleteCancelButton"), async a =>
{
//ToastNotificationHelper.ShowMovedToast(Entity, resource.GetResourceValue("EntityDeleting"), text);
await Model.MarkForDelete(_resource.GetResourceValue("RecycleBinTitle"));
//NavigationHelper.GoBack();
}, null);
}
#endregion
}
}

View File

@@ -10,17 +10,20 @@
x:Name="PageRoot"
mc:Ignorable="d">
<Page.Resources>
<viewModels:MainVm x:Key="ViewModel"/>
<CollectionViewSource
x:Name="MenuItemsSource"
Source="{Binding MainMenuItems}"
IsSourceGrouped="True" />
</Page.Resources>
<Page.Background>
<StaticResource ResourceKey="ApplicationPageBackgroundThemeBrush"/>
</Page.Background>
<Page.DataContext>
<viewModels:MainVm />
</Page.DataContext>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" DataContext="{StaticResource ViewModel}">
<Grid.Resources>
<CollectionViewSource x:Name="MenuItemsSource" Source="{Binding MainMenuItems}" IsSourceGrouped="True" />
</Grid.Resources>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Grid.ChildrenTransitions>
<TransitionCollection>
<EntranceThemeTransition/>

View File

@@ -13,7 +13,7 @@ namespace ModernKeePass.Views
/// </summary>
public sealed partial class MainPage
{
private new MainVm Model => (MainVm)Resources["ViewModel"];
public new MainVm Model => (MainVm)DataContext;
public MainPage()
{

View File

@@ -10,16 +10,16 @@
x:Class="ModernKeePass.Views.SettingsPage"
mc:Ignorable="d">
<Page.Resources>
<viewModels:SettingsVm x:Key="ViewModel"/>
<CollectionViewSource x:Name="MenuItemsSource" Source="{Binding MenuItems}" IsSourceGrouped="True" />
</Page.Resources>
<Page.DataContext>
<viewModels:SettingsVm />
</Page.DataContext>
<Page.Background>
<StaticResource ResourceKey="ApplicationPageBackgroundThemeBrush"/>
</Page.Background>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" DataContext="{StaticResource ViewModel}">
<Grid.Resources>
<CollectionViewSource x:Name="MenuItemsSource" Source="{Binding MenuItems}" IsSourceGrouped="True" />
</Grid.Resources>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Grid.ChildrenTransitions>
<TransitionCollection>
<EntranceThemeTransition/>

View File

@@ -12,7 +12,7 @@ namespace ModernKeePass.Views
/// </summary>
public sealed partial class SettingsPage
{
private new SettingsVm Model => (SettingsVm)Resources["ViewModel"];
public new SettingsVm Model => (SettingsVm)DataContext;
public SettingsPage()
{

View File

@@ -4,9 +4,6 @@ using Windows.Storage.Pickers;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Input;
using GalaSoft.MvvmLight.Messaging;
using Messages;
using Microsoft.Extensions.DependencyInjection;
using ModernKeePass.ViewModels;
// Pour en savoir plus sur le modèle d'élément Contrôle utilisateur, consultez la page http://go.microsoft.com/fwlink/?LinkId=234236
@@ -29,13 +26,9 @@ namespace ModernKeePass.Views.UserControls
typeof(OpenDatabaseUserControl),
new PropertyMetadata(null, (o, args) => { }));
public OpenDatabaseUserControl() : this(App.Services.GetRequiredService<IMessenger>()) { }
public OpenDatabaseUserControl(IMessenger messenger)
public OpenDatabaseUserControl()
{
InitializeComponent();
messenger.Register<DatabaseClosedMessage>(this, async action => await Model.OpenDatabase(DatabaseFilePath));
}
private async void PasswordBox_KeyDown(object sender, KeyRoutedEventArgs e)

View File

@@ -3,12 +3,16 @@ using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Views;
using MediatR;
using Messages;
using Microsoft.Extensions.DependencyInjection;
using ModernKeePass.Application.Common.Interfaces;
using ModernKeePass.Application.Database.Commands.CloseDatabase;
using ModernKeePass.Application.Database.Commands.SaveDatabase;
using ModernKeePass.Application.Database.Queries.GetDatabase;
using ModernKeePass.Application.Database.Queries.OpenDatabase;
using ModernKeePass.Common;
using ModernKeePass.Domain.AOP;
namespace ModernKeePass.ViewModels
@@ -98,6 +102,7 @@ namespace ModernKeePass.ViewModels
protected readonly IMediator Mediator;
private readonly IResourceProxy _resource;
private readonly IMessenger _messenger;
private readonly IDialogService _dialog;
private bool _hasPassword;
private bool _hasKeyFile;
private bool _isOpening;
@@ -112,14 +117,16 @@ namespace ModernKeePass.ViewModels
public OpenDatabaseControlVm() : this(
App.Services.GetRequiredService<IMediator>(),
App.Services.GetRequiredService<IResourceProxy>(),
App.Services.GetRequiredService<IMessenger>())
App.Services.GetRequiredService<IMessenger>(),
App.Services.GetRequiredService<IDialogService>())
{ }
public OpenDatabaseControlVm(IMediator mediator, IResourceProxy resource, IMessenger messenger)
public OpenDatabaseControlVm(IMediator mediator, IResourceProxy resource, IMessenger messenger, IDialogService dialog)
{
Mediator = mediator;
_resource = resource;
_messenger = messenger;
_dialog = dialog;
OpenDatabaseCommand = new RelayCommand<string>(async databaseFilePath => await TryOpenDatabase(databaseFilePath), _ => IsValid);
_keyFileText = _resource.GetResourceValue("CompositeKeyDefaultKeyFile");
_openButtonLabel = _resource.GetResourceValue("CompositeKeyOpenButtonLabel");
@@ -132,7 +139,27 @@ namespace ModernKeePass.ViewModels
var database = await Mediator.Send(new GetDatabaseQuery());
if (database.IsOpen)
{
_messenger.Send(new DatabaseAlreadyOpenedMessage { OpenedDatabase = database });
await _dialog.ShowMessage(_resource.GetResourceValue("MessageDialogDBOpenTitle"),
string.Format(_resource.GetResourceValue("MessageDialogDBOpenDesc"), database.Name),
_resource.GetResourceValue("MessageDialogDBOpenButtonSave"),
_resource.GetResourceValue("MessageDialogDBOpenButtonDiscard"),
async isOk =>
{
if (isOk)
{
await Mediator.Send(new SaveDatabaseCommand());
ToastNotificationHelper.ShowGenericToast(
database.Name,
_resource.GetResourceValue("ToastSavedMessage"));
await Mediator.Send(new CloseDatabaseCommand());
await OpenDatabase(databaseFilePath);
}
else
{
await Mediator.Send(new CloseDatabaseCommand());
await OpenDatabase(databaseFilePath);
}
});
}
else await OpenDatabase(databaseFilePath);
}