//
you're reading...
ASP.NET

Hour 1: Understanding 5 ASP.NET State management techniques in 5 hours

What is State management: HTTP is stateless and no matter how advance application framework is, it will always remain stateless. Which is after every web request, client get disconnected from the server and all the page objects get discarded. So there should be some technique which could store information between web requests and retrieve it when it is required.

What techniques are available in ASP.NET (most popular one)

ViewState Query String Custom Cookies Session State Application State
Data types supported All.NET
data types which are serializable
Part of string data. String data. All.NET data types which are serializable. Nonserializable types are also supported in some cases. All .NET data types.
Storage location A hidden field in the
current web page.
The browser’s URL string. The client’s computer (in memory or a small text file, depending on its lifetime settings). Server memory
or a dedicated database,
depending on the mode
Server memory.
Lifetime Retained permanently
for postbacks
to a single page.
Lost when the user
enters a new URL or
closes the browser.
However, can be
stored and can persist
between visits.
Set by the
programmer. It can be
used in multiple pages
and it persists
between visits.
Times out after a predefined
period (usually 20 minutes
but can be altered globally or
programmatically).
The lifetime of the application
(typically, until the server
is rebooted).
Scope Limited to the
current page.
Limited to the
target page.
The whole ASP.NET
application.
The whole ASP.NET
application.
The whole ASP.NET application.
Unlike most other types
of methods, application data
is global to all users.
Security Tamper-proof by
default but easy to
read. You can use the
Page directive to
enforce encryption.
Clearly visible and
easy for the user to
modify.
Insecure and can be modified by the user Secure, because data is never
transmitted to the client.
However, subject to session
hijacking if you don’t use SSL.
Very secure, because data
is never transmitted to the
client.
Performance 

Storing a large
amount of information
will slow
transmission but
will not affect server
performance.
None, because the
amount of data is
trivial.
None, because the
amount of data is
trivial.
Storing a large amount of
information can slow down
the server severely, especially
if there are a large number of
users at once, because each
user will have a separate set of
session data.
Storing a large amount of
information can slow down
the server, because this data
will never time out and be
removed.
Mostly used areas Page-specific
settings.
Sending a product ID
from a catalog page
to a details page.
Personalization preferences
for a website.
Store items in a shopping
basket.
Storing any type of global data.

What are client side state management techniques?

1) Cookies,

2) Query Strings (URL),

3) Hidden fields,

4) View State and Control state

What client side state management mean? When your user clicks on an URL or button or server side control, the information goes from your page to the server and then back again to the user’s web browser. How do you remember the information that is currently on the page. These are the techniques to save the information on the client side and not the server side.

What are Server side state management techniques?

1) Session State,

2) Application  State,

3) Profiles

4) Caching

What server side state management mean? Server-side option for storing page information tends to have security than client-side options, but they can use more web server resources, which may lead to scalability issues when the size of the information store is large.

What is important to keep in mind while choosing right state management?

1)    data need to store,

2)     the length of time need to store it,

3)    the scope of data (whether it’s limited to individual users or shared across multiple requests),

4)    Additional security and performance considerations.

Note: Although it depend but we will almost always use a combination of them in the same web application (and often the same page).

HOUR ONE: View State:

Points to remember

1)    View state is used natively by the ASP.NET web controls. It allows them to retain their properties between postbacks.

2)    ViewState is page’s built in property for storing our own custom data in view state collection

3)    View state uses dictionary collection is way

4)    How to store:

ViewState[“Counter”] = 1;

5)    How to retrieve:

int counter;

if (ViewState[“Counter”] != null)

{

counter = (int)ViewState[“Counter”];

}

Scenario 1: Storing and Retrieving control data in View State

Step 1: we will create a customer input form, like below

Step 2: On Save: Here on save click we will save all the control’s data into view state.

protected void cmdSave_Click(object sender, EventArgs e)

{

// Save the current text.

SaveAllText(Page.Controls, true);

}

private void SaveAllText(ControlCollection controls, bool saveNested)

{

foreach (Control control in controls)

{

if (control is TextBox)

{

// Store the text using the unique control ID.

ViewState[control.ID] = ((TextBox)control).Text;

//Clear text from controls

((TextBox)control).Text = “”;

}

if ((control.Controls != null) && saveNested)

{

SaveAllText(control.Controls, true);

}

}

}

Step 3: On Restore click, retrieve all data from view state:

protected void cmdRestore_Click(object sender, EventArgs e)

{

// Retrieve the last saved text.

RestoreAllText(Page.Controls, true);

}

private void RestoreAllText(ControlCollection controls, bool saveNested)

{

foreach (Control control in controls)

{

if (control is TextBox)

{

if (ViewState[control.ID] != null)

((TextBox)control).Text = (string)ViewState[control.ID];

}

if ((control.Controls != null) && saveNested)

{

RestoreAllText(control.Controls, true);

}

}

}

Scenario 2: Storing and Retrieving own created custom objects in View State

Point to remember:

1) We can store our own object in view state like numeric and string types.

2)    ASP.NET converts these objects into stream of bytes so that they can be added into hidden input fields in the page. This is called Serialization

3)    To make our object serializable, we need to add a Serializable attribute before class.

Step 1: Create a class with Serializable attribute.

[Serializable]

public class User

{

public string FirstName;

public string LastName;

public User(string firstName, string lastName)

{

FirstName = firstName;

LastName = lastName;

}

}

Step 2: After this we can store information in view state.

// Store a customer in view state.

User user = new User(“Vishal”, “Nayan”);

ViewState[“CurrentUser”] = user;

Step3: When we want to retrieve , we will need to cast this;

// Retrieve a customer from view state.

User user;

user = (User)ViewState[“CurrentUser”];

Step 4: Its important and mandatory that all member variables of the class must use serializable data types. Any nonserializable data type must be decorated with the NonSerialized attribute (which means it is simply ignored during the serialization process).

Step 5: if the Serializable attribute isn’t present, the object isn’t serializable, and you won’t be able to store it in view state.

Why not to user View State.

View state is ideal because it doesn’t take up any memory on the server and doesn’t restrict any arbitrary usage limits (such as a time-out).

1) Any important data should be not stored in view state, because hackers can access and modify that information when page is posted back.

2) In case we need to share data with multiple pages, view state cannot be used.

3) When we need to store large amount of data  , avoid View state

How to see View State Value for page;

Step 1: Enable trace to see the value;

<%@ Page Language=”C#” Trace=”true” AutoEventWireup=”true” CodeFile=”ViewState.aspx.cs” Inherits=”ViewState” %>

How to secure View State

Hashing: A hash code is a cryptographically strong checksum.

How it work: When the page is posted back, ASP.NET recalculates the checksum and ensures that it

Matches. If a malicious user changes the view state data, ASP.NET will be able to detect the change,

And it will reject the postback.

Status: enabled by default

How to disable it: <%@ Page Language=”C#” EnableViewStateMac=”false”

OR

Change setting in web.config

<system.web>

<pages enableViewStateMac=”false” />

Encryption: prevent users from getting any view state information

Status: Auto by default.

How to enable it: <%@ Page Language=”C#” ViewStateEncryptionMode=”Always”

This is end of your 1st hour of reading .Hope you enjoyed it.Click to go on 2nd hour of reading

Advertisements

About Vishal

Vishal Nayan is a seasoned professional with hand on Experience on Mircrosoft Technologies. He always look for challenging IT position that allows him to learn new Microsoft Technologies while utilizing experience of Project Development and Software Engineering Ethics. A MCP in WCF ,and looking forward for more.

Discussion

One thought on “Hour 1: Understanding 5 ASP.NET State management techniques in 5 hours

  1. Thanks good work…

    Posted by Able | 2012/08/24, 2:16 PM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow Vishalnayan on WordPress.com

Blog Stats

  • 208,756 hits
%d bloggers like this: