Your Ad Here
Google

Tuesday, March 06, 2007

 

Implementing an extensible factory method pattern using ASP.NET and ajax

Introduction


The general approach taken for dynamically building pages using AJAX (Asynchronous JavaScript and XML) is to use client side scripting to call a web service (or a page) to retrieve data and populate a control which is already available on the client side. This approach has some advantages and disadvantages.


The advantage is that the GUI elements are already placed and the page layout is well known. The disadvantages are:



These problems can be addressed if the controls are created on the server side, populated with data and the HTML along with the data is serialized to the client. The only burden on the client side would be to have a place holder available for the HTML element returned.


ASP.NET web class libraries offer excellent support to create HTML elements as classes which support rendering methods that provide an excellent opportunity to address this problem.


To implement a factory method pattern I have separated every call into two sections:



To accommodate and render the HTML element returned by the processor on the client side a DIV tag is created as the target element. As soon as the asynchronous call returns the script will take the responseText and using the innerHTML property will add this code inside the DIV tag which will render the control on the page. If there are client side scripts associated with this dynamically created element, optionally the ID for the created element may be set on the server side (which requires it to be passed as another parameter in the query string like the setID in the demo program).


The code for the solution can be separated into the following:



  1. The initial AJAX calling sequence.
  2. Handling the code in ASP.NET (the server side code).
  3. Processing the response on the browser side.

The initial client call sequence



Handling the code inside ASP.NET (the server side code)


The module, filter, page model provided by ASP.NET is very flexible and gives excellent opportunity to extend the ASP.NET functionality.



A custom call from a client can be handled in three ways:



  1. By using an ASPX page- This is the simplest and involves least development effort. In the example code provided the call is handled in the Init() method and the response stream is closed. This avoids the overhead of other events like loading, rendering and others at the page level.
  2. Providing a custom handler- This is bypassing the default ASP.NET page handler. Once all the modules configured in machine.config or web.config finish their processing the call is handed over to our handler. This approach gives the advantage of a custom extension and bypasses any overhead the default page handler has. This involves adding the extension in IIS and adding the handler in the CONFIG file (see below).
  3. Writing a custom module- A custom module can handle the call very early in the sequence of events inside ASP.NET and also provides the advantage of bypassing some modules and a handler. There are two scenarios in writing a custom module. The BeginRequest is the earliest event where the Request object is available to the module. If you do not want any authentication or authorization this is the quickest way to return the data back to the client. But if you are targeting security subscribe for Authenticated or Authorized event and handle the request. This approach like the handler requires registration of the extension with IIS and also adds the module to the CONFIG file (as shown below):
    <configuration>
    <system.web>
    <!-- registering a module -->
    <httpModules>
    <ADD type="DataBrowser.AjaxCallModule,DataBrowser"
    name="ajaxcalls" />
    </httpModules>
    <!-- registering a handler -->
    <httpHandlers>
    <ADD type="DataBrowser.AjaxCallHandler,DataBrowser"
    path="*.acall" verb="*"/>
    </httpHandlers>

    .......

    <system.web>
    <configuration>

To make all the above scenarios possible, the AjaxCallProcessor class is provided which handles all the logic. This class invokes a method dynamically using Reflection which returns the GUI element which is dynamically created and populated with data (depending on the client parameters read from the Request object).



The code below shows the ProcessAjaxCall() method on AjaxCallProcessor class. This can also be made a static method. I made it an instance method to simplify the code:

internal void ProcessAjaxCall()
{
// clear any headers added to the response
// header by ASP.NET HTTP pipe
_response.Clear();
try
{
// prepare connection string, part of business
// logic in this demo
PrepareConnectionString();

// invoke the method requested by the client
// dynamically using reflection
typeof(AjaxCallProcessor).GetMethod(_request["method"],
BindingFlags.NonPublic|BindingFlags.Instance).Invoke(this, null);

// create a HTMLTextWriter for the response stream
// and let the dynamic control to create it
HtmlTextWriter hw = new HtmlTextWriter(_response.Output);

// let the asp.net control render itself
dynamicControl.RenderControl(hw);
hw.Close();

if (sqlConn.State == ConnectionState.Open) // just in case :-)
sqlConn.Close();
}
catch (Exception ex)
{
// writing back an error message as HTML to response stream
_response.Write("<STRONG><FONT color=red>Error : ");
_response.Write(ex.Message);
_response.Write("</FONT></STRONG>");
}

// close the response stream to end the call immediately
// this will bypass any delay in ASP.NET HTTP pipe
_response.End();
}

Processing the response on the browser side



The demo program included demonstrates the use of this technique. Please see the screen shots below which show you how a control is replaced on the client side:





References




Labels:


Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?