11 April 2011

IIS6 to IIS7 - Catching Ajax errors

The way Ajax errors are sent to the browser has changed between IIS6 and IIS7. Errors used to be sent automatically and you could parse the XML on the client. Now, the developer is required to do a little more work because IIS traps the error and stops code execution before reaching the end of the method.
For example, the Ext JS Ajax call takes an object with 5 parameters: method, url, params, success and failure. The last parameter is a callback function that is executed if the server sends back a failure.
The good news is that you have to make a small change to the server-side code (only). Another piece of good news is that the code is generic - the snippet will work with most web methods.
To make it work, create a try... block around the code that may throw an error. (This example is written in C#.) Next, add the following catch block:

catch (Exception e) {
HttpResponse Response = HttpContext.Current.Response;
Response.StatusCode = 500;
Response.Write(e.Message);
HttpContext.Current.ApplicationInstance.CompleteRequest();
Response.End();
}

The code above intercepts the error and returns it to the client. If you already had Ajax code listening for failure, you will not have to change the client side at all.

Note: Special thanks to this blog post by Rick Strahl.

28 March 2011

Ext JS - Mixed Collection Extension

At the top of my wish list for Ext JS is some recursive container search logic. There are times when you need to access a control on a form and can get it via a search term.

 In this case, I wanted to look for the control with a tab index of one greater than the current control. Ext.getCmp would make one control dependent on another.  This logic enables me to find the next control in the container by searching for by property for the next largest tabIndex property.

This extension will recursively search an Ext JS (v 2.x) mixed collection for the first object that has the property you are looking for.  The new method is called 'findByProperty'.


/* Extends the mixed collection object and recursively finds an object */

Ext.override(Ext.util.MixedCollection, {

    findByProperty: function (property, value, defaultValue) {

        var obj = defaultValue,

            notFound = true,

            find = function (itm, idx, len) {

                if (itm.items) {
                    this.items.each(find);
                }

                if (itm[property] && itm[property] === value) {
                    obj = itm;
                    notFound = false;
                }

                return notFound;
            };

        this.each(find);

        return obj;
    }
});



Where:
  • property is the string property you are looking for
  • value is the property value 
  • defaultValue is the optional value to be returned if nothing is found