ASP.NET string resource to lower case? - asp.net

I'm including a string resource in an ASPX:
<asp:Literal runat="server" Text="<%$ Resources:Global, MyString %>"/>
Let's say the value of MyString is "Home". How can I convert that to lower case ("home") in the resource tag? E.g., I don't want to have to store both upper/title and lower case variants of the string in the resource file.
I realize I could do this normally (outside a control) like this:
<%= Resources.Global.MyString.ToLower() %>
But that doesn't help when I have to use a resource for some property of a control. I was hoping to be able to do something simple such as:
<asp:Literal runat="server" Text="<%$ (Resources:Global, MyString).ToLower() %>"/>

I ended up building my own ExpressionBuilder which uses the built-in ResourceExpressionBuilder to get the underlying resource value and then convert it to lower case:
Convert the Base Expression to a Lower-case String
public class ResourceLowerCase : ResourceExpressionBuilder
{
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
{
CodeExpression getResourceExpression = base.GetCodeExpression(entry, parsedData, context);
CodeMethodInvokeExpression toStringExpression = new CodeMethodInvokeExpression(getResourceExpression, "ToString");
CodeMethodInvokeExpression toLowerExpression = new CodeMethodInvokeExpression(toStringExpression, "ToLower");
return toLowerExpression;
}
}
Register the Expression Builder
<system.web>
<expressionBuilders>
<add expressionPrefix="ResourceLowerCase" type="My.Project.Compilation.ResourceLowerCase"/>
</expressionBuilders>
</compilation>
Invoke the Expression Builder
<asp:Literal runat="server" Text="<%$ ResourceLowerCase:Global, MyString %>" />

Have you tried:
<asp:Literal runat="server" Text="<%$ Code:
GetGlobaloResources("MyString").ToString().ToLower() %>"/>
Just pseudo code.
Update:
http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx
Just use the CodeExpressionBuilder from above link.

Related

formatting and number using Xpath and Xmldatasource

when i try to format number in asp repeater. I am using Xpath and XMl datasource. It Does not say any error, but i just keeps it, without any decimals.
<asp:Repeater ID="rptCvrInfo" OnItemDataBound="rptCvrInfo_ItemDataBound" runat="server" DataSourceID="DataSource1">
<itemtemplate>
<asp:Label ID="lblEquity" Text='<%# FormatAmount( XPath("Equity") )%>' runat="server" />
</itemtemplate>
</asp:Repeater>
My codebehind method
public static string FormatAmount(object In)
{
Decimal amount = Decimal.Parse(In.ToString(), new NumberFormatInfo() { NumberDecimalSeparator = "," });
return amount.ToString();
}
xmlnode from document
<Equity contextRef="ctx37" unitRef="DKK" decimals="-3">101015000
Assuming that 101015000 is the value you want to convert to Decimal, you have to return a formatted string from you method. All you are doing now is convert it to a decimal and then send it back exactly as it was. You can return a formatted decimal as a string.
return string.Format("{0:N2}", amount);
Or inline without a method in code behind
<%# string.Format("{0:N2}", Convert.ToDecimal(XPath("Equity"))) %>
See https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings

Set TemplateField HeaderText dynamic for localization

I am trying to create localization for my ASP.NET code, but I have issues setting the TemplateField's HeaderText
I have this that works
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<%# Eval("Description") %>
</ItemTemplate>
<FooterTemplate>
<asp:Panel ID="Panel5" runat="server" DefaultButton="EditSubmission">
<asp:TextBox runat="server" ID="Submission_DescriptionTxtBox" TextMode="MultiLine"
ToolTip='<%# GetById("atforbedringsforslag_description_tooltip") %>'/>
</asp:Panel>
</FooterTemplate>
</asp:TemplateField>
But I want to change
<asp:TemplateField HeaderText="Description">
To
<asp:TemplateField HeaderText='<%# GetById("atforbedringsforslag_description_title") %>'>
But then I get
Databinding expressions are only supported on objects that have a DataBinding event. System.Web.UI.WebControls.TemplateField does not have a DataBinding event.
How should I set this field? I can find some that uses OnRowCreated, but then you access the fields with an index number, and then it becomes easy to make mistakes or forgot to change indexes if new fields are added later on
EDIT My solution:
Created the custom expression builder
using System.Web.Compilation;
using System;
using System.CodeDom;
public class LocalizationExpressionBuilder : ExpressionBuilder
{
public override CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
{
CodeExpression[] inputParams = new CodeExpression[] { new CodePrimitiveExpression(entry.Expression.Trim()),
new CodeTypeOfExpression(entry.DeclaringType),
new CodePrimitiveExpression(entry.PropertyInfo.Name) };
// Return a CodeMethodInvokeExpression that will invoke the GetRequestedValue method using the specified input parameters
return new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(this.GetType()),
"GetRequestedValue",
inputParams);
}
public static object GetRequestedValue(string key, Type targetType, string propertyName)
{
// If we reach here, no type mismatch - return the value
return GetByText(key);
}
//Place holder until database is build
public static string GetByText(string text)
{
return text;
}
}
Added the prefix to my web.config
<system.web>
<compilation debug="true" defaultLanguage="c#" targetFramework="4.0">
<expressionBuilders>
<add expressionPrefix="localizeByText" type ="LocalizationExpressionBuilder"/>
</expressionBuilders>
</compilation>
</system.web>
And I can now get my text like this
<asp:TemplateField HeaderText='<%$ localizeByText:Some text %>'>
You can build your own custom Expression Builder which calls your GetById method. Look at the following link for an old but good article explaining how to build an expression builder and how to use it:
https://web.archive.org/web/20210304125044/https://www.4guysfromrolla.com/articles/022509-1.aspx
When you have an expression builder, you use it with the <%$ syntax. This is different from the databinding syntax <%#.
For the HeaderText field, it is not allowed to use DataBinding syntax (not sure why, but that's how MS made it). Using expression syntax IS allowed and will work once you have your custom expression builder done.
Do go through the page I linked to, it's quite a lot of text, but in the end making you expression builder will not take much effort...
Also, the page has a link at the bottom to a library of expression builder that the author has made. Have a look at them, maybe one of them could be used directly to solve your problem (specifically, the CodeExpressionBuilder).

HTTPContext.Current.User.Identity.Name not working inside a control?

I have a label and I want to set text of this label to
HTTPContext.Current.User.Identity.Name
So I wrote
Text = '<%=HTTPContext.Current.User.Identity.Name %>'
but it doesn't work, however when I wrote this outside of the lable for example:
<h2>
<%=HTTPContext.Current.User.Identity.Name %>
</h2>
it works.
<asp:Label ID="lbUserName"
runat="server"
Text='<%# HttpContext.Current.User.Identity.Name %>'
/>
in Page_Load
if (!Page.IsPostBack )
{
lbUserName.DataBind();
}
use label like this
<asp:label id="lblx" runat="server" ><%= HTTPContext.Current.User.Identity.Name %></asp:label>
To bind the text like this you will have to create your own custom expression builder.
First, add such class to your namespace:
using System.Web.Compilation;
using System.CodeDom;
[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : ExpressionBuilder
{
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, ExpressionBuilderContext context)
{
return new CodeSnippetExpression(entry.Expression);
}
}
Next step is adding this to your web.config file:
<compilation debug="true">
<expressionBuilders>
<add expressionPrefix="Code" type="YourNameSpace.CodeExpressionBuilder"/>
</expressionBuilders>
</compilation>
Then finally this should work:
<asp:Label id="YourLabel" runat="server" Text='<%$ Code:HttpContext.Current.User.Identity.Name %>' />
Complicated way to achieve something simple, but this will allow you to use the syntax you want throught your whole project so might worth the extra effort.
Reference.

Add text after expression <%$ ... %>

In my ASPX page I've this:
<h3>
<asp:HyperLink runat="server"
NavigateUrl="<%$ Resources:Path, Article%>"
Text='<%# Eval("title") %>' />
</h3>
For the NavigateUrl attribute I want to specify an ID like
NavigateUrl="<%$ Resources:Path, Article%>?id=4"
But when I do that the expression is not precessed by the ASP parser.
How can I do that?
Don't do this in markup. You have a server control here -- give it an ID (say, ID="NavigationLink", and then do something like this in your .cs file:
void Page_Load(object sender, EventArgs e)
{
// I'm guessing that "4" was just an example here, so fill that piece in with a function you can call to create the proper ID.
NavigationLink.NavigateUrl = Properties.Resources.Path + Properties.Resources.Article + "?id=4"
}
Edit: I'm assuming that when you say <%$ Resources:Path, Article%> that you're trying to reference the Path and Article entries in your resources file, but upon further reflection, it's hard to tell exactly what you're doing. Can you be more specific here?
You can define a protected function in the code behind class and call it from the markup. Like this:
<h3>
<asp:HyperLink runat="server"
NavigateUrl="<%# GetNavigateUrl(Eval("ID")) %>" <%-- Passing an ID as a parameter for example --%>
Text='<%# Eval("title") %>' />
</h3>
Code behind:
// Again, idObj is just an example. Any info from the data item can be passed here
protected string GetNavigateUrl(object idObj)
{
int id = (int)idObj;
string urlFromResources = // retrieving the url from resources
return urlFromResources + '?ID=' + id;
}
You could retrieve the resource values programmatically, in your code-behind, and set the NavigateUrl property from there.
Try String.Format...
<% =String.Format({0}?id={1}, Request.ApplicationPath, 4) %>
It looks like you're mixing some other language into this (javascript?).
Also, don't forget to give your server-side controls an ID.

Can I use <%= ... %> to set a control property in ASP.NET?

<asp:TextBox ID="tbName" CssClass="formField" MaxLength="<%=Constants.MaxCharacterLengthOfGameName %>" runat="server"></asp:TextBox>
The code above does not work. I can set the MaxLength property of the textbox in the code behind but i rather not. Is there away I can set the MaxLength property in the front-end code as above?
You could use DataBinding:
<asp:TextBox
ID="tbName"
CssClass="formField"
MaxLength="<%# Constants.MaxCharacterLengthOfGameName %>"
runat="server">
</asp:TextBox>
and in your code behind Page_Load call:
tbName.DataBind();
or directly databind the page:
this.DataBind();
The <%= expression %> syntax is translated into Response.Write(expression), injecting the value of expression into the page's rendered output. Because <%= expression %> is translated into (essentially) a Response.Write these statements cannot be used to set the values of Web control properties. In other words, you cannot have markup like the following:
<asp:Label runat="server" id="CurrentTime" Text="<%= DateTime.Now.ToString() %>" />
Source: https://web.archive.org/web/20210513211719/http://aspnet.4guysfromrolla.com/articles/022509-1.aspx
Try to use custom expression builder:
// from http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx
[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : System.Web.Compilation.ExpressionBuilder
{
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, ExpressionBuilderContext context)
{
return new CodeSnippetExpression(entry.Expression);
}
}
And then use it like
<asp:TextBox ID="tbName" CssClass="formField" MaxLength="<%$ Code: Constants.MaxCharacterLengthOfGameName %>" runat="server"></asp:TextBox>
As Ropstah said, it isn't going to work with the <%= expression %> syntax.
But you could probably use databinding, which just requires that you use the <%# expression %> syntax and then call MyTextBox.Databind in CodeBehind.
Of course, at that point it might be more clear to just do the whole operation in CodeBehind.
Another alternative: if you really want this to be declarative, you could get away from the Label and embed your expression in a span tag.That way you still get to apply CSS, etc and I think the <%= expression %> syntax would work.
Why don't you just set it in the Page_Init callback function in the code behind?
This example is geared towards getting the max length from underlying sql types in linq. But you should be able to customise it to your needs
http://blog.binaryocean.com/2008/02/24/TextBoxMaxLengthFromLINQMetaData.aspx
It looks like you want to be able to control the max length of a specific type of text box from a single location so that if that max length needs to change, you only need to change it in one place.
You can accomplish this by using a skin file. You set the max length in the skin file as you would normally and then any textbox that uses that max length would use the skin. If the length changes then you only need to change the skin file.
You can do it with databinding
<asp:TextBox
ID="tbName"
CssClass="formField"
MaxLength='<%# Constants.MaxCharacterLengthOfGameName %>'
runat="server" />
Then in the code behind
protected void Page_Load(object sender, EventArgs e) {
Page.DataBind();
}
You can embed "normal" code in the .aspx file if you so want, like:
<%
tbName.MaxLength = Constants.MaxCharacterLengthOfGameName
%>
<asp:TextBox ID="tbName" CssClass="formField" runat="server"></asp:TextBox>
This harkens back to an older style "classic" ASP way of doing this.

Resources