CodeVerge.Net Beta


   Explore    Item Entry   Register  Login  
Microsoft News
Asp.Net Forums
IBM Software
Borland Forums
Adobe Forums
Novell Forums




Can Reply:  No Members Can Edit: No Online: Yes
Zone: > NEWSGROUP > Asp.Net Forum > general_asp.net.faq_frequently_asked_questions Tags:
Item Type: NewsGroup Date Entered: 3/8/2006 4:49:55 AM Date Modified: Subscribers: 0 Subscribe Alert
Rate It:
NR
XPoints: N/A Replies: 34 Views: 102 Favorited: 0 Favorite
35 Items, 2 Pages 1 2 |< << Go >> >|
rmprimo
Asp.Net User
How to do a language switch in a master page.3/8/2006 4:49:55 AM

0

As the rap song goes: ?There?s no champagne in the champagne room...?, there is no page in MasterPage. It derives from UserControl. As such it does not support the InitializeCulture() method for us to override as described in this post. Newbies love master pages, even though half the time they do not understand them, so here is a solution, compounding the misuse, but here it goes.

Declare a dropdown as usual in the master page. Instead of overriding the InitializeCulture() place the same code in the Application_BeginRequest event handler in the global.asax. It is very similar to InitializeCulture() in the sense that it occurs early and no controls are ready yet. We have a little problem though, now the control is declared in a template and its name and id attributes rendered differently. We can't use the control id and cheat like in the other post any more. We cant use the Control.UniqueID property either, remember no controls yet. So now what?

Another collection like the form variables collection that is also not originally server collection is the cookies collection. I use the cookie but it can be any of the ways for cross page communication that do not depend on server controls, like profile, session, querystring etc. We cannot use a cookie to carry the culture name value which comes from the dropdown selected item value, because the culture would always be a step behind. It would be set early on but later the dropdown selection change it but the resources for the previous culture come up. So normally only the page containing the dropdown would be a step behind, but because the dropdown is in the master page it appears that the whole site is ALWAYS ONE STEP BEHIND.

If, however, in the cookie, we pass the control name (which is information that never changes, so we can never be behind), instead of the culture name( which we can never keep up with), and then use that key to get the form variable value, we have pieced ourselves a workaround.

in the master page:

<asp:DropDownList runat="server" ID="DropDownList1" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
      
<asp:ListItem Value="en" Text="English"
/>
      <asp:ListItem Value="fr" Text="French"
/>
      
<asp:ListItem Value="de" Text="German"
/>
</asp:DropDownList>

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){
   HttpCookie cookie = new HttpCookie("DropDownName");
   cookie.Value=DropDownList1.UniqueID;
   Response.SetCookie(cookie);
}

in global asax

void Application_BeginRequest(Object sender, EventArgs e){
      string lang = string.Empty;
//default to the invariant culture
      HttpCookie cookie = Request.Cookies["DropDownName"];

      if (cookie != null && cookie.Value != null)
         lang = Request.Form[cookie.Value];

      Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
}

Notice, there is absolutely no code in any of the content pages. Thats it ten lines of code and we are done for the whole site.
This is not complete code, just a tip and trick of using master page and the .net event model to globalize code.

The new issue now is what about pages that do not have a master page? Not all pages are strapped in a template like that. This approach can be modified to support both. That is for next post.

Enjoy


Regards,

Rob
Veni, vidi, v2.0
aspnet20beginne
Asp.Net User
Re: How to do a language switch in a master page.3/16/2006 12:08:15 PM

0

rmprimo,

Well I am working on web portal, which has a master page and content pages.
In master page, I am selecting language like fr, de, es and ar i.e. arabic.

I did exactly what you mentioned in your sample code, however I could see any changes in the screen.

Text, from English to French or German didnt change. Currencies, Date format, numeric values as per the culture and uiculture changed.

Would it possible for you to explain bit more in details, why same thing may not be working in my situation?

Hritesh.

ludo018
Asp.Net User
Re: How to do a language switch in a master page.4/11/2006 3:38:03 PM

0

The same for me
i'll try this code and didn't seems to works.
 
i'll try some response.write to understand.
 
System.Threading.Thread.CurrentThread.CurrentCulture.ToString()=fr-FR
and after affectation the Culture
System.Threading.Thread.CurrentThread.CurrentCulture.ToString()=en-US
 
so the lang have switch but my ressources is not use in the good language.
 
I've try the change my navigator language and all works good.
 
I think the Application_BeginRequest append to late?
 
If anyone could help please.
ludo018
Asp.Net User
Re: How to do a language switch in a master page.4/12/2006 4:00:21 PM

0

I have some help from rmprimo now it's working very good.
Even better than the tutorials in asp.net website (the tutorials the save the language must be submitted 2 times for the change to be applied)
 
I used query string for language switching :
    string sLang = string.Empty;
    HttpCookie oCookie = Request.Cookies["LANGUAGE"];

    if (Request.QueryString["lang"] != null)
    {
      sLang = Request.QueryString["lang"];
      HttpCookie oCookieSet = new HttpCookie("LANGUAGE");
      oCookieSet.Value = Request.QueryString["lang"];
      Response.SetCookie(oCookieSet);
    }
    else if (oCookie != null && oCookie.Value != null)
      sLang = oCookie.Value;

    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(sLang);
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(sLang);
 
and all work fine
thnaks for your help
marmot74
Asp.Net User
Re: How to do a language switch in a master page.4/19/2006 9:40:47 PM

0

Is there a way to make this work WITHOUT using QueryString?
joschua
Asp.Net User
Re: How to do a language switch in a master page.5/5/2006 8:58:08 AM

0

You can use a virtual directory in the iis and point it to an common folder for all langauge depend pages.

e.g
/en/yourPage.aspx
/es/yourPage.aspx

the directory structur could be :

\bin
\common\yourPage.aspx
\controls\.....

to switch the language read the current page, create some links to the current page and prepend the
different langauge codes to the links.

- for a first-time visitor, read whose language from the request
- to redirect a visitor to the last visited language, use a coockie
- if a user type an unavailable languagecode in the url, implement a mehtod to
define a default system language.
- then set the language to the current thread

protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        String language = Request.UserLanguages[0];
        if (language.Length > 1) language = language.Substring(0, 2);

        HttpCookie cookie = Request.Cookies["ReBuy"];
        if (cookie != null && cookie["language"] != null)
        {
            language = (String)cookie["language"];
        }
       
        String appName = Request.ApplicationPath.Length > 1 ? Request.ApplicationPath : "";
        String path = this.Request.FilePath.Substring(appName.Length);

        String[] splitPath = path.Split('/');

        if (splitPath.Length > 1)
        {
            if (splitPath[0].Length == 2)
            {
                language = splitPath[0];
            }
            else if (splitPath[1].Length == 2)
            {
                language = splitPath[1];
            }
        }
        language = Bll.Language.Language.GetSystemLanguage(language);

        if (cookie == null)
        {
            cookie = new HttpCookie("myappname");
        }
        if (cookie["language"] == null || cookie["language"].ToString() != language)
        {
            cookie["language"] = language;
            cookie.Expires = DateTime.Now.AddYears(1);
            Response.Cookies.Add(cookie);
        }

        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language);
        Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);
    }

I hope it helps you.




Ran Davidovitz
Asp.Net User
Re: How to do a language switch in a master page.5/5/2006 2:52:50 PM

0

Hi,

I would not recommend overriding the global.asax begin_Request event because this is not a encapsulated solution
My advise is to create a base page that will have the logic of language switching (by using the previous solution that joschua wrote) or if you don't like base pages you can use the aggregation solution by creating an utility (static) class.

So changing the language will only require you to call a method on the base page that will handle everything (saving the language needed to the session / cookie, validating, etc).

The final solution will be clean and reusable

Hope this helps (If you need a sample code tell me - although its relatively simple)
Ran Davidovitz http://davidovitz.blogspot.com

 


-Davidovitz
http://davidovitz.blogspot.com
Husain
Asp.Net User
Re: How to do a language switch in a master page.5/6/2006 9:58:56 AM

0

Sample code would help a lot, Ran. Thanks in advance.
sebastian.piu
Asp.Net User
Re: How to do a language switch in a master page.5/31/2006 1:15:57 AM

0

 Check this basepage i've made, hope it helps .. ctl00$ddlLanguage is a dropdown that the user uses to switch cultures (this can be tweaked a bit).

It should work with pages that use or don't a master page.

If a culture change is detected OnCultureChange event is raised

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Threading;

public delegate void CultureChanged(object Sender, string CurrentCulture);
public class Base: Page
{
    public event CultureChanged OnCultureChanged;
    public string LastCultureName
    {
        get
        {
            string lastCultureName = (string)Session["_lastCulture"];

            if (lastCultureName == null)
                Session["_lastCulture"] = Thread.CurrentThread.CurrentCulture.Name;

            return lastCultureName;
        }
        set
        {
            Session["_lastCulture"] = value;
        }
    }

    protected override void InitializeCulture()
    {
        //TODO: make this prettier
        string lang = Request["ctl00$ddlLanguage"];

        if (lang == null || lang == String.Empty)
            lang = LastCultureName;

       Thread.CurrentThread.CurrentCulture = new CultureInfo(lang);
       Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
    }

    protected override void OnLoadComplete(EventArgs e)
    {
        base.OnLoadComplete(e);

        if (LastCultureName != Thread.CurrentThread.CurrentCulture.Name)
        {
            LastCultureName = Thread.CurrentThread.CurrentCulture.Name;

            if ( this.OnCultureChanged != null)
                this.OnCultureChanged(this, LastCultureName);
        }
    }
}
 Thanks
quasa
Asp.Net User
Re: How to do a language switch in a master page.6/28/2006 8:43:28 AM

0

LastCultureName prop needs following small change, othewise first time "null" gets returned, which throws an exception at the CurrentCulture setting.:

    public string LastCultureName
    {
        get
        {
            string lastCultureName = (string)Session["_lastCulture"];

            if (lastCultureName == null){
                Session["_lastCulture"] = Thread.CurrentThread.CurrentCulture.Name;
                lastCultureName = Thread.CurrentThread.CurrentCulture.Name;
            }

            return lastCultureName;
        }
        set
        {
            Session["_lastCulture"] = value;
        }
    }

 

saratjandhyala
Asp.Net User
Re: How to do a language switch in a master page.> could you check it once> why it doesn't work7/3/2006 10:10:12 AM

0

<

asp:content id="ContentLogin" contentplaceholderid="Main_Content" runat="server">

<div>

<asp:Label ID="Label1" runat="server" Text="Select Culture" meta:resourcekey="Selectculture"></asp:Label>

<asp:DropDownList ID="Language1" AutoPostBack="true" OnSelectedIndexChanged="Language1_SelectedIndexChanged" runat="server">

<asp:ListItem value="auto">Auto</asp:ListItem>

<asp:ListItem Value="en-US">English</asp:ListItem>

<asp:ListItem Value="zh-sg">Chinese</asp:ListItem>

<asp:ListItem Value="ru">Russain</asp:ListItem>

</asp:DropDownList>

<asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>

</div>

</

asp:Content

 

in global.asax

Sub

Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)

Dim lang As String = String.Empty

Dim cookie As HttpCookie = Request.Cookies("lang")

If Not (cookie Is Nothing) AndAlso Not (cookie.Value Is Nothing) Then

lang = Request.Form(cookie.Value)

End If

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang)

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang)

End Sub

in .vb

Imports

System.Globalization

Imports

System.Threading

Public

Class _Default

Inherits System.Web.UI.Page

Protected Overrides Sub InitializeCulture()

Dim lang As String = Request("Language1")

If Not lang = "auto" Then

If lang IsNot Nothing Or lang <> "" Then

Thread.CurrentThread.CurrentUICulture =

New CultureInfo(lang)

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang)

End If

End If

End Sub

Protected Sub Language1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)

Dim cookie As HttpCookie = New HttpCookie("lang")

cookie.Value = Language1.UniqueID

Response.SetCookie(cookie)

End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Language1.SelectedItem.Value = "auto" Then

Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentCulture

End If

End Sub

End

Class

 


Sarat JR
Guya
Asp.Net User
Re: How to do a language switch in a master page.7/10/2006 2:45:19 PM

0

Hi

What happen if cookie is not enabled on the client browser? any other solutions?

EngMotagaly
Asp.Net User
Re: How to do a language switch in a master page.7/12/2006 7:46:11 AM

0

Dear ppl,

I figured out a solution for the problem in the thread, its a combination of all posts including this one http://forums.asp.net/1219973/ShowPost.aspx :)

 

it?s not that clean but I think it?s better than nothing and I like to share the idea with you as you are more experienced, I?m going to tell you the situation how I solved that.

Scenario:
1-Build a multilingual website using ASP.NET 2.0 for my company
2-MaterPage with a change language combo that is localized at the first request of the page [suing asp.net 2.0 new browser request culture detection] and then the user can change the language any time from the master page. [So the new culture reflects all the website pages]

3-It?s supposed that there are 3 languages, English, French and Arabic [Arabic needs the pages to rendered in RTL L I did it but there is some issues]

 

I didn?t put any code in the global.asax - Application_BeginRequest, I figured out a way for doing that, thanks for the great hint of Ran Davidovitz is not online. Last active: 21-05-2006, 12:51 PMRan Davidovitz  to use the helper class which actually is a class that inherits from a webpage to add the InitializeCulture() , and then make all site pages inhereit from this baseclass.

 

What I did:

1-web.config

    <globalization  enableClientBasedCulture="true" culture="en-US" uiCulture="en-US"  requestEncoding="utf-8" responseEncoding="utf-8"  />

 

2-MasterPage:

Design:

a. Add the global resource files under the App_GlobalResources folder:

AllSite.ar.resx

AllSite.resx

 

AllSite.ar.resx:

  <data name="TextDirection" xml:space="preserve">

    <value>RTL</value>

  </data>

 

AllSite.resx:

  <data name="TextDirection" xml:space="preserve">

    <value>LTR</value>

  </data>

 

b. HTML direction attribute to be retrieved from a global resource to adjust page direction [in case of English, French it will be LTR and Arabic will be RTL

<html runat="server" xmlns="http://www.w3.org/1999/xhtml" dir='<%$ Resources:AllSite, TextDirection %>'>

 

c. localized label and combo for language selection

<td align="left">

<asp:Label ID="lblSelLang" runat="server" meta:resourcekey="lblSelLangResource1"

Text="Select your language:"></asp:Label>

</td>

</tr>

<tr>

<td align="left">

<asp:DropDownList ID="comboSelLanguage" runat="server" AutoPostBack="True" meta:resourcekey="comboSelLanguageResource1"

OnSelectedIndexChanged="comboSelLanguage_SelectedIndexChanged">

<asp:ListItem meta:resourceKey="ListItemResource1">Choose ....</asp:ListItem>

<asp:ListItem meta:resourceKey="ListItemResource2" Text="English" Value="en"></asp:ListItem>

<asp:ListItem meta:resourceKey="ListItemResource3" Text="Francais" Value="fr"></asp:ListItem>

<asp:ListItem meta:resourceKey="ListItemResource4" Text="???????" Value="ar"></asp:ListItem>

</asp:DropDownList></td>

</tr>

Code: to handle the language (culture selection) and then return the referrer page

protected void comboSelLanguage_SelectedIndexChanged(object sender, EventArgs e)

{

        HttpCookie cookie = new HttpCookie("SelLang");

        cookie.Value = comboSelLanguage.SelectedValue;

        Response.SetCookie(cookie);

        Response.Redirect(Request.UrlReferrer.AbsoluteUri); // this is for the redirecting to the referrer page

}

 

3-Build a BaseClass under the App_Code\BL forlder in your project ,that all pages will inherit from.

Code:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Threading;

using System.Globalization;

 

/// <summary>

/// Summary description for BasePage

/// </summary>

public class BasePage :Page

{

   public BasePage()

   {

        //

        // TODO: Add constructor logic here

        //

    }

    protected override void InitializeCulture()

    {

        string lang = string.Empty;//default to the invariant culture

        HttpCookie cookie = Request.Cookies["SelLang"];

 

        if (cookie != null && cookie.Value != null)

        {

            lang = cookie.Value;

            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);

            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);

        }

        base.InitializeCulture();

    }

}

 

4-Build the web pages [the will be in the content place holder in the master page] and generate local resources, and DON?T FORGET INHERIT FROM THE BASEPAGE CLASS ;), and add your local resources for them.

 

My Issues is that some controls doesn?t render to RTL well , I don?t know why and what?s going to drive me nuts is the same control (ex: asp:Label) renders sometimes right and sometimes wrong .. I think there is a web design consideration that should be taken or layout considerations to support both RTL and LTR languages; I hope any one can help me in this area

 

Hope this helps

gotchi
Asp.Net User
Re: How to do a language switch in a master page.7/18/2006 8:20:26 AM

0

hi

first I want to say that I prefer the global.asax solution - it's much easier for locaolize an homepage which already exists. also microsoft means that editing the global.asax is a goot way to make changes for a whole website.

but it doesn't matter, my problem is a little bit different

set the uiculture and co to auto and starting my browser with different language settings let everything work fine, especially the Convert.ToDateTime(Textbox1.Text); works fine.

But if I do a language switch with a drop down box like mentioned in the post - I get an exception when my code tries to convert the same textbox with the localized date.

so whats the main problem hier - letting the browser set the language everything looks the same on the frontend then setting the language by hand. only problem is - when I set the language by hand the convert.todatetime throws an exception.

caos
Asp.Net User
Re: How to do a language switch in a master page.7/31/2006 9:55:56 AM

0

Hello, could you explain this step in detail please.

 

4-Build the web pages [the will be in the content place holder in the master page] and generate local resources, and DON?T FORGET INHERIT FROM THE BASEPAGE CLASS ;), and add your local resources for them.

 

Thank you!

EngMotagaly
Asp.Net User
Re: How to do a language switch in a master page.7/31/2006 10:24:16 AM

0

well i've mentioned before that you should create a helper class, that all your webpages will inherit from to execute the code in the InitializeCulture() in all tour pages without having to override this mehtod in every webpage code

"3-Build a BaseClass under the App_Code\ forlder in your project ,that all pages will inherit from :

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Threading;

using System.Globalization;

 

/// <summary>

/// Summary description for BasePage

/// </summary>

public class BasePage :Page

{

   public BasePage()

   {

        //

        // TODO: Add constructor logic here

        //

    }

    protected override void InitializeCulture()

    {

        string lang = string.Empty;//default to the invariant culture

        HttpCookie cookie = Request.Cookies["SelLang"];

 

        if (cookie != null && cookie.Value != null)

        {

            lang = cookie.Value;

            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);

            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);

        }

        base.InitializeCulture();

    }

}"

the bold text was just a hint not to forget :) to do that for very web page:

public

partial class [PageClassName] : BasePage

 

 

charo
Asp.Net User
Re: How to do a language switch in a master page.12/1/2006 11:12:27 AM

0

Thak you for this forum, it has helped mi so much!!!Big Smile I've used EngMotagaly is not online. Last active: 08-10-2006, 9:16 AM EngMotagaly 's solution and it works fine, but i will need to introduce some changes, because my applicattion will execute in two servers and because of that i won't be able to use cookies.

Mi code in the Master Page is:

ViewState["Idiom"]= lang; 

 

Mi code in the class BasePage is like this:

string lang= (string)ViewState["Idiom"];

 

And then the code is the same as EngMotagaly, but it doesn't work and i don't know if i need to enable viewState somewhere (i'm beginning whit asp.net). Any ideas?

Than you so much and sorry for my english (i'm spanish)

a4nsd
Asp.Net User
Re: How to do a language switch in a master page.12/14/2006 6:02:12 PM

0

Hello rmprimo,

I use your code to apply my page. But there is an error

"Value cannot be null.
Parameter name: name"

Error occurs at line

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);

I don't know why. Can you show me how...Thanks very much


Mark as Answer if it helps you. Thanks
StarSoft JSC Company
a4nsd
Asp.Net User
Re: How to do a language switch in a master page.12/14/2006 6:20:23 PM

0

Thanks all. This forum is fantastic
Mark as Answer if it helps you. Thanks
StarSoft JSC Company
charo
Asp.Net User
Re: How to do a language switch in a master page.12/20/2006 11:52:16 AM

0

Hello, it?s me again, i've finnaly coded it using session and it works all right, there?s only a handicap and it?s that i need to double-click on the select culture button, any ideas? thanks very much
35 Items, 2 Pages 1 2 |< << Go >> >|


Free Download:




   
  Privacy | Contact Us
All Times Are GMT