November 24, 2024

Mindgaze.Languages with Blazor

Hey folks! Hope this post finds you in good development shape! Have you heard of Blazor? This new tech is a first class citizen in .NET Core 3.0. With the help of Blazor, you can create C# apps that run as SPAs directly in browser. Hence you can share code with other .NET libraries and use the common APIs of .NET directly in the browser. You are limited of course, for instance APIs that call file methods are throwing a PlatformNotSupported exception.

A Blazor app is the same as a .NET Core Web App one, just that it doesn’t serve cshtml files, but static prerendered content that is handled to the client. The client starts from where the server left and control of the app is given to the client and works as SPA app. The cool thing is that you can use any netstandard library from Nuget. That means the Mindgaze.Languages too! If you are not familiar with this library please check this post and this one.

Setup the app

Now let’s get started. First make sure you have Visual Studio 2019 with latest updates installed, including .NET Core SDK 3.0. If you don’t have already, please create a Blazor WebApp in your solution. Now go to packages and install these two libraries:

Create in the project a Strings folder with two json files called Strings.json and Strings.config.json. You can put whichever content you like there, but mind that there are rules to be respected there. If you define two or languages in the config file, your strings file needs to have definitions for all languages written in config.

Strings.json

{
  "ApplicationTitle": {
    "en-US": "Multilanguage Sample",
    "ro-RO": "Exemplu Multilanguage"
  },
  "ApplicationAbout": {
    "en-US": "About the app",
    "ro-RO": "Despre aplicație"
  },
  "Home": {
    "en-US": "Home",
    "ro-RO": "Acasă"
  },
  "About": {
    "en-US": "About",
    "ro-RO": "Despre"
  },
  "Contact": {
    "en-US": "Contact",
    "ro-RO": "Contact"
  }
}

Strings.config.json

{
  "languages": [
    {
      "name": "en-US",
      "extra": {
        "Description": "English"
      }
    },
    {
      "name": "ro-RO",
      "extra": {
        "Description": "Română"
      }
    }
  ]
}

Now in Startup.cs, you need to add the MultiLanguage service and the middleware. and the Environment property. So, the whole Startup class will look like this:


public class Startup
{
    public Startup(IConfiguration configuration, IWebHostEnvironment environment)
    {
        Configuration = configuration;
        Environment = environment;
    }

    public IConfiguration Configuration { get; }

    public IWebHostEnvironment Environment { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddSingleton<WeatherForecastService>();
        services.AddMultiLanguage(
            Path.Combine(Environment.ContentRootPath, "Strings", "Strings.json"),
            Path.Combine(Environment.ContentRootPath, "Strings", "Strings.config.json")
            );
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseRequestMultiLanguageLocalization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
        });
    }
}

It’ time to go to a .razor file and check it out. First what you need to do is to inject the MultiLanguageWorkshop service and the use it whenever is necessary:

@inject MultiLanguageWorkshop Workshop
....
@Workshop["ApplicationTitle"]

Change the language

You can very easily change the language on the fly and the UI will update accordingly. Add buttons for each language change and then use the injected language service to instruct to use the desired language. Check this out (ignore the counter code, it comes from the template 😃):

As you can observe if you run the application, you can change the language with the buttons. Horray!

Persist across refreshes

You’ll notice this language change is not preserved if you refresh the page. In order to do that, a cookie needs to be created and the easiest way to do that is to call a server method. However this is beyond the purpose of this article, but you can find information here. Please check the SetCulture method described there. If you implement that, there’s nothing more do to because the Languages library integrates very well with the AspNetCore CultureProvider so it’ll know to read the cookie and set the right language for your app.

If you run into trouble with anything above, I’d be delighted to help. Just reach to me; you can find info in the About page or use this Contact form.

And very important don’t forget to check the source code!

Thanks for reading, I hope you found this article useful and interesting. If you have any suggestions don’t hesitate to contact me. If you found my content useful please consider a small donation. Any support is greatly appreciated! Cheers  😉

afivan

Enthusiast adventurer, software developer with a high sense of creativity, discipline and achievement. I like to travel, I like music and outdoor sports. Because I have a broken ligament, I prefer safer activities like running or biking. In a couple of years, my ambition is to become a good technical lead with entrepreneurial mindset. From a personal point of view, I’d like to establish my own family, so I’ll have lots of things to do, there’s never time to get bored 😂

View all posts by afivan →