DCSIMG
September 2009 - Posts - Pini Dayan

Pini Dayan

The best thing about a boolean is even if you are wrong, you are only off by a bit.

September 2009 - Posts

RoundedCorners control – how does it really work?

ASP.NET Ajax toolkit has many cool controls, one of them is the RoundedCorners control. I think any ASP.NET developer meets the problem of how to create a control with rounded corners sometime during his career. Most of us solve this issue using images by creating 4 images , one for each corner. Here is a good example of how to achieve this using image and table.

There is another solution that is not yet cross browser one. there is the css 3 new upcoming feature for giving each control a raduis. Mozilla already supports it and calls it “moz-border-radius”, I even wrote about it in my blog:CSS 3 new amazing feature - border radius. But what I want to discuss today is another cool solution that is actually cross browser one. The RoundedCorners control that is available in the ASP.NET AJAX toolkit.

Let's say we have a simple div control:

   <div id="test" style="background-color:Red;width:200px;height:200px;">

        aaa

   </div>


That looks like this:

image

and we want to make it rounded. Here is the server RoundedCorner control definition to achieve this:

 <cc1:RoundedCornersExtender ID="RoundedCornersExtender1" runat="server"

         TargetControlID="test" Color="red"

         Radius="6" 

         Corners="All" />

(and naturally I added a script manager to the page and added the “Register” directive as well).

 

The result is this:

image

 

So how does the control work:

As it turns out, the control does not use any images , it does it using a very nice technique. If you look at the source code that is created for our div ( using any tool, I used the IE 8 developer tool bar) you will see the following code:


<DIV style="BACKGROUND-COLOR: red; HEIGHT: 1px; MARGIN-LEFT: 3px; FONT-SIZE: 1px; OVERFLOW: hidden; MARGIN-RIGHT: 3px" __roundedDiv="true"></DIV>
<DIV style="BACKGROUND-COLOR: red; HEIGHT: 1px; MARGIN-LEFT: 2px; FONT-SIZE: 1px; OVERFLOW: hidden; MARGIN-RIGHT: 2px" __roundedDiv="true"></DIV>
<DIV style="BACKGROUND-COLOR: red; HEIGHT: 1px; MARGIN-LEFT: 1px; FONT-SIZE: 1px; OVERFLOW: hidden; MARGIN-RIGHT: 1px" __roundedDiv="true"></DIV>
<DIV style="BACKGROUND-COLOR: red; HEIGHT: 1px; MARGIN-LEFT: 0px; FONT-SIZE: 1px; OVERFLOW: hidden; MARGIN-RIGHT: 0px" __roundedDiv="true"></DIV>
<DIV style="BACKGROUND-COLOR: red; HEIGHT: 1px; MARGIN-LEFT: 0px; FONT-SIZE: 1px; OVERFLOW: hidden; MARGIN-RIGHT: 0px" __roundedDiv="true"></DIV>


<DIV style="BORDER-BOTTOM: medium none; BORDER-LEFT: medium none; BACKGROUND-COLOR: red; WIDTH: 100%; HEIGHT: 200px; BORDER-TOP: medium none; BORDER-RIGHT: medium none">aaa </DIV>


<DIV style="BACKGROUND-COLOR: red; HEIGHT: 1px; MARGIN-LEFT: 0px; FONT-SIZE: 1px; OVERFLOW: hidden; MARGIN-RIGHT: 0px" __roundedDiv="true"></DIV>
<DIV style="BACKGROUND-COLOR: red; HEIGHT: 1px; MARGIN-LEFT: 0px; FONT-SIZE: 1px; OVERFLOW: hidden; MARGIN-RIGHT: 0px" __roundedDiv="true"></DIV>
<DIV style="BACKGROUND-COLOR: red; HEIGHT: 1px; MARGIN-LEFT: 1px; FONT-SIZE: 1px; OVERFLOW: hidden; MARGIN-RIGHT: 1px" __roundedDiv="true"></DIV>
<DIV style="BACKGROUND-COLOR: red; HEIGHT: 1px; MARGIN-LEFT: 2px; FONT-SIZE: 1px; OVERFLOW: hidden; MARGIN-RIGHT: 2px" __roundedDiv="true"></DIV>
<DIV style="BACKGROUND-COLOR: red; HEIGHT: 1px; MARGIN-LEFT: 3px; FONT-SIZE: 1px; OVERFLOW: hidden; MARGIN-RIGHT: 3px" __roundedDiv="true"></DIV>
<DIV style="BACKGROUND-COLOR: red; HEIGHT: 1px; MARGIN-LEFT: 6px; FONT-SIZE: 1px; OVERFLOW: hidden; MARGIN-RIGHT: 6px" __roundedDiv="true"></DIV></DIV>

All the control is doing is simply adding some div controls above it and under it. (The above divs are for the top corners and the bottom divs are for the bottom corners) And all that is changing between all these divs is the margin-left and margin-right property. which means each div is a simple 1 px height control that follows by another div that is longer and so on….

Amazing and simple right?

The problem with this control is that i does not support 2 colors, which means that if you have a div that it’s upper side is in one color and the bottom side is in another color, you simply have to do it manually.

ASP:Chart control – Amazing

Today I discovered something I should have known long ago. ASP.NET has a Chart control!!! It is free to download and use and it will be part of ASP.NET 4.0 coming up soon.

If you wish to use it today simply follow these steps:

1. Download and install the  Chart controls.

2. Download and install the VS 2008 tool support.

3. Optional: Download the code samples. This is a huge web application project we can learn a lot from.

Here are some snap shots of what you can do with these control I took from the sample web project:

ChartImg2 ChartImg3 ChartImg4 3DSpline ChartImg5 2DDoughnut2 2DPolar ChartImg6 ChartImg

Enjoy.

Building ASP.NET Real – time web application – Part 5

After seeing the core of the real-time solution in post 1 – 4 this post will show the other code parts and specify a few details and steps we can take to optimize the solution:

So here are the missing codes to complete the puzzle:

The StocksValuesDB class, that simulate a DB being updated in each interval and has an event to tell clients when an update occurs:

public class StocksValuesDB

{

     //The event this DB raised when the data changes

     public delegate void StocksChangedDeleaget(StocksEventArgs args);

     public static event StocksChangedDeleaget OnStocksChanged;

     public static bool Initialized { get; private set; }

     public static int Stock1Value { get; set; }

     public static int Stock2Value { get; set; }

     public static int Stock3Value { get; set; }

     public static int Stock4Value { get; set; }

     public static int Stock5Value { get; set; }

    private static Timer oStocksTimer;

    static StocksValuesDB()

    {

          Initialized = true;

         //Start a timer that simulate a change to the stocks

         oStocksTimer = new Timer();

         oStocksTimer.Interval = 2000;

         oStocksTimer.Elapsed += new ElapsedEventHandler(StocksTimer_Elapsed);

         oStocksTimer.Enabled = true;

         oStocksTimer.Start();

    }

 

    private static void StocksTimer_Elapsed(object sender, ElapsedEventArgs e)

    {

        //Stop the timer and uppdate the stocks

         oStocksTimer.Stop();

  

         Random oRandom = new Random();

         Stock1Value = oRandom.Next(1,1000);

         Stock2Value = oRandom.Next(1, 1000);

         Stock3Value = oRandom.Next(1, 1000);

         Stock4Value = oRandom.Next(1, 1000);

         Stock5Value = oRandom.Next(1, 1000);

         oStocksTimer.Start();

         if(OnStocksChanged != null)

         {

            OnStocksChanged(new StocksEventArgs(Stock1Value, Stock2Value, Stock3Value,

                                           Stock4Value, Stock5Value));

          }

   }

}

The StocksEventArgs class, to be used as the event args for the OnStocksChanged event.

  public class StocksEventArgs : EventArgs

  {

      public StocksValues Stocks;

      public StocksEventArgs(int nStock1Value, int nStock2Value, int nStock3Value, int

            nStock4Value, int nStock5Value)

      {

          Stocks = new StocksValues

                       {

                         Stock1Value = nStock1Value,

                         Stock2Value = nStock2Value,

                         Stock3Value = nStock3Value,

                         Stock4Value = nStock4Value,

                         Stock5Value = nStock5Value

                     };

            }

  }

The StocksValues class, to be passes as a memeber of the event args to the clients.

public class StocksValues

  {

        public int Stock1Value { get; set; }

        public int Stock2Value { get; set; }

        public int Stock3Value { get; set; }

        public int Stock4Value { get; set; }

        public int Stock5Value { get; set; }

  }

The AsyncCallbacksWrapper class, wrapp the AsyncResult object with extra data.

public class AsyncCallbacksWrapper

{

         #region Class members

         //For holding the AsyncResultm for the Async handler

         public AsyncResult<StocksValues> AsyncResult { get; set; }

         //For knowing if it's the same user

         public string SessionID { get; private set; }

         #endregion

 

        #region Class Constructors

        public AsyncCallbacksWrapper(string sSessionID)

        {

          this .SessionID = sSessionID;

        }

        #endregion

}

Te code that I downloaded from the internet and is used as a generic class that implement IAsyncResult can be found in the complete solution file here.

A few important notes:

1. Don’t be afraid if you are getting HTTP 403.9 error, all you need to do is to make sure to abort the timeout request and invoking the handler in case of timeouts or windows close event.If you are using IIS 5.1 you will get it a lot since it is limited to 10 connections.

2. Use TCPView tool to watch what happens on the server and on the client IE.

3. I used a timer to simulate the DB being updated, you can even use SQLCacheDependency

   with polling or notification services ( I tried it it worked).

4. Use the AsyncCallbacksWrapper to add more properties to be filtered later. Instead

   of waiting all the client in case of an updat , you can filter the clients that are

   interested in this event or even filder the Data being returned to them.

Enjoy.

 

Building ASP.NET Real – time web application – Part 4

In the previous post, I explained how to use the HTTP Async handler (or simply Async page) in order to create a callback and store it somewhere. Later when something changes this callback will be invoked and update the web client waiting for update. But what is this callback ,how do we get it invoked and what is BeinXXX and EndXXX in this post:

Asynchronous Programming Model:

When an application performs an IO operation, the application is very much depend on the device that is doing this IO work. for example when you are trying to read something from a FileStream or a NetworkStream, even worse , if this file you are trying to read is in a remote machine and this machine is offline , your application is waiting until timing out! You can assign a different thread to do this “dirty work” but when you will create many thread the application will suffer from this overhead (context switching and so on). So when you have IO operations like this and you will your application to be more scalable and reliable you should not do these operations Synchronous. You should use the APM. so how does it work?

An application wishing to support the APM, meaning to have a method that works Synchronously and Asynchronously will provide the method itself,  lets call it Func, a BeingFunc and an EndFunc methods. (Just like our HTTP handler has public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) and public void EndProcessRequest(IAsyncResult asyncResult))

Lets being with the BeinXXX method: this method will return an object implementing IAsyncResult (is implemented by classes containing methods that can operate asynchronously) The class implementing this interface stores state information for an asynchronous operation and provides a synchronization object to allow threads to be signaled when the operation completes. So basically this is the object that monitors the operations and update it’s state. Now for the parameters the BeginXXX accepts. It accepts AsyncCallback object which is a delegate pointing to a function to be invoked when this Async operation is ended! look at the signature of this delegate:

public delegate void AsyncCallback( IAsyncResult ar)

as you can see it gets as a parameter the IAsyncResult object that has the information and state about the Async operation. In additon, the BeginXXX method gets another parameter that is the state of the operation in order to distinguish the operations and to supply extra data.

So in our case (The HTTP handler) we are creating our own AsyncResult object ( that implement IAsync) , and store this object in the manager:

AsyncCallbacksWrapper oAsync = new AsyncCallbacksWrapper( this.sSessionID)

                              {

                               AsyncResult = new AsyncResult<StocksValues>(cb, null),  

                              };

StocksClientsManager.Instance.AddCallBack(oAsync);

and then returning it.as you can see the first parameter is the cb, which is the ASP.NET call back to be invoked when we want it to be.

When we decide to invoke this cb, all we need to do is to find it inside our IAsync object and invoke it ( so it will get to the EndXXX method of the HTTP handler).

More on the APM:

http://msdn.microsoft.com/en-us/library/system.iasyncresult.aspx

http://msdn.microsoft.com/en-us/library/system.asynccallback.aspx

http://msdn.microsoft.com/he-il/magazine/cc163467(en-us).aspx

All there is left is to show the other parts of the application, read more in the next post.

Building ASP.NET Real – time web application – Part 3

In part 2 of these series of posts , I showed the basics of building the UI for the page and the JavaScript for calling the server using AJAX and waiting for a response. But how did I make the HTTP request “wait” and let the server “wake” it up? The answer is very simple. Async page (or Async HTTP Handlers).

Here is a simple explanation from MSDN:

“When ASP.NET receives a request for a page, it grabs a thread from a thread pool and assigns that request to the thread. A normal, or synchronous, page holds onto the thread for the duration of the request, preventing the thread from being used to process other requests. If a synchronous request becomes I/O bound—for example, if it calls out to a remote Web service or queries a remote database and waits for the call to come back—then the thread assigned to the request is stuck doing nothing until the call returns. That impedes scalability because the thread pool has a finite number of threads available. If all request-processing threads are blocked waiting for I/O operations to complete, additional requests get queued up waiting for threads to be free ……………….”

“Asynchronous pages offer a neat solution to the problems caused by I/O-bound requests. Page processing begins on a thread-pool thread, but that thread is returned to the thread pool once an asynchronous I/O operation begins in response to a signal from ASP.NET. When the operation completes, ASP.NET grabs another thread from the thread pool and finishes processing the request. Scalability increases because thread-pool threads are used more efficiently”

So in a nutshell , using ASP.NET Async pages we can set free the ASP.NET thread that was assigned to handle the request in the first place. But still we need a way to queue this request and it’s parameter somewhere and to be able to release this request whenever the server has something to tell the client waiting for a response. We will accomplish this using the APM that I  will explain later.

So lets show the Async part in the server, only instead of using Async page, I will use Async HTTP Handler (More about HTTP handlers Here).

This is the ASHX file the JavaScript requestes once loaded and each time the client finishes to update it’s UI:

public class AyncHandler : IHttpAsyncHandler

{

   #region Class Memebers

   private HttpContext oCurrent;

   private string sSessionID = string.Empty;

   #endregion

  public void ProcessRequest(HttpContext context)

  {}

    

  public bool IsReusable

  {

      get

      {

        return false;

      }

}

#region IHttpAsyncHandler Members

public IAsyncResult BeginProcessRequest(HttpContext context,

                                   AsyncCallback cb, object extraData)

{

    context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

    var bInitialized = StocksValuesDB.Initialized;

    this.oCurrent = context;

   //Get param from the QS

   if (context.Request["sSessionID"] != null)

   {

      this.sSessionID = context.Request["sSessionID"];

   }

   AsyncCallbacksWrapper oAsync =

                                 new AsyncCallbacksWrapper( this.sSessionID)

                                 {

                                  AsyncResult = new AsyncResult<StocksValues

                                                   (cb,null),  

                                 };

  StocksClientsManager.Instance.AddCallBack(oAsync);

  return oAsync.AsyncResult;

}

public void EndProcessRequest(IAsyncResult oAsyncResult)

{

    AsyncResult<StocksValues> oAsyncResult1 = (AsyncResult<StocksValues>)oAsyncResult;

    StocksValues oStocksValues = oAsyncResult1.EndInvoke();

    if (oStocksValues == null)

    {

        oCurrent.Response.Write("-1");

    }

    else

    {

    //Serialize the results back to the client

    JavaScriptSerializer oSerializer = new JavaScriptSerializer();

    string sResult = oSerializer.Serialize(oStocksValues);

    if (oCurrent.Response.IsClientConnected)

    {

       oCurrent.Response.Write(sResult);

     }

   }

}

#endregion

}

}

OK, So what is going here?Instead of simply implementing ProcessRequest we need to implement the Async version of this HTTP Handler, so we need to implement BeginProcessRequest and EndProcessRequest. The BeginProcessRequest gets a callback called cb from ASP.NET which she expect you to invoke when you want to end the request and invoke the EndProcessRequest. So for this purpose I am building a Wrapper called AsyncCallbacksWrapper that will wrap a generic object of type AsyncResult<T>. We will get into details later on this subject. But for now all I am doing is Creating this wrapper object , initialize it with the Session ID i got from the QS and store it in a StocksClientsManager object which is the “Callbacks Manager” that will manage the callbacks for me. Once I finished adding my callback to this manager , the BeginProcessRequest finishes its job. Since the cb parameter was not invoked in any way, the request simply waits. (We can protect it with a timeout if we wishes).

As you can guess, later, when the DB changes(I am using a timer to change the values of the stocks to simulate this scenario) The StocksClientsManager will iterate all the callbacks and invoke them, causing the EndProcessRequest to be invoked and return a response to the client(That will update it’s UI).

Here is the code for the StocksClientsManager:

public class StocksClientsManager

{

   #region Singleton

   private static readonly object oLocker = new object();

   private static StocksClientsManager _instance;

   public static StocksClientsManager Instance

   {

      get

      {

         if (_instance == null)

         {

            lock (oLocker)

            {

              if (_instance == null)

              {

                 var oTemp = new StocksClientsManager();

                 Thread.MemoryBarrier();

                 _instance = oTemp;

               }

             }

          }

          return _instance;

      }

  }

  private StocksClientsManager()

  {

   //Register for the updates from the Stocks "DB"

   StocksValuesDB.OnStocksChanged += new StocksValuesDB.StocksChangedDeleaget

                                               (StocksValuesDB_OnStocksChanged);

  }

#endregion

//For holding the list of callbacks

private List<AsyncCallbacksWrapper> oListOfCallBacks=new List<AsyncCallbacksWrapper>();

public void AddCallBack(AsyncCallbacksWrapper oCallBack)

{

   lock (oLocker)

   {

   //If already exists must invoke it and reinsert it (instead of removig

   //   it on timeouts)

   var oAsyncCallbacksWrapperTemp =

                     GetAsyncCallbacksWrapperBySessionID(oCallBack.SessionID);

   if (oAsyncCallbacksWrapperTemp == null)

   {

       this.oListOfCallBacks.Add(oCallBack);

   }

   else

   {

    //It's not null. must invoke it

    this.oListOfCallBacks.Remove(oAsyncCallbacksWrapperTemp);

    this.oListOfCallBacks.Add(oCallBack);

   }

  }

}

public AsyncCallbacksWrapper GetAsyncCallbacksWrapperBySessionID(string sSessionID)

{

   foreach(AsyncCallbacksWrapper oAsyncCallbacksWrapper in this.oListOfCallBacks)

   {

      if(oAsyncCallbacksWrapper.SessionID == sSessionID)

      {

            return oAsyncCallbacksWrapper;

      }

   }

return null;

}

private void StocksValuesDB_OnStocksChanged(StocksEventArgs args)

{

   //Copy the original list and clear it

   List<AsyncCallbacksWrapper> asyncCallbacksWrapperTemp;

   lock (oLocker)

   {

    asyncCallbacksWrapperTemp = new List<AsyncCallbacksWrapper>(this.oListOfCallBacks);

    this.oListOfCallBacks.Clear();

   }

    

   //Here we will wake up the callbacks that are waiting for the updates

   foreach (var callback in asyncCallbacksWrapperTemp)

   {

       if (!callback.AsyncResult.IsCompleted)

       {

           callback.AsyncResult.SetAsCompleted(args.Stocks, false);

       }

   }

  }

}

More on the APM (Understanding IAsyncResult and it’s friends) in the next post.

Building ASP.NET Real – time web application – Part 2

In the previous post , I wrote the general steps to accomplish the solution of achieving real time web application. In this post we will start and demonstrate the solution step by step and explain the application blocks of the solution from building the simple UI for this sample project and moving forward to the hardcode parts of the solution, so without further ado lets start.

The demo code can be downloaded from here.
(It is a web application solution that runs and works without a DB, but instead with a in memory DB)

Building the UI:

As a first step , I will build a simple UI that manages stocks value in a simple table. All the next posts that demonstrate how to update this table in a real time manner will use this stocks table. Needless to say that each one can implement it’s own web application for achieving his real time solution.

The original state of the stocks table is initialized like this:

image 

and the mark up for this table is also very simple:

<head runat="server">

<title>Real time Stocks updating</title>

<style>

html,body

{

    padding-top:100px;

}   

.TableHeader

{

   background:blue;

   color:white;

   font-weight:bold;

   font-size:120%;

}

.TableRow

{                                   

  font-size:110%;

}

.MainTable

{

   padding:5px;

   margin:5px;

}               

</style>

<body>

<form id="form1" runat="server">

<div align=center>

<table border=1 class="MainTable">

     <tr class="TableHeader">

         <td>Stock 1</td>

         <td>Stock 2</td>

         <td>Stock 3</td>

         <td>Stock 4</td>

         <td>Stock 5</td>

     </tr> 

<tr class="TableRow">

  <td>N/A</td>

  <td>N/A</td>

  <td>N/A</td>

  <td>N/A</td>

  <td>N/A</td>

</tr>

<table>

</body>

Getting Updates:

Now starts the interesting part, We will add an event handler for the page’s load event to start an Async ajax call to the server. Only that this call to the server will be to the AsyncHandler.ashx which is an Async HTTP Handler(Which I will explain soon). lets show some code:

html modification:

<body onload="PageOnLoad();">


JavaScript modification to the page:

<script src="JavaScript/Ajax.js" type="text/javascript"></script>

<script>    

//For holding the session ID

 var sSessionID = "<%= Session.SessionID %>";

function PageOnLoad() {           

GetUpdates();

}

function GetUpdates() {

   var sURL = "http://" + location.host + "/Handlers/AyncHandler.ashx?sSessionID=" +

                                                                         sSessionID;           

   oAsyncExceuter = MSMakeAsyncGETHTTPCall(sURL, GetUpdatesCallBack, 60000);           

}

function GetUpdatesCallBack(executor, eventArgs) {

if (executor != null && executor.get_responseAvailable())

{

   if (executor != null)

   {

       var sResponseDate = executor.get_responseData();

      //Set the UI according to the result

      UpdateUI(sResponseDate);

     //Get updated again

     GetUpdates();

   }

}

 else {

   if (executor.get_timedOut()) {

      alert("Time out occured");

      //Abort the previous request

      if (oAsyncExceuter != null) {

        oAsyncExceuter.abort();

      }

     //Register for updates again

     GetUpdates();

    }

    else {

        if (executor.get_aborted()) {

          alert("Aborted");

          }

        }

    }

}

function UpdateUI(sResponseDate) {

 

  //Convert to JSON

  var oJSONObj = JSON.parse(sResponseDate);

  //Update the UI in the most ugliest way i can :-)

  var oRow = document.getElementById("StocksRow");

  oRow.cells[0].innerText = oJSONObj.Stock1Value;

  oRow.cells[1].innerText = oJSONObj.Stock2Value;

  oRow.cells[2].innerText = oJSONObj.Stock3Value;

  oRow.cells[3].innerText = oJSONObj.Stock4Value;

  oRow.cells[4].innerText = oJSONObj.Stock5Value;

  

}

</script>

As you can see , when the page loads, I am initializing a sessionID that can be used to later filter the results and send back only the data that this particular client is interested in.Next i am calling a GetUpdates function that starts an Ajax async call to the server to the ashx handler. In addition I am specifying what is the client’s call back function to be invoked when this AJAX call returns from the server.

(I am using Microsoft Ajax to perform these AJAX tasks, but naturally anyone can choose it’s own AJAX library). The complete source for this AJAX call available in the code sample.

So all we have here is a simple page calling the server using AJAX , Only this time the request “waits” on the server. How does it “waits”. In the next post…

 

Building ASP.NET Real – time web application

What if we could write a web application that it’s clients (browsers in our case) can get notified in case of something happening in the server, like a DB row added/changed, a BL entity (from any object model you have built ) raising an event or anything you can come up with in your mind. To clarify things let me further explain by using a very simple example : Say you have a web page (aspx, html, or any other) that displays a various stocks values in a grid, these values are changing very fast and every time. what if we wish that this html grid will change itself the minute any stock value changes? let me further add an important note: We don’t want to use polling mechanism (like using ajax requests at any interval using window.setTimeout)

As it turns out: Yes we can!

Here is a sample of waht we wish to achive(The sample solution i will upload on the next posts, will create this sample)

 

This is without no doubt the most exciting series of posts I am about to write and i am very exited to write these posts. In this series I am going to explain all the bits and bytes in the solution I am about to show. It was not an easy task but once you understand the general idea and pass over all the obstacles in the way it’s very easy. These posts are will demonstrate the solution using ASP.NET.

So lets first define what we wish to accomplish here and explain what are the options:

1. Display an html on out web page – this is a simple a every day task, we simply build our UI using ASP.NET controls (HTML controls, HTML server controls or web server controls, and naturally JavaScript and CSS).

2. This UI is changing all the time and we wish to display the updated UI. We don’t want to initiate a request for getting the updates at some interval, we also don’t want the user to press any “Update” button to get it as well. What we want is way to get notified from the server in case any thing “interesting” happened there. for this purpose we can use a known technique : polling. (I know some companies that does exactly that).

Polling:

Using this method a web client (browser) initiates an HTTP Request (Asynchronous or not using AJAX) in a wanted interval ( window.setTimeout) and check if there are any updates, if there are – get them and update the UI. This solution has a huge drawback both on the network side and both on the server resources.

On the network side, we have lots of users initiating an HTTP request (which open an underlying TCP/IP communication for each request) ,passing some data to the server and getting lots of updated data as well. This is naturally bad for the network.

On the server side , there are many many HTTP requests that needs to be handled all the time (again open TCP/IP communication, fetching the incoming request and handling it etc).

What we need is a way in which any client simply waits for something to happen and as soon as it does update it’s UI, So lets introduce the solution, here are the steps and i am going to explain them in much details:

Step 1:

Building the UI. This step is the basic part of building any ASP.NET web application, it is simply using ASP.NET and plain old html to construct your UI. In this step we will also use the CS part (The code behind) to build our UI. This can include a simple data binding,initialize some control or can use any Business logic and Data Access code to build this page.

Step 2:

Once the page loads (client side onload event), using JavaScript, initiate an Async HTTP request to a Asynchronous page or an Asynchronous http handler.The client can initiate this request by using native script (e.g Microsoft.XMLHTTP object), he can use MS ajax ( Like i did) or even use JQuery or any other js library).

For those who are not familiar with Asynchronous page , it is a way for ASP.NET to handle long processing requests ( like IO bound operations or web service calls).Since these long processing requests takes time , the handling thread is stuck processing this job while meantime other requests “stay outside”. ASP.NET uses a Thread-pool thread to handle it’s requests , so by “freeing” this thread,ASP.NET can now handle other requests. Once the long processing task completes, ASP.NET will grab a new thread from the Thread-pool and finishing process the request.

here is a nice image from MSDN to illustrate Async pages/handlers:

untitled

In our case we are using Async pages/handlers to open a request, let the client wait for a response ( but without stucking the UI) and freeing the ASP.NET thread by using Async page/handlers.

We will not go into more details about this feature at this point although we will discuss it more later since this is the critical part of the entire solution.

Step 3:

The Async page or handler will get the request in a BeginProcessRequest request method , create an IAsyncResult object to be later used in the EndProcessRequest method and will save this IAsyncResult object somewhere. Since no EndProcessRequest will happen in this BeginProcessRequest method the request simply hangs and the client that initiated this request is waiting for a result. (but not stucking the UI since this is an Async request. At this point (where BeginProcessRequest ended) the thread pool thread is released and free to server other requests.

An important note that is critical to understand here is that even though the thread is released a communication TCP channel is open and will not close until we close it by calling the EndProcessRequest (in the good way or when time out happens). otherwise the web server (IIS) will throw an HTTP 403.0 error code very fast.

The IAsyncResult object is critical for this solution , so for understanding it deeply i recommend any one wishing to really understand to read this article about APM (Async programming model). In addition i will explain it in the next posts.

The IAsyncResult will contain among other things the AsyncCallback that ASP.NET is waiting for us to “wake up” and that will invoke later the EndProcessRequest method.

Step 4:

Now that we have this IAsyncResult callback we can do whatever we like with it. At first I started a new Thread for each one and let it do the work of waiting to something to happen but very fast we realized that there will be too many Thread (and we will need a Thread pool to manage them), so we came up with a new idea. Instead of starting a new Thread, we will simply store these IAsyncResult callbacks in some list and when something will happen on the server, we will simply use them to invoke the AsyncCallback ASP.NET waits for it’s invocation.

Step 5:

In this step, something did happen on the server, How do we know? well there are lots of ways, like, using polling the DB for changes , of by using the SQL notification services and get invoked when anything interesting happens on the DB. During the samples i will show in the next posts, I will demonstrate one of them.

Now that we know we will to invoke all the EndProcessRequest from the ASP.NET Async pages/handlers we can simply extract the callback we got from ASP.NET and invoke it so that the execution will now be passed to the EndProcessRequest  to finish the request and return a response to the client.

Step 6:

The client gets the response, updates the UI using JavaScript and then restart another request like in step 2.