ASP.NET Control State for Custom Server Controls

State management is a perennial challenge for any web development framework – once a page is refreshed any data on the page (such as text already entered in textboxes) must be persisted using some method. Traditionally ASP.NET solves this problem using View State which inserts text directly into the html of the page which can then be read by the server when the page is posted to the server. This solution works well in most circumstances but the one major issue is performance – View State adds a large payload to each page request and will slow the ASP.NET site/app down. The issue is especially acute when using ASP.NET AJAX since there are numerous background hits on the server and each of which needs to contain the full View State payload.

Control State is designed to be a much more lightweight store of data than view state . Control State is designed to store   data a control is currently using. Technically, control state works in the same manner as view state—storing serializable data that’s placed in a hidden field when a page is rendered. ASP.NET actually puts   view state and control state data into the same hidden field. The only major difference is that control state is unaffected by the EnableViewState property, therefore even if EnableViewState is set to false, acontrol can still store and retrieve data from  control state.

Since control state cannot be disabled, you will need to  carefully restrict the amount of information stored. Normally, it is limited to something critical such as the current page index or else a data key value. To use control state in  a custom server control, you   begin by overriding the OnInit() method and the calling Page.RegisterRequiresControlState() to notify ASP.NET that the control needs to access control state.

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Page.RegisterRequiresControlState(this);
}

Unlike view state, control state cannot be accessed  directly through a collection and you must override two methods:  LoadControlState() and SaveControlState(). These methods use a slightly irregular pattern. The overall idea is that you need to take any control state which has been serialized by the base class and then combine that with an object which contains your new serializable object. You can do this using the System.Web.Pair class, as shown below:

string myData;
protected override object SaveControlState()
{
// Get state from the base class.
object baseStateObj = base.SaveControlState();
// Combine  with the state object you wish to store
// and then return the final object.
return new Pair(baseStateObj, myData);
}

This technique will enable you to only store  a single object. For storing several items of information, consider creating a custom class which encapsulates all these details (and ensure it includes the Serializable attribute). An alternative method is to  create a chain of Pair objects:

private string strData;
private int integerData;
protected override object SaveControlState()
{
// Get state from the base class.
object baseStateObj = base.SaveControlState();
// Combine with the state objects you want to store,
// and return the final object.
Pair pairA = new Pair(strData, integerData);
Pair pairB = new Pair(baseStateObj, pairA);
return pairB;
}

Continues…

Optimizing ASP.NET Profiles Performance

ASP.NET Profiles were introduced to assist developers in persisting user information. Previous methods of persistence all had limitations in how they stored user data, Session state would only be held in memory and lost once the user’s session ended, a query-string would only be useful for that particular page and had to be recreated on each new page, cookies are only available on a single user machine. Profiles addressed all these difficulties by providing a simple persistent store which plugs into ASP.NET Membership. Profiles are ideal for storing user info such as preferences for a web app, besides being convenient they are very simple to use – just create them in the web.config file and access them anywhere in the application using Profile.ProfileName.

But with the convenience and power of Profiles comes a price – performance. Profiles are stored in a database, and therefore if used without caution can have a major performance cost.

To understand how best to use Profiles, first we will look at how they work under the hood. Profiles plug into the life-cycle of the page at two points:

  • The first time the Profile object is accessed in your code ASP.NET retrieves all the  profile data for the current user from the   database. If   the profile data is used more  than once in the same request ASP.NET reads it only once and then reuses it.
  • If profile data is updated, that update is deferred until the page has finished processing( ie after the PreRender, PreRenderComplete, and Unload events have completed). At that point the profile data  is written   to the database, thus  multiple changes are updated in batch.

Thus, using Profiles can result in an extra two database hits  per  request (if Profile data is read and then updated) or one extra database hit  (for simply reading the Profile data). It should be noted that Profiles do not have a caching mechanism so so every request for Profile data or update of Profile data  requires a database connection.

Thus from a performance viewpoint, Profiles are best when:

  • There are a relatively small number of pages which access the Profile data.
  • Profiles only store small amounts of data (since accessing Profiles always results in the retrieval of all the Profile data for that user it can be quite result in large payloads).

Therefore to optimize performance when using ASP.NET Profiles it is best to combine  

Profiles with other methods of  state management. For example,   a web app could first check if there was a cookie stored on the user’s machine for the user’s date format preference and if not available  this data could be retrieved from the Profile (which would then then add a cookie) this will save a database round trip each time to check the preferences (session state could also be used for this).

ASP.NET Sever Side State Management

1. Application Object

The Application object provides a mechanism for storing data that is accessible to all code running within the Web application,The ideal data to insert into application state variables is data that is sharedby multiple sessions and does not change often.. And just because it is visibleto the entire application, you need to used Lock and UnLock pair to avoid having conflit value.

Application.Lock();
Application[“mydata”]=”mydata”;
Application.UnLock();

2. Session Object

The Session object can be used for storing session-specific information that needs to be maintained between server round trips and between requests for pages. Session object is per-client basis, which means different clients generate different session object.The ideal data to store in session-state variables is short-lived, sensitive data that is specific to an individual session.

Each active ASP.NET session is identified and tracked using a 120-bit SessionID string containing URL-legal ASCII characters.SessionID values are generated using an algorithm that guarantees uniqueness so that sessions do not collide,and SessionID’s randomness makes it harder to guess the session ID of an existing session.
SessionIDs are communicated across client-server requests either by an HTTP cookie or amodified URL, depending on how you set the application’s configuration settings.So how to set the session setting in application configuration? Ok, let’s go further to look at it.

Every web application must have a configuration file named web.config, it is a XML-Based file, there is a section name ‘sessionState’, the following is an example:

<sessionState mode=”InProc”stateConnectionString=”tcpip=127.0.0.1:42424″ sqlConnectionString=”datasource=127.0.0.1;user id=sa;password=” cookieless=”false” timeout=”20″/>

‘cookieless’ option can be‘true’ or ‘false’. When it is‘false’(default value), ASP.NET will use HTTP cookie to identify users. When it is ‘true’, ASP.NET will randomly generate a unique number and put it just right ahead of the requested file, this number is used to identify users, you can see it on the address bar ofIE:

http://localhost/Management/(2yzakzez3eqxut45ukyzq3qp)/Default.aspx

Ok, this is enough, let’s go back to the session object.

//to store information
Session[“myname”]=”Mike”;
//to retrieve information
myname=Session[“myname”];

3. Database

Database enables you to store large amount of information per taining to state in your Web application.
Continues…

ASP.NET Client-Side State Management – ViewState, Cookies and QueryString

Web form pages are HTTP-Based, they are stateless, which means they don’t know whether the requests are all from the same client, and pages are destroyed and recreated with each round trip to the server, therefore information will be lost and state management is a major issue in developing web applications. In this article we review how to handle state manage on the client using ViewState , Cookies, Hidden Fields and QueryStrings.

1. ASP.NET ViewState

Each control on a Web Forms page, including the page itself, has a ViewState property, it is a built-in struture for automatic retention of page and control state, which means you don’t need to do anything about getting back the data of controls after posting page to the server.

Here, which is useful to us is the ViewState property, we can use it to save information between round trips to the server.

//to save information
ViewState.Add(“shape”,”circle”);
//to retrieve information
string shapes=ViewState[“shape”];

Note: Unlike Hidden Fields, the values in ViewState are invisible in the ‘viewsource’ of the page, they are compressed and encoded.

2. ASP.NET 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. Cookies are mainly used for tracking data settings.

Let’s take an example: say we want to customize a welcome web page, when the user request the default web page, the application first to detect if the user has logined before, we can retrieve the user informatin from cookies:

if(Request.Cookies[“username”]!=null)
 lbMessage.text=”Dear“+Request.Cookies[“username”].Value+”, Welcome shoppinghere!”;
else
 lbMessage.text=”Welcome shoppinghere!”;

If you want to storeclient’s information, you can use the following code:

Response.Cookies[“username’].Value=username;

So next time when the user request the web page, you can easily recongnize the user again.

3. ASP.NET Hidden Fields

A hidden field does not render visibly in the browser,but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in theHTTP Form collection along with the values of other controls.

A hidden field acts as a repository for any page-specific information that you would like tostore directly in the page. Hidden field stores a single variable in itsvalue property and must be explicitly added it to the page.
ASP.NET provides the HtmlInputHidden control that offers hidden field functionality.

protected System.Web.UI.HtmlControls.HtmlInput Hidden Hidden1;
//to assign a value to Hiddenfield
Hidden1.Value=”this is a test”;
//to retrieve a value
stringstr=Hidden1.Value;

Note: Keep in mind, in orderto use hidden field, you have to use HTTP-Post method to post web page. Although its name is ‘Hidden’, its value is not hidden, you can see its value through ‘view source’ function.

4. ASP.NET QueryStrings

Query strings provide a simple but limited way of maintaining some state information.You can easily pass information from one page to another, But most browsers and client devices impose a 255-character limit on the length of the URL. In addition, the query values are exposed to the Internet via the URL so in some cases security may be an issue.Continues…