Shorten links created using asp:repeater and Buildlink(Eval - c#

I have asked a question similar to this before, where I needed the link changed to something else, but I actually need to shorten the link instead of replacing it.
So I need to shorten links, when they are longer than...say...50 characters. I know how to change the link but can't figure out how to shorten it.
For example: http://www.google.com would shorten to something like http://google...
My code:
<%# BuildLink(Eval("TaskDefinition.Url").ToString(),Eval("TaskInstanceID").ToString())%>
I've done this, which replaces the link. But I need to shorten it, instead of replacing it.
<asp:HyperLink runat="server"
NavigateUrl='<%# BuildLink(Eval("TaskDefinition.Url").ToString(), Eval("TaskInstanceID").ToString())%>'>
My Link
</asp:HyperLink>
My BuildLink method:
public string BuildLink(string baseUrl, string taskInstanceId)
{
if (!string.IsNullOrEmpty(baseUrl))
{
string parms =
"taskinstanceid=" + taskInstanceId +
"&callback=" + GetCallBackUrl();
string url = baseUrl.Contains("?")
? baseUrl + "&" + parms
: baseUrl + "?" + parms;
bool isUnc = false;
try
{
Uri uri = new Uri(baseUrl);
isUnc = uri.IsUnc;
}
catch { }
string link;
if (isUnc)
{
link = "<a href='" + baseUrl + "' >" + baseUrl + "</a>";
}
else
{
link = "<a href='" + url + "' >" + baseUrl + "</a>";
}
return link;
}
return "";
}
This is the current view. Everything where it belongs
This is the view that's generated with the code JF gave
Also, the links are shortened even though they aren't 50> which is odd... I dislike asp repeaters.

An <asp:Hyperlink> also gives you the ability to set the text to be displayed. So similar to how you build the link, you can also trim the text.
First, set the text attribute. You can also remove the text from in between the hyperlink tags as the text attribute does this for you.
<asp:HyperLink runat="server"
NavigateUrl='<%# BuildLink(Eval("TaskDefinition.Url").ToString(), Eval("TaskInstanceID").ToString())%>'
Text='<%# TrimLink(Eval("TaskDefinition.Url").ToString(), Eval("TaskInstanceID").ToString())%>'>
</asp:HyperLink>
Then, create your code behind method. In this method, do you logic to get the full text of the URL that will be displayed. Check the length of that text. If the length is longer than 50, Substring() it to 50 characters and concatenate some ellipsis onto it.
public string TrimLink(string baseUrl, string taskInstanceId)
{
string urlText = "";
// do your logic to get the full url
if(urlText.Length > 50)
{
urlText = urlText.Substring(0, 50);
urlText = urlText + "...";
}
return urlText;
}
Instead of returning an entire hyperlink to be used as the URL for the <asp:Hyperlink>, try returning just the URL instead. I'm wondering if all the extra characters are unintentionally being used as closings for other controls. In BuildLink, do this instead.
if (isUnc)
{
link = baseUrl;
}
else
{
link = url;
}
return link;

Related

Error when pass a directory path

In start page: I want to pass a directory path to a popup window page when client click on LinkButton lbtnEditText
<asp:LinkButton ID="lbtnEditText" runat="server" Text="Edit Text" CommandArgument='<%# Eval("Path") + "," + Eval("Name")%>' OnCommand="Button1_Click"></asp:LinkButton>
And the code behind:
protected void Button1_Click(object sender, CommandEventArgs e)
{
string[] values = e.CommandArgument.ToString().Split(',');
string queryString =
"editpage.aspx?path="
+ values[0];
string newWin =
"window.open('" + queryString + "');";
ClientScript.RegisterStartupScript
(this.GetType(), "pop", newWin, true);
}
The queryString exactly is = "editpage.aspx?path=D:\\C#Projects\\website\\Lecturer\\giangvien\\profile.xml" (I check it when I debug)
But In destination page (popup window): editpage.aspx
string path = Request.QueryString["path"];
string content = File.ReadAllText(path);
if(content!=null)
textarea.Value = content;
It has an error: Could not find file 'D:\C#Projects\website\C
Try to debug, the path I recieved is just only : "D:C"
And in the address bar of editpage.aspx display:
http://localhost:41148/website/editpage.aspx?path=D:C#ProjectswebsiteLecturergiangvienprofile.xml
Help!!! Why is the path changed when I pass it to the editpage???
The reason behind happening so is :: you are passing query string data which is having unexpected characters which are '\,#'.
The solution to this is escape and encode this values before setting as query string values
Encoding Urls correctly is unfortunately required skill for anyone doing web development...
Everything after # is "hash" portion of Url and browser don't need to send it to server. More formal name is fragment identifier.
What you need to do is encode value of path query parameter correctly (i.e. with encodeURIComponent funcition in JavaScript).
To give you the actual solution for C#:
string queryString = "editpage.aspx?path=" + System.Web.HttpUtility.UrlEncode(values[0]);
see reference for encoding http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx
and decoding http://msdn.microsoft.com/en-us/library/system.web.httputility.urldecode%28v=vs.110%29.aspx

String that came from Request.Url.ToString() misteriously changes to another string when manipulating/comparing the first characters

I'm aware that there are easier ways to do this and believe me, I've tried them. I'm of course open to any suggestions =). You don't need to read the whole code, just the part that says where the problem lies. Also, I'm debbugging perl style so you guys can see. Oh and did I mention that on my development environment everything works as intended?
Here's the code:
string GetPortalAlias()
{
String myURL2 = Request.Url.ToString();
URLLabel.Text = "Original Request.Url.ToString() returned: \"" + myURL2 + "\"";
string myURL = string.Copy(myURL2);
URLLabel.Text = "Copying it to myURL, it's now: \"" + myURL + "\"";
myURL = myURL.ToLower().Trim();
URLLabel.Text += "<br>Trimming and ToLower myURL.<br>The new url is \"" + myURL + "\"" + "<br>";
myURL = myURL.Replace(":80", "");
URLLabel.Text += "Replacing the \":80\".<br> The new url is\"" + myURL + "\"<br>";
//***HERE LIES THE PROBLEM***
myURL = myURL.Replace("http://", "");
URLLabel.Text += "Replacing the \"http://\".<br> The new url is\"" + myURL + "\"<br>";
//***PROBLEM ENDS***
myURL = myURL.Remove(myURL.IndexOf("/"));
URLLabel.Text += "Removing everything after the \"/\"." + "<br> The new url is \"" + myURL + "\"<br>";
URLLabel.Text += "<br>GetPortalAlias Returning \"" + myURL + "\"";
return myURL;
}
Believe it or not, the output produced in the webpage is this:
Copying it to myURL, it's now: "http://sar.smg.com.ar/Default.aspx?TabID=912"
Trimming and ToLower myURL.
The new url is "http://sar.smg.com.ar/default.aspx?tabid=912"
Replacing the ":80".
The new url is"http://sar.smg.com.ar/default.aspx?tabid=912"
Replacing the "http://".
The new url is"intranetqa/default.aspx?tabid=912"
Removing everything after the "/".
The new url is "intranetqa"
GetPortalAlias Returning "intranetqa"
So... for some reason whenever it reaches the replace section it mysteriously mutates to start with "intranetqa" instead of "sar.smg.com.ar". "intranetqa" is our default hostname. CHANGING OR TAKING AWAY ANY CHARACTER OF HTTP:// IN ANY WAY MUTATES THE STRING.
I do a string.copy because I'm aware that if two strings are equal the compiler stores them in the same place therefore I wanted to prevent errors. Taking those lines away and use Request.Url.ToString() tomyURL directly does nothing at all. They were just a test to see if that worked.
Here's a list of the things I've tried:
All combinations of string / String, none worked.
I've tried Request.Host.Url and it just gave me "intranetqa".
I've used Request.Url.AbsoluteUri and that's why I have the replace
:80 line.
USING THE .tochararray FUNCTION GIVES ME BACK THE INTRANETQA THING
myURL = myURL.Substring(6) gives back the intranetqa thing.
string.Contains("sar.smg.com.ar") gives back false.
I believe the trick lies around here:
Uri uriAddress1 = Request.Url; and "The parts are <br>" + "Part 1: " + uriAddress1.Segments[0] + "<br>Part 2: " + uriAddress1.Segments[1]; Gives Part1 : "/" and Part 2: "Default.aspx". Trying to access part 3 (index 2) gives an exception.
The request.url does not have the first part, but when I call the ToString() method, it does have like a "fake" first part
Between your browser and the server are a reverse proxy and an output re-writer. These may be the same component, or separate components.
The URL your server actually sees is always of the form http://intranetqa/default.aspx?tabid=912 (after the reverse proxy/URL re-writer has intercepted the request).
The output your server produces is actually like:
Copying it to myURL, it's now: "http://intranetqa/Default.aspx?TabID=912"
Trimming and ToLower myURL.
The new url is "http://intranetqa/default.aspx?tabid=912"
Replacing the ":80".
The new url is"http://intranetqa/default.aspx?tabid=912"
Replacing the "http://".
The new url is"intranetqa/default.aspx?tabid=912"
Removing everything after the "/".
The new url is "intranetqa"
GetPortalAlias Returning "intranetqa"
The output re-writer is inspecting the output from your server and doing a replace of http://intranetqa with http://sar.smg.com.ar. Once you strip the http:// off of the front of these strings, it's no longer a match and so replacement no longer occurs.
If you want to know what the original requesting URL/host are, hopefully the reverse proxy either is, or can be configured to, adding an extra header to the request with the original URL.
You can try something like this
Uri uriAddress1 = new Uri("http://www.contoso.com/title/index.htm");
Console.WriteLine("The parts are {0}, {1}, {2}", uriAddress1.Segments[0], uriAddress1.Segments[1], uriAddress1.Segments[2]);
Uri.Segments Property
This is better way to handle URIs and their segments.
Try to use this property instead:
String myURL2 = Request.Url.AbsoluteUri;
Here is an Extension method that I use to pull the SiteRootPath. You should be able to easily adjust it however you need it. You will need access to the HttpContext for what I currently have below, however, you don't sound like you need that.
using System;
using System.Web;
namespace FlixPicks.Web.Extensions
{
public static class HttpContextExtensions
{
public static string SiteRootPath(this HttpContext context)
{
if (context == null || context.Request == null) { return null; }
return context.Request.Url.SiteRootPath(context.Request.ApplicationPath);
}
public static string SiteRootPath(this HttpContextBase context)
{
return context.Request.Url.SiteRootPath(context.Request.ApplicationPath);
}
private static string SiteRootPath(this Uri url, string applicationPath)
{
if (url == null) { return null; }
// Formatting the fully qualified website url/name.
string appPath = string.Format(
"{0}://{1}{2}{3}",
url.Scheme,
url.Host,
url.Port == 80 ? string.Empty : ":" + url.Port,
applicationPath);
// Remove ending slash(es) if one or more exists to consistently return
// a path without an ending slash. Could have just as well choosen to always include an ending slash.
while (appPath.EndsWith("/") || appPath.EndsWith("\\"))
{
appPath = appPath.Substring(0, appPath.Length - 1);
}
return appPath;
}
}
}
Good luck,
Tom
Don't you want to achieve part of what is done here?
Something like
string host = Request.Url.IsDefaultPort ?
Request.Url.Host :
Request.Url.Authority;
If you want to persist with the old method change it like this
string GetPortalAlias()
{
var rawUrl = Request.Url.ToString();
var lowerTrimmedUrl = rawUrl.ToLower().Trim();
var withoutPortUrl = lowerTrimmedUrl.Replace(":80", "");
var withoutProtocolUrl = withoutPortUrl.Replace("http://", "");
var justHostUrl = withoutProtocolUrl.Remove(myURL.IndexOf("/"));
var evolution = new StringBuilder();
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(rawUrl));
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(lowerTrimmedUrl));
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(withoutPortUrl));
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(withoutProtocolUrl));
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(justHostUrl));
URLLabel.Text = evolution.ToString();
return justHostUrl;
}
So you can see whats going on.

how to preview a html file from database to a browser using C#

I have HTML code stored in a database and would like to display (render) it onto a view.
I wanted to show it as a normal text page.
eg: **HTML:** <h3 style="font-weight: bold">Usage:</h3>
<p style="text-decoration: underline">Viewing of Form -</p>
Should be shown as: Usage:
Viewing of Form -
I have a button as view and when clicked, it should show me the page.
I am using entity frame work so i have written,
string url = ("view.aspx?id = " + page.ID + "&Text=" + page.Text);
ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "window.open( '" + url + "', null, 'height=500,width=800,status=yes,toolbar=yes,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=yes' );", true);
and i have created a new page view.aspx and tried to use System.Web.HttpUtility.HtmlDecode(Request.QueryString["Text"]) to render the file.
But i am getting a blank page.
Please help me.
Thanks,
Can you confirm that page.Text has a value when it's being rendered?
If you are certain that the value page.Text is populated correctly (I'm assuming something like "view.aspx?id=1&Text=<h3>example post<h3>") then you may want to try encoding the string for the URL before returning it to the client.
string url = ("view.aspx?id = " + page.ID + "&Text=" + System.Web.HttpUtility.UrlEncode(page.Text));
ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "window.open( '" + url + "', null, 'height=500,width=800,status=yes,toolbar=yes,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=yes' );", true);
Then make sure that you are getting encoded characters in your links on the client.

How to make a function into a class or module in c#

I am just learning how to use classes in my projects. I have been working on a DataAccessClass.cs and am doing well (I think).
Taking a break from data access, I decided to try to make a void into a class. This void sends a message to the client as a javascript alert. It works well, but has to be included on each page. When I tried to make it a class, I was informed that my class does not contain a definition for ClientScript. I included all the "using" directives from the original page to no avail... Any hints or suggestions would be greatly appreciated.
The original code:
//------------------------------------------------------------------------------
//Name: SendErrorMessageToClient
//Abstract: show alert on client side
//------------------------------------------------------------------------------
protected void SendErrorMessageToClient(string strErrorType, string strErrorMessage)
{
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = "<script type=\"text/javascript\" language=\"javascript\">alert( '" + strErrorType + "\\n\\n" + strErrorMessage + "' );</script>";
this.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}
Messages are sent into this void like this:
if (DataAccessClass.OpenSqlConnection(ref Conn, strConn, out strErrorMessage) == false)
{
string strErrorType = "Database Connection Error:";
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
Or this:
catch (Exception excError)
{
string strErrorType = "Unhandled Exception:";
string strErrorMessage = excError.Message;
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
You are receiving the error as 'Clientscript' is a property derived from a System.Web.UI.Page and by moving into a separate class file, you no longer have access to this property.
You could solve this by passing in the page as well, and amending the code to
protected void SendErrorMessageToClient(string strErrorType, string strErrorMessage, Page page)
{
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = "<script type=\"text/javascript\" language=\"javascript\">alert( '" + strErrorType + "\\n\\n" + strErrorMessage + "' );</script>";
page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}
ClientScript Property is part of the Page class that every ASPX page inherit from. Therefore you can not just use it from inside your class unless it (i.e. your class) has Page as its base class.
this. is for fields in your method in classes.
Why do you want to make this a class? It shouldn't be a class, it doesn't have any properties or fields, unless you can think of one. You do understand if you make it a class you would still have to intialize it on every page.
You could make it a static string method you would still have to include this on every page.
this.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
You'll need to pass the page into the function
SendErrorMessageToClient(Page page, string strErrorType, string strErrorMessage)
so that you can change
this.ClientScript...
to
page.ClientScript...
The reason being that ClientScript is part of the Page class
Or, possibly better, pass the ClientScript object, rather than page.
So your definition would look like
SendErrorMessageToClient(ClientScript clientScript, string strErrorType, string strErrorMessage) {
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = String.Format("<script type='text/javascript' language='javascript'>alert('{0}\\n\\n{1}');</script>",
strErrorType, strErrorMessage);
clientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}

ASP.NET - How to write some html in the page? With Response.Write?

I need that some html in the area in the asp.net page that i am coding, is changed according to a string variable.
I was thinking about creating a label, and then change the text on it.
But the string variable contains something like:
<h2><p>Notify:</p> alert</h2>
So, I don't feel that give this to a label text is a good idea
How i can do?
Using response.write?
If I use response.write, my added code will be at the beginning of the html source, how i can tell him to add it in a specific ?
Thank you
If you really don't want to use any server controls, you should put the Response.Write in the place you want the string to be written:
<body>
<% Response.Write(stringVariable); %>
</body>
A shorthand for this syntax is:
<body>
<%= stringVariable %>
</body>
why don't you give LiteralControl a try?
myLitCtrl.Text="<h2><p>Notify:</p> Alert</h2>";
If you want something lighter than a Label or other ASP.NET-specific server control you can just use a standard HTML DIV or SPAN and with runat="server", e.g.:
Markup:
<span runat="server" id="FooSpan"></span>
Code:
FooSpan.Text = "Foo";
ASPX file:
<h2><p>Notify:</p> <asp:Literal runat="server" ID="ltNotify" /></h2>
ASPX.CS file:
ltNotify.Text = "Alert!";
Use a literal control and write your html like this:
literal1.text = "<h2><p>Notify:</p> alert</h2>";
You should really use the Literal ASP.NET control for that.
You can go with the literal control of ASP.net or you can use panels or the purpose.
You can also use pageMethods in asp.net. So that you can call javascript functions from asp.net functions. E.g.
[WebMethod]
public static string showTxtbox(string name)
{
return showResult(name);
}
public static string showResult(string name)
{
Database databaseObj = new Database();
DataTable dtObj = databaseObj.getMatches(name);
string result = "<table border='1' cellspacing='2' cellpadding='2' >" +
"<tr>" +
"<td><b>Name</b></td>" +
"<td><b>Company Name</b></td>" +
"<td><b>Phone</b></td>"+
"</tr>";
for (int i = 0; i < dtObj.Rows.Count; i++)
{
result += "<tr> <td><a href=\"javascript:link('" + dtObj.Rows[i][0].ToString().Trim() + "','" +
dtObj.Rows[i][1].ToString().Trim() +"','"+dtObj.Rows[i][2]+ "');\">" + Convert.ToString(dtObj.Rows[i]["name"]) + "</td>" +
"<td>" + Convert.ToString(dtObj.Rows[i]["customerCompany"]) + "</td>" +
"<td>"+Convert.ToString(dtObj.Rows[i]["Phone"])+"</td>"+
"</tr>";
}
result += "</table>";
return result;
}
Here above code is written in .aspx.cs page. Database is another class. In showResult() function I've called javascript's link() function.
Result is displayed in the form of table.

Categories