Skip to content

Commit

Permalink
Moving config setup and fixing build
Browse files Browse the repository at this point in the history
  • Loading branch information
aritchie committed Sep 20, 2024
1 parent 2f0f3d8 commit 10046d0
Show file tree
Hide file tree
Showing 23 changed files with 259 additions and 138 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Shiny.Mediator.Infrastructure;

namespace Shiny.Mediator.Middleware;
Expand All @@ -7,7 +8,7 @@ namespace Shiny.Mediator.Middleware;
public class OfflineAvailableRequestMiddleware<TRequest, TResult>(
IInternetService connectivity,
IStorageService storage,
IFeatureService features
IConfiguration config
) : IRequestMiddleware<TRequest, TResult>
{
public async Task<TResult> Process(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Configuration;
using Shiny.Mediator.Infrastructure;

namespace Shiny.Mediator.Middleware;
Expand All @@ -11,7 +12,7 @@ namespace Shiny.Mediator.Middleware;
/// <typeparam name="TResult"></typeparam>
public class ReplayStreamMiddleware<TRequest, TResult>(
IStorageService storage,
IFeatureService features
IConfiguration config
) : IStreamRequestMiddleware<TRequest, TResult> where TRequest : IStreamRequest<TResult>
{
public IAsyncEnumerable<TResult> Process(
Expand Down
31 changes: 27 additions & 4 deletions src/Shiny.Mediator.Blazor/Infrastructure/InternetService.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,35 @@
using Microsoft.JSInterop;
using Shiny.Mediator.Infrastructure;

namespace Shiny.Mediator.Blazor.Infrastructure;

public class InternetService : IInternetService

public class InternetService(IJSRuntime jsruntime) : IInternetService, IDisposable
{
public bool IsAvailable { get; }
public Task WaitForAvailable(CancellationToken cancelToken = default)
public bool IsAvailable => ((IJSInProcessRuntime)jsruntime).Invoke<bool>("navigator.onLine");


[JSInvokable("InternetService.OnStatusChanged")]
public void OnStatusChanged(bool isOnline)
{
throw new NotImplementedException();
if (isOnline)
this.waitSource?.TrySetResult();
}


TaskCompletionSource? waitSource;
public async Task WaitForAvailable(CancellationToken cancelToken = default)
{
if (this.IsAvailable)
return;

var objRef = DotNetObjectReference.Create(this);
((IJSInProcessRuntime)jsruntime).InvokeVoid("InternetService.subscribe", objRef);

this.waitSource = new();
await this.waitSource.Task.ConfigureAwait(false);
this.waitSource = null;
}

public void Dispose() => ((IJSInProcessRuntime)jsruntime).InvokeVoid("InternetService.unsubscribe");
}
59 changes: 55 additions & 4 deletions src/Shiny.Mediator.Blazor/Infrastructure/StorageService.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,73 @@
using System.Text.Json;
using Microsoft.JSInterop;
using Shiny.Mediator.Infrastructure;

namespace Shiny.Mediator.Blazor.Infrastructure;


public class StorageService : IStorageService
public class StorageService(IJSRuntime jsruntime) : IStorageService
{
public Task Store(object request, object result, bool isPeristent)
{
throw new NotImplementedException();
var key = this.GetStoreKeyFromRequest(request);
var store = isPeristent ? "localStorage" : "sessionStorage";

var json = JsonSerializer.Serialize(result);
((IJSInProcessRuntime)jsruntime).Invoke<string?>(store + ".setItem", key, json);

return Task.CompletedTask;
}

public Task<TResult?> Get<TResult>(object request, bool isPeristent)
{
throw new NotImplementedException();
var key = this.GetStoreKeyFromRequest(request);
var store = isPeristent ? "localStorage" : "sessionStorage";
var stringValue = ((IJSInProcessRuntime)jsruntime).Invoke<string?>(store + ".getItem", key);
if (String.IsNullOrWhiteSpace(stringValue))
return null!;

var final = JsonSerializer.Deserialize<TResult>(stringValue);
return Task.FromResult(final);
}

public Task Clear()
{
throw new NotImplementedException();
var inproc = (IJSInProcessRuntime)jsruntime;
inproc.InvokeVoid("localStorage.clear");
inproc.InvokeVoid("sessionStorage.clear");
return Task.CompletedTask;
}


protected virtual string GetStoreKeyFromRequest(object request)
{
if (request is IRequestKey keyProvider)
return keyProvider.GetKey();

var t = request.GetType();
var key = $"{t.Namespace}_{t.Name}";

return key;
}


// protected virtual string GetPersistentStoreKey(object request, bool createIfNotExists)
// {
// var key = this.GetStoreKeyFromRequest(request);
// this.EnsureKeyLoad();
// if (this.keys.ContainsKey(key))
// {
// key = this.keys[key];
// }
// else if (createIfNotExists)
// {
// var newKey = Guid.NewGuid().ToString();
// this.keys.Add(key, newKey);
// key = newKey;
//
// this.PersistKeyStore();
// }
//
// return key;
// }
}
1 change: 1 addition & 0 deletions src/Shiny.Mediator.Blazor/Shiny.Mediator.Blazor.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components" Version="8.0.8" />
<PackageReference Include="Microsoft.JSInterop" Version="8.0.0" />
<ProjectReference Include="..\Shiny.Mediator.AppSupport\Shiny.Mediator.AppSupport.csproj" />
<ProjectReference Include="..\Shiny.Mediator\Shiny.Mediator.csproj"/>
</ItemGroup>
Expand Down
21 changes: 21 additions & 0 deletions src/Shiny.Mediator.Blazor/wwwroot/Mediator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
let handler;

window.InternetService = {
subscribe: function(interop) {

handler = function() {
interop.invokeMethodAsync("InternetService.OnStatusChanged", navigator.onLine);
}

window.addEventListener("online", handler);
window.addEventListener("offline", handler);
},

unsubscribe: function() {
if (handler == null)
return;

window.removeEventListener("online", handler);
window.removeEventListener("offline", handler);
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@
namespace Shiny.Mediator.Caching.Infrastructure;


public class CachingRequestMiddleware<TRequest, TResult>(
IMemoryCache cache,
IFeatureService features
) : IRequestMiddleware<TRequest, TResult>
public class CachingRequestMiddleware<TRequest, TResult>(IMemoryCache cache) : IRequestMiddleware<TRequest, TResult>
{
public async Task<TResult> Process(
TRequest request,
Expand Down
4 changes: 1 addition & 3 deletions src/Shiny.Mediator.Maui/MauiExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,9 @@ public static ShinyConfigurator AddMainThreadMiddleware(this ShinyConfigurator c
/// to show a customized message
/// </summary>
/// <param name="cfg"></param>
/// <param name="config"></param>
/// <returns></returns>
public static ShinyConfigurator AddUserNotificationExceptionMiddleware(this ShinyConfigurator cfg, UserExceptionRequestMiddlewareConfig? config = null)
public static ShinyConfigurator AddUserNotificationExceptionMiddleware(this ShinyConfigurator cfg)
{
cfg.Services.AddSingleton(config ?? new());
cfg.AddOpenRequestMiddleware(typeof(UserExceptionRequestMiddleware<,>));
return cfg;
}
Expand Down
10 changes: 7 additions & 3 deletions src/Shiny.Mediator.Maui/Middleware/MainTheadEventMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
using System.ComponentModel;
using System.Reflection;
using Shiny.Mediator.Infrastructure;

namespace Shiny.Mediator.Middleware;


public class MainTheadEventMiddleware<TEvent> : IEventMiddleware<TEvent> where TEvent : IEvent
{
public async Task Process(IEvent @event, EventHandlerDelegate next, IEventHandler<TEvent> eventHandler, CancellationToken cancellationToken)
public async Task Process(
IEvent @event,
EventHandlerDelegate next,
IEventHandler<TEvent> eventHandler,
CancellationToken cancellationToken
)
{
var attr = eventHandler.GetHandlerHandleMethodAttribute<TEvent, MainThreadAttribute>();

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

namespace Shiny.Mediator.Middleware;


Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Shiny.Mediator.Infrastructure;

namespace Shiny.Mediator.Middleware;


public class UserExceptionRequestMiddleware<TRequest, TResult>(
IFeatureService features,
ILogger<TRequest> logger
ILogger<TRequest> logger,
IConfiguration config
) : IRequestMiddleware<TRequest, TResult>
{
public async Task<TResult> Process(TRequest request, RequestHandlerDelegate<TResult> next, IRequestHandler requestHandler, CancellationToken cancellationToken)
public async Task<TResult> Process(
TRequest request,
RequestHandlerDelegate<TResult> next,
IRequestHandler requestHandler,
CancellationToken cancellationToken
)
{
var attribute = requestHandler.GetHandlerHandleMethodAttribute<TRequest, UserNotifyAttribute>();
attribute ??= request!.GetType().GetCustomAttribute<UserNotifyAttribute>();
Expand All @@ -25,14 +31,14 @@ public async Task<TResult> Process(TRequest request, RequestHandlerDelegate<TRes
catch (Exception ex)
{
logger.LogError(ex, $"Error executing pipeline for {typeof(TRequest).FullName}");
try
{
var msg = config.ShowFullException ? ex.ToString() : attribute.ErrorMessage ?? config.ErrorMessage;
await Application.Current!.MainPage!.DisplayAlert(attribute.ErrorTitle ?? config.ErrorTitle, msg, config.ErrorConfirm);
}
catch
{
}
// try
// {
// var msg = config.ShowFullException ? ex.ToString() : attribute.ErrorMessage ?? config.ErrorMessage;
// await Application.Current!.MainPage!.DisplayAlert(attribute.ErrorTitle ?? config.ErrorTitle, msg, config.ErrorConfirm);
// }
// catch
// {
// }
}

return result!;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Polly.Registry;
using Shiny.Mediator.Infrastructure;

Expand All @@ -20,7 +21,7 @@ namespace Shiny.Mediator.Resilience.Handlers;
//https://learn.microsoft.com/en-us/dotnet/core/resilience/?tabs=dotnet-cli
//https://devblogs.microsoft.com/dotnet/building-resilient-cloud-services-with-dotnet-8/
public class ResilientRequestHandlerMiddleware<TRequest, TResult>(
IFeatureService features,
IConfiguration config,
ResiliencePipelineProvider<string> pipelineProvider
) : IRequestMiddleware<TRequest, TResult> where TRequest : IRequest<TResult>
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Linq;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
Expand Down Expand Up @@ -76,6 +75,8 @@ public void Execute(GeneratorExecutionContext context)
var assName = context.Compilation.AssemblyName?.Replace(".", "_");
var sb = new StringBuilder();
sb
.AppendLine("using Shiny.Mediator;")
.AppendLine()
.AppendLine($"namespace {nameSpace};")
.AppendLine()
.AppendLine("public static class __ShinyMediatorSourceGenExtensions {")
Expand Down
84 changes: 0 additions & 84 deletions src/Shiny.Mediator/Impl/FeatureService.cs

This file was deleted.

Loading

0 comments on commit 10046d0

Please sign in to comment.