public new IStringLocalizer Create(string baseName, string location) { FieldInfo fieldInfo = typeof(SqlStringLocalizerFactory).GetField("_resourceLocalizations", BindingFlags.Static | BindingFlags.NonPublic); var resourceLocalizations = (ConcurrentDictionary <string, IStringLocalizer>)fieldInfo.GetValue(this); fieldInfo = typeof(SqlStringLocalizerFactory).GetField("_developmentSetup", BindingFlags.Instance | BindingFlags.NonPublic); var developmentSetup = (DevelopmentSetup)fieldInfo.GetValue(this); fieldInfo = typeof(SqlStringLocalizerFactory).GetField("_options", BindingFlags.Instance | BindingFlags.NonPublic); var localizationOptions = (IOptions <SqlLocalizationOptions>)fieldInfo.GetValue(this); if (resourceLocalizations.Keys.Contains(baseName + location)) { return(resourceLocalizations[baseName + location]); } Type type = GetType().BaseType; MethodInfo method = type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic) .Single(m => m.Name == "GetAllFromDatabaseForResource"); SqlStringLocalizerFactory baseFactory = this; Dictionary <string, string> localizations = (Dictionary <string, string>)method.Invoke(baseFactory, new object[] { baseName + location }); SqlStringLocalizer sqlStringLocalizer = new SqlStringLocalizer(localizations, developmentSetup, baseName + location, localizationOptions.Value.ReturnOnlyKeyIfNotFound, localizationOptions.Value.CreateNewRecordWhenLocalisedStringDoesNotExist); return(resourceLocalizations.GetOrAdd(baseName + location, sqlStringLocalizer)); }
private async Task ImportResxLanguages() { try { if (!await _localizationDbContext.LocalizationRecords.AnyAsync()) { _logger.LogInformation("Importing Resx files in db"); var regex = new Regex(@".(\w{2}-\w{2}).resx"); foreach (var resxFile in Directory.GetFiles(@"..\..\Shared\BlazorBoilerplate.Localization", "*.resx")) { var m = regex.Match(resxFile); var culture = Shared.SqlLocalizer.Settings.NeutralCulture; if (m.Success) { culture = m.Groups[1].Value; } XDocument doc = XDocument.Load(new XmlTextReader(resxFile)); foreach (var node in doc.Element("root").Elements("data")) { _localizationDbContext.Add(new LocalizationRecord() { LocalizationCulture = culture, Key = node.Attribute("name").Value, Text = node.Element("value").Value, ResourceKey = "Global" }); } await _localizationDbContext.SaveChangesAsync(); } SqlStringLocalizerFactory.SetLocalizationRecords(_localizationDbContext.LocalizationRecords); } } catch (Exception ex) { _logger.LogError("Importing Resx files in db error: {0}", ex.Message); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRequestLocalization(); // cookie policy to deal with temporary browser incompatibilities app.UseCookiePolicy(); EmailTemplates.Initialize(env); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebAssemblyDebugging(); //ClientSideBlazor } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. // app.UseHsts(); //HSTS Middleware (UseHsts) to send HTTP Strict Transport Security Protocol (HSTS) headers to clients. } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseBlazorFrameworkFiles(); //ClientSideBlazor app.UseRouting(); app.UseIdentityServer(); app.UseAuthentication(); app.UseAuthorization(); app.UseMultiTenant(); using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope()) { var databaseInitializer = serviceScope.ServiceProvider.GetService <IDatabaseInitializer>(); databaseInitializer.SeedAsync().Wait(); var localizationDbContext = serviceScope.ServiceProvider.GetService <LocalizationDbContext>(); SqlStringLocalizerFactory.SetLocalizationRecords(localizationDbContext.LocalizationRecords); } app.UseMiddleware <UserSessionMiddleware>(); // before app.UseMultiTenant() make injected TenantInfo == null app.UseMiddleware <APIResponseRequestLoggingMiddleware>(); if (_enableAPIDoc) { app.UseOpenApi(); app.UseSwaggerUi3(settings => { settings.OAuth2Client = new OAuth2ClientSettings() { AppName = projectName, ClientId = IdentityServerConfig.SwaggerClientID, UsePkceWithAuthorizationCodeGrant = true }; }); } app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); endpoints.MapControllers(); endpoints.MapBlazorHub(); endpoints.MapFallbackToPage("/_Index"); // new SignalR endpoint routing setup endpoints.MapHub <Hubs.ChatHub>("/chathub"); }); }
public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); //TODO see what oqtane does var baseModule = new Theme.Material.Module(); var adminModule = new Theme.Material.Admin.Module(); var demoModule = new Theme.Material.Demo.Module(); Assembly[] allAssemblies = AppDomain.CurrentDomain.GetAssemblies(); ModuleProvider.Init(allAssemblies); builder.RootComponents.AddRange(new[] { ModuleProvider.RootComponentMapping }); builder.Services.AddSqlLocalization(options => options.ReturnOnlyKeyIfNotFound = !builder.HostEnvironment.IsDevelopment()); builder.Services.AddDataProtection().SetApplicationName(nameof(BlazorBoilerplate)); builder.Services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); builder.Services.AddAuthorizationCore(config => { config.AddPolicy(Policies.IsAdmin, Policies.IsAdminPolicy()); config.AddPolicy(Policies.IsUser, Policies.IsUserPolicy()); config.AddPolicy(Policies.IsReadOnly, Policies.IsUserPolicy()); // config.AddPolicy(Policies.IsMyDomain, Policies.IsMyDomainPolicy()); Only works on the server end }); builder.Services.AddTransient <ILocalizationApiClient, LocalizationApiClient>(); builder.Services.AddScoped <AuthenticationStateProvider, IdentityAuthenticationStateProvider>(); builder.Services.AddScoped <IAccountApiClient, AccountApiClient>(); builder.Services.AddScoped <AppState>(); builder.Services.AddTransient <IApiClient, ApiClient>(); foreach (var module in ModuleProvider.Modules) { module.ConfigureWebAssemblyServices(builder.Services); } var host = builder.Build(); foreach (var module in ModuleProvider.Modules) { module.ConfigureWebAssemblyHost(host); } using (var serviceScope = host.Services.GetRequiredService <IServiceScopeFactory>().CreateScope()) { var js = serviceScope.ServiceProvider.GetService <IJSRuntime>(); var cookieCulture = await js.GetAspNetCoreCultureCookie(); if (!string.IsNullOrWhiteSpace(cookieCulture)) { CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(cookieCulture); CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CurrentCulture; } var localizationApiClient = serviceScope.ServiceProvider.GetService <ILocalizationApiClient>(); var localizationRecords = (await localizationApiClient.GetLocalizationRecords()).ToList(); SqlStringLocalizerFactory.SetLocalizationRecords(localizationRecords); } await host.RunAsync(); }
public ApiResponse ReloadTranslations() { SqlStringLocalizerFactory.SetLocalizationRecords(persistenceManager.Context.LocalizationRecords); return(new ApiResponse(Status200OK)); }