Thursday, July 07, 2011

How to set browser language as a default language for .NET Silverlight application

How to set browser language as a default language for .NET Silverlight application
Here the requirement is that, the application should change its culture based on the Browser language setting. Let say if user changed his language in IE browser then application should reflect with same culture.  Ex: US English (default) to French (standard)
In short, the application should display the content based on client browser settings.
Steps-1: Read Browser Language from code
You have to write inline code into Default.aspx page (Page_Init())
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Threading" %>
C# code
<script runat="server">
void Page_Init(object sender, EventArgs e)
  ViewStateUserKey = Session.SessionID;
  if (HttpContext.Current.Request.UserLanguages != null)
    CultureInfo culture = new CultureInfo(HttpContext.Current.Request.UserLanguages[0]);
    Thread.CurrentThread.CurrentCulture = culture;
    Thread.CurrentThread.CurrentUICulture = culture;

Steps-2: Go to the Main Page and set language
Set application language with current culture on the page Constructor after InitializeComponent() method
this.Language = System.Windows.Markup.XmlLanguage.GetLanguage(System.Threading.Thread.CurrentThread.CurrentCulture.Name);

Steps-3: Create Resource files for different languages
Resource file name should create with following manner
<ResounceFileName>.<Language ISO Code>.resx
French (Canada)   file name should be ""
Dutch file name should be ""
Run the application and now application will behave based on the language set into the browser.
This code has been tested with IE 9.0 32 bit browser and Silverlight 4.0 with .NET framework 4.0.
Note: following solution you can try with asp.NET application, steps 1 and 3 will be same

No comments: