Related Links

Thursday, July 16, 2009

Global Variables/Value Persistent in ASP.NET

Session (User Level Value Persistent)
Session must be seen as a Value persistent for a Single user in any WebSite and isn't actually seems to be Global Variable as its value is lost when Particular user whose values contained or saved in Session Sign-Out from WebSite.

Sessions are used extensively in Web Applications Development.
Definition i found was "A session is defined as the period of time that a unique user interacts with a Web application. Active Server Pages (ASP) developers who wish to retain data for unique user sessions can use an intrinsic feature known as session state".
Programmatically, session state is nothing more than memory in the shape of a dictionary or hash table, e.g. key-value pairs, which can be set and read for the duration of a user's session. For example, a user selects stocks to track and the Web application can store these values in the user's ASP session instance:

in VB.... Session("Stocks") = "MSFT; VRSN; GE"
in Session["Name"] = Textboxname.text;

from an Article..............
Session helps programmers for Authentication purpose and for personalization of WebSites for Particular User. When a user Sign-In's to a WebSite, if Authenticated, then his Name and other Important info can be saved in Session and the pages that user visits are personalized accordingly.

Since the HTTP protocol used by web browsers to request files from web servers is stateless, ASP.NET needs to determine which requests were from the same user. The primary mechanism utilizes a non-persistent cookie that is issued by the web server that contains a session id value. The id provided by this cookie is the key used to index into the session infrastructure to access the user's specific data. The session framework is implemented by the HTTP module System.Web.SessionState.SessionStateModule, which executes before the .aspx page events. The module uses the EnableSessionState attribute from the @Page directive to determine if it must retrieve the user’s session information (and whether it needs to write out changes when the request is complete). If the EnableSessionState attribute is true (which it is by default), the module retrieves all of the user’s session information and sets the Session property of the Page class to an instance of the HttpSessionState class. This article focuses on the cookie mechanism, although a cookie-less method of sessions is implemented in ASP.NET (the session id is embedded in the URL string). The Session information can be stored in-process (default, stores in web server memory), with a state service, or a SQL Server database.

ASP maintains session state by providing the client with a unique key assigned to the user when the session begins. This key is stored in an HTTP cookie that the client sends to the server on each request. The server can then read the key from the cookie and re-inflate the server session state.

Session state settings in ASP.NET are configured through the ASP.NET XML configuration file config.web.
Web.config file contaims info about Session Start and Session End....

QueryString (URL Level Vlaue Persistent)
Session was used to store values for a single user and when going back and forth any URL or different webpages, the session expires and values in the Session are lost.
For purpose of restoring values while going back and forth on different URLz, QueryString is used.
It works by appending Name/Value pairs to a specific URL that we want user to Redirect to. It helps in identifying that particular user when he clicks that URL and is redirected to that URL alongwith sent values being persistent. Then when he reaches that page whose URL was iun QueryString, the programmer can easily extract values from the Querystring name wise or index wise according to order to which tha values to URL were Appended.
Security Issue while dealing with QueryString comes along when anyonee reads or hacks the values in QueryString, as HOTMAIL accounts were hacked by Decrypting of QueryStruing they used to redirect users to their respective accounts.
So the values that are to be sent along URL or that are appended to URL must first be Encrypted by using a good Encryption method. Mostly a 16-bit Encryption technique is used which converts each vaalue to 16-bit and can be Decrypted by Programmer using same method.

an Example extracted from following link alongwith details.......
Example of QueryString..........

This html addresses use QueryString property to pass values between pages. In this address you send 3 information.

Webform2.aspx this is the page your browser will go.
name=Atilla you send a name variable which is set to Atilla
lastName=Ozgur you send a lastName variable which is set to Ozgur

As you have guessed ? starts your QueryString, and & is used between variables. Building such a query string in Asp.Net is very easy. Our first form will have 2 textboxes and one submit button.

private void Page_Load(object sender, System.EventArgs e)
this.txtBox1.Text = Request.QueryString["Name"];
this.txtBox2.Text = Request.QueryString["LastName"];
} Request.QueryString is overloaded with a second way. You can also retrieve this values using their position in the querystring. There is a little trick here. If your QueryString is not properly built Asp.Net will give error.

Collapse Copy Code
private void Page_Load(object sender,

System.EventArgs e)
this.txtBox1.Text = Request.QueryString[0];
this.txtBox2.Text = Request.QueryString[1];

Disadvantages of this approach

QueryString have a max length, If you have to send a lot information this approach does not work.
QueryString is visible in your address part of your browser so you should not use it with sensitive information.
QueryString can not be used to send & and space characters.

Initially I created just a simple class for passing parameters through the querystring, which met my needs at the time. But thinking more about my class, I realized that the high-level aim was to pass data from one page to another - why should I limit it to using the querystring? I decided to take a step back and define the functionality needed for passing data from one page to another, ignoring the actual implementation details.

In order to pass data from one page to another I reasoned that the following would be needed:

The URL of the page that is to receive the data
The name/value pairs of the data to pass
A method that, when called, will pass the supplied data to the specified page
Similarly, the page that received the data needed a means to:
Extract the value for a name/value pair
Enumerate all values in the parameter collection

ViewState (Page Level Value Persistent)

Actully All HTML controls are state-less ie;-these can not store any type of clients inputs.when ever we send the page to server it will send this page as fresh we loose the data what we have entered.

To store all these data (temporarly) in clients browsers ,.Net provide a concept that is known as View state .View state store the data in encoding format,so that one can not gues it easily.
ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks.

If you set the viewstate for a server side control to true. You will see that the value for the control is retained even after post back.

Normally it should, because for every request a new page is created.

But if viewstate is true for that control then the value ( encrypted ) of the control is stored in a hidden variable in the form itself.

And in the Page Init event of the page life cycle it agains load the viewstate, meaning assigns the values for each control from the hidden variable.

In ASP, on submitting a form if an error occurs then you click BACK. the page is loaded with all fields cleared.To prevent this, view state, in ASP.NET, holds the status of the page when submitted and the field values are not cleared. But if the page is opened as a new page, the view state values are lost.

1. By default, View State is enabled for every control in the ASP.NET Framework.
2. ViewState does not hold the controls, rather it holds the values of the form controls and their corresponding ID's that would otherwise be lost due to a post back because they do not post with the form.
3. ViewState is not used to hold session data or to transmit data between pages.
4. ViewState does not recreate the dynamically created controls of a page.
5. It does not restore the values to the controls after a post back operation.

from a website..

View State is the maintain the controls properties Under postback implimentaion that is called view stae.
View State deos not allocated any memory on client side and server side.
view state is maintain the with in the page only.
view state stired the values in hidden fields.
view state is maintain Application level,page level etc.
Session:Session is maintain the User Information on server side .
Session can be maintain the each client only,but not more than one client.
By using session you can pass the values from one page to anther page .
Session disadvantages is the allocated the More Memory in Server side
Microsoft ASP.NET Web Forms pages are capable of maintaining their own state across multiple client round trips. When a property is set for a control, the ASP.NET saves the property value as part of the control's state. To the application, this makes it appear that the page's lifetime spans multiple client requests. This page-level state is known as the view state of the page. In Web Forms pages, their view state is sent by the server as a hidden variable in a form, as part of every response to the client, and is returned to the server by the client as part of a postback. In this article we will see how View State is implemented in ASP.NET for state management and we will also see how effectively you can use this object in your web form.

ViewState("FontSize") = value

Application Variables (Application Level Value Persistent)

Generally, application variables should hold information that you write nfrequently. In most cases, the values of these variables are set once, most often when an application first starts. Then the values of these variables are referenced many times throughout the life of the application or the course of a session.

Application Variables are defined in Global.asax file which is an optional file used to declare and handle application- and session-level events and objects. The Global.asax file resides in the IIS virtual root of an ASP.NET application. At run time, upon the arrival of the first request, Global.asax is parsed and compiled into a dynamically generated .NET Framework class. ASP.NET is configured so that any direct request for the Global.asax is automatically rejected, external users cannot view or download the code in it.
Useful Events in Global.asax:

1. Application_Init
2. Application_Start
3. Session_Start
4. Application_BeginRequest
5. Application_EndRequest
6. Application_AuthenticateRequest
7. Application_Error
8. Session_End
9. Application_End

We can use the Application() object:

Application("MyVariable") = "Test String"
and then we can use Application("MyVariable") for whole Application and for each user the same Value is preserved that we have stored in it initially.

A good example from

In Global.asax.cs

using System;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
public class Global : HttpApplication
protected void Application_Start(Object sender, EventArgs e)
Application["appCtr"] = 0;
Application["noOfUsers"] = 0;
protected void Application_BeginRequest(Object sender, EventArgs e)
Application["appCtr"] = (int) Application["appCtr"] + 1;

protected void Session_Start(Object sender, EventArgs e)
Application["noOfUsers"] = (int) Application["noOfUsers"] + 1;
// Code for other handlers

On your Regular Page:

Response.Write("Wow. This application has been accessed "+ Application["appCtr"] + " times today.");
Response.Write("There are currently "+ Application["noOfUsers"] + " users accessing this web application");

If many users access the application simultaneously and you use Application scope variables extensively, your application performance might degrade. If your application uses many application variables, consider whether the variables must be in the Application scope or whether they can be Session or Request scope variables.


Anonymous said...

good job