Tuesday 24 January 2012

Understanding 5 ASP.NET State management techniques in 5 hours



 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”







Query String:

Points to remember: Benefits
1)    Used for passing information using a query string in the URL
2)    The query string is the portion of the URL after the question mark
3)    Query strings are lightweight and don’t exert any kind of burden on the server.
4)    Best suited in e-Commerce scenario


Points to remember: Disadvantages
1) They can only contain simple string and they should only contain URL pre-defined accepted characters.
2) Information is visible and can be tampered. Values can be changed which could not be handled by the application at receiving it
3)    We cannot put large amount of data in query string, as there is size limitation enforced by different browsers, usually from 1 to 2 Kb.

How to send value in query string

Response.Redirect(“QueryStringRecipient.aspx” + “?Version=” +
((Control)sender).ID);

How to receive value from query string
lblDate.Text = “The time is now:<br>” + DateTime.Now.ToString();
switch (Request.QueryString["Version"])
{
case “cmdLarge”:
lblDate.Font.Size = FontUnit.XLarge;
break;
case “cmdNormal”:
lblDate.Font.Size = FontUnit.Large;
break;
case “cmdSmall”:
lblDate.Font.Size = FontUnit.Small;
break;
}

What is URL encoding: In query string, there is limitation in allowing valid characters. With URL encoding, special characters are replaced by escaped character sequences starting with the percent sign (%), followed by a two-digit hexadecimal representation.

When to use it: when we want that the data should store in the query string may not consist of URL legal characters, you should use URL encoding.
These special characters have special meaning
1)    (&) is used to separate multiple query string parameters,
1)    (+) is an alternate way to represent a space
2)    (#) is used to point to a specific bookmark in a web page.
Example:
string productName = “Apple iPad”;
Response.Redirect(“newpage.aspx?productName=” + Server.UrlEncode(productName));
Here we have used method UrlEncode from HttpServerUtility class. URL encloding here we are encoding a string of arbitrary data for use in the query string. This replaces all the non legal characters with escaped character sequences.

HttpServerUtility.UrlDecode() method can be used to  return a URL-encoded string to its initial value.

Cross Page Posting

Description: Till here we learned that page postbacks to themselves, and when they do it send back the current controls in the form for that page which also includes content of hidden variables value.

How it works: PostBackUrl property of button support cross page post backs. When the user clicks the button, the page will be posted to that new URL with the values from all the input controls on the current page.

Scenario #1: How to Set CrossPostBack attribute
<asp:Button runat=”server” ID=”cmdPost” PostBackUrl=”CrossPageTarget.aspx”
Text=”Cross-Page Postback”  />

Scenario #2: How to get source page info on target page.
In CrossPageTarget.aspx, the page can interact with the CrossPageSpurce.aspx objects using the Page.PreviousPage property.
if (Page.PreviousPage != null)
{
lblInfo.Text = “You came from a page titled ” +
PreviousPage.Header.Title;
}
But if we are interested into more specific details, such as control values, you need to cast the PreviousPage reference to the appropriate type.
CrossPageSource prevPage = PreviousPage as CrossPageSource;
Just by casting the previous page to the appropriate page type, we still won’t be able to directly access the control values. That’s because the controls are declared as protected members. You can handle this by adding properties to the page class that wrap the control variables
In Source page, create a property like this;
public string TextBoxContent
{
get { return txt1.Text; }
}
And in target page write below code to access previous page control value
if (prevPage != null)
{
lbl.Text += “You typed in this: ” + prevPage.TextBoxContent + “<br />”;
}

Scenario #3: How to keep control view state inact without using CrossPagePostBack.
Solution; Server.Transfer , because we need some work around , because only button control implements iButton iterface have this attribute , so in case you don’t have any button  , you can use server.tranfer overloaded method
Server.Transfer(“CrossPageTarget.aspx”, true);

Scenario #4: How to check between a cross-page post that’s initiated directly through a button and the Server.Transfer() method
if (PreviousPage.IsCrossPagePostBack)
{
lbl.Text += “The page was posted directly”;
}
else
{
lbl.Text += “You used Server.Transfer()”;
}

Scenario #5: How Page.IsPostBack work in Cross Page PostBack.
For the source page (the one that triggered the cross-page postback), the IsPostBack property is true. For the destination page (the one that’s receiving the postback), the IsPostBack property is false.

How it works: once we navigate from source page to target page, and from target page calls page.previouspage , life cycle for source page starts and Page.load event is fired. Page.IsPostBack property on source page is true so what happens is your code skips the time-consuming initialization
steps. Instead, the control values are restored from view state.  On the other hand, the Page.IsPostBack property for target page is false, so this page performs the necessary first-time
Initialization.
if (IsCrossPagePostBack)
{
// This page triggered a postback to CrossPage2.aspx.
// Don’t perform time-consuming initialization unless it affects
// the properties that the target page will read.
}
else if (IsPostBack)
{
// This page was posted back normally.
// Don’t do the first-request initialization.
}
else
{
// This is the first request for the page.
// Perform all the required initialization.
}

Scenario #6: How Validation controls works in Cross Page Postings.
We are looking at scenario where user click the button and validations doesn’t happens for any reason say client side scripting is not supported. So there should be an way out by which we can test it from target page.
if (Page.PreviousPage != null)
{
if (!PreviousPage.IsValid)
{
Response.Redirect(Request.UrlReferrer.AbsolutePath + “?err=true”);
}
else
{
So now source page need to know presence of this query string value and perform the validation. So on source page we can something like this;
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["err"] != null)
Page.Validate();
}
To test this set RequiredFieldValidator.EnableClientScript property to false.







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



Cookies: Cookie is one of several ways to store data about web site visitors during the time when web server and browser are not connected. They are small files
That are created on the client’s hard drive (or, if they’re temporary, in the web browser’s memory).
Benefits of Cookie:

1) They work transparently without the user being aware that information needs to be stored.
1) It is used by any page in the application
2) Retain user information between visits, which allows for truly long-term storage
3) Cookies do not require any server resources since they are stored on the client.
4) You can configure cookies to expire when the browser session ends (session cookies) or they can exist for a specified length of time on the client computer (persistent cookies).
Drawbacks:
1) Users can delete cookies.
2) User’s browser can refuse cookies, so your code has to anticipate that possibility.
3) Cookies exist as plain text on the client machine and they may pose a possible security risk as anyone can open and tamper with cookies.

Scenario #1: How to create and implement cookie.
HttpCookie myCookie = new HttpCookie(“Visitordetail”);
//We created the cookie but there are no keys with values in it, so for now it’s useless. So let’s add some:
myCookie["Country"] = “India”;
myCookie["VisitorName"] = “Vishal Nayan”;
myCookie["Language"] = “English”;
//We also need to add the cookie to the cookie collection
Response.Cookies.Add(myCookie);
//this cookie persist for 7 days
myCookie.Expires = DateTime.Now.AddDays(7);
//Check to see whether a cookie was found with this name.
HttpCookie cookie = Request.Cookies["Visitordetail"];
// Check to see whether a cookie was found with this name
if (cookie != null)
{
string sCountry = cookie["Country"];
}
//How to remove a cookie
Response.Cookies.Remove(“Visitordetail”);
//OR replacing it with a cookie that has an expiration date that
//has already passed
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);


Scenario #2: Generate Cookie for Remember me.

Below code below will create a cookie at client side for login name and password (don’t store password as per security reason). It will do following job.

1. Check if Remember me check box is checked or not
2. Create cookie Object
3.Remove old and Add new cookie with appropriate values.
4. Set expire time of cookie.
//suppose on login page we a checkbox to remember the user

CheckBox cbk = new CheckBox();
TextBox txtUsername = new TextBox();
txtUsername.Text = “Vishal Nayan”;
cbk.Checked = true;
if (cbk.Checked)
{
HttpCookie loginCookie = new HttpCookie(“logindetail”);
if (loginCookie != null)
{
Response.Cookies.Remove(“logindetail”);
Response.Cookies.Add(loginCookie);
myCookie.Values.Add(“UserInfo”, txtUsername.Text);
DateTime cookieExpiry = DateTime.Now.AddDays(5);
Response.Cookies["logindetail"].Expires = cookieExpiry;
}
}
Scenario #3: How to find does web browser accepts cookies

There are two possible cases when your client will not accept cookies:
1) Web browser does not support cookies
2) Web browser supports cookies, but user disabled that option through a browser’s privacy settings.
//How to check whether visitor’s browser have support for cookie
if (Request.Browser.Cookies)
{
// Cookies supported
}
else
{
// Web browser not supports cookies
}
Note: Request.Browser.Cookies will still return true but your cookies will not be saved. Only way to check client’s privacy settings is to try to save a cookie on the first page, and then redirect to second page that will try to read that cookie. You can eventually use the same page to save and read a cookie when perform a testing, but you must use Response.Redirect method after saving and before reading cookies.

Scenario #4: How cookies are saved as per domain details

Respective application can read only cookies related to your web domain. You can’t read cookies related to other web sites. Web browser stores cookies from different sites separately.
Scenario #5: How to save user login detail at time of login button click
//Another example whcih check whether cookie exists and then takes username and passwords and store
if ((Request.Cookies["PBLOGIN"] == null))
{
//Create a cookie with expiry of 30 days
Response.Cookies["PBLOGIN"].Expires = DateTime.Now.AddDays(30);
//Write username to the cookie
Response.Cookies["PBLOGIN"].Values["UNAME"] = “Vishal Nayan”;
//Write password to the cookie
Response.Cookies["PBLOGIN"].Values["UPASS"] = “123″;
}
//If the cookie already exist then wirte the user name and password on the cookie
else
{
Response.Cookies["PBLOGIN"].Values["UNAME"] = “Vishal Nayan”;
Response.Cookies["PBLOGIN"].Values["UPASS"] = “123″;
}

Scenario #6: Multi-Valued Cookies (Subkeys)

We can also store multiple name-value pairs in a single cookie. The name-value pairs are referred to as “keys” or “subkeys,” depending on what you are reading. There are a couple of reasons to use subkeys instead of separate cookies. Obviously, it is tidy to put related or similar information into a single cookie. In addition, because all the information is in a single cookie, cookie attributes such as expiration apply to all the information.
//Multi value cookies
Response.Cookies["userInfo"]["userName"] = “mike”;
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie(“userInfo”);
aCookie.Values["userName"] = “mike”;
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);

Scenario #7: How to define scope of cookie for particular domain
 

By default, cookies are associated with a specific domain.
Response.Cookies["domain"].Value = DateTime.Now.ToString();
Response.Cookies["domain"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["domain"].Domain = “support.vishalnayan.com”;



Session State Management: It is a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information. 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.

Advantages:
1)    Uniquely identify browser or client-device requests and map them to individual session instances on the server. This allows you to track which pages a user saw on your site during a specific visit. 
2)    Store session-specific data on the server for use across multiple browser or client-device requests during the same session. This is perfect for storing shopping cart information. 
3)    Raise appropriate session management events. In addition, you can write application code leveraging these events. 

How and where ASP.NET session state stores data:

We know how ASP.NET handles an HTTP request; actually it flows through a HTTP pipeline of different modules that can react to application events. One of the modules in this chain is the SessionStateModule (in the System.Web.SessionState namespace). The job of this module SessionStateModule is to generate the session ID, retrieves the session data from external state providers, and binds the data to the call context of the request. But actually SessionStateModule doesn’t actually store the session data. Instead, the session state is persisted in external components, which are named state providers.
These state provider are below;
1)    In-Memory objects.
2)    Windows Service (aspnet_state.exe)
3)    Tables in ASPState database.

What is role of session id: Session state is menained by Session ID which is the only piece of information that is transmitted between the web server and the client. When the client presents the session ID, ASP.NET looks up the corresponding session, retrieves the serialized data from the state server, converts it to live objects, and places these objects into a special collection so they can be accessed in code. This process takes place automatically.

How session state works: For session state to work, the client needs to present the appropriate session ID with each
request. The final ingredient in the puzzle is how the session ID is tracked from one request to the next. You can accomplish this in two ways:

1)    Using cookies: In this case, the session ID is transmitted in a special cookie (named ASP.NET_SessionId), which ASP.NET creates automatically when the session collection is used. This is the default

1)    Using modified URLs: In this case, the session ID is transmitted in a specially modified (or “munged”) URL

How to use Session State:
Class Name: System.Web.SessionState.HttpSessionState
Storing dataset in session variable,
Session["ProductsDataSet"] = dsProducts;
Retrieving value from session variable;
dsProducts = (DataSet)Session["ProductsDataSet"];

When session variable value will be lost:
1)    If browser is closed and restarted by user.
2)    If same page is accessed or browsed via a different browser window
3)     If the user accesses the same page through a different browser window, although the session
Will still exist if a web page is accessed through the original browser window. Browsers        differ on how they handle this situation.
4)     If the session times out because of inactivity. By default, a session times out after 20 idle minutes.
5)     If the programmer ends the session by calling Session.Abandon().
6)    When application domain will be recreated.

How to configure Session State in web.config

Below is a sample config.web file used to configure the session state settings for an ASP.NET application?
<sessionState
mode=”InProc”
stateConnectionString=”tcpip=127.0.0.1:42424″
stateNetworkTimeout=”10″
sqlConnectionString=”data source=127.0.0.1;Integrated Security=SSPI”
sqlCommandTimeout=”30″
allowCustomSqlDatabase=”false”
useHostingIdentity=”true”
cookieless=”UseCookies”
cookieName=”ASP.NET_SessionId”
regenerateExpiredSessionId=”false”
timeout=”20″
customProvider=”">
</sessionState>
What are Session Modes:

1) InProc:
1.1)        ASP.NET to store information in the current application domain.
1.2)        Once the server is restarted, the state information will be lost. i.e. session state is managed in process and if the process is re-cycled, state is lost.
1.3)        Its default option
1.4)        High performance because  the time it takes to read from and write to the session state dictionary, will be much faster when the memory read to and from is in process

2)    Off:
2.1) This setting disables session state management for every page in the application.
2.2) it can provide a slight performance improvement for websites that are not using                                  session state.

3)    StateSever:
3.1) the objects you store in session state must be serializable.
3.2) ASP.NET will use a separate Windows service for state management
3.3) the problem is that increased time is delay imposed when state information is transferred       between two processes. If you frequently access and change state information, this can make          for a fairly unwelcome slowdown.
To use this in your application, you need to start it
Browse this path:
Select Start ➤ Programs ➤ Administrative Tools➤ Computer Management➤ Services and Applications➤service node; Find the service called ASP.NET State Service in the list.

From here you can manually start and stop this servie.

1) Custom:
4.1) while using custom mode, we need to indicate what session state store provider to use by      supplying the customProvider attribute.
4.2) we use custom mode when we need to store session information in a database other than      SQL Server or to use an existing table in a database that has a specific schema.
4.3) the customProvider attribute directs to the name of a class that’s part of web application         in the App_Code directory, or in a compiled assembly in the Bin directory or the GAC.

What is CookieLess attribute in session state configuration setting.
cookieless=”UseCookies”
This feature with which we can configure for ASP.NET session state is cookieless session state. Essentially this feature allows sites whose clients choose not to use cookies to take advantage of
ASP.NET session state.

How it works: ASP.NET will modify relative links found within the page and embed this ID. Thus, as long as the user follows the path of links the site provides, session state can be maintained. This is done by modifying the URL with an ID that uniquely identifies the session:
http://localhost/(lit3py55t21z5v55vlm25s55)/Application/SessionState.aspx
Lets us understand about these attributes in details
1)    useCookie: Cookies are always used, even if the browser or device doesn’t support cookies or they are disabled. This is the default
2)    useURI: Cookies are never used, regardless of the capabilities of the browser or device. Instead, the session ID is stored in the URL.
3)    UseDeviceProfile: ASP.NET chooses whether to use cookieless sessions by examining the BrowserCapabilities object. The drawback is that this object indicates what the device should support
4)    AutoDetect: ASP.NET attempts to determine whether the browser supports cookies by attempting to set and retrieve a cookie
How to control timeout for session state: Timeout specifies the number of minutes that ASP.NET will wait, without receiving a request, before it abandons the session,
timeout=”20″
You can also programmatically change the session time-out in code.
Session.Timeout = 10;
Reference read from msdn here:
http://msdn.microsoft.com/en-us/library/ms972429.aspx
Session Example: The idea here is to create product detail class and save the items in session and bind it to listbox. On selecting product from listbox we provide full detail for that product. Here we also show and use session attribute to show session id , mode, cookieless etc.
Product class:
public class Product
{
public string name;
public string description;
public double cost;
public Product(string sname, string sdescription, double scost)
{
name = sname;
description = sdescription;
cost = scost;
}
}
Creating product object , storing them in session variable and adding it in listbox
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Product product1 = new Product(“laptop”, “Apple”, 1234);
Product product2 = new Product(“camera”, “Sony”, 5433);
Product product3 = new Product(“watch”, “Omega”, 6789);
Session["product1"] = product1;
Session["product2"] = product2;
Session["product3"] = product3;
lstItems.Items.Clear();
lstItems.Items.Add(product1.name);
lstItems.Items.Add(product2.name);
lstItems.Items.Add(product3.name);
}
// Display some basic information about the session.
// This is useful for testing configuration settings.
lblSession.Text = “Session ID: ” + Session.SessionID;
lblSession.Text += “<br>Number of Objects: “;
lblSession.Text += Session.Count.ToString();
lblSession.Text += “<br>Mode: ” + Session.Mode.ToString();
lblSession.Text += “<br>Is Cookieless: “;
lblSession.Text += Session.IsCookieless.ToString();
lblSession.Text += “<br>Is New: “;
lblSession.Text += Session.IsNewSession.ToString();
lblSession.Text += “<br>Timeout (minutes): “;
lblSession.Text += Session.Timeout.ToString();
}
On More information click , we are retriving more details from session variable and displaying.
protected void cmdMoreInfo_Click(object sender, EventArgs e)
{
if (lstItems.SelectedIndex == -1)
{
lblRecord.Text = “You have not seleected any product”;
}
else
{
string key = “product” + (lstItems.SelectedIndex + 1).ToString();
Product p = (Product)Session[key];
if (p != null)
{
lblRecord.Text = “Name: ” + p.name;
lblRecord.Text += “<br>Description: “;
lblRecord.Text += p.description;
lblRecord.Text += “<br>Cost: $” + p.cost.ToString();
}
}
}





Application State: It store global objects that can be accessed by any client.
It supports the same types what session state support which are of type objects, retains information on the server, and uses the same dictionary-based syntax. Application state is based on the System.Web.HttpApplicationState class, which is provided in all web pages through the built-in Application object.
Points to remember:

1)    application state items are stored as objects, so you need to cast them when you retrieve them from the collection
2)    Items in application state never time out
3)    Application state information is always stored in process. This means you can use any .NET data types
4)    Application state isn’t often used, because it’s generally inefficient and its rarely used in practical scenario because its most common uses have been replaced by easier and more efficient methods
1)    We use application state to store database connection string, which is stored now in web.config file, which is more flexible
2)    Previously application state was used to store more frequent data like full product , now you can use ASP.NET cache , which are more efficeint.
Example: We are often interested into knowing how many times a given page has been requested by various cleint. Using application state variable we can do this;
protected void Page_Load(object sender, EventArgs e)
{
int count = 0;
if (Application["HitCounterForOrderPage"] != null)
count = (int)Application["HitCounterForOrderPage"];
count++;
Application["HitCounterForOrderPage"] = count;
lblcounter.Text = “Page Visited: ” + count.ToString() + “Times”;
}
Problem with this approach: In above code, page counter would probably not keep an accurate count, particularly in times of heavy traffic. For example, if two clients requested the page at the same time, you could have a sequence of events like this
1. User A retrieves the current count (432).
2. User B retrieves the current count (432).
3. User A sets the current count to 433.
4. User B sets the current count to 433.
To avoid this problem you can use mechanism to lock and unlock application state;
Application.Lock();
int count = 0;
if (Application["HitCounterForOrderPage"] != null)
count = (int)Application["HitCounterForOrderPage"];
count++;
Application["HitCounterForOrderPage"] = count;
Application.UnLock();
lblcounter.Text = “Page Visited: ” + count.ToString() + “Times”;
When to use: You are storing infrequently changed, application-scope information that is used by many users, and security is not an issue. Do not store large quantities of information in an application state object.
This is end of your 5th hour of reading Hope you enjoyed it.
Posted by

No comments :