Skip to content

Commit

Permalink
Added init for ResourcesManager
Browse files Browse the repository at this point in the history
  • Loading branch information
dyatlov-a committed Sep 20, 2024
1 parent ed151d3 commit 9cf09e1
Show file tree
Hide file tree
Showing 9 changed files with 59 additions and 47 deletions.
10 changes: 6 additions & 4 deletions src/Inc.TeamAssistant.Gateway/Apps/MainApp.razor
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
@using FluentValidation
@using Inc.TeamAssistant.Gateway.Configs
@using Inc.TeamAssistant.Primitives.Languages
@using Inc.TeamAssistant.WebUI.Contracts
@using Microsoft.AspNetCore.Components.Web
@using Inc.TeamAssistant.WebUI.Features
@using Inc.TeamAssistant.WebUI.Services

@inject IRenderContext RenderContext
@inject AnalyticsOptions AnalyticsOptions
@inject IServiceProvider ServiceProvider

<!DOCTYPE html>
<html lang="@_lang">
Expand Down Expand Up @@ -79,10 +81,10 @@
private readonly string _appVersion = ApplicationContext.GetVersion();
private string _lang = LanguageSettings.DefaultLanguageId.Value;

protected override void OnInitialized()
protected override async Task OnInitializedAsync()
{
var languageContext = RenderContext.GetLanguageContext();
var culture = await ValidatorOptions.Global.SetCulture(ServiceProvider);

_lang = languageContext.CurrentLanguage.Value;
_lang = culture.Name;
}
}
3 changes: 0 additions & 3 deletions src/Inc.TeamAssistant.Gateway/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
using Inc.TeamAssistant.Gateway.Services.ServerCore;
using Inc.TeamAssistant.Holidays.Model;
using Inc.TeamAssistant.Primitives.DataAccess;
using Inc.TeamAssistant.Primitives.Languages;
using Inc.TeamAssistant.RandomCoffee.Application;
using Inc.TeamAssistant.RandomCoffee.Application.Contracts;
using Inc.TeamAssistant.RandomCoffee.DataAccess;
Expand All @@ -41,8 +40,6 @@
using Microsoft.Extensions.WebEncoders;
using Serilog;

ValidatorOptions.Global.Configure(LanguageSettings.DefaultLanguageId);

var builder = WebApplication
.CreateBuilder(args)
.ConfigureTelemetry()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,15 @@ namespace Inc.TeamAssistant.Gateway.Services.Clients;
internal sealed class MessageProviderCached : IMessageProvider
{
private readonly IMemoryCache _memoryCache;
private readonly ILogger<MessageProviderCached> _logger;
private readonly IMessageProvider _messageProvider;
private readonly TimeSpan _cacheAbsoluteExpiration;

public MessageProviderCached(
IMemoryCache memoryCache,
ILogger<MessageProviderCached> logger,
IMessageProvider messageProvider,
TimeSpan cacheAbsoluteExpiration)
{
_memoryCache = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_messageProvider = messageProvider ?? throw new ArgumentNullException(nameof(messageProvider));
_cacheAbsoluteExpiration = cacheAbsoluteExpiration;
}
Expand All @@ -32,13 +29,7 @@ public async Task<Dictionary<string, Dictionary<string, string>>> Get(Cancellati
c.SetAbsoluteExpiration(_cacheAbsoluteExpiration);
return await _messageProvider.Get(token);
});

if (cacheItem is null)
{
_logger.LogWarning("Can not get object with key {CacheKey} from cache", cacheKey);
return await _messageProvider.Get(token);
}

return cacheItem;
return cacheItem ?? await _messageProvider.Get(token);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,15 @@ namespace Inc.TeamAssistant.Gateway.Services.ServerCore;
internal sealed class QuickResponseCodeGeneratorCached : IQuickResponseCodeGenerator
{
private readonly IMemoryCache _memoryCache;
private readonly ILogger<QuickResponseCodeGeneratorCached> _logger;
private readonly IQuickResponseCodeGenerator _generator;
private readonly TimeSpan _cacheAbsoluteExpiration;

public QuickResponseCodeGeneratorCached(
IMemoryCache memoryCache,
ILogger<QuickResponseCodeGeneratorCached> logger,
IQuickResponseCodeGenerator generator,
TimeSpan cacheAbsoluteExpiration)
{
_memoryCache = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_generator = generator ?? throw new ArgumentNullException(nameof(generator));
_cacheAbsoluteExpiration = cacheAbsoluteExpiration;
}
Expand All @@ -37,11 +34,7 @@ public string Generate(string data, string foreground, string background)

return _generator.Generate(data, foreground, background);
});

if (cacheItem is not null)
return cacheItem;

_logger.LogWarning("Can not get object with key {CacheKey} from cache", key);
return _generator.Generate(key, foreground, background);
return cacheItem ?? _generator.Generate(key, foreground, background);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@

private string _title = GlobalSettings.CanonicalName;

protected override void OnParametersSet()
protected override async Task OnParametersSetAsync()
{
await ResourcesManager.Initialize();

_title = CreateTitle();
}

Expand Down
16 changes: 4 additions & 12 deletions src/Inc.TeamAssistant.WebUI/Features/Routes.razor
Original file line number Diff line number Diff line change
Expand Up @@ -35,24 +35,16 @@

protected override async Task OnInitializedAsync()
{
SetCurrentLanguage();

NavigationManager.LocationChanged += OnLocationChanged;

await ResourcesManager.Load();

_eventsProvider = ServiceProvider.GetService<EventsProvider>();
if (_eventsProvider is not null)
await _eventsProvider.Start();

NavigationManager.LocationChanged += OnLocationChanged;
}

private void OnLocationChanged(object? sender, LocationChangedEventArgs e) => SetCurrentLanguage();

private void SetCurrentLanguage()
private async void OnLocationChanged(object? sender, LocationChangedEventArgs e)
{
var languageContext = RenderContext.GetLanguageContext();

ValidatorOptions.Global.Configure(languageContext.CurrentLanguage);
await ValidatorOptions.Global.SetCulture(ServiceProvider);
}

public async ValueTask DisposeAsync()
Expand Down
7 changes: 6 additions & 1 deletion src/Inc.TeamAssistant.WebUI/Program.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using FluentValidation;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Inc.TeamAssistant.WebUI.Services;

Expand All @@ -8,4 +9,8 @@
.AddServices()
.AddIsomorphic();

await builder.Build().RunAsync();
var host = builder.Build();

await ValidatorOptions.Global.SetCulture(host.Services);

await host.RunAsync();
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public sealed class ResourcesManager : IDisposable
private readonly IMessageProvider _messageProvider;
private readonly PersistentComponentState _applicationState;

private readonly SemaphoreSlim _sync = new(1, 1);
private PersistingComponentStateSubscription? _persistingSubscription;
private Dictionary<string, Dictionary<string, string>> _resources = new();

Expand All @@ -21,10 +22,29 @@ public ResourcesManager(
_renderContext = renderContext ?? throw new ArgumentNullException(nameof(renderContext));
_applicationState = applicationState ?? throw new ArgumentNullException(nameof(applicationState));
}

public async Task Initialize(CancellationToken token = default)
{
if (_resources.Any())
return;

await _sync.WaitAsync(token);

try
{
if (!_resources.Any())
await Load(token);
}
finally
{
_sync.Release();
}
}

public async Task Load(CancellationToken token = default)
private async Task Load(CancellationToken token)
{
const string key = nameof(ResourcesManager);

var resources = _applicationState.TryTakeFromJson<Dictionary<string, Dictionary<string, string>>>(key, out var restored) && restored is not null
? restored
: await _messageProvider.Get(token);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
using System.Globalization;
using FluentValidation;
using Inc.TeamAssistant.Primitives.Languages;
using Inc.TeamAssistant.WebUI.Contracts;
using Inc.TeamAssistant.WebUI.Services.ClientCore;

namespace Inc.TeamAssistant.WebUI.Services;

public static class ValidatorConfigurationExtensions
{
public static ValidatorConfiguration Configure(
public static async Task<CultureInfo> SetCulture(
this ValidatorConfiguration validatorConfiguration,
LanguageId languageId)
IServiceProvider serviceProvider)
{
ArgumentNullException.ThrowIfNull(validatorConfiguration);
ArgumentNullException.ThrowIfNull(languageId);
ArgumentNullException.ThrowIfNull(serviceProvider);

validatorConfiguration.LanguageManager.Culture = new(languageId.Value);
var renderContext = serviceProvider.GetRequiredService<IRenderContext>();
var resourcesManager = serviceProvider.GetRequiredService<ResourcesManager>();

var languageContext = renderContext.GetLanguageContext();
var culture = new CultureInfo(languageContext.CurrentLanguage.Value);

validatorConfiguration.LanguageManager.Culture = culture;
validatorConfiguration.DefaultClassLevelCascadeMode = CascadeMode.Continue;
validatorConfiguration.DefaultRuleLevelCascadeMode = CascadeMode.Stop;

return validatorConfiguration;

await resourcesManager.Initialize();

return culture;
}
}

0 comments on commit 9cf09e1

Please sign in to comment.