How can i manipulate the page while it is rendering? - asp.net

I want to change some elements text when page is leaving the server (page_render, endRequest etc.).
How can i get access to the page and how can i find the elements to change their values, texts?

You can do so by using a HttpModule. This sits in the pipeline and can do pre- and postprocessing.
For example take a look at this whitespaceremover.

Besides HttpModules, you can also override the 'Render' method (or do this in a basepage to make it reusable).
protected override void Render(HtmlTextWriter writer )
{
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
base.Render(htmlWriter);
string html = stringWriter.ToString();
// do stuff with the html
writer.Write(html);
}

There are a number of options and which one suites you will depend largely on what the actual goal is.
Handle the PreRender event of a Page and adjust any elements you want to in this event. Ideally you would put this in a base class that is inherited by all the pages that require this processing. This gives you access to the actual page model and control tree.
Setup a filter that will give you direct access to the response stream. You can implement this in 2 ways, either as a separate HttpModule that installs the filter or you can install the filter directly from the Global.asax. Which route you choose depends on how reusable you need this, with the HttpModule being the most reusable.
Here is a nice article Modifying the HTTP Response Using Filters

Related

Approach to targetting HTTP Handler from Button Click

Main purpose here is to target the handler to download a file that is being previewed.
There are two different conditions of the file, one where it is already saved in the database, then the following parameters to the handler through a query string
COIHandler.axd?Action=preview_saved&letterId=xxxx
or
one that hasn't been saved yet, in which i store it in the session and target the handler in the following way
COIHandler.axd?Action=preview_unsaved
then the handler will handle clearing the session after I'm done.
Any thoughts on how to make this occur. Still new to http handlers.
CLARIFICATION
I have a OnClientClick property in my sub classed version of the Button class which allows me to append javascript to it that will be executed client-side. That is where I want the targeting to occur.
I want the user stay on the same page when they click the download button as well.
I dont want to simply do a redirect in javascript that will target the handler and I would like to avoid a pop-up window if possible. Not really sure if that leaves any options
In Response to Yads comment, you can use a button click handler on your page to download the file without a need for a popup or separate HTTP Handler.
protected void btnDownload_OnClick(object sender, EventArgs args)
{
PDFContentData data = GeneratePDFData(); //parses strings from some source (as mentioned in comments)
WebFileUtil.InvokePDFDownload(Page.Context, data);
}
public static class WebFileUtil
{
public static void InvokePDFDownload(HttpContext context, PDFContentData data)
{
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
FileStore.generateDocument(data, context.Response.OutputStream);
context.Response.ContentType = "application/pdf";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}_Documenth.pdf", DateTime.Now.ToShortDateString()));
context.Response.End();
}
}
Your handler would actually be .ashx. Other than that your approach seems fine. You can examine the context that is passed into the PrcoessRequest method.
public void ProcessRequest(HttpContext context)
{
switch(context.Request.QueryString["Action"].ToLower())
{
case "preview_saved":
//do stuff for saved
case "preview_unsaved":
//do stuff for unsaved
}
}
UPDATE If you want a central handler, then you'll either want to redirect the user at the end of the call in which case you'll also want to pass a returnUrl parameter in the query string. Then you can just do a context.Response.Redirect(context.Request.QueryString["returnUrl"]). Or if you want the page to retain its state, you're going to have to make an Ajax call to your handler.
First off thank you very much for all the possible solutions they were helpful in getting outside the box.
I figured out a unique solution that I thought I would share.
I place an invisible iframe in the html markup of my page.
then I set a property called OnClientClick in my server control Download Button (this allows me to render a parameter string to the onclick attribute of the html)
I set the property to a javascript method which embodies a recursive algorithm to navigate to the top parent frame of the page, once it reaches that point, I use a simply JQuery selector to look for the iframe I spoke of in step 1. (The reason for the recursion is to maintain support with Master Pages where you will have frames inside of frames).
Set the src attribute of the iframe to the target HTTP Handler. The applied behavior causes the iframe to load the requested source ... but in this case it is a handler, and since it was made all originally from direct user input (via the Download button click), you won't even have the issue of getting the Yellow Bar with IE7+
The handler serves the request and the file is served to the browser
Yay!

ASP.NET Save HTML Sent to Browser

I need to save the full and exact HTML sent to the browser for some transactions (for legal tracking purposes.) I suspect I am not sure if there is a suitable hook to do this. Does anyone know? (BTW, I am aware of the need to also save associated pages like style sheets and images.)
You can create an http module and have the output stream saved somewhere.
You should hook to PreSendRequestContent event...:
This event is raised just before ASP.NET sends the response contents to the client. This event allows us to change the contents before it gets delivered to the client. We can use this event to add the contents, which are common in all pages, to the page output. For example, a common menu, header or footer.
You could attach to the PreSendRequestContent. This event is raised right before the content is sent and gives you a chance to modify it, or in your case, save it.
P&P article on interception pattern
You could implement a response filter. Here is a nice sample that processes the HTML produced by ASP.NET. In addition to the HTML being sent to the client you should be able to also write the HTML to a database or other suitable storage.
Here is an alternate and IMO much easier way to hook the filter into your application:
in Global.asax, place the following code in the Application_BeginRequest handler:
void Application_BeginRequest(object sender, EventArgs e)
{
Response.Filter = new HtmlSavingFilter(Response.Filter);
}
I suppose you only want to save the rendered html for certain pages. If so, I have been using the following approach in one of my applications that stores the rendered html for caching purpose somewhere on the disk. This method simply overrides the render event of the page.
protected override void Render(HtmlTextWriter writer)
{
using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
{
base.Render(htmlwriter);
string html = htmlwriter.InnerWriter.ToString();
using (FileStream outputStream = new FileStream(#"C:\\temp.html", FileMode.OpenOrCreate))
{
outputStream.Write(html, 0, html.Length);
outputStream.Close();
}
writer.Write(html);
}
}
Really works well for me.
There are also hardware devices made specifically for this purpose. We've used one called "PageVault".

Rewrite ASP.NET page output

A little background: I am trying to create a lightweight cookieless database-backed user session using a highly striped down ASP.NET implementation. This site audience will be mobile users connecting via celluar networks, so the page sizes need to be very small. I am not using the .NET session, viewstate, etc. and most page contain very few if any server controls.
I want to be able to process the output of a page request so I can modify internal links in the response with my own session information. I have read that there was an ISAPI filter to allow cookieless sessions pre-ASP.NET. That is basically what I want to build, just inside the application.
Has anyone done anything like this? I'm already inheiriting the System.Web.UI.Page class for my page base for other reasons. It seems like I should be able to do something from here.
Thanks
HttpModules can give you complete control over your output, but there are also a couple other things you can do that are a little simpler.
Create a custom Filter for the Response.Filter. More or less you create a Stream that you run everything through before sending it onto the underlying stream letting you make your changes there.
Override the render event for the Page and write all your contents to a string and then make your changes there... for example...
.
//this is from memory, you might need to check it
override void Render(HtmlTextWriter writer) {
StringWriter html = new StringWriter();
HtmlTextWriter render = new HtmlTextWriter(html);
base.Render(render);
string output = html.ToString()
//make your changes to output
//output = ???
writer.Write(output);
}
Look into using an HttpModule for this. You can process the entire response on the way out.
You might also be able to do something with a base class - perhaps go through all the server-side controls that might have links in them on the PreRenderComplete event. This wouldn't help you with HTML <A> tags, though.

Modifying the HTML of a page before it is sent to the client

I need to catch the HTML of a ASP.NET just before it is being sent to the client in order to do last minute string manipulations on it, and then send the modified version to the client.
e.g.
The Page is loaded
Every control has been rendered correctly
The Full html of the page is ready to be transferred back to the client
Is there a way to that in ASP.NET?
You can override the Render method of your page. Then call the base implementation and supply your HtmlTextWriter object. Here is an example
protected override void Render(HtmlTextWriter writer)
{
StringWriter output = new StringWriter();
base.Render(new HtmlTextWriter(output));
//This is the rendered HTML of your page. Feel free to manipulate it.
string outputAsString = output.ToString();
writer.Write(outputAsString);
}
You can use a HTTPModule to change the html. Here is a sample.
Using the answer of Atanas Korchev for some days, I discovered that I get JavaScript errors similar to:
"The message received from the server could not be parsed"
When using this in conjunction with an ASP.NET Ajax UpdatePanel control. The reason is described in this blog post.
Basically the UpdatePanel seems to be critical about the exact length of the rendered string being constant. I.e. if you change the string and keep the length, it succeeds, if you change the text so that the string length changes, the above JavaScript error occurs.
My not-perfect-but-working solution was to assume the UpdatePanel always does a POST and filter that away:
protected override void Render(HtmlTextWriter writer)
{
if (IsPostBack || IsCallback)
{
base.Render(writer);
}
else
{
using (var output = new StringWriter())
{
base.Render(new HtmlTextWriter(output));
var outputAsString = output.ToString();
outputAsString = doSomeManipulation(outputAsString);
writer.Write(outputAsString);
}
}
}
This works in my scenario but has some drawbacks that may not work for your scenario:
Upon postbacks, no strings are changed.
The string that the user sees therefore is the unmanipulated one
The UpdatePanel may fire for NON-postbacks, too.
Still, I hope this helps others who discover a similar issue. Also, see this article discussing UpdatePanel and Page.Render in more details.
Take a look at the sequence of events in the ASP.NET page's lifecycle. Here's one page that lists the events. It's possible you could find an event to handle that's late enough in the page's lifecycle to make your changes, but still get those changes rendered.
If not, you could always write an HttpModule that processes the HTTP response after the page itself has finished rendering.
Obviously it will be much more efficient if you can coax the desired markup out of ASP.Net in the first place.
With that in mind, have you considered using Control Adapters? They will allow you to over-ride how each of your controls render in the first place, rather than having to modify the string later.
I don't think there is a specific event from the page that you can hook into; here is the ASP.Net lifecycle: http://msdn.microsoft.com/en-us/library/ms178472.aspx
You may want to consider hooking into the prerender event to 'adjust' the values of the controls, or perform some client side edits/callbacks.

ASP.NET MVC Equivalent to "override void Render" from ASP.NET WebForms

What is the ASP.NET MVC equivalent to "override void Render" from ASP.NET WebForms?
Where are you opportunities to do some last-minute processing before the output is sent to the client?
For example, I wouldn't use this in production code, but illustrates cleaning up the <title> and <head> markup for an entire site when placed in the MasterPage of a WebForms app.
protected override void Render(HtmlTextWriter writer)
{
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
base.Render(htw);
htw.Close();
string h = sw.ToString();
string fhtml = h.Replace("<title>\r\n\t", "\n<title>")
.Replace("\r\n</title>", "</title>")
.Replace("</head>","\n</head>");
// write the new html to the page
writer.Write(fhtml);
}
What is the best approach for playing with the final text rendering in ASP.NET MVC?
UPDATE:
So looking at the link (the chart) that Andrew Hare mentioned it looks you could do this in the View Engine. Can you bolt things onto or alter the way the default View Engine works or do you have to replace the whole thing?
This isn't the way in which MVC works.
All your 'onprerender' code is done in the view. By the time you pass your data to the view from the controller you should have done all processing necessary to display the whole page.
The only slight exception to this is the model may still do a little processing while it is being probed by the view.
This may include setting variables required for partials to turn themselves on or off etc.
As far as I can see, the only thing you want to do in your Render()-method is to re-arrange some of the tags in the <head> section. This is already done correctly for you in MVC, unless you're using some home-built way of creating the <head>-section in your Masterpage.
I'd recommend aligning the tags exactly the way you want them directly in the html markup of your Master, and ensure that the ViewData["title"] or whatever you use to fill the tags with content to not start or end with line breaks.

Resources