How to perform localization using database instead of resource files in Blazor?
This article explains how to perform the localization by using the database without using the resource files in Blazor
Create Blazor App
Create Blazor Server App with Scheduler component. Here, Scheduler component added in ~/Index.razor.
@using Syncfusion.Blazor.Schedule <h2>Syncfusion Blazor Schedule Component</h2> <br /> <SfSchedule TValue="AppointmentData" Height="650px" SelectedDate="@(new DateTime(2020, 2, 14))"> <ScheduleEventSettings DataSource="@DataSource"></ScheduleEventSettings> </SfSchedule> <br /> <br /> @code{ List<AppointmentData> DataSource = new List<AppointmentData> { new AppointmentData { Id = 1, Subject = "Paris", StartTime = new DateTime(2020, 2, 13, 10, 0, 0) , EndTime = new DateTime(2020, 2, 13, 12, 0, 0) }, new AppointmentData { Id = 2, Subject = "Germany", StartTime = new DateTime(2020, 2, 15, 10, 0, 0) , EndTime = new DateTime(2020, 2, 15, 12, 0, 0) } }; public class AppointmentData { public int Id { get; set; } public string Subject { get; set; } public DateTime StartTime { get; set; } public DateTime EndTime { get; set; } } }
Fig 1: This is the image for Schedule Default Output
Click the any cells for make interaction and schedule the new event.
Fig 2: This is the image for Schedule default popup interaction
Create database to store key and strings for localization
Create the Table in SQL Server or any data base for storing the localization key and culture-based strings. Here, the table is created in SQL server in a name Table.
Fig 3: This is the image for Localization database table
Scaffolding database in Blazor App
Follow below steps to scaffold Table.cs table to create DbContext and model classes.
- Install following NuGet packages to scaffolding table in SQL server database. Run the following commands in the Package Manager Console.
//This package creates database context and model classes from the database.
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 5.0.0
//The database provider that allows EntityFramework to work with SQL Server.
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 5.0.0
- Once these packages are installed, scaffold DbContext and model classes by running the following command in the Package Manager Console under Server project.
Scaffold-DbContext “<<Connection-String>>” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
- After running the above command, ‘SyncLocalizationContext.cs’ and ‘Table.cs’ files will be created in the Models folder as follows.
Fig 4: Representation for Table.cs
Fig 5: Representation for SyncLocalizationContext.cs
- Configure connection string to ‘appsettings.json’ file, since it is not recommended to have a connection string with sensitive information in the ‘SyncLocalizationContext.cs’ file.
Fig 6: This is the image for Connection String Setup
Localize using database
Create ~/Shared/SyncfusionLocalizer.cs file and implement ISyncfusionStringLocalizer interface. This acts as a middleware to connect the Syncfusion Blazor UI components and Database to get the localization strings based on the key values.
In SyncfusionLocalizer.cs, the GetText method returns the localized strings from database table for the corresponding key.
namespace {{NameSpace}} { public class SyncfusionLocalizer : ISyncfusionStringLocalizer { public SyncLocalizationContext Localizer { get; set; } public SyncfusionLocalizer(SyncLocalizationContext StringLocalizer) { this.Localizer = StringLocalizer; } public string GetText(string key) { string cultureValue = ""; //Code for retriving the localized strings based on the key. IList<Table> table = Localizer.Tables.ToList(); Table data = table.Where(obj => obj.Key == key).FirstOrDefault(); if (data != null) { string culture = CultureInfo.CurrentCulture.Name; cultureValue = data.GetType().GetProperty(culture).GetValue(data, null).ToString(); return cultureValue; } return cultureValue; } … … … } }
Now, configure DbContext and ISyncfusionStringLocalizer in startup.cs as below,
. . . . . . . . using Microsoft.EntityFrameworkCore; public class Startup { ..... ..... ..... public void ConfigureServices(IServiceCollection services) { ..... ..... services.AddSyncfusionBlazor(); services.AddControllers(); services.AddDbContext<SyncLocalizationContext>(options => { options.UseSqlServer(Configuration.GetConnectionString("LocalizationDBConString")); }); var context = services.BuildServiceProvider().GetService<SyncLocalizationContext>(); services.AddSingleton<ISyncfusionStringLocalizer>(serviceProvider => new SyncfusionLocalizer(context)); ..... ..... } }
Configure the localization
Create ~/Controllers/CultureController.cs file and configure the controller to switch the culture using UI.
namespace BlazorServer.Controllers { [Route("[controller]/[action]")] public class CultureController : Controller { public IActionResult SetCulture(string culture, string redirectUri) { if (culture != null) { HttpContext.Response.Cookies.Append( CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture))); } return LocalRedirect(redirectUri); } } }
Then add the below configurations for localization in ~/Startup.cs
public class Startup { .... .... .... public void ConfigureServices(IServiceCollection services) { .... .... services.AddSyncfusionBlazor(); services.AddControllers(); .... .... services.Configure<RequestLocalizationOptions>(options => { // Define the list of cultures your app will support var supportedCultures = new List<CultureInfo>() { new CultureInfo("en-US"), new CultureInfo("de") }; // Set the default culture options.DefaultRequestCulture = new RequestCulture("en-US"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); } // 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(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value); ..... ..... ..... app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapBlazorHub(); endpoints.MapFallbackToPage("/_Host"); }); } }
For more details about Syncfusion Blazor Application Localization, Check here.
Configure the UI for culture switcher
Create a Blazor component named as CultureSwitcher.razor in the ~/Shared/ folder.
@inject NavigationManager NavigationManager <h3>Select your language</h3> <select @onchange="OnSelected"> <option>Select Culture</option> <option value="en-US">English</option> <option value="de">German</option> </select> @code { private void OnSelected(ChangeEventArgs e) { var culture = (string)e.Value; var uri = new Uri(NavigationManager.Uri) .GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped); var query = $"?culture={Uri.EscapeDataString(culture)}&" + $"redirectUri={Uri.EscapeDataString(uri)}"; NavigationManager.NavigateTo("/Culture/SetCulture" + query, forceLoad: true); } }
Then, add CultureSwitcher component to ~/Shared/MainLayout.razor file.
@inherits LayoutComponentBase <div class="page"> <div class="sidebar"> <NavMenu /> </div> <div class="main"> <div class="top-row px-4"> <CultureSwitcher /> <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a> </div> <div class="content px-4"> @Body </div> </div> </div>
Now, run the project and use the switcher to change the culture.
Fig 7: Output for 'en-US'
Fig 8: Output for 'de' (German)