Thursday, 3 January 2013

ASP.NET MVC Hosting :: Create ASP.NET MVC Localization with Language Detection

Introduction

In this tutorial we will show a easy way to create localization (globalization) for web application making use of APS.NET MVC framework. It must function fine with MVC 1 and 2 and we’re currently employing .NET three.5 SP1, but .NET 4. will perform as properly. All code is in C# and for language translations we use XML files.

Language files with XML

For translations of different languages we use straightforward xml files. We store them in App_Information/messages/.xml, for example en-US.xml or de-DE.xml. Right here is the xml structure:

  Home
  Merchandise
  Solutions

You ought to have identical language files for all desired languages. All translation items need to be the identical (with equal “crucial” attributes).

Develop Translator class

Primary translation operate will be done by Translator singleton class. Create “Infrastructure” folder in your MVC project and put class Translator there.
First, let’s make class singleton:

personal static Translator instance = null
public static Translator Instance

get

  if (instance == null)
 
instance = new Translator()
 
  return instance

personal Translator()

Add the following fields and properties to the class:

personal static string[] cultures = “en-US”, “bg-BG”
personal string locale = string.Empty

public string Locale

get

  if (string.IsNullOrEmpty(locale))
 
throw new Exception(“Locale not set”)
 
  else
 
return locale
 

set

  if (Cultures.Consists of(value))
 
locale = value
load()
 
  else
 
   throw new Exception(“Invalid locale”)
 

public static string[] Cultures

get

  return cultures

Field “cultures” lists offered cultures.

“Locale” keeps current culture. And in “set” portion of Locale house you can see invocation of load() strategy. We will speak about it later.
To keep localization information I will create easy dictionary and then use keys from XML for dictionary keys and XML item values as dictionary values. Easy Translate strategy will do translation job. We have indexer method for simple access.

private Dictionary information = null

public string Translate(string key)

if (data != null &amp&amp information.ContainsKey(important))

  return information[crucial]

else

  return “:” + key + “:”

public string this[string key]

get

  return Translate(important)

If some essential can’t be discovered and translated, we return the key with “:” about it, so you can easy discover untranslated things.
Lastly, for loading XML we use LINQ to XML. we have static caching dictionary, so I never want reading XML on each and every request.

private static Dictionary&gt cache =
  new Dictionary&gt()

private void load()

if (cache.ContainsKey(locale) == false) // CACHE MISS !

  var doc = XDocument.Load(
HttpContext.Recent.Server.MapPath(
“~/App_Data/messages/” + locale + “.xml”))

  cache[locale] = (from item in doc.Descendants(“item”)
exactly where item.Attribute(“important”) != null
pick new

  Essential = item.Attribute(“key”).Worth,
 Data = item.Value,
).ToDictionary(i =&gt i.Key, i =&gt i.Data)

data = cache[locale]

public static void ClearCache()

cache = new Dictionary&gt()

You can use translator in your controller like this:
Translator.Instance[crucial]
Right after load() methid we have ClearCache strategy for easy creating (you know, when read, data is cached and you have to restart IIS Application Pool to refresh localization data).
Translator class is ready, we will show you how to use it later.

Produce localization helpers

Develop static class LocalizationHelpers and place it in “Helpers” folder in your project.

public static string CurrentCulture(this HtmlHelper html)

return Translator.Instance.Locale

public static string T(this HtmlHelper html, string key)

return html.Encode(Translator.Instance[crucial])

public static string T(this HtmlHelper html, string crucial,
params object[] args)

return html.Encode(string.Format(
  Translator.Instance[crucial], args))

We will use this in html views for translation like this

If you want params in translated values you can use second T implementation like string.Format. Very first helper CurrentCulture is employed in language choose user manage to establish recent culture.

Develop BaseController class

Create BaseController class that extends Controller and place it in “Infrastructure” folder of your MVC project. You must extend all your controller classes from this class. Develop simple home for present chosen culture (locale)

public string CurrentCulture

get

  return Translator.Instance.Locale

You will use this in your controller when you initialize your model, for instance.
In the following code I will clarify language detection and saving with cookie.

private void initCulture(RequestContext requestContext)

string cultureCode = getCulture(requestContext.HttpContext)

requestContext.HttpContext.Response.Cookies.Add(
  new HttpCookie(“Culture”, cultureCode)
 
Expires = DateTime.Now.AddYears(1),
HttpOnly = accurate,
 
)

Translator.Instance.Locale = cultureCode

CultureInfo culture = new CultureInfo(cultureCode)
Program.Threading.Thread.CurrentThread.CurrentCulture = culture
System.Threading.Thread.CurrentThread.CurrentUICulture = culture

personal string getCulture(HttpContextBase context)

string code = getCookieCulture(context)

if (string.IsNullOrEmpty(code))

  code = getCountryCulture(context)
 

return code

personal string getCookieCulture(HttpContextBase context)
string.IsNullOrEmpty(cookie.Worth)

private string getCountryCulture(HttpContextBase context)

// some GeoIp magic right here
return “en-US”

First we try to get language cookie if there is any (if this is not very first time go to). If there is no cookie you can detect browser language, make GeoIP IP address lookup and so on. After finding some valid locale/culture we set response cookie for next page visits. Immediately after this we change present thread culture. This is beneficial if you want to format some date or currency values.
You ought to contact initCulture in overridden Initialize technique.

Changes in HomeController

Do not forget to modify parent class of all your controller to BaseController. Add following code to your HomeController, so you can modify current culture. When you open specified URL, a cookie is set and user is redirected to index page. This URL is like instance.com/house/culture/en-US. Clear cache technique is for deleting present cache with out restarting application pool. Access it with instance.com/house/ClearLanguageCache

public ActionResult Culture(string id)

HttpCookie cookie = Request.Cookies["Culture"]
cookie.Value = id
cookie.Expires = DateTime.Now.AddYears(1)
Response.SetCookie(cookie)

return Redirect(“/”)

public ActionResult ClearLanguageCache(string id)

Translator.ClearCache()

return Redirect(“/”)

To alter existing language we will create unique user handle which will be included in could Master.Web site layout. Generate CultureUserControl.ascx and put it in Views/Shared/ folder of your MVC project. Right here is the code:

en

bg

In our layout we use to contain it.

Conclusion

In this simple tutorial we’ve made localization infrastructure for ASP.NET MVC internet application. Translations of distinct languages are stored in XML files. Then we use Translator class to load them. Current user culture is kept in cookie. You can access Translator class in html views making use of some helpers. Also all the translation data we cached so it will not be loaded type XML every request.
Hope this tutorial helps.

What is so Specific on ASPHostDirectory.com ASP.NET MVC Hosting?

We know that discovering a inexpensive, trustworthy net host is not a simple process so we’ve place all the data you require in 1 place to aid you make your choice. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make certain they have all the specifics they need to have ahead of making that massive choice.

We will perform tirelessly to give a refreshing and friendly level of buyer service. We feel in creativity, innovation, and a competitive spirit in all that we do. We are sound, sincere organization who feels that company is far more than just the bottom line. We think about every single company chance a possibility to engage and interact with our clients and our community. Neither our customers nor our workers are a commodity. They are part of our family members.

The followings are the top ten reasons you must trust your on the web company and hosting needs to us:

- Free of charge domain for Life – ASPHostDirectory offers you your own totally free domain name for life with our Specialist Hosting Strategy and three totally free domains with any of Reseller Hosting Program! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to make certain you by no means drop the all essential identity of your site
- 99,9% Uptime Guarantee – ASPHostDirectory promises it really is buyers 99.9% network uptime! We are so concerned about uptime that we set up our personal company to monitor people’s uptime for them referred to as ASPHostDirectory Uptime
- 24/7-based Assistance – We never ever fall asleep and we run a service that is opening 24/7 a year. Even everybody is on holiday in the course of Easter or Christmast/New Year, we are often behind our desk serving our buyers
- Buyer Tailored Help – if you evaluate our hosting plans to other people you will see that we are supplying a a lot far better deal in each element performance, disk quotas, bandwidth allocation, databases, safety, handle panel characteristics, e-mail solutions, actual-time stats, and service
- Money Back Guarantee – ASPHostDirectory offers a ‘no concerns asked’ income back guarantee with all our plans for any cancellations made inside the first 30 days of ordering. Our cancellation policy is very basic – if you cancel your account within 30 days of very first signing up we will supply you with a complete refund
- Authorities in ASP.NET MVC Hosting – Given the scale of our surroundings, we have recruited and developed some of the best talent in the hosting technology that you are employing. Our team is sturdy simply because of the expertise and talents of the men and women who make up ASPHostDirectory
- Day-to-day Backup Service – We realise that your site is extremely crucial to your company and therefore, we by no means ever neglect to produce a everyday backup. Your database and site are backup each night into a permanent remote tape drive to make sure that they are always protected and safe. The backup is always ready and offered anytime you want it
- Simple Web site Administration – With our potent control panel, you can constantly administer most of your site features effortlessly with no even needing to get in touch with for our Support Team. Furthermore, you can also set up much more than one hundred Free of charge applications directly by way of our Control  Panel in 1 minute!

Happy Hosting!

At ASPHostDirectory.com, our mission is to give a range of modern, reputable and easy-to-use Net solutions to our clients and to help them with unprecedented, personalized support. For far more info, go to http://asphostdirectory.com. You can also find our official website at http://dotnethost.wordpress.com

No comments:

Post a Comment