Detect User's Country in .CS File - c#

I have an application that needs to detect the user's country so I can adjust dates to that expectation for that country. I do have JS that is working already in detecting the locale. Now, I understand that JS is browser side and my CS file is server side. Is there a way to either:
1) Link that JS's answer up to my CS
or
2) Detect the locale within the CS file?
Thank you for your time
Kevin

Well, detecting the user's country isn't really the issue. If you need to format dates, you need to use something like this to detect the current culture rather than the country:
CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
You wouldn't want to detect the country as there's plenty of users in a given country that don't use the program in that country's culture. For example, say someone has their system set to Spanish, but they live in the USA. You'd force them to use English, but using this method, you can take it directly from the system setting instead. Being dynamic is good!
That way, when you output a date, you can do something like this:
// Displays dt, formatted using the ShortDatePattern
// and the CurrentThread.CurrentCulture.
Console.WriteLine(dt.ToString("d"));
Reference: http://msdn.microsoft.com/en-us/library/5hh873ya(v=vs.90).aspx
See also: http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture.aspx

Related

How to select correct country from currency ISO code in C#

I am building an app where the user can input their currency via the ISO 4127 code (EUR,USD, JPY, etc).
As a eye-candy feature, I wanted to add a tooltip to the TextBox control where one could find some inforamtion about the currency, that is the translated name, the symbol and the native name.
For the translated and symbol all is good, I found all I need (I found an amazing repository with everything translated), but when it comes to the native name I got into an interesting a peculiar issue:
As an example, let's take the UK Pounds (ISO "GBP"). Using the methods available from the CultureInfo and RegionInfo class I get that there are 3 regions adopting the GBP:
the Welsch one, with CurrencyNativeName = "Punt Prydain"
the British one, with CurrencyNativeName = "Pound Sterling"
the Scottish one, with CurrencyNativeName = "Punnd Sasannach"
The question is: is there any "default international native name"? in this case, usually one means the british name, but all of these 3 region have as parent the "en" language.
This question does not intend to raise any political or regional issue at all, I'm just asking if there is a default value when somebody chooses a courrency used in multiple countries or regions.
new RegionInfo("GB").CurrencyNativeName will get you the "default international native name" for the UK (which is "Pound Sterling"), where "GB" is the two-letter code defined in ISO 3166.

How to obtain the control panel currency format in C#

Our report generator works fine when the culture setting uses "$" for currency symbol.
Now we want to use this in European and use "€" instead.
I went to control panel, change the "Region and Language" format to "Danish (Denmark)" and apply the change.
Now open Excel and type in a number then set the cell format to currency, the currency symbol is updated.
However, our report generator is still using "$". When debugging the software we found that CultureInfo.CurrentCulture is still a culture using "$" (i.e., en-AU).
(The code is trivial but I just simply written down here:)
result = ValueToDisplay.ToString("C"); //CultureInfo.CurrentCulture is "en-AU"
I recon this might not be a real problem when the user's computer is in European since in that case CultureInfo.CurrentCulture will be different.
However, obviously Excel can correspond to the setting change in control panel without even reboot the computer, so in theory our software should be able to do so as well.
So how do we work like Excel?
You can handle this without a restart of your application by listening for the event that indicates the locale has changed and then clearing the CultureInfo cache.
To listen for the event, you can do this:
SystemEvents.UserPreferenceChanged += SystemEvents_UserPreferenceChanged;
Then in the event handler, you can clear the Culture cache:
private void SystemEvents_UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e)
{
if (e.Category == UserPreferenceCategory.Locale)
CultureInfo.CurrentCulture.ClearCachedData();
}
Now, when you run code like this:
var number = 21.00;
MessageBox.Show(number.ToString("C"));
You will get the correct output based on whatever locale information the user has changed.
Thanks to the hints, I found that our program do reset the culture and stored the original culture somewhere else. When change the code to
result = ValueToDisplay.ToString("C", originalCulture);
this works fine.

User!Language vs CurrentThread

For formatting our Dates in the RDL-Files, we use the following format:
=First(FormatDateTime(Fields!SomeDate.Value, 2))
According to this Page, it should take the Computer's Regional Settings.
The problem is: If I call the Reporting-Service via another Service and try to set the Language:
rs.SetExecutionParameters(MapParameters(Report.Parameters).ToArray(), "de-CH");
This gets ignored. I tried to override the Thread-Cultures via
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("de-CH");
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-CH");
Which gets ignored as well.
Whats really string: The Reporting-Server itself has de-CH as culture as well, but it keeps using the english date-format.
Can someone tells me what's meant with "Computer's Regional Settings" and why the Reporting-Service refuses to take the passed Culture?
Edit: The language in the Report is
=User!Language
Generally said I'd like to pass the Report-Language from outside, be it via CurrentThread or via Parameter. But both get ignored.
Short Answer
Instead of FormatDateTime, you could use Format and specify your expected output format:
=First(Format(Fields!SomeDate.Value, "dd.MM.yyyy"))
Or another alternative to have the culture in a parameter, but in this case you will have to read the long answer.
Long answer
Your first attempt with the SetExecutionParameters was to set the culture of the parameters, which does not affect the report itself (only the parameters you pass to it).
Your second attempt was to change the culture of the client application, which also does not affect the report (only the client application culture).
The FormatDateTime function usually uses the computer regional settings, but not in Reporting Services. It will take the report culture, which in your case is User!Language.
User!Language returns the language configured in the client web browser when browsing to the report server.
I'm not sure what the behavior is when calling from web services (a specific setting taken or default to en-US).
The Report Language property can be an expression, so nothing stops you from adding another text parameter to the report, say, ReportCulture, and use this in Properties => Language:
=Parameters!ReportCulture.Value
You would have to keep using your expression for the dates:
=First(FormatDateTime(Fields!SomeDate.Value, 2))
You can configure a default value (de-CH in your case), so that this setting will only be specified if you want to override it.

Use of CultureInfo.InvariantCulture

I'm working on a project that uses decimals in a textbox. I'm currently developing in a machine that has decimal separators set to "," instead of "." so I had to use this sentence when parsing text string into decimal:
decimal number = Decimal.Parse(number.Text, CultureInfo.InvariantCulture);
Now... Is CultureInfo.InvariantCulture the right thing to do or should I use CurrentCulture instead?
Thank you,
Matias.
For user input, you usually want CultureInfo.CurrentCulture. The fact that you're using a locale that's not natural to you is not the usual user case - if the user has , as the decimal point in their whole system, they're probably used to using that, instead of your preferred .. In other words, while you're testing on a system with locale like that, learn to use , instead of . - it's part of what makes locale testing useful :)
On the other hand, if you're e.g. storing the values in a configuration file or something like that, you really want to use CultureInfo.InvariantCulture.
The thinking is rather simple - is it the user's data (=> CurrentCulture), or is it supposed to be global (=> InvariantCulture)?
If you do a correctly internationalized program...
A) If you are using Winforms or WPF or in general the user will "work" on the machine of the program, then input parsing should be done with the CurrentCulture
B) If you are web-programming, then the user should be able to select its culture, and CurrentCulture (the culture of the web-server) should be only used as a default
And then,
A) data you save "internally" (so to be written and then read by your program) should use InvariantCulture,
B) data you interchange with other apps would be better to be written with InvariantCulture (unless the other app is badly written and requires a specific format),
C) files you export to the user should follow the previous rules (the ones about user interface), unless you are using a "standard-defined format" like XML (then use Xml formatters)

ASP.NET Globalization -- Displaying dates

Good morning,
Apologies for the newbie question. I'm just getting started with ASP.NET internationalization settings.
Background info:
I have a website which displays a <table> HTML object. In that <table> HTML object, I have a column which displays dates. My server being in the US, those dates show up as MM/DD/YYYY. Many of my users plug into this webpage through Excel, via the Data --> Import External Data --> Import Web Query interface. My users, for the most part, are in the US, so those dates show up correctly in their Excel screens.
Now I need to make the webpage work for UK users. As is, they are downloading the dates as MM/DD/YYYY, which makes their spreadsheets unusable since their regional settings are set to DD/MM/YYYY.
My question is:
How do I make it so the web server realizes that the incoming request has a en-GB culture setting? I could engineer my own little custom workaround, but I'm sure I'm not the first programmer to come across this. How do the pro's handle this? I'm looking for a solution that would be relatively simple and quick to put up, but I don't want to just put some crappy buggy piece of my own logic togethe that I'm going to dread 6 months from now.
Thanks a lot in advance,
-Alan.
A couple of points:
The <globalization> element also needs the attribute culture="auto". The uiCulture attribute affects the language used to retrieve resources. The culture attribute affects the culture used for formatting numbers an dates.
As noted in this MSDN article, it is not a best practice to rely exclusively on browser settings to determine the UI culture for a page. Users frequently use browsers that are not set to their preferences (for example, in an Internet cafe). You should provide a method for users to explicitly choose a language or language and culture (CultureInfo name) for the page.
You can allow the browser to set your UI culture automatically if you wish, by opening up the web.config, like this:
<configuration>
<system.web>
<globalization uiCulture="auto" />
...
And then the culture set by the browser will be automatically set in your app. This means that when you have the framework display date/time values, they will be formatted according to the current thread's UI Culture.
This will also help if you are using currency and/or localized text (however you have to provide the localized resources for each culture you support).
You could also accept a query string parameter for overriding the culture settings.
Culture initialization should go in the Page.InitializeCulture method.
protected override void InitializeCulture ( )
{
Thread.CurrentThread.CurrentCulture
= Thread.CurrentThread.CurrentUICulture
= Request.QueryString [ "culture" ] != null ? new CultureInfo ( Request.QueryString [ "culture" ] ) : CultureInfo.InvariantCulture;
//base.InitializeCulture ( );
}
Usage: http://tempuri.org/page.aspx?culture=en-GB

Categories