How to consume an asp.net image resizer with javascript - c#

I use javascript/jquery to fill with html a web page. In IE works fine but in Firefox or Chrome the image is not shown wherever the image is shown when i click only the link:
http://localhost:12240/ImageResize.aspx?imgsrc=images/test.jpg&width=100
With javascript i create this html code:
<div class="item related-padding">
<div class="item-container item-0">
<div class="item-content" style="background:url(ImageResize.aspx?imgsrc=images/test.jpg&width=127) no-repeat;"></div>
<div class="item-type video"></div>
</div>
<div class="item-caption">Test</div>
</div>
I believe the problem is in C#, ASP.NET headers
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "image/jpg";
Random random = new Random();
int randomNumber = random.Next(1000000);
//Response.AddHeader("content-disposition", "attachment;filename=" + $randomNumber.ToString() + ".jpg");
/*resize happens here*/
bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.Flush();
Response.End();
bmp.Dispose();
image.Dispose();
any ideas?
All i want is to resize the image and output it as jpg

Add the <img src="ImageResize.aspx?imgsrc=images/test.jpg&width=127" alt=""/> instead of div with background image.

Your question misses the details needed for a to-the-point answer, but here are some hints you can look at:
Relative URIs in CSS are not always treated the same way, check with FireBug or an HTTP sniffer whether the correct relative URI is being retrieved. There used to be a difference here between IE and others, not sure it's still the same.
It's very likely that the error is in your JavaScript, which you don't show. You can check that with the javascript console and/or by printing out the result in an alert box or textbox and rendering that by hand, see what happens (look carefully at correct escaping).
You don't use an entity for the ampersand, though I can hardly imagine a browser would care about that
You don't do a Response.Clear(), which, if you create the response through a normal page request, can create a crippled response stream with headers and data from the page that you don't want there.
Test your code with a regular image on file, see if the CSS still holds (and the JavaScript, of course). Test JavaScript output and CSS separately to make sure to find the right guilty party (CSS, JS, server side C# or else).

Related

How to clear cache of IFrame using c# Code in asp.net

In my asp.net (Runtime Version 3.5) there is a requirement of displaying Pdf in the middle of the page along with other content.
So in such case I found the solution. for this I used Iframe . But we have to display the pdf on linbutton_click event.
HTML part
<div id='Pdfviewer'>
<iframe id="ifrDisplay" runat="server" scrolling="auto" width="600" height="700"></iframe>
</div>
C# code part
LinkButton1_click
{
string pdfUrl = "https://test-folder.com/rxdata//P09/201305240039MA9_000/Data/00000010.pdf";//
ifrDisplay.Attributes.Add("src", pdfUrl);
}
Here the issue is even if the content of the particular pdf changes, still it loads the pdf of older content.
So it is clear this is caching related issue.
Please let me know how to remove the cache due to which still the older content of pdf file is loading.
--Sarthak
To avoid caching you can use some random number in the URL so that browser does not cache the response.
string pdfUrl = "https://test-folder.com/rxdata//P09/201305240039MA9_000/Data/00000010.pdf"+DateTime.Now();
The second possible option is that who is serving PDF should set the cache to (-1) so that it not get cached in the browser.

Prevent Chrome from downloading files

I need to display files in a HTML page in an object tag.
I use C# MVC4 to send the file. In my code, I set the "Content-Type" and "Content-Disposition" headers.
When I set the Content-Type to something Chrome dosen't know, it will download the file, regardless of the "Content-Disposition" header.
HTML:
<div>
<object data="http://localhost/UncHelper?path=secrectPath\file.dwg"></object></div>
C#:
public override void ExecuteResult(ControllerContext context)
{
context.RequestContext.HttpContext.Response.AddHeader("Content-Type", _contentType);
context.RequestContext.HttpContext.Response.AddHeader("Content-Disposition", "inline; filename=\"" + _fileName + "\"");
context.HttpContext.Response.WriteFile(_uncPath);
context.HttpContext.Response.End();
}
When I try to display a pdf file (_contentType = application/pdf) everything is fine.
But when I try to display a .dwg (_contentType = application/dwg) Chrome will download the file. How can I prevent this?
(I don't want to set a HTML status of 203 based on the browser or anything like that.)
Thanks!
This is not possible, and is also a slight misunderstanding on your part i think. For a browser to be able to display a file, it first has to be downloaded.. This goes for all file types. For instance, if you were displaying an image of image/jpeg, with the disposition set to inline, the browser still downloads the image, and then displays it inline, instead of asking the user where he/she would like to save it. If the browser has no knowledge of how to display the file, this is not an option, and will default to the only other option, which is to ask the user where to save it.

Display an image in WinRT WebView control

Say I have a WebView in my page, with its content loaded by WebView.NavigateToString(string html). Now the problem is the html string contains a few <img> tags like
<img src="http://www.remotefakesite.com/1.jpg" />
however the image can't be downloaded correctly unless the request has a special cookie. But the request is sent by the control, I don't know how to modify the request(adding a cookie to it). I've tried setting HttpRequest.DefaultWebProxy, but it doesn't work for the requests sent by the built-in control.
An alternative solution is downloading the image by my own HttpWebRequest(with the correct cookie) to local folder and then modify the img tag in the html string to
<img src="files:///xxxxx" />
but obviously files:/// scheme is against the security policy of metro apps. Neither ms-appx nor ms-appdata works, because the downloaded images are not part of my project.
Do you have any solution?
I did some test here, and if you can download the image to example in the project folder.
Example in the "Media" folder, then you can open the image using this code:
<img src="ms-appx-web:///Media/10.jpg" />
If the image size isn't a problem, you could try to download it using a custom HTTP request with the required cookies, base64 encode it, and insert it into the src attribute:
<img src="data:image/png;base64,iVBOR8Q..." />
And pass it with the rest of the html to the WebView using the NavigateToString method.
This might not be the best solution in the world, but it just works, compared to other options.
You can enable the Pictures Library capability of your app and use the picture library location for downloading the images. Here is a guide on accessing pictures library.
Update:
The image is then created from the image objects in the pictures library. An example would be:
async private void LoadImage()
{
try
{
IReadOnlyList<Windows.Storage.StorageFile> resultsLibrary =
await Windows.Storage.KnownFolders.PicturesLibrary.GetFilesAsync();
MessageBlock.Text += "Show image: " + resultsLibrary[0].Name + "\n";
Windows.Storage.Streams.IRandomAccessStream imageStream =
await resultsLibrary[0].OpenAsync(Windows.Storage.FileAccessMode.Read);
Windows.UI.Xaml.Media.Imaging.BitmapImage imageBitmap =
new Windows.UI.Xaml.Media.Imaging.BitmapImage();
imageBitmap.SetSource(imageStream);
ImagePlayer.Source = imageBitmap;
}
catch (Exception ex)
{
MessageBlock.Text += "Exception encountered: " + ex.Message + "\n";
}
}
You can better use this, write just like HTML:
this.InitializeComponent();
string htmContent = #" <html>
<head></head>
<body>
<img src="http://www.remotefakesite.com/1.jpg" />
</body>
</html>";
preview.NavigateToString(htmContent);
Only you need a webview element (here this called "preview")

PDF in modal iframe renders blank in IE

EDIT 2
It appears that moving the object tag in the Dom is the cause of the problem. I added an iframe directly to the page and it works fine without any problems.
However, when I move that iFrame into a modal dialogue box (http://www.ericmmartin.com/projects/simplemodal/) the PDF disappears (the object tag no longer renders correctly).
So it appears that it's no longer a question about my handler, but more a question about why moving the "object" (or embed) tag in the DOM (which lives inside an iFrame) causes it to "blank-out."
Also, when the pdf is moved from the modal dialogue back to its original position, it appears correctly. So, perhaps I should focus more on the modal dialogue itself.
Thoughts? Thanks for your suggestions thus far.
EDIT 1
So I've made some modifications for testing.
I've got the iframe to output an object tag for pdf requests along with the server time.
Response.AddHeader("content-type", "text/html");
WebClient client = new WebClient();
Response.Write("<html><head></head><body><h1>"+ DateTime.Now.ToString() + "</h1><object height='100%' width='100%' name='plugin' data='" + Request.Url.ToString() + "&embed=true' type='application/pdf' /></body></html>");
Response.Flush();
Response.Close();
Response.End();
Now I get a page with the current time correctly, but the object only displays the PDF the first time after I publish the aspx page. So it appears to be some sort of caching issue? Except that the object isn't loading anything (not even the previously loaded PDF).
If right click on the iframe and refresh the page, the object loads up fine. (The same is true if I use an embed tag).
Original Question
I know there are a lot of questions on this...
streaming PDF data through an ASPX page
Server generated PDF not displaying in IFrame on aspx page on some (but not all )PCs
Displaying a PDF Document in ASP.net page
But they either weren't answered, or the answer didn't work.
Environment
.Net 4
Adobe 9.3.4
IIS 5.1
XP sp3
VS 2010
IE 8.0.6001.18702
Background
The pdf's I'm streaming come from a storage repository where the files don't have any extensions (this is done for security). I look up the file in the database and stream it back to the client via the following code:
Response.Clear();
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(sPath);
Response.AddHeader("content-length", buffer.Length.ToString());
Response.AddHeader("content-disposition", "inline;filename=" + fileName);
Response.AddHeader("expires", "0");
Response.AddHeader("Content-Type", "application/pdf"); //this is usually dynamic to support other types (doc, xls, txt, etc.)
Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.Flush();
Response.Close();
Response.End();
This works for every file type (doc, txt, xls, html) when used directly in the browser or in the iframe (displayed as a modal popup) with the exception of pdf files. They do not work reliably when accessed via the iframe, but work fine when accessed directly in the browser.
The only time it does work is the first time I request a document after I publish the aspx page that is serving these files. All subsequent hits return a blank page (even from new tabs or browser windows). Firefox reliably displays the pdf every time regardless.
Attempted Solutions
I've tried various ways I of streaming the file:
Response.TransmitFile(sPath);
Response.WriteFile(sPath);
//As well as some others
I've tried adding .pdf to a parameter at the end of the request
http://www.myurl.aspx?File=test.pdf
I've tried making the URL unique by adding a time stamp
http://www.myurl.aspx?File=test.pdf&Unique=Friday__September_17__2010_12_02_16_PM
Un-Attempted
I've read about IIS compression causing problems, but it was for a newer version of IIS.
Didn't try using embed tag since I would like to stick to the iFrame if possible (The existing infrastructure uses it).
Any help would be greatly appreciated!!!
Thanks.
I had a similar problem that arose when the PDFs were streaming over SSL (IE only, FF didn't exhibit the issue) that was only solved by doing the following:
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.AppendHeader("Content-Disposition", "inline; attachment; filename=Filename.pdf");
Response.ContentType = "application/pdf";
Response.WriteFile(path);
Response.Flush();
Response.End();
So I gave up and decided to use a standard IE popup window instead.
window.open(URL, 'Window', 'height=' + pageHeight + ',width=' + pageWidth + ',top=0,left=0,resizable');
I had to render the pdfs in an object tag and everything else inside an iframe within the popup for it to work, but it works...
if (sDocType == "pdf")
{
Response.AddHeader("content-type", "text/html");
WebClient client = new WebClient();
Response.Write("<html style='margin:0px;padding:0px;'><head></head><body style='margin:0px;padding:0px;'><object height='100%' width='100%' name='plugin' data='" + Request.Url.ToString() + "&embed=true' type='" + zGetContentType(HttpContext.Current.Request.QueryString["docType"]) + "'><param name='src' value='" + Request.Url.ToString() + "&embed=true' />alt : <a href='" + Request.Url.ToString() + "&embed=true'>View</a></object></body></html>");
Response.Flush();
Response.Close();
Response.End();
}
else
{
Response.AddHeader("content-type", "text/html");
WebClient client = new WebClient();
Response.Write("<html style='margin:0px;padding:0px;'><head></head><body style='margin:0px;padding:0px;'><iframe frameborder='0' scrolling='no' height='100%' width='100%' src='" + Request.Url.ToString() + "&embed=true' /></body></html>");
Response.Flush();
Response.Close();
Response.End();
}
I'm not sure that you need to set the filename, especially if it doesn't have the .pdf extension. When streaming PDFs to browser in the past, I've always used this code:
Response.Clear();
Response.ContentType = "application/pdf";
Response.BinaryWrite(pdfBuffer);
Response.Flush();
Otherwise, there's a possibility that something has hosed over the registry settings for the application/pdf CLSID on the client computer.
I was able to solve a similar problem (pdf inside of modal window internet explorer)
by taking out the iframe. Instead, load the pdf into an html object element.
see the link below:
http://intranation.com/test-cases/object-vs-iframe/
To sum it up:
The setup that did not work:
jQuery floatbox, loads html fragment with iframe, load aspx page into iframe, load pdf into aspx page
The setup that now works:
jQuery floatbox, loads html fragment, append object element.
before appending the object element, set data
attribute of object element to the aspx page url

Redirecting to another page after Response.End() has been called in C#

I am exporting a gridview to excel, using .Net 4.0 in a web application, on page load and need for the file to be generated and then the page to be redirected to the calling page. I am running into issues because my code to export to excel is as follows:
gvSummary.Style.Add("font-size", ".6em");
Response.Clear();
string attachment = "attachment; filename=filename.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvSummary.GridLines = GridLines.Horizontal;
gvSummary.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
I know that if I put the Response.Redirect() before the .End(), I will get redirected but the file is never generated, and if I put the Response.Redirect() after the .End() I get the file but no redirection.
The code written above works just fine in generating the file, however when after the file is generated I am still stuck seeing my Loading animation because I can not break out of the page. Any ideas?
I suggest to add a redirect header. Something like this:
Response.AddHeader("Refresh", "3; url=index.html");
Where 3 is time of the delay and index.html is url you need to redirect to
The problem is Response.End() send the last bits of the page to the client in order to complete the request. In your case, the request contains the file.
One possible solution is be to open a new page for the download and keep the redirect in the current page.
I added the target="_blank" to the link that takes me to the page. So when it opens in a new window, it send the excel sheet to the browser, and closes the page as it has nothing else to do after the Response.End();
Hope this helps. Worked for me.
You can't do both open so you might want to try setting the link to the generated xls file in a new window or as source to a iframe
In JavaScript:
function refresh() { document.location.reload(true); }
button:
<td valign="top" style=" width:100px ">
<asp:Button runat="server" ID="btnX" Text="X" CssClass="ui-button ui-widget ui-state-default ui-corner-all ui-button-text ui-state-hover" OnClientClick="refresh();" Width="180px" />
</td>
I tried opening a separate page through ScriptManager that will download my file while doing the redirect in my original page.
So I added below code in my main page:
string strScript = "<script language='javascript'> window.open('CommonDownload.aspx','Report');</script>";
ScriptManager.RegisterStartupScript(Page, this.GetType(), "clientScript", strScript, false);
Response.Redirect("Page.aspx");
And then added the download code in the Page_Load method of my CommonDownload page. I passed some of the info I needed in the CommonDownload page through through the session.
OnClientClick call this method and it will automatically be refreshed.
function PageRefresh() {
setTimeout(function () {
window.location.reload(1);
}, 5000);
}

Categories