Master Thread Repair
![]() |
No items matching your keywords were found.
ASP.Internet MVC Hosting Design ASP.World Wide Web MVC Localization Along With Language Discovery
Intro
While in this tutorial we are going to show a simple method to create localization (globalization) for web application using APS.NET MVC framework. It should work fine with MVC 1 and a pair of and we're currently using .NET 3.5 SP1, but .NET 4.0 would work in addition. All code carries in C# and for language translations we use XML files.
Language files with XML
For translations of various languages we utilize simple xml files. We store them in App_Data/messages/.xml, one example is en-US.xml or de-DE.xml. Here is the xml structure:
Home
Products
Services
You should have identical language files for many desired languages. All translation items needs to be the same (with equal "key" attributes).
Create Translator elegance
Main translation work shall be created by Translator singleton class. Create "Infrastructure" folder as part of your MVC project and put class Translator there.
First, let's make class singleton:
private static Translator instance = null;
public static Translator Occasion
have
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 Milieu
obtain
if (string.IsNullOrEmpty(locale))
throw new Exception("Locale not set");
also
return locale;
group
if (Cultures.Contains(value))
locale = value;
load();
in addition
throw new Exception("Invalid locale");
public static string[] Traditions
get
return cultures;
Field "cultures" lists available cultures. "Locale" keeps current culture. And in "set" component of Locale property notice invocation of load() method. We will talk about it later.
To store localization data I'll create simple dictionary then use keys from XML for dictionary keys and XML item values as dictionary values. Simple Translate method does translation job. We now have Nuclear Link Indexer Review way of easy access.
private Dictionary data = null;
public string Translate(string key)
if (data != null data.ContainsKey(key))
return data[key];
in addition
return ":" key ":";
public string this[string key]
obtain
return Translate(key);
If some key must not be found and translated, we return the main element with ":" around it, to help you to easy find untranslated items.
Finally, for loading XML we use LINQ to XML. we have now static caching dictionary, therefore i do not particularly 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 could use translator in your controller just:
Translator.Instance[key];
After load() methid we have ClearCache solution to easy developing (you will know, once read, data is cached you have indeed to restart IIS Application Pool to refresh localization data).
Translator class is prepared, we are going to 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 are going to use this in html views for translation just
If you want params in translated values you should use second T implementation like string.Format. First helper CurrentCulture is applied in language select user control to work out current culture.
Create BaseController elegance
Create BaseController class that extends Controller and set it in "Infrastructure" folder of your MVC project. It is best to extend your controller classes out of this class. Create simple property for current selected culture (locale)
public string CurrentCulture
have
return Translator.Instance.Locale;
You will use that in your controller when you initialize your model, for instance.
In the following code I shall 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 generally there is any (if such will not be only time visit). There is not any cookie it is possible to detect browser language, make GeoIP IP address lookup et cetera. After finding some valid locale/culture we set response cookie for next page visits. After this we change current thread culture. This can be useful if you would like format some date or currency values.
It is best to call initCulture in overridden Initialize method.
Changes in HomeController
Don't forget so as to modify parent class of your complete controller to BaseController. Add following code to your HomeController, to help you to 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. Can get on 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 alter current language we will create special user control which can be included in may Master.Site layout. Create CultureUserControl.ascx and put it in Views/Shared/ folder of this MVC project. Extremely effective code:
en
bg
Within our layout we utilise to include it.
Conclusion
While in this simple tutorial we've created localization infrastructure for ASP.NET MVC web application. Translations of different languages are saved in XML files. All of us use Translator class to load them. Current user culture is kept in cookie. You could access Translator class in html views aplying some helpers. Also each of the translation data we cached hence it may not be loaded form XML every request.
Hope this tutorial helps.
What exactly is so thrilling on ASPHostDirectory.com ASP.NET MVC Hosting?
We understand that locating a cheap, reliable web host will never be easy job so we've put all of the information you need available as one spot for a take you step by step to make your decision. At ASPHostDirectory, we pride inside ourselves our resolve for customers and want to make certain they ve all of the details they need before making that big decision.
We can work tirelessly to provide a refreshing and friendly level of players care. We perceive in creativity, innovation, plus a competitive spirit in many that many of us do. We're sound, honest company who feels that business is a bit more than just the underside line. We consider every business opportunity an opportunity engage and interact with these customers and our community. Neither our clients nor our employees absolutely are a commodity. They are portion of our family.
The followings will be the top 10 reasons you need to trust your online business and hosting needs to us:
- FREE domain your entire life - ASPHostDirectory delivers your own free domain name forever with this Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There's no should panic about renewing your domain as ASPHostDirectory will automatically do this for you to make certain you never lose the all important identity within your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it's customers 99.9% network uptime! We are most certainly so concerned about uptime which we set up our own company to manage people's uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never sleep off when we manage a service that is opening 24/7 12 months. Even everybody is on holiday during Easter or Christmast/New Year, we're always behind our desk serving consumers
- Customer Tailored Support - should you compare our hosting tactics to others ensure that we are most certainly offering a significantly better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, user interface features, e-mail services, real-time stats, and service
- A refund Guarantee - ASPHostDirectory offers a no questions asked' cost refund guarantee with all our plans for any cancellations made in first one month of sequencing. Our cancellation policy is very simple - should you cancel your account within at least a month of first registering we will provide you with complete refund
- Experts in ASP.NET MVC Hosting - Together with the scale of our surroundings, we have now recruited and developed some of the best talent within the hosting technology that you are using. Our team is strong because of the experience and abilities of the people who make up ASPHostDirectory
- Daily Backup Service - We realise that your websites are crucial in your business and hence, we never ever forget to create a daily backup. Your database and website are backup regularly inside permanent remote tape drive with the intention that these are always secure. The backup is without doubt ready and available anytime you want it
- Easy Site Administration - With these powerful cp, you will certainly administer the majority of your web page features easily without even wanting to contact for our particular Support Team. Additionally, you may also install above 100 FREE applications directly via our Control Panel in a single minute!
Happy Hosting!
How to Repair Motorcycle Brakes : How to Install a Motorcycle Master Cylinder
You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.