BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The...

24
BIT 285: (Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session State, Global.asax Instructor: Craig Duckett

Transcript of BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The...

Page 1: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

BIT 285: (Web) Application Programming

Lecture 06: Thursday, January 22, 2015

Page Object, The Lifetime of a Web Application, Application State and Session State, Global.asax

Instructor: Craig Duckett

Page 2: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

2

JUST A HEAD'S UP: Assignment 1: Web Forms is due Tuesday, February 3, (zipped and uploaded to StudentTracker by midnight)

A NOTE ABOUT ICE 5: Additional links posted on ICE 5 that can prove useful and “solutions” to ICE 5 have also been posted

Page 3: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

3

The Page Object Revisited

Page 4: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

4

The Page Object RevisitedUnderstanding the page cycle helps in writing code for making some specific things happen at any stage of the page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with view-state data and run control behavior code.

Following are the different stages of an ASP.Net page:

1. Page Request: When ASP.Net gets a page request, it decides whether to parse and compile the page or there would be a cached version of the page; accordingly the response is sent

2. Starting of Page Life Cycle: At this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set (e.g., en-US)

3. Page Initialization: At this stage, the controls on the page are assigned unique ID by setting the UniqueID property and themes are applied. For a new request postback data is loaded and the control properties are restored to the view-state values.

4. Page Load: At this stage, control properties are set using the view state and control state values.5. Validation: The Validate method of the validation control is called and if it runs successfully, the IsValid property of the page is set to

true.6. Postback Event Handling: If the request is a postback (old request), the related event handler is called.7. Page Rendering: At this stage, view state for the page and all controls are saved. The page calls the Render method for each control

and the output of rendering is written to the OutputStream class of the Page's Response property.8. Unload: The rendered page is sent to the client and page properties, such as Response and Request are unloaded and all cleanup

done.

https://msdn.microsoft.com/en-us/library/ms178472%28v=vs.85%29.aspx

Page 5: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

5

The Page Object RevisitedAt each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes like onclick. Following are the page life cycle events:

• PreInit: PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler.

• Init: Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler.

• InitComplete: InitComplete event allows tracking of view state. All the controls turn on view-state tracking.

• LoadViewState: LoadViewState event allows loading view state information into the controls.

• LoadPostData: during this phase, the contents of all the input fields defined with the <form> tag are processed.

• PreLoad: PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.

• Load: the Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler.

• LoadComplete: the loading process is completed, control event handlers are run and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler.

• PreRender: the PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered.

• PreRenderComplete: as the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase.

• SaveStateComplete: state of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler.

• UnLoad: the UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.

Page 6: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

6

Note: Uncommented Response.Write("Page_Unload" + <br/>"); in Page_Unload event because it cause a runtime exception if allowed to run. Response is not available in this context. Demo: pageoverridedemo.zip

Page 7: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

7

The Lifetime of a Web Application

An Application object is created when the first request by the first user is made. It's global across all web pages and all web visitors.

The Application object is removed from memory after inactivity or shut down by the web server.

The Session object is created when the first request by each user is made. It is global across all web pages for each individual web visitor.

The Session object is removed from memory after inactivity by each individual web visitor.

Page 8: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

8

The Lifetime of a Web Application

The first time a request from a web browser is made for any page within a web site project an object called the Application is created and maintained by the ASP.NET runtime engine.

This Application object contains information that is global to the entire web site regardless of how many people access it or how many pages are contained in it.

When the application has been inactive for a long period of time or when the web site has been stopped by the web server, the Application object is removed from the computer's memory.

Similarly, each time a new user accesses a website, a Session object is created for that user. A Session can span multiple requests by a single user, but after a period of inactivity—like twenty minutes—the Session object is destroyed from the web server's computer memory.

After looking at both the Application and Session objects in more depth, we will revisit them several times throughout the quarter, however since we're talking about events right now let's talk about the four events that are triggered when (1) the application starts, (2) when the application ends, and (3) when a new session starts and (4) when a session ends.

Page 9: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

9

The Lifetime of a Web Application CONTINUED

Now, there is a special file that we can add to our website that will contain the events that occur at this global level and it is called the global.asax file.

1. I'm going to select and open a copy of the postbackdemo project from Lecture 4 called globaldemo, then right-click on the project in the Solution Explorer and Add a New Item, then scroll down to find and select the Global Application Class and leave it named Global.asax, then click the Add button.

globaldemo.zip

Page 10: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

10

The Lifetime of a Web Application CONTINUED

2. You can see that the Global.asax file has several event handlers, including the Application_Start event, the Application_End event, the Session_Start event, and the Session_End event.

3. There's also an Application_Error event which we'll talk about a bit later in the quarter when we discuss how to create a global error handler (exception handler) for the application.

Page 11: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

11

The Lifetime of a Web Application CONTINUED

So, what can we do with these four global events that occur?

In the case of the start events, the Application_Start and the Session_Start we can initialize any objects that are global to our Application or Session respectively. We can, for example, use the Application object or the Session object in order to save information in their respective internally managed collection of values (and we're going to do this in just a moment).

In the case of the end events, both Application_End and Session_End, we can perform any clean-up such as removing items from the computer's memory, setting them equal to null, storing the current state of either a user's data or the application's data back into the database before it shuts down, and other things of that nature.

Let me show you one quick way that we can gain some benefit from writing some code behind the Session_Start and Session_End events that will allow us to keep track of the current number of users that are working with our web site.

Page 12: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

12

The Lifetime of a Web Application CONTINUED

So, as I said a moment ago, the Application object and Session object both have an internally managed collection so I can add some values (think of these like variables, in the case of the Application, that are available to every user of every page of our website). So, in this case, I'm going to

3. Create a variable-like item in my global collection at the Application level called "userCount" and initialize that value to zero in Application_Start: Application.Add("userCount", 0);

Page 13: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

13

The Lifetime of a Web Application CONTINUED

4. Then I'll go down to Session_Start because what I want to do is when a new user comes to the website increment that userCount by 1. So, the first thing I want to do is retrieve the userCount value from the Application collection using Get and a also bit of data conversion because its going to return it to use in an object form (a bit messy because we'll have convert this first to a string and then convert the string to an integer) and then increment it by 1. Finally, I'll round things off by using a Set to store values back in.

Page 14: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

14

The Lifetime of a Web Application CONTINUED

5. Now, let's do the same thing for the Session_End but this time decrement the count when a user leaves the website.

Page 15: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

15

The Lifetime of a Web Application CONTINUED

6. Now, back in our pages we want to display the current user count in our web page. A quick-and-dirty way of writing a value to a web page is we can get access to that particular pages response stream by invoking:

Page.Response.Write("User Count:" + Application.Get("userCount").ToString());

Page 16: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

The Lifetime of a Web Application CONTINUED

7. When I run the program, I should get User Count: 1 appearing at the top of the page, and I do

8. Now, if I copy the URL from my Firefox browser, and paste it in my Chrome browser, the line at the top of the page should now display User Count: 2, and it does

9. And doing the same with Internet Explorer it now reads User Count: 3

16Demo: globaldemo.zip

Page 17: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

17

Application State

http://www.codeproject.com/Articles/87316/A-walkthrough-to-Application-State

Page 18: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

18

Application State

Application state is a data repository available to all classes in an ASP.NET application.

Application state is stored in memory on the server and is faster than storing and retrieving information in a database.

Unlike session state, which is specific to a single user session, application state applies to all users and all sessions.

Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another.

Page 19: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

19

Session State

Page 20: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

20

Session State

Session state enables you to store and retrieve values for a user as the user navigates the different ASP.NET pages that make up a Web application. HTTP is a stateless protocol, meaning that your Web server treats each HTTP request for a page as an independent request; by default, the server retains no knowledge of variable values used during previous requests. As a result, building Web applications that need to maintain some cross-request state information (applications that implement shopping carts, data scrolling, and so on) can be a challenge. Session state identifies requests received from the same browser during a limited period of time as a “session” and provides the ability to persist variable values for the duration of that session.

Session state is enabled by default for all ASP.NET applications. Session-state variables are easily set and retrieved using the Session property, which stores session variable values as a collection indexed by name.

For example, the following code example creates the session variables FirstName and LastName to represent the first name and last name of a user, and sets them to values retrieved from TextBox controls.

Page 21: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

21

Difference Between ViewState,Application State, and Session State

Page 22: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

22

The Differences

ViewState1. ViewState of a web form is available only with in that web form2. ViewState is stored on the page in a hidden field called _ViewState. Because of this, the

ViewState, will be lost, if you navigate away from the page, or if the browser is closed.3. ViewState is used by all asp.net controls to retain their state across postbackApplication State4. Application State variables are available across all pages and across all sessions. Application State

variables are like multi-user global data.5. Application State variables are stored on the web server.6. Application State variables are cleared, when the process hosting the application is restarted.Session State7. Session state variables are available across all pages, but only for a given single session. Session

variables are like single-user global data.8. Session state variables are stored on the web server.9. Session state variables are cleared, when the user session times out. The default is 20 minutes.

This is configurable in web.config

Page 23: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

23

Suggested Application and Session State Links of Interest

• Application State Overview (MSDN)

• How to Save Values in Application State (MSDN)

• How to Read Values from Application State (MSDN)

• Walkthrough to Application State (Code Project)

• Session State Overview (MSDN)

• How to Save Values in Session State (MSDN)

• How to Read Values from Session State (MSDN)

• Exploring Session in ASP.NET (Code Project)

• Session and Application in ASP.NET (C# Corner)

Page 24: BIT 285: ( Web) Application Programming Lecture 06: Thursday, January 22, 2015 Page Object, The Lifetime of a Web Application, Application State and Session.

24

Lecture 06: In-Class ExerciseFrom the menu bar, select Lectures and go to the Lectures 06 bar and select Lecture 06 ICE to begin working on today's in-class exercises.