Click here to Skip to main content
15,881,803 members
Articles / Web Development / HTML
Tip/Trick

.Net custom Culture with use case

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
6 May 2015CPOL3 min read 11.4K   99   6  
In this article I'll show how to create custom culture and then show an exemple of how to use it in an ASP.Net MVC application.

Introduction

This article show the register and unregister custom culture on the local machine. In a second time, it show an use case of custom culture in an ASP.Net MVC project (using VS2013).

1 - New custom cultures

In the first step we create a new Console project, it allowed the custom culture's registering on the local machine.

  • once created, add a reference to C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\sysglobl.dll
  • in Program.cs file add "using System.Globalization;"

Next the instructions to register a culture :

C#
static void AddCulture(string region, string baseCulture, string newCulture)
{
    try {
        var cultureInfos = new CultureInfo(baseCulture);
        var regionInfos = new RegionInfo(region);

        var builder = new CultureAndRegionInfoBuilder(newCulture, CultureAndRegionModifiers.None);
        builder.LoadDataFromCultureInfo(cultureInfos);
        builder.LoadDataFromRegionInfo(regionInfos);

        builder.Register();
        Console.WriteLine("SUCCES ADD [" + newCulture + "]");
    }
    catch (Exception e)
    {
        Console.WriteLine("ERREUR ADD [" + newCulture + "] : " + e.Message);
    }
}

And to unregister it :

C#
static void DeleteCulture(string newCulture)
{
    try {
        CultureAndRegionInfoBuilder.Unregister(newCulture);
        Console.WriteLine("SUCCES DELETE [" + newCulture + "]");
    }
    catch (Exception e)
    {
        Console.WriteLine("ERREUR DELETE [" + newCulture + "] : " + e.Message);
    }
}

In the Main sub we can write this code to add two cultures "fr-FR-Canin" and "fr-FR-Felin" :

C#
string region = "FR";
string baseCulture = "fr-FR";
string[] tbCulture = new string[2] { "fr-FR-Felin", "fr-FR-Canin" };

Console.WriteLine("Taper 1 pour ajouter les cultures ou 2 pour les enlever :");
string key = Console.ReadLine();
if (key == "1") {
    foreach (var item in tbCulture) AddCulture(region, baseCulture, item);
}
if (key == "2") {
    foreach (var item in tbCulture) DeleteCulture(item);
}

Console.ReadLine();

To go more deep in Culture you have this article here.

Now we can build the project to create the executable file and launch it on the local machine with administrator privileges.

2 - How to use it

For that we are going to use an ASP.Net MVC application, and add/update files.

2.1 - Resource files

Here we create a new folder "Ressources" and add 3 resource files :

  • the base one "Caracteristique.resx" which contains (property/value) :
    • "Bruit"   :    "fait du bruit"
    • "MetsFavoris"    :    "nourriture"
    • "Ennemi"    :    "puce"
  • the one for Felin "Caracteristique.resx" which contains (property/value) :
    • "Bruit"   :    "miauler"
    • "MetsFavoris"    :    "poisson"
  • the one for Canin "Caracteristique.resx" which contains (property/value) :
    • "Bruit"   :    "aboyer"
    • "MetsFavoris"    :    "os"

2.2 - Model "Animal.cs"

We create it in the Models folder and add using instruction inside :

  • C#
    using System.ComponentModel.DataAnnotations;       //for attributs
  • C#
    using resx = WebAppCulture.Ressources;            //to acces resource properties

Then we add properties and set the Display attribut :

C#
public string Nom { get; set; }

[Display(ResourceType = typeof(resx.Caracteristique), Name = "Bruit")]
public bool FaitDuBruit { get; set; }

[Display(ResourceType = typeof(resx.Caracteristique), Name = "MetsFavoris")]
public bool MetsFavoris { get; set; }

[Display(ResourceType = typeof(resx.Caracteristique), Name = "Ennemi")]
public bool Infecter { get; set; }

2.3 - Custom "ActionFilterAttribute"

Next we create a custom ActionFilterAttribute (in a new folder "Attributes") to define the culture to use when an action is called. The culture is passed as a parameter to the constructor. This custom action filter will be used like a class attribut in controllers.

C#
using...
using System.Web.Mvc;
using System.Globalization;
using System.Threading;

namespace WebAppCulture.Attributes
{
    /// <summary>
    /// Attribut permettant de définir la localisation à utiliser pour toutes les actions d'un contrôleur
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class LocalisationAttribute : ActionFilterAttribute
    {
        public readonly string CultureName;

        public LocalisationAttribute(string cultureName)
        {
            CultureName = cultureName;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(CultureName);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(CultureName);
        }
    }
}

2.4 - Controllers and View

In the Controllers folder we first create "BaseAnimalController.cs" and add one using instruction :

  • C#
    using WebAppCulture.Models;                //to use "Animal" model class

We arrange the Index action like that : (here is the default animal, not a dog, not a cat)

C#
public ActionResult Index(Animal animal = null)
{
    if (animal == null) { animal = new Animal() { Nom="Toutou" }; }
    if (string.IsNullOrEmpty(animal.Nom)) { animal.Nom = "Toutou"; }

    return View("Animal", animal);
}

In the second step we create the view "Animal.cshtml" in the Views\Shared folder :

  • add "@model WebAppCulture.Models.Animal"
  • and for all model properties :
    • @Html.DisplayNameFor(model => model.property)    when executed, the information is reliated to the culture
    • @Html.DisplayFor(model => model.property)

In the third step we create two areas "Canin" and "Felin". For each of them we add a controller named "AnimalController.cs" who inherits from BaseAnimalController, so :

  • in the two controllers we add
    • C#
      using WebAppCulture.Controllers;         //for the base controller
    • C#
      using WebAppCulture.Attributes;         //for the custom ActionFilterAttribute
    • C#
      using WebAppCulture.Models;             //for the Animal model class
  • for the controller attribute we use the rigth culture (depends on the area) :
C#
[LocalisationAttribute("fr-FR-Canin")]
public class AnimalController : BaseAnimalController

 

C#
[LocalisationAttribute("fr-FR-Felin")]
public class AnimalController : BaseAnimalController
  • and then the action for each :

 

C#
// GET: Felin/Animal
public ActionResult Animal()
{
    Animal animal = new Animal() {
        Nom = "MiaouMiaou",
        FaitDuBruit = false,
        Infecter = true,
        MetsFavoris = true };
    return base.Index(animal);
}
C#
// GET: Canin/Animal
public ActionResult Animal()
{
    Animal animal = new Animal() {
        Nom = "WouafWouaf",
        FaitDuBruit = true,
        Infecter = false,
        MetsFavoris = false };
    return base.Index(animal);
}

 

  2.5 - Home page

In order to test all this is an example of content for the view "Views\Home\Index.cshtml"

HTML
<div class="row">
    <div class="col-md-4">
        <h2>CANIN</h2>
        <p><a href="@Url.Action("Animal", "Animal", new { Area = "Canin" })"
              class="btn btn-primary">Test canin</a></p>
    </div>
    <div class="col-md-4">
        <h2>FELIN</h2>
        <p><a href="@Url.Action("Animal", "Animal", new { Area = "Felin" })"
              class="btn btn-primary">Test félin</a></p>
    </div>
    <div class="col-md-4">
        <h2>AUTRE</h2>
        <p><a href="@Url.Action("Index", "BaseAnimal")"
              class="btn btn-primary">Test autre</a></p>
    </div>
</div>

Here we go ! You can test it to see the custom culture in action.

Conclusion

The explanation is simple enough for the creation of custom culture. Regarding its use, that is how I put it into practice. But this is not the only way !!! Besides, I await your remarks and in what circumstances did you use custom cultures.

 

History

 

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
France France
Software developer since 2000, I started with Delphi 5 and now I'm working with Visual Studio in particular with ASP.Net platform (WebForm/MVC).

Comments and Discussions

 
-- There are no messages in this forum --