I want to achieve that a file that is described by URL or network drive (N:\ESSBP1-Office\Imagenes\Check list.xlsx) can be opened through a browser by using the resonse.redirect function in c#.
BUT: This only works for me if the path doesn't contain a space.
How can I avoid the encoding? If I type that same path into the InternetExplorer the address - with space - is resolved correctly and the file is opened.
I didn't manage to avoid the encoding with the response.redirect function. Server.UrlEncode() didn't do that neither, as it just adds another unwanted encoding, while I wanted the exact content of a TextBox/Label to be the string passed to the browser's URL-bar, followed by hitting the enter key - which should be done through code.
I finally achieved that, following #Richard Housham´s suggestion using Javascript:
Mark-up:
<asp:TextBox id="TB_ExternalLink" runat="server"/>
<asp:LINKButton ID="LB_Open" runat="server" OnClick="OpenLink">Open Link</asp:LINKButton>
<input type="hidden" runat="server" id="hiddenExternalFile"/>
Code:
protected void OpenLink(object sender, EventArgs e)
{
string url = TB_ExternalLink.Text.Replace(#"\\", #"\\");
hiddenExternalFile.Value = url;
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "windowOpen()", true);
}
Javascript:
function windowOpen() {
Window = window.open(document.getElementById('hiddenExternalFile').value, "_blank");
}
Opens any link that is typed into the textbox in these formats in a new tab:
http://www.url.com
\\corp.root.int\INT-Host$\USR03\XXX\W10\Desktop\Kaizen MRO\RMA_Part.png
N:\ESSBP1-Office\Imagenes\Check list.xlsx
regardless of spaces or special ASCI characters
Related
I have a textfield which displays a string which contains < and >. The code throws an error because of that. How can I allow the usage of those chars in my textfield?
Thanks :)
Problem is that when this gets posted to server, it will not work, doesn't matter what you try. This is the ASP.NET XSS protection, which can be disabled like so:
<%# Page ... ValidateRequest="false" %>
Trouble is, you'll have to be very careful validating all the postback yourself. Easier way is to escape all the contents of textbox using javascript just before posting. You can escape it using same HTML escaping, then unescape in server side code.
Update:
Example of escaping. This will flash the changed text on screen before postback - ideal solution is to use a hidden field for this, i.e. assign value to a hidden field, instead of that same field. This is the simplest version:
<script>
function EscapeField(){
document.getElementById("your client control ID").value =
escape(document.getElementById("your client control ID").value);
}
</script>
And in code-behind:
this.ClientScript.RegisterOnSubmitStatement(this.GetType(),
"EscapeField", "EscapeField();")
Update:
Again, warning - if you save HTML in your database like this, and then just display it to the client, you are directly vulnerable to XSS attacks. There are worms out there that will find and exploit your web site. Make sure you cleanse the HTML you are getting.
If you're in an asp.net page, you can wrap the whole of the output text in a
Server.HtmlEncode("YourTextWith<and>Characters")
function and it will encode any dodgy characters for you.
If, for some reason, you're doing this in a .cs file, you can use System.Web.HttpUtility.HtmlEncode("YourTextWith<and>Characters")
before passing it to the presentation layer.
Convert them to < and >. In Html, < is converted to < and > is converted to > without it thinking it's part of the markup. So the string <Blah> will be <Blah>.
Edit: I forgot, to automatically convert them and escape all HTML characters (so this isn't an issue for other things), in Asp.net you can use Server.HtmlEncode(string) to automatically convert all characters that could cause issues to their HTML equivalent.
The easiest solution is to disable request validation in single pages
<%# Page ... ValidateRequest="false" %>
but don't forget to enable requestValidationMode="2.0"
<system.web>
...
<httpRuntime requestValidationMode="2.0" />
</system.web>
This solution could espose some threats.
Another smart solution is to replace via javascript text written by user to make it safe for validation: <tag> is considere dangerous, but < tag> is considered safe!
A javascript replacement can solve the problem.
function validateTxt() {
$("textarea, input[type='text']").change(function () {
html = $(this).val(); //get the value
//.replace("a" , "b") works only on first occurrence of "a"
html = html.replace(/< /g, "<"); //before: if there's space after < remove
html = html.replace(/</g, "< "); // add space after <
$(this).val(html); //set new value
});
}
$(document).ready(function () {
validateTxt();
});
<asp:TextBox ID="TextBox1" runat="server"><</asp:TextBox>
I don't know if your question is related to this or if you are getting a validateRequest issue
You can either use the TextBox.Text property which will HTML-encode whatever you enter
<asp:TextBox ID="TextBox1" runat="server" Text="<>"></asp:TextBox>
or you can enter the html names for < and >.
<asp:TextBox ID="TextBox1" runat="server"><</asp:TextBox>
or you can enter the html codes
<asp:TextBox ID="TextBox1" runat="server"><</asp:TextBox>
for the name and code conversions, check out this chart.
your problem is,you cannot use html tags in .net controls. so set the ValidateRequest="false" in your aspx page and encode the text before you saving the text.
//encode
private string Encode(string text)
{
byte[] encodedText = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(encodedText);
}
when you retrieving your text make sure to decode the encoded text.
// Decode:
private string Decode(string encodedText)
{
byte[] decodedText = System.Convert.FromBase64String(encodedText);
return System.Text.Encoding.UTF8.GetString(decodedText );
}
We want to reduce the number of steps it takes for a user to upload a file on our website; so we're using jQuery to open and postback files using the below markup (simplified):
<a onclick="$('#uplRegistrationImage').click();">
Change profile picture
</a>
<!-- Hidden to keep the UI clean -->
<asp:FileUpload ID="uplRegistrationImage"
runat="server"
ClientIDMode="static"
Style="display:none"
onchange="$('#btnSubmitImage').click();" />
<asp:Button runat="server"
ID="btnSubmitImage"
ClientIDMode="static"
Style="display:none"
OnClick="btnSubmitImage_OnClick"
UseSubmitBehavior="False" />
This works absolutely fine in Firefox and Chrome; opening the file dialog when the link is clicked and firing the postback when a file is selected.
However in IE9 after the file upload has loaded and a user has selected a file; insteaed of the OnChange working I get a "SCRIPT5 Access is denied" error. I've tried setting an arbitrary timeout, setting intervals to check if a file is given to no avail.
There are a number of other questions relating to this; however none appear to have a decent answer (One said set the file dialog to be transparent and hover behind a button!)
Has anyone else resolved this? Or is it absolutely necessary that I provide a button for IE users?
For security reasons, what you are trying to do is not possible. It seems to be the IE9 will not let you submit a form in this way unless it was an actual mouse click on the File Upload control that triggers it.
For arguments sake, I was able to use your code to do the submit in the change handler, but it worked only when I clicked the Browse button myself. I even set up polling in the $(document).ready method for a variable set by the change handler that indicates a submission should be triggered - this didn't work either.
The solutions to this problem appear to be:
Styling the control in such a way that it sits behind a button. You mentioned this in your question, but the answer provided by Romas here In JavaScript can I make a "click" event fire programmatically for a file input element? does in fact work (I tried in IE9, Chrome v23 and FF v15).
Using a Flash-based approach (GMail does this). I tried out the Uploadify demo and it seems to work quite nicely.
Styling a File Upload:
http://www.quirksmode.org/dom/inputfile.html
http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom
References:
jQuery : simulating a click on a <input type="file" /> doesn't work in Firefox?
IE9 file input triggering using Javascript
getting access is denied error on IE8
Hey this solution works.
for download we should be using MSBLOB
$scope.getSingleInvoicePDF = function(invoiceNumberEntity) {
var fileName = invoiceNumberEntity + ".pdf";
var pdfDownload = document.createElement("a");
document.body.appendChild(pdfDownload);
AngularWebService.getFileWithSuffix("ezbillpdfget",invoiceNumberEntity,"pdf" ).then(function(returnedJSON) {
var fileBlob = new Blob([returnedJSON.data], {type: 'application/pdf'});
if (navigator.appVersion.toString().indexOf('.NET') > 0) { // for IE browser
window.navigator.msSaveBlob(fileBlob, fileName);
} else { // for other browsers
var fileURL = window.URL.createObjectURL(fileBlob);
pdfDownload.href = fileURL;
pdfDownload.download = fileName;
pdfDownload.click();
}
});
};
This solution looks like it might work. You'll have to wrap it in a <form> and get it to post in the jquery change handler, and probably handle it in form_load using the __eventtarget or and iframe or whatever it is that web forms uses, but it allows you to select a file, and by submitting the form, it should send it. I can't test it however, since I don't have an environment set up at home.
http://jsfiddle.net/axpLc/1/
<a onclick="$('#inputFile').click();">
Change profile picture
</a>
<div id='divHide'>
<input id='inputFile' type='file' />
</div>
$('#inputFile').change(function() { alert('ran'); });
#divHide { display:none; }
Well, like SLC stated you should utilize the <Form> tag.
First you should indicate the amount of files; which should be determined by your input fields. The second step will be to stack them into an array.
<input type="file" class="upload" name="fileX[]"/>
Then create a loop; by looping it will automatically be determined based on the input field it's currently on.
$("input[#type=file]:nth(" + n +")")
Then you'll notice that each file chosen; will replace the input name to the file-name. That should be a very, very basic way to submit multiple files through jQuery.
If you'd like a single item:
$("input[#type=file]").change(function(){
doIt(this, fileMax);
});
That should create a Div where the maximum file found; and attaches to the onEvent. The correlating code above would need these also:
var fileMax = 3;
<input type="file" class="upload" name="fileX[]" />
This should navigate the DOM parent tree; then create the fields respectively. That is one way; the other way is the one you see above with SLC. There are quite a few ways to do it; it's just how much of jQuery do you want manipulating it?
Hopefully that helps; sorry if I misunderstood your question.
I have some text being fetched from the DB, which I am binding to the DataList ItemTemplate in the following form:
<asp:LinkButton runat="server" Text='<%#Eval("url")%>' />
The text that is fetched from the DB might be long and I want to restrict it to (let's say 50 chars at max. with a ... afterwards) in the above eval assignment.
How can this be done here?
Secondly, how do I specify the link here in LinkButton so that on clicking on it, it goes to the specified, the link should open in a new window as in taget=_blank
You can use a tag directly
<a href='<%#Eval("url")%>' taget=_blank> <%# BindText(Eval("url"))%></a>
Codebehind:
public string BindText(obj url)
{
if(url!=null) {return (url.ToString().length > 50) ? url.ToString().Substring(0,50) + '...': url.ToString() ;}
return "";
}
One easy way to handle that would be to create a "Truncate" extension of type String which simply strips X characters from the end of it.
Regarding "target=_blank" - you should be able to accomplish this with the Attributes property of the LinkButton.
Depending on the target browser, using CSS text-overflow is an elegant way to do this at the client instead of the server (maximizes space; only that text which must be truncated will be truncated, and it also takes into account simple punctuation rules).
https://developer.mozilla.org/en/CSS/text-overflow
This blog post shows a decent solution in that it seeks whitespace in which to inject the ellipses (rather than blind truncation).
For setting the target of a LinkButton...
<asp:LinkButton runat="server" target="_blank">
ASP.Net will (usually) ignore attributes that it doesn't recognize and just render them to the client verbatim. However, this won't actually work because a LinkButton is meant to initiate a postback. You can use an anchor tag instead.
Hy,
In my application I store a html code in a string, for example:
string myHtml = "<html><body><input type ='text' value='hello'/></body></html>";
How can I preview this html in another window pressing some button?
<asp:Button ID="PreviewButton" runat="server" Text="Preview" OnClick="PreviewButton_Click"/>
I've tried :
protected void PreviewButton_Click(object sender, EventArgs e)
{
myHtml = "<html><body><input type ='text' value='hello'/></body></html>";
Response.Write(myHtml);
Response.End();
}
And it works, the preview it's opened but in the same window.. does anyone know how can I open it in another window?
Thanks in advance.
Jeff
You could store the source in a javascript string and use window.open and then write to the new window the source.
Remeber to escape the source correctly first.
You can call window.open in Javascript to open a new window showing an ASHX handler that serves your HTML. (you may need to pass information on the query string)
Remember to set the Response.ContentType in the handler.
I have an ASP.NET web application and at a certain point I do this:
mycontrol.stringparameterforjscript = "document.getElementById('" + myotherparam + "').value = 'Hello'";
The problem is that this thing does not work.
As you can see this sets a javascript in some event of some tag. Well when the page is redered the problem is that my parameter look like this:
<textarea onfocus="document.getElementById('myvalue').value = 'Hello'"></textarea>
I must precise that this textbox I'm trying to set is located inside a InsertItemTemplate of a ListView and it is not so easy to intialize. For this reason I inserted my initialization code that you see inside the load event handler of my textbox. I can say you one thing: If this code referred to a text box located freely in the page and I called this piece of code from the load event handler of the page, this would work well. But I do not know how to do in this particular case.
I'm also considering the possibility to create a webcntrol to handle such a problem. I don't really know what's the best practice in this case.
I think you might need the # on both string literals in your assignment, and remove the slashes:
mycontrol.stringparameterforjscript = #"document.getElementById('" + myotherparam + #"').value = 'Hello'";
EDIT
How I did it:
On the .aspx:
<asp:Textbox ID="tbTest" runat="server" TextMode="MultiLine" />
In the code:
protected void Page_Load(object sender, EventArgs e)
{
string myotherparam = "paramval";
tbTest.Attributes.Add("onfocus", #"document.getElementById('" + myotherparam + #"').value = 'Hello'");
}
Resultant output:
<textarea name="tbTest" rows="2" cols="20" id="tbTest" onfocus="document.getElementById('paramval').value = 'Hello'"></textarea>
OK, I finally managed it. HTML Encoded strings recognized by the javascript engine, how's it possible?
As you will see there is nothing to worry about in what happens.