Showing posts with label Language. Show all posts
Showing posts with label Language. Show all posts

Tuesday, December 12, 2017

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

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

Introduction

In this tutorial we will show a simple way to create localization (globalization) for web application using APS.NET MVC framework. It should work fine with MVC 1 and 2 and we're currently using .NET 3.5 SP1, but .NET 4.0 will work as well. All code is in C# and for language translations we use XML files.

Language files with XML

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


  Home
  Products
  Services


You should have identical language files for all desired languages. All translation items should be the same (with equal "key" attributes).

Create Translator class

Main translation work 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:


private static Translator instance = null;
public static Translator Instance
{
get
{
  if (instance == null)
  {
instance = new Translator();
  }
  return instance;
}
}
private Translator() { }

Add the following fields and properties to the class:


private static string[] cultures = { "en-US", "bg-BG" };
private string locale = string.Empty;


public string Locale
{
get
{
  if (string.IsNullOrEmpty(locale))
  {
throw new Exception("Locale not set");
  }
  else
  {
return locale;
  }
}
set
{
  if (Cultures.Contains(value))
  {
locale = value;
load();
  }
  else
  {
   throw new Exception("Invalid locale");
  }
}
}


public static string[] Cultures
{
get
{
  return cultures;
}
}


Field "cultures" lists available cultures. "Locale" keeps current culture. And in "set" part of Locale property you can see invocation of load() method. We will talk about it later.
To keep localization data I will create simple dictionary and then use keys from XML for dictionary keys and XML item values as dictionary values. Simple Translate method will do translation job. We have indexer method for easy access.


private Dictionary data = null;


public string Translate(string key)
{
if (data != null && data.ContainsKey(key))
{
  return data[key];
}
else
{
  return ":" + key + ":";
}
}


public string this[string key]
{
get
{
  return Translate(key);
}
}

If some key cannot be found and translated, we return the key with ":" around it, so you can easy find untranslated items.
Finally, for loading XML we use LINQ to XML. we have static caching dictionary, so I don't need reading XML on every request.


private static Dictionary> cache =
  new Dictionary>();


private void load()
{
if (cache.ContainsKey(locale) == false) // CACHE MISS !
{
  var doc = XDocument.Load(
HttpContext.Current.Server.MapPath(
"~/App_Data/messages/" + locale + ".xml"));


  cache[locale] = (from item in doc.Descendants("item")
where item.Attribute("key") != null
select new
{
  Key = item.Attribute("key").Value,
 Data = item.Value,
}).ToDictionary(i => i.Key, i => i.Data);
}


data = cache[locale];
}


public static void ClearCache()
{
cache = new Dictionary>();
}

You can use translator in your controller like this:
Translator.Instance[key];
After load() methid we have ClearCache method for easy developing (you know, once 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.

Create localization helpers

Create static class LocalizationHelpers and put 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[key]);
}


public static string T(this HtmlHelper html, string key,
params object[] args)
{
return html.Encode(string.Format(
  Translator.Instance[key], 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. First helper CurrentCulture is used in language select user control to determine current culture.

Create BaseController class

Create BaseController class that extends Controller and put it in "Infrastructure" folder of your MVC project. You should extend all your controller classes from this class. Create simple property for current selected culture (locale)


public string CurrentCulture
{
get
{
  return Translator.Instance.Locale;
}
}

You will use this in your controller when you initialize your model, for example.
In the following code I will explain 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 = true,
  }
);


Translator.Instance.Locale = cultureCode;


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


private string getCulture(HttpContextBase context)
{
string code = getCookieCulture(context);


if (string.IsNullOrEmpty(code))
{
  code = getCountryCulture(context);
 }


return code;
}


private string getCookieCulture(HttpContextBase context)
{
HttpCookie cookie = context.Request.Cookies["Culture"];


if (cookie == null || string.IsNullOrEmpty(cookie.Value) ||
!Translator.Cultures.Contains(cookie.Value))
{
  return string.Empty;
}


return cookie.Value;
}


private string getCountryCulture(HttpContextBase context)
{
// some GeoIp magic here
return "en-US";
}


First we try to get language cookie if there is any (if this is not first time visit). 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. After this we change current thread culture. This is useful if you want to format some date or currency values.
You should call initCulture in overridden Initialize method.

Changes in HomeController

Don't forget to change parent class of all your controller to BaseController. Add following code to your HomeController, so you can change current culture. When you open specified URL, a cookie is set and user is redirected to index page. This URL is like example.com/home/culture/en-US. Clear cache method is for deleting current cache without restarting application pool. Access it with example.com/home/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 change current language we will create special user control which will be included in may Master.Site layout. Create CultureUserControl.ascx and put it in Views/Shared/ folder of your MVC project. Here is the code:




en

bg


In our layout we use to include it.

Conclusion

In this simple tutorial we've created localization infrastructure for ASP.NET MVC web application. Translations of different 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 using some helpers. Also all the translation data we cached so it will not be loaded form XML every request.
Hope this tutorial helps.

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

We know that finding a cheap, reliable web host is not a simple task so we've put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There's no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it's customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people's uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked' money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in ASP.NET MVC Hosting - Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!



At ASPHostDirectory.com, our mission is to provide a range of innovative, reliable and easy-to-use Internet solutions to our customers and to support them with unprecedented, personalized support. For more information, visit http://asphostdirectory.com. You can also find our official blog at http://dotnethost.wordpress.com




Related Sitemap Xml Articles

Friday, September 8, 2017

Origin of XML (Extensible Markup Language)

Origin of XML (Extensible Markup Language)

The letters XML stand for Extensible Markup Language. This is a great language to know and even better to learn for it is not very difficult to learn. Certifications in this language are also available to earn on line in the comfort of home with a computer at the speed of preference. First the basics should be mastered in HTML and then in XML. That is not a problem either as all the details are available with an online editor in both HTML and XML free of charge for practice and preparation for the certification test. There are quiz questions and samples to view and edit for oneself at the great 3W school web site. The 3W school website is maintained for keeping the standard in the World Wide Web consortium level of expertise.


Why was XML developed? The main purpose of XML is to transport data and to store data. To learn XML it is very important to have a good foundation in HTML and JavaScript since those are basic building blocks for XML. Although XML is very similar to HTML it does not have predefined tags. The tags must be defined by the author. This is a language that is has been designed to be self-descriptive. The 3W Consortium recommends this language.


The functions of HTML and XML are their main differences. HTML was designed to display data. XML was designed to store and transport data. The most common use of XML which is as prevalent as HTML on the web is to simplify the storage of data and the sharing of data. For example, with dynamic data in an HTML document it is much easier to store the files in XML in the document than to rewrite it many times in HTML to display it. There are many great uses and advantages to using XML in web pages.


1. XML simplifies hardware and software platform changes; XML facilitates upgrading to new systems without losing data.


2. XML makes data more user accessible; Data can be processed by "reading machines," (PDA's, voice machines, news feeds) and is available to the blind.


3. Many internet languages have been created with XML; XHTML, WSDL, WAP, WML, RSS for news feeds, RDF and OWL for ontology and SMIL, each of these are a type of descriptive language on line.


The structure of XML language in its storage capacity is a tree. The 'root' is the basic start of an XML document and then come the branches and the leaves of the document. The root is the parent of the sum of all other elements in the document. The document tree is formed from a root then branches to child elements.



Find out more about xml schema