State Management Beginning ASP.NET 4.5.1 in C# and VB Chapter 4 Pages 124 - 131 1 Objectives You will be able to: Understand the need to retain class member variables across page requests. Use .NET state variables to retain the values of member variables across page requests. View State Session State Application State 2 Repeat the Hello Page Download Hello.zip from the class web site: http://www.cse.usf.edu/~turnerr/Web_Application_Design/Downloads/025/ Expand Hello.zip . In Visual Studio, File > Open Web Site Navigate to the website folder and Open Be careful to drill down to the second level Hello folder. See next slide 3 Drill Down to the Website Folder 4 View Solution Explorer Be sure you have the right files. 5 The Code-Behind File Add this. 6 Run the App Enter name and then click OK. 7 After Clicking OK The textbox is still filled. 8 The TextBox is Still Filled We didn’t set the Text property of the TextBox. The server (ASPX) received the user input. Set the Text in the TextBox to the input value before it rendered the HTML for this page and sent it to the browser in response to the postback. Restored the appearance of the page as it was before the postback. 9 The TextBox is Still Filled This doesn’t happen with an HTML page. The textbox is empty when a fresh copy of the page is loaded on postback. 10 Add a Cancel Button Set ID and Text properties. Double click on Cancel button to add event handler. 11 Let Cancel Clear the TextBox 12 Try it! Fill in name. Then click Cancel rather than OK 13 After Cancel Clicked Now the TextBox is clear. 14 Try it again! Fill in name. This time click OK, then click Cancel. 15 After Cancel The TextBox is clear, but the greeting is still there! 16 The Greeting Was Restored The greeting was restored by the server before the HTML was sent down to the browser. But the greeting is not an input. How did the server know that it should restore the greeting? How did it know the contents of the greeting? 17 Viewstate The server encoded the appearance properties of the page, other than inputs, in a hidden input: ViewState 18 Look at the Source Hidden input __viewstate encodes the properties of the page that were set by our code. Sent back to the server on postback. If the application code does not change the properties, the previous appearance of the page will be restored when the page is refreshed on the browser. Including content that was set programatically on an earlier request. 19 VIEWSTATE The VIEWSTATE string is Base64 encoded. Can easily be decoded. 20 Clearing the Greeting If we want a clean copy of the page following Cancel, the event handler for Cancel must reset the greeting. End of Section 21 Visit Count Let’s add a counter and keep track of how many times the page has been visited. New label shows the count. 22 Visit Count: Designer 23 Visit Count: Code Behind 24 After First OK 25 After Second OK 26 What’s going on here? Why is count still 1 after additional OK clicks? Each OK sends a fresh copy of the page to the browser. count is reinitialized each time. To persist member variables across page loads, we can use session variables. Each user session will have its own copy. 27 Using a Session Variable Note C# indexer syntax. 28 Session State The Session object is a collection of name-value pairs. We can read and write a value using its name as an indexer. Values are stored as objects. We have to typecast them on retrieval. Session state is normally stored in server memory. Persists as long as the session lives. 29 Initial Page 30 After First OK 31 After Second OK 32 Very Important Any member variable that we want to remember from one page request to the next should be preserved in a session variable. Alternative to hidden inputs Create session variables for member variables that need to be preserved across interactions. Get values on Page_Load Check for existance and create if necessary. Update values when they change. 33 Session Variables Each session gets its own copy of all session variables. But what is a session? Look at the web site on a server, from various browsers and browser windows. 34 First Browser 35 First Browser After a few clicks on OK. 36 Another Tab on Same Browser Same session. 37 Same Browser, Another Window May have to run as administrator to get Chrome to open another window. Same session. 38 Different Browser New session. 39 New Window at Later Time New browser instance gets existing session. (After some amount of time the session will expire.) 40 From a Different Computer Browsers on different computers always have separate sessions. 41 Conclusions Be cautions about multiple tabs and multiple browser windows. Different tabs of a browser get a single session. Same browser in separate windows of the same computer get a single session. Different browsers on the same computer get different sessions. Browsers on different computers have separate sessions. 42 Using ViewState SessionState is stored in the server. Rather than using SessionState we can use ViewState to persist class variables. Values are stored in the __VIEWSTATE hidden variable sent to the browser and returned on PostBack. Each window and each tab will have a separate copy of ViewState. 43 Using ViewState 44 Looks the Same 45 After First OK 46 New Tab Gets own copy of the count. 47 ViewState A variable stored in ViewState is reinitialized on each direct request for the page (vs. PostBack). Old values are restored only on postback. A request for a different page automatically gets a new ViewState. 48 Try it! 49 New Tab 50 Original Tab, Reload 51 ViewState The __VIEWSTATE hidden variable is Base64 coded. Normally no reason to decode it. Use the ViewState collection to get values. 52 SessionState vs. ViewState Each has advantages and disadvantages. SessionState Stored on the server. Relatively safe from hacking. Is shared across tabs and windows Persists for some time after browser window is closes. Is not reinitialized on a direct request for the page. Is shared among different pages of an app. 53 SessionState vs. ViewState Each has advantages and disadvantages. ViewState Is included in the page sent to the browser. Is not shared among different pages Easily hacked. More communication overhead. Less server overhead. Not shared across tabs and windows. without special effort Is reinitialized on each direct request for a page. End of Section 54 Application State Similar to Session State but shared among all sessions running a given app. Stored in server memory. Collection created when the application is started. Concurrency issues! First request for the URL after server started Persists so long as the application runs. Lost when the application is stopped or restarted. Whenever the server is stopped or restarted 55 Application Level Events Event handlers for application level events are in file Global.asax. Application start Application end Application error Session start Session end In Global.asax 56 Example Let’s record the application start time in Application state and display it on each page. Will need to add Global.asax 57 Add New Item to Website 58 Add Global.asax Name should be Global.asax 59 Initial Global.aspx.cs 60 Application Start Time 61 Default.aspx.cs Response.Write puts its parameter into the output stream going to the browser. 62 Default.aspx 63 Page in Chrome 64 App on a Real Web Server http://rollinsturner.net/Hello_Application_State 65 Later That Evening The app has been restarted. 66 Same Page in IE Same start time. 67 Summary Application State can be used for objects to be shared among all users of an app. Stored in server memory. Take care not to use excessive memory. If objects are updated, use concurrency control. End of Presentation 68