Download presentation
Presentation is loading. Please wait.
Published byAlan Morris Modified over 9 years ago
1
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Managing State
2
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Quick test using System; using System.Collections.Generic; using System.Web.UI; using System.Windows.Forms; namespace WebApplication2{ public partial class _Default : Page { private readonly List _source = new List (); protected override void OnInit(EventArgs e) { base.OnInit(e); Button1.Click += Button1_Click; Button2.Click += Button2_Click; } protected void Page_Load(object sender, EventArgs e) { _source.Add(new User()); } private void Button1_Click(object sender, EventArgs e) { _source.Add(new User()); } private void Button2_Click(object sender, EventArgs e) { _source.Add(new User()); MessageBox.Show(_source.Count.ToString()); } } } using System; using System.Collections.Generic; using System.Web.UI; using System.Windows.Forms; namespace WebApplication2{ public partial class _Default : Page { private readonly List _source = new List (); protected override void OnInit(EventArgs e) { base.OnInit(e); Button1.Click += Button1_Click; Button2.Click += Button2_Click; } protected void Page_Load(object sender, EventArgs e) { _source.Add(new User()); } private void Button1_Click(object sender, EventArgs e) { _source.Add(new User()); } private void Button2_Click(object sender, EventArgs e) { _source.Add(new User()); MessageBox.Show(_source.Count.ToString()); } } } public class User { private string Name { get; set; } } Không dùng máy tính, giả sử có 1 web application có 2 button là button1, button2! Hãy đọc kỹ đoạn code sau đây trong 120 sec ! Khi chạy application, user click vào button1 3 lần, sau đó click vào button 3 thì messagebox sẽ show ra giá trị _source.Count bằng bao nhiêu ! Lý giải tại sao ? Không dùng máy tính, giả sử có 1 web application có 2 button là button1, button2! Hãy đọc kỹ đoạn code sau đây trong 120 sec ! Khi chạy application, user click vào button1 3 lần, sau đó click vào button 3 thì messagebox sẽ show ra giá trị _source.Count bằng bao nhiêu ! Lý giải tại sao ?
3
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Overview State Management Application and Session Variables Cookies and Cookieless Sessions
4
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Lesson: State Management What is State Management? Types of State Management Server-Side State Management Client-Side State Management The Global.asax File
5
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 What is State Management? First Name Last Name Please enter your logon information: John Submit Chen Web Server Login.aspx Web Server Hello John Chen Greetings.as px Please enter your logon information: John Submit Chen Hello Greetings.as px I forget who you are!! First Name Last Name Without State Management With State Management
6
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Types of State Management Server-Side State Management Client-Side State Management Management Application state Information is available to all users of a Web application Cookies Text file stores information to maintain state Session state Information is available only to a user of a specific session The ViewState property Retains values between multiple requests for the same page Database In some cases, use database support to maintain state on your Web site Query strings Information appended to the end of a URL
7
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Server-Side State Management Application state is a global storage mechanism accessible from all pages in the Web application Session state is limited to the current browser session Values are preserved through the use of application and session variables Scalability ASP.NET session is identified by the SessionID string Web Server Client Computer Application and Session variables SessionI D
8
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Client-Side State Management Uses cookies to maintain state Persistent cookies Temporary/ Non-persistent cookies Less reliable than server-side state management options User can delete cookies Less secure than server-side state management options Limited amount of information Client-side restrictions on file sizes Web Server Client Computer Cookie s
9
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 The Global.asax File Only one Global.asax file per Web application Stored in the virtual root of the Web application Used to handle application and session events The Global.asax file is optional
10
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 The Global.asax File (continued) ASP.NET Web Server Client ASP.NET HTTP Runtime IIS Application_BeginRequest Application_AuthenticateRequest Application_AuthorizeRequest Application_ResolveRequestCache Application_AquireRequestState Application_PreRequestHandlerExecute Application_EndRequest Application_UpdateRequestCache Application_ReleaseRequestState Application_PostRequestHandlerExecute Page execution Request Response
11
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Lesson: Application and Session Variables Initializing Application and Session Variables Using Application and Session Variables Demonstration: Using Session Variables Application and Session Variable Duration Scalable Storage of Application and Session Variables Saving Application and Session Variables in a Database
12
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Initializing Application and Session Variables Variables are initialized in Global.asax The Application object shares information among all users of a Web application The Session object stores information for a particular user session Sub Application_Start(s As Object,e As EventArgs) Application("NumberofVisitors") = 0 End Sub Sub Application_Start(s As Object,e As EventArgs) Application("NumberofVisitors") = 0 End Sub protected void Application_Start(Object sender,EventArgs e) { Application["NumberofVisitors"] = 0; } protected void Application_Start(Object sender,EventArgs e) { Application["NumberofVisitors"] = 0; }
13
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Using Application and Session Variables Set session and application variables Read session and application variables Session("BackColor") = "blue" Application.Lock() Application("NumberOfVisitors") += 1 Application.UnLock() Session("BackColor") = "blue" Application.Lock() Application("NumberOfVisitors") += 1 Application.UnLock() strBgColor = Session("BackColor") lblNbVisitor.Text = Application("NumberOfVisitors") strBgColor = Session("BackColor") lblNbVisitor.Text = Application("NumberOfVisitors") Session["BackColor"] = "blue"; Application.Lock(); Application["NumberOfVisitors"] = (int)Application["NumberOfVisitors"] + 1; Application.UnLock(); Session["BackColor"] = "blue"; Application.Lock(); Application["NumberOfVisitors"] = (int)Application["NumberOfVisitors"] + 1; Application.UnLock(); strBgColor = (string)Session["BackColor"]; lblNbVisitor.Text = Application["NumberOfVisitors"].ToString(); strBgColor = (string)Session["BackColor"]; lblNbVisitor.Text = Application["NumberOfVisitors"].ToString();
14
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Demonstration: Using Session Variables Initialize a session variable (a number) in global.asax Access the session variable from one page Access the session variable from another page and modify it Re-access the session variable from the first page
15
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Application and Session Variable Duration Session variables have a set duration after last access Default is 20 minutes Session duration can be changed in Web.config: Application variables persist until the Application_End event is fired
16
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Scalable Storage of Application and Session Variables By default, the session state is managed in process Disadvantage of in process storage: Not Scalable ASP.NET provides out of process storage of session state State can be stored in a SQL Server database or a state server Advantages of out of process storage: Scalable SQ L Session and Application variables Clien t Web farm Session and Application variables -Or- State server
17
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Saving Application and Session Variables in a Database Configure the session state in Web.config Mode is set to sqlserver or stateserver Then, configure the SQL server OSQL creates several stored procedures and temporary databases for storing the variables c:\> OSQL –S SQLServerName –E <InstallSqlState.sql 11 22
18
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Lesson: Cookies and Cookieless Sessions Using Cookies to Store Session Data Instructor-Led Practice: Using Variables and Cookies Retrieving Information from a Cookie Using Cookieless Sessions Setting Up Cookieless Sessions
19
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Using Cookies to Store Session Data Creating a cookie: Cookie contains information about the domain name HttpCookie objCookie = new HttpCookie("myCookie"); DateTime now = DateTime.Now; objCookie.Values.Add("Time", now.ToString()); objCookie.Values.Add("ForeColor", "White"); objCookie.Values.Add("BackColor", "Blue"); Response.Cookies.Add(objCookie); HttpCookie objCookie = new HttpCookie("myCookie"); DateTime now = DateTime.Now; objCookie.Values.Add("Time", now.ToString()); objCookie.Values.Add("ForeColor", "White"); objCookie.Values.Add("BackColor", "Blue"); Response.Cookies.Add(objCookie); HttpCookie objCookie = new HttpCookie("myCookie"); DateTime now = DateTime.Now; objCookie.Values.Add("Time", now.ToString()); objCookie.Values.Add("ForeColor", "White"); objCookie.Values.Add("BackColor", "Blue"); objCookie.Expires = now.AddHours(1); Response.Cookies.Add(objCookie); HttpCookie objCookie = new HttpCookie("myCookie"); DateTime now = DateTime.Now; objCookie.Values.Add("Time", now.ToString()); objCookie.Values.Add("ForeColor", "White"); objCookie.Values.Add("BackColor", "Blue"); objCookie.Expires = now.AddHours(1); Response.Cookies.Add(objCookie); To create a persistent cookie, specify the expiration time Set-Cookie: Username=John+Chen; path=/; domain=microsoft.com; Expires=Tuesday, 01-Feb-05 00.00.01 GMT Set-Cookie: Username=John+Chen; path=/; domain=microsoft.com; Expires=Tuesday, 01-Feb-05 00.00.01 GMT
20
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Instructor-Led Practice: Using Variables and Cookies Students will: See how the application and session variables, and persistent cookies, are used to store user information Time: 15 Minutes
21
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Retrieving Information from a Cookie Read the cookie Retrieve values from the cookie lblTime.Text = objCookie.Values("Time") lblTime.ForeColor = System.Drawing.Color.FromName _ (objCookie.Values("ForeColor")) lblTime.BackColor = System.Drawing.Color.FromName _ (objCookie.Values("BackColor")) lblTime.Text = objCookie.Values("Time") lblTime.ForeColor = System.Drawing.Color.FromName _ (objCookie.Values("ForeColor")) lblTime.BackColor = System.Drawing.Color.FromName _ (objCookie.Values("BackColor")) Dim objCookie As HttpCookie = Request.Cookies("myCookie") HttpCookie objCookie = Request.Cookies["myCookie"]; lblTime.Text = objCookie.Values["Time"]; lblTime.ForeColor = System.Drawing.Color.FromName (objCookie.Values["ForeColor"]); lblTime.BackColor = System.Drawing.Color.FromName (objCookie.Values["BackColor"]); lblTime.Text = objCookie.Values["Time"]; lblTime.ForeColor = System.Drawing.Color.FromName (objCookie.Values["ForeColor"]); lblTime.BackColor = System.Drawing.Color.FromName (objCookie.Values["BackColor"]);
22
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Using Cookieless Sessions Each active session is identified and tracked using session IDs Session IDs are communicated across client-server requests using an HTTP cookie or included in the URL Cookieless sessions Session ID information is encoded into URLs Cannot use absolute URLs Most browsers limit the URL size to 255 characters, which limits use of cookieless Session IDs http://server/(h44a1e55c0breu552yrecobl)/page.aspx
23
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Setting Up Cookieless Sessions Session state is configured in the section of Web.config Set cookieless = true
24
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Review State Management Application and Session Variables Cookies and Cookieless Sessions
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.