Display image from database in ASP.net with C# - asp.net

I know this kind of question has been asked many times.
Yet I don't succeed in displaying an image from my db on a page.
I tried the following method.
protected void Page_Load(object sender, EventArgs e)
{
//Get the picture id by url
//Query here
byte[] picture = queryoutput;
Response.ContentType = "image/jpeg";
Response.BinaryWrite(picture);
}
Link to get the image.
<asp:Image runat="server" ImageUrl="~/givememypicture.aspx?pic=3" ID="testimage" />
The <asp:Image /> tag is located in between <asp:Content > tags.
When I run this code and check in firebug, it simply states 'Failed to load fiven URL'.
I also tried putting the Respone.Con...(picture); part into a public method and call that method with the byte var given.
I'm quite new to asp.net, but I have somewhat more experience in c#.
I start to really dislike asp.net... I have been struggling with this for about 20 hours already and tried a lot of options, yet none worked.
The best would be if I could just fill in the picture via the codefile from that same page. It seems quite illogical to me to call another page to load the image from.
Can somebody please tell me what I'm doing wrong here?
Solution: Master page reference removed from the page directive on the page that handles the image response. Also removed everything else except for the #page directive itself within the aspx file.

try using a handler file (.ashx) put the code form your page_load in that lie so
public void ProcessRequest (HttpContext context) {
//Get the picture id by url
//Query here
byte[] picture = queryoutput;
Response.ContentType = "images/jpeg";
Response.BinaryWrite(picture);
}
public bool IsReusable {
get {
return false;
}
}
then call the handler file and pass the correct querystring items from the
this should then work

There's an error in your path reference...
ImageUrl="/~givememypicture.aspx?pic=3"
should be:
ImageUrl="~/givememypicture.aspx?pic=3"
~ is shorthand for "the application root" and needs to be followed by a slash to indicate that it's a directory. Think of it as similar to other path shorthand notations such as . and ...

Make sure you call Response.Flush(); and also Response.End(); and see if that does the trick
Also, your content type has a misspelling. Is not "images/jpgeg" I think it's "image/jpeg"
EDIT: Yes, I just confirmed in Wikipedia that the correct content-type is image/jpeg.

I do this all the time. Here's some sample code:
Response.ContentType = "image/jpeg";
Response.BinaryWrite(bytes);
That's all there is too it. If it's not working, then something is probably wrong with your data.
A flush is not required. I have working code for this open on my screen right now.
I would suggest that you try writing that buffer of data to a file and see if it opens up as a valid picture. I bet something's wrong with that data.
Also, it's a good idea to enable browser side caching for your dynamic content. Here's a GREAT link that shows exactly how to do that, which will boost your performance / scalability a lot.
http://edn.embarcadero.com/article/38123

Related

ASP.NET "application/pdf": code runs only once

I'm working on a SharePoint 2013 site and I've added the ability to save pages in PDF. The PDF conversion is handled by the third party library SelectPdf.
I managed to get everything to work (rendering and file download), except that the "PDF Download" button that I have on my page works only 1 time. Meaning, the click event on the code behind is fired only once, no matter how many times I click the button (notice that I click it with intervals of 10+ seconds). If I want to download the PDF file again, I have to refresh the page.
I put together a "hello world" example (see below) in order to pinpoint the problem:
protected void lnkPdfDownload_Click(object sender, EventArgs e)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=test.pdf");
/************************************ Create PDF File ************************************/
string html = #"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"">
<html dir=""ltr"" lang=""en-US"">
<body><h1>Hello World</h1></body>
</html>";
HtmlToPdf converter = new HtmlToPdf();
PdfDocument doc = converter.ConvertHtmlString(html);
byte[] bytes = doc.Save();
Response.OutputStream.Write(bytes, 0, bytes.Length); // ALTERNATIVE: doc.Save(Response.OutputStream);
/************************************ Create PDF File ************************************/
//Response.End(); // This throw a ThreadAbortException, therefore I'm using the alternative code below
Response.Flush();
Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
At the beginning I thought it was Response.End() that caused the issue (by throwing the ThreadAbortException), but I replaced it with other code and I still have the same problem (no exceptions are thrown now).
I don't think the problem is in the SelectPdf library: I can comment out the entire block (between the "Create PDF File" comments), and I still get the same thing (obviously no PDF is generated).
I noticed that, at most, I can successfully click the "download" button up to 2 times (it's rare, and not consistent): the third time nothing happens.
While this isn't a huge deal, I think there is something wrong going on that I'm not seeing. Here is why: after I click the "download" button (and get my PDF file), I am not able to go on edit mode in my SharePoint page. The "loading" message keeps spinning but nothing happens (again, unless I refresh the page).
Has anyone had this problem? I looked online but I couldn't find anything about it.
I'm using Internet Explorer 11 and Chrome 51. Please let me know if you need more information. Thank you.
Are you sure there are not javascript/jquery errors happening when the download button is clicked that prevent the re-clicking of the PDF button and also going into edit mode?
Especially since refreshing the page makes everything work again.

Issues with Kendo MVVM file upload control

I was trying to get a Kendo MVVM file upload working along with ASP.NET. This is how my HTML looks for the upload declaration:
<input name="attachments"
id="fileUpload"
type="file"
data-role="upload"
data-async="{ saveUrl: 'FileUpload.aspx', autoUpload: true }"
data-bind="events: { success: onSuccess,error: onError }">
and the FileUpload page load:
Response.Expires = -1;
//Code to upload -- This returns me the file url that i need to send back as a response
Response.ContentType = "text/plain";
Response.Write(fileUrl);
Response.End();
The page load written above does function as expected and return me the desired result but the kendo control here behaves in a funny manner. It tells me that the upload is unsuccessful as in the error icon shows up on the UI. Moreover it is the error handler provided by Kendo that is executed though the written response is returned properly when I try accessing it as:
e.XMLHttpRequest.responseText
Well I guess I might have missed out something/done some small mistake here or there but unfortunately I am not able to figure the same out. Anyone who could possibly suggest/correct?
Well it seems that the response for the file upload control should be empty or a JSON string otherwise it is treated as an error. I changed the Response text to thus:
Response.Write(new JavaScriptSerializer().Serialize(fileUrl));
to resolve.
Hope this helps someone else!

Access to the path is denied C# error

I want my user to be able to hit the submit button and have a string write into a css file. When I hit the submit button, I am getting the error message:
Access to the path 'C:/.....' is denied
This happens when running the site from localhost and on my hosting (123reg)
protected void btnSubmit(object sender, EventArgs e)
{
using (StreamWriter writer = new StreamWriter("B00101168.css"))
{
writer.Write("Word ");
writer.WriteLine("word 2");
}
}
The first problem is, you can't write to a file without setting permissions on the folder. See this link for details. Essentially, you must give the Internet Guest Account permission to write to the folder.
But, the bigger problem is, you probably shouldn't be trying to dynamically write a CSS file anyway. At least, not the way you are trying to do it. Can you explain why you are trying to dynamically change a CSS file on your server? If you can explain what you are trying to accomplish, I might have some suggestions on how to do it that work better than what you are trying to do.
UPDATE: You're using WebForms, and you're trying to dynamically generate CSS. So here's one way to do that.
Use a generic page handler -- a file that ends in .ashx. You dynamically create the CSS however you're doing it now, but instead of writing it to a file, you output it directly to the browser. Here is some (untested!) code:
In the DynamicStyles.ashx file, there is basically nothing to add from what it automatically generates.
In the DynamicStyles.ashx.cs file:
public void ProcessRequest( HttpContext context )
{
StringBuilder css = new StringBuilder();
// Use the StringBuilder to generate the CSS
// however you are currently doing it.
context.Response.ContentType = "text/css";
context.Response.Write( css.ToString() );
}
Then, in your code that needs the CSS file, include it just like you would any other CSS:
<link rel="stylesheet" type="text/css" href="/path/to/DynamicStyles.ashx">

asp.net - Hyperlink not working

protected void Button1_Click(object sender, EventArgs e)
{
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(#"C:\Documents and Settings\Admin\Desktop\New Folder\"+TextBox1.Text);
foreach (System.IO.FileInfo file in dir.GetFiles())
{
HyperLink h = new HyperLink();
h.NavigateUrl = "file:///c:/Documents and Settings/Admin/Desktop/New Folder/" + TextBox1.Text + "/" + file.Name;
h.Text = file.Name;
PlaceHolder1.Controls.Add(h);
}
}
On execution of this code hyperlinks get generated but they are not working.
nothing happens when i click on them.
Please help.
In ASP.NET hyperlinks must be URLs not a folder on the computer.
If your file is in your site try Sever.MapPath
This is due to security restrictions in the browser. If you generate a "file://" link, it is relative to the user's file system.
Theoretically, if browsers allowed these types of links, attackers could discover information about a user's file system remotely. Thus, modern browsers do not allow this type of link.
Unfortunately this is not very well documented, and most browsers allow the links and just drop the behaviour - so nothing happens when you click them. There aren't any good workarounds either.
See my question here for further discussion.
Check out this question. The solution may work for you too.
I have found that (in the context of redirecting to another one of your own web pages) using this:
compontent.NavigateUrl = "~/page.aspx";
instead of this:
compontent.NavigateUrl = server.MapPath("path");
worked for me. The server.MapPath created a File:// link so that it was not allowed by the browser.
Hope this helps someone, it won't work in some cases but it worked for my individual requirements.

How to generate HTML in a Pop Up window with Asp.Net

I have very simple html report generated from one of my objects on server. I generate html code at PageLoad because I need to clear that object from session and don't want ask external web service for data after user clicks on link button.
Roughly idea is that user clicks on button on page and the report will be displayed at new window.
As I said I have html generated at PageLoad and right now stored in unique file at server. I also thought that I could hide the html code in hidden control. But that wont work without extra work, that would convert html code into some nonsense string and restored later on.
I can manage to display my html code into current window by using Response.Write(myhtml as string);
So my question are:
where could I store my html code beyond file system (that is tricky with security issues)
how to display my htmlcode into new window on click event. What way could I use.
I found one possible solution described here.
UPDATE:
Just adding pieces of code. It displays html string in current window which is not exactly I want.
private void InitData(){
string filename = DateTime.Now.ToString("yyyyMMdd_HHmmssfff");
lbtnPrintOutOrder.CommandArgument = filename;
StreamWriter swXLS = new StreamWriter((MapPath("Files\\")) + filename);
string message = GetEmail();//get data form session object
swXLS.Write(message);//save data to file
swXLS.Close();
}
protected void lbtnPrintOutOrder_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
{
string filePath = (MapPath("Files\\")) + e.CommandArgument.ToString();
string content;
using (StreamReader reader = File.OpenText(filePath)) {
content = reader.ReadToEnd();//get html from file
}
Response.Write(content);//load it to current window
Response.End();
}
One big question, is why do you need to clear the object from Session? Why cant you keep the object in session until after the string is displayed in the new window?
You could open an aspx page in the new window, use the string object stored in the session to output the html, and clear the session once the html is displayed.

Resources