Friday, June 10, 2011

ASP.NET State Management

Application - Stored on the server and shared for all users. Does not expire.  Deprecated by Cache (below).
Cache - Stored on the server and shared for all users. Can expire.
Session - Stored on the server.  Unique for each user.  Can expire.
ViewState - Stored in a hidden page input (by default).  Does not expire.
Cookies - Stored at the client. Can expire.
QueryString - Passed in the URL.  Must be maintained with each request.
Profile - Stores the data in the database. Can be used to retain user data over multiple request and session.

View State :

Advantages of using view state are:

No server resources are required   The view state is contained in a structure within the page code.

Simple implementation   View state does not require any custom programming to use. It is on by default to maintain state data on controls.

Enhanced security features   The values in view state are hashed, compressed, and encoded for Unicode implementations, which provides more security than using hidden fields.

Disadvantages of using view state are:

Performance considerations   Because the view state is stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it. This is especially relevant for mobile devices, where bandwidth is often a limitation.

Device limitations   Mobile devices might not have the memory capacity to store a large amount of view-state data.

Potential security risks   The view state is stored in one or more hidden fields on the page. Although view state stores data in a hashed format, it can still be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue. For more information, see ASP.NET Web Application Security and Basic Security Practices for Web Applications.

Control State : 

Advantages of using control state are:

No server resources are required   By default, control state is stored in hidden fields on the page.

Reliability   Because control state cannot be turned off like view state, control state is a more reliable method for managing the state of controls.

Versatility   Custom adapters can be written to control how and where control-state data is stored.

Disadvantage of using control state are:

Some programming is required   While the ASP.NET page framework provides a foundation for control state, control state is a custom state-persistence mechanism. To fully utilize control state, you must write code to save and load control state.

Hidden Fields :

You can store page-specific information in a hidden field on your page as a way of maintaining the state of your page.

If you use hidden fields, it is best to store only small amounts of frequently changed data on the client.

Cookies : 

Cookies are useful for storing small amounts of frequently changed information on the client.
Advantages of using cookies are:

Configurable expiration rules   The cookie can expire when the browser session ends, or it can exist indefinitely on the client computer, subject to the expiration rules on the client.

No server resources are required   The cookie is stored on the client and read by the server after a post.

Simplicity   The cookie is a lightweight, text-based structure with simple key-value pairs.

Data persistence   Although the durability of the cookie on a client computer is subject to cookie expiration processes on the client and user intervention, cookies are generally the most durable form of data persistence on the client.

Disadvantages of using cookies are:

Size limitations   Most browsers place a 4096-byte limit on the size of a cookie, although support for 8192-byte cookies is becoming more common in newer browser and client-device versions.

User-configured refusal   Some users disable their browser or client device's ability to receive cookies, thereby limiting this functionality.

Potential security risks   Cookies are subject to tampering. Users can manipulate cookies on their computer, which can potentially cause a security risk or cause the application that is dependent on the cookie to fail. Also, although cookies are only accessible by the domain that sent them to the client, hackers have historically found ways to access cookies from other domains on a user's computer. You can manually encrypt and decrypt cookies, but it requires extra coding and can affect application performance because of the time that is required for encryption and decryption.

Query Strings : 

Advantages of using query strings are:

No server resources are required   The query string is contained in the HTTP request for a specific URL.

Widespread support   Almost all browsers and client devices support using query strings to pass values.

Simple implementation   ASP.NET provides full support for the query-string method, including methods of reading query strings using the Params property of the HttpRequest object.

Disadvantages of using query strings are:

Potential security risks   The information in the query string is directly visible to the user via the browser's user interface. A user can bookmark the URL or send the URL to other users, thereby passing the information in the query string along with it. If you are concerned about any sensitive data in the query string, consider using hidden fields in a form that uses POST instead of using query strings. For more information, see ASP.NET Web Application Security and Basic Security Practices for Web Applications.

Limited capacity   Some browsers and client devices impose a 2083-character limit on the length of URLs.


State management optionRecommended usage
View stateUse when you need to store small amounts of information for a page that will post back to itself. Using the ViewState property provides functionality with basic security.
Control stateUse when you need to store small amounts of state information for a control between round trips to the server.
Hidden fieldsUse when you need to store small amounts of information for a page that will post back to itself or to another page, and when security is not an issue.
NoteNote
You can use a hidden field only on pages that are submitted to the server.
CookiesUse when you need to store small amounts of information on the client and security is not an issue.
Query stringUse when you are transferring small amounts of information from one page to another and security is not an issue.
NoteNote
You can use query strings only if you are requesting the same page, or another page via a link.



Application State:

Advantages of using application state are:

Simple implementation   Application state is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.

Application scope   Because application state is accessible to all pages in an application, storing information in application state can mean keeping only a single copy of the information (for instance, as opposed to keeping copies of information in session state or in individual pages).

Disadvantages of using application state are:

Application scope   The scope of application state can also be a disadvantage. Variables stored in application state are global only to the particular process the application is running in, and each application process can have different values. Therefore, you cannot rely on application state to store unique values or update global counters in Web-garden and Web-farm server configurations.

Limited durability of data   Because global data that is stored in application state is volatile, it will be lost if the Web server process containing it is destroyed, such as from a server crash, upgrade, or shutdown.

Resource requirements   Application state requires server memory, which can affect the performance of the server as well as the scalability of the application.

Session State :

Advantages of using session state are:

Simple implementation   The session-state facility is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.

Session-specific events   Session management events can be raised and used by your application.

Data persistence   Data placed in session-state variables can be preserved through Internet Information Services (IIS) restarts and worker-process restarts without losing session data because the data is stored in another process space. Additionally, session-state data can be persisted across multiple processes, such as in a Web farm or a Web garden.

Platform scalability   Session state can be used in both multi-computer and multi-process configurations, therefore optimizing scalability scenarios.

Cookieless support   Session state works with browsers that do not support HTTP cookies, although session state is most commonly used with cookies to provide user identification facilities to a Web application. Using session state without cookies, however, requires that the session identifier be placed in the query string, which is subject to the security issues stated in the query string section of this topic. For more information about using session state without cookies, see ASP.NET Web Site Administration.

Extensibility   You can customize and extend session state by writing your own session-state provider. Session state data can then be stored in a custom data format in a variety of data storage mechanisms, such as a database, an XML file, or even to a Web service. For more information, see Implementing a Session-State Store Provider.

Disadvantage of using session state are:

Performance considerations   Session-state variables stay in memory until they are either removed or replaced, and therefore can degrade server performance. Session-state variables that contain blocks of information, such as large datasets, can adversely affect Web-server performance as server load increases.

Profile Properties :

Advantages of using profile properties are:

Data persistence   Data placed in profile properties is preserved through IIS restarts and worker-process restarts without losing data because the data is stored in an external mechanism. Additionally, profile properties can be persisted across multiple processes, such as in a Web farm or a Web garden.

Platform scalability   Profile properties can be used in both multi-computer and multi-process configurations, therefore optimizing scalability scenarios.

Extensibility   In order to use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows you to store profile data in a SQL database, but you can also create your own profile provider class that stores profile data in a custom format and to a custom storage mechanism, such as an XML file, or even to a Web service. For more information, see ASP.NET Profile Providers and Implementing a Profile Provider.

Disadvantages of using profile properties are:

Performance considerations   Profile properties are generally slower than using session state because instead of storing data in memory, the data is persisted to a data store.

Additional configuration requirements   Unlike session state, the profile properties feature requires a considerable amount of configuration to use. To use profile properties, you must not only configure a profile provider, but you must pre-configure all of the profile properties that you want to store. For more information, see ASP.NET Profile Properties Overview and Defining ASP.NET Profile Properties.

Data maintenance   Profile properties require a certain amount of maintenance. Because profile data is persisted to non-volatile storage, you must make sure that your application calls the appropriate cleanup mechanisms, which are provided by the profile provider, when data becomes stale.

State management optionRecommended usage
Application stateUse when you are storing infrequently changed, global information that is used by many users, and security is not an issue. Do not store large quantities of information in application state.
Session stateUse when you are storing short-lived information that is specific to an individual session and security is an issue. Do not store large quantities of information in session state. Be aware that a session-state object will be created and maintained for the lifetime of every session in your application. In applications hosting many users, this can occupy significant server resources and affect scalability.
Profile propertiesUse when you are storing user-specific information that needs to be persisted after the user session is expired and needs to be retrieved again on subsequent visits to your application.
Database supportUse when you are storing large amounts of information, managing transactions, or the information must survive application and session restarts. Data mining is a concern, and security is an issue.

when and how to use viewstate,session,application,cookies,hidden from field

ViewState is a page level persistence and it happens only on same page where a viewstate persists page values. http://msdn2.microsoft.com/en-us/library/ms972976.aspx
Page level state is information maintained when an element on the web form page causes a subsequent request to the server for the same page – referred to as 'postback'. This is appropriately called ViewState as the data involved is usually, though not necessarily, shown to the user directly within the page output.
The Control.ViewState property is associated with each server control in your web form and provides a dictionary object for retaining values between such multiple requests for the same page. This is the method that the page uses to preserve page and control property values between round trips.
When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. When the page is posted back to the server, the page parses the view state string at page initialization and restores property information in the page.
ViewState is enabled by default so if you view a web form page in your browser you will see a line similar to the following near the form definition in your rendered HTML:

<input type="hidden" name="__VIEWSTATE"
value="dDwxNDg5OTk5MzM7Oz7DblWpxMjE3ATl4Jx621QnCmJ2VQ==" /> 

When a page is re-loaded two methods pertaining to ViewState are called: LoadViewState and SaveViewState. Page level state is maintained automatically by ASP.NET but you can disable it, as necessary, by setting the EnableViewState property to false for either the controls whose state doesn't need to be maintained or for the page as a whole. For the control:

<asp:TextBox id=”tbName” runat=”server” EnableViewState=”false” /> 

for the page:

<%@ Page EnableViewState=”false” %> 

You can validate that these work as claimed by analyzing the information presented if you turn on tracing for a page containing the above elements. You will see that on postback, and assuming ViewState is enabled, that the LoadViewState method is executed after the Init method of the Page class has been completed. SaveViewState is called after PreRender and prior to actual page rendering.
You can also explicitly save information in the ViewState using the State Bag dictionary collection, accessed as follows:

ViewState(key) = value 

Which can then be accessed as follows:

Value = ViewState(key) 

It is important to remember that page level state is only maintained between consecutive accesses to the same page. When you visit another page the information will not be accessible via the methods above.
Session
Sessions are used to persist information which you want to pass from page to page but in a unique user scope. What that means is that each user has a unique Session and hence may have unique values.
Usage of session Session["Key"] = value (where you can assign any key and value and retrieve those values based on the key) as string myval = (string)(Session["Key"])
Application
Application allows you to persist values that are global throughout the application. So for e.g. authentication may be a global function throughout application. An example is as follows in global.asax
Sub Application_Start()
    Dim ds As New DataSet()
    Dim fs As New FileStream(Server.MapPath("schemadata.xml"),FileMode.Open,FileAccess.Read)
    Dim reader As New StreamReader(fs)
    ds.ReadXml(reader)
    fs.Close()
    Dim view As New DataView (ds.Tables(0))
    Application("Source") = view
End Sub

function Application_Start() : void {
    var ds:DataSet = new DataSet();
    var fs:FileStream = new FileStream(Server.MapPath("schemadata.xml"),FileMode.Open,FileAccess.Read);
    var reader:StreamReader = new StreamReader(fs);
    ds.ReadXml(reader);
    fs.Close();
    var view:DataView = new DataView(ds.Tables[0]);
    Application("Source") = view;
}
CookiesClient side cookies are used to store volatile user preferences as followsProtected Sub Page_Load(sender As Object, e As EventArgs)
    If Request.Cookies("preferences1") = Null Then
        Dim cookie As New HttpCookie("preferences1")
        cookie.Values.Add("ForeColor", "black")
        ...
        Response.AppendCookie(cookie)
    End If
End Sub
protected function Page_Load(sender:Object, e:EventArgs) : void {
    if (Request.Cookies("preferences1") == null) {
        var cookie:HttpCookie = new HttpCookie("preferences1");
        cookie.Values.Add("ForeColor", "black");
        ...
        Response.AppendCookie(cookie);
    }
}
  Hidden field You also can store small amounts of information on the client by using hidden fields. Hidden fields are HTML elements, similar to text boxes, where you can store strings. Web browsers don'tdisplay hidden fields in page output. However, when you use a hidden field within an HTML form, the contents are submitted back to your program and can be used in your code behind. <input type="hidden" value="Value That You Need to Store" id="KeyName">  //Setting hidden field String strValue = Request.Params["KeyName"];      // retrieving the filed.
Read more here   http://msdn2.microsoft.com/en-us/library/z1hkazw7.aspx

Monday, June 6, 2011

A Beginner's Guide to ASP.NET Application Folders

Courtesy : http://www.codeproject.com/KB/aspnet/AspNetAppFolder.aspx


Table of Contents

Introduction

First of all I would like to thank Sean Ewington for his article Beginner's Walk - Web Development, which gives me a great opportunity to write an article for beginners on ASP.NET web development here on CodeProject. After writing articles on caching and view state for beginners, I have decided to write an article for beginners on the ASP.NET Application Folders. However, I will be back with another article on rest of state management. Like my other articles, I believe this will also give you very good idea on the Application Folders. Please give your valuable suggestions and ideas for improvement that I can incorporate into this article, as well as my future articles.

Overview - ASP.NET Application Folders

ASP.NET 2.0 uses a file-based approach. That means, all class files, resource files, data files and folders are maintained in a hierarchical structure. If we are working with ASP.NET 2.0, we can add files and folders using the Add Items option. If we look at a sample application hierarchy, it will look like the following figure.
beginn1.jpg
We can add as many as files and folders as we like (according to our requirements) within our solutions,and it won't be necessary to recompile them each and every time they are added. It is ASP.NET'stask to dynamically compile them when required. So, what ASP.NET 2.0 does is, it uses a predefined folder structure containing the files (classes, images, resources, etc.), to compile them dynamically and we can access those files throughout the application. ASP.NET also provides special folders to maintain files and resources. Let's see the advantages of using these folders.

Advantages of ASP.NET Application Folders

Following are the main advantages of use of ASP.NET's Application Folders
  • We can maintain resources (classes, images, code, databases, themes) in an organized manner, which allows us to develop and maintain sites easily
  • All files and folders are accessible through the application
  • We can add as many files as required
  • Files are compiled dynamically when required

Different Types of Application Folder

ASP.NET treats the following folders in a special manner. They are:
  • App_Code
  • Bin
  • App_Data
  • App_Theme
  • App_Browser
  • App_WebReference
  • App_LocalResource
  • App_GlobalResource

Details of the Application Folders

Now, to look at the use of these folders, I am going to start from App_Code.

App_Code Folder

As its name suggests, the App_Code Folder stores classes, typed data sets, etc. All the items that are stored inApp_Code are automatically accessible throughout the application. If we store any class files (like .cs or .vb) it compiles them automatically. It automatically creates type data sets from .xsd (XML schema) files, and creates XML web service proxy classes from WSDL.Let's have a look at how we can use the App_Code folder.
We can add an App_Code folder, by Solution File → right click → Add ASP.NET Folder → App_Code. The App_Codefolder is now added to your application.
beginn2.jpg
Note: Try to add one more App_Code folder by using the same steps. Oops... the App_Code folder is no longer available there. So, ASP.NET allows you to add an App_Code folder only once.
Now we can add new items like classes, text and xml files into the App_Code folder and we can also add existing files there.
beginn3.jpg
Let's have a look at one example that shows how it works. Into the App_Code folder, I have added a classMyCSharpClass.cs.
beginn4.jpg
In that class I have written a small spice of code for adding two numbers.
beginn5.jpg
Now, Try to access this class, from any where in your application. You will see that MyCSharpClassis accessiblethroughout the application.
beginn6.gif
If we want to store different classes like .cs or .vb, then what will happen? If we kept both .cs and .vb classes in the same folder, it will give following compilation error:
beginn7.jpg
This is because all the classes contained in the App_Code folder are built into a single assembly and it can't have different languages at root level, or even at child level folders in following manner:
beginn8.jpg
We have a solution to overcome this problem. We have to create separate folders for C# and for VB or other classes.
beginn10.jpg
Store class files separately in those folders and an configure the folder hierarchy in the web.config file.
beginn9_s.png
Now I will move to our next part -the Bin folder.

Bin Folder

The Bin folder is used for keeping assemblies inside it. We can access those as a reference from anywhere of our web application. Use of Bin folder comes into the picture if we use any class library within our web application. Suppose we are creating a class library called TestLib After building the library, we will get TestLib.dll. Now, right click on solution file → Add References → Project, select the TestLibProject, click on OK. Check the Bin folder, it will contain TestLib.dll and TestLib.pdb files.
beginn11.jpg
Assemblies in the Bin folder do not need to registered on the system, ASP.NET recognizes the presence of DLLs inside the Bin Folder. Keeping .pdb files inside Bin folder helps us in debugging. The main limitation of storing assemblies in the Bin folder is that their scope is limited to the current application. Therefore, they cannot access any code outside of current web application. [Source]
Next, let's have a look at App_Data folder

App_Data Folder

The App_Data folder is used as a ata storage for the web application. It can store files such as .mdf.mdb, and XML. It manages all of your application's data centrally. It is accessible from anywhere in your web application.The real advantage of the App_Data folder is that, any file you place there won't be downloadable.
We can add .mdf files to the App_Data folder directly by selecting Add New Item. From there we can a create table, procedure or function without opening SQL Server.Now if we want to add that data to our application, we can easily use it.
beginn12.jpg
Now, look at the connection string that we need to write for accessing the App_Data folder's databases.

beginn13.gif
We can connect with MyDB.mdf database using this connection string. Check the example below, which I have used to read the table data from the MyDB.Mdf file/p>
beginn14_s.png

App_Theme Folder

If you want to give your web sites a consistent look, then you need to design themes for your web application. TheApp_Themes folder contains all such themes. An App_Theme folder can contain two subfolders; one for CSS files and the other for skin files. When we add an App_Theme folder, a subfolder with name Theme1 will be automatically created. We can change the name of the theme folder as per our requirements.
beginn15.jpg
I will not cover how to create skin files or CSS file in this article, my main concern here is how to apply them. You can easily find the details ofskins and CSS via Google.
Now that we have to apply the theme to the page, there are several way to do that. We could set the theme fromaspx page using a page directive in following way:
beginn16.jpg
While we are going to set themefrom aspx page, the list of themes available to us is as shown in the figure. We can set the theme from the code behind file also, and we can even change theme at runtime (using HttpHandler.

App_Browser Folder

The App_Browser folder contains browser information files (.browser files). These files are XML based files which are used to identify the browser and browser capabilities. You will find the browser files in the following location:
beginn17.jpg
If you want to change a .browser file, just copy the file to the App_Browser folder and change it. You can create new browser files by just clicking on Add New Item of the App_Browser folder
beginn18.jpg
As I already mentioned, a browser file is a configuration file, it generally looks like this:
beginn19_s.png

App_WebReference Folder

As the name suggests, the App_WebReference folder contain references to any web services. If we added any web services with our web application, they go automatically into the App_WebReference folder, in the same way as in windows applications, if we added any DLLs, they would go under the Reference folder.
beginn20.jpg

Resources Folders

Before starting on the App_GlobalResource and App_LocalResource folders, I would like to give a small introduction on ASP.NET resources. If you are, say, creating sites for a multinational company, or a public web sites that can be accessible from all over the world, you need to consider the best way to address users in different cultures and different countries in different languages. ASP.NET provides the infrastructure to create web applications that automatically adjust formatting and language according to the user's preferences, by using resource files.The main purpose of resource files is localization of the web application.
ASP.NET uses resource files to make supporting multiple languages simpler. Visual Studio 2005 can automatically generate XML resource files that contain text for your controls in different languages. When a user visits the sites, they can change the languages of the sites based on their preference. There are two type of resources:
  • Local resources
  • Global resources
The App_LocalResource folder contain local resource files and the App_GlobalResource folder contains global resource files.

App_LocalResource Folder

Local resources are specific to a single web page, and should be used for providing multilingual functionalityon a web page.
Local resources must be stored in the App_LocalResource subfolder of the folder containing the web page. Because you might have local resources for every page in your web application, you might have App_LocalResource subfolders in every folder.
Resource file names should be like <pageName>[.langauge].resx. Some examples of local resource files are,Mypage.aspx.ex.resx and Mypage.aspx.de.resxDefault.aspx.resx is the base resource file to use if no other resource file matches with the user's current culture.
If you want to create local resources for a page, open the design view of the page and then from Tool Menu selectGenerate Local Resource. You will then see that a resource file is automatically created in the correspondingApp_LocalResource folder.
beginn21_s.png
Note: Default2.aspx.resx is the resource file for Default2.aspx, and Others.aspx.resx is the resource file forOthers.aspx. Both resource files are inside the App_LocalResource folder.
The following code shows you the XML code for the resource file. To change the resource file, we can either change the XMLdirectly or use the Resource Editor.
beginn22.gif
If we change anything on the page, the resource file will be automatically updated. If you want a test application for Local_Resource, just create a copy of Default2.aspx.resx and rename it to default2.aspx.fr.resx (for French resources). Now, as a test, I have changed the button's tool tipfor the French resource to "French ToolTip". Now change your web browser settings and set French as the default culture.
(For Internet Explorer, use Tools → Internet options → Languages, add French to the top of the list and test the application)
beginn23.jpg
Test the button tool tip in this way, and you can test it for other languages also.
beginn24_s.png

App_GlobalResource Folder

The App_GlobalResource folder can be read from any page or code that is anywhere in the web site. Global resources must be stored in the App_GlobalResource folder at the root of the application. We should use theApp_GlobalResource folder when we need a single resource for multiple web pages. We candefine ASP.NET control properties by manually associating them with resources in global resource files.You can add a global resource file by right clicking on the App_GlobalResource folder and clicking on Add Items. Add .resx files as resources.
beginn25.jpg
We can access these resources programmatically by using the Resource.Resourceobject.
E.g.:
 Collapse
Label1.Text = Resource.Resource.MyText
We can use the GetLocalResourceObject()and GetGlobalResourceObject()methods to access global resources, and then cast them to the correct type.
 Collapse
Label1.Text = GetLocalResourceObject("Label1.Text").ToString(); 

Summary

I have explained in this article all about the use of application folders that are available in ASP.NET. I hope I have described them well enough for you to understand. There is lots more to learn, like how to design themes and skins, and working with resource files. I am giving some reference links at the end, that can help you in further study.
Please read these links, at least the one on resources, which are a very important part of ASP.NET 2.0. In future I plan to write an article for beginners on ASP.NET Resources. But not now.
Thanks for reading, and please don't forget to give your suggestions!

Beginner's Guide To View State

Courtesy : http://www.codeproject.com/KB/aspnet/BegViewState.aspx


Table of Contents

Introduction

First of all I want to thank Sean Ewington for his great initiative to write Beginner's Walk for Web Development article. I have decided to write some articles on state management There are a few article on Code project on State Management, basically on Session, Caching, Cookies, etc. Though all are very good article, still I have planned for write some article on state management. and I believe that should definitely helps to all the Beginners. And I have organized the content in a way that it would be helpful to not only beginners also to advance user also.
In this article, I will cover the fundamentals of State Management and Details of View State.

What is state management?

Web is Stateless. It means a new instance of the web page class is re-created each time the page is posted to the server. As we all know HTTP is a stateless protocol, its can't holds the client information on page. As for example , if we enter a text and client on submit button, text does not appear after post back , only because of page is recreated on its round trip.
User_S9_1.JPG
As given in above pages, page is recreated before its comes to clients and happened for each and every request. So it is a big issue to maintain the state of the page and information for a web application. That is the reason to start concept of State Management. To overcome this problem ASP.NET 2.0 Provides some features like View State, Cookies, Session, Application objects etc. to manage the state of page.
There are some few selection criteria to selected proper way to maintain the state, as there are many way to do that. Those criteria are:
  • 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 on the server?
  • Is the information sensitive?
  • What performance and bandwidth criteria do you have for your application?
  • What are the capabilities of the browsers and devices that you are targeting?
  • Do you need to store information per user?
  • How long do you need to store the information?
  • Do you have a Web farm (multiple servers), a Web garden (multiple processes on one machine), or a single process that serves the application?
So, when ever you start to think about state management, you should think about above criteria. based on that you can choose the best approaches for manages state for your web application.

Different types of state management?

There are two different types of state management:
  1. Client Side State Management
    • View State
    • Hidden Field
    • Cookies
    • Control State
  2. Server Side State Management
    • Session
    • Application Object
    • Caching
    • Database
Client Side state management does not use any server resource , it store information using client side option. Server Side state management use server side resource for store data. Selection of client side and server side state management should be based on your requirements and the selection criteria that are already given.

What is view state?

View State is one of the most important and useful client side state management mechanism. It can store the page value at the time of post back (Sending and Receiving information from Server) of your page. ASP.NET pages provide the ViewState property as a built-in structure for automatically storing values between multiple requests for the same page.
Example:
If you want to add one variable in View State,
 Collapse
ViewState["Var"]=Count;
For Retrieving information from View State
 Collapse
string Test=ViewState["TestVal"];
Sometimes you may need to typecast ViewState Value to retreive. As I give an Example to strore and retreive object in view state  in the last of  this article.

Advantages of view state?

This are the main advantage of using View State:
  • Easy to implement
  • No server resources are required
  • Enhanced security features ,like it can be encoded and compressed.

Disadvantages of view state?

This are the main disadvantages of using View State:
  • It can be performance overhead if we are going to store larger amount of data , because it is associated with page only.
  • Its stored in a hidden filed in hashed format (which I have discussed later) still it can be easily trapped.
  • It does not have any support on mobile devices.

When we should use view state?

I already describe the criteria of selecting State management. A few point you should remember when you select view state for maintain your page state.
  • Size of data should be small , because data are bind with page controls , so for larger amount of data it can be cause of performance overhead.
  • Try to avoid storing secure data in view state
WhenViewState.PNG

When we should avoid view state?

You won't need view state for a control for following cases,
  • The control never change
  • The control is repopulated on every postback
  • The control is an input control and it changes only of user actions.

Where is view state stored?

View State stored the value of page controls as a string which is hashed and encoded in some hashing and encoding technology. It only contain information about page and its controls. Its does not have any interaction with server. It stays along with the page in the Client Browser. View State use Hidden field to store its information in a encoding format.
Suppose you have written a simple code , to store a value of control:
 Collapse
ViewState["Value"] = MyControl.Text;
Now, Run you application, In Browser, RighClick > View Source , You will get the following section of code
User_S1.jpg
Fig : View state stored in hidden field
Now , look at the value. looks likes a encrypted string, This is Base64 Encoded string, this is not a encoded string. So it can easily be decoded. Base64 makes a string suitable for HTTP transfer plus it makes it a little hard to read . Read More about Base64 Encoding . Any body can decode that string and read the original value. so be careful about that. There is a security lack of view state.

How to store object in view state?

We can store an object easily as we can store string or integer type variable. But what we need ? we need to convert it into stream of byte. because as I already said , view state store information in hidden filed in the page. So we need to use Serialization. If object which we are trying to store in view state ,are not serializable , then we will get a error message .
Just take as example,
 Collapse
//Create a simple class and make it as Serializable
[Serializable]
public class student
{
    public int Roll;
    public string Name;
    public void AddStudent(int intRoll,int strName)
      {
        this.Roll=intRoll;
        this.Name=strName;
           }
}
Now we will try to store object of "Student" Class in a view state.
 Collapse
//Store Student Class in View State
student _objStudent = new student();
_objStudent.AddStudent(2, "Abhijit");
ViewState["StudentObject"] = _objStudent;

//Retrieve Student information view state
 student _objStudent;
_objStudent = (student)ViewState["StudentObject"]; 

How to trace your view state information?

If you want to trace your view state information, by just enable "Trace" option of Page Directive
User_S2.gif
Now Run your web application, You can view the details of View State Size along with control ID in Control TreeSection. Don't worry about "Render Size Byte" , this only the size of rendered control.
User_S3.jpg
Fig : View State Details

Enabling and Disabling View State

You can enable and disable View state for a single control as well as at page level also. To turnoff view state for a single control , set EnableViewState Property of that control to false. e.g.:
 Collapse
TextBox1.EnableViewState =false;
To turnoff the view state of entire page, we need to set EnableViewState to false of Page Directive as shown bellow.
User_S4.gif
Even you disable view state for the entire page , you will see the hidden view state tag with a small amount of information, ASP.NET always store the controls hierarchy for the page at minimum , even if view state is disabled.
For enabling the same, you have to use the same property just set them as True
as for example, for a single control we can enabled view state in following way,
 Collapse
TextBox1.EnableViewState =true;
and for a page level,
User_S5.gif

How to make view state secure?

As I already discuss View state information is stored in a hidden filed in a form of Base64 Encoding String, and it looks like:
User_S1.jpg
Fig : View state stored in hidden field
Many of ASP.NET Programmers assume that this is an Encrypted format, but I am saying it again, that this is not a encrypted string. It can be break easily. To make your view state secure, There are two option for that,
  • First, you can make sure that the view state information is tamper-proof by using "hash code". You can do this by adding "EnableViewStateMAC=true" with your page directive. MAC Stands for "Message Authentication Code"
User_S6.gif
A hash code , is a cryptographically strong checksum, which is calculated by ASP.NET and its added with the view state content and stored in hidden filed. At the time of next post back, the checksum data again verified , if there are some mismatch, Post back will be rejected. we can set this property to web.config file also.
  • Second option is to set ViewStateEncryptionMode="Always" with your page directives, which will encrypt the view state data. You can add this in following way
User_S7.gif
It ViewStateEncryptionMode has three different options to set:
  • Always
  • Auto
  • Never
Always, mean encrypt the view state always, Never means, Never encrypt the view state data and Auto Says , encrypt if any control request specially for encryption. For auto , control must callPage.RegisterRequiresViewStateEncryption() method for request encryption.
we can set the Setting for "EnableViewStateMAC" and ViewStateEncryptionMode" in web.config also.
User_S8.gif
Note : Try to avoid View State Encryption if not necessary , because it cause the performance issue.

Some Important Points

QuestionsAnswer
Client Side or Server Side ?Client Side
Use Server Resource ?No
Easy to implement ?Yes
Cause Performance Issue ?For heavy data and case of encryption & decryption
Support Encryption Decryption?Yes
Can store objects ?Yes, but you need to serialize the class.
TimeoutNo
That's all for view state. Hope you have enjoyed this article, please don't forget to give me your valuable suggestions. If anything need to update or changed please post your comments and please give me suggestion.