Get Sitecore content editor language selection - c#

I have created a custom Sitecore control (extending Control) to be used in the content editor. It calls a service and this services requires a language.
When the control is rendered it returns "en" as language every time, how can I get the user selection from the "language dropdown" in the content editor ?
In my method, I want to do something like this:
Language theLanguage = new Language.Parse("da-dk");
Item theLanguageSpecificItem = (Sitecore.Data.Database.GetDatabase("master")).GetItem(myId, theLanguage);
However, I don't want the da-dk part to be hardcoded, I want to get it from the language dropdown in the content editor. For some reason I always get "en" if I use Sitecore.Sites.SiteContext.Current.Language, Any idea ?

Ok, finally got it. When selecting another language you can request the language by simply doing like this.
string currentLanguage = HttpContext.Current.Request["scLanguage"];
Thank you all for helping.

Have you tried to use the Sitecore Context to get it?
Sitecore.Context.Culture.Name

The selected language is stored in a hidden field on the page:
<input type="hidden" id="scLanguage" name="scLanguage" value="en">
This changes when you change language, and is posted with each request.
string language = Sitecore.WebUtil.GetFormValue("scLanguage");
Internally this just does a HttpContext.Current.Request.Form[fieldName]. If you are extending a control then you may already have access to the language as a property, or take a look at one of the existing Sitecore controls and follow their implementation pattern, e.g. Sitecore.Shell.Applications.ContentEditor.LookupEx:
public string ItemLanguage
{
get
{
return this.GetViewStateString("ItemLanguage");
}
set
{
Assert.ArgumentNotNull((object) value, "value");
this.SetViewStateString("ItemLanguage", value);
}
}

I haven't tried this yet but looks like you may be able to get the selected language in the content editor by parsing the language parameter of the ServerProperties.
Language.Parse(Context.ClientPage.ServerProperties["language"] as string)

Related

conditionally run code in cshtml based on URL [duplicate]

I know on client side (javascript) you can use windows.location.hash but could not find anyway to access from the server side. I'm using asp.net.
We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:
When the form submits, grab the hash (window.location.hash) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash" so we can find it easily later.
On the server you can use this value if you need to do something with it. You can even change it if you need to.
On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.
If the hidden input field has a valid value, set that as the URL hash (window.location.hash again) and/or perform other actions.
We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.
Before submit:
$("form").submit(function() {
$("input", "#urlhash").val(window.location.hash);
});
On page load:
var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
window.location.hash = hashVal;
}
IsHashValid() can check for "undefined" or other things you don't want to handle.
Also, make sure you use $(document).ready() appropriately, of course.
[RFC 2396][1] section 4.1:
When a URI reference is used to perform a retrieval action on the
identified resource, the optional fragment identifier, separated from
the URI by a crosshatch ("#") character, consists of additional
reference information to be interpreted by the user agent after the
retrieval action has been successfully completed. As such, it is not
part of a URI, but is often used in conjunction with a URI.
(emphasis added)
[1]: https://www.rfc-editor.org/rfc/rfc2396#section-4
That's because the browser doesn't transmit that part to the server, sorry.
Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX).
Regards
Artur
You may see also how to play with back button and browser history
at Malcan
Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).
Possible solution for GET requests:
New Link format: http://example.com/yourDirectory?hash=video01
Call this function toward top of controller or http://example.com/yourDirectory/index.php:
function redirect()
{
if (!empty($_GET['hash'])) {
/** Sanitize & Validate $_GET['hash']
If valid return string
If invalid: return empty or false
******************************************************/
$validHash = sanitizeAndValidateHashFunction($_GET['hash']);
if (!empty($validHash)) {
$url = './#' . $validHash;
} else {
$url = '/your404page.php';
}
header("Location: $url");
}
}

How to manually set language in ASP MVC without reconfiguring routing

EDIT
The mistake was in the country code. Albania's country code is sq-AL, and not al-AL.
For a full list of country codes: http://timtrott.co.uk/culture-codes/
I don't need to have different routing for different languages.
All I need is by the click of a button to toggle between two languages, Albanian, and English.
What I can't figure out: how to change the language? I'm not worried on how to detect which language needs to be selected, but how to actually change the language.
I have these 2 resource files:
Resources.resx, Resources.al-AL.resx
Always the strings from Resources.resx are used, how can I change so that the strings from Resources.al-AL.resx are used?
I tried something like this:
//I'm just trying stuff I read here in SO, none worked so far.
Resource.Culture = CultureInfo.CreateSpecificCulture("al-AL");
HttpContext.Session["culture"] = "al-AL";
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("al-AL");
return RedirectToAction("Index", "Home");
And in my view I have this:
#Resource.Culture
#Html.Label(Resource.CustomerName, new { #class = "control-label"})
When I first open the view, the first line is empty, after selecting one of the buttons to change the language, I verify that the Resource's culture is being changed, but the text stays the same.
EDIT:
I even added this to web.config <globalization uiCulture="al-AL" culture="al-AL"/>
Custom folder to hold the resource files
Instead of using culture code al-AL I had to use sq-AL. For a full list of culture codes:
http://timtrott.co.uk/culture-codes/

How to covert a string from report table in c# to Vietnamese currency?

I have a c# report that contains one String column represent the currency.
Now I try to convert the String value to currency:
= FormatCurrency(Fields!SOTIEN_GUI.Value, 0)
That works, but the value is now US currency (EX: $ 7.000)
What have I do to to get the result like "₫ 7.000" ?
Thanks.
I assume, you have created .rdlc report file. To set Current region settings, so to display currency in the format you'd prefer, you should to do next.
First, you should find Language report property. To do that, just click free place around you report objects. In the Properties window, VS will display the properties for the report.
Second, find there Language property, and change it to those, that you like. Btw, it's described here.
So, you'll get something like this:
Is this in some special context, like Excel or something? In regular C#, I think what you want to do is use something like:
moneyValue.ToString("C", new CultureInfo("vi-VN"));
Instead of using FormatCurrency you could use the ToString() Method.
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
you maybe take a look at this thread: How to format a string as Vietnamese currency?
as you can see it's possible to use the ToString() Method (or like in the example the string.Format() Method):
var value = 8012.34m;
var info = System.Globalization.CultureInfo.GetCultureInfo("vi-VN");
Console.WriteLine(String.Format(info, "{0:c}", value));

How can I convert a C# .NET application to support multiple languages?

I have a C# application that I need to convert to support English and Spanish, is there a semi easy way to add that in and be able to add other languages later on?
Yes! It's called resource (.resx) files. What you do is this:
Change the Localizable property of your localizable forms to true. This will make the designer fetch text and other properties from the .resx files instead of hard-coding them.
Create your program in one language, let's say English.
Next, change all your forms to another language like so:
Change the Language property of the form to the other language, let's say Spanish.
Change the text on all your controls. The designer will automatically generate a new .resx file for the language.
Swap back and forth as needed during development.
When publishing, go into your Assembly Settings and change the language. You can also change the language in code, I think.
And voilà! You're done!
You mark all your forms and controls as localizable. This will put all UI related text (labels etc.) in resource files. If you need to create strings in code then you use string resource files and look up the string by the resource key (e.g StringResource.Get("My_Message")). Then you can use a tool to translate all your resources. Typically you create a localized .dll for each language. We use Passolo for that but there are other tools around.
You can make a multilingual application in two ways:
By making the application Localizable, so when the user changes the culture of the device, the application will switch automatically to culture's UI if you added this language already to the supported languages in the application.
You can perform this by setting each form's Localizable property on the project to Localizable, and then changing the UI to the new culture.
By making a language option and a resource file (.resx) for each added language in your application, and depending on the selected language, you can load the images or the strings from selected language's resource file.
Without installing any 3rd party tool, APIs, or dll objects, I am able to utilize the App_LocalResources. Although I still use Google Translate for the words and sentences to be translated and copy and paste it to the file as you can see in one of the screenshots below (or you can have a person translator and type manually to add). In your Project folder (using MS Visual Studio as editor), add an App_LocalResources folder and create the English and other language (resx file). In my case, it's Spanish (es-ES) translation. See screenshot below.
Next, on your aspx, add the meta tags (meta:resourcekey) that will match in the App_LocalResources. One for English and another to the Spanish file. See screenshots below:
Spanish: (filename.aspx.es-ES.resx)
English: (filename.aspx.resx)
.
Then create a link on your masterpage file with a querystring that will switch the page translation and will be available on all pages:
<%--ENGLISH/SPANISH VERSION BUTTON--%>
<asp:HyperLink ID="eng_ver" runat="server" Text="English" Font-Underline="false"></asp:HyperLink> |
<asp:HyperLink ID="spa_ver" runat="server" Text="Español" Font-Underline="false"></asp:HyperLink>
<%--ENGLISH/SPANISH VERSION BUTTON--%>
.
On your masterpage code behind, create a dynamic link to the Hyperlink tags:
////LOCALIZATION
string thispage = Request.Url.AbsolutePath;
eng_ver.NavigateUrl = thispage;
spa_ver.NavigateUrl = thispage + "?ver=es-ES";
////LOCALIZATION
.
Now, on your page files' code behind, you can set a session variable to make all links or redirections to stick to the desired translation by always adding a querystring to urls.
On PageLoad:
///'LOCALIZATION
//dynamic querystring; add this to urls ---> ?" + Session["add2url"]
{
if (Session["version"] != null)
{
Session["add2url"] = "?ver=" + Session["version"]; //SPANISH version
}
else
{
Session["add2url"] = ""; // ENGLISH as default
}
}
///'LOCALIZATION
.
On Click Events sample:
protected void btnBack_Click(object sender, EventArgs e)
{
Session["FileName.aspx"] = null;
Response.Redirect("FileName.aspx" + Session["add2url"]);
}
I hope my descriptions were easy enough.

Javascript culture always en-us

I'm not sure if I understand this code or if I'm using it right, but I was under the impression that in an ASP.NET 2.0 AJAX website I could run javascript like:
var c = Sys.CultureInfo.CurrentCulture
and it would give me the culture/language settings the user had specified in their browser at the time of the visit. However, for me, it always comes back 'en-US' no matter what language I pick in firefox or IE.
This serverside code however:
string[] languages = HttpContext.Current.Request.UserLanguages;
if (languages == null || languages.Length == 0)
return null;
try
{
string language = languages[0].ToLowerInvariant().Trim();
return CultureInfo.CreateSpecificCulture(language);
}
catch (ArgumentException)
{
return null;
}
does return the language I have currently set. But I need to do this clientside, because I need to parse a string into a datetime and do some validations before I postback, and the string could be a MM/DD/YYYY or DD/MM/YYYY, or some other such thing.
What am I missing?
EDIT:
Ok, I came across this library http://www.datejs.com/. It looks pretty sweet, and it has ninjas, so I'm pretty much sold already. But in their doc I noticed that you need to include one of the language specific js files to include. I imagine you'd have to make that determination serverside and emit the proper script include tag, which got me thinking. Am I supposed to be doing this with the ASP.NET AJAX stuff? i.e. checking the serverside culture(which works) and setting the Sys.CultureInfo.CurrentCulture in js based on that? I was hoping it would just automagically get it from the browser clientside.
The value of Sys.CultureInfo.CurrentCulture is based on a value that is sent from the server. To get the server to send the correct value back to the client, you need to set the EnableScriptGlobalization property to true on the ScriptManager object (it's false by default).
TMK, the browser does not pass any timezone info to server in the first request. You need to do this with Javascript

Categories