Dear All,
I Wish you and your family a happy new year 2009.
Thanks
Sandeep Reddy Pasham
Welcome to my blog, Hope you'll enjoy it's content, Leave a comment if u feel like help full.
ASP.NET Session State and Modes
The following terms are specific to this document:
Application Domain: A virtual process space within which ASP.NET is hosted and executed. On a Web server, it is possible to have multiple ASP.NET Web applications running inside a single process. Each ASP.NET application runs within its own application domain and is isolated from other ASP.NET applications that are running in separate application domains. An application domain has a unique identifier used as part of the identifying key on a state server when storing and retrieving session data.
ASP.NET: A Web server technology for dynamically rendering HTML pages using a combination of HTML, Javascript, CSS, and server-side logic.
ASP.NET State Server: Alternately, StateServer mode uses a stand-alone Microsoft Windows service to store session variables. Because this service is independent of Microsoft Internet Information Server (IIS), it can run on a separate server. You can use this mode for a load-balancing solution because multiple Web servers can share session variables. Although session variables are not lost if you restart IIS, performance is impacted when you cross process boundaries. .
InProc: In-Proc mode stores values in the memory of the ASP.NET worker process. Thus, this mode offers the fastest access to these values. However, when the ASP.NET worker process recycles, the state data is lost.
Session State: A feature for temporarily storing data associated with a browser session. Session state can be stored outside the process space of a session state client. The ASP.NET State Server is the default implementation for storing session state out of process.
URL: A uniform resource locator that identifies network-addressable endpoints. In the context of the ASP.NET State Server Protocol, a URL is used to identify a running instance of a state server implementation. The format of a state server URL is as specified in [RFC1738].
User Session Identifier: A unique identifier used as part of the identifying key when storing and retrieving session data.
Web Application Identifier: Each ASP.NET application running on a Web server is uniquely identified with a Web application identifier. The Web application identifier is the virtual path of the Web application on the Web server. A Web application identifier is used as part of the identifying key on a state server when storing and retrieving session data for a specific browser session.
ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET applications.
Alternatives to session state include the following:
The query string and fields on an HTML form that are available from an HTTP request.
Session Variables
Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext..::.Session property. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object.
The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to the collection. The following example shows how to create session variables in an ASP.NET page for the first and last name of a user, and set them to values retrieved from TextBox controls.
Visual Basic
Session("FirstName") = FirstNameTextBox.Text
Session("LastName") = LastNameTextBox.Text
C#
Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;
Session variables can be any valid .NET Framework type. The following example stores an ArrayList object in a session variable named StockPicks. The value returned by the StockPicks session variable must be cast to the appropriate type when you retrieve it from the SessionStateItemCollection.
Visual Basic
' When retrieving an object from session state, cast it to
' the appropriate type.
Dim stockPicks As ArrayList = CType(Session("StockPicks"), ArrayList)
' Write the modified stock picks list back to session state.
Session("StockPicks") = stockPicks
C#
// When retrieving an object from session state, cast it to
// the appropriate type.
ArrayList stockPicks = (ArrayList)Session["StockPicks"];
// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;
Note: When you use a session-state mode other than InProc, the session-variable type must be either a primitive .NET type or serializable. This is because the session-variable value is stored in an external data store. For more information, see Session-State Modes. |
By default, the SessionID value is stored in a non-expiring session cookie in the browser.
However, you can specify that session identifiers should not be stored in a cookie by
setting the cookieless attribute to true in the sessionState section of the Web.config file.
The following example shows a Web.config file that configures an ASP.NET application to cookieless session identifiers.
<configuration>
<system.web>
<sessionState cookieless="true"
regenerateExpiredSessionId="true" />
</system.web>
</configuration>
ASP.NET maintains cookieless session state by automatically inserting a unique session ID into the page's URL. For example, the following URL has been modified by ASP.NET to include the unique session ID lit3py55t21z5v55vlm25s55:
http://www.example.com/(S(lit3py55t21z5v55vlm25s55))/orderform.aspx
When ASP.NET sends a page to the browser, it modifies any links in the page that use an application-relative path by embedding a session ID value in the links. (Links with absolute paths are not modified.) Session state is maintained as long as the user clicks links that have been modified in this manner. However, if the client rewrites a URL that is supplied by the application, ASP.NET may not be able to resolve the session ID and associate the request with an existing session. In that case, a new session is started for the request.
The session ID is embedded in the URL after the slash that follows the application name and before any remaining file or virtual directory identifier. This enables ASP.NET to resolve the application name before involving the SessionStateModule in the request.
ASP.NET session state supports several storage options for session variables. Each option is identified as a session-state Mode type. The default behavior is to store session variables in the memory space of the ASP.NET worker process. However, you can also specify that session state should be stored in a separate process, in a SQL Server database, or in a custom data source. If you do not want session state enabled for your application, you can set the session mode to Off.
For more information, see Session-State Modes.
ASP.NET provides two events that help you manage user sessions. The Session_OnStart event is raised when a new session starts, and the Session_OnEnd event is raised when a session is abandoned or expires. Session events are specified in the Global.asax file for an ASP.NET application.
The Session_OnEnd event is not supported if the session Mode property is set to a value other than InProc, which is the default mode.
Session-State Modes
ASP.NET session state supports several different storage options for session data. Each option is identified by a value in the SessionStateMode enumeration. The following list describes the available session state modes:
You can specify which mode you want ASP.NET session state to use by assigning a SessionStateMode enumeration values to the mode attribute of the sessionState element in your application's Web.config file. Modes other than InProc and Off require additional parameters, such as connection-string values as discussed later in this topic. You can view the currently selected session state by accessing the value of the HttpSessionState..::.Mode property.
Inproc Mode
In-process mode is the default session state mode and is specified using the InProc SessionStateMode enumeration value. In-process mode stores session state values and variables in memory on the local Web server. It is the only mode that supports the Session_OnEnd event. For more information about the Session_OnEnd event, see Session-State Events.
Caution: If you enable Web-garden mode by setting the webGarden attribute to true in the processModel element of the application's Web.config file, do not use InProc session state mode. If you do, data loss can occur if different requests for the same session are served by different worker processes.
State Server Mode
StateServer mode stores session state in a process, referred to as the ASP.NET state service, that is separate from the ASP.NET worker process or IIS application pool. Using this mode ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
To use StateServer mode, you must first be sure the ASP.NET state service is running on the server used for the session store. The ASP.NET state service is installed as a service when ASP.NET and the .NET Framework are installed. The ASP.Net state service is installed at the following location:
systemroot\Microsoft.NET\Framework\versionNumber\aspnet_state.exe
To configure an ASP.NET application to use StateServer mode, in the application's Web.config file do the following:
Note: To improve the security of your application when using StateServer mode, it is recommended that you protect your stateConnectionString value by encrypting the sessionState section of your configuration file. For details, see Encrypting Configuration Information Using Protected Configuration.
The following example shows a configuration setting for StateServer mode where session state is stored on a remote computer named SampleStateServer:
<configuration>
<system.web>
<sessionState mode="StateServer"
stateConnectionString="tcpip=SampleStateServer:42424"
cookieless="false"
timeout="20"/>
</system.web>
</configuration>
Note: Objects stored in session state must be serializable if the mode is set to StateServer. For information on serializable objects, see the SerializableAttribute class.
To use StateServer mode in a Web farm, you must have the same encryption keys specified in the machineKey element of your Web configuration for all applications that are part of the Web farm. For information on how to create machine keys, see article 313091, "How to create keys by using Visual Basic .NET for use in Forms authentication," in the Microsoft Knowledge Base at http://support.microsoft.com.
SQL Server mode
SQLServer mode stores session state in a SQL Server database. Using this mode ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
Note: Objects stored in session state must be serializable if the mode is SQL Server. For information on serializable objects, see the SerializableAttribute class.
To use SQLServer mode, you must first be sure the ASP.NET session state database is installed on SQL Server. You can install the ASP.NET session state database using the Aspnet_regsql.exe tool, as described later in this topic.
To configure an ASP.NET application to use SQLServer mode, do the following in the application's Web.config file:
Note: to improve the security of your application when using SQLServer mode, it is recommended that you protect your sqlConnectionString value by encrypting the sessionState section of your configuration file. For details, see Encrypting Configuration Information Using Protected Configuration.
The following example shows a configuration setting for SQLServer mode where session state is stored on a SQL Server named "SampleSqlServer":
<configuration>
<system.web>
<sessionState mode=" SQLServer "
sqlConnectionString="Integrated Security=SSPI;data
source=SampleSqlServer;" />
</system.web>
</configuration>
Configuring Session State
Session state is configured by using the sessionState element of the system.web configuration section. You can also configure session state by using the EnableSessionState value in the @ Page directive.
The sessionState element enables you to specify the following options:
The following example shows a sessionState element that configures an application for SQLServer session mode. It sets the Timeout value to 30 minutes, and specifies that session identifiers are stored in the URL.
<sessionState mode="SQLServer"
cookieless="true "
regenerateExpiredSessionId="true "
timeout="30"
sqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;"
stateNetworkTimeout="30"/>
You can disable session state for an application by setting the session-state mode to Off. If you want to disable session state for only a particular page of an application, you can set the EnableSessionState value in the @ Page directive to false. The EnableSessionState value can also be set to ReadOnly to provide read-only access to session variables. Examples:
Save Values in Session State
Visual Basic
Dim firstName As String = "John"
Dim lastName As String = "Smith"
Dim city As String = "Seattle"
Session("FirstName") = firstName
Session("LastName") = lastName
Session("City") = city
C#
string firstName = "Jeff";
string lastName = "Smith";
string city = "Seattle";
Session["FirstName"] = firstName;
Session["LastName"] = lastName;
Session["City"] = city;
Read Values from Session State
Visual Basic
Dim firstName as String = CType(Session.Item("FirstName"), String)
Dim lastName as String = CType(Session.Item("LastName"), String)
Dim city as String = CType(Session.Item("City"), String)
C#
string firstName = (string)(Session["First"]);
string lastName = (string)(Session["Last"]);
string city = (string)(Session["City"]);
Many of you might have come across the situation where you need to making server side discussion based on client side JavaScript confirm message value. Though this may sound very basic feature, surprisingly large developers struggle when implementing this. In this article, I will show you how to.
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">
<table style="margin-top:100px;">
<tr style="padding-bottom:10px">
<td>
<asp:Label ID="lblitemName" Text="Item Value" runat="server">asp:Label>td>
<td>
<asp:TextBox ID="txtitemval" runat="server">asp:TextBox>td>
tr>
table>
<div style="padding-bottom:10px">
<asp:Label ID="lblMsg" runat="server">asp:Label>
div>
<div style=" margin-bottom:100px; margin-left:120px">
<asp:HiddenField ID="hdnField" runat="server" Value="false" />
<asp:Button ID="btnSubmit" runat="server" Text="Check Val" OnClick="btnSubmits_Click" />
div>
asp:Content>
And the code behind for this page is like
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmits_Click(object sender, EventArgs e)
{
string itemValue = Convert.ToString(txtitemval.Text);
if (hdnField.Value == "false")
{
lblMsg.Visible = false;
AddJavascriptCode(itemValue);
}
else if (hdnField.Value == "true")
{
lblMsg.Visible = true;
lblMsg.Text = string.Format("You have entered {0}", itemValue);
hdnField.Value = "false";
}
}
private void AddJavascriptCode(string itemValue)
{
string script = @"<script language=""JavaScript"" type=""text/javascript"">
window.onload=function()
{
var IsConfirm = 1;
objField = document.getElementById('" + hdnField.ClientID + @"');
objSubmit = document.getElementById('" + btnSubmit.ClientID + @"');
IsConfirm = newConfirm('Test','You have entered " + itemValue + @" value. Are you sure you want to go next page?',1,1,0);
if(IsConfirm == true)
{
objField.value = 'true';
objSubmit.click();
}
else
{
objField.value = 'false';
}
}
function newConfirm(title,mess,icon,defbut,mods)
{
if (document.all)
{
retVal = confirm(mess);
retVal = (retVal==1)
}
else
{
retVal = confirm(mess);
}
return retVal;
}
</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Test", script);
}
}
See the Result below