State Management ASP.NET
State Management ASP.NET
1
Problem of State Management
• Traditional Windows Application
– State is managed automatically and transparently.
– Memory is plentiful; a portion of memory is allocated to
store state information.
• Web Application
– Thousands of users run application on same computer
(server)
– Scalable solutions are required
• May include more than one servers
– web farm, web garden,…
• Disconnected access pattern
– resource and speed efficient
2
• Web pages are recreated each time the page is posted
back to the server.
– All information associated with the page and contained
controls would be lost with each round trip.
– If a user enters information into a textbox, that
information would be lost in the round trip.
3
State Management Options
5
View State
• When the page is processed, the
current state of the page and controls
Web Page Code
is hashed into a string and saved in the
page as a hidden field.
• When the page is posted back to the
Viewstate
server, the page parses the view state
string at page initialization and
restores property information in the
page. Web Control 1
6
Advantages
• The view state is contained in a structure within the page code.
No server resources required.
• Simple implementation.
• Automatic retention of page and control state.
• Enhanced security features. The values in view state are hashed,
compressed, and encoded for Unicode implementations, thus
representing a higher state of security than hidden fields have.
Disadvantages
• Performance: Storing large values can cause the page to slow down
when users display it and when they post it.
• Security: Although view state stores data in a hashed format, it can
be tampered with.
• Tightly bound to a page.
7
• What type of information can be stored in
ViewState?
8
Example
9
Viewstate Example 2: 3
10
UI
1. A form
2. A multiline textbox
3. A save button
4. A load button
11
Pseudocode
• Import namespaces and inherit custom page class
• Add members variables; TextBox and twoButtons
• A member variable that ordinarily will be cleared with every postback.
Private Contents As String*
• Restore variables in Page_Load Event during each postback.
If Me.IsPostBack = True Then
Contents = CType(Me.ViewState("Text"), String)
End If
• Persist variables in Page_PreRender Event.
Me.ViewState("Text") = Contents
• cmdSave_Click=>Transfer contents of text box to member variable.
Contents = txtValue.Text
txtValue.Text = ""
• cmdLoad_Click=> Restore contents of member variable to text box.
txtValue.Text = Contents
12
*white lines show code statements
Securing ViewState
• <input type="hidden“ name="__VIEWSTATE“
value="dDw3NDg2NTI5MDg7Oz4="/>
• Because this value isn’t formatted as clear text, many
ASP.NET programmers assume that their view state data
is encrypted.
• Base64 string
• For securing VIEWSTATE there are two options:
– Hashing
– Encryption
13
Hash Codes
• A hash code is sometimes described as a
cryptographically strong checksum.
• ASP.NET examines all the data in your view state and
runs it through a hashing algorithm (with the help of a
secret key value).
• The hashing algorithm creates a short segment of data,
which is the hash code.
• This code is then added at the end of the view state
data.
14
• When the page is posted back, ASP.NET
examines the view state data and recalculates the
hash code using the same process.
• It then checks whether the checksum it calculated
matches the hash code that is stored in the view
state for the page.
• If a malicious user changes part of the view state
data, ASP.NET will end up with a new hash code
that doesn’t match.
15
• Occasionally, developers choose to disable this
feature to prevent problems in a web farm where
different servers have different keys.
<system.web>
<pages enableViewStateMac="false"/>
...
16
ViewState Encryption
• Three choices for view state encryption setting
– always encrypt (Always)
– never encrypt (Never)
– or encrypt only if a control specifically requests
it (Auto).
17
<%@Page ViewStateEncryptionMode="Always"%>
18
Storing Custom Objects
• You can store your own objects in view state just
as easily as you store numeric and string types.
• However, to store an item in view state, ASP.NET
must be able to convert it into a stream of bytes so
that it can be added to the hidden input field in the
page. This process is called serialization.
• If your objects aren’t serializable (and by default
they’re not), you’ll receive an error message when
you attempt to place them in view state.
19
Serializable
<Serializable( )>_
Public Class Customer
Public FirstName As String
Public LastName As String
Public Sub New(ByVal firstName As String,ByVal lastName As
String)
Me.FirstName =firstName
Me.LastName =lastName
End Sub
End Class
20
'Store a customer in view state.
Remember, when using custom objects, you’ll need to cast your data
when you retrieve it from view state.
21
Hidden Form Fields
22
Pros and Cons of Using Hidden Fields
Advantages
• No server resources are required.
• Broad support. Almost all browsers and client devices support
forms with hidden fields.
• Simple implementation.
Disadvantages
• Security. The hidden field can be tampered with.
• Limited storage structure.
• Performance. storing large values can cause the page to slow
down.
23
Query Strings
• Search engines
• Database applications
• E-commerce applications
• Query string is the portion after the URL.
24
Using Query Strings
ViewInformation_Click Event
Request.QueryString("Item")
Request.QueryString("Mode") 25
The advantages of using query strings are:
• No server resources required.
• Broad support. Almost all browsers and client devices support
passing values in a query string.
• Simple implementation.
• Light weight.
• Specially used in some database applications due to ease of use.
The disadvantages of using query strings are:
• Security.
– query string is directly visible to the user via the browser user interface.
– The query values are exposed to the Internet via the URL so in some cases
security may be an issue.
• Limited capacity.
– Most browsers and client devices impose a 255-character limit on URL
length.
• Url legal characters
• Can be used with Get method only
26
Cross Page Posting
• A newer approach
• Tightly coupled pages (difficult to enhance, debug)
• Example:
– P1, P2, P3
• PostBackUrl
– <asp:Button runat=“server” id=“cmdPost”
PostBackUrl=“CrossPage2.aspx Text=“CrossPage
PostBack” />
• Page.PreviousPage property
27
• TryCast
• Protected members
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
EventArgs) Handles Me.Load
Dim prevPage As CrossPage1
prevPage =TryCast(PreviousPage,CrossPage1)
28
Cookies
• A cookie is a small amount of data stored either in a text file
on the client's file system or in-memory in the client browser
session.
• It contains page-specific information the server sends to the
client along with page output.
• Cookies can be temporary (with specific expiration time and
date) or persistent.
29
• The browser can only send the data back to the server that
originally created the cookie. (User security)
30
More than one
values can be
stored in a cookie
31
Cookies: Pros and Cons
Advantages
• The cookie is stored transparently on the client.
• Long term storage
• Simplicity
– lightweight, text-based structure with simple key-value pairs.
• Configurable expiration.
Disadvantages
• Limited size string information.
– 4096/8192-byte size (browser limit)
• User-configured refusal.
– App failure
– user intervention
• Security
• Durability
32
• Embedded browsers
• First time no cookie is found.
• Cookie is created.
• Browser is closed, and reopened.
• A cookie is found this time.
33
d.
e
at
cre
i s
e
o ki
Co
34
Ne
ac x t
m ces tim
c r a c h se d e w
se eate ine fro he
co nt t d c , th m n p
ok o t oo e p the ag
i es h e k i r e s e i
co ser e is vio ame s
lle ve fo us
cti r i un ly
on n t d.
. h e It
is
35
36
References
State Management
Chapter 8 Textbook
37