ASP.NET Response Content - asp.net

I have tested this in IIS 6.1, IE 7, ASP.NET 3.5 SP1.
I have a file download in a method in my aspx codebehind:
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", contentDisposition);
Response.BinaryWrite(file);
This works great, but if I attempt to modify any of my sever side controls the changes do not take affect. I have isolated this down to the call to ContentType, this apparently whipes all pending changes to the Response stream when called? Does this sound familiar to anyone?
If the code takes an alternate branch and the call to download does not fire the markup is modified as expected.
Any suggestions on how I can fix this and have the page flush the attachment and update the UI in the same response stream?
This is specifically for updating the ValidationSummary, so I could tear into the JS on the PageRequestManager event complete as a last resort, but I'd prefer not to rely on JS for this.

Not sure what you're trying to do - are you trying to simultaneously serve a download file and an update to the HTML page they linked to it from? That's not how HTML works.
If you want to achieve this result then you'll basically have to render a meta redirect that goes to the file which is returned in the HTML, that way the page will load and then the download starts (Like you'll see on a lot of download sites).

As fyjham said, I don't really understand what you're trying to do. A few tips that might help:
Keep in mind that the Render phase, when the content from your markup and controls is generated, happens as almost the very last phase in your code behind (well after Page_Load)
Once you flush headers, you can't set them again
Controls can override some HTTP headers
You can't mix a file download and HTML markup in the same HTTP response

Related

How make Firefox see changes to .aspx page?

I created an aspx page and viewed it in Firefox and it worked correctly, running the code. But when I make changes to the page (including deleting everything and serving up a blank page), Firefox continues to show the original compiled aspx page! How can I get it to see the new page?
I even added the following code, but it still loads the original page:
<script runat="server">
Sub Page_Load
Random rd = new Random();
Response.AddHeader("ETag", rd.Next(1111111, 9999999).ToString());
Response.AddHeader("Pragma", "no-cache");
Response.CacheControl = "no-cache";
Response.Cache.SetNoStore();
Response.Expires = -1;
End Sub
</script>
I even cleared Firefox's cache, but it still loads the original version!
EDIT: It appears the issue might be on the ASP.Net side. It's also not changing in Chrome. So, how do I force changes to an aspx file to force a recompiling?
I've had luck with the following code:
// Stop Caching in IE
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
// Stop Caching in Firefox
Response.Cache.SetNoStore();
Also, your browser may have already cached it prior to when you added the cache prevention code. If so, try hitting CTRL-SHIFT-R in Firefox to force a reload without hitting the cache and see if you still have a problem with Firefox storing cached copies of your page.
Since it appears the issue is not firefox related but something in the ASP.Net web server (since it happens in Chrome as well), I've asked a different question and will close this one.
Yet another way to reload and override cache CTRL + F5
It may also depend on how you are developing your ASP.Net application/site
re-compiling after making changes before viewing again?
If you are building a web application, you have to rebuild (In Visual Studio) your application to reflect any change(s) you made to server side code - this isn't an "ASP.Net issue" it's the norm. You can make changes to the HTML (client side) without re-building, but any server code change will need a rebuild (recompile the dll(s)).
The sample code you have above however, looks like in-line code - is all your code in-line - as in you don't have code behind files (i.e. foo.aspx.vb or foo.aspx.cs)?
All the above is based on local development - obviously if you are viewing your "production"/live site, then it goes without saying that you have to "push"/"publish"/upload/update, whatever local changes you made to it.

AjaxToolkit AsyncFileUpload needs ViewStateMode enabled, how to avoid?

I know this is rather a trivial question but anyhow I want to know if it is solvable.
I have an ASP.NET webform page with a nested masterpage and JavaScript includes. I make extensive use of jQuery and Ajax calls. Once a page is loaded, all communication with the server is done with Ajax calls, so I don't need ViewState enabled, and this is resulting in a reduced HTML output code.
I now have to implement a page where a user can upload a file. So I used the AsyncFileUpload control of AjaxToolkitFileUpload. Once a file is uploaded, I do a Ajax call to the server to request the filename.
It all works fine but I noticed that FireBug found 10 errors per file upload between the OnClientUploadStarted and the OnClientUploadComplete events. The file is uploaded properly and the events on the client side are working too. But I can't ignore the fact that there are errors thrown so I went looking for the problem.
I rebuild the page piece by piece and I found out that this control needs the Viewstate enabled.
However with viewstate=disabled in the page directive the file size is 76.6kb, and with viewstate=enabled the size is 99.2kb.
Again, I know it is trivial and will not affect performance on the site, but it is a nice to know.
- Why does this control needs the viewstate? (I suppose because it actually post the file to a iFrame or something like that?)
- How can I reduce the viewstate and let this control still work properly?
For reducing view state and having this one control work properly, you can use leave view state enabled on your page and set the ViewStateMode to Disabled for the page and then set the ViewStateMode to Enabled for the one control that needs view state. For all other controls they should inherit the setting of the parent by default.

aspx ashx mash-up

I'm retro-fitting a .aspx page with AJAX functionality (using VB, not C#). The codebehind populates the page with data pulled from a web-service. The page has two panels that are populted (with different data, of course) in this way. On a full page refresh, one or both panels might need to be populated. But populating Panel 2 can take a long time, and I need to be able to update panel 1 without refreshing Panel 2. Hence the need for AJAX (right?)
The solution I've come up with still has the old .aspx page with .aspx.vb codebehind, but introduces a Generic Handler (.ashx) page into the mix. Those first two components do the work on the user's first visit or on a full page refresh, but when AJAX is invoked, the request is handled by the .ashx page.
First question: Is this sound architecture? I haven't found a situation online quite like mine. Originally, I wanted to make the .aspx page into the AJAX handler by having the codebehind implement IHttpRequest, and then providing "ProcessRequest" and "IsReusable" methods, but I found I couldn't separate a regular visit to the page from an AJAX request, so my AJAX handlers took over even on the first visit to the page. Second question: Am I right to think that this approach (making the .aspx page do double-duty as the AJAX handler) will never work? Is it impossible to tell whether we're getting a full-page request or a partial-page (AJAX) request?
If the architecture is good, then I need to dynamically generate a lot of HTML in the .ashx file, right? If that is right, should I send HTML back to the client, or should I encode it in some way? I've heard of JSON encryption, but haven't figured out how to use it yet. So, Third question: Is "context.Response.Write" the only pipeline for sending data back to the client? And, if so, should I send back HTML or some kind of JSON-encoded objects?
Thanks in advance.
It sounds as if the page requires some AJAX functionality added to the UI.
Suggest using an UpdatePanel for each web form element that needs to have AJAXy refresh
functionality. That'll save you from having to refactor a bunch of code, and introduce a whole lot of HTML creation on your .ashx.
It'll be more maintainable over the long run, and require a shorter development cycle.
As pointed out by others, UpdatePanel would be a easier way - but you need to use multiple update panels with UpdateMode property set as conditional. Then you can trigger the update-panel refresh using any button on the page (see AsyncPostBackTrigger) or even using java-script (see this & this). On the server side, you may decide what has triggered the partial post-back and act accordingly by bypassing certain code if not needed.
You can also go with your approach - trick here is to capture the page output using HttpServerUtility.Execute in your ashx and write it back into the response (see this article where this trick has been used to capture user control output). Only limitation with this approach is that you can only simulate GET requests to your page and so you may have to change your page to accept parameters via query string. Personally, I will suggest that you create a user control that accept parameters via method/properties and will generate necessary output and then use the control on your page and in ashx (by dynmaically loading it in a temperory page - see this article).
EDIT: I am using jquery to illustrate how to do it from grid-row-view.
$(document).ready(function() {
$("tr.ajax-grid-row").click(function() {
$("#hidden-field-id").val($(this).find(".row-id").val()); // fill hidden filed
$("#hidden-button-id").click(); // simulate button click
});
});
You can place above script in the head element in markup - it is assuming that you have decorated each grid-row-view with css class "ajax-grid-row" and each row will have hidden field decorated with css class "row-id" to store row identifier or the value that you want to pass to server for that row. You can also use cell (but then you need to use innerHTML to get the value per row). "hidden-field-id" and "hidden-button-id" are client ids for hidden field and submit button - you should use Control.ClientID to get actual control ids if those are server controls.
JSON is not for that purpose, it is to pass objects serialized with a nice light weight notation, is you need to stream dinamically generated html using ashx, response.Write is what you have. You may want to take a look at MVC
Or you could use jquery if it's just html, the simpliest would be the load function, or you can look into Ajax with jquery. Since the ashx can be served as any resource it can be used in the load function.
I agree with #p.campbell and #R0MANARMY here. UpdatePanel could be the easiest approach here.
But then like me, if you don't want to go the UpdatePanel route, I don't see anything wrong with your approach. However, generating the html dynamically (entirely) at the back end is not a route I'll personally prefer (for the maintainence reasons). I'd rather prefer implementing a solution that will keep the design separate from the data.

ASP.NET Page Rendering

How does the ASP.NET page rendering happens from Server to Client Browser? The question is, consider the Page has a Header and Footer which are User controls and contain many server controls.
Does ASP.NET start sending the HTML to client browser, once it gets some of the controls being rendered and converted in their respective HTML? Or does it wait for the whole page to be rendered and converted in HTML on Server, and then it sends back the Page HTML to the browser.
I am seeing that the "Page Title" of our website is shown much before and then the page takes too much time in loading completely. I want to be clear on this concept whether its server that is taking time or the client side scripts, images etc.. are the culprit. Accordingly we will start the optimizations.
Specifically I am interested in knowing how the outputstream (in response object) is sent to the Client Browser? Is the outputstream flushed once whole page is rendered in outputstream or it is sent to client in batches (i.e. few controls rendered and sent to browser via outputstream --> then some more controls are rendered and so on...)?
Sorry if am not clear enough on the problem.
in terms of debugging you can turn .NET tracing on to see whats taking the time on the server side,
and use google chrome or firebug for firefox to see whats taking the time on the client side.
I believe this is controlled by Response.BufferOutputor something similar(no reference at hand) to determine if it should start sending out HTML as soon as it's ready or if it should store it in a buffer and wait until everything is done and then send it.
The answer I was looking for was regarding the rendering way, how is stream sent to client, there could be two ways, Either directly sending it as soon as it is generated, in multiple chunks, Or cache and store until whole page is rendered and then send it to client.
I got the answer at: http://www.asp.net/aspnet/overview/aspnet-and-visual-studio-2012/whats-new
"Normally ASP.NET buffers the response bytes as they are created by an application. ASP.NET then performs a single send operation of the accrued buffers at the very end of request processing.
If the buffered response is large (for example, streaming a large file to a client), you must periodically call HttpResponse.Flush to send buffered output to the client and keep memory usage under control. However, because Flush is a synchronous call, iteratively calling Flush still consumes a thread for the duration of potentially long-running requests."
Thank you all for your help!!!
User controls are rendered before controls on the .aspx page itself.
Take a look at the Page Life Cycle
Fiddler should help determine where the bottleneck is, if you're seeing the page title show up but the page doesn't render for a bit after I'd suspect there are other files (images, javascript, css, etc) that are holding up the page from rending in the browser and not the html in the page
Page rendering . at this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is written to the OutputStream class of the Page's Response property.

AJAX call to asp from bookmarklet

I'm trying to create a bookmarklet that will start off an AJAX call to an aspx page I've written.
The code tests out perfectly when I place the javascript in a static html page, but when I try and call it off from a bookmarklet, the code will just hang at the xmlHttp.open("GET", url, true) part.
The code of the bookmarklet is basically this (found on several examples on the web):
javascript:(function(){
var s,
d=document,
a=function(o){ d.body.appendChild(o) };
s=d.createElement('script');
s.type='text/javascript';
s.src='http://localhost/squirt/sq.js';
a(s)
})();
This adds the contents of sq.js (the ajax call + some other processing) to whatever page the browser is currently at, and then calls off the ajax to my aspx page.
I'm using ASP 2.0 (with VS2008) and IIS 7. So far I've just been testing it on my home network.
I assume there must be some sort of permissions issue with the ajax call from an outside page, since, like I said, everything works fine from a static page. Is this an IIS setting I need to change to allow the call, or am I doing something completely wrong?
The XMLHttpRequest object is subject to a Same Origin Policy.
This is why the script your bookmarklet is loading can't use an XHR to get data from your server unless it's embedded in a page from your server.
Script added by dynamically adding a script tag will work though, as you can tell - your bookmarklet can load script from a different origin.
So there's your answer. Don't use an XMLHttpRequest object: dynamically load your script in the same way the bookmarklet does.
This is how JSONP works (actually there's a bit more to JSONP but that's how it gets around the SOP)
Actually, why not just use JSONP
Injecting JavaScript code on the page still has the same permission issues as code that is there normally. You can not make an Ajax call to a different domain. So if you are calling localhost from example.com, it is not going to work.
You might want to look at returning JSON from your service and make JSON calls with a script tag.
Eric
The code you're using there is rather ugly, I would suggest using something like this that I built: http://sktrdie.org/getScript.js
It works like this:
getScript("http://anotherdomain.com/something", function(data) {
alert(data); // the request is complete
});
On the http://anotherdomain.com/something it would have to return something like this, given you're using PHP:
echo $_GET["jsonp"]."('Testing data, you can put anything in here');";
Be sure to read about JSONP.

Resources