Skip to content

Commit

Permalink
Bug fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
aritchie committed Feb 15, 2025
1 parent 5731ef6 commit ff1cefe
Show file tree
Hide file tree
Showing 10 changed files with 96 additions and 46 deletions.
4 changes: 3 additions & 1 deletion samples/Sample.Uno/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ protected async override void OnLaunched(LaunchActivatedEventArgs args)
.Section<AppConfig>()
)
.UseNavigation(RegisterRoutes)
.AddShinyMediator()
.AddShinyMediator(x => x
.AddUnoPersistentCache()
)
.ConfigureServices(s => s.AddDiscoveredMediatorHandlersFromSample_Uno())
);

Expand Down
18 changes: 13 additions & 5 deletions samples/Sample.Uno/Presentation/MainPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,32 @@
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>

<utu:NavigationBar Content="Shiny Mediator" />

<StackPanel Grid.Row="1"
Orientation="Vertical"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Spacing="16">
<TextBlock Text="{Binding OfflineResultText}" />
<TextBlock Text="{Binding OfflineDate}" />

<TextBlock Text="{x:Bind ViewModel.OfflineResultText}"
TintColor="Black" />

<TextBlock Text="{x:Bind ViewModel.OfflineDate}"
TintColor="Black" />

<Button Content="Run Offline"
Command="{Binding OfflineCommand}"/>
Command="{x:Bind ViewModel.OfflineCommand}"/>

<Button Content="Test Exception Handler"
Command="{Binding ErrorTrapCommand}" />
Command="{x:Bind ViewModel.ErrorTrapCommand}" />

<Button Content="Publish Event"
Command="{Binding PublishEventCommand}" />
Command="{x:Bind ViewModel.PublishEventCommand}" />

<Button Content="Go To Second Page"
Command="{x:Bind ViewModel.GoToSecondPageCommand}" />
</StackPanel>
</Grid>
</ScrollViewer>
Expand Down
2 changes: 2 additions & 0 deletions samples/Sample.Uno/Presentation/MainPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ public MainPage()
{
this.InitializeComponent();
}

public MainViewModel? ViewModel => DataContext as MainViewModel;
}
9 changes: 8 additions & 1 deletion samples/Sample.Uno/Presentation/MainViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,17 @@ async Task Offline()
}

[RelayCommand]
Task PublishEvent() => mediator.Publish(new AppEvent("Hello from SecondViewModel"));
async Task PublishEvent()
{
await mediator.Publish(new AppEvent("Hello from SecondViewModel"));
await navigator.ShowMessageDialogAsync(this, title: "Done", content: "Publish message sent successfully");
}

[RelayCommand]
Task ErrorTrap() => mediator.Send(new ErrorCommand());

[RelayCommand]
Task GoToSecondPage() => navigator.NavigateViewModelAsync<SecondViewModel>(this);

public async Task Handle(AppEvent @event, EventContext<AppEvent> context, CancellationToken cancellationToken)
{
Expand Down
2 changes: 2 additions & 0 deletions samples/Sample.Uno/Presentation/SecondPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ public SecondPage()
{
this.InitializeComponent();
}

public SecondViewModel? ViewModel => DataContext as SecondViewModel;
}
40 changes: 25 additions & 15 deletions src/Shiny.Mediator.AppSupport/Infrastructure/OfflineService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,19 @@ public class OfflineService(IStorageService storage, ISerializerService serializ
public async Task<string> Set(object request, object result)
{
var requestKey = Utils.GetRequestKey(request);
await this.DoTransaction(dict =>
{
dict[requestKey] = new OfflineStore(
this.GetTypeKey(request.GetType()),
requestKey,
DateTimeOffset.UtcNow,
serializer.Serialize(result)
);
return true;
});
await this
.DoTransaction(dict =>
{
dict[requestKey] = new OfflineStore(
this.GetTypeKey(request.GetType()),
requestKey,
DateTimeOffset.UtcNow,
serializer.Serialize(result)
);
return true;
})
.ConfigureAwait(false);

return requestKey;
}

Expand Down Expand Up @@ -92,23 +95,30 @@ public Task Clear() => this.DoTransaction(dict =>
});


SemaphoreSlim semaphore = new(1, 1);
Dictionary<string, OfflineStore> cache = null!;
readonly SemaphoreSlim semaphore = new(1, 1);
Dictionary<string, OfflineStore>? cache = null!;

Task DoTransaction(Func<IDictionary<string, OfflineStore>, bool> action) => Task.Run(async () =>
{
await this.semaphore.WaitAsync();
if (this.cache == null)
{
var dict = await storage
.Get<Dictionary<string, OfflineStore>>(nameof(IStorageService))
.Get<Dictionary<string, OfflineStore>>(nameof(OfflineService))
.ConfigureAwait(false);

this.cache = dict ?? new();
}
var result = action(this.cache);
if (result)
await storage.Set(nameof(IStorageService), this.cache).ConfigureAwait(false);

{
await storage
.Set(
nameof(OfflineService),
this.cache
)
.ConfigureAwait(false);
}
this.semaphore.Release();
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using Shiny.Mediator.Caching;

namespace Shiny.Mediator.Infrastructure;


Expand All @@ -17,7 +15,10 @@ public class StorageCacheService(IStorageService storage) : ICacheService
// TODO: check expiry or clear it out?
public async Task<CacheEntry<T>?> GetOrCreate<T>(string key, Func<Task<T>> factory, CacheItemConfig? config = null)
{
var e = await storage.Get<InternalCacheEntry<T>>(key).ConfigureAwait(false);
var e = await storage
.Get<InternalCacheEntry<T>>(key)
.ConfigureAwait(false);

if (e != null)
{
if (e.ExpiresAt != null && e.ExpiresAt > DateTimeOffset.UtcNow)
Expand Down
32 changes: 16 additions & 16 deletions src/Shiny.Mediator.Uno/Infrastructure/AlertDialogService.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
using Microsoft.Extensions.Logging;
using Microsoft.UI.Xaml.Controls;
using Uno.Extensions.Navigation;

namespace Shiny.Mediator.Infrastructure;


public class AlertDialogService(ILogger<AlertDialogService> logger) : IAlertDialogService
public class AlertDialogService(INavigator navigator) : IAlertDialogService
{
public void Display(string title, string message)
public async void Display(string title, string message)
{
// TODO: could use acr userdialogs
// ContentDialog deleteFileDialog = new ContentDialog
// {
// Title = "Delete file permanently?",
// Content = "If you delete this file, you won't be able to recover it. Do you want to delete it?",
// PrimaryButtonText = "Delete",
// CloseButtonText = "Cancel"
// };
//
// deleteFileDialog.XamlRoot = anyLoadedControl.XamlRoot;
//
// ContentDialogResult result = await deleteFileDialog.ShowAsync();
try
{
await navigator.ShowMessageDialogAsync(
this,
title: title,
content: message
);

}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
14 changes: 9 additions & 5 deletions src/Shiny.Mediator.Uno/Infrastructure/StorageService.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
using System.IO;
using Windows.Storage;

namespace Shiny.Mediator.Infrastructure;


public class StorageService(ISerializerService serializer) : IStorageService
{
static readonly StorageFolder local = ApplicationData.Current.LocalFolder;

public async Task Set<T>(string key, T value)
{
var local = ApplicationData.Current.LocalFolder;
var json = serializer.Serialize(value);
var file = await local.CreateFileAsync(key, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, json);
Expand All @@ -17,10 +17,12 @@ public async Task Set<T>(string key, T value)

public async Task<T?> Get<T>(string key)
{
var file = await local.GetFileAsync(key);
if (file == null)
var local = ApplicationData.Current.LocalFolder;
var fn = Path.Combine(local.Path, key);
if (!File.Exists(fn))
return default;


var file = await local.GetFileAsync(key);
var json = await FileIO.ReadTextAsync(file);
if (String.IsNullOrWhiteSpace(json))
return default;
Expand All @@ -32,6 +34,7 @@ public async Task Set<T>(string key, T value)

public async Task Remove(string key)
{
var local = ApplicationData.Current.LocalFolder;
var file = await local.GetFileAsync(key);
if (file != null)
await file.DeleteAsync();
Expand All @@ -43,6 +46,7 @@ public async Task Remove(string key)

async Task DeleteBy(string? startsWith)
{
var local = ApplicationData.Current.LocalFolder;
var files = await local.GetFilesAsync();
foreach (var file in files)
{
Expand Down
14 changes: 14 additions & 0 deletions src/Shiny.Mediator.Uno/UnoExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,20 @@ public static ShinyConfigurator UseUno(this ShinyConfigurator cfg)
cfg.AddUnoInfrastructure();
return cfg;
}


/// <summary>
///
/// </summary>
/// <param name="cfg"></param>
/// <returns></returns>
public static ShinyConfigurator AddUnoPersistentCache(this ShinyConfigurator cfg)
{
cfg.AddUnoInfrastructure();
cfg.AddCaching<StorageCacheService>();
return cfg;
}


/// <summary>
/// Add Shiny Mediator to Uno
Expand Down

0 comments on commit ff1cefe

Please sign in to comment.