0% found this document useful (0 votes)
1 views

State Management ASP.NET

The document discusses the challenges of state management in web applications compared to traditional Windows applications, highlighting the need for scalable solutions due to multiple users and disconnected access patterns. It outlines various client-based and server-based state management options, such as View State, Cookies, and Session State, along with their advantages and disadvantages. Additionally, it covers criteria for selecting state management options and provides examples of implementation and security measures for View State.

Uploaded by

REHMAN ASHRAF
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

State Management ASP.NET

The document discusses the challenges of state management in web applications compared to traditional Windows applications, highlighting the need for scalable solutions due to multiple users and disconnected access patterns. It outlines various client-based and server-based state management options, such as View State, Cookies, and Session State, along with their advantages and disadvantages. Additionally, it covers criteria for selecting state management options and provides examples of implementation and security measures for View State.

Uploaded by

REHMAN ASHRAF
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

State Management

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.

• Various options to preserve changes for managing state.


– These state management options are either client based or server
based.

3
State Management Options

Client Based State Management Options


1. View State
2. Hidden Form Fields
3. Cookies
4. Query Strings
5. Cross Page Posting
Server Based State Management Options
5. Session State
6. Application State
4
Criteria for Selecting State Management Options
• How much information do you need to store?

• Does the client accept persistent or in-memory cookies?

• Do you want to store the information on the client or server?

• Is the information sensitive?

• What sorts of performance criteria do you have for your


application?

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

• Control.ViewState Property Web Control 2


• Page.ViewSate
• Instance of StateBag Collection Class Web Control 3

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

• Implement a simple program that uses viewstate to


store and retrieve counter value. Whenever Increment
button is clicked Counter should be incremented?
• If this page is accessed using different browser
windows or from more than one clients whether the
counter value would be same or different at different
time instants? Give reason for the observation?

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"%>

Or set the same attribute in a configuration file:

<configuration xmlns="http://schemas.microsoft.com/ .NetConfiguration/v2.0">


<system.web>
<pages 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.

Dim cust As New Customer("Marsala","Simons")


ViewState("CurrentCustomer")=cust

Remember, when using custom objects, you’ll need to cast your data
when you retrieve it from view state.

'Retrieve a customer from view state.

Dim cust As Customer


cust =CType(ViewState("CurrentCustomer"),Customer)

21
Hidden Form Fields

• A hidden field does not render visibly in the browser


• When a page is submitted to the server, the content of a
hidden field is sent in the HTTP Form collection.
• A hidden field acts as a repository for any page-specific
information that you would like to store directly in the page.
• HtmlHiddenControl
• Works with Post method only.

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

Dim Url As String


Url = "QueryStringRecipient.aspx?Item="
& lstItems.SelectedItem.Text
& "&Mode=" & chkDetails.Checked.ToString()
Response.Redirect(Url)

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)

If prevPage IsNot Nothing Then


'(Read some information from the previous page.)
End If
End Sub

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.

• When the browser requests a page, it sends the information in


the cookie along with the request information.
• The server can read the cookie and extract its value.

29
• The browser can only send the data back to the server that
originally created the cookie. (User security)

• Best for preference related information only.


– In most of these cases, identification is the issue rather than
authentication, so it is enough to merely store the user
name, account name, or a unique user ID.

– A typical use is to store a token (perhaps encrypted)


indicating that the user has already been authenticated in
your application.

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

You might also like