DCSIMG
Building ASP.NET Real – time web application - Pini Dayan

Pini Dayan

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

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.

Comments

Building ASP.NET Real ??? time web application - Pini Dayan said:

Pingback from  Building ASP.NET Real ??? time web application - Pini Dayan

# August 31, 2009 2:33 AM

Building ASP.NET Real ??? time web application - Pini Dayan said:

Pingback from  Building ASP.NET Real ??? time web application - Pini Dayan

# August 31, 2009 2:33 AM

Building ASP.NET Real ??? time web application – Pini Dayan | Webmaster Tools said:

Pingback from  Building ASP.NET Real ??? time web application – Pini Dayan | Webmaster Tools

# August 31, 2009 7:00 AM

חלי ג said:

פיני, פוסט מדהים!!!

מחכה לפוסטים הבאים עם דוגמאות קוד...

# August 31, 2009 10:16 AM

יוסי שמעוני said:

לא הבנתי מה הכוונה לא לתפוס את ה thread של ASPNET?

# August 31, 2009 10:28 AM

Pini Dayan said:

היי יוסי,

הכוונה היא של ASP.NET יש מספר Thread שהוא יכול להשתמש בהם לטפל ב Request...

אם כולם יחכו על בקשת ה Async כל הבקשות מרגע זה ואילך יחכו.

# August 31, 2009 11:42 AM

Rotem Bloom said:

אחלה של פוסט

# September 1, 2009 2:38 PM

Pini Dayan said:

תודה רותם:-)

# September 1, 2009 2:56 PM

Mesothelioma News - Building Requires Asbestos Abatement said:

Pingback from  Mesothelioma News - Building Requires Asbestos Abatement

# September 13, 2009 9:55 AM

Tonmoy Roy said:

Hi Pini,

Thanks for your great efforts for the work and this article. Its really excellent.

Can you please explain me how to achieve the following:-

How can I get the corresponding response from the following ?

function PageOnLoad() {

           GetUpdates1();

           GetUpdates2();

       }

       function GetUpdates2() {

           var sURL = "http://" + location.host + "/TestRealTimeWCFService/AsyncHandler.ashx?sSessionID=" + sSessionID + "&sQueryID=2";

           oAsyncExceuter = MSMakeAsyncGETHTTPCall(sURL, GetUpdatesCallBack);

       }

       function GetUpdates1() {

           var sURL = "http://" + location.host + "/TestRealTimeWCFService/AsyncHandler.ashx?sSessionID=" + sSessionID + "&sQueryID=1";

           oAsyncExceuter = MSMakeAsyncGETHTTPCall(sURL, GetUpdatesCallBack);

       }

Based on each response, I want to update different parts of a screen. Both responses may come simultaneously.

Thanks

Tonmoy

# June 10, 2010 12:49 PM

Pini Dayan said:

Hi

First of all thanks for your comment

About your question, as far as I understood,You have one open connection and 2 types of query string parameters.

Why dont you simply specify a diffrent callback to each one of them like:

MSMakeAsyncGETHTTPCall(sURL, GetUpdatesCallBack1);

MSMakeAsyncGETHTTPCall(sURL, GetUpdatesCallBack2);

and then update your dom.

Or you can see what has happen during each update.

If i misunderstood your question please write me to pinid@012.net.il

# June 10, 2010 3:03 PM

Tonmoy Roy said:

Hi

Thanks for your suggestions.

I'll try and let you know. Actually my target was to use one common handler as well as callback funtion for all callbacks.

By the way, does this approach (ashx callback) has any restriction or limitation for more than one browser window? Because, when I open the same application on two browsers it's working fine but one I open the third browser, it gives me some dom error?

Thanks.

# June 11, 2010 2:19 PM

Pini Dayan said:

No there should be no problem

I doing it all the time.

# June 13, 2010 8:16 AM

Steve said:

please provide code???

# June 25, 2010 12:57 PM

Tonmoy Roy said:

Hi Pini,

Once again I need your help. Let's say I've one async. handler for each aspx page and there are two users opened a specific page. Now, for each of them one handler is initiated and waiting for response.

By that time, if one user leaves the page, does the handler initiated by that user will be removed or still it will wait for response.

If it exists, then how to remove that handler?

Thanks in advance

# June 30, 2010 12:43 PM

Tonmoy Roy said:

Hi Steve, which code you want?

# June 30, 2010 12:45 PM

Pini Dayan said:

Hi Tonmoy

You should provide this functionality by attaching an event to the unload event of the page

And then cal the server and remove this callback.

Pini

BTW write to my mail since I am not checking the messages here all the time

# June 30, 2010 10:53 PM

Gina said:

I am doing a paper for school. Can anyone explain to me exactly what <a href="IP'>http://www.vertical.com">IP communication</a> is. It is really confusing me.

# August 10, 2010 2:28 AM

sri said:

any small project

first how can design

how can write the code thats design part

# September 24, 2011 1:19 PM

SomeBody said:

Code Please?

# September 25, 2011 9:51 PM

uggs said:

Upright assignment! This is the best weblog for anyone who wants to know about this subject. You know a lot its virtually challenging to argue with you  . You certainly place a new spin on the topic thats been composed about for many years. Fantastic things, just fantastic!

# November 22, 2011 6:49 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: