Saturday, February 14, 2015

View State Management

Table of Contents

Introduction

First of all I want to thank Sean Ewington for his great initiative to write Beginner's Walk for Web Developmentarticle. I have decided to write some articles on state management There are a few article on Code project on State Management, basically on Session, Caching, Cookies, etc. Though all are very good article, still I have planned for write some article on state management. and I believe that should definitely helps to all the Beginners. And I have organized the content in a way that it would be helpful to not only beginners also to advance user also.
In this article, I will cover the fundamentals of State Management and Details of View State.

What is state management?

Web is Stateless. It means a new instance of the web page class is re-created each time the page is posted to the server. As we all know HTTP is a stateless protocol, its can't holds the client information on page. As for example , if we enter a text and client on submit button, text does not appear after post back , only because of page is recreated on its round trip.
User_S9_1.JPG
As given in above pages, page is recreated before its comes to clients and happened for each and every request. So it is a big issue to maintain the state of the page and information for a web application. That is the reason to start concept of State Management. To overcome this problem ASP.NET 2.0 Provides some features like View State, Cookies, Session, Application objects etc. to manage the state of page.
There are some few selection criteria to selected proper way to maintain the state, as there are many way to do that. Those criteria are:
  • How much information do you need to store?
  • Does the client accept persistent or in-memory cookies?
  • Do you want to store the information on the client or on the server?
  • Is the information sensitive?
  • What performance and bandwidth criteria do you have for your application?
  • What are the capabilities of the browsers and devices that you are targeting?
  • Do you need to store information per user?
  • How long do you need to store the information?
  • Do you have a Web farm (multiple servers), a Web garden (multiple processes on one machine), or a single process that serves the application?
So, when ever you start to think about state management, you should think about above criteria. based on that you can choose the best approaches for manages state for your web application.

Different types of state management?

There are two different types of state management:
  1. Client Side State Management
    • View State
    • Hidden Field
    • Cookies
    • Control State
  2. Server Side State Management
    • Session
    • Application Object
    • Caching
    • Database
Client Side state management does not use any server resource , it store information using client side option. Server Side state management use server side resource for store data. Selection of client side and server side state management should be based on your requirements and the selection criteria that are already given.

What is view state?

View State is one of the most important and useful client side state management mechanism. It can store the page value at the time of post back (Sending and Receiving information from Server) of your page. ASP.NET pages provide the ViewState property as a built-in structure for automatically storing values between multiple requests for the same page.
Example:
If you want to add one variable in View State,
 ViewState["Var"]=Count;
For Retrieving information from View State
string Test=ViewState["TestVal"];
Sometimes you may need to typecast ViewState Value to retreive. As I give an Example to strore and retreive object in view state  in the last of  this article.

Advantages of view state?

This are the main advantage of using View State:
  • Easy to implement
  • No server resources are required
  • Enhanced security features ,like it can be encoded and compressed.

Disadvantages of view state?

This are the main disadvantages of using View State:
  • It can be performance overhead if we are going to store larger amount of data , because it is associated with page only.
  • Its stored in a hidden filed in hashed format (which I have discussed later) still it can be easily trapped.
  • It does not have any support on mobile devices.

When we should use view state?

I already describe the criteria of selecting State management. A few point you should remember when you select view state for maintain your page state.
  • Size of data should be small , because data are bind with page controls , so for larger amount of data it can be cause of performance overhead.
  • Try to avoid storing secure data in view state
WhenViewState.PNG

When we should avoid view state?

You won't need view state for a control for following cases,
  • The control never change
  • The control is repopulated on every postback
  • The control is an input control and it changes only of user actions.

Where is view state stored?

View State stored the value of page controls as a string which is hashed and encoded in some hashing and encoding technology. It only contain information about page and its controls. Its does not have any interaction with server. It stays along with the page in the Client Browser. View State use Hidden field to store its information in a encoding format.
Suppose you have written a simple code , to store a value of control:
ViewState["Value"] = MyControl.Text;
Now, Run you application, In Browser, RighClick > View Source , You will get the following section of code
User_S1.jpg
Fig : View state stored in hidden field
Now , look at the value. looks likes a encrypted string, This is Base64 Encoded string, this is not a encoded string. So it can easily be decoded. Base64 makes a string suitable for HTTP transfer plus it makes it a little hard to read .Read More about Base64 Encoding . Any body can decode that string and read the original value. so be careful about that. There is a security lack of view state.

How to store object in view state?

We can store an object easily as we can store string or integer type variable. But what we need ? we need to convert it into stream of byte. because as I already said , view state store information in hidden filed in the page. So we need to use Serialization. If object which we are trying to store in view state ,are not serializable , then we will get a error message .
Just take as example,
//Create a simple class and make it as Serializable
[Serializable]
public class student
{
    public int Roll;
    public string Name;
    public void AddStudent(int intRoll,int strName)
      {
        this.Roll=intRoll;
        this.Name=strName;
           }
}
Now we will try to store object of "Student" Class in a view state.
 //Store Student Class in View State
student _objStudent = new student();
_objStudent.AddStudent(2, "Abhijit");
ViewState["StudentObject"] = _objStudent;

//Retrieve Student information view state
 student _objStudent;
_objStudent = (student)ViewState["StudentObject"]; 

How to trace your view state information?

If you want to trace your view state information, by just enable "Trace" option of Page Directive
User_S2.gif
Now Run your web application, You can view the details of View State Size along with control ID in Control Tree Section. Don't worry about "Render Size Byte" , this only the size of rendered control.
User_S3.jpg
Fig : View State Details

Enabling and Disabling View State

You can enable and disable View state for a single control as well as at page level also. To turnoff view state for a single control , set EnableViewState Property of that control to false. e.g.:
TextBox1.EnableViewState =false;
To turnoff the view state of entire page, we need to set EnableViewState to false of Page Directive as shown bellow.
User_S4.gif
Even you disable view state for the entire page , you will see the hidden view state tag with a small amount of information, ASP.NET always store the controls hierarchy for the page at minimum , even if view state is disabled.
For enabling the same, you have to use the same property just set them as True
as for example, for a single control we can enabled view state in following way,
TextBox1.EnableViewState =true;
and for a page level,
User_S5.gif

How to make view state secure?

As I already discuss View state information is stored in a hidden filed in a form of Base64 Encoding String, and it looks like:
User_S1.jpg
Fig : View state stored in hidden field
Many of ASP.NET Programmers assume that this is an Encrypted format, but I am saying it again, that this is not a encrypted string. It can be break easily. To make your view state secure, There are two option for that,
  • First, you can make sure that the view state information is tamper-proof by using "hash code". You can do this by adding "EnableViewStateMAC=true" with your page directive. MAC Stands for "Message Authentication Code"
User_S6.gif
A hash code , is a cryptographically strong checksum, which is calculated by ASP.NET and its added with the view state content and stored in hidden filed. At the time of next post back, the checksum data again verified , if there are some mismatch, Post back will be rejected. we can set this property to web.config file also.
  • Second option is to set ViewStateEncryptionMode="Always" with your page directives, which will encrypt the view state data. You can add this in following way
User_S7.gif
It ViewStateEncryptionMode has three different options to set:
  • Always
  • Auto
  • Never
Always, mean encrypt the view state always, Never means, Never encrypt the view state data and Auto Says , encrypt if any control request specially for encryption. For auto , control must callPage.RegisterRequiresViewStateEncryption() method for request encryption.
we can set the Setting for "EnableViewStateMAC" and ViewStateEncryptionMode" in web.config also.
User_S8.gif
Note : Try to avoid View State Encryption if not necessary , because it cause the performance issue.

Some Important Points

QuestionsAnswer
Client Side or Server Side ?Client Side
Use Server Resource ?No
Easy to implement ?Yes
Cause Performance Issue ?For heavy data and case of encryption & decryption
Support Encryption Decryption?Yes
Can store objects ?Yes, but you need to serialize the class.
TimeoutNo
That's all for view state. Hope you have enjoyed this article, please don't forget to give me your valuable suggestions. If anything need to update or changed please post your comments and please give me suggestion.

Beginner's Guide to ASP.NET Cookies

Table of Contents

Introduction

First of all, I would like to thank all of the readers who have read my previous articles and voted for me. Wow.. what a great support I have got from you people. Again, thanks to Sean Ewington for starting up a very fantastic idea with the Beginner's Walk for Web Development article. I have written a few articles for beginners. I really felt great when my Beginner's Guide to ViewState article was displayed on the CodeProject Home page Editor's Choice section. Following are the articles that I have written so far for beginners.
Cookies, Session, and Application object are in my queue. Now it's time for learning about cookies. I have spent a lot of time to prepare this article. And you will be very surprised to know that the Introduction part is the last topic which I am writing before posting the article. I have read many articles, books before writing this article. I have done some hands on projects also. Hope I have explained this well and I hope you people will like it. Please give your suggestions and feedback.

What are Cookies?

Cookies are the small files that are created on the client's system or client browser memory (if temporary). It is used for state management which I have already discussed in my ViewState article. We can store small pieces of information in a client system and use it when needed. The most interesting thing is that it works transparently with the user. It can be easily used anywhere in your web application. Cookies store information in plain text format. If a web application uses cookies, the server sends cookies and the client browser will store it. The browser then returns the cookie to the server the next time the page is requested. The most common examples of using a cookie are to store user information, user preferences, password remember option, etc. Cookies have many advantages and disadvantages. I will come to this later on, but first, have a look at how cookies are started.

How are Cookies started?

When a client requests to the server, the server sends cookies to the client. The same cookies can be referred to for subsequent requests. For example, if codeproject.com stores the session ID as cookies, when a client hits the first time on the server, the server generates the session ID and sends it as a cookie to the client [as shown in Fig. 1.0.].
Cookie1.jpg
Fig. 1.0: Initial state of cookie creation
Now for all subsequent requests from the same client, it uses the session-ID from the cookies, just like in the picture below:
Cookie2.jpg
Fig. 1.1: Subsequent request for other pages
The browser and web server are responsible for exchanging cookies information. For different sites, the browser keeps cookies differently. If a page needs information from the cookies, when that URL is hit, first it searches the local system for cookies information, then it is moved to the server with that information.

Advantages of Cookies

Following are the main advantages of using cookies in a web application:
  • It's very simple to use and implement.
  • Browser takes care of sending the data.
  • For multiple sites with cookies, the browser automatically arranges them.

Disadvantages of Cookies

The main disadvantages of cookies are:
  • It stores data in simple text format, so it's not secure at all.
  • There is a size limit for cookies data (4096 bytes / 4KB).
  • The maximum number of cookies allowed is also limited. Most browsers provide limits the number of cookies to 20. If new cookies come, the old ones are discarded. Some browsers support up to 300.
  • We need to configure the browser. Cookies will not work on a high security configuration of the browser. [I have explained this in details.]

How to create Cookies

For working with cookies, we need to use the namespace System.web.
Cookie3.gif
Have a look at the code and see how we create cookies and add it with a web response.
Cookie4.gif
The cookies which have been created will persist until the browser is closed. We can persist cookies beyond that. But how? I have explained this below.

How to read data from Cookies

Now it is time to retrieve data from the cookies. Before reading the cookies, first we need to check whether a cookie was found or not. It is always a good practice to check a cookie before reading it, because the browser might have disabled cookies.
Cookie7.gif

What are persistent and non-persistent Cookies?

We can classify cookies into two:
  • Persistent Cookies
  • Non-persistent Cookies
Persistent cookies: These can be called permanent cookies, which are stored in the client hard-drive until they expire. Persistent cookies should be set with an expiration dates. Sometimes thet stays until the user deletes the cookies. Persistent cookies are used to collect identification information about a user from the system. I have discussde about the creation of persistent cookies in the "How to make persistant Cookies" section.
Non-persistent Cookies: These can be called temporary Cookies. If there is no expiration time defined, then the cookie is stored in the browser memory. The example which I have shown above is a non-persistent cookie.
There is no difference between modifying a persistent and non-persistent cookie. The only difference between them is persistent cookies should have an expatriation time defined.

How to make persistent Cookies?

I have already given an example of non-persistent cookies. For persistent cookies, we need to add an expiration time. In the given code, I have specified 5 days.
//Creting a Cookie Object
HttpCookie _userInfoCookies = new HttpCookie("UserInfo");

//Setting values inside it
_userInfoCookies["UserName"] = "Abhijit";
_userInfoCookies["UserColor"] = "Red";
_userInfoCookies["Expire"] = "5 Days";

//Adding Expire Time of cookies
 _userInfoCookies.Expires = DateTime.Now.AddDays(5);

//Adding cookies to current web response
Response.Cookies.Add(_userInfoCookies);
The most interesting thing is where they are stored in the hard drive.

Where are Cookies stored in the local hard drive?

This is one of the interesting things to know to find out cookies in your local drive. First of all, from ExplorerFolder Options, select show hidden files and folders.
Cookie8.jpg
Fig 1.2 : Show Hidden files and Folders settings
Now browse into Documents & Settings of the current user and open the cookies folder. Take a look at this picture.
Cookie9.jpg
Fig 1.3 : Reading Cookies info in the local System

How to remove persistent Cookies before its expiration time?

This is a funny task. If you want to remove persistent cookies before the expiration date, the only way is to replace them with cookies with a past expiration date.
HttpCookie _userInfoCookies = new HttpCookie("UserInfo");
//Adding Expire Time of cookies before existing cookies time
_userInfoCookies.Expires = DateTime.Now.AddDays(-1);
//Adding cookies to current web response
Response.Cookies.Add(_userInfoCookies);

How to control Cookies scope?

We can controll the scope of cookies the following ways:
  • Limiting Cookies to Path
  • Limiting Cookies Domain

What is Cookie Munging?

By default, ASP.NET uses cookies to stores session IDs, but as I have already mentioned, some browser do not support cookies. To overcome this problem, ASP.NET uses "Cookie Munging" to manage session variables without cookies.
[Though this is related with Session, I am just giving a basic overview. I will explain this in detail in my next article which will be on Session.]

Why are we using Cookie Munging in ASP.NET?

There are some specific reasons to use cookie munging in ASP.NET:
  • Some browsers do not support cookies.
  • Sometimes users disable cookies in the browser.

How Cookie Munging works

When the user requests for a page on the server, the server encodes the session ID and adds it with every HREF link in the page. When user click on a link, ASP.NET decodes that session ID and passes it to the page that the user has requested. Now the requesting page can retrieve any session variable. This all happens automatically if ASP.NET detects that the user's browser does not support cookies.
Cookie10.jpg
Fig .1.4 : Steps of Cookie Munging

How to implement Cookie Munging

For this, we have to make session state cookie-less.
<sessionState cookieless= "true />
I am stopping here on this topic. I will explain it in detail when I write an article on Session.

How to configure Cookies in the browser

We can now take a look at how we can configure the browser for enabling/disabling cookies. I have already discussed about settings in the IE browser. Click on Tools -> Internet Options -> go to Privacy tab. There you will be able to see a scroll bar with the following options:
  • Accept All Cookies
  • Low
  • Medium
  • Medium High
  • Block All Cookies
Test.gif
The first option will accept all cookies and the last option will block all cookies. You can get the details of those settings while scrolling the bar.

Summary

There are many topics to learn about cookies. I have covered just a small portion. Hope this will help all beginners to get familiar with cookies. Please give your feedback and suggestions.

A Walkthrough to Application State

Table of Contents

Introduction

There are a lot of articles available on different ways of managing the states in the web. I was not able to find details on Application Object and events. So I read different books and articles and thought of sharing my knowledge with all of you. Hope you will like it and give your feedback and suggestions.
As we all know, web is stateless. A Web page is recreated every time it is posted back to the server. In traditional web programming, all the information within the page and control gets wiped off on every postback. To overcome this problem, ASP.NET Framework provides various ways to preserve the states at various stages like controlstate, viewstate, cookies, session, etc. These can be defined in client side and server side state management. Please see the image below:
Various option to maintain the states
Figure: Options available to maintain the state
There are lot more written about most of them. In this article, I am going to explore mainly Application state,Application events and Application Objects.

Application LifeCycle

First, I am going to explain ASP.NET Application Lifecycle. One needs to really understand the application Lifecycle, so that one can code efficiently and use the resources available. Also it is very important to discuss, as we are going to Application level events, objects, etc.
ASP.NET uses lazy initialization technique for creating the application domains, i.e., Application domain for an application is created only when the first request is received by the web server. We can categorise Application life cycle in several stages. These can be:
  • Stage 1: User first requests any resource from the webserver.
  • Stage 2: Application receives very first request from the application.
  • Stage 3: Application basic Objects are created.
  • Stage 4: An HTTPapplication object is assigned to the request.
  • Stage 5: And the request is processed by the HTTPApplication pipeline.
I'll explain the points one by one.
Stage 1: The Application life cycle starts when a user hits the URL by typing it in the browser. The browser sends this request to the webserver. When webserver receives the request from the browser, it examines the file extension of the requested file and checks which ISAPI extension is required to handle this request and then passes the request to the appropriate ISAPI extension.
URL Request Flow
Figure: URL Processing
Note 1: If any extension is not mapped to any ISAPI extension, then ASP.NET will not receive the request and the request is handled by the server itself and ASP.NET authentication, etc. will not be applied.
Note 2: We can also make our own custom handler, to process any specific file extension.
Stage 2: When ASP.NET receives the first request, the Application manager creates an application domain for it. Application domains are very important because they provide the isolation amongst various applications on the webserver and every application domain is loaded and unloaded separately, and in application domain an instance of class HostingEnvironment is created which provides access to information about all application resources.
ALC1.JPG
Figure: ASP.NET Handling first request
Stage 3: After creating the application domain and hosting environment, ASP.NET initializes the basic objects asHTTPContextHTTPRequest and HTTPResponseHTTPContext holds objects to the specific application request as HTTPRequest and HTTPResponse.HTTPRequest contains all the information regarding the current request like cookies, browser information, etc. and HTTPResponse contains the response that is sent to client.
Stage 4: Here all the basic objects are being initialized and the application is being started with the creation ofHTTPApplication class, if there is Global.asax (It is derived from HTTPApplication class) in the application, then that is instantiated.
Multiple request processing
Figure: Multiple requests processed by ASP.NET
Note: When the application is accessed for the first time, the HTTPApplication instance is created for further requests. It may be used for other requests as well.
Stage 5: There are a lot of events executed by the HTTPApplication class. Here, I have listed down a few important ones. These events can be used for any specific requirement.
Application Events
Fig: Application Events

What is Global.asax

To handle application events or methods, we can have a file named Global.asax in the root directory of your application. At any single point of time, an HTTPApplication instance handles only one request, so we don't need to think about locking and unlocking of any non static members, but for static members we do require. I'll discuss it in detail in a later section of this article. Following are the commonly used events in theglobal.asax file.
AppEvents.JPG
Figure: Methods in Global.asax

Application Restarts When

If we are going to change the source code, then ASP.NET requires to recompile into assemblies and also the application will restart as well. In spite of this, there are also certain things that force the application to get restarted. If we'll change in the following folder whether adding, modifying or deleting, the application will restart:
  • Any changes in the application's bin folder
  • Changes in Localisation resources, i.e., App_GlobalResources or App_LocalResources folders
  • Changes in Global.asax file
  • Modification of any source code in App_code folder
  • Any changes in web.config file
  • Any changes in the webservice references, i.e., App_WebReferences folder.

Application State:Intro

Application state is one of the ways available to store some data on the server and faster than accessing the database.The data stored on the Application state is available to all the users(Sessions) accessing the application. So application state is very useful to store small data that is used across the application and same for all the users. Also we can say they are global variables available across the users. As I am saying small data, we should not store heavy data in ApplicationState because it is stored on the server and can cause performance overhead if it is heavy. We'll discuss it later. Technically the data is shared amongst users viaHTTPApplcationState class and the data can be stored here in key value pair. It can also be accessed through Application property of the HTTPContext class.

How Application State Works

As I have already discussed above, an instance of HttpApplicationState is created when first time a request comes from any user to access any resource from the application. And this can be accessed through the propertyApplication property of HTTPContext Object. All HTTPModules and Handlers have access to this property. The lifetime of the values spans through the lifetime of the ASP.NET application until the application is unloaded. Normally, we set these Application variables in Application_OnStart event in Global.asax file and access and modify through ASP.NET pages.

How to Save values in Application State

One thing to keep in mind is that application state stores the data as of Object type, so at the time of reading, the values we need to convert it in the appropriate type.
So normally, we use to store the Application wise data in Application state which is shared across the users. So we can save the data in Application_OnStart method in Global.asax file as:
void Application_Start(object sender, EventArgs e)
{ 
Application["Message"] = "Welcome to my Website"; 
}
We can also save object of some Class in Application variable. Let's say we have a class as:
/// <summary>
/// Summary description for Employee
/// </summary>
public class Employee
{
    private string _name;
    public string Name {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
        } 
    }
    private decimal _annualSalary;
    public decimal AnnualSalary
    {
        get
        {
            return _annualSalary;
        }
        set
        {
            _annualSalary = value;
        }
    }
 public Employee()
 {
  //
  // TODO: Add constructor logic here
  //
 }
}
Put this class file in App_Code folder. Now class will be available throughout the application so also in Global.asax. Now to save it in Application_OnStart as:
   void Application_Start(object sender, EventArgs e) 
    {
        Employee objEmployee = new Employee();
        objEmployee.Name = "Brij";
        objEmployee.AnnualSalary = 1000000;
        Application["EmployeeObject"] = objEmployee;
    }
Note: Here one thing I would like to mention is that we don't require to serialize the object to store in Application state as we need to keep in mind in case of viewstate, etc. So there is no need of serializationhere. Smile | :) We can also modify these values from any method in the application. Here I am modifyingApplication["Message"] in onclick method of a button in a page as:
protected void Button1_Click(object sender, EventArgs e)
    {
        Application["Message"] = "Welcome Dude!!";
    }
Now we'll get the modified values whenever we try to access it. Let's also add a new variable on another button Click event as:
 protected void Button3_Click(object sender, EventArgs e)
 {
     Application["NewValue"] = "Hello";
 }
This value will also be available throughout the application life. One thing I also want to discuss is that Application state is not thread safe so it can be accessed by multiple threads at the same time, i.e., if we have stored some value in Application state say some counter and we increase it whenever a particular page is accessed. So at a single point of time, two instances of page of a different session can read the same value and update it. So we'll not get the desired result. So here we need some synchronisation mechanism so that at a single point of time only, one can update its value. Here we can call theSystem.Web.HttpApplicationState.Lock method, set the application state value, and then call theSystem.Web.HttpApplicationState.UnLock method to unlock the application state, freeing it for other write or update it as:
  if (Application["Counter"] != null)
        {
            Application.Lock();
            Application["Counter"] = ((int)Application["Counter"]) + 1;
            Application.UnLock();
        }
So by this way, we can avoid writing the same value from multiple Threads at the same time.

How To Read Values from Application State

So to read from Application state is fairly simple. We should just have a safety check to see whether the value we are accessing is null, if the data will not be in Application state is not there then it will return null and if we'll try to cast it in any different type, it'll throw an exception. As I already discussed, Application state stores the data in object form so we need to typecast after reading it. So we can read the value as:
if(Application["Message"] !=null)
{
      string message = Application["Message"] as string;
}
The object also can be read as:
if (Application["EmployeeObject"] != null)
{
    Employee myObj = Application["EmployeeObject"] as Employee;
    string Name = myObj.Name;
}

A Classic Example of Application State

A classic example of Application variable can be to show the number of online user in a website. This can be done in the following steps:
  • Add an online counter variable ApplicationStart method of Global.asax file as:
    Application["OnlineCounter"] = 0; 
    So in this, a variable will be added when the application first starts and will be initialized to as there will be no logged in user at that point of time.
  • Now as we know whenever a new user opens the website, a new session is created and Session_Startmethod of Global.asax is called. So we can increase the counter in this method as:
        void Session_Start(object sender, EventArgs e) 
        {
            // Code that runs when a new session is started
           if (Application["OnlineCounter"] != null)
            {
                Application.Lock();
                Application["OnlineCounter"] = 
       ((int)Application["OnlineCounter"]) + 1;
                Application.UnLock();
            }
        }
    We should use the Locks, else we may get the wrong result because this may be updated at the same time and updated data is not correct. How: Let's say we currently have Application["OnlineCounter"] is 5and at the same time, two sessions read the value and make an increment to and updated it. Application state as 6. So although two users are logged in, the counter is increased by one only. So to avoid this, we should use the locks.
  • So also at the time session ends, we should decrease it by one. As I already discussed, an eventSession_End is fired whenever a session ends. So it can be done as:
        void Session_End(object sender, EventArgs e) 
        {
            // Code that runs when a new session is started
            if (Application["OnlineCounter"] != null)
            {
                Application.Lock();
                Application["OnlineCounter"] = 
      ((int)Application["OnlineCounter"]) - 1;
                Application.UnLock();
            }
        }
  • And this value can be accessed throughout the application at any point of time in the application as:
      if (Application["OnlineCounter"] != null)
            {
                int OnlineUsers = ((int)Application["OnlineCounter"]);
            }    
    and this value can be used anywhere in the application.

Application State: Points to Think About Before Using

  • Application state is stored in memory of webserver, so huge amount of data can cause severe performance overhead. Also keep in mind that these variables will be stored in memory till the application ends whether we need the entire time or not. So use it judiciously.
  • If the application goes down or is restarted, then all the data stored in Application state is lost.
  • Also Application data is not shared between multiple servers in webfarm scenario.
  • Application also doesn't work in case of Webgarden. Variables stored in application state in either of those scenarios are global only to the particular process in which the application is running. Each application process can have different values.
  • Application state is not thread safe, so we must keep the synchronisation in mind as discussed above.

Application State vs Caching

Although both provide the same feature and can be used to store the data at application level, there are a lot of differences between both.
Sr NoApplication StateCache
1Application variables are one of the techniques provided by ASP/ASP.NET to store the data at application level and this is available to all users.Cache is one technique provided by ASP.NET to store the data at the application level with many options.
2Application variables are available throughout the lifecycle of the application until explicitly removed or overridden.Cache is volatile. It provides the opportunity to automatically expire the data based on the settings or memory gets reclaimed when memory is scarce.
3Application variable should be used only when data is limited, i.e., it should not be like we store some dataset and keep adding the data in same, which may lead to choke the webserverCache provides a flexible way to store data on the webserver and also get removed when memory becomes low.