I need a help to select language and change the CultureInfo dynamically after selecting the desired language. I have the files .resx , the view and the controller. But I use Tenant, so.. It is possible or recommended change the language in it?
I have in view:
<div class="form-group" >
<select id="idiomSelect" class="form-control" style=" border-color: #FFFFFF;">
<option id="pt-BR" ng-selected="selected">Português (Brasil)</option>
<option id="es-CL">Español (Chile)</option>
<option id="es-ES">Español (España)</option>
<option id="en-US">English (USA)</option>
</select>
</div>
And I thought of building a method with the following parameters(example with en-US):
Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
Could anyone help me, please?
Dealing with multi-tenancy (i.e. multiple domains mapping to the same application). The answer for this does depend on how the tenencies are set up. For example, if you follow the Wikipedia model, the culture name is encoded in the URL (i.e. en.wikipedia.org, ja.wikipedia.org, de.wikipedia.org). In this case you have your CultureInfo encoded into the URL itself. You just need to extract it and use it to retrieve your resource. If you have another model for multi-tenancy, then your best bet might be to use a session variable or cookie to remember the requested culture.
The remaining part of the problem is directly related to i18n (internationalization) and l10n (localization). The folks at ASP.Net have come up with a great article on how to build that infrastructure in to your system (link to article). Essentially it uses the some of the clues I provided, but wraps them up in helper classes so you always have access to it as you need it:
They recommend using the ASPNET_CULTURE cookie (CookieRequestCultureProvider) to store the culture info.
The preferred option to automatically detecting the desired culture is to use the Accept-Language HTTP header. When set, it provides the preferred order of cultures. This provides a better experience for expats who live in foreign countries but want to read in their native language.
Your .resx files follow the standard naming pattern: (FileName.resx for default language, FileName.fr.resx for the French culture, etc.). The i18n variants must live in the same namespace/folder as the default .resx file. (this is required for the ResourceManager to resolve resources based on culture info).
The article provides examples of creating your own helpers to look up and resolve resources automatically.
The ".resx" file has a few properties and methods that you may not know about.
Culture -- the CultureInfo to use for all requests by name
ResourceManager -- the actual dictionary for the resources
Each property you've defined in your ".resx" file simply calls the following equivalent method:
ResourceManager.GetString("ResourceName", Culture);
There's nothing that automatically looks at your Thread.CurrentCulture values automatically. However, you can use the nameof() operator and that value to get your values:
MyResources.ResourceManager.GetString(
nameof(MyResources.ResourceManager.ResourceName),
Thread.CurrentUICulture);
Thank you guys .. I got it..
OutputCache(NoStore = true, Duration = 0)]
// set language on select(view) and create a cookie
[HttpGet]
public ActionResult SetCulture(string idiomString)
{
HttpCookie cookie = Request.Cookies["_culture"];
if (cookie != null)
cookie.Value = idiomString;
else
{
cookie = new HttpCookie("_culture");
cookie.Value = idiomString;
}
Response.Cookies.Add(cookie);
return RedirectToAction("Index");
}
// set the language
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
string cultureName = null;
HttpCookie cultureCookie = Request.Cookies["_culture"];
if (cultureCookie != null)
cultureName = cultureCookie.Value;
else
cultureName = Request.UserLanguages["0"];
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
return base.BeginExecuteCore(callback, state);
}
Related
I work out of New Zealand developing a web application for some Romanian clients. The application should default to ro-RO when viewed by a client using a Romanian machine and en-GB for pretty much everyone else at this stage. Problem is ALL machines I have used to test this are defaulting to en-US. That is, machines on Windows Azure European data centers, local machines here in NZ and various machine in Romania which I access via RDP.
So i use this code in a controller to set language based on user defaults:
public static void OnBeginExecuteCore(Controller controller)
{
if (controller.RouteData.Values[Constants.ROUTE_PARAMNAME_LANG] != null &&
!string.IsNullOrWhiteSpace(controller.RouteData.Values[Constants.ROUTE_PARAMNAME_LANG].ToString()))
{
// set the culture from the route data (url)
var lang = controller.RouteData.Values[Constants.ROUTE_PARAMNAME_LANG].ToString();
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
}
else
{
// load the culture info from the cookie
var cookie = controller.HttpContext.Request.Cookies[Constants.COOKIE_NAME];
var langHeader = string.Empty;
if (cookie != null)
{
// set the culture by the cookie content
langHeader = cookie.Value;
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
}
else
{
// set the culture by the location if not specified
langHeader = controller.HttpContext.Request.UserLanguages[0];
if (langHeader.ToLower() == "en-us") langHeader = "en-GB";
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
}
// set the lang value into route data
controller.RouteData.Values[Constants.ROUTE_PARAMNAME_LANG] = langHeader;
}
// save the location into cookie
HttpCookie cultCookie;
cultCookie = new HttpCookie(Constants.COOKIE_NAME, Thread.CurrentThread.CurrentUICulture.Name)
{
Expires = DateTime.Now.AddYears(1)
};
controller.HttpContext.Response.SetCookie(cultCookie);
}
where
langHeader = controller.HttpContext.Request.UserLanguages[0];
is always en-US. There are in fact 3 entries in this collection however:
but ro is clearly not weighted correctly. This is the same across all machines in all locales.
Globalization in web config is set to auto:
<globalization requestEncoding="utf-8"
culture="auto"
uiCulture="auto"
And regional windows settings are as follows:
Browser:
How can I make this work?
ANSWER
As per Martins answer in comments. Problem was that I had this in apparently all settings the world over.
when what I really wanted was this in Chrome... will get to the other browsers soon.
Ensure that your browser of choice (Internet Explorer, Chrome, Firefox, Safari etc.) has been set up to specify ro as the first language in the User Languages sent over HTTP to the server.
Updating the Windows and/or browser's UI language won't necessarily cause a non-English language ISO code to be sent to the server, which means that you'd just get English returned.
In Firefox, for example, this setting can be found under Options->Content->Languages->Choose.
I'm looking for the best approach for storing strings in kentico and accessing them programmatically similar to how you would access app.config settings.
Scenario:
I wish to create an ITask, which when executed will generate a number of HTML templates. I would allow entry of the text fields via Kentico. The templates are backbone templates.
My initial thought would be to store them in UI Culture and then access them via the task but I'm having some difficulty doing this as it's a scheduled task I don't have access to the HttpContext.
Potentially I should be storing these values in custom settings?
so i found the answer.
// ResHelper
using CMS.GlobalHelper;
using CMS.SiteProvider;
// Get culture ID from query string
var uiCultureID = QueryHelper.GetInteger("UIcultureID", 0);
// Get requested culture
var ui = UICultureInfoProvider.GetSafeUICulture(uiCultureID);
var dui = UICultureInfoProvider.GetUICultureInfo(CultureHelper.DefaultUICulture);
var s = ResHelper.GetString("myculturevalue.test", dui.UICultureCode);
for those interested in the task, take a look here http://devnet.kentico.com/Blogs/Martin-Hejtmanek/June-2010/New-in-5-5-Provide-your-classes-from-App_Code.aspx
thanks
In our application there are two types of user, let's call them Alpha and Beta users. Each of these users sees a different type of toolbar / menu.
We have decided to track this using cookies. The majority of our pages are either Alpha pages or Beta pages and then there are some common pages that Alpha and Beta users share. So in each view of our application where we know the user type (Alpha or Beta) we have the following code:
HttpCookie isAlphaCookie = new HttpCookie("IsAlpha", "false"); // or true
HttpCookie isBetaCookie = new HttpCookie("IsBeta", "true"); // or false
isAlphaCookie.Expires = DateTime.MaxValue;
isBetaCookie.Expires = DateTime.MaxValue;
Response.Cookies.Add(isAlphaCookie);
Response.Cookies.Add(isBetaCookie);
The idea is then, in common pages, we don't set any cookie and rely on the previously set cookie to determine which toolbar to load. So, these two cookies are set to true or false as above in our known pages before we read them in the controller method which loads our toolbar like so:
HeaderViewModel header = new HeaderViewModel
{
FirstName = UserProfile.CurrentUser.FirstName,
LastName = UserProfile.CurrentUser.LastName,
ImageUrl = null,
OrganisationName = UserProfile.CurrentUser.OrganisationName,
OrganisationUrl = UserProfile.CurrentUser.OrganisationUrl,
ShowAlphaToolbar = bool.Parse(Request.Cookies["IsAlpha"].Value),
ShowBetaToolbar = bool.Parse(Request.Cookies["IsBeta"].Value),
ShowPublicToolbar = false
};
return PartialView("Common/_Header", header);
From reading up on how to read / write cookies this seems to be the right approach; writing the cookie to the Response object and reading the cookie from the Request object.
The problem I'm having is that when i get to the controller method that loads the toolbar the values of the IsAlpha and IsBeta cookies are both empty strings and this breaks the application.
I have confirmed that the cookies are set in the Response before they are read in the Request.
I'm wondering whether I'm missing something fundamental here.
I only expect your assumption " in common pages, we don't set any cookie and rely on the previously set cookie to determine which toolbar to load" to work if you are calling these partial actions, which you referring to as "common pages" I guess, through Ajax Calls. If you are using
#Html.RenderAction('nameOfaAtion')
then I don't think what you have in place will work.
Reason is Both your main action and partial actions are executed within the same Http Request Cycle so the cookies you are trying to access from the Request Object in your common pages have not yet came as part of Request.
Edit
As I can see you are hard coding the cookies on each page so Guess you can also do something like below. Not originally the way you are trying to do but I think it will do the same thing you are trying.
In your pages change the partial view call to like this.
#Html.Action("LoadHeader", "Profile", new{IsAlpha=False, IsBeta=true});
Then Change the signature of the LoadHeader action to receive these two extra parameters
public ViewAction LoadHeader(bool IsAlpha, Bool IsBeta)
Then with the viewModel Initialization change two lines as below.
ShowAlphaToolbar = IsAlpha,
ShowBetaToolbar = IsBeta,
I am developing a site in asp.net in multiple languages but i didn't understand how this can be done because we can manage multilingual language by using resource files. we did this, but my major problem is that how we can change globalization at run time for a particular user. if A user choose English language then he/she can view this i English and if B user choose Spanish then he/she can view this site in Spanish. How we can do this? or how we can choose a particular language resource file???
use this code
protected override void InitializeCulture()
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); //'en-US' these values are may be in your session and you can use those
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");//'en-US' these values are may be in your session and you can use those
base.InitializeCulture();
}
I had this same question when i started developing multilingual sites and i found those two articles as the best starting point:
http://www.codeproject.com/KB/aspnet/localization_websites.aspx
http://www.codeproject.com/KB/aspnet/LocalizedSamplePart2.aspx
you could try something like this:
string culture = "en-US"; //could come from anything (session, database, control, etc..)
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
I think it works!
you need to use localization for language and individual resource file. Now when your site is being access at client side you need to check the locale setting on client's machine his date/time setting and the Default language ... on the basis of this you can provide language that user wish...
How can I make a website multilingual?
I want to create a website and in the home page i want the client to choose a language from English and Arabic. Then the whole website is converted to that language. What should I do to achieve this? I am creating this website in asp.net 2.0 with C#
What you're asking for is a tutorial, which you really should try googling for. Look at the links below, if there's something particular, more specific you don't understand - ask the question here.
http://www.beansoftware.com/ASP.NET-Tutorials/Globalisation-Multilingual-CultureInfo.aspx
http://www.asp.net/learn/Videos/video-40.aspx
http://www.about2findout.com/blog/2007/02/aspnet-multilingual-site_10.html
Good luck!
ASP.NET can use a number of mechanisms to change language settings - however you will need to perform the translations your self.
You could look at using Resource files for the common elements of your site - see this answer to Currency, Calendar changes to selected language, but not label in ASP.NET
However, for the main content you'd probably want to do something with the URL to ensure that your content is served correctly - the links that Honsa has supplied would be a good place to start.
Sample code i have done using resource file add global.asax
void Application_BeginRequest(Object sender, EventArgs e)
{
// Code that runs on application startup
HttpCookie cookie = HttpContext.Current.Request.Cookies["CultureInfo"];
if (cookie != null && cookie.Value != null)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cookie.Value);
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cookie.Value);
}
else
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en");
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en");
}
}
http://satindersinght.blogspot.in/2012/06/create-website-for-multilanguage.html
http://satindersinght.wordpress.com/2012/06/14/create-website-for-multilanguage-support/
For Arabic you need to change the direction left to right