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

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.

Related

Accessing web config value from asp:ListItem

I'm trying to print the value I have stored in the web config as text for a list item.
<asp:ListItem Enabled="true" Selected="true" Text="Web Only - <%$ AppSettings:SubscriptionPrice %>"
Value="web" />
will give me: Web Only - <%$ AppSettings:SubscriptionPrice %>
However, if I remove the Web Only text and do this:
<asp:ListItem Enabled="true" Selected="true" Text="<%$ AppSettings:SubscriptionPrice %>"
Value="web" />
I'll get the variable desired. Is there a way to have the text and the value from my appsettings?
You cannot do it inline that easily. Your options are:
Set the complete value in your AppSettings. (easy)
Set the value from code behind. (easy)
Lastly, if you want to be in ASPX and nothing else is acceptable, you need to write a CodeExpressionBuilder so that you can provide custom code, as follows: (may be an overkill)
here is the code expression builder
namespace Funky
{
[System.Web.Compilation.ExpressionPrefix("Code")]
public class CodeExpressionBuilder : System.Web.Compilation.ExpressionBuilder
{
public override System.CodeDom.CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, System.Web.Compilation.ExpressionBuilderContext context)
{
return new System.CodeDom.CodeSnippetExpression(entry.Expression);
}
}
}
add this web.config entry
<compilation debug="true" targetFramework="4.5">
<expressionBuilders>
<add expressionPrefix="MyCode" type="Funky.CodeExpressionBuilder"/>
</expressionBuilders>
</compilation>
finally use the code expression as follows:
<asp:ListItem Enabled="true" Selected="true" Text='<%$ MyCode: "Web Only - " + ConfigurationManager.AppSettings["SubscriptionPrice"] %>' Value="web" />
I'm not sure you can do this on page, but you can do this in your code file:
ListItem item = new ListItem();
item.Text = "Web Only - " + System.Configuration.ConfigurationManager.AppSettings["SubscriptionPrice"];
item.Value = "web";
item.Selected = true;
ListBox1.Items.Add(item);
Sorry about the earlier post.
I think you are going to have to bind the value is code.
ddl.Items.Clear()
ddl.Items.Add(New ListItem("Web Only -" & ConfigurationManager.AppSettings("SubscriptionPrice"), "Web"))

Add HTML5 placeholder text to a textbox .net

I have a standard input:
<asp:TextBox type="text" runat="server" id="txtSearchTerm" />
I'd like to have this render with a dynamic HTML5 placeholder. Something like:
'Code Behind
txtSearchTerm.**placeholder** = "Search " + Site.Name
So that it outputs the following HTML:
<input type="text" runat="server" id="txtSearchTerm"
placeholder="Search Site #1" />
where Site.Name = "Site #1".
txtSearchTerm.placeholder is not a property. I have it set to text and then run javascript to show/hide on focus BUT I would much rather just use the HTML5 placeholder value. How can I render this?
Please no JS/client side solutions.
You could use the Attributes collection. So you would have something like
txtSearchTerm.Attributes.Add("placeholder", "Search" + Site.Name);
or
txtSearchTerm.Attributes["placeholder"] = "Search" + Site.Name; // or Attributes("placeholder") if you're using vb.net
And if you're using resources for localization/translation:
txtSearchTerm.Attributes["placeholder"] = GetLocalResourceObject("YourLocalResourceName").ToString();
Because I find it annoying/tiresome to add all the placeholders from the code behind. You can create a new TextBox Class that inherits the WebControls TextBox and then you can add the placeholder from the CodeBehind or from the HTML Side.
TextBox.cs (Placed in Project/Controls/)
namespace Project.Controls
{
public class TextBox : System.Web.UI.WebControls.TextBox
{
public string PlaceHolder { get; set; }
protected override void OnLoad(EventArgs e)
{
if(!string.IsNullOrWhiteSpace(PlaceHolder))
this.Attributes.Add("placeholder", PlaceHolder);
base.OnLoad(e);
}
}
}
Register Control In the Web.Config:
<system.web>
<pages>
<controls>
<add tagPrefix="ext" assembly="Project" namespace="Project.Controls" />
</controls>
</pages>
</system.web>
(use whatever tag prefix you want)
Usage:
<ext:TextBox runat="server" id="SomeId" PlaceHolder="This is a PlaceHolder" />
or from the code behind
SomeId.PlaceHolder="This is a PlaceHolder";
I just put placeholder property in HTML code and works:
<asp:TextBox placeholder="hola mundo" ID="some_id" runat="server"/>
There is also the TextBoxWatermark extender included in Microsoft's Ajax Control toolkit. It's not HTML5, but it's backwards compatible (I believe).
http://www.asp.net/AjaxLibrary/AjaxControlToolkitSampleSite/TextBoxWatermark/TextBoxWatermark.aspx
<ajaxToolkit:TextBoxWatermarkExtender ID="TBWE2" runat="server"
TargetControlID="TextBox1"
WatermarkText="Type First Name Here"
WatermarkCssClass="watermarked" />

ASP.NET string resource to lower case?

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.

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).

Is it possible to create a generic Util Function to be used in Eval Page

I am currently binding a Nullable bit column to a listview control. When you declare a list view item I need to handle the case when the null value is used instead of just true or false.
<asp:Checkbox ID="Chk1" runat="server"
Checked='<%# HandleNullableBool(Eval("IsUsed")) %>' />
Then in the page I add a HandleNullableBool() function inside the ASPX page.
protected static bool HandleNullableBool(object value)
{
return (value == null) ? false : (bool)value;
}
This works fine but I need to use this in several pages so I tried creating a utility class with a static HandleNullableBool. But using it in the asp page does not work. Is there a way to do this in another class instead of the ASPX page?
<asp:Checkbox ID="Chk1" runat="server"
Checked='<%# Util.HandleNullableBool(Eval("IsUsed")) %>' />
You can simply write
<asp:Checkbox ID="Chk1" runat="server"
Checked='<%# Eval("IsUsed") ?? false %>' />
To answer your question, you need to include the namespace that contains the class, like this: (at the top of the file)
<%# Import Namespace="Your.Namespace.Here" %>
You can also do this in Web.config:
<pages>
<namespaces>
<add namespace="Your.Namespace.Here" />
</namespaces>
</pages>

Resources