SQLite Localization In Blazor Server

Introduction

 
Blazor is a framework built by Microsoft for creating interactive client-side web UI with .NET codebase. We can write both client-side and server-side code in C#.NET. There are two hosting models available for Blazor: Blazor Server and Blazor WebAssembly. Blazor WebAssembly was released in May 2020, as per the Microsoft roadmap.
 
In this article, I will show how to use SQLite localization in a Blazor server-side application. We will have two cultures ("en" and "ru").
 

Create a Blazor server application using Visual Studio for Mac

 
Currently, Visual Studio for Mac 8.8 is available with the Blazor server template. Since we are creating a WebApp, I am using a Visual Studio extension to create it. This extension will provide the template for Razor.
 
Choose a template for your project: Blazor Server App, Next > Authentication: No Authentication, Next > ProjectName: (For example` BlazorSqlite), then create a solution.
 
 

Modify appsettings.json

 
In our project, we have an appsettings.json file. We need to open and modify it.
 
Add a Localization section for the SQLite file path. We will use it for getting translations for our keys.
 
 

Manage NuGet packages 

 
There are many types of localization, but in this article, we will use SQLite localization. For that, we need to add "Localization.SqlLocalizer" from NuGet packages. We also need "Microsoft.EntityFrameworkCore.Sqlite '' for working with SQLite files.
 
Add the following packages to your project:
  • Localization.SqlLocalizer
  • Microsoft.EntityFrameworkCore.Sqlite

Modify Startup.cs

 
First of all, we need to get an SQLite connection string for our appsettings, and then add services and supported cultures.
 
Add the following code to your Startup > ConfigureServices: 
  1. public void ConfigureServices(IServiceCollection services) {  
  2.     services.AddRazorPages();  
  3.     string sqlConnectionString = Configuration.GetSection("Localization").GetValue < string > ("ConnectionString");  
  4.     services.AddServerSideBlazor();  
  5.     services.AddDbContext < LocalizationModelContext > (options => options.UseSqlite(sqlConnectionString, b => b.MigrationsAssembly("BlazorSqlite")), ServiceLifetime.Singleton, ServiceLifetime.Singleton);  
  6.     var useTypeFullNames = true;  
  7.     var useOnlyPropertyNames = false;  
  8.     var returnOnlyKeyIfNotFound = true;  
  9.     var CreateNewRecordWhenLocalisedStringDoesNotExist = true;  
  10.     services.AddSqlLocalization(options => options.UseSettings(useTypeFullNames, useOnlyPropertyNames, returnOnlyKeyIfNotFound, CreateNewRecordWhenLocalisedStringDoesNotExist));  
  11.     services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);  
  12.     IList < CultureInfo > supportedCultures = new List < CultureInfo > ();  
  13.     CultureInfo defCulture = new CultureInfo("en");  
  14.     supportedCultures.Add(new CultureInfo("en"));  
  15.     supportedCultures.Add(new CultureInfo("ru"));  
  16.     services.AddSingleton < WeatherForecastService > ();  
  17.     services.Configure < RequestLocalizationOptions > (options => {  
  18.         options.DefaultRequestCulture = new RequestCulture(defCulture);  
  19.         options.SupportedCultures = supportedCultures;  
  20.         options.SupportedUICultures = supportedCultures;  
  21.     });  
  22. }   
** defCulture is your default culture.
** supportedCultures is yout project supported cultures (Ex` en/ru)
 
Add the following code to your Startup > Configure
 
After adding services, we need to add supported request cultures.
  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {  
  2.     IList < CultureInfo > supportedCultures = new List < CultureInfo > ();  
  3.     CultureInfo defCulture = new CultureInfo("en");  
  4.     supportedCultures.Add(new CultureInfo("en"));  
  5.     supportedCultures.Add(new CultureInfo("ru"));  
  6.     RequestLocalizationOptions localizationOptions = new RequestLocalizationOptions {  
  7.         DefaultRequestCulture = new RequestCulture(defCulture),  
  8.             SupportedCultures = supportedCultures,  
  9.             SupportedUICultures = supportedCultures  
  10.     };  
  11.     RouteDataRequestCultureProvider requestProvider = new RouteDataRequestCultureProvider();  
  12.     localizationOptions.RequestCultureProviders.Insert(0, requestProvider);  
  13.     CultureInfo.DefaultThreadCurrentCulture = defCulture;  
  14.     CultureInfo.DefaultThreadCurrentUICulture = defCulture;  
  15.     if (env.IsDevelopment()) {  
  16.         app.UseDeveloperExceptionPage();  
  17.     } else {  
  18.         app.UseExceptionHandler("/Error");  
  19.         // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.    
  20.         app.UseHsts();  
  21.     }  
  22.     app.UseRequestLocalization(localizationOptions);  
  23.     app.UseHttpsRedirection();  
  24.     app.UseStaticFiles();  
  25.     app.UseRouting();  
  26.     app.UseEndpoints(endpoints => {  
  27.         endpoints.MapControllers();  
  28.         endpoints.MapBlazorHub();  
  29.         endpoints.MapFallbackToPage("/_Host");  
  30.     });  
  31. }   
** defCulture is your default culture.
** supportedCultures is your project supported cultures (Ex` en/ru)
 

Create CultureController

 
I'm using the SetCulture action, in order to change our project culture. It accepts two parameters. The first is culture, which we will change and the second is redirecUri, which we will use to redirect
 
Create a Controllers folder, then add CultureController.cs
  1. [Route("[controller]/[action]")]  
  2.     public class CultureController : Controller  
  3.     {  
  4.         public IActionResult SetCulture(string culture, string redirectUri)  
  5.         {  
  6.             if (culture != null)  
  7.             {  
  8.                 HttpContext.Response.Cookies.Append(  
  9.                     CookieRequestCultureProvider.DefaultCookieName,  
  10.                     CookieRequestCultureProvider.MakeCookieValue(  
  11.                         new RequestCulture(culture)));  
  12.             }  
  13.   
  14.             return LocalRedirect(redirectUri);  
  15.         }  
  16.     }  
 

Modify _Imports.razor

 
Append the following using, which will help to use IStringLocalizer in our razor pages.
  1. @using Microsoft.Extensions.Localization  

Modify Index.razor in Pages

 
For using localization in razor pages, we need to do the following steps:
  • Inject IStringLocalizer in the top as "Localizer"
  • Use @Localizer["Hello, world"] so as to achieve getting translated value
  • At the bottom, we need to write a function, which will help us to change the culture.
  • Call "ChangeCulture" function in select.
  1. @page "/"  
  2.   
  3. @inject NavigationManager NavigationManager  
  4. @inject IStringLocalizer<BlazorSqlite.Controllers.CultureController> Localizer  
  5.   
  6. <h1>@Localizer["Hello, world"]!</h1>  
  7.   
  8. @Localizer["Welcome to your new app"].  
  9.   
  10. <SurveyPrompt Title="How is Blazor working for you?" />  
  11.   
  12. <h3>Select your language</h3>  
  13.   
  14. <select @onchange="ChangeCulture">  
  15.     <option>Select culture</option>  
  16.     <option value="en">English</option>  
  17.     <option value="ru">Russian</option>  
  18. </select>  
  19.   
  20.   
  21. @code {  
  22.     private void ChangeCulture(ChangeEventArgs e)  
  23.     {  
  24.         var culture = (string)e.Value;  
  25.         var uri = new Uri(NavigationManager.Uri)  
  26.             .GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped);  
  27.         var query = $"?culture={Uri.EscapeDataString(culture)}&" +  
  28.             $"redirectUri={Uri.EscapeDataString(uri)}";  
  29.   
  30.         NavigationManager.NavigateTo("/Culture/SetCulture" + query, forceLoad: true);  
  31.     }  
  32. }  
Now we can test our Blazor SQLite localization 
  1. Run the project (ensure your SQLite path is correct) 
  2. Change select value
Select English: 
 
 
Select Russian:
 
 
SQLite File Example
 
Here is my SQLite file view:
 
 

Conclusion

 
In this post, I have explained how to set localization in the Blazor server app. I used Visual Studio Mac. In this example, I used a template project of the Blazor server app. I have used two cultures, English and Russian. Please feel free to send your feedback.
 
Thanks! 


Similar Articles