Monday, April 23, 2012

Compression of Session State in ASP.NET 4.0


We all know that what is session state in ASP.NET and what is it used for. We also know that Session in ASP.NET can be In Proc and Out Proc
Details of ASP.NET session can be find here.


In case of ASP.NET In Proc mode, session data is stored in memory of worker process of IIS; But in case of Out Proc mode there are two options
  •   State Server
  •  SQL Server
If we use Out Proc mode then large amount of data me need to move to SQL Server or state Server this may be an overhead and performance bottleneck. To improve the performance ASP.NET 4.0 introduces
new configuration called as CompressionEnabled. This property is present in SessionStateSection. You can configure the CompressionEnabled  property as below.

Please see above image here sessionState is set to SQLServer and compressionEnabled is set to true. Default value of compressionEnabled  is false.

When set to true value session data is compressed using GZipStream before storing to SQL Server or State Server and same class is used to expand the session data after fetching It from the SQL Server or State Server.

Example 

Let us write following code in default.aspx of a web application

 


Here Employee class is defined as follows


Few points about the code:

1. Class Employee is marked as serializable which is important. Without declaring it as serializable it cannot be stored in the out proc session.
2. Code in file deafult.aspx generates the large data to be stored in session in for loop and then stores data in session as

                Session["lstEmployee"] = lstEmployee;

This stores data in SQL Server.

Now Let us see length of data stored in cases when compressionEnabled true and when compressionEnabled is false.

Case when compressionEnabled = true in web.config


Case when compressionEnabled = false in web.config


 
From the two images above it can be seen that when compressionEnabled is set to true data stored is less 2609 bytes and in case when it is set to false data stored is large 5314 bytes.

Further Reading
Some good articles about the session
How to configure the SQL Server to save session state.

Friday, April 13, 2012

HttpContext.Items

Each time client sends a HTTP request to ASP.NET web site or Web Service object of class HttpContext is created. This class many useful objects like Request, Response , Session , Application etc. HttpContext has one more collection named Items. In this article let us see what is use of this collection.

HttpContext.Items is IDictionary (Key value collection) like Session , Application but has life of only single HTTP request.  That means that when processing of server is finished and response is sent back to the client collection Items will be cleared. How to use HttpContext.Items

Add the value to Items collection
 
   HttpContext.Items["SomeKey"] = "SomeValue";

Retrieve the value from the Items collection


   if(HttpContext.Items["SomeKey"] != null)
          {
                   string value =  Convert.ToString(HttpContext.Items["SomeKey"]);
          }



Use of HttpContext.Items

  • Sharing data between the HttpModules/ HttpHandlers
 HttpContext.Items has life time of only single request; So it is used to pass (share and organize ) data between the HttpModule  and HttpHandler. Each request from client to server pass through different Http Modules and Http Handlers . So if we have written some custom Http Handlers or Http Modules and if you want to set some value in those modules or handlers and use it on web application specific to that request only then you can use HttpContext.Items collection

  •  Per request cache
 HttpContext.Items can be used for per request caching; This means that if your web page shows same information on the page multiple times like shopping cart at top and bottom of the page. or related information at different places on the same web page. In these case information can be brought from the database only once and kept at HttpContext.Items and use at whenever required.

Thursday, April 12, 2012

Developing Real time application with ASP.NET using Signal R


What is SignalR
From the GitHub website https://github.com/SignalR/SignalR
" Signal R is Async signaling library for .NET to help build real-time, multi-user interactive web applications. "
It is library developed by the David Fowler and Damian Edwards; which supports the asynchronous connection in ASP.NET and helps to build the real time web application using JavaScript at client side and ASP.NET at server side.
We know that in HTTP web application client makes request to the server and then server respond to the client; SO it is always from client to server. But there are certain situation where some happenings at server needs to notify to the client. So how do we achieve it? Previously we used to write JavaScript polling for this. But this polling is buggy and needs lot of error handling and it also not really real time it has some delay.

SignalR library provide this facility of notifying client when something happens at server.
SignalR uses Web Sockets and Logrolling whichever is best suited by the browser. 
You can find more information on Web Sockets and Logrolling here and here.

 Normal HTTP request response flow
Client makes request to server and server responds to the client.
Old age solution for notifying client

 
Client is making the request to the server after each timer interval; timer is implemented at client side
SignalR Async flow for notifying client
Client makes asycn request to the client; Server waits for some event to occur on occurring the event server notifies the all clients
Application development using SignalR library
SignalR has different component like
·         SignalR
·         SignalR.Server
·         SignalR.Js
·         SignalR.Client
To develop the ASP.NET real time web application we need to install SignalR package from Nuget. To do this run the following command in Package Manager Console

PM> install-package SignalR

Installed the SignalR from Nuget

Start VS2010 and create new Web Site project (File->New->Web Site..) and run the command to install SignalR package. After running the above command it will add SignalR references and SignalR JS to your application as shown below.
 
Create web site project

 
References of SignalR JS and SignalR dll
Server Side code
We will be developing chat application so let us add class with name Chat as shown below

Following are some notable points about the code
1.   This class file has reference to SignalR.Hubs.
2.   Chat class has attribute HubName "chat" this is very important and required; This says that this is a hub for the SignalR and SignalR JS client  shall call this class method.
3.   Chat class has one method Send with attribute HubMethodName "send"; This says that SignalR JS client calls this method asynchronously.
4.   Let us look at the implementation of the Send method this contain signal line
                   Clients.addMessage(message);
Here Clients is dynamic variable; and addMessage shall be resolved at a runtime. When this method is called subscribed method of the clients shall be get called.  
Client side code  
At client side create UI like shown below
   
It has one bullet list with id messages, one text box with id msg and one button with id broadcast as shown in the image above. 
Let us see the client JavaScript , Following is the JavaScript's are included.

 
1.   jquery-1.7.2.js This is required as SignalR JS  requires JQuery. Please make sure that you have latest version of Jquery included.
2.   json2.js This is required for working SignalR JS client in IE 8 + browsers.
3.   jquery.signalR.js This is SignalR JS client.
4.   Following line is most important
<script type="text/javascript" src='<%= ResolveClientUrl("~/signalr/hubs") %>'></script>
This is required because at run time SignalR creates JavaScript proxy for the server at the location ~/signalr/hubs; To create this proxy it uses the attributes given in server code. If you do not include this path or include it incorrectly SignalR will not find proxy and will not be able to run. you can look the proxy generated in browser by entering the URL <You server path>/signalr/hubs; as below
Let us see JavaScript written as follows
 

1.   First line var chat = $.connection.chat; creates connection to the server side Chat class. Please note that "chat" here is the same as the HubName attribute.


2.   Next Line
            $.connection.hub.start({ transport: 'auto' }, function () {
                // alert('connected');
            });

It opens the connection with transport auto and function specified there gets called once the connection is established.
3.   Next piece of code is
        $("#broadcast").click(function () {
                //                alert($("#msg").val());
                chat.send($("#MainContent_userName").text() + $("#msg").val());

                $("#msg").val('')
            });
This code is get called when user clicks broadcast button; and chat.send() method calls the server side Chat.Send method. Please note that "send" method here is same as the HubMethodName attribute in server side code.
4.   Next code
     chat.addMessage = function (message) {
                $('#messages').append('<li>' + message + '</li>');
            };
It specifies when server calls addMessage method then function should get called  this function displays message in bulleted list. Please note that we have added addMessage method to dynamic variable Clients in the server code.
So, Now you have developed the application What next? Let us run it. Run the application in two separate browser as shown below; Enter your name and click Enter Chat room button. For testing in both browsers I have taken one as IE and other as Firefox.

As soon as you type message in one window and click send button it will be displayed in both the window; you can try opening more windows.


You can find the running sample application here.