Categories
Uncategorized

WAT? A Funny Look at Ruby and JavaScript Oddities

WAT: A donkey in an orange raincoat, standing on the deck of ship holding a tabby cat

The Urban Dictionary definition of "wat" is "the only proper response to something that makes absolutely no sense". The concept of wat is covered a little more completely on its page in Know Your Meme.

Darth Vader standing in the ocean, pouring water from a Brita pitcher into a plastic jug

"Wat" is also the title of a funny demo of Ruby and JavaScript oddities presented by Gary Bernhardt at CodeMash 2012, a rather unlikely tech conference — it takes place in Sandusky, Ohio, in Ohio’s largest indoor waterpark. (If you just said "wat" right now, you’ve used the word correctly.)

In the video, you see this classic wat bit about undefined variables and assignment in Ruby:

Screenshot of an irb session full of wat

You’ll also marvel at the way JavaScript treats (array + array) vs. (array + object) vs. (object + array) vs. (object + object):

Screenshot of a jsc session full of wat

Watch the video, and wait for that final slide, which is pure, hilarious wat!

This article also appears in the Shopify Technology Blog.

Categories
Uncategorized

The jQuery Online Conference: Monday, July 12th – Everywhere!

ThinkVitamin presents...The jQuery Online Conference

Are you a web developer and want to sharpen your jQuery skills? Would you like to attend a conference featuring some of the brightest lights in jQuery programming? Are you too short on time and travel expenses to hit such a conference?

For a mere US$150 and no travel at all, you can attend the jQuery Online Conference. It’s a live, over-the-‘net conference taking place on Monday, July 12th starting at 12:00 noon EDT / 9:00 a.m. Pacific and featuring these four sessions:

  • Beyond String Concatenation. Using jQuery Templating to Cleanly Display Your Data
    Rey Bango (Client-Web Community Program Manager for Microsoft and Head of Evangelism for the jQuery JavaScript Project)
    In this presentation, Rey will show you a new way to produce easily maintainable dynamic pages via pre-built JavaScript templates and the Microsoft jQuery templating plugin.
  • Testing Your Mobile Web Apps
    John Resig (JavaScript tool developer for Mozilla and creator of jQuery)
    This talk will be a comprehensive look at what you need to know to properly test your web applications on mobile devices, based upon the work that’s been done by the jQuery team. We’ll look at the different mobile phones that exist, what browsers they run, and what you can do to support them. Additionally we’ll examine some of the testing tools that can be used to make the whole process much easier.
  • Taking jQuery Effects to the Next Level
    Karl Swedberg (Web developer at Fusionary Media, member of the jQuery Team, author of jQuery 1.3 and 1.4 Reference Guides and maintainer of the jQuery API site)
    One of the first things web developers learn to do with jQuery is to show and hide elements on a page and then add some flair by sliding those elements up and down or fading them in and out. Too often, though, we stop there, missing out on the incredible range and flexibility of jQuery’s core effects. In this talk, we’ll investigate both standard and custom animations and how they can be used to create useful and fun effects. We’ll also build a couple effects plugins, explore parts of the effects API that are often overlooked, and learn how to avoid common problems when attaching these effects to certain events.
  • jQuery Pluginization
    Ben Alman (Developer at Boston.com, contributor to jQuery and Modernizr)
    In this live-coding session, Ben explains how, with just a little thought and effort around generalization, parameterization and organization, you can convert your "just get the job done" jQuery code into a legitimate, reusable, modular jQuery plugin.

Your conference attendance fee not only lets you watch the live event and ask questions of the presenters, it also lets you watch the recordings of the events any time afterwards. So if you can’t catch the live event (perhaps you’re busy at work, or it’s 3:00 a.m. in your time zone), you can still watch the presentations. This also lets you watch the live event to get the general idea, and then watch it again for note-taking or hands-on workshopping.

This article also appears in Canadian Developer Connection.

Categories
Uncategorized

Internet Explorer 9 Videos on Channel 9

nine on 9By now, you’ve probably seen my article covering the new, faster, even more standards-compliant Platform Preview 3 of Internet Explorer 9. From hardware acceleration to a speed-boosted JavaScript engine with support for new ECMAScript 5 language features to support for SVG, <audio>, <video> and <canvas> tags, IE9 is shaping up to be a great browser for an open web.

Before there were Microsoft blogs (such as Canadian Developer Connection), there was Channel 9, Microsoft’s community site run by Microsoft employees. Like Microsoft blogs, Channel 9 gives you unfiltered access to the people building stuff at The Empire, all outside the control of the marketing and PR departments. Channel 9 features a lot of videos – there are times when they post several videos in a day – featuring developer news and training, training kits and courses, discussion forums and wikis for various Microsoft tools and technologies. If you’re a .NET developer or just curious about what’s going on the in the .NET world, you should check out Channel 9 and see what’s happening.

Channel 9 posted a number of videos covering the new features in the third Platform Preview of Internet Explorer 9. I’ve gathered them all into this blog article – enjoy!

A Look at the New IE9 Demos

Get Microsoft Silverlight

Can’t see the video? You can download and install Silverlight or download the video in MP4, MP3, WMA, WMV, WMV (High) or Zune formats.

This video shows some of the sample apps living on the IE Test Drive site in action. It covers the following demos:

<canvas> and FishIE Tank

Get Microsoft Silverlight

Can’t see the video? You can download and install Silverlight or download the video in MP4, MP3, WMA, WMV, WMV (High) or Zune formats.

Here’s a closer look at the FishIE Tank demo and how it makes use of <canvas> to draw up to thousands of animated, moving, scaling fish sprites.

<canvas> and Amazon.com

Get Microsoft Silverlight

Can’t see the video? You can download and install Silverlight or download the video in MP4, MP3, WMA, WMV, WMV (High) or Zune formats.

Another <canvas> demo: Amazon Shelf. This one ties into Amazon’s data to create a virtual bookshelf that lets you browse Amazon’s catalogue of books.

<video> and IMDb Video Panorama

Get Microsoft Silverlight

Can’t see the video? You can download and install Silverlight or download the video in MP4, MP3, WMA, WMV, WMV (High) or Zune formats.

The IE9 team showed a preview of support for the <video> tag, and with Platform Preview 3, you can try it out for yourself. In this video, you see how it’s used to build the IMDb Video Panorama demo.

ECMAScript 5 and the Tile Game

Get Microsoft Silverlight

Can’t see the video? You can download and install Silverlight or download the video in MP4, MP3, WMA, WMV, WMV (High) or Zune formats.

There are lots of boring ways to show of ECMAScript 5’s new array methods in action, but why not show them off with a fun game? In addition to the new JavaScript goodies, the ECMAScript 5 Game demo also shows off:

  • HTML5 <video> and <audio>
  • CSS3 multiple backgrounds
  • HTML5 local storage (first made available in IE8)
  • DOM Level 3 events
  • <window.getComputedStyle()>

Download IE9 Platofmr Preview 3 now!

This article also appears in Canadian Developer Connection.

Categories
Uncategorized

IE9 Platform Preview 2

It wasn’t that long ago that an early version of Internet Explorer 9 – we called it Platform Preview 1 – was announced at MIX10 Conference back in mid-March. If you missed it, here’s MIX10’s Day 2 keynote session, in which the Internet Explorer team’s supreme Kahuna, Dean Hachamovitch, made the announcement (it’s the first part of the keynote, so you don’t have to watch or scan through the entire two hours):

Get Microsoft Silverlight
Don’t have Silverlight? Download it here,
or watch the video in WMV, high-def WMV or MP4 format.

As I wrote back then, IE9 showed a lot of improvements. In addition to the improvements, IE9 came with a commitment made to updating the preview about every eight weeks.

The time has come to announce the release of IE9 Platform Preview 2! The whole story’s over at the latest post to IEBlog, but I thought I’d cover a couple of things I felt were worth noting.

Improved JavaScript Performance

Chart showing JavaScript performance of various browsers

The chart above shows the results of various browsers, including IE9 Platform Preview 2, under WebKit’s Sunspider JavaScript benchmark, version 0.9.1 on a 3.0GHz Dell Optiplex with an Intel Core 2 Duo processor, 4GB RAM and Intel Integrated Video running Windows 7. As you can see, JavaScript performance on Platform Preview 2 is a mere eye-blink away from that of the Esteemed Competition.

If you’d like to run the SunSpider JavaScript benchmark in your default browser right now, click here.

Getting HTML5ier

Acid3 test for Internet Explorer 9 Platform Preview 2 - 68/100

The goal for the final release of IE9 is full HTML5 compliance and “Same Markup” – that is, rendering the same HTML, CSS and JavaScript the same way. The idea is that you, the web developer, shouldn’t have to come up with workaround or hacks to get the same page to display the same way across browsers.

If you’d like to run the Acid3 test in your default browser right now, click here.

Part of that approach is technical: a standards-compliant IE9, and the first platform preview was a step in that direction. Platform Preview 2 add more fixes to HTML, SVG, CSS3 and JavaScript implementations as well as features like CSS3 media queries, DOMContentLoaded, DOM traversal and range, getElementsByClassName, createDOcument and so on.

While the Acid3 test isn’t the holy grail – some of its tests don’t mesh with the HTML5 standard as it is right now, others are still “under construction” – more compliance with HTML5 typically means a higher Acid3 score. IE9 Platform Preview 2 currently scores 68 out of a possible 100, which is an improvement over Platform Preview 1’s score of 55, and leaps and bounds ahead of IE8’s scores for 20.

People Issue : Standards

Another part of the “Same Markup” approach is working within the various standards groups defining the web experience. Among other things, we’ve been doing things like:

People Issue : Developers

Let me show you a couple of photos from Toronto Code Camp, which took place last Saturday. Here’s Colin Bowern’s session, titled JQuery is Your Friend:

Colin Bowern presenting at Toronto Code Camp to a packed room

That was a fairly packed room, but that ain’t nuthin’ compared to Todd Anglin’s afternoon session, The Rich Standard: Getting Familiar with HTML5, which went beyond “standing room only” and into the “any place I can park myself” zone:

Todd Anglin presenting at Toronto Code Camp to a very packed room

From looking at the crowd – and yes, talking with them, too – it’s quite clear that there’s a lot of hunger for information, tutorials, guidance and general knowledge of HTML5, CSS3 and JavaScript and how to build modern web applications using them.

That’s where I can help, and in all sorts of ways. For starters, there will be a number of HTML5, CSS3 and JavaScript articles, tutorials and pointers on this blog. I’ll also be participating in a number of presentations, workshops and TechDays events to cover HTML5, CSS3 and JavaScript. Keep watching this space for more.

Take IE9 Platform Preview 2 for a Spin!

Windows Internet Explorer 9

You can download Internet Explorer 9 Platform Preview 2 right now. As with Platform Preview 1, it coexists with Internet Explorer 8, and it’s a very thin wrapper around the engine, meaning that it’s really for developer and designer testing rather than general browsing. The UI elements you’d expect in a browser, such as the address bar (you open sites using File –> Open…), nor are the security features such as Protected Mode, SmartScreen filter and XSS scripting filter.

Platform Preview 2 installs right over Platform Preview 1; you don’t have to uninstall Platform Preview 1 before installing Platform Preview 2.

Take it for a spin and send us feedback!

This article also appears in Canadian Developer Connection.

Categories
Uncategorized

jQuery 1.4 Released / 14 Days of jQuery

jQuery logo: "Write less, do more."In case you hadn’t heard the news last week, the newest version of the jQuery JavaScript library, version 1.4, has been released! Even with the new features, it’s still tiny: the uncompressed development version is 156KB and the minified production version is a svelte 23KB when gzipped.

To celebrate this release, the jQuery folks have created a site called The 14 Days of jQuery, where they’ll post all sorts of supporting articles on the jQuery 1.4 for 14 days, starting on the day that was both the release date of jQuery and its birthday, January 14th. So far, they’ve posted the expected download links to jQuery 1.4 as well as a Q&A session with some of the jQuery team, a jQuery podcast with John Resig, a contest for the coolest use of jQuery, a presentation of how to get involved in the jQuery community and more.

This article also appears in Canadian Developer Connection.

Categories
Uncategorized

Taking JavaScript Performance to the Extreme with Thomas Fuchs

"Extreme JavaScript Performance" (from JSConf.eu, November 7)

thomas fuchsTake a look at the slides from Extreme JavaScript Performance, a presentation by Thomas Fuchs, creator of the script.aculo.us JavaScript library, collaborator on the book Agile Web Development with Rails and one of the people behind FailCamp. He gave the presentation last week at JSConf.eu in Berlin.

In the presentation, Thomas looked at six simple things you can do to boost the performance of your JavaScript:

  • Use inline functions instead of function calls.
  • Embrace the language – using the language’s conventions yields unexpectedly faster code. Instantiate arrays using var myArray = [] instead of var a = new Array, and instantiate objects using var myObject = {} instead of var o = new Object.
  • Unroll your loops! (A trick so old that we covered it when I was in school!)
  • Cache globals. If you’re going to access a global object, store a local reference and use that instead.
  • Tune your boolean expressions: in logical “AND” (&&) operations, make the operand most likely to be false the first one.
  • Watch out for slow constructs such as with blocks, try/catch and features that JIT compilers don’t support well.

The presentation includes benchmarks for the four most common JavaScript engines:

  • SpiderMonkey (Firefox 3.5)
  • JavaScript Core (Safari 4)
  • JScript (Internet Explorer 8)
  • V8 (Google Chrome)

And yes, he does warn you – at least twice – of the dangers of premature optimization.

JavaScript Performance Rocks

JavaScript performance rocks

If you liked Extreme JavaScript Performance, you’ll love the ebook Thomas co-authored with Amy Hoy, JavaScript Performance Rocks! Actually, it’s more than just a book – it’s four books and a profiling tool:

  • Book 1: Understanding and Measuring Performance (or: “Dude, Where’s My Performance?”) – “In which our brave hero or heroine (that’s you!) apprentices to the cryptic-but-charming Master (that’s us) and learns how to get into the enemy’s head—the better to eat it alive, my dear.”
  • Book 2: Loadtime (or: “The Land of Unicorn Tears”) – “Loadtime is a sad time, a time of of enormous, slow-loading assets; of maxed-out request queues; of bloated, waddling DOMs. Of limp white screens. Most of the world’s worst web performance woes? They live and breed in Loadtime. That’s why it’s the Land of Unicorn Tears, because unicorns hate slow web apps just as much as the rest of us. And they have magical horns. So there.“
  • Book 3: Runtime (or: “’Cuz Tuning Loops is Hardcore”) – “The vast majority of the problems that the vast majority of apps will have can be solved with loadtime fixes of various stripes. But just in case you’re unique, and special, and have particularly intractable issues—or are just a glutton for punishment—we have written a third booklet, all about speeding up code when it runs.”
  • Book 4: Interface Coping Strategies (or: “If You Can’t Fix It, Fake It”) – “Come across a performance problem that you really can’t fix? Long-running calculations? Slow server you can’t tune up? If you can’t make it, fake it. You can make your app feel faster to your customers, even if you can’t fix the underlying problem. And, let’s face it, that’s what your customers care about.”
  • The DOM Monster profiling tool.

JavaScript Performance Rocks! isn’t your ordinary ebook, with material laid out for a dead-tree book simply cast in PDF form. It was designed from the ground up for onscreen reading, written in an entertaining way to keep you amused and your mind ready to learn, and written in a fun, irreverent way so that you don’t zone out. I know Thomas and Amy personally and have seen them teach; trust me – you want to learn from them.

JavaScript Performance Rocks! usually sells for US$49, but there’s a special deal right now – the first 500 books are selling for 10 dollars less — US$39. You’ve got two good reason to buy immediately: first, there’s this $10 discount, and second, the US/Canada exchange rate’s pretty good right now (as I write this, the PayPal exchange rate is CAD$1 = US$0.92).

I’ve already ordered my copy.

This article also appears in Canadian Developer Connection.

Categories
Uncategorized

A Fix for the Error in Hour 9 of “Teach Yourself ASP.NET Ajax in 24 Hours” / Client-Side Error Handling in ASP.NET Ajax in .NET 3.5

Cover of "Teach Yourself ASP.NET Ajax in 24 Hours"While following the exercises in the book Teach Yourself ASP.NET Ajax in 24 Hours – one of the few books I’ve been able to find on Ajax for ASP.NET 3.5 – I found an error in the “Hour 9” chapter in the example that covers client-side error-handling (it starts on page 137). I’ve reported this error to the publisher and with any luck, they’ll post a corrected version on their support web page for the book.

I’ve done some searching and haven’t found anything covering this error so I thought I’d cover it here. Better still, I’ll also cover the fix, which turns out to be quite simple. If you’ve been trying out the code in the book and wondering why it doesn’t work, relax: at least in this case, it’s not your fault.

In the course of covering the error and how to fix it, I’ll also talk about how ASP.NET handles exceptions raised by asynchronous postbacks and how you can make use of it to make better user interfaces. Even if you don’t have a copy of Teach Yourself ASP.NET Ajax in 24 Hours, you should find this article an interesting introduction to client-side error handling in ASP.NET Ajax.

Unhandled Exceptions and Asynchronous Postbacks

In ASP.NET Ajax, if an exception is raised during an asynchronous postback and isn’t handled on the server side – that is, in the code-behind – it gets passed along to the client side. What happens on the client side depends on which version of ASP.NET you’re using:

  • In ASP.NET Ajax 1.0, the server-side exception object is serialized into JSON. The JSON is sent to the client, which displays the exception’s message property in an alert box.
  • In ASP.NET Ajax for .NET 3.5, the server-side exception is still serialized into JSON and the JSON is still sent to the client. However, instead of displaying the exception’s message property in an alert box – a presumptuous design decision, if you want my opinion – the client throws the exception, which gives you the opportunity to handle it on the client side as you please.

(In this article, I’ll stick to covering ASP.NET Ajax for .NET 3.5.)

This is quite different from most other web application frameworks, where an exception raised as the result of an XMLHttpRequest call to the server results in some kind of “error” page from the server (or a blank page, if you’re suppressing error reporting).

To illustrate this, let’s put together a simple ASP.NET Ajax application. It’s a single page with a single button, that if clicked, throws an exception.

Here’s the code for the page layout. It’s pretty straightforward:

Listing 1: Default.aspx – Layout for the page of our simple ASP.NET Ajax application.

<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Error Handling Demo 1</title>
</head>

<body>
    <form id="form1" runat="server">
        
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <asp:UpdatePanel runat="server" ID="UpdatePanel1">
                <ContentTemplate>
                    <asp:Button runat="server" ID="Button1"
                    Text="Click Me" OnClick="Button1_OnClick" />
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
        
    </form>
</body>

</html>

Some notes about the code:

  • The ScriptManager control at the top of the form enables Ajax by ensuring that the JavaScript needed to support ASP.NET Ajax on the client side is downloaded to the browser.
  • The UpdatePanel control determines the controls that trigger asynchronous postbacks and defines the region of the page that can be updated via Ajax.
  • Button1 is the button control that we want to throw an exception when clicked. We’ll set it to call the Button1_OnClick method, which will contain the exception-throwing code.

The code-behind is very simple. In it, we define a single method: the event handler Button1_OnClick, which is called in response when the user clicks Button1. All we want it to do is throw an exception that uniquely identifies itself:

Listing 2: Default.aspx.cs – Code-behind for the page of our very simple example app.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Button1_OnClick(object sender, EventArgs e)
        {
            throw new Exception("Click!");
        }
    }
}

Running with Debugging vs. Running Without Debugging

Listing 1 and 2 give us enough to make our simple app work. It’s time to take it for a spin.

Here’s something that doesn’t get covered in Teach Yourself ASP.NET Ajax in 24 Hours: what happens when you try to run this app with debugging (starting it by hitting F5 in Visual Studio or “Start Debugging” under the “Debug” menu)?

Here’s a screenshot of what happened for me: simple_app_with_debugging

With debugging on, the unhandled exception thrown in Button1_OnClick is caught by the debugger. Normally, this sort of error-catching behaviour is welcome, but in this particular case, it gets in the way of what we’re trying to achieve: having an exception on the server side and passing it along to the user’s browser to handle.

If we run the same app without debugging, we get the effect we want: the exception is raised on the server side, but the server-side part of the application doesn’t halt with an error message. Instead, the client shows the error message.

Here’s a screenshot. Note that the error message includes the string “Click!”, which is the argument in the throw statement the Button1_OnClick event handler. Thanks to this, we can be pretty certain that the error message is the result of our deliberately-thrown exception:

image

Now that we have the exception that we threw on the server side being handled on the client side, let’s do something with it. 

Handling Exceptions Passed from the Server on the Client Side

Let’s do something simple – let’s catch the exception caused by the button click, and instead of having a JavaScript error box pop up, let’s make a couple of changes to the button:

  • Change its text to “This button has been disabled for your safety.”
  • Disable it.

To handle exceptions on the client side, we need to write some client-side JavaScript. Luckily, this is made simple by the number of handy utility classes defined in the scripts downloaded to the client by the ScriptManager component. In this case, we’re going to make use of the Sys.Webforms.PageRequestManager class to deal with the exception because it provides us with the following:

  • The endRequest event, which is raised after an asynchronous postback has completed and control is returned to the browser.
  • The add_endRequest method, which specifies a method to call when the endRequest event is raised.

Here’s the JavaScript, which we’ll put in a file called ErrorHandler.js:

Listing 3: ErrorHandler.js — Client-side error handler for our very simple example app.

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

function EndRequestHandler(sender, args)
{
    if (args.get_error() != undefined) {
        $get('Button1').value = "This button has been disabled for your safety.";
        $get('Button1').disabled = true;
        args.set_errorHandled(true);
    }
}

The script performs the following:

  • It registers the method EndRequestHandler as the method to call whenever the endRequest event is raised.
  • It defined the method EndRequestHandler, which does the following:
    • If an exception did occur during the asynchronous callback:"
      • The button’s text is changed
      • The button is disabled
      • The error is reported as handled, which allows the application to continue

Now that we have this client-side code, we need to get it to the client. We do this by using the Scripts section of the ScriptManager to send this file to the client. The listing below shows the updated layout code for our simple application. I’ve highlighted the change in the listing below:

Listing 4: Revised Default.aspx – Layout for the page of our simple ASP.NET Ajax application.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Error Handling Demo 1</title>
</head>

<body>
    <form id="form1" runat="server">
        
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
                <Scripts>
                    <asp:ScriptReference Path="~/ErrorHandler.js" />
                </Scripts>
            </asp:ScriptManager>
            <asp:UpdatePanel runat="server" ID="UpdatePanel1">
                <ContentTemplate>
                    <asp:Button runat="server" ID="Button1"
                    Text="Click Me" OnClick="Button1_OnClick" />
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
        
    </form>
</body>

</html>

The Scripts section of the ScriptManager lets us specify scripts to be sent to the client along with the page, with each script specified in a ScriptReference tag.

When we run the app (remember, without debugging on) with these changes and click the button, here’s what we get:

Button with text "This button has been disabled for your safety"

In a later article, I’ll look at other ways of using client-side error handling in ASP.NET Ajax in .NET 3.5.

The Error in Teach Yourself ASP.NET Ajax in 24 Hours

Here’s the page layout code for the error-handling example in Teach Yourself ASP.NET Ajax in 24 Hours. The code-behind for the page and the client-side JavaScript are fine, it’s this code that has the error. See if you can spot what’s amiss:

Listing 5: Default.aspx — Page layout of client-side error-handling example in Hour 9 of Teach Yourself ASP.NET Ajax in 24 Hours.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
Inherits="WebApplication1._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:UpdatePanel runat="server" ID="UpdatePanel1"> <ContentTemplate> <asp:Button runat="server" ID="Button1" Text="Click Me" OnClick="Button1_OnClick" /> </ContentTemplate> </asp:UpdatePanel> </div> <br /><br /> <div id="Message" style="visibility: hidden;"> <asp:HyperLink ID="HyperLink1" runat="server" Font-Bold="true" Text="Error Occurred..." Font-Italic="true" ForeColor="red" > </asp:HyperLink> </div> </form> </body> </html>

Just for kicks, here’s what happens when you click on the button in the app using the code straight from Teach Yourself ASP.NET Ajax in 24 Hours:

Screen capture of resulting error message from original "Teach Yourself ASP.NET Ajax in 24 Hours" application

The mistake is simple: although there is some error-handling client-side JavaScript in the app, it’s not referenced in the ScriptManager tag, which means it’s not sent to the client. Without error-handling code on the client side, the exception is thrown, there’s nothing to catch it and the user is presented with the standard error dialog box.

The fix is equally simple: reference the script in the ScriptManager tag’s Scripts section:

<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Scripts>
        <asp:ScriptReference Path="~/ErrorHandlingScript.js" />
    </Scripts>
</asp:ScriptManager>

Once that’s done, the program works as promised.