Issue with asp.net expression builder - c#

I have the same issue mentioned in this question, but the accepted answer doesn't work for me. Basically I simply would like to add translations to elements (e.g. button, label) in a webforms page.
I checked other sites too, they all point to the same solution. E.g. this this MSDN article says:
For example, when localizing content automatically, you can set the Text property of a server control using expression syntax, as in this example:
<asp:Label id="label1" runat="server" text="<%$ Resources: Messages, ThankYouLabel %>" />
In the App_GlobalResources folder, you could have resource files named Messages.resx, Messages.es.resx, Message.de.resx, and so on—a Messages resource file for each language you want to support
In my case, the translation is not picked up, I see always the neutral language (English).
I made a dummy skeleton project too with only a few lines of code, there I have 2 resource files in the App_GlobalResources folder:
MyResources.resx
MyResources.nl.resx
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("nl");
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("nl");
}
Default.aspx
<%-- this displays the translation (nl) --%>
<%= Resources.MyResource.MyKey %>
<%-- this displays the neutral language (en) --%>
<asp:Label ID="Label1" runat="server" Text="<%$ Resources: MyResource, MyKey %>" />
Any ideas what do I miss?

After several tries (and failures) I got it working. This answer and this MSDN page put me on the right track.
In short, I needed override the InitializeCulture method like this:
protected override void InitializeCulture()
{
UICulture = "nl";
Culture = "nl"
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("nl");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("nl");
base.InitializeCulture();
}
To make it a general solution, I had to create a new PageBase class, which is inherited by all pages, as it is nicely described here.

Related

How to make my webform to be multi-language?

I am going to write a web form via Visual Studio 2013 with Devexpress v14.1.
The web form is required to change the language with CheckedChanged event.
I have read some of the articles from Google,
but it seems that it required to set all of the controls one by one.
For example, if there are 30 labels in my web page, it is necessary to add 30 lines:
Label1.Text = ...;
Label2.Text = ...;
...
Label30.Text = ...;
What is the best approach to make multi-language web page ?
Please help!!!
Implementing multi-lingual is not as simple as you think.
Prerequisite: -
All controls which need multi-lingual on your page should be server control. e.g.
<Label runat="server" ID="lblName" Text="Type your name"></Label>
Create a resource file
To generate a local resource file from an ASP.NET Web page
Open the page for which you want to create a resource file.
Switch to Design View.
In the Tools menu, click Generate Local Resource. (It will create the a resource file in local resources folder)
Type values for each resource that you need in your application, and then save the file.
Read more Creating Resources From a Web Page
When you have successfully created a default resource file (e.g. mypage.resx) then copy/paste it and rename the copied file with the language specific e.g. mypage.fr.resx for french
Change the values to the language specific values
Asp.net uses the resx file based on the current thread culture but the problem is CheckedChanged event occurs after the Page_Load event so CheckedChanged event method is not the correct place to change thread culture.
So you will need to capture the CheckedChanged value manually in Page_Init event (which occurs before Page_Load) event from Request.Form values and set the culture
Or inside CheckedChanged save a value in session or cookie and reload the page and in Page_Init use the session/cookie value to set the thread culture
I hope these articles ASP.NET Web Page Resources Overview and How to: Retrieve Resource Values Programmatically can help you to solve your problem:
Creating Resource Files for ASP.NET Web Sites
Working with Resources in Web Pages
Selecting Resource Files for Different Languages
eg.
<%# Page Language="C#" %>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
Button1.Text =
GetLocalResourceObject("Button1.Text").ToString();
Image1.ImageUrl =
(String)GetGlobalResourceObject(
"WebResourcesGlobal", "LogoUrl");
Image1.Visible = true;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click"
Text="Get Resources" />
<asp:Image ID="Image1" runat="server"
Visible="false" />
</div>
</form>
</body>
</html>
Take into account several aspects:
1. You have to keep track of the UICulture in your session (for example, using your SessionManager class). Then, you have to initialize in on your Page.
Code in your SessionManager class:
public string SUICulture
{
get
{
if (HttpContext.Current.Session["SUICulture"] == null)
{
HttpContext.Current.Session["SUICulture"] = "es";
}
return HttpContext.Current.Session["SUICulture"].ToString();
}
set
{
HttpContext.Current.Session["SUICulture"] = value;
}
}
Code in your Page:
protected override void InitializeCulture()
{
String currentUICulture = clsSessionManager.GetInstance().SUICulture;
if(currentUICulture != null){
UICulture = currentUICulture;
Thread.CurrentThread.CurrentUICulture = new CultureInfo(currentUICulture);
}
base.InitializeCulture();
}
2. Change the UICulture on the specific event of your page (onCheckedChanged in this case). In this example the page just offers two possible languages, English or Spanish
protected void chckOnCheckedChange(object sender, EventArgs e)
{
if (clsSessionManager.GetInstance().SUICulture== "es")
{
clsSessionManager.GetInstance().SUICulture= "en";
}else
{
clsSessionManager.GetInstance().SUICulture= "es";
}
Response.Redirect(Page.Request.Url.ToString(), true);
}
3. Change the labels of your page. Best approach: use resource files i.e. you can have two resource files.
You have to use server controls in order to achieve this. For example:
<asp:Literal ID="lblTitle" runat="server" />
Then you have to change it in your codebehind:
lblTitle.Text = GetGlobalResourceObject("Default","labelTitle").ToString();
You will find more information here
https://msdn.microsoft.com/en-us/library/fw69ke6f.aspx
4. Beside using resource files for the content of your page there is a possibility that you need to translate the menu as well (when using a sitemap).
This page show you how to do that https://msdn.microsoft.com/en-us/library/ms178426.aspx

access resource text from markup page

I'm creating an web application with multiple languages.
I've set the culture like this
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedLanguage);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedLanguage);
I've got several language files like "en.resx" and "de.resx".
I can read them from my code behind them like this
var test = GetGlobalResourceObject(Thread.CurrentThread.CurrentUICulture.ToString(), "aboutUsLnk");
But how about from the markup page.
I've been searching the web and most pages is suggesting something like this
<asp:Literal Text='<%$ Resources:Resource, aboutUsLnk %>' runat="server" />
That works if I have a .resx file called Resource but i that's not what I want. What did I miss?
That works if I have a .resx-file called Resource but i thats not what I want. What did I miss?
You are probably looking for local resources and meta:resourcekey attribute.
Local are defined per page (you define exactly the same name as your page for them), you use them for storing resources specific to one page. You create them by adding ASP.NET specific folder (App_LocalResources) and then inside it local resources for each of your pages:
App_LocalResources/{pagename}.resx
And then call for resource objects from resource files (AboutUs.resx, AboutUs.fr-BE.resx,...) from the page markup (AboutUs.aspx) would be something like this:
<asp:Literal Text='About Us' meta:resourcekey="aboutUsLnk" runat="server" />
Global resources which you mentioned are defined accros the whole website (usually you store here resources like "Edit", "Save", etc.) and are usually called as you showed.
Read here for more details: http://msdn.microsoft.com/en-us/magazine/cc163566.aspx
EDIT
Ahh sorry for misunderstanding, you are probably asking how to call your global resources which names differentiate per culture. You can do that in your markup code almost the same as you are doing in code behind, using GetGlobalResourceObject.
Anywhere outside of server controls you can write:
<%= GetGlobalResourceObject(System.Threading.Thread.CurrentThread.CurrentUICulture.ToString(), "aboutUsLnk")%>
To call GetGlobalResourceObject inside of server control attributes you cannot use <%= %>, but you can wrap the server controls around it (in the ones that allow this, like Label for example):
<asp:Label ID="Label1" runat="server"><%= GetGlobalResourceObject(System.Threading.Thread.CurrentThread.CurrentUICulture.ToString(), "aboutUsLnk")%></asp:Label>
Or, you can use the binding syntax:
<asp:Label ID="Label1" runat="server" Text='<%# GetGlobalResourceObject(System.Threading.Thread.CurrentThread.CurrentUICulture.ToString(), "aboutUsLnk")%>'></asp:Label>
Note, that when using the latter you will need to bind your control:
protected void Page_Load(object sender, EventArgs e)
{
Label1.DataBind();
}
EDIT 2
You can wrap the upper code in some helper method to improve code readabilty. In code behind you declare it:
protected string GetResource(string resourceName)
{
return GetGlobalResourceObject(System.Threading.Thread.CurrentThread.CurrentUICulture.ToString(), resourceName).ToString();
}
And in markup you can call it similiar as previous:
<asp:Label ID="Label1" runat="server" Text='<%# GetResource("aboutUsLnk")%>'></asp:Label>
<asp:Label ID="Label2" runat="server"><%= GetResource("aboutUsLnk")%></asp:Label>

Localization of ASP.NET website is not working

I am trying to localize an asp.net website, however its not working properly.
At the moment I have a user control, which I wish to localize. So inside the UserControls folder, I have created an App_LocalResources folder, and 4 files which will be used for the localization :
UCMain.aspx.resx
UCMain.aspx.it-IT.resx
UCMain.aspx.de-DE.resx
UCMain.aspx.fr-FR.resx
In the UserControls folder, I have the main UCMain.aspx and inside the UCMain.aspx, I have the following simple file:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="UCMain.ascx.cs" Inherits="SCPerformance.UserControls.UCMain" %>
<%# Import Namespace="SCPerformance.Shared.Models" %>
<div class="PanelContainer">
<div class="ContentTitle2">
<asp:Label runat="server" ID="lblAboutText" meta:resourcekey="lblAboutTextResource1" />
</div>
</div>
Inside the localized files (resx) I have the following for all the languages:
Name Value
lblAboutTextResource1.Text Informazione
The culture is set correctly when I click on the flags I have, so that is not the problem. The problem is to retrieve the actual text, I am always getting the English version.
What could be my problem?
Thanks for your help and time.
Here's another solution that works for my asp website with 4 languages ​​in my "GlobalRessource" folder.
Have you tried this option?
C# -- overload function InitializeCulture
protected override void InitializeCulture()
{
try
{
string langID = "fr-FR";
Thread.CurrentThread.CurrentUICulture = new CultureInfo(langID);
base.InitializeCulture();
}
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
}
}
ASP --> <%$ Resources:[resource directory name],[resource label name] %>
<asp:Label runat="server" ID="lblAboutText" Text="<%$ Resources:UCMain,lblAboutTextResource1 %>" ></asp:Label>

Button click is not working in usercontrol Umbraco

I started to build a website using Umbraco and I noticed that button click events (and probably other events) are not working.
I created simplest usercontrol with one button, added it to a page, When I debug it the Page_Load is called (breakpoint being hit), but not button click.
The code is very standard, but here it is:
.aspx file
<%# Control Language="C#" AutoEventWireup="true" CodeFile="TestControl.ascx.cs" Inherits="usercontrols_TestControl" %>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
and code behind:
protected void Button1_Click(object sender, EventArgs e) {
Label1.Text = "Button clicked!";
}
Where can be the problem?
Make sure you are wrapping your body with <form runat="server">...</form> tags, the user control/macro should be inside the form tags. Also ensure that you are adding the user control correctly. To help you out with this, here are a few resources:
A demo by Niels Hartvig. (Niels is using a current Umbraco version.)
Tim Geyssens' screencast. (Tim is using an older version of Umbraco in the screencast (not 4.7.*), but there isn't much difference.)
Step-by-step instructions by Skiltz.

Nullref Exc. on label detected by intellisense?

Okay so I'm quite new to ASP.NET and the MasterPage concept and there's an error I just can't figure out.
This is a part of my default.aspx:
<asp:Content ID="ContentLoginContent" ContentPlaceHolderID="LoginContentPlaceHolder" runat="server">
<div id="ContentLoginDiv">
You've got <asp:Label ID="MemberCreditLabel" runat="server" Text="0"></asp:Label> credits.
</div>
This is the relevant part of my default.aspx.cs:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
if (User.IsInRole("Authenticated"))
{
MemberCreditLabel.Text = "hello ";
}
}
}
I get a Nullref exception on MemberCreditLabel. It gets detected with intelliSense. I think the problem could be that the ContentPlaceHolder "ContentLoginContent" only shows when logged in. This is a part of my MasterPage:
<asp:LoginView ID="MemberLoginView" runat="server">
<AnonymousTemplate>
<asp:Login ID="LogInBox" runat="server" Height="137px" style="margin-left: 0px"
Width="16px">
</asp:Login>
</AnonymousTemplate>
<LoggedInTemplate>
Welcome <asp:LoginName ID="MemberLoginName" runat="server" /> !
<asp:LoginStatus ID="MemberLoginStatus" runat="server" />
<asp:ContentPlaceHolder ID="LoginContentPlaceHolder" runat="server">
//Is this the problem?
</asp:ContentPlaceHolder>
</LoggedInTemplate>
</asp:LoginView>
What I want to do is to show a credit amount stored in a database. The function for retreiving the data I want works. I take the user name of the currently logged in user and want to get the credit amount associated with the user. But this strange error with the label halts me completely.. It's probably got to do with a concept of MasterPages that I haven't stumbled across yet. Any ideas?
Apparently this is by design:
This is by design. The content control replaces the content of the contentplaceholder control which is inside a template. Thus the textbox actually gets instatiated in a template and thus needs to be looked up using FindControl - direct access will not be available.
Thanks,
The WebPlatform and Tools Team.
However, using a recursive FindControl, I wasn't able to actually get hold of the control inside the LoggedInTemplate - indeed in the markup of the Page, ReSharper was complaining that it couldn't resolve the symbol "LoginContentPlaceHolder" - i.e. it couldn't find the content placeholder correctly on the MasterPage.
Is there any way you could display the credits on all authenticated pages?
Or, you could wrap the LoginView with just a LoggedInTemplate containing the credit count into a usercontrol, and drop that inside the content placeholder.

Categories