Presentation is loading. Please wait.

Presentation is loading. Please wait.

SESSION AND COOKIE MANAGEMENT IN.NET. Topics Covered Introduction to session management Ways of doing session management Creating and Handling cookies.

Similar presentations


Presentation on theme: "SESSION AND COOKIE MANAGEMENT IN.NET. Topics Covered Introduction to session management Ways of doing session management Creating and Handling cookies."— Presentation transcript:

1 SESSION AND COOKIE MANAGEMENT IN.NET

2 Topics Covered Introduction to session management Ways of doing session management Creating and Handling cookies Problems with User sessions Improved models and solutions Session state element References

3 Session Tracking 3 Personalization Personalization makes it possible for e-businesses to communicate effectively with their customers. Online shopping sites often store personal information for customers, tailoring notifications and special offers to their interests. Privacy A trade-off exists, however, between personalized e-business service and protection of privacy. Some consumers fear the possible adverse consequences if the info they provide to e-businesses is released or collected by tracking technologies.

4 Session management A session is defined as the period of time that a unique user interacts with a Web application. Programmatically, session state is nothing more than memory in the shape of a dictionary or hash table, e.g. key-value pairs, which can be set and read for the duration of a user's session

5 Session("Stocks") = "MSFT; VRSN; GE" On subsequent pages these values are read and the Web application has access to these values without the user re-entering them: ' Get Stocks, split string, etc. Dim StockString StockString = Session("Stocks")

6 Session Tracking 6 Recognizing Clients To provide personalized services to consumers, e-businesses must be able to recognize clients when they request information from a site. HTTP is a stateless protocol—it does not support persistent connections that would enable web servers to maintain state information between requests. Tracking individual clients, known as session tracking, can be achieved in a number of ways. – Using cookies. – Using ASP.NET’s HttpSessionState object. – Using “ hidden ” form elements. – Embedding session-tracking information directly in URLs.

7 Cookie-based Session Handling  To enable cookie-based session handling, make sure that web.config file of the web-application contains the following entry: Let’s say the browser makes a request to a server. This is the first request from the browser to the server. For e.g. for a request: http://localhost/WebApplication1/WebForm1.aspx The HTTP request header sent by the browser would be as shown below: 1. GET /WebApplication1/WebForm1.aspx HTTP/1.1 2. Accept: image/gif, image/x- xbitmap, image/jpeg, image/ pjpeg, application/vnd.ms-excel, application/vnd.ms- powerpoint, application/ msword, application/x-shockwave-flash, */* 3. Accept-Language: en-us 4. Accept-Encoding: gzip, deflate 5. User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Avant Browser [avantbrowser.com];.NET CLR 1.1.4322) 6. Host: localhost 7. Connection: Keep-Alive

8  The response send back by the server would consist of a HTTP response header and response body. The response header would look something like this: 1. HTTP/1.1 200 OK 2. Server: Microsoft-IIS/5.0 3. Date: Wed, 07 Jan 2004 09:31:07 GMT 4. X-Powered-By: ASP.NET 5. X- AspNet-Version: 1.1.4322 6. Set- Cookie: ASP.NET_SessionId=ll345q550ozqll45qithgi45; path=/ 7. Cache-Control: private 8. Content-Type: text/html; charset=utf-8 Content- Length: 540

9  If the browser clicks on a button of the first page to make a request to WebForm2.aspx, the request header sent would be: GET /WebApplication1/WebForm2.aspx HTTP/1.1 Accept: */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Avant Browser [avantbrowser.com];.NET CLR 1.1.4322) Host: localhost Connection: Keep-Alive Cookie: ASP.NET_SessionId= ll345q550ozqll45qithgi45

10  For cookie-less Session handling we need to set the ‘cookieless’ attribute to ‘true’ in web.config. The request header is as shown below. (Similar to earlier request header in cookie-based session handling) 1. GET /WebApplication1/WebForm1.aspx HTTP/1.1 2. Accept: image/gif, image/x- xbitmap, image/jpeg, image/ pjpeg, application/vnd.ms-excel, application/vnd.ms- powerpoint, application/ msword, application/x-shockwave-flash, */* 3. Accept-Language: en-us 4. Accept-Encoding: gzip, deflate 5. User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Avant Browser [avantbrowser.com];.NET CLR 1.1.4322) 6. Host: localhost 7. Connection: Keep-Alive

11 The response returned by the browser is as follows HTTP/1.1 302 Found Server: Microsoft-IIS/5.0 Date: Wed, 07 Jan 2004 10:25:25 GMT X-Powered-By: ASP.NET X- AspNet-Version: 1.1.4322 Location:/WebApplication1/(bcgmybvma1y45czof4me3sq4)/WebForm1.aspx Cache-Control: private Content-Type: text/html; charset=utf-8 Content-Length: 174 Object moved Object moved to her e.

12 The Request header it sends would be as shown below: GET /WebApplication1/(bcgmybvma1y45czof4me3sq4)/WebForm1.a spx HTTP/1.1 Accept: image/gif, image/x- xbitmap, image/jpeg, image/ pjpeg, application/vnd.ms-excel, application/vnd.ms- powerpoint, application/ msword, application/x-shockwave-flash, */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Avant Browser [avantbrowser.com];.NET CLR 1.1.4322) Host: localhost Connection: Keep-Alive

13 Cookies A Cookie is a small text file that the browser creates and stores on the hard drive of your machine. Cookie is just one or more pieces of information stored as text strings. The most common use of a cookie is to store information about the user and preferences the user makes.

14 Session Tracking - Cookies 14 Cookies are pieces of data stored in a small text file on the user’s computer. A cookie maintains information about the client during and between browser sessions. Every HTTP-based interaction between a client and a server includes a header containing information about the request or response. When a web server receives a request, the header includes any cookies that have been stored on the client machine by that server. When the server formulates its response, the header contains any cookies the server wants to store on the client computer.

15 Session Tracking - Cookies 15 The expiration date of a cookie determines how long the cookie remains on the client’s computer. If no expiration date is set, web browser maintains the cookie for the duration of the browsing session. Otherwise, the web browser maintains the cookie until the expiration date occurs. Cookies are deleted when they expire. Most browsers allow 20 cookies per server. The size of a cookie is not more than 4096 bytes or 4 KB. Portability Tip Users may disable cookies in their web browsers to help ensure their privacy. Such users will experience difficulty using web applications that depend on cookies to maintain state information.

16 Example using Cookies Create Options.aspx file with: 1.A Label "Select a programming language:" 2.5 radio buttons with the values Visual Basic, Visual C#, C, C++, and Java. 3.A Submit button 4.A Hyperlink that navigates to "~/Options.aspx“ 5.A Hyperlink that navigates to "~/Recommendations.aspx“

17 Creation of a cookie  The System.Web namespace offers a class called HttpCookie to create cookies. Private Sub Select_Click(By Val sender As System.Object, By Val e As_ System.EventArgs) Handles Select.Click Dim newCookie As HttpCookie = New HttpCookie("Books") newCookie.Values.Add("Name", TextBox1.Text) newCookie.Values.Add("FavBook", RadioButtonList1.SelectedItem.Text) newCookie.Expires = #12/31/2008# Response.Cookies.Add(newCookie) Label3.Text = "Cookie Created" Select.Visible = False TextBox1.Visible = False Label1.Visible = False Label2.Visible = False RadioButtonList1.Visible = False End Sub

18 Retrieving the cookie  Private Sub Retrieve_Click(By Val sender As System.Object, By Val e As_ System.EventArgs) Handles Retrieve.Click Label3.visible=False Label4.Text = "Hello" &" "& Request.Cookies("Books")("Name") & "."&_ "We have a new book for you:" If Request.Cookies("Books")("FavBook") = "VB" Then Label5.text="XYZ VB Book" ElseIf Request.Cookies("Books")("FavBook") = "C#" Then Label5.text="ABC C# Book" Else Label5.text="Startvbdotnet.com's ASP Book" End If End Sub

19 Enter your Name Select your interest VB C# ASP Cookie details Hello Username. We have a new book for you: XYZ VB Book

20  HttpCookie aCookie = new HttpCookie("Mycookie"); aCookie.Values["userName"] = “user name"; aCookie.Values["lastVisit"] = DateTime.Now.ToString(); aCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(aCookie);  The cookie that will be created with the code will be in the form of "administrator@www.startvbdotnet[1].txt" and it can be found in C:\Documents and Settings\Administrator\Cookies.

21 Problems with ASP Session State These limitations include: Process dependent. Server farm limitations. Cookie dependent.

22 Problems with user sessions in Asp  The stateless nature of HTTP makes the inclusion of a mechanism to save application state between user requests a must—the server must be able to identify the same user across multiple requests.  First, the 120-bit session ID used to identify the session is always stored as a cookie on the browser. So, if the security policy of a user's employer disallows cookies, the Session object cannot be populated.  Second, the data associated with the session and accessed through the session ID is stored on the Web server that processed the initial request and started the session. As a result, the session data can’t be shared in a web farm scenario where multiple web servers are processing requests from multiple clients.

23 Solutions ASP.NET session state solves all of the above problems associated with classic ASP session state: Process independent Support for server farm configurations. Cookie independent.

24 Improved models and solutions  The ASP.NET session implementation addresses both of these weaknesses by allowing for "cookieless" sessions and off-server storage of session data. The ASP.NET session state module is configured declaratively in the Web.config file like so: In this case, the mode attribute is set to InProc (the default) to indicate that the session state is stored in memory by ASP.NET and that cookies will not be used to pass the session ID. Instead, the session ID is inserted into the query string for a page’s URL.

25 For example, using InProc mode, after a session is established, a call to a hypothetical ASP.NET page would look something like the following: http://my.website.com/(55mfgh55vgblurtywsityvj q)/education.aspx ASP.NET offers three session management solutions. They are: InProcess, StateServer (outProcess), SQLServer (database based)

26  InProc: This is same as the conventional ASP session management. Session is stored in memory on the web server.  StateServer session management By setting the mode attribute to StateServer, is storing session data in a separate in-memory cache controlled by a Windows service running on a separate machine. The state service, called the ASP.NET State Service (aspnet_state.exe), is configured by the stateConnectionString attribute in the Web.config file. It specifies the service’s server and the port it monitors: using the state service has the advantages of process isolation and sharability across a web farm.

27  Session management with SQL Server In this case, ASP.NET attempts to store session data on the SQL Server specified by a sqlConnectionString attribute that would contain the data source and security credentials necessary to log on to the server. To configure the SQL Server with the appropriate database objects, an administrator would also need to create the ASPState database by running the InstallState.sql script found in the WinDir\ Microsoft.Net\Framework\Version folder (where WinDir is the name of your server’s Windows folder and Version is the installation folder for the appropriate version of the.NET Framework you’re using). osql –S localhost –U sa –P –i Installsqlstate.sql ( cmd prompt) Once the SQL Server is configured, the application code should run identically to the InProc mode.  By storing session state in the database, you’re effectively trading performance for scalability and reliability.

28  To use StateServer mode  Make sure ASP.NET state service is running on the remote server that will store session state information. This service is installed with ASP.NET and is located by default at :\systemroot\Microsoft.NET\Framework\version\aspnet_s tate.exe.  In the application's Web.config file, set mode=StateServer and set the stateConnectionString attribute. For example, stateConnectionString="tcpip=dataserver:42424".  To use SQLServer mode  Run InstallSqlState.sql (installed by default in :\systemroot\Microsoft.NET\Framework\version) on the computer running SQL Server that will store the session state. This creates a database called ASPState with new stored procedures and ASPStateTempApplications and ASPStateTempSessions tables in the TempDB database.  In the application's Web.config file, set mode=SQLServer and set the sqlConnectionString attribute. For example, sqlConnectionString="data source=localhost; Integrated Security=SSPI; Initial Catalog= northwind".

29 InProc - stored in memory on web server This is the default setting. – Pros: least overhead, fastest performance – Cons: breaks web clusters, restarting IIS loses sessions StateServer - managed by a remote service (aspnet_state) HTTP protocol over TCP port. – Pros: reasonably fast, works with clusters – Cons: clear text, no authentication, overflows... SQLServer - stored in SQL Server DB tables Uses normal ODBC connection. – Pros: reliable, scalable – Cons: relatively slow, much overhead

30 Session state element

31 References  http://msdn2.microsoft.com/en- us/library/ms972429.aspx  http://www.codeproject.com/Purgatory/SessionManag ementAspNet.asp  http://www.codeproject.com/aspnet/ASPNETSession. asp  http://msdn2.microsoft.com/en- us/library/h6bb9cz9(vs.71).aspx  http://www.startvbdotnet.com/aspsite/forms/cookies.a spx  http://msdn2.microsoft.com/en- us/library/ms178194.aspx


Download ppt "SESSION AND COOKIE MANAGEMENT IN.NET. Topics Covered Introduction to session management Ways of doing session management Creating and Handling cookies."

Similar presentations


Ads by Google