2 February 2014

Sql Server Mode

      In this 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.

       Objects stored in session state must be serializable if the mode is SQL Server
       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

         To configure an ASP.NET application to use SQLServer mode, do the following in the application's Web.config file:


·         Set the mode attribute of the session State element to SQLServer.
·         Set the sqlConnectionString attribute to a connection string for your SQL Server database.
Implementation of SQL Server :

   <configuration>
      <system.web>
      <sessionState mode="SQLServer"
      SqlConnectionString="Integrated Security=SSPI;
      data source=SampleSqlServer;" />
    </system.web>
  </configuration>

Configuring Sql server in web farm

        To configure SQLServer mode for a Web farm, in the configuration file for each Web server, set the session State element's sqlConnectionString attribute to point to the same SQL Server database. The path for the ASP.NET application in the IIS metabase must be identical on all Web servers that share session state in the SQL Server database




State Server (Out Process Session)

         A second option, accomplished by setting the mode attribute to StateServer, is storing session data in a separate in-memory cache controlled by a Windows service running on a separate machine.

        The state service, called the ASP.NET State Service (aspnet_state.exe), is configured by the stateConnectionString attribute in the Web.configfile. It specifies the service’s server and the port it monitors:

<sessionState mode="StateServer"
stateConnectionString="tcpip=myserver:42424" cookieless="false" timeout="20" />

  
       In this case, the state service is running on a machine called myserver on port 42424, which is the default. At the server, the port can be changed by editing the Port value in the HKLM\SYSTEM\CurrentControlSet\Services\aspnet_state registry key. Obviously, using the state service has the advantages of process isolation and sharability across a web farm.
      
       However, if the state service is stopped, all session data is lost. In other words, the state service does not persistently store the data as SQL Server does; it simply holds it in memory.

Implementation of State Server:


<configuration>
   <system.web>
   <sessionstate mode="state server" state connectionstring="tcpip=samplestateserver:42424"
      cookieless="false" timeout="20"/>
   <system.web>
</configuration>

    Objects stored in session state must be serializable if the mode is set ti state server

    To use stateserver mode in a web farm ,you must have the same encryption keys specified in the machine key element of our web configuration for all applications that are part of the web farm 

In-Process Session

      The InProc Session State Mode is the default Session State Mode. We can host multiple websites/web applications on a single IIS. Each application runs in a separate Application Domain. The InProc Session State Mode stores session data in a memory object in the application worker process (aspnet_wp.exe) in the application domain.

       It is usually the fastest, but more session data means more memory is used on the web server, and that can affect performance. 

        The session data is stored in the application domain of the web server. When the server restarts then existing data is lost. If you modify the Global.asax file and the Web.Config file for an ASP.NET application then the application will be restarted and all the session data will be lost.

         ASP.NET provides two events that help you manage user sessions. These events are defined in the Global.asax file of the web application.

Events in InProc Session:

Session_start(): This  Event Occurs when a new session begins
Session_End(): This event occurs when a session is abandoned or expires.

Implementation of InProc Session

       The InProc Session State Mode is the default session mode but you can also set the Session State Mode and session timeout in the Web.Config file of you application as in the following code snippet.

 <Configuration>
  <system.web>    
    <sessionState mode="InProc" timeout="25"></sessionState>
  </system.web>
</configuration>

     The preceding session timeout setting keeps the session alive for 25 minutes. If you don't define a timeout attribute in the SessionState then the default value is 20 minutes.

Storing Session Value:    

       Now provide the following code in the button click event to store the user name in a session variable in the code behind file ("User.aspx.cs") and redirects to another page to show the session data. The following is the code snippet for it.

using System;
public partial class User : System.Web.UI.Page
 {
    protected void btnSubmit_Click(object sender, EventArgs e)
     {
       Session["Name"] = txtName.Text;
        Response.Redirect ("UserDetail.aspx");
       }
  }


Retrieving Session Value:

        To retrieve session data I create another web page "UserDetail.aspx" and its code behind page, the Page_Load () event has code to retrieve the session data. As in the following code snippet if the session data exists then the try block is successfully executed otherwise the catch block will be executed.

    using System;
     public partial class UserDetail : System.Web.UI.Page
     {
         protected void Page_Load(object sender, EventArgs e)
         {
           try
           {
            string name = Session["Name"].ToString();
            Response.Write(string.Format("User name is :{0}", name));
           }
          catch (NullReferenceException ex)
          {
            Response.Write(ex.Message +" Because Session doesn't exist");
          }
    }
}

1 February 2014

Types of Sessions

In ASP.NET, there are the following session modes available:
         InProc
         StateServer(Out Process)
         SQLServer
         Custom

         We can choose the session state provider based on which session state we are selecting. When ASP.NET requests for information based on the session ID, the session state and its corresponding provider are responsible for sending the proper information.


The following are session mode along with the provider name:
  •  InProc: In Memory Object.
  •  State server: asp.net _state.exe
  • SQLServer: Database
  • Custom: Custom Provider

            Apart from that, there is another mode off. If we select this option, the session will be disabled for the application. But our objective is to use session, so we will look into the above four session state modes.

Session States

               Session state essentially means all the settings that you have made for your web application for maintaining the session. Session State itself is a big thing. It says all about your session configuration, either in the web.config or from the code-behind. In the web.config, <SessionState> elements are used for setting the configuration of the session. Some of them are Mode, Timeout, StateConnectionString, CustomProvider, etc. I have discussed about each and every section of the connection string. Before I discuss Session Mode, take a brief overview of session events.

web is stateless, which means a new instance of a web page is re-created each time the page is posted to the server. Http is a stateless Protocol ,it can’t hold client information on a page. If the user inserts some information and move to the next page ,that data wil be lost and the user would not be able to retrieve the information


we need to store information .session provides the facility to store information on server memory .it can support any type of object to store along with our custom objects.For Every client ,session data is stored separately,which means session data is stored on per client basis.

Storing and retrieving Sessions

Storing and retrieving values in session are quite similar to that in View State. We can interact with session state with the System.Web.SessionState.HttpSessionState class, because this provides the built-in session object in ASP.NET pages.

The following code is used for storing a value to session:

//Storing UserName in Session
Session["UserName"] = txtUser.Text;

Now, let's see how we can retrieve values from session:

//Check weather session variable null or not
if (Session["UserName"] != null)
{
    //Retrieving UserName from Session
    lblWelcome.Text = "Welcome : " + Session["UserName"];
}
else
{
 //Do Something else
}

We can also store other objects in session. The following example shows how to store a Dataset in session.

//Storing dataset on Session
Session["DataSet"] = _objDataSet;
The following code shows how we to retrieve that Dataset from session: 

//Check weather session variable null or not
if (Session["DataSet"] != null)
{
    //Retrieving UserName from Session
    DataSet _MyDs = (DataSet)Session["DataSet"];
}
else
{
    //Do Something else
} 
Session ID

ASP.NET uses 120 bit identifier to track each session. This is secure enough and can't be reverse engineered. When a client communicates with a server, only the session ID is transmitted between them. When the client requests for data, ASP.NET looks for the session ID and retrieves the corresponding data. This is done in the following steps:
·         Client hits the web site and information is stored in the session.
·         Server creates a unique session ID for that client and stores it in the Session State Provider.
        ·         The client requests for some information with the unique session ID from the server.
·         Server looks in the Session Providers and retrieves the serialized data from the state server and type casts the object.

Asp.net Server Side State Management -Sessions

Web is stateless, which means a new instance of a web page class is re-created each time the page is posted to the server. As we all know, HTTP is a stateless protocol, it can't hold client information on a page. If the user inserts some information and move to the next page, that data will be lost and the user would not be able to retrieve that information.

We need to store information. Session provides a facility to store information on server memory. It can support any type of object to store along with our own custom objects. For every client, session data is stored separately, which means session data is stored on a per client basis.

State management using session is one of the best ASP.NET features, because it is secure, transparent from users, and we can store any kind of object in it. Along with these advantages, sometimes session can cause performance issues in high traffic sites because it is stored in server memory and clients read data from the server. Now let's have a look at the advantages and disadvantages of using session in our web applications.

Storing and retrieving Sessions

Types of Sessions

Advantages:
  • It helps maintain user state and data all over the application.
  • It is easy to implement and we can store any kind of object.
  • Stores client data separately.
  • Session is secure and transparent from the user.

Disadvantages:
  •  Performance overhead in case of large volumes of data/user, because session data is stored in server memory.
  •  Overhead involved in serializing and de-serializing session data, because in the case of State Server and SQL Server session modes, we need to serialize the objects before storing them.


About Asp.net Page life cycle

Asp.net Page Execution :

   As the request comes from Client (Browser) and sends to Server (we call it as Web server) in turn server process the request and sends response back to the client in according to the client request.

Internally Interesting Process Happens. To Know this Process we need to know the architecture of the IIS(Internet Information System)


It Consists of Three Parts
  • Inetinfo.exec
  • ISAPI Filer (Container for Internet Server Application Interface dlls),
  • Worker Process (aspnet_wp.exe)
Inetinfo.exec:
    When Client makes are request first Inetinfo.exec  asp.net request handler with the request.when the request is for the static resources like HTML files or image files inetinfo.exe process the request and sent to client.if the Request contains the extension such as .asp,.aspx then it will processes the request to API filter

ISAPI Filer (Container for Internet Server Application Interface dlls):

    ISAPI filter will have several runtime modules called as ISAPI extensions. To process the request ISAPI filter takes the help of these runtime modules. The runtime module loaded for ASP page is asp.dll. And for ASP.NET page it's ASPNET_ISAPI.dll. From here the request is processed to the "worker process". Worker Process will have several application domain.

Application Domain
      
  The purpose of the application domain is in order to isolate one application from another. Whenever we create a new application, application domains are created automatically by the CLR Host. Worker process will create a block of memory related to particular application. Application domains provide a more secure and versatile unit of processing that the common language runtime can use to provide isolation between applications. 

      Application domains are normally created by runtime hosts. Runtime host is responsible for bootstrapping the common language runtime before an application is run.

       Worker process sends the request to HTTP PIPE line.(HTTP Pipeline is nonetheless collection of .net framework classes). HTTP Pipeline compiles the request into a library and makes a call to HTTP runtime and runtime creates an instance of page class

public class File : System.Web.UI.Page{}

 ASP.Net web page is a class derived from page class, this page class resides in system.web.dll

 After creating instance pf page class HTTP Runtime immediately invokes process request method of page class

Page Req = new Page();
Req.ProcessRequest(); 

Process Request Method does following things:

  1) Intialize the memory
  2) Load the view state
  3) Page execution and post back events
  4) Rendering HTML content
  5) Releasing the memory

Process Request Method executes set of events for page class .These are called as Page life cycle events.

Page Life Cycle Events:


Page_Init

    The server controls are loaded and initialized from the Web form's view state. This is the first step in a Web form's life cycle.


Page_Load

       The server controls are loaded in the page object. View state information is available at this point, so this is where you put code to change control settings or display text on the page.


Page_Pre Render
     
      The application is about to render the page object.


Page_Unload

      The page is unloaded from memory.


Page_Disposed

      The page object is released from memory. This is the last event in the life of a page object.


Page_Error

      when unhandled exception occurs.


Page_Abort Transaction

      A transaction is aborted.


Page_Commit Transaction

      A transaction is accepted.


Page_Data Binding

      A server control on the page binds to a data source. 
      Process Request Method finally renders HTML Page. 


Dependencies:
     
      When the request comes to ASP.net worker process, it will be forwarded to HTTP Application factory. This "Application Factory" will maintain address of the application domains which are currently executing under worker process. If the required virtual directory application domain is unavailable it will create a new application domain. If the application domain is already existing, the request will be forwarded to corresponding AppDomain.

      Application Domain maintains page handler factory class. This will contain all libraries addresses corresponding to webpage. If the requested webpage library is available the instance of the page class is created, if the library is unavailable the request will be forwarded to HTTP pipeline.