Pini Dayan

The best thing about a boolean is even if you are wrong, you are only off by a bit.
ASP.NET 4.0 New features – HTML, JS, ASP.NET Snippets

                                            image

In previous version of VS.NET we encountered the new snippet solution for creating a chunk of code that is usually reusable and then using it during programming or even lecturing. This feature was available for both C# and VB.NET coders. But we could not create or use snippets for the markup we are writing like HTML, JavaScript or even the ASP.NET page. VS.NET 2010 allows us to do just that!

Lets see some of the “out of the box” snippets we can use:

HTML Snippets:

image 

 

AS you can see the same snippet sign is now available on the ASPX page side.  So for example if I choose the checkbox snippet and double tab click it i will get the following markup:

image

JavaScript Snippets:

Let move even further and see a much useful sample. Most of us are writing JavaScript and lots of it in our web application, so lets see what is available out of the box for us in JavaScript :

alert snippet,control snippet,create snippet, do for while snippets, if else snippets and much much more. Here for example I am using the for snippet for creating a for clause.

image

ASP.NET snippets:

We have some useful control declarations as a snippets such as updatepanel, sqldatasource , all the validator controls and much much more.

Creating our own custom snippets:

Wouldn’t it be great to create our own snippets since we are the ones knowing what markup we most commonly using. So before showing how to accomplish this, Here is how you can see the entire list of snippets.

In the VS.NET 2010 , clicj the tool menu and open the “code  snippets manager”
image 

This snippet manager will now show you all the HTML, ASP.NET snippets or the JS snippets if you choose Jscript in the language select box. So in order to add them simply use this manager and read how to create the snippet files here.

Surround with feature:

Another cool thing we have in C# and is really useful is the “surround with” . We can for example write some JS code and then decide we want to surround it with a function. Simply select the wanted Js , right click and choose “surround with” .

Enjoy.

ASP.NET 4.0 New features – URL Routing

                                               image

Hi all, In this series of posts I am going to write about ASP.NET 4.0 new features. I will try to concentrate on the important features since there are many new cool ones. At this point of writing I am using the VS.NET 2010 Ultimate Beta 2 version. So lets introduce the first feature:

URL Routing:                  

URL Routing is the ability to use “friendly” URL’s instead of of using the once we know so far. So instead of using the knows URL’s like:

http://www3.cet.ac.il/FieldsPage.aspx?ID=Science

http://www.google.com/search?q=vs.net+2010&rls=com.microsoft:en-us&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1

where we have a protocol , a host name , a directory list, a page and a query string in the format: field1=value1&field2=value2&field3=value3...

We can use a “friendlier” version like:

http://www.Developers.com/software/aspnet

These “friendly” URL’s has the following benefits:

  1. They are more readable ( Actually it is debatable but lets go with the flow)  
  2. They are more SEO friendly (Search engine optimization)

The idea is to map these URL’s to a physical files by configuring your application. Up until now, this feature existed in ASP.NET MVC, now we can use it in ASP.NET 4.0. So how do we do it and where do we do it:

All we need to do is adding the routing data some where in the application , A good place to do it is in the Application_Start event so it will happen only once. Here is a sample code that demonstrate how to achieve the routing:

 

Adding routing to the global.asax:

 

 

protected void Application_Start(object sender, EventArgs e)
{
  //Routes: An object of type RouteCollection that contains all the routes
  ConfigureSiteURLRouting(System.Web.Routing.RouteTable.Routes);
}

private void ConfigureSiteURLRouting(System.Web.Routing.RouteCollection routeCollection)
{
  routeCollection.MapPageRoute("RouteCategory",       // A friendly name to descrive the route
                               "Books/{bookName}",    // The url format
                               "~/Book.aspx");        // The actual web page to handle the request

}

Getting the url values in the destination page:

Now once I am navigating to http://localhost:1559/Books/ASPNET in my development environment I am actually running the page “book.aspx” which has the following code for getting the book parameter:

string bookName = Page.RouteData.Values["bookName"] as string;

Programmatically Generating outgoing URL’s :

Just like we can map incoming URL’s to our real pages, we can generate them for the outgoing request as well. So in order to generate a URL in the following format  we can use the Page.GetRouteUrl method to perform just that.

Enjoy

 
Ajax ToolKit:Fix ResizableControl handler position problem

One of the controls available in the Ajax ToolKit is the ResizableControlExtender which makes a panel (div) resizable. One of the major bugs this control has his the ability to set the location for the handler (The place holder for the mouse with the resize cursor) to the left bottom corner of the ResizableControl target. There are many solutions out there , but as I tried them most of them simply do not solve the problem. After downloading the ResizableControlBehavior.js file and learning how it works , here is a simple solution to the problem:

1. Set the HandleOffsetY and HandleOffsetX properties of the ResizableControlExtender control to 3.

2. During this point the handler will be set in the top right corner as the following code from the ResizableControlBehavior.js  indicates: 

  // The this._handleHolder provedes a wrapper with absolute positioning

  // so that this._handle can be absolutely positioned relative to the

  // this._frame instead of the page

  this._handleHolder = document.createElement('DIV');

  this._handleHolder.style.width = '0px';

  this._handleHolder.style.height = '0px';

  this._handleHolder.style.position = ((Sys.Browser.agent === Sys.Browser.Opera) ?

    'relative' : 'absolute');

  this._frame.insertBefore(this._handleHolder, this._frame.firstChild);

 

  // The this._handle represents the UI handle for the user to grab with

  // the mouse

  this._handle = document.createElement('DIV');

  this._handle.className = this._HandleCssClass;

  this._handle.style.position = 'absolute';

  this._handleHolder.appendChild(this._handle);

 

3. So all we need to do is fix the _handler position:

 

  //Get control using the behaviour id

  var resizeControl = $find("ResizableControlExtenderBehavior1");

 

  //Get initial left and top of the handler

  var handlerInitialLeft = resizeControl._handle.style.left;

  var handlerInitialTop = resizeControl._handle.style.top;

 

 //Get the width and height of the resizable control

 var myPanel = $get(GetdivParticipantsID());

 var myPanelWidth = parseInt(myPanel .style.width.replace("px", "")) - 10;

var myPanelHeight = parseInt(myPanel .style.height.replace("px", "")) - 10;

 

//Change the handlers location

resizeControl._handle.style.left = (parseInt(handlerInitialLeft.replace("px", ""), 10) 

                                                 myPanelWidth ) + "px";

resizeControl._handle.style.top = (parseInt(handlerInitialTop.replace("px", ""), 10) +

                                                myPanelHeight ) + "px";

 

Enjoy.

Ajax Tip: Set position for ModalPopupExtender

Hi all, Ever wanted to set the location of the Modal windows you open using the ModalPopupExtender available when using ASP.NET Ajax toolkit?

Well there is a very simple way to do it using BLOCKED SCRIPT

1. Get the position you want the modal window to show. You can do it using ASP.NET Ajax library using Sys.UI.DomElement.getLocation method like this:

var location = Sys.UI.DomElement.getLocation($get("div1")); 

In this case I used some div control to set the modal windows next to it.

2. Get the Modal window reference by using it’s panel or div element.

3. Set the location of the modal window:

    Sys.UI.DomElement.setLocation($get(‘panel1’), location.x,

                                                         location.y);     

 


Enjoy

Microsoft ASP.NET Ajax DOM Events

Hi all, Lately I add to deal with a lot of cross browser stuff (Needless to say is is very ugly and in frustration times I wish we only had IE :-) )

Anyway , one cool way to solve lots of these issues is of course to use a Framework that does all the Cross browser JS for you.I am using Microsoft ASP.NET Ajax Library. Here is a nice example of how to handle mouse clicks in a way that will work on IE, Chrome and Firefox.

When trying to work with the mouse event (And writing cross browser code) you get familiar with the phrase :”JavaScript Madness”. For example: When wanting to know which mouse button was clicked and we want to use the “event” object JavaScript offers we see there is little cross browser compatibility regarding the number representing which button was clicked. In IE we have “event.button” with the values of 1, 4, 2 but we don’t have “event.which” which works for Safari Netscape and some other browsers. The “event.which” value was originally used in Netscape, and the “event.button” value was originally used in Internet Explorer. Later browsers used both, and messed them both up.

So here is a Sample code to illustrate how simple it is when using the framework and the DOM options it provides:

<script>

function pageLoad(sender, args) {

    //Attach the onmousedown to a div

    Sys.UI.DomEvent.addHandler($get("divMoustDown"), "mousedown", ShowContextMenu);

}

 

function ShowContextMenu(e) {

  if (e.button == Sys.UI.MouseButton.rightButton)

  {

    alert("Right button was clicked");

   }

   else if (e.button == Sys.UI.MouseButton.leftButton)

   {

    alert("Left button was clicked");

   }

   else {

       alert("Middle button was clicked");

   }

}   

</script>

You can read more on the JavaScript mouse problems here: Mouse Events

And the Sys.UI namespace here : ASP.NET Ajax Client reference.

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)

This solution was build together by the very talented Developer/Team leader Dror Ergaz (that works with me at the company I working now) and by me.

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.

Monitoring your application – real-time

Wouldn’t it be nice if we could monitor our application while it is actually running? And by monitoring i mean watching what is happening , which method is being called right now and what are the arguments it has?

Apparently we can. All we need to do is write code that writes to a log file with any library we wish. We can use Enterprise library Logging application block or log4net (Or build something of our own).

When our application is running the log file is being appended with the new data. but we cant see what is being written there in real time. so , here is a nice cool tool that does exactly that : it watches the appended text, let you filter what ever you want no matter what the format line is and let you even color important words you wish to see.

It is called “WinTail” and can be downloaded from here.

Here is a snap shot of what it can do:

ScrShot

Enjoy.

Posted: Aug 27 2009, 09:26 AM by Pini Dayan | with 1 comment(s) |
תגים:
Handling ASP.NET Async pages client disconnection

Lately I have been working a lot with ASP.NET amazing feature :Asynchronous  pages. Whenever the page has a lot of work in the server and he wishes to set free the thread handling this request, this is the time we need to use Async pages.

I will not go into details about what Async pages are, but in a nutshell: Since there is a limit to the thread ASP.NET can use , we wish to free the long bounded thread to other thread so that they will not wait. (A good example can be: a page calling web service or doing IO work)

Now what is the operation the BeginProcessRequest does is very long, how do we know that the client is still connected and we need to send him back the response?

In addition to Async pages we can even write an HTTPHandler that is Async and will show one to illustate the problem:

   public class CallMeAsyncHandler : IHttpAsyncHandler

   {

         private HttpContext oCurrent;

         public void ProcessRequest(HttpContext context){}

 

         public bool IsReusable

         {

             get

             {

                 return false;

             }

         }

 

   public IAsyncResult BeginProcessRequest

                  (HttpContext context, AsyncCallback cb, object extraData)

   {

     //Do some log operation here

     //Create some IAsync result and return it

     return oAsync;

   }

 

   public void EndProcessRequest(IAsyncResult oAsyncResult)

   {

       //Write back to the output (Response object for instance)

   }

The answer is very simple,as it turns out the Response object has a property specifying the client is still connected : Response.IsClientConnected.

Hope this helps, enjoy.

Advanced JavaScript Open House

Hi all, As I promised, I am uploading the presentation and source files from the Open day at Sela this week.

In these files you can see the source code of the samples we showed in class and the slides which are a good reference to the highlight of this day. Than you all for participating...

Download

More Posts Next page »