Application State in ASP

6
Ask a Question READER LEVEL: ARTICLE This article explains the life cycle of Application State; the Global.asax file is also explained with a real-life example. Application State in ASP.Net By Divya Sharma on Jun 15, 2014 Download Files: Application_state.rar 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 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. 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. 01 Basics of AngularJS: Part 1 02 Google+ Authentication in ASP.Net 03 How to Configure SharePoint Server in Windows Azure 04 How to Retrieve All Users From the Group in SharePoint Using REST API 05 How to Create Nodejs Module and Publish Over to Npm 06 Basics of AngularJS: Part 2 07 AngularJS Shopping Cart Using MVC and WCF Rest Service 08 Learn Simple MVVM and Command Bindings in 15 Mins 09 Simplify JavaScript Object Oriented Programming Model: Part 1 10 OWIN and Katana Interfaces of ASP.Net View All TRENDING UP Follow @twitterapi In Focus Delhi Developer's Day: Learn Microsoft Dynamics CRM Contribute Basics of AngularJS: Part 1 C# Corner Search 12.3 k 1 2 TECHNOLOGIES ANSWERS BLOGS VIDEOS INTERVIEWS BOOKS NEWS CHAPTERS CAREER ADVICE JOBS

description

asp.net application state

Transcript of Application State in ASP

  • Ask a Question

    READER LEVEL:ARTICLE

    This article explains the life cycle of Application State; the Global.asax file is alsoexplained with a real-life example.

    Application State in ASP.NetBy Divya Sharma on Jun 15, 2014

    Download Files: Application_state.rar

    Background

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

    Introduction

    Application State is a state management technique. Application State is stored in the memory of the theserver and is faster than storing and retrieving information in a database. Session sate is specific for a singleuser session, but Application State is for all users and sessions. Application State does not have a defaultexpiration period. When we close the worker process the application object will be lost. Technically the data isshared amongst users by a HTTPApplcationState class and the data can be stored here in a key/value pair. Itcan 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 the request it firstchecks the extension to determine whether or not it is ISAPI because this request can only be handled bythe ISAPI extension; if the extension is different then the request is handled by the server itself.

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

    01 Basics of AngularJS: Part 1

    02 Google+ Authentication in ASP.Net

    03 How to Configure SharePoint Server inWindows Azure04 How to Retrieve All Users From theGroup in SharePoint Using REST API05 How to Create Nodejs Module andPublish Over to Npm06 Basics of AngularJS: Part 2

    07 AngularJS Shopping Cart Using MVCand WCF Rest Service08 Learn Simple MVVM and CommandBindings in 15 Mins09 Simplify JavaScript Object OrientedProgramming Model: Part 110 OWIN and Katana Interfaces ofASP.Net

    View All

    TRENDING UP

    Follow @twitterapi

    In Focus Delhi Developer's Day: Learn Microsoft Dynamics CRM

    Contribute

    Basics of AngularJS: Part 1 C#CornerSearch

    12.3 k 1 2

    TECHNOLOGIES ANSWERS BLOGS VIDEOS INTERVIEWS BOOKS NEWS CHAPTERS CAREER ADVICE JOBS

  • 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 asHTTPRequest and HTTPResponse.HTTPRequest contains all the information regarding the current requestlike cookies, browser information and so on and the HTTPResponse contains the response that is sent to theclient.

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

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

    Global.asax file: the Global.asax file is used for handling application events or methods. It always exists inthe 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. Theevents 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 cleanup but wecan use it for safety purposes.

    ASP.NET Application State reallife example

    Now I am explaining the reallife example. If you want to see the number of users online then we need touse Application State.

    Step 1 : Open Visual Studio 2010.

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

    Step 3 : Now click on Solution Explorer.

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

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

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

    01.

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

    01. protectedvoidApplication_Start(objectsender,EventArgse)02. {03. //thiseventisexecuteonlyoncewhenapplicationstartanditstorestheservermemoryuntiltheworkerprocessisrestart04. Application["user"]=0;05. }06. protectedvoidSession_Start(objectsender,EventArgse)07. {08. //whensessioninstartapplicationvariableisincreasedby109. Application.Lock();10. Application["user"]=(int)Application["user"]+1;11. Application.UnLock();12. }13. protectedvoidSession_End(objectsender,EventArgse)14. {15. //whensessioninendapplicationvariableisdecreaseby116. 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:

    01. protectedvoidPage_Load(objectsender,EventArgse)02. {03. Response.Write("Thenumofusersonline="+Application["user"].ToString());04. }

  • Output

    When the same request is sent to the server with a different browser then the number of online clients isalso not increased because the browser binds with the session id so both of the tabs have the same sessionid so the server knows that the request comes from the same user. If we change the session id from the URLand again refresh then the number of online clients is increased by one because the server thinks that therequest 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 variablesare like multiuser 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.

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

    5. Application State variables have a concurrency problem so we need to synchronize the method byusing the lock and unlock methods. So multiple thread problems are resolved since only one threadcan do the work.

    6. An application variable is used only when the variable needs to have global access and when you needthem for the entire time, during the lifetime of an application.

    Divya SharmaHello I am Divya Sharma,Now i am final year student of mewar university,chittorgarh(Rajasthan)

    Rank321

    139.7kReaders

    StarterMember

    1Time

  • RELATED ARTICLES

    Hosted By CBeyond Cloud Services

    2015 C# Corner. All contents are copyright of their authors.

    Showing Data In GridView Using ApplicationState in VB.NET

    Application Level State Management inASP.NET

    ASP.NET State Management Techniques Part 2 ASP.NET Session StateWhat is View State and How it Works inASP.Net

    Hour 5: Understanding 5 ASP.NET StateManagement Techniques in 5 hours

    Introduction to ASP.Net Session State Management in ASP.NetHour 1: Understanding 5 ASP.NET Statemanagement techniques in 5 hours

    InProc Session State Mode in ASP.Net

    COMMENTS 1of1

    Jan 23, 2015

    620 7 1.8k 1 0 Post Reply

    Nice article ...Deepak Porwal

    Type your comment here and press Enter Key....

    COMMENT USING

    MVPs MOST VIEWED LEGENDS NOW PRIZES REVIEWS SURVEY CERTIFICATIONS DOWNLOADS

    CONTACT US PRIVACY POLICY TERMS & CONDITIONS SITEMAP REPORT ABUSE

    PHOTOS CODE SNIPPETS CONSULTING TRAINING STUDENTS MEMBERS MEDIA KIT ABOUT US LINKS IDEAS