Thursday, 30 April 2015

State Management at Server side in ASP.NET


You often hear how the Web is meant to be stateless. What it actually means is HTTP (the protocol over which Internet or the Web works) is a stateless protocol and it works on Requests from Clients to Server and Responses from Server back to Clients. Beyond a Request/Response cycle, the server doesn’t know/care about the state of the client.

In my previous post I explained about client-side state management where the client, i.e. your browser preserves the state.

ASP.Net provides two ways to store state on the server:

Application state - The information is global o the application and is available to all users regardless of the identity of the user requesting the page.
Session state - user specific state that is stored on the server. It is available on a user basis who is visiting your site.


Application state

Application state is a global storage mechanism for your application for data that needs to be available for your entire application. You can use application state to store information that must be maintained between requests. A product catalogue which does not change very often can be considered for application state. You can think of application state as a form of application level caching of data which is hard to obtain.

Application state us stored in an instance of HttpApplicationState class available through the Page.Application property. This class represents a key-value pair where data is stored as key-value pairs. You can write into and read from application state. Once data is added to application state the server manages it.

Application state is a great place to store data when you don’t want to track users and require your data to be available for the entire application. All pages can access data from a single location rather than having multiple copies of it serving each request.

Data stores in ASP.Net application is not permanent. It is lost when your application is restarted or your web server restarts.

Care should be taken not to store sensitive information in application state as it is global to your application.













Global.asax and Application events

The HttpApplication class provides you with several events that you can handle to perform actions at application level. These can include anything like initialising variable, logging requests, handling application level errors etc. The events are implemented in a file called Global.asax file, also known as Global Application Class. Here are some of the common events you would find in a Global.asax file. When the files are added to your Visual Studio project the event stubs are created by Visual Studio.

How to read and write Application-state data

Application collection can be used to read and write data into application state. Because there might be number of users accessing your data, care should be taken to lock the Application object before writing data to it .Otherwise changes can be made to the data by another page between the time the first page reads the data and updates it.

Code Example 1

void Application_Start(object sender, EventArgs e)

Application.Lock();
Application["AppVariableName"] =”MyAppStarted”;
Application.Unlock(); 
}

You need not lock the Application object before you read it. However, you must cast the data to the correct type before using it as the data is stored as an object value in Application state. You should also add a check to ensure that the data is not null.

Code Example 2

if(Application["AppVariableName"] !=null)
{
      string message = Application["Message"] as string;
}


void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown
        Trace.WriteLine(GetAppDescription("Application_End"));
    }

    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs
        Trace.WriteLine(GetAppDescription("Application_Error"));
    }

    void Application_BeginRequest(object sender, EventArgs e)
    {
        Trace.WriteLine(GetAppDescription("Application_BeginRequest"));
    }

    void Application_EndRequest(object sender, EventArgs e)
    {
        Trace.WriteLine(GetAppDescription("Application_EndRequest"));
    }

Session state

Most of the web applications today need to store user-specific data between individual requests. Imagine a user on your website trying to shop and add products into shopping basket. This requires data to be temporarily available between pages until user has completed the process. In this case you can use the ASP.Net process to store data in the server memory and this is called session state.

Session state is very similar to application state except for the fact that the data is scoped to the current user rather than all the users and is available only to that session. Each user on your website will have an isolated session running in the memory of the server. The information is available as a user traverses through multiple pages on the website. As soon as the session times out or user closes the browser the data is lost.
You can respond to session events using the events available in Global.asax files. Some of the most common events are listed below.











Reading and writing session data
Session object is used to store session state. This is an instance of HttpSessionState class and represents a key-value dictionary collection.

Code Example 2
//Reading
Session[“LastRequestTime”]=DateTime.Now;

//Writing
If(Session[“LastRequestTime”] != null)
{
DateTime LastVisitTime =(DateTime)(Session[“LastRequestTime”]);
}

Note:- You should always ensure that session is not null and cast the data to correct type before using it.


Configuring cookieless session

If browser cookies are enabled, ASP.Net saves a cookie to the client to track session. The cookie is called ASPNet_SessionId and contains a random 24-byte value. This cookie is submitted with a request and ASP.Net maps a session to this cookie. If cookies are disabled on a browser ASP.Net uses the url to track session. It embeds a session id after the application anme and before any remaining virtual directory name of the file name.

Cookieless sessions can be enabled in the web.config file by setting the cookieless attribute of the sessionstate element to true.


Disabling session state

Session state can be disabled site wide by setting mode attribute of the sessionstate element to Off. You can also enable session state on a per page basis by setting the EnableSessionState directive to true. If it is specified ReadOnly the page will only have read-only access to session state.


Using a database to store state
In many cases, state information must be stored for long periods of time or must be preserved even if the server restarts. For this reason, using database technology to maintain state is a common practice. Using databases to maintain state also makes sense when the amount of user-specific information that needs to be maintained for a particular session is very large, but doesn’t need to be kept in memory at all times.


What ASP developers may not know is that ASP.NET can protect the session state in the case of IIS restarts by storing the data in a different process space. This differs from the situation in classic ASP, where the data was always stored in the IIS process space and would not survive a restart. Shared session state is an ideal mechanism for creating scalable solutions for Web gardens or Web farms. The session state can be shared in a common memory area on a central machine or can be pushed to a back-end SQL Server database automatically. Although by default ASP.NET uses cookies to store a local copy of the Session ID between round-trips to the Web application,



State Management (Client Side) in asp.net

In this article I will demonstrate  all about how to maintain, clear or hold the state of your pages in ASP.NET applications or in web-based applications. Here I tried to briefly summarize the concept of State Management (but here am including only Client-Side State Management).

List of task
The points of this post will be as follows:
1.    Overview
2.    Introduction
3.    Outline
4.    State Management Types

Types of State:-
                           I.          Client-side Management
                          II.          Server-side Management


5.    Client-side Techniques of State Mangement 
                             I.          View
                             II.          Hidden
                             III.          Cookies
                              IV.          Control State
                               V.          Query Strings

6.       Servert-side Techniques of State Mangement
                                  I.          Session State
                                  II.          Application State

Overview:-
As we all know, browsers are generally stateless.
Now may be in your question arises here, what does stateless actually mean?
Stateless means, whenever we visit a website, our browser communicates with the respective server depending on our requested functionality or the request. The
browser communicates with the respective server using the HTTP or HTTPs protocol.
But after that response, what's next or what will happen when we visit that website again after closing our web browser?
In this case HTTP/HTTPs doesn't remember what website or URL we visited or in other words we can say it doesn't hold the state of a previous website that we visited before closing our browser, that is called stateless.
Now I guess you have at least an idea of what state and stateless actually means.
So our browsers are stateless.
 

Introduction
Here I'll try to give you a feel of state and actually why we need states and State Management in ASP.NET. I'll take you through several State Management techniques along with their respective general case examples.
 

Outline
As I said in the startingthat HTTP is a stateless protocol. It just cleans up or we can say removes all the resources/references that were serving a specific request in the past. These resources can be:
1.    Objects
2.    Allocated Memory
3.    Sessions ID's
4.    Some URL info and so on.
Types of State Management

In ASP.NET there are the following 2 State Management methodologies:







Client-Side State Management:-
Whenever we use Client-Side State Management, the state related information will directly get stored on the client-side. That specific information will travel back and communicate with every request generated by the user then afterwards provides responses after server-side communication.


This architecture is something like the following:
















Server-Side State Management:-
Server-Side State Management is different from Client-Side State Management but the operations and working is somewhat the same in functionality. In Server-Side State Management all the information is stored in the user memory. Due to this functionality there is more secure domains at the server side in comparison to Client-Side State Management.


Scenario:-
It will be a little difficult to directly evaluate what will be better for our application. We cannot directly say that we will use client-side or server-side architecture of State Management.

Techniques:-
State Management techniques are based on client side and server side. Their functionality differs depending on the change in state, so here is the hierarchy:













Client-Side State Management techniques are:

1. View State
2.    Hidden field
3.    Cookies
4.    Control State
5.    Query Strings


Server-Side State Management techniques are:
1.    Session State
2.    Application State

Now I am defining each and every technique in detail with their reference example.

View State
In general we can say it is used for storing user data in ASP.NET, sometimes in ASP.NET applications the user wants to maintain or store their data temporarily after a post-back.. In this case VIEW STATE is the most used and preferred way of doing that.

This property is enabled by default but we can make changes depending on our functionality, what we need to do is just change the EnableViewState value to either TRUE for enabling it or FALSE for the opposite operation.

Snippet
1.   // Page Load Event  
2.   protected void Page_Load(object sender, EventArgs e)  
3.   {  
4.       if (IsPostBack)  
5.       {  
6.           if (ViewState["count"] != null)  
7.           {  
8.               int ViewstateVal = Convert.ToInt32(ViewState["count"]) + 1;  
9.               View.Text = ViewstateVal.ToString();  
10.              ViewState["count"]=ViewstateVal.ToString();  
11.          }  
12.          else  
13.          {  
14.              ViewState["count"] = "1";  
15.          }  
16.      }  
17.  }  
18.    
19.  // Click Event  
20.  protected void Submit(object sender, EventArgs e)  
21.  {  
22.         View.Text=ViewState["count"].ToString();  
23.   


Some of the features of view state are:
1.    It is page-level State Management
2.    Used for holding data temporarily
3.    Can store any type of data
4.    Property dependent

Hidden Field
A hidden field is used for storing small amounts of data on the client side. In most simple words it's just a container of some objects but their result is not rendered on our web browser. It is invisible in the browser.

It stores a value for the single variable and it is the preferable way when a variable's value is changed frequently but we don't need to keep track of that every time in our application or web program.
 


Figure: [Hidden Field Management]


Snippet


   // Hidden Field      
  1.   int newVal = Convert.ToInt32(HiddenField1.Value) + 1;  
  2.   HiddenField1.Value = newVal.ToString();  
  3.   Label2.Text = HiddenField1.Value;  

Some features of hidden fields are:
1.       Contains a small amount of memory
2.       Direct functionality access

Cookies
A set of Cookies is a small text file that is stored in the user's hard drive using the client's browser. Cookies are just used for the sake of the user's identity matching as it only stores information such as sessions id's, some frequent navigation or post-back request objects.












Figure: [Cookie Management]


Whenever we get connected to the internet for accessing a specific service, the cookie file is accessed from our hard drive via our browser for identifying the user. The cookie access depends upon the life cycle or expiration of that specific cookie file.

Snippet
1.   int postbacks = 0;  
2.   if (Request.Cookies["number"] != null)  
3.   {  
4.       postbacks = Convert.ToInt32(Request.Cookies["number"].Value) + 1;  
5.   }  
6.   // Generating Response  
7.   else   
8.   {  
9.       postbacks = 1;  
10.  }  
11.  Response.Cookies["number"].Value = postbacks.ToString();  
12.    
13.  Result.Text = Response.Cookies["Number"].Value;  


Type of Cookies:-

Persistent Cookie
Cookies having an expiration date is called a persistent cookie. This type of cookie reaches their end as their expiration dates comes to an end. In this cookie we set an expiration date.

Snippet
1.   Response.Cookies["UserName"].Value = "Abhishek";  
2.   Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(1);  
3.     
4.   HttpCookie aCookie = new HttpCookie("Session");  
5.   aCookie.Value = DateTime.Now.ToString();  
6.   aCookie.Expires = DateTime.Now.AddDays(1);  
7.   Response.Cookies.Add(aCookie);  


Non-Persistent Cookie
Non-persistent types of cookies aren't stored in the client's hard drive permanently. It maintains user information as long as the user access or uses the services. Its simply the opposite procedure of a persistent cookie.

Snippet
1.   HttpCookie aCookie = new HttpCookie("Session");  
2.   aCookie.Value = DateTime.Now.ToString();  
3.   // without the below line it become a non-persistent
4.   // aCookie.Expires = DateTime.Now.AddDays(1);  
5.   Response.Cookies.Add(aCookie);  


Some features of cookies are:
1.    Store information temporarily
2.    It's just a simple small sized text file
3.    Can be changed depending on requirements
4.    User Preferred
5.    Requires only a few bytes or KBs of space for creating cookies
Control State

Control state is based on the custom control option. For expected results from CONTROL STATE we need to enable the property of view state. As I already described you can manually change those settings.



Some features of query strings are:
1.    Used for enabling the View State Property
2.    Defines a custom view
3.    View State property declaration
4.    Can't be modified
5.    Accessed directly or disabled


Query Strings
Query strings are used for some specific purpose. These in a general case are used for holding some value from a different page and move these values to the different page. The information stored in it can be easily navigated to one page to another or to the same page as well.



Figure: [Query Strings]

Snippet
   // Getting data  

1.   if (Request.QueryString["number"] != null)   
2.   {  
3.       View.Text = Request.QueryString["number"];  
4.   }  
5.     
6.   // Setting query string  
7.   int postbacks = 0;  
8.     
9.  if (Request.QueryString["number"] != null)   
10.  {  
11.      postbacks = Convert.ToInt32(Request.QueryString["number"]) + 1;  
12.  }  
13.  else   
14.  {  
15.      postbacks = 1;  
16.  }  
17.    
18.  Response.Redirect("default.aspx?number=" + postbacks);  
     Some of the features are:
1.    It is generally used for holding values
2.    Works temporarily
3.    Switches info from one to another page
4.    Increase performance
5.    Uses real and virtual path values for URL routing