I have a key-value pair defined in the Web.Release.config and Web.Debug.config for a url.
In the C# file I use it like so (key is "Report-URL"):
string reportUrl = System.Configuration.ConfigurationManager.AppSettings["Report-URL"];
CoverSheetReportViewer.ServerReport.ReportServerUrl = new Uri(reportUrl);
This works but now I want to use it in a .ascx file where I currently have the url hardcoded:
<asp:HyperLink ID="HyperLinkReports" runat="server" CssClass="LeftNav"
NavigateUrl="http://mygroup-dev-appsr/ReportServer?%2fASD%2fTransactions%2fCoverSheet&rs:Command=ListChildren" />
How do I do this?
Try this with help of Inline Syntax
NavigateUrl="<%$ AppSettings:Report-URL %>
or
In .ascx
Report
in .ascx.cs
protected string GetReportUrl(){
string reportUrl = System.Configuration.ConfigurationManager
.AppSettings["Report-URL"];
return new Uri(reportUrl).ToString();
}
Another Syntax Reference
Related
I need to keep using a list box to do this as there are a number of other dependencies on the control being a list box.
Ultimately I want each list item to consist of 3 distinct URL's so:
Url1 Url2 Url3
which would be HTML of:
<ul>
<li>Url1Url2Url3</li>
</ul>
So in my ASPX page I am maintaing there is already:
<asp:BulletedList ID="lstDashboards" runat="server" DisplayMode="Text"</asp:BulletedList>
And in code behind I have the following to populate the list:
private void GuiSideMenuBuild(Int64 aUserId)
{
//Always clear any dashboards
lstDashboards.Items.Clear();
//Get the dashboards from the database
DashboardsForUserGetDto userDashboards = DashboardBL.Instance.DashboardsForUserGet(Convert.ToInt32(aUserId));
const string HREF_DASHBOARD_EDIT = "Edit...";
const string HREF_DASHBOARD_DELETE = "Delete...";
foreach (TableDashboardDashboardDtoBase userDashboard in userDashboards.Dashboards)
{
string listItemText = userDashboard.Title;
if (userDashboard.DashboardId == DashboardId)
listItemText += HREF_DASHBOARD_EDIT + HREF_DASHBOARD_DELETE;
ListItem listItem = new ListItem
{
Text = listItemText,
Value = Convert.ToString(userDashboard.DashboardId),
Selected = userDashboard.DashboardId == DashboardId
};
lstDashboards.Items.Add(listItem);
}
}
However the HTML that the control is producing has escaped all the supplied HTML so that I end up with something like:
<<a href="#" id="...
which means that the resulting HTML is "broken" and the URL's don't work. So my question is:
How can I keep using the existing list box (ie. asp:BulletedList) but supply it Text for the item so that it will produce valid HTML so that I can have 3 separate URL's?
I have already tried HTML Encoding the string before adding it to listItem.Text but that makes no difference.
I don't see any need for a UserControl here - you don't use any server-side components, you're just generating markup. Why not just do this in your .aspx page?
<ul>
<% foreach (TableDashboardDashboardDtoBase userDashboard in userDashboards.Dashboards)
{
%>
<li>Url1Url2Url3</li>
<%
}
%>
</ul>
Either that, or use a repeater:
HTML
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate><ul></HeaderTemplate>
<ItemTemplate><li>Url1Url2Url3</li></ItemTemplate>
<FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
Code Behind
Repeater1.DataSource = userDashboards.Dashboards
Repeater1.DataBind()
This code:
<asp:TextBox runat="server" MaxLength="<%=Settings.UsernameMaxLength %>" ID="Username"/>
Throws a parser error.
Is it possible to set properties in any way similar to this without using the code behind?
No, it is not possible. Syntax <%= some code here %> cannot be used with server-side controls. You can either go with <%# some code here %>, but only in case of data binding, or just set this property in code behind, say on Page_Load:
protected void Page_Load(object source, EventArgs e)
{
Username.MaxLength = Settings.UsernameMaxLength;
}
You may try this, which should set the MaxLength value upon rendering :
<%
Username.MaxLength = Settings.UsernameMaxLength;
%>
<asp:TextBox runat="server" ID="Username"/>
I think (not tried) you can also write :
<asp:TextBox runat="server" MaxLength="<%#Settings.UsernameMaxLength %>" ID="Username"/>
But you would then need to call Username.DataBind() somewhere in the codebehind.
I'm late to the party here, but here goes anyway...
You could build your own Expression Builder to handle this case. That would allow you to use syntax like this:
<asp:TextBox
runat="server"
MaxLength="<%$ MySettings: UsernameMaxLength %>"
ID="Username"/>
Note the $ sign.
To learn how to make you own Expression Builder, please go through this old but still relevant tutorial. Don't let the wall of text scare you off because in the end, making an expression builder is easy. It basically consists of deriving a class from System.Web.Compilation.ExpressionBuilder and overriding the GetCodeExpression method. Here is a very simple example (some parts of this code was borrowed from the linked tutorial):
public class SettingsExpressionBuilder : System.Web.Compilation.ExpressionBuilder
{
public override System.CodeDom.CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, System.Web.Compilation.ExpressionBuilderContext context)
{
// here is where the magic happens that tells the compiler
// what to do with the expression it found.
// in this case we return a CodeMethodInvokeExpression that
// makes the compiler insert a call to our custom method
// 'GetValueFromKey'
CodeExpression[] inputParams = new CodeExpression[] {
new CodePrimitiveExpression(entry.Expression.Trim()),
new CodeTypeOfExpression(entry.DeclaringType),
new CodePrimitiveExpression(entry.PropertyInfo.Name)
};
return new CodeMethodInvokeExpression(
new CodeTypeReferenceExpression(
this.GetType()
),
"GetValueFromKey",
inputParams
);
}
public static object GetValueFromKey(string key, Type targetType, string propertyName)
{
// here is where you take the provided key and find the corresponding value to return.
// in this trivial sample, the key itself is returned.
return key;
}
}
In order to use it in your aspx page, you must also register it in web.config:
<configuration>
<system.web>
<compilation ...>
<expressionBuilders>
<add expressionPrefix="MySettings" type="SettingsExpressionBuilder"/>
</expressionBuilders>
</compilation>
</system.web>
</configuration>
This is just to show you that it's not difficult. But please review the tutorial I linked to in order to see an example of how to deal with the expected return type from your method depending on the property being assigned etc.
I have the following code in an asp Gridvidiew:
<asp:HyperLink ID="hlPSTNNum" CssClass="OrdRef" Text='<%# DataBinder.Eval(Container.DataItem, "PSTNNum")%>' runat="server" ToolTip='please click here to view the full record details'
NavigateUrl='<%#"https://THE URL IS HERE Searches/advancedsearchresults.asp?supplierid=" + Eval("Supplierid") + "&display1=IS%20Number&display2=Supplier&display3=Product&display4=Supplier%20Order%20Number&order1=order%20date&pstnnum=" + Eval("PSTNNum")%>' />
I think Visual Studio 2012 is playing up about the semicolons in the query string part (from "pstnnum=" + Eval("PSTNNum")%>' />" and i tried to escape them with \ (that keeps VS happy), but the browser leaves one of the slashes in at each escape.
Not sure the best practice here as im still cutting my coding teeth...
I think the more appropriate approach would be something like this:
<asp:HyperLink ID="hlPSTNNum"
CssClass="OrdRef"
Text='<%# DataBinder.Eval(Container.DataItem, "PSTNNum")%>'
runat="server"
ToolTip='please click here to view the full record details'
NavigateUrl='<%#Server.HtmlEncode("https://THE URL IS HERE Searches/advancedsearchresults.asp?supplierid=" + Eval("Supplierid") + "&display1=IS Number&display2=Supplier&display3=Product&display4=Supplier Order Number&order1=order date&pstnnum=" + Eval("PSTNNum"))%>' />
Note the use of Server.HtmlEncode and then the use of the actual values you want rather than the directly encoded values. This will make it easy to build in Visual Studio, but ensure it gets encoded when it's rendered.
EDIT
After some more research into Microsoft's code I found that the base RenderContents method for the HyperLink class is going to encode this for you. That method, internally, calls another one called ResolveClientUrl, which looks like this:
public string ResolveClientUrl(string relativeUrl)
{
if (this.DesignMode && this.Page != null && this.Page.Site != null)
{
IUrlResolutionService urlResolutionService = (IUrlResolutionService)this.Page.Site.GetService(typeof(IUrlResolutionService));
if (urlResolutionService != null)
{
return urlResolutionService.ResolveClientUrl(relativeUrl);
}
}
if (relativeUrl == null)
{
throw new ArgumentNullException("relativeUrl");
}
string virtualPathString = VirtualPath.GetVirtualPathString(this.TemplateControlVirtualDirectory);
if (string.IsNullOrEmpty(virtualPathString))
{
return relativeUrl;
}
string text = this.Context.Request.ClientBaseDir.VirtualPathString;
if (!UrlPath.IsAppRelativePath(relativeUrl))
{
if (StringUtil.EqualsIgnoreCase(text, virtualPathString))
{
return relativeUrl;
}
if (relativeUrl.Length == 0 || !UrlPath.IsRelativeUrl(relativeUrl))
{
return relativeUrl;
}
}
string to = UrlPath.Combine(virtualPathString, relativeUrl);
text = UrlPath.AppendSlashToPathIfNeeded(text);
return HttpUtility.UrlPathEncode(UrlPath.MakeRelative(text, to));
}
Since you're URL is not relative it should fall all the way to the last line, the return statement, so honestly you shouldn't have to encode it at all. This changes your code to this:
<asp:HyperLink ID="hlPSTNNum"
CssClass="OrdRef"
Text='<%# DataBinder.Eval(Container.DataItem, "PSTNNum")%>'
runat="server"
ToolTip='please click here to view the full record details'
NavigateUrl='<%#"https://THE URL IS HERE Searches/advancedsearchresults.asp?supplierid=" + Eval("Supplierid") + "&display1=IS Number&display2=Supplier&display3=Product&display4=Supplier Order Number&order1=order date&pstnnum=" + Eval("PSTNNum")%>' />
Not 100% sure if this will work, but asp.net 4.5 has <%#: which encodes automatically. you can try that and see if it works, just change the <%# to <%#:
I'm trying to work with a class that has a child object, which has a string - and I'm trying to access this with in-line C# code on my aspx page.
More specifically, let's say I'm working with an object of 'Upload' class which has a Title property (String). An Upload object can also have a 'File' property (object). And each File object has a Url property (String).
I can access the Title like so:
<%# ((Upload)Container.DataItem)["Title"] %>
That works fine. But then how do I access a File's Url? Because the following does not work:
<%# ((File)((Upload)Container.DataItem)["File"]).Url %>
As you may be able to guess from the syntax, this is all within an asp repeater.
try this:
<%# ((Upload)Container.DataItem).File.Url %>
You get the container dataitem & cast it. Once you have the object, you can call it's properties & methods like any other object
you might try something like
<%# Bind("File.Url") %>
or
<%# DataBinder.Eval(Container.DataItem, "File.Url") %>
I am just giving you a sample, you can implmement the same on your own:-
First create a server side code to to return a URL of the File.
Then call that function from client side to get the URL of the title passed to the same.
Below is an example which returns the text with the suffix dots
Step 1 : Create server side code to return text with suffix dots
public string ReturnDotSuffix(string strValue, int iFontSize, int iWidth)
{
string strReturnValue = string.Empty;
try
{
CommonLib objCommonLib = new CommonLib();
strReturnValue = objCommonLib.SuffixDots(strValue, iFontSize, iWidth);
}
catch (Exception ex)
{
HandleException.ExceptionLogging(ex.Source, ex.Message, true);
}
return strReturnValue;
}
Step 2: Call this from Client Side.
Text='<%# ReturnDotSuffix((string)DataBinder.Eval(Container.DataItem, "MessageTitle"),8,170) %>'
The same can be done in your case.
I am attempting to fill in an ASP.NET page textbox with some predefined text so that when it is displayed the value is predefined. I have tried
protected void Page_PreRender ()
{
mytextbox.Text = somestring;
}
which works fine in the development environment but on the server produces...
System.NullReferenceException: Object reference not set to an instance of an object
The same applies when I try this in Page_Load. As I read the answers to this question, what I am trying should work (in at least one of these places).
Can anyone see what I am doing wrong?
EDIT more code, as suggested. The C# looks like this:-
protected void Page_PreRender (Object sender, EventArgs e)
{
try
{
string [] file_list;
int i = 0;
file_list = Directory.GetFiles(MyProg.Common.GetDirectory(),
MyProg.Common.GetFileNameRoot() + "*.*");
foreach (string filename in file_list)
{
string filenameonly = Path.GetFileName (filename);
if (filenameonly == MyProg.Common.GetFileNameRoot() + "runlog.log")
{
nametextbox.Text = filenameonly;
}
}
}
catch (Exception ex)
{
string mystring = ex.ToString();
errorMessage.Text = "Page Load Error : " + mystring;
}
}
and the ASP.NET page like this...
<%# Page Language="C#"
AutoEventWireup="true"
CodeBehind="MyDialogue.aspx.cs"
Inherits="MyDialogue" %>
<%# Register assembly="ComponentArt.Web.UI"
namespace="ComponentArt.Web.UI"
tagprefix="ComponentArt" %>
<%# Register assembly="ComponentArt.Web.Visualization.Charting"
namespace="ComponentArt.Web.Visualization.Charting"
tagprefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
</head>
<body>
<form id="myForm" runat="server">
<div style="visibility:hidden">
<asp:TextBox ID="nametextbox"
TextMode="MultiLine"
runat="server"
Visible="true" />
</div>
</form>
</body>
</html>
Did you publish your site but did the filerefence to the codebehind stay in the aspx page?
are you sure the dll in the bin folder?
This should work without complaint. Does the mytextbox control have the runat="server" attribute? You can only access from the codebehind stuff with the runat="server" attribute.
There could be several areas that are causing this problem. How are you sure that you've narrowed it down to the textbox itself? Was this code completely bug-free before adding the textbox message? I'll post your code below with where I think potential null references may be occurring (in comments):
string [] file_list;
int i = 0;
file_list = Directory.GetFiles(MyProg.Common.GetDirectory(),
MyProg.Common.GetFileNameRoot() + "*.*");
// it is possible that file_list is null
// potentially due to an invalid path (missing / perhaps?)
foreach (string filename in file_list)
{
string filenameonly = Path.GetFileName (filename);
// It's possible that the MixedZone.Kernel.Common library
// is experiencing the null reference exception because it
// may not understand what file to get the name root of or
// maybe it is not capable of getting the root for some
// other reason (permissions perhaps?)
if (filenameonly == MixedZone.Kernel.Common.GetFileNameRoot() + "runlog.log")
{
nametextbox.Text = filenameonly;
}
Some possible solutions or safer code:
string [] file_list;
int i = 0;
file_list = Directory.GetFiles(MyProg.Common.GetDirectory(),
MyProg.Common.GetFileNameRoot() + "*.*");
if (file_list == null) throw new Exception("File List is null. Something is wrong.");
foreach (string filename in file_list)
{
string filenameonly = Path.GetFileName (filename);
string fileroot = MixedZone.Kernel.Common.GetFileNameRoot();
if(string.IsNullOrEmpty(fileroot) throw new Exception("MixedZone Library failed.");
if (filenameonly.Equals(fileroot + "runlog.log", StringComparison.OrdinalIgnoreCase)) // Choose your own string comparison here
{
nametextbox.Text = filenameonly;
}
Run with Antivirus disabled on the Production Server?
Compare .Net versions between Production and Development?
"which works fine in the development environment but on the server produces" - so, permissions or missing files perhaps?