Error when pass a directory path - c#

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

Related

Shorten links created using asp:repeater and Buildlink(Eval

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;

URL where user come from ASP.Net but have NULL

I want to know-from what url user come from.
So, i use
Uri MyUrl = Request.UrlReferrer;
But when i get only null value from MyUrl:
I have two projects-first is my aspx page, second- redirects to this first project-page with GET parameters.
But when second project redirect to first project- i have :
Object reference not set to an instance of an object.
My second test project so simple:
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect("http://localhost:54287/go.aspx?id=DEFAULT");
}
First and main project:
protected void Page_Load(object sender, EventArgs e)
{
//Request.ServerVariables('http_referer');
// Request.ServerVariables;
string id = Request.QueryString["id"];
if (id != null)
{
Uri MyUrl = Request.UrlReferrer;
Console.WriteLine(MyUrl);
Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
}
}
Error in :Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
OK, there a a few errors:
Your code:
Uri MyUrl = Request.UrlReferrer;
Console.WriteLine(MyUrl);
Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
In the code above you get a NullReferenceException because MyUrl is null.
The UrlReferer may be null, so you have to check this like:
Uri MyUrl = Request.UrlReferrer;
Console.WriteLine(MyUrl);
if (MyUrl != null)
Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
Also you can never make sure that the UrlReferer can have a value, if the user comes from another website you don't know if this website will provide this value, so you have first to assume the referrer is null (in summary never trust it).
Second, when you use Response.Redirect on your code ran server-side you don't know what is the referrer.
I find this question and this question that will help you to better understand.
UrlReferrer is based off the HTTP_REFERER header that a browser should send. But, as with all things left up to the client, it's variable.
I know some "security" suites (like Norton's Internet Security) will strip that header, in the belief that it aids tracking user behavior. Also, I'm sure there's some Firefox extensions to do the same thing.
Bottom line is that you shouldn't trust it. Just append the url to the GET string and redirect based off that.
Reference:
Stackover flow reference

printing some HTML in a string in Asp.net

i have some html content and i stored it in string variable and i want to print it directly.Is there any way in c# ?i have a javascript code which is not working
string emailbody="HTML i need to send";
Page.RegisterStartupScript("StatusMessage", "<SCRIPT LANGUAGE=\"JavaScript\">function printsheet(" + emailbody + "){var win = window.open('mywindow', 'left=0', 'top=0')var html = Zstring; win.document.open()win.document.write(html);win.print();}</Script>");
You have many ways to do that.
One way, make the string public
public string emailbody="HTML i need to send";
and on aspx page you render it as:
<%=emailbody%>
One other way is to use a Literal control and render it there. When you have UpdatePanel this is the only way.
Eg, you place the Literal on page, on the point you wish to render your text as:
<asp:Literal runat="server" id="txtRenderOnMe" />
and on code behind you type:
txtRenderOnMe.Text = "HTML i need to send";
Now, in your case the issue is that you render a string on the javascript code without the quotas as the other jesse point out on their comments.
string emailbody="HTML i need to send";
Page.RegisterStartupScript("StatusMessage", "<script language=\"JavaScript\">function printsheet('" + emailbody + "'){var win = window.open('mywindow', 'left=0', 'top=0')var html = Zstring; win.document.open()win.document.write(html);win.print();}</script>");

Using jQuery .load() with aspx

So I'm fairly new to the .NET framework, but what I'm trying to do is execute the following jQuery code:
$(document).on('click', 'a[data-link]', function () {
var $this = $(this);
url = $this.data('link');
$("#imagePreview").load("imageProcess.aspx?"+url);
where url holds something like "model=2k01&type=black&category=variable".
Unfortunately this doesn't work, becuase when I do something as simple as a Response.Write() in the aspx file, the div tag imagePreview doesn't do anything. However, removing the ? + url part works, but then I can't send any data over to the aspx file. I'm doing it this way because every link a[data-link] has different data that's being sent over, and I need to find a dynamic way to achieve this. Any suggestions would be much appreciated.
UPDATE:
Here is the part in my html code that is generating the url stuff:
<a class='modelsBlue' href = '#' data-link='model=" + $(this).find('model').text() + "&type=" + category + "'>" + $(this).find("model").text() + "</a>
and #image preview is in my code as:
<div id = "imagePreview"></div>
When I try to run the code above, i get the following error which seems to be coming from the jQuery.js file:
Microsoft JScript runtime error: Syntax error, unrecognized expression: &type=AutoEarly
Here is the imageProcess.aspx.cs file, which right now is just outputting all images in the directory:
namespace ModelMonitoring
{
public partial class imageProcess : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("test");
foreach (var f in Directory.GetFiles(Directory.GetCurrentDirectory()))
{
Response.Write(f);
Response.Write("<br />");
}
}
}
}
SECOND UPDATE:
I don't get the error running in chrome or firefox, but the files are not being output.
Turns out it was a whitespace issue. I had to add a wrapper around:
$(this).find('model').text()
to read:
$.trim($(this).find('model').text())
becuase the xml file I was reading from had whitespace around the model name. Thanks to anyone who replied!

Why are backward slashes removed from querystring - ASP.NET & Javascript

I am trying to generate a URL that contains a UNC path as one of the query string variables. The URL will open in a pop up window when an ASP.NET button control is clicked by the user. When the clicks the button, the backwards slashes are removed from the UNC path causing the page to break.
The button renders correctly in the page source file with all the backward slashes.
Is there any way to prevent this?
Here is my source code:
Code behind:
string unc = #"\\myserver\myfolder\myfile.txt";
string url = string.Format("http://www.mysite.com/page.aspx?a={0}", unc);
MyButton.Attributes.Add("onclick", #"javascript:FullPop('" + url + #"')");
ASPX page
<script language="javascript" type="text\javascript">
function FullPop(Newurl) {
Win = window.open( Newurl,"Monitor", "fullscreen=0,toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1,width=800,height=600,top=50,left=50");
Win.focus();
}
</script>
<asp:button id="MyButton" runat="server" cssclass="mycss" text="View Actual Target" />
Update
Server.UrlEncode does not work. Same behavior.
Update 1
Based on Daniel Lew's answer, I developed the following solution:
protected void Page_Load(object sender, EventArgs e)
{
string unc = #"\\myserver\myfolder\myfile.txt";
string url = string.Format("http://www.mysite.com/page.aspx?a={0}", unc);
MyButton.Attributes.Add("onclick", #"javascript:FullPop('" + this.EscapeforJavaScript(url) + #"')");
}
private string EscapeforJavaScript(string url)
{
return url.Replace(#"\", #"\\");
}
You have to URL encode the value that you put in the URL:
string url = "http://www.mysite.com/page.aspx?a=" + Server.UrlEncode(unc);
Edit:
To safely put the url in the Javascript code, you also have to encode the string for being a literal string:
MyButton.Attributes.Add("onclick", #"FullPop('" + url.Replace(#"\", #"\\").Replace("'", #"\'") + #"')");
(The javascript: protocol is only used when the Javascript is used as href for a link, not when you put code in an event like onclick.)
I don't know anything about asp.net, but I have had experience with problems when adding text straight into JavaScript before through templating. Have you tried escaping the backslashes on your url, to avoid this?
// Returns "\myservermyfoldermyfile.txt", due to escpaing the backslash.
alert("\\myserver\myfolder\myfile.txt");
// Returns correct value of "\\myserver\myfolder\myfile.txt"
alert("\\\\myserver\\myfolder\\myfile.txt");
You may want to try URLEncoding your string on your server side, using the following method:
public static string UrlFullEncode(string strUrl)
{
if (strUrl == null)
return "";
strUrl = System.Web.HttpUtility.UrlEncode(strUrl);
}
I'm not 100% sure it if will replace the backslashes, but it's worth a try.

Categories