I am working a multi-lang site. I want to get and set culture and uiculture with culturename without countryname. If browser is english or lang is English choosen, it will return en not en-US or en-GB. Because I use one localresources file per language and I have to send language code to sql procedure as a parameter.
Thread.CurrentThread.CurrentCulture
Thread.CurrentThread.CurrentCulture.Name
Thread.CurrentThread.CurrentUICulture
All of them returns en-GB,de-DE,de-AT etc... I just want first part and use this ones.
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28VS.71%29.aspx
There are the name in the link but browser does note return it, I just want and use the simple part.
How can I do that?
It is solved (:
edit:
Now, How can I read browser's culture and if I don't have it, how can I set the culture that I have.
eg: I have en,de,ru and the visitor's browser sen me fr, I want it is shown en ?
Have a look at the TwoLetterISOLanguageName-property. It should return the identifier you are looking for. For example:
var cult = new System.Globalization.CultureInfo("en-US").TwoLetterISOLanguageName;
Returns "en" so that you can send it to the stored procedures.
Related
We are building a site that supports several languages. We have created resources to support fr, de, and en-US with en-US as the default. I have added:
<system.web>
<globalization
uiCulture="auto" culture="auto"
requestEncoding="utf-8"
responseEncoding="utf-8"
enableClientBasedCulture="true" />
...
</system.web>
to my web.config file. If I set the language to fr, de, or en-US in IE or Chrome, I get the expected language. If I set the language to ar-EG, I get en-US, also as expected.
If I set my language to fr-FR, but do not include fr in the list of accepted languages, the site returns the fr page, even if I tell the browser that I prefer accept de to generalized fr (as opposed to fr-FR). This appears to be contrary to the RFC's, but is not surprising, because IE defaults to fr-FR in France and de-DE in Germany, and does not work with sites that do not automatically generalize the culture.
However, if I tell the browser that I accept ar-EG and fr, the site defaults to en-US -- even though the Accept-Language header specifies that I will accept fr with a higher priority. I captured the request header in the browser to make sure all the languages I asked for were being sent with the right priorities.
It appears that ASP.NET is only ever looking at the first language specified in the Accept-Language header. Is the ASP.NET language matching algorithm specified anywhere? Is there a way to specify that ASP.NET/MVC should check all the languages in the Accept-Language list to determine the best one? Or do I have to write my own language matching code?
Well, as nobody else answered yet, I make my suggestion. There is a better or at least more beautiful solution for sure, but for my needs it was enough. Just set the culture inside your Application_AcquireRequestState() event:
protected void Application_AcquireRequestState()
{
var language = "whatever"; // default fall back
if (request.UserLanguages.Length > 0)
{
var acceptedLangs = new List<string> {"de", "en"};
var langs = request.UserLanguages.Where(l => acceptedLangs.Any(al => al.Equals(l.Substring(0, 2))));
language = langs.FirstOrDefault();
}
// TODO: may be better inside a try..catch block
var culture = new CultureInfo(language);
Thread.CurrentThread.CurrentUICulture = culture;
Thread.CurrentThread.CurrentCulture = culture;
}
I'm developing a shopping cart, and part of the functionality is to select your currency.
I have a drop down list, and when the selected index changes I've written some code to find the culture code (such as en-GB or en-US) and then change the culture of the current session. In addition, using the exchange rates given it changes the price...
I currently have en-GB as the default culture. When someone selects the en-US culture from the drop down everything works fine. The currency changes (all currency labels are set with ToString("C")) and the exchange rate changes.
When I use the drop down list to select en-GB again, the exchange rate changes (so I know the code is working), and after debugging I can see that the culture session has changed from en-US to en-GB, but the currency still displays as $ and not £.
I really can't understand why this is happening. The code is very simple, I'm overriding the page_Load event for each page to display the correct currency based on culture:
protected override void OnLoad(EventArgs e)
{
if (Session["Culture"] != null)
{
string culture = Session["Culture"].ToString();
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Session["Culture"].ToString());
}
base.OnLoad(e);
}
Why does it not change the currency back to £ when I'm changing the session culture from en-US to en-GB?
Because you are checking if (Session["Culture"] != null), which restricts you to set the culture second time as Session["Culture"] will not be null.
I got it, because it was coming from a database entry that for some reason was a char(10) datatype, I forgot to trim the text. This resulted in the culture not being found by the Framework and defaulting back to en-US as it couldn't find 'en-GB '.
In asp.net multilingual website in english Uk and swedish, i have three rsources file
1. en-GB.resx
2. sv-SE.resx
3. Culture neutral file.
I have create one base class and all pages is inherited from that class. There i write following lines to set UICULTURE and culture
1. Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentUICulture.Name;
2. Thread.CurrentThread.CurrentCulture = CultureInfo.CurrentCulture.Name;
Question: Suppose my browser language is Swedish(sv-SE) then this code will run because it find CurrentUICulture and CurrentCulture values as sv-SE.
Now if suppose browser language is Swedish(sv) only, in that case values will be set as
CurrentUICulture = sv; and CurrentCulture = sv-SE
Now the problem is that user can able to view all text in Culture neutral resource file that i kept as english while all decimal saperators, currency and other will be appear in swedish.
It looks confusing to usr.
What would be right approach. I am thinking following solution. Please correct me?
1. i can create extra resource file for sv also.
2. I check value of CurrentUICulture in base class and if it is sv then replace it with sv-SE
Please correct me which one is right approach or Is there any other good way of doing?
You can easily replace the value in the base class like you mentioned. I would stay away from creating an additional resource file that duplicates data since it will be harder to maintain.
if (Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToLower() != "sv")
...replace with sv-SE
EDIT See this other question]1 for additional info. There's a good article referenced in the answer of that question
I'm building an ASP.NET web application, and all of my strings are stored in a resource file. I'd like to add a second language to my application, and ideally, I'd like to auto-detect the user's browser language (or windows language) and default to that, instead of making them choose something besides English. Currently, I'm handling all the resource population manually, so adding a second resource file and language is trivial from my point of view, if I had an easy way to automatically figure out what language to display.
Has anybody done this, or do you have any thoughts about how I might retrieve that value? Since ASP.NET is server-based, I don't seem to have any access to specific browser settings.
RESOLUTION: Here's what I ended up doing. I used a "For Each" to go through "HttpContext.Current.Request.UserLanguages" and search for one I support. I'm actually just checking the left two characters, since we don't support any dialects yet - just English and Spanish. Thanks for all the help!
Try this in the web.config:
<globalization culture="auto" uiCulture="auto" />
This will cause ASP.NET to auto-detect the client's culture from the request header. You can also set this on a per-page basis via the Page attribute.
This article (linked to archive.org as original link is now dead) might be helpful with auto detecting the browser's language setting.
[EDIT] Yes. The quoted article does not use ASP.NET. This article does.
Request.UserLanguages in ASP.NET 4 parses this as a string array.
Good info: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
This is a great question, as localization in ASP.NET is overlooked by many developers.
ASP.NET should automatically pick up on the user's browser settings and force the CultureInfo.CurrentCulture to the user's browser language. You can force the issue with a line in Page_OnInit() like:
Thread.CurrentThread.CurrentCulture = new CultureInfo(HttpContext.Current.Request.UserLanguages[0]);
How can you test this? Enter the languages panel on our browser and change settings.
The client generally sets Accept-Language in the HTTP request header with a quantitatively scored list of preferred language, conventionally (but not necessarily) in order of most favored to least favored. You can parse that, but as Maxam has noted, ASP.NET does have a mechanism for doing that on your behalf.
/// <summary>
/// Sets a user's Locale based on the browser's Locale setting. If no setting
/// is provided the default Locale is used.
/// </summary>
public static void SetUserLocale(string CurrencySymbol, bool SetUiCulture)
{
HttpRequest Request = HttpContext.Current.Request;
if (Request.UserLanguages == null)
return;
string Lang = Request.UserLanguages[0];
if (Lang != null)
{
// *** Problems with Turkish Locale and upper/lower case
// *** DataRow/DataTable indexes
if (Lang.StartsWith("tr"))
return;
if (Lang.Length < 3)
Lang = Lang + "-" + Lang.ToUpper();
try
{
System.Globalization.CultureInfo Culture = new System.Globalization.CultureInfo(Lang);
if (CurrencySymbol != null && CurrencySymbol != "")
Culture.NumberFormat.CurrencySymbol = CurrencySymbol;
System.Threading.Thread.CurrentThread.CurrentCulture = Culture;
if (SetUiCulture)
System.Threading.Thread.CurrentThread.CurrentUICulture = Culture;
}
catch
{ ;}
}
}
The source of this article is here:
How to detect browser language
Is it possible to display local times to users without using Javascript when you store the values as UTC?
You would need serverside to be aware of the clients timezone. There isn't enough information in the typical request to make that determination, the closest you can get is the Accept_Language header which might give you a clue but is hardly useful enough (esp. if the client is in a country that has multiple timezones).
Hence you would need to user to tell you what their timezone is and then use a logon or cookie to store that info.
You could do the conversion on the serverside in vb.net, c# or whatever .net language your using. You are going to have to convert to the local time somewhere.
Your asking a very broad question with no detail so I can't recommend how to do this on the server.
Edit
Based on the comments I see the problem your having is that you want to figure out what the users timezone is without javascript. I always have the user tell me their timezone when they register.
One approach which won't be perfect would be would to be use a geo-ip lookup service that will tell you most likely where your user and give your better granularity then using the language settings.
Think this is the closest you can do:
using System.Globalization;
// get the first language from request (en, fr, ru)
var primaryLanguage = Request.UserLanguages.First().Split(";").First();
// find a culture by this language
var culture = new CultureInfo(primaryLanguage);
// if the culture is neutral, try to find the specific one
if (culture.IsNeutralCulture)
culture = CultureInfo.GetCultures(CultureTypes.SpecificCultures).FirstOrDefault(o => o.TwoLetterISOLanguageName == primaryLanguage);
// get the string from a datetime
var datetimeText = culture ? DateTime.Now.ToString(culture) : DateTime.Now.ToString();