Lately I've been using a laptop more often than a desktop to work in Visual Studio, and of course like most laptop keyboards, the keys are jammed close together. The most annoying thing I keep doing by mistake is hitting F1 instead of Escape, which of course begins the not-so-quick process of bringing up help. Every time I do it, I sigh, wait, and close it.

No longer... realizing I can just disable F1 has made my day.

F1HelpBefore

F1HelpAfter

Now I can hit escape without fear.

Sky Lynn Reed's 0th birthday is 5/15/2008 at 5:44pm, when she weighed 8 pounds, 0 ounces. A nice round binary number. Our first born! There are simply no words to describe the experience. We debated on whether we should have kids for a long time. After being married almost 5 years now, we finally decided to take the plunge. Now that she's here, and about 5 weeks old, we couldn't imagine our lives without her.

SkyLynnReed

Of course, being a programmer daddy should be fun. We'll just see how early it is possible to learn to type. Imagine having an email address that you've had since before you were born? Oh, and a birthday cake with a number 0 candle on it makes sense to me. You're how old? Yeah, but you've only had that many traditional "birthdays". You've been robbed of the most important birthday there is -- your BIRTH day. As soon as she fits into it, I'll post a picture of her wearing her "Microsoft Future Developer" outfit. Dad is a geek, Sky, you better get used to it.

I look forward to just about everything that is to come. Of course it will be difficult. There will be major hurdles to jump over. Good times and bad times. But what a gift -- I get to live life all over again. I get to experience childhood as an adult.

If you upgrade from Microsoft ASP.NET AJAX Extensions 1.0 to 3.5, and you have a TabContainer inside an update panel, like this:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
 
        <act:TabContainer runat="server">
            <act:TabPanel runat="server">
                <HeaderTemplate>
                    Tab
                </HeaderTemplate>
                <ContentTemplate>
                    Tab Content
                </ContentTemplate>
            </act:TabPanel>
        </act:TabContainer>
 
    </ContentTemplate>
</asp:UpdatePanel>    

...you may notice a change in behavior. When the update panel updates, the UI seems to flicker off and on again, whereas with AJAX 1.0 it seemed to update instantly without any flicker. You may have noticed a similar problem with other components as well, depending on what they are doing.

This is one of those interesting bugs with a convoluted history, driven by browser quirky behavior.

The Tale -- First, some background

Update panels basically work by replacing their content with the new content from the server by setting its innerHTML. However, there may also be components defined within that HTML that register script. Those components need to be recreated now that there is a new set of HTML. UpdatePanel runs those scripts by dynamically creating a new <script> element, setting its content, and then appending the script element to the DOM. It goes something like this:

var script = document.createElement("script");
script.type = "text/javascript";
script.text = "[script that creates a new component]"
document.getElementsByName("head")[0].appendChild(script);

After it has done this for all of the components in the new content, it raises the load event on Sys.Application, among some other page request manager events.

The Browser Quirk

When you append a script element dynamically like this, would you expect the script it contains to execute immediately, or later? Keep in mind we're talking about literal script here, not a reference to another script by url. Remember once all the scripts are appended, page request manager proceeds with raising events. So whether the script executes immediately or later affects whether that component will be created and initialized before, or after those events. That's an important difference.

The intention is for the script to execute immediately. And that was a valid assumption that IE, FireFox, Opera, and Safari all agreed with at the time. That is, until FireFox 2.0.0.2 was released. With that release, FireFox started delaying the execution of the script until later. This caused components to be created after the load events, which broke some AJAX controls that depended on the ordering.

What we did about it

At the time we were in development of Microsoft AJAX Extensions 3.5. We certainly felt that this was a breaking change in FireFox that should be fixed. But we couldn't count on that. We had to fix this problem in AJAX so it wouldn't be a problem whether or not FireFox, or any browser, exhibited this quirk. The fix was to ensure the script executed first, by deferring future operations with a window.setTimeout. It goes something like this:

var script = document.createElement("script");
script.type = "text/javascript";
script.text = "..."
document.getElementsByName("head")[0].appendChild(script);
window.setTimeout(doContinue, 0);
function doContinue() {
    alert('definitely after script executes');
}

window.setTimeout is one of those poorly understood JavaScript features. JavaScript is single threaded. All setTimeout does is queue the referenced function for execution at a later time, when the timeout period has expired and there is no other javascript operation occurring (since only one train can be active at a time). Queuing the script element either executed the script, or it queued it for executing. The window.setTimeout just ensures that 'doContinue' is queued up afterwards. I often see people using this trick, but using a timeout value of "1" or something else very small. There's no reason for that, 0 does the trick, which is easily understood if you understand what it's really doing.

Problem Solved

This indeed solved the problem -- scripts would now execute in the order we intended, regardless of whether the browser executes dynamic inline script elements immediately. And so this fix was released with AJAX Extensions 3.5.

Thankfully, FireFox was also quick to respond. Likely this behavioral change broke other frameworks as well (I can only guess), so there was probably enough of a splash with it to get them to fix it in quick order -- because soon after 2.0.0.2 was released, 2.0.0.3 came out and this behavior reverted back to it's pre-2.0.0.2 behavior. But still, it was good that we had the workaround in place in case this issue ever came up again.

Problem Caused

We didn't see any adverse side effects with the setTimeout work-around, other than a small performance hit on initializing components after an asynchronous update from an update panel. Unfortunately, this turned out to affect some components much more than others. The point at which the setTimeout occurs is after the innerHTML has been replaced, but before component initialization occurs. Any component that performs any serious DOM manipulation from its initialize() method would now be doing so later than it used to. The setTimeout not only delays execution, it also gives the browser more opportunity to draw stuff on the screen. So a component that say, creates a bunch of new elements from initialize, would be causing a FOUC ("flash of uninitialized content"), since the user would first see the natural HTML of the component and then a split second later, the manipulated DOM. This is the cause of the 'flicker' you see with the TabContainer!

The Real Solution

First of all, if at all possible, AJAX components should rely as little as possible on DOM manipulation to create their initial UI. Especially if they are server components as well -- they should render out the initial UI and only manipulate it as needed. This is better practice for FOUC purposes, performance, and probably SEO or script disabled browsers too. I don't know for a fact that the TabContainer is doing this, or if it is really necessary for it to do it, I can only infer that it is based on this behavior.

The Actual Solution

Barring that, the framework should do whatever it can to improve the experience of any controls that need to rely on DOM manipulation from initialize.

Since FireFox fixed the quirk, and no other browsers have experienced it, we have decided the workaround is no longer necessary. All it is doing is hurting performance. If any browser makes this kind of change again, or if a new browser is released that exhibits this quirk, it may not be compatible with some components or applications that rely on the ordering of events (but at least it won't flicker). But the number of components and applications that would have a problem should be very small, and such a quirk we hope would be deemed incorrect behavior and fixed in that browser. It may not be specifically called out in any W3C recommendations (provide me a link if you find one), but it should be, and the fact that the 4 major browsers of today are consistent with this really says something about what the correct behavior is. So all in all, the workaround just it isn't worth the cost anymore.

So the workaround is removed in the upcoming 3.5 Extensions release. But if you want to apply the fix to your 3.5 scripts today without waiting, here is how to do it. The goal is to replace the internal method used by PageRequestManager to load scripts, in the ScriptLoader component. The easiest/simplest way to do it would be to put this script in your own JS file, and then reference it on every AJAX page with the ScriptManager. There other ways of patching it, such as by extracting the AJAX scripts and using the ScriptManager.ScriptPath or ScriptReference.Path feature to point to your modified copy of MicrosoftAjax.js and MicrosoftAjax.debug.js (copies of which are in your program files directory).

Sys._ScriptLoader.getInstance()._loadScriptsInternal = function() {
    if (this._scriptsToLoad && this._scriptsToLoad.length > 0) {
        var nextScript = Array.dequeue(this._scriptsToLoad);
        var scriptElement = this._createScriptElement(nextScript);
 
        if (scriptElement.text && Sys.Browser.agent === Sys.Browser.Safari) {
            scriptElement.innerHTML = scriptElement.text;
            delete scriptElement.text;
        }            
 
        if (typeof(nextScript.src) === "string") {
            this._currentTask = new Sys._ScriptLoaderTask(scriptElement, this._scriptLoadedDelegate);
            this._currentTask.execute();
        }
        else {
            document.getElementsByTagName('head')[0].appendChild(scriptElement);
            Sys._ScriptLoader._clearScript(scriptElement);
            this._loadScriptsInternal();
        }
    }
    else {
        var callback = this._allScriptsLoadedCallback;
        this._stopLoading();
        if(callback) {
            callback(this);
        }
    }

Include this script on your page with a TabContainer, and volia, the flickering will be gone.

This has been a bug tale! Happy coding, I wish you all a non-flickering UI.

UPDATE 05/02/08: Removed the bit about 3.5 extensions preview. The fix isn't in the extensions preview as I originally thought.

Many of the comments I've received in the various dynamic controls entries I've written have been questions for help with a specific scenario. A lot of those scenarios are similar. One in particular I keep hearing is something as follows:

The user is presented with a drop down list of potential items to add to a list of items. As they select an item, it is added to the list. A different type of control is designated to represent each type of item the user can select. Each control provides a unique user interface that is unique to the type it represents.

Dynamic Controls Scenario

The uniqueness of the scenario is that there is a different control designated to 'represent' each data item, depending on the type of that data. The data itself might also be editable within each control.

It is of course necessary to 'dynamically' load the control responsible for each item, since you can't know what they are ahead of time. You also don't know how many there are, and they can be added and removed by the user in the meantime.

Rather than discuss designs for such a page at length (boring!!!), I decided to implement the scenario in a sample application. Also great for really understanding things, I implemented it in 3 different ways, each one progressively better than the last. Hopefully that helps with not only understanding dynamic control scenarios, but understanding alternatives to them or ways of minimizing their use when possible. If a picture is worth a 1000 words, a sample application is worth a 1000 blog entries, I say! Please have a look!

Dynamic Controls By Example Sample Application

Download the sample application here:

TRULY Understanding Dynamic Controls By Example

I get this question a lot for some reason. The more general question is whether it is better to override a virtual method on the page or control in question (OnLoad, OnInit, OnPreRender, etc), or to hook into the corresponding event. For page development you have yet another choice; that magical Page_Load method.

I'm not the first blog out there to talk about this, but I haven't really read them, just skimmed a few. Didn't want to taint my opinion too much... here's my take on it all.

Let's throw it all together... just so we know what we're talking about here.

public partial class _Default : System.Web.UI.Page 
{
    public _Default() {
        Init += new EventHandler(_Default_Init);
        Load += new EventHandler(_Default_Load);
    }
 
    void _Default_Load(object sender, EventArgs e) {
        // load event
    }
 
    void _Default_Init(object sender, EventArgs e) {
        // init event
    }
 
    protected override void OnLoad(EventArgs e) {
        // do something here
        base.OnLoad(e);
        // or should I do something here?
    }
 
    protected void Page_Load(object sender, EventArgs e) {
        // what on earth calls this anyway?
    }
 
    protected override void OnPreRender(EventArgs e) {
        // pre pre render?
        base.OnPreRender(e);
        // post pre render?
    }
}

I think I get this question so much just because my posted samples usually override OnLoad, OnInit, etc, even though the default page-generated code uses Page_Load. So it strikes people as odd, and then they start looking into it too deeply and thinking I have some super secret reason for doing it...

Not really. I just prefer it. But we may as well really look into it.

Performance?
Strictly speaking, calling a virtual method that is overridden should certainly be faster than invoking a delegate (which is what an event is). I don't have proof of this. I haven't done any performance testing. But it makes sense. Page_Load has its own story about this. It's hooked up through the AutoEventWireup feature, which can only be even slower than a traditional event handler. But it should be the last thing on your mind. The difference in performance is probably analogous to a jockey getting a hair cut before a big race, to gain a weight advantage! Yeah... it will help. Some law of thermodynamics probably proves that. But you'd probably get a thousand fold better results out of putting in one more practice instead! Better to worry about the bottlenecks in your app, not low level details like this. Still -- overriding OnX wins here.

Object Oriented?
A component listening to its own event just doesn't seem right to me. Why? Overriding the method is simpler, and less code. (I tried to think of a funny analogy for this one -- talking to yourself, reminding yourself of your own birthday, etc). As for Page_Load, if you were designing a base class for some purpose, would you consider documenting for derived classes that "hey, if you make a method named XYZ_Foo", it will be called when the Foo event occurs!" No, probably not... it's unnecessary complexity, isn't it? Just create a method for them to override! Why reinvent the wheel? You wouldn't automatically go to an event I don't think either, for the same reason.

Consistency/Deterministic Behavior?
What happens when multiple components all subscribe to the same event from the same component, and the event fires? Well you might ask yourself what order they hooked into the event in, and you'd expect them to fire in that order. Nope... .NET makes no promises, there's no first-come-first-serve service here. MulticastDelegates may very well always fire the listeners in the order they were added, but you still wouldn't easily know what order they were subscribed in. Also, components don't have to use one for their events. When you publish an event, you can provide your own custom add/remove implementations, which may not honor order at all. Maybe different components are loaded in a different order depending on who-knows-what? Maybe that isn't the case now, but it will be in 2 years when some poor intern has to fix your code? Never rely on the order of event handlers. That might sound easy enough, but it isn't hard in a complex system to accidentally create a dependency on the order of things. Such a dependency should be obvious through the design of the system.

Using the override approach gives you better control over that, if you know what you are doing. It turns out, the base implementation of OnLoad is what raises the Load event. OnInit raises the Init event, etc. Consider this:

protected override void OnLoad(EventArgs e) {
    // do something here before the load event is raised
    base.OnLoad(e); // the Load event is raised
    // definitely comes after all listeners have been notified.
}

Now you have control over the order of things, at least with respect to the logic you are adding -- whether it comes before or after the event listeners. Furthermore, if anyone derives from this class, they can also control whether their logic comes before or after yours (or both) by deciding when to call base. And the behavior is consistent every time.

Mistakes?
Ok -- so should I put my logic before or after calling base??? And what if I don't call base??? What will blow up? Will the control fail to load?

This is an argument for not using the override method. If you forget to call base, the corresponding event will not be raised. Depending on lots of things, that may or may not cause a problem. It could cause a very subtle problem that you won't catch until much later. But thankfully tools like Visual Studio exist, and they insert the call to base for us automatically. In this OO age, it should be rare for someone to forget this.

Whether you put your logic before or after calling base really depends on the scenario. Personally I always call base last, at the bottom of the method, just because in general I think it makes sense for my component/control to do its own 'X' before raising the 'X' event for external listeners to respond to. If I want to know about anything those external listeners have done to me, then I could have more code after calling base. But let me just say I can't really even think of a time where this should matter. If you end up with code that needs to worry about this, then just pause and consider your design, it's a CodeSmell. You should be able to design it in a manner that doesn't depend on such subtlety.

Purity?
Trying to think like a purest -- I can't decide from that point of view what is right. If the purpose of OnX is to raise the X event, then you shouldn't override it if you're only purpose is to do something when the X event is raised. You should override it if you need to modify to ammend the strict and narrow task of raising the event, right? But listening to the event just smells worse to me. Perhaps OnX should be called RaiseX, and there should be protected OnX methods whose base implementations do nothing at all. That seems more pure... but that's not the way it is :) Purity and reality must collide in the real world to create... pureality.

And to me, that's within the OnLoad method, not the Load event.

So -- should you go around and convert all your apps one way or another? No way. Just stick with what you're used to. You're probably more likely to make mistakes and introduce bugs if you try to change your ways. Not that you would just because you read this :)

UPDATE 3/25 - clarified delegate ordering section.

A long time ago I published one of my first blog entries, TRULY Understanding ViewState. And what an experience it has been. It was pretty popular with commenters, so much so I decided to spin off a whole series of articles, TRULY Understanding Dynamic Controls based on some of the issues people were asking me about.

In the meantime, TRULY Understanding ViewState has accumulated over 250 comments! Most are questions from developers facing problems they cannot solve or architects seeking advice on how to approach a project. I've tried hard to answer each and every commenter with a meaningful answer. I have missed some, but I haven't forgotten about them -- they are still in my outlook inbox with that little red flag on them.

I do enjoy helping people, and I don't expect anything in return -- but here's a reader who really gave back. Trevor Morrison painstakingly combed through each and every comment in TRULY Understanding ViewState, categorized and indexed them, and compiled them into a 69 page word and pdf document! I cannot even imagine how much work that was, thank you Trevor!! He even took the time to highlight key statements throughout. I remember college, and how great used books were, because usually some overachiever had already highlighted all the important parts for me.

Trevor has also been gracious enough to let me publish the index here, for all of you to benefit.

Behold, just one page of the table of contents.

TRULY Understanding ViewState Comments Index - Table of Contents

 

And a random page within... notice the category.

 

TRULY Understanding ViewState Comments Index - Example Page

 

Download the TRULY Understanding ViewState Comment Index [word]. Also in PDF.

If for any reason the above links do not work for you, try the mirror site below, courtesy of Colin Bowern:
http://rockstarguys.com/blogs/colin/archive/2008/02/22/truly-understanding-viewstate-mirrored.aspx

Still relatively unknown, ASP.NET Futures is a nice little add-on to ASP.NET and ASP.NET AJAX that contains some features we want public feedback on. It's a playground in which technology gets to frolic in front of the public's (your) eyes. So why not seize the opportunity to play with the bits and submit your thumbs up, thumbs down?

I thought I'd give an introduction to two of the controls in ASP.NET Futures that I'm most fond of (I've worked on them, so I'm a little bit partial). If you already know about them, excellent, please log in some feedback.

<asp:Xaml runat="server" />

The Xaml control is an integration story between Silverlight and ASP.NET. If you are writing ASP.NET pages that contain Silverlight content, especially if you are also using AJAX features, it's definitely worth a look. Because it's not only an integration of Silverlight and ASP.NET, but between Silverlight and ASP.NET AJAX. It defines a new client-side ajax type, Sys.Preview.UI.Xaml.Control. So, if you are familiar with ASP.NET and with ASP.NET AJAX, this control gives you a logical extension. Just point the control at a XAML resource, and it wraps an ajax type around Silverlight, giving you a familiar and object-oriented asp.net ajax programming model to work with the surface area between the HTML page and the Silverlight plugin instance.

Take a look at a Calculator implemented using the Xaml control.

<asp:Media runat="server" />

I said it is object oriented, and it is. The media control defines another client-side ajax type which derives from the first: Sys.Preview.UI.Xaml.Media.Player. When this type wraps a Silverlight plug-in, it does a lot of work to it, searching within the Xaml document for elements of certain predetermined names like "PlayButton", and makes them more than just a pretty Canvas by adding behavior to them implied by their name. It may seem trivial, but there are a lot of subtle things that must happen to make what is essentially static markup (the xaml) behave like a full-blown media player. Silverlight makes it look pretty. The Media control brings it to life.

Not just a black box

When you watch video on a web page, you probably don't expect much in the way of interaction between the video and the page. The video is like a rich island in the middle of boring HTML, and never the twain shall meet. Even the orientation of the video is pretty much fixed -- ever seen a movie playing on a webpage at at 15 degree angle? I haven't. I'm not sure I want to, but I sure haven't!

But it doesn't have to be that way... The media control exposes some pretty cool client-side APIs in the form of properties and events that allow for some really interesting interaction between the media and the rest of the page. asp:Media... Tearing down walls!

Take a look at some of the cool things you can do with it.

Not just for fun, either

The Media control can work with any Xaml. It's very forgiving with which Xaml elements it requires, too. What? Your Xaml doesn't have a MuteButton? Ok, no problem. But it does have a WizzyWigDoSomethingButton -- well, it doesn't know what that is, but a client-side type you create that derives from the media player's client side type knows what to do with it.

The only element required is the MediaElement. Yeah you kind of need that one...

You get the picture. But what most people don't know, even those who use it, is that the client-side code that drives the Media control has already appeared in many places. So many, in fact, that if you've seen video playing in Silverlight, you've probably executed the code. The code was joint developed and is shared by the Expression Encoder product, which allows you to export videos to html for execution in Silverlight. It too creates nice media player functionality in Silverlight... and it does it using the exact same code the Media control uses. Well, the namespace is different. But that's it.

Here are some examples of sites using the Media control's client-side ajax type. Note how vastly different they look and behave -- a testament to Silverlight and this control.

So there you have it. If you want to play video or audio on your site using Silverlight, and you don't want to implement an entire media player UI from scratch, have a look-see.

EDIT: Hey, my first post tagged "Silverlight". Expect more in the future.

I've struggled with pretty bad headaches probably ever since high school. They come and go with intensity and frequency. Sometimes I think I have them figured out. Eat right, and before I get starving, get enough sleep, and they usually leave me alone. But stressful times, like long business trips or big presentations, or other matters, can easily prompt one. I've grown so used to them that I always make sure I have a supply of Excedrin nearby. There's a bottle at home, up and down stairs, at work, even in the car for those unexpected times. I even have family members be sure to have a stock if I know I'll be visiting for an extended period of time.

For whatever reason, Excedrin seems to be the only thing that helps. Nothing else even touches my headaches. But sometimes, on rare occasions, even Excedrin fails. Today was one of those times.

Bad enough that I finally went to a doctor about it (I was lucky to get a walk-in appointment). After describing all my symptoms, sure enough, these Excedrin-immune headaches are the migraine variety.

If you've had a migraine, I need not explain how terrible they are. If you're one of the lucky ones who don't get them, well, for me they on par with a really bad hangover.

There are lots of options these days for dealing with them. The key is preventing them by understanding what triggers them for you. I've lived with them all my life so far because they crept up on me. I never thought they were migraines because descriptions I read of them seem much more severe than what I have. Indeed I do seem to be luckier than most migraine sufferers -- they are bad, but not so bad that I must lock myself in a dark room for two days. Just thought I'd share my experience -- I'm sure lots of you can relate!

Perhaps this is one sub-conscious reason why I prefer The Dark Side of Visual Studio. The bright light of the normal color scheme is just too overpowering.

 

I recently received a comment in my Truly Understanding ViewState article about the "ArrayList of controls in the control hierarchy that need to be explicitly invoked by the page class during the raise postback event stage of the life cycle." Such is the 3rd entry in the master Triplet that makes up ViewState as a whole.

It was a very excellent question, and in some quick searches I don't see any really clear topics dedicated to answering it, so I decided to answer it with a blog post rather than bury it at the bottom of 100 comments. You can read the comment here.

 

Page.RegisterRequiresPostBack

To understand why this method is needed, lets walk through what happens when you use an ImageButton.

When you click on an html element of the <input type=image> variety, what is added to the form collection sent to the server is not what a normal button sends. A normal button sends the key/value pair "id=value". But an image submit sends "id.x=##&id.y=##". It sends 2 values, the x and y coordinates of the location of the image you clicked.

This means the KEY of the submission will not match the ID of the control. Normally, ASP.NET matches keys to their control IDs, and is able to find the control directly with FindControl() (which also has the indirect effect of calling EnsureChildControls). But it won't find a control named "id.x" or "id.y", so that ImageButton will never be notified of the postback data it generated.

All is not lost! RegisterRequiresPostBack comes the rescue. It tells asp.net to notify the control of postback data regardless of whether the form collection contains an entry for it. ImageButton can now happily look for "id.x" and "id.y" in the form data, and raise its click event if it is found.

Now why is there a list of controls that call RegisterRequiresPostBack in ViewState of all places? Because when you call RegisterRequiresPostBack, you're doing so for the next request not the current one. You're saying, "when what I'm rendering right now is posted back, I want to be notified." So ASP.NET needs to maintain the list of controls in ViewState so it can do so on the next request.

Some people have complained that even when they disable ViewState for the entire page, they see ViewState in their page. This is one of the reasons for that. It is simply required for the controls to function, it cannot be turned off.

The humble CheckBox

Another control the calls RegisterRequiresPostBack is the humble CheckBox control. When you post a form, any checked checkboxes are added to the form collection with "id=value". However, and quite unfortunately if you ask me, unchecked checkboxes add NOTHING to the form collection.

Ok -- so a CheckBox knows it is checked if its post data key exists, and unchecked if it is missing, right? Nope, sorry, that simply won't do. What would happen to a checkbox that is first created during a postback? For example, a checkbox within a databound control that has just been databound? How does that CheckBox know whether it is unchecked or has just been born into the world, err, page? The only way to know the difference is RegisterRequiresPostBack. If not for that, all checkboxes first created during postbacks would always start off unchecked, even if they were databound or declared to be checked.

Homework

Open up reflector and find the Page.RegisterRequiresPostBack method. Use the analyzer to find all the controls that call it. Try to understand why each of them needs it. I assure you, they all have good but distinct reasons.

This question comes up from time to time, to time. If you understand how redirects work, then you also know it is "not possible" to redirect into a new window, because a redirect on the server causes a special HTTP response to be sent to the users browser, the client. The browsers native implementation interprets the special response code and sends the user off to the destination. There's no built-in mechanism or standard for specifying a new window.

The only way to open a new window is for it to be initiated on the client side, whether it be through script or clicking on a link.

So the solution always proposed to this problem is to instead write out some script that opens the window, rather than using Response.Redirect:

<script type="text/javascript">
    window.open("foo.aspx");
</script>

Ok... so first you lecture me about how it is "not possible", and then you give me the code that makes it possible. Why can't I just redirect to a new window -- I don't care how HTTP works or client this or server that. There's obviously a solution, so why do I have to worry about it?

(The make-believe developers in my head are always quite temperamental)

It's easy enough to write a little helper that abstracts the details away from us... while we're at it, we might as well add 'target' and 'windowFeatures' parameters. If we're going to open the new window with script, why not let you use all of the window.open parameters? For example, with 'windowFeatures' you can specify whether the new window should have a menu bar, and what its width and height are.

public static class ResponseHelper {
    public static void Redirect(string url, string target, string windowFeatures) {
        HttpContext context = HttpContext.Current;
 
        if ((String.IsNullOrEmpty(target) ||
            target.Equals("_self", StringComparison.OrdinalIgnoreCase)) &&
            String.IsNullOrEmpty(windowFeatures)) {
 
            context.Response.Redirect(url);
        }
        else {
            Page page = (Page)context.Handler;
            if (page == null) {
                throw new InvalidOperationException(
                    "Cannot redirect to new window outside Page context.");
            }
            url = page.ResolveClientUrl(url);
 
            string script;
            if (!String.IsNullOrEmpty(windowFeatures)) {
                script = @"window.open(""{0}"", ""{1}"", ""{2}"");";
            }
            else {
                script = @"window.open(""{0}"", ""{1}"");";
            }
 
            script = String.Format(script, url, target, windowFeatures);
            ScriptManager.RegisterStartupScript(page,
                typeof(Page),
                "Redirect",
                script,
                true);
        }
    }
}

Now you just call ResponseHelper.Redirect, and it figures out how to honor your wishes. If you don't specify a target or you specify the target to be "_self", then you must mean to redirect within the current window, so a regular Response.Redirect occurs. If you specify a different target, like "_blank", or if you specify window features, then you want to redirect to a new window, and we write out the appropriate script.

One nice side effect of this "do you really need a new window?" detection is that it's dynamic. Say the destination you redirect to is configurable by some administrator. Now they can decide whether it opens in a new window or not. If they don't want it to they can specify blank or _self as the target.

Disclaimers:

Note: If you use it outside the context of a Page request, you can't redirect to a new window. The reason is the need to call the ResolveClientUrl method on Page, which I can't do if there is no Page. I could have just built my own version of that method, but it's more involved than you might think to do it right. So if you need to use this from an HttpHandler other than a Page, you are on your own.

Note: Beware of popup blockers.

Note: Obviously when you are redirecting to a new window, the current window will still be hanging around. Normally redirects abort the current request -- no further processing occurs. But for these redirects, processing continues, since we still have to serve the response for the current window (which also happens to contain the script to open the new window, so it is important that it completes).

Extension Methods

Recently, Eilon and Bertrand blogged about a novel use of some C# 3.0 features. Eilon posed the question, "Have you come up with a novel way to use a new language feature that you'd like to share?". Well here you go.

Extension Methods are a new feature in C# 3.0 (you'll need it for the rest of the article). They allow you to add methods to existing types, imported via a 'using' statement. I've seen a lot of debate over their use -- whether they are bad or good. Well -- I don't know, I don't really want to be involved in that debate. But I do know that in some scenarios they seem to fit perfectly. Like all language tools, you should use it sparingly and only when appropriate. I believe even the dreaded GOTO statement, which yes, exists in C#, has its place (I wasn't a believer originally, but some old coworkers of mine convinced me (Bob!)).

In this case, an extension method seems to work well. In general, whenever you find yourself writing a static Helper class whose only purpose in life is to help use the APIs of another type, it's probably a great candidate for extension methods. Especially if the first parameter to all those methods is the type you're trying to help with -- or if the methods always grabs the instance through some static API (like HttpContext.Current) or instantiates a new one.

By rewriting our ResponseHelper to use extension methods...

public static class ResponseHelper {
    public static void Redirect(this HttpResponse response,
        string url,
        string target,
        string windowFeatures) {
 
        if ((String.IsNullOrEmpty(target) ||
            target.Equals("_self", StringComparison.OrdinalIgnoreCase)) &&
            String.IsNullOrEmpty(windowFeatures)) {
 
            response.Redirect(url);
        }
        else {
            Page page = (Page)HttpContext.Current.Handler;
            if (page == null) {
                throw new InvalidOperationException(
                    "Cannot redirect to new window outside Page context.");
            }
            url = page.ResolveClientUrl(url);
 
            string script;
            if (!String.IsNullOrEmpty(windowFeatures)) {
                script = @"window.open(""{0}"", ""{1}"", ""{2}"");";
            }
            else {
                script = @"window.open(""{0}"", ""{1}"");";
            }
 
            script = String.Format(script, url, target, windowFeatures);
            ScriptManager.RegisterStartupScript(page,
                typeof(Page),
                "Redirect",
                script,
                true);
        }
    }
}

Note the 'this' keyword in the first parameter. Now whenever we include the namespace this class is defined within, we get a nice override on the actual Response object.

ResponseRedirect

Simply including a 'using' to a namespace is what gets extensions methods to show up. So it's probably a good idea to keep extension methods isolated to their own namespaces, lest someone get more than they bargained for when they use your namespace.

Also worth noting is that this is still a static API, so you can use it the traditional way, too. You just have to pass in the Response object as the first parameter.

And to see it in action...

Response.Redirect("popup.aspx", "_blank", "menubar=0,width=100,height=100");

Redirected into a new Window...

More Posts Next page »