Response.TransmitFile and Server.Transfer - c#

I have a ASP.NET app that at one point generates a PDF file and loads the next page. I can easily do this with two separate buttons but it is made much tougher when I try to do this with one button.
When both are fired by the same button the PDF will download but the page will not load. I even had the thread sleep after the file was transmitted but it would wait but then stop afterwards.
I have attached the code that I have been trying to make work:
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=labels.pdf");
Response.TransmitFile(Server.MapPath("~/"+randomNumber.ToString()+".pdf"));
Server.Transfer("~/createshipment.aspx", true);

You can't have two different responses from the server but you're trying to do so.
First - you'd like the server to return a PDF.
Second - you'd like the server to return the createshipment.aspx page.
This is just against the communication protocol. Probably the best solution is already presented by another user, competent_tech - you could open a new window (javascript's window.open) and this new window would return the PDF and in the same time the main window could post to the server and be redirected to the createshipment.aspx.

So in a nutshell you want to navigate to the next page that says something like "thank you for downloading this file" and start the download.
What you should do is on your button click you need to generate PDF and save it somewhere (on disk or DB - whichever is easier in your app), store the name/location of the new file (or primary key from DB) in a session variable and redirect to the next page. No reason to do transfer here. Then on that next page you should add a hidden iframe that points to your saved file.
Alternatively your button click could be just a link to the next page, which includes a hidden iframe pointing to the page that generates PDF. This is a bit simple but wouldn't work so well if you need to pass parameters from original page to the page that generates PDF.

This is because server.transfer "...terminates execution of the current page and starts execution of a new page by using the specified URL path of the page".
Your best bet is to open a new window in the client that gets the PDF and then perform whatever postback is needed to move the user to the next page.

I know this is old, but I'm just seeing it (looking for similar info myself).
I'm going to guess that this is causing issues:
Response.TransmitFile(Server.MapPath("~/"+randomNumber.ToString()+".pdf"));
You would need to map the path to the actual file and not some randomly created filename - or am I missing some steps?

Related

UpdatePanel from Page_Load without postback

I created an ASP .NET Web Forms application from Visual Studio 2017 creator with C# as a language. I did minimum changes to the template and my web page loads a 3D image, takes a few additional parameters via Buttons and Text fields, sends it for processing to server. There it lands in a directory where it is processed by a commercial program, independent of Visual Studio, which initially writes to a directory with an image ID (say ABCD) and into a directory with an image taking date (say 20170629), after some processing, 2-5 minutes, it writes the results of the analysis into a new folder with a current date (say 20171031) into a text file where the name consists of 15 digits code and a known extension (say 123456789012345.txt). It is within Java Derby database, for which I did not find any connectors from .NET.
The web page meanwhile shows the summary of data sent. What I got working is the Button which while pressed checks if the mentioned directory (20171031) is already created shows the asp:UpdatePanel with progress (1/3 stages passed, 2/3 stages passed etc.) and when the file 123456789012345.txt is ready it gets the data from it and on the server side it calculates some values and displays them. Because of waiting there are several public async Task and public async Task methods to search for file appearance.
I wanted to avoid manual pressing of the Button, so that the processing stage is shown and once the file 123456789012345.txt is ready the values is calculated. For the moment I tried various ways, but without success. I prefer to avoid reloading the whole page every 30 seconds, because the user may get confused.
asp:UpdatePanel, as far as I understand needs pressing of the Button or some other interaction from the user side. If I use in aspx.cs file in Load_Page method the UpdatePanelName.Update(); for whatever reason the panel is not updated. Due to the use of await CalculateImageAsync(), the only way I found to have it in Page__Load is to have it as protected async void Page_Load(object sender, EventArg e) , but when page is loaded, it never loads. Anything else needs user interaction, which I want to avoid. I got stuck...
I am new in ASP .NET and C#, so maybe I do something wrong or miss some nice .NET method. I would be obliged for help. I have seen pages doing the job like I want, for example in the journals, where you submit a DOCX file where it is converted to PDF - once you submit it after some time you get a page with resulting PDF.
Regards, Marcin

File upload that looks like ajax

I am trying to create a form which allow async file uploading with asp.net. I realize you cannot upload a file with ajax per se so I am examining alternatives
What is the best way to do this? Create an Iframe on the page with the entire form including the file input? Can I on the parent to the frame have the submit button which forces the frame to submit and then displays some sort of spinner to indicate file is uploading? Ideally upon completion I'd like to redirect the user to another page. Is there a somewhat easy way to do this???
Have you tried using one of the jquery plugins vice doing it by hand?
http://aquantum-demo.appspot.com/file-upload
Why not use the ASP.NET AJAX Control Toolkit's AsyncFileUpload control? It's free and works pretty well.
You could use http://jquery.malsup.com/form/#file-upload
Have it post to a page that will handle a file upload on the server side in your usual way.
I like to have the page return JSON with a success/failure flag and message, then parse the response to determine if the upload succeeded.

C# code for saving an entire web page? (with images/formatting)

I've been struggling to find an exmample of some C# code (I'm using C# Visual Studio 2008 Express) that can programmatically save an entire web page (given a URL) including the images and formatting (e.g. CSS). The intention is that in a subsequent phase I'd ship this off (not sure how yet) so it could be viewed later via a browser.
Is there an example of the most simple approach (leveraging the .NET Framework methods) to save an entire web page? Saving as one page with a subdirectory for images, or otherwise. Basically the same as what you get with browsers when you say "save entire web page".
The simplest way is probably to add a WebBrowser Control to your application and point it at the page you want to save using the Navigate() method.
Then, when the document has loaded, call the ShowSaveAsDialog method. The user can then save the page as a single file, or a file with images in a subdirectory.
[Update]
Having now noticed "programatically" in your question, the above approach is not ideal as it requires either user involvement or delving into the Windows API to send input using SendKeys or similar.
There is nothing built-in to the .NET Framework that does all of what you ask.
So my approach revised would be:
Use System.NET.HttpWebRequest to get the main HTML document as a string or stream (easy).
Load this into a HTMLAgilityPack document where you can now easily query the document to get lists of all image elements, stylesheet links, etc.
Then make a separate web request for each of these files and save them to a subdirectory.
Finally update all relevent links in the main page to point to the items in the subdirectory.
In effect you would be implementing a very simple web browser. You may run into issues with pages that use JavaScript to dynamically alter or request page content, but for most pages this should give acceptable results.
From code Project: ZetaWebSpider
It's definitely not elegant, but you could navigate a System.Windows.Forms.WebBrowser to the URL and then call its ShowSaveAsDiagog() method to save the page.

Read & display text file in javascript

The user needs to click on browse button to browse his system .He then selects a text file & clicks ok.Once he clicks ok all the data in the text file should be displayed in a text area.How do I do that? I am using JavaScript & c# designing aspx pages.It would be preferable if i avoid round trip to the server.
You can't do it without a trip to the server, the only way for you to get the content of the file is by submitting it as part of a form. You can make the trip to the server happen in an iframe via XHR and then update the text area with the result from the XHR call, so it sort of seems like one wasn't involved, but you can't directly access the content of files of the user's machine, for obvious reasons.
I know you said you would prefer a round trip, but its the only way you are going to be able to accomplish what you want.
You could put the file upload in an iframe, and do the upload behind the scenes (No page refresh, gmail does this :) ) then use AJAX to download the data and insert it into the textarea.
It can't in general be done, as answers here outline.
However, it can be done in Firefox 3+ only, using the uploadfield.files array. Other browsers would have to fall back to the server round-trip.
For security reasons, JavaScript cannot access the local filesystem like that.
Javascript cannot do that without putting a severe security risk on the user. That said, the file will need to be posted to your server.
As other posters here have indicated, you're not allowed to access the local filesystem from Javascript directly. But you can set up an action on your server to take the file form POST input, and simply echo the data right back out to the response. If you hide an iframe inside your page as the form POST target, that response data can appear in the hidden iframe, and then the page won't have to reload. Then once the iframe has loaded with the text, you can use JS to pull the text out of the iframe, and put it into the text area that you're interested in.
Alternately, if you're inclined to restrict usage to Firefox users with an extension, you should be able to accomplish this without a roundtrip using a Greasemonkey user script (see www.greasespot.com) or something like it, that uses the custom Mozilla extensions.

Computer file caching issue with asp.net website

This may be some "best practices" thing I've overlooked or don't know about, so go easy on me please.
I have an asp.net website that populates a gridview with columns from my database table. One of those columns gets processed into a link to a word document on another server. The issue is that if a user clicks on the word document to view it, and then that document is updated on the remote server, the user cannot access the changed document until their browser cache is cleared and it's forced to go out to the network to grab a fresh copy when the link is clicked.
Basically I want to somehow force the machine never to use the cached copy of the document, but always go out to the network to get the newest copy.
Bonus question: Would this be better handled somehow by storing the documents in SharePoint?
UPDATE: using Response.Cache.SetCacheability(HttpCacheability.NoCache); in my codebehind I have now resolved the issue in FireFox, but IE8 is weird. If I update the document and then left click on it, it brings up the word doc in the IE window without the changes. However, if I make changes, save them and then middle click on the document so it opens up a new tab, the document reflects the changes. I'm mostly there...
Try adding a little extra data to the link. Here's an example using js; if you're building the url server side, it should be essentially the same:
var url = "http://www.mydomain.com/mywordfile.doc?ts=" + (new Date()).getTime();
That'll force the url to have a different query url each time, which (in theory) should force the browser to re-request and re-download it.
By chance are you seeing this with IE8 specifically? We've seen it show this behavior where caching was previously not an issue.
Typically it can be cleared up with a couple steps: explicitly telling the browser not to cache via HTTP headers, and also expiring the page immediately. Google the "pragma no-cache" header, there is typically a couple of different lines you need to add to cover all browsers.

Categories

Resources