state management. what is state management why state management viewstate querystring cookies
TRANSCRIPT
State Management
What is State management Why State management ViewState QueryString Cookies
State management
In a window program the user interacts with the continuously running application
A portion of memory on the desktop computer is allocated to store the current set of working information
In Web application the story is different
A professional ASP.NET site might look like a continuously running application
Web application uses a disconnected access pattern
Why State Management-Disconnected access pattern
Client Web Server
Connect & request a page
Response & info abandoned
Web servers discard the client information
Web Application handles of thousands of requests
Web Server
Client 1
Client 2
Client 3
Client 4
Client 5
Client 6
The clients can be connected to the web server only for a few seconds
Web server needs to serve thousands of request To retain the working information the user needs to
take special measure
Viewstate QueryString Cookies
Viewstate
It allows the controls to retain their state Viewstate information is stored in the hidden field The hidden field holds the information in a crazy
string format that is non-readable and it changes dynamically everytime the informations in the control is changed
It is the first option for state management
ViewState Example :Counter
Dim count As Integer If Me.ViewState("count") = Nothing Then count = 1 Else count = CType(Me.ViewState("count"), Integer) + 1
End If Me.ViewState("count") = count Label1.Text = count.ToString()
Transferring information
One of the limitations of the viewstate is that it is tightly bound to a page
Page navigation makes the data to get lost One common approach that we use is to pass
information using the query string Used in search engines
http://www.askjeeves.com/main/askjeeves.asp?ask=organic
QueryString
The querystring is a portion of the URL followed after the ?
In the above example, it defines a single variable named ask which contains the string “organic”
It is a useful technique in the database applications where you present a list of details that correspond to records in the db
QueryString
The user can select an item and be forwarded to a detailed information page
This page can receive the unique ID that identifies the record from the sending page and look up for information from the db
Example Amazon site
Response.redirect(“newpage.aspx?recordID=10”)
Querystring example
Querystring example
if (ListBox1.SelectedIndex == -1) { Label1.Text = "U must select a item"; } else { string qs = "Default.aspx?"; qs += "Item=" + ListBox1.SelectedItem.Text; Response.Redirect(qs); }
QueryString
The new page can receive the values from the querystring with Request object
Dim ID as String=Request.QuerySting(“recordID”)
QueryString limitation
Information is limited to simple string; which contain legal URL characters
Information is clearly visible to the user (eavesdrop) Less security over the Internet Browsers impose restriction on the length of the
Querystring,hence a large string cannot be placed
Cookies
Custom cookies provide another way that you can store information
Cookies are small files that are stored on the hard drive
Cookies work transparently (ie) without the user being aware that information are stored
Long term storage
Drawbacks
Suffer with the limitation of the string length Information's are easily readable by the user and less
security
Using Cookies
Use the namespace Using System.Net Both the Request and Response objects provide the
cookie collection The cookies are retrieved from the Request object and
cookies are set using the Response object To set a cookie just create System.Net.HttpCookie
object
Creating cookies
Set a value in it
Add it to the cookies collection
Cookie=new HttpCookie(Preferences”)
Cookie(“LanguagePref”)=English
Response.cookies.add(Cookie)
Setting the expiry time for cookies A cookie normally persists until the user closes the
browser and will be sent with the request.To create a long lived cookie set the expiry date
This cookie lives for 1 year
Cookie.Expires =DateTime.Now.AddYears(1)
Check for the existence of cookies
Private Sub Page_Load(sender as Object,e as EventArgs){dim cookie As HttpCookie =Request.Cookies(“Preferences”)if cookie Is Nothing ThenLabelWelcome.Text=”Unkown Customer”elseLabelWelcomet.Text=”Cookie found”LabelWelcome.Text=”Cookie found,” & Cookie(“Name”)End IfEnd Sub
Cookies storing and retrieving
Private sub cmdstore_Click(sender as object,e as EventArgs)Dim cookie as HttpCookie=Request.Cookies(“Preferences”)If cookie is Nothing ThenCookie=new HttpCookie(“Preferences”)End If
Cookie(“Name”)=TextName.TextCookie.Expires=DateTime.AddYears(1)Response.Cookies.Add(Cookie)LabelWelcome.Text=”New customer” & Cookie(“Name”)
Session State
Application need to access complex information such as Datasets which cannot be persisted by Querystring or cookies
In these situations we use the ASP.NET built in facility Session state facility
It is one of the premiere feature It allows you to store any type of data on the server
Session State
The information is protected with a unique session.
Every client who access the application is created with a unique session
Session tracking
ASP.NET tracks each session using a 120 bit identifier.
It uses a special algorithm to track the value No hackers can guess the session ID This ID is the piece of information transferred
between the client and the server
Session Information I
Session IDSession Information II
Session ID
User presents the Session-ID
Matches the Session ID and
Returns the Session information
Session State -Storing values in Session State
Syntax
Session(“Session variable”) =Datasource
Example
Session(“ds)=dsinfo
Session State -Retrieving values from Session
Syntax
Temporary variable =Ctype(Session(“Session Variable”),DataSet)
Example
ds=CType(Session(“ds”),DataSet)
How can Session State be lost
If the user closes the browser If the session is timed out If the programmer ends the session in the
program If the user access the same page through
different browser
Example
Restrict only the signed in users to enter the appropriate page
Session State configuration
Session State is configured through Web.config file in the ASP.NET
It allows to set most of the options such as Session State mode and timeout ..
CookieLess
You can set the cookieless setting to true or false <sessionState>
cookieless=”false” </sessionState>
Session State
When set to true,the session ID will automatically be inserted into the URL
ASP.NET on receiving the request it collects the session information
Timeout
Another Session State settings in the web.config file is timeout
It specifes the number of minutes that ASP.NET will wait,without receiving the Request,before it discards the session
<SessionState> timout=”20” </SessionState>
Mode Off: this setting disables state management for
every Page in the application StateServer:Separate windows service outside
ASP.NET Set manual setting to start on and off
SqlServer:It stores the session information in the databases available in the SQL Server
Application State
It stores global objects that can be used by any client
A common example is the global counter that tracks how many times an operation has been performed by all clients
Global counter
Protected Sub Page_Load(sender as Object,e as EventArgs)Application .Lock( )Dim count as Integer =CType(Application(“Hit”,Integer))Count+=1Application(“Hit”)=countApplication.Unlock( )Label1.text=Count.ToString( )End Sub