Application State in ASP.Net (2024)

Background

We all know that the web uses the HTTP protocol and that the HTTP protocol is a stateless protocol, in other words when a client sends a request to the server, an instance of the page is created and the page is converted to HTML format and then the server returns the response and then the instance of the page and the value of the control is destroyed. So if we have a requirement to store the value of controls then a State Management technique is used.

Introduction

Application State is a state management technique. Application State is stored in the memory of the the server and is faster than storing and retrieving information in a database. Session sate is specific for a single user session, but Application State is for all users and sessions. Application State does not have a default expiration period. When we close the worker process the application object will be lost. Technically the data is shared amongst users by a HTTPApplcationState class and the data can be stored here in a key/value pair. It can also be accessed using the application property of the HTTPContext class.

Application State Life Cycle

Step 1: When the Browser sends a request to the web server and the server receives the request it first checks the extension to determine whether or not it is ISAPI because this request can only be handled by the ISAPI extension; if the extension is different then the request is handled by the server itself.

Application State in ASP.Net (1)

Step 2: After receiving the request the Application Manager creates an application domain. In the application domain an instance of the class HostingEnvironment is created that provides access to information about all application resources.

Application State in ASP.Net (2)

Step 3: After creating the application domain, ASP.NET initializes the basic objects as HTTPContext, HTTPRequest and HTTPResponse. HTTPContext holds objects to the specific application request as HTTPRequest and HTTPResponse.HTTPRequest contains all the information regarding the current request like cookies, browser information and so on and the HTTPResponse contains the response that is sent to the client.

Step 4: Here all the basic objects are being initialized and the application is being started with the creation of the HTTPApplication class.

Application State in ASP.Net (3)

Step 5: Then events are executed by the HTTPApplication class for any specific requirement. Here is a list of events:

Application State in ASP.Net (4)

Global.asax file: the Global.asax file is used for handling application events or methods. It always exists in the root level. Events are one of the following of the 2 types in the Global application:

  1. Events that will be raised on a certain condition.
  2. Events that will be raised on every request.

The application will be started only once; if 10 users send a request then 10 user sessions are created. The events of the Global.asax file are:

  1. Application_Start() : This method is invoked initially when first application domain is created.
  2. Session_Start() : This method is called every time a session is start.
  3. Application_BeginRequest() : After an application has started the first method Application_BeginRequest() is executed for every user.
  4. Application_AuthenticateRequest() : It checks to determine whether or not the user is valid.
  5. Application_Error() : Whenever an unhandled exception occurs then this event will be called.
  6. Session_End() : When a user session is ended and all the data related to a specific user is cleared then the Session_End() event is called.
  7. Application_End() : This method is called before the application ends. This can take place if IIS is restarted or the application domain is changing.
  8. Application_Disposed() : This event is called after the application will be shut down and the .NET GC is about to reclaim the memory it occupies. Although this is very late to perform any clean-up but we can use it for safety purposes.

ASP.NET Application State real-life example

Now I am explaining the real-life example. If you want to see the number of users online then we need to use Application State.

Step 1: Open Visual Studio 2010.

Step 2: Then click on "New Project" > "Web" > "ASP.NET Empty Web Application" .

Application State in ASP.Net (5)

Step 3: Now click on Solution Explorer.

Application State in ASP.Net (6)

Step 4: Now right-click on "Add" > "New Item" > "Web Form" and add the name of the web form.

Application State in ASP.Net (7)

Step 5: Now add the Global.asax file. Again go to Solution Explorer and "Add" > "New Item" > "Global Application Class".

Application State in ASP.Net (8)

Step 6: Now to configure the session we need to use the web.config file as in the following:

  1. <sessionStatemode="InProc"timeout="20"cookieless="true"></sessionState>

Step 7: Now to count the number of users online we need to use the global.asax file as in the following:

  1. protectedvoidApplication_Start(objectsender,EventArgse)
  2. {
  3. //thiseventisexecuteonlyoncewhenapplicationstartanditstorestheservermemoryuntiltheworkerprocessisrestart
  4. Application["user"]=0;
  5. }
  6. protectedvoidSession_Start(objectsender,EventArgse)
  7. {
  8. //whensessioninstartapplicationvariableisincreasedby1
  9. Application.Lock();
  10. Application["user"]=(int)Application["user"]+1;
  11. Application.UnLock();
  12. }
  13. protectedvoidSession_End(objectsender,EventArgse)
  14. {
  15. //whensessioninendapplicationvariableisdecreaseby1
  16. Application.Lock();
  17. Application["user"]=(int)Application["user"]-1;
  18. Application.UnLock();
  19. }

Step 8: Now to show the online users we need to use a web form as in the following:

  1. protectedvoidPage_Load(objectsender,EventArgse)
  2. {
  3. Response.Write("Thenumofusersonline="+Application["user"].ToString());
  4. }

Output

Application State in ASP.Net (9)

Application State in ASP.Net (10)

When the same request is sent to the server with a different browser then the number of online clients is also not increased because the browser binds with the session id so both of the tabs have the same session id so the server knows that the request comes from the same user. If we change the session id from the URL and again refresh then the number of online clients is increased by one because the server thinks that the request comes from a different browser.

Important points of Application State variables

  1. Application State variables are available across all pages and all sessions. Application State variables are like multi-user Global data.
  2. Application variables are stored on a web server.
  3. Application State variables are cleared, only when the process hosting the application is restarted, that is when the application is ended.
  4. Application State variables do not support web farms and web gardens: Application State variables are not supported be web farms.

    Application State in ASP.Net (11)

    A client sends a request and the request goes to the load balancer and the load balancer sends a request to web server1 and the Application State variables are stored in a web server1. If the subsequent request is sent by the client again and the load balancer sends a request to web server2 and the Application State variables are not stored in web server2 then something. Web servers do not share application state variables.

  5. Application State variables have a concurrency problem so we need to synchronize the method by using the lock and unlock methods. So multiple thread problems are resolved since only one thread can do the work.
  6. An application variable is used only when the variable needs to have global access and when you need them for the entire time, during the lifetime of an application.
Application State in ASP.Net (2024)
Top Articles
Complete Tome Rs3
Paisanos Duncan Sc Menu
Funny Roblox Id Codes 2023
Golden Abyss - Chapter 5 - Lunar_Angel
Www.paystubportal.com/7-11 Login
Joi Databas
DPhil Research - List of thesis titles
Shs Games 1V1 Lol
Evil Dead Rise Showtimes Near Massena Movieplex
Steamy Afternoon With Handsome Fernando
Which aspects are important in sales |#1 Prospection
Detroit Lions 50 50
Zürich Stadion Letzigrund detailed interactive seating plan with seat & row numbers | Sitzplan Saalplan with Sitzplatz & Reihen Nummerierung
Grace Caroline Deepfake
978-0137606801
Nwi Arrests Lake County
Justified Official Series Trailer
London Ups Store
Committees Of Correspondence | Encyclopedia.com
Pizza Hut In Dinuba
Jinx Chapter 24: Release Date, Spoilers & Where To Read - OtakuKart
How Much You Should Be Tipping For Beauty Services - American Beauty Institute
Free Online Games on CrazyGames | Play Now!
Sizewise Stat Login
VERHUURD: Barentszstraat 12 in 'S-Gravenhage 2518 XG: Woonhuis.
Jet Ski Rental Conneaut Lake Pa
Unforeseen Drama: The Tower of Terror’s Mysterious Closure at Walt Disney World
Kcwi Tv Schedule
What Time Does Walmart Auto Center Open
Nesb Routing Number
Random Bibleizer
10 Best Places to Go and Things to Know for a Trip to the Hickory M...
Black Lion Backpack And Glider Voucher
Duke University Transcript Request
Lincoln Financial Field, section 110, row 4, home of Philadelphia Eagles, Temple Owls, page 1
Jambus - Definition, Beispiele, Merkmale, Wirkung
Netherforged Lavaproof Boots
Ark Unlock All Skins Command
Craigslist Red Wing Mn
School Tool / School Tool Parent Portal
D3 Boards
Jail View Sumter
Nancy Pazelt Obituary
Birmingham City Schools Clever Login
Trivago Anaheim California
Thotsbook Com
Vérificateur De Billet Loto-Québec
Funkin' on the Heights
Vci Classified Paducah
Www Pig11 Net
Ty Glass Sentenced
Latest Posts
Article information

Author: Kerri Lueilwitz

Last Updated:

Views: 5518

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Kerri Lueilwitz

Birthday: 1992-10-31

Address: Suite 878 3699 Chantelle Roads, Colebury, NC 68599

Phone: +6111989609516

Job: Chief Farming Manager

Hobby: Mycology, Stone skipping, Dowsing, Whittling, Taxidermy, Sand art, Roller skating

Introduction: My name is Kerri Lueilwitz, I am a courageous, gentle, quaint, thankful, outstanding, brave, vast person who loves writing and wants to share my knowledge and understanding with you.