Category Archives: ASP.NET

ASP.NET 4.0 Features

ASP.NET v4 is released with Visual studio 2010. Web developers are presented with a bewildering range of new features and so Ludmal De Silva has described what he considers to be the most important new features in ASP.NET V4

The focus of Microsoft’s latest ASP.NET 4has mainly been on improving the performance and Search-engine Optimization (SEO). In this article, I’ll be taking a look at what I think are the most important new features in ASP.NET 4.

  • Output cache extensibility
  • Session state compression
  • View state mode for individual control
  • Page.MetaKeyword and Page.MetaDescription properties
  • Response.RedirectPermanent method
  • Routing in ASP.NET
  • Increase the URL character length
  • New syntax for Html Encode
  • Predictable Client IDs
  • Web.config file refactoring
  • Auto-Start ASP.NET applications
  • Improvements on Microsoft Ajax Library

I’ll describe the details of each of these features in the following sections.

Output Cache extensibility

Output caching, or Page-Level Caching, caches the entire rendered markup of an ASP.NET web page for a specific time-period. This has always been one of the essential features for ASP.NET that is used extensively to increase application performance. However there have been some limitations on the feasible extent of caching, because cached content always had to be stored in-memory.

But with ASP.NET 4.0 developers can extend their caching by using Output-cache providers. Developers can now create ‘output-cache providers’ that store the cache contents to any persistence mechanism such as databases, disks, cloud storage and distributed cache engines.

To create a custom output-cache provider, a class which derived from System.Web.Caching.OutputCacheProvider has to be created in ASP.NET 4.0. There are four public methods which you have to override in order to provide your own implementation for add, remove, retrieve and update functionality. Also, the output-cache provider has to be registered in the web.config file as shown in the following screen capture.

You can also set this custom output-cache provider as your default cache mechanism. So once you add the page cache directives all of your contents will be stored using the custom output-cache provider.

Moreover, developers can also dynamically configure which output-cache Provider is used. For example you might want to cache the frequently access pages in the memory for faster access and less frequent pages on disk. By overriding the GetOutputCacheProviderName() method you can configure which output cache provider to use for different requests. These additions to the output-cache can enable developers to write extensible and more efficient cache mechanisms to their web application and thereby improve its responsiveness.

Session State compression

The ASP.NET session state is a mechanism to maintain session-specific data through subsequent requests. In some instances, you may wish to store your session state data in a session-state server or in Microsoft SQL server. However, these two options require you to store data out of the web application’s worker process. To send across to the relevant sources, (State server or Microsoft SQL Server), session-state data has to be serialized. This can take a significant time if the size of the data to be serialized grows significantly. This will increase the latency of the application.

This latency can be reduced if the size of the data is lessened by compression. ASP.NET 4.0 introduces a new mechanism to compress your session state data for both Session-state server and Microsoft SQL server.  Compression can be enabled by setting the compressionEnable to true in the web.config file. In this example, the session-state data will be serialized/desterilized using System.IO.Compression.GZipStream.

<sessionState  mode=”SqlServer”  sqlConnectionString=”data source=DB;Initial Catalog=LudmalDB”  allowCustomSqlDatabase=”true”  compressionEnabled=”true”/>

With this compression feature, developers can often reduce the time it takes for a web application to respond by reducing the size of session data.

View State mode for Individual Controls

View state is a mechanism to maintain page controls’ state on subsequent post backs. ASP.NET stores the view state data for controls that are in the page, even if it’s not necessary. Since the view state data is stored in the pages’ html, the size of the request object will be increased, and make performance worse.

In ASP.NET 4.0, each web control will include a ViewStateMode property which lets developers disable view-state by default, and enable it just for the controls for which a persistence of state is required. ViewStateMode has the following three values;

  • Enabled – enables the view state for this control and any child control.
  • Disabled – disable the view state.
  • Inherits – this specify the control uses the settings from its parent control.

By setting these values in page controls accordingly, a significant performance improvement can be gained in response-time.

Page.MetaKeywords and Page.MetaDescription properties

To increase the relevance of pages in searches, developers should  include relevant “keyword” and “description” meta tags in the html <head> section.     Unfortunately, it takes some time to add these tags for each and every page, and the alternative of adding these tags programmatically was difficult.

But with ASP.NET 4.0, there are two new properties in the code behind file;

  • Page.MetaDescription – equivalent to meta name “description”
  • Page.MetaKeywords – equivalent to meta name “keywords”

This will enable developers to easily and programmatically add the relevant keywords and description.

This will even be useful for Master pages—where you only have to add these properties in the master page. In addition to “keywords” and “description” settings in the code behind, developers can also set these values within the @Page directive.

Response.RedirectPermanent Method

ASP.NET 4.0 has improved SEO (Search-engine Optimization) facilities. Typically developers use Response.Redirect(string url) to handle requests for old URLs. However, this leads to an extra round trip to access the old URLs and so will negatively affect your page-ranking  in search-engines.

ASP.NET 4.0 introduces a new Response.RedirectPermanent(string url) helper method to be used as HTTP 301 (Moved permanently) to handle requests. This will enable search-engines to index URLs and content efficiently and thus improve the page rankings.

Routing in ASP.NET

Routing will let developers serve meaningful URLs to users and map them with the actual physical files. This URL-rewriting mechanism enables developers to write high ranking, search-engine optimized web applications. For example, URL for a page which displays an actual product might look like the following;

By using routing the URL will look like the following

In this way, the URLs will be more easily remembered by users.  It will also significantly improve the search-engine page rankings of the web site.

The following example shows how to implement routing behavior in ASP.NET 4 using new MapPageRoute in Route class.

public class Global : System.Web.HttpApplication {   void Application_Start(object sender, EventArgs e)   {     RouteTable.Routes.MapPageRoute(“ProductsRoute”,       “product/{prodId}”, “~/products.aspx”);       } }

Increase the URL character length

In previous versions of ASP.NET,  URLs were limited to 260 characters in length. But in ASP.NET 4.0 developers have the option of increasing or decreasing  the length of URLs by using  the new maxRequestPathLength and maxQueryStringLength. I’ll illustrate this in an example.

<httpRuntime maxRequestPathLength=”360″ maxQueryStringLength=”1024″ />

In previous versions of ASP.NET you were limited to a fixed set of characters but in v4, developers can also validate the invalid characters by specifying values in the requestPathInvalidChars attribute.

New syntax for Html Encode

Html Encode method encodes a particular string to be displayed in a browser. It is important to encode strings prior it’s rendering in the page, mainly to avoid cross-site script injection (XSS) and HTML injection attacks. However, developers so often forget to call the encode function.

In previous .NET versions, Server.HtmlEncode() or HttpUtility.Encode() methods has been used for string encoding as shown in the following example.

ASP.NET 4.0 introduced new code expression syntax for encoding a particular string.  While the syntax will render the output it also encodes the relevant string as shown below. Note “:” character after opening tag (“<%”).

The new encoding syntax provides an easy and concise way of encoding a particular string.

Predictable Client IDs

ASP.NET 4 now supports a new ClientIDMode property for server control. This property indicates how the Client ID should be generated to a particular control when they render. Client ID has been an important property of the server controls recently—especially with the success of jQuery and other Ajax scripting technologies.  The ClientIDMode property has four values;

  • AutoID – This renders the output as it was before (example: ctl00_ContentPlaceholder1_ListView1_ctrl0_Label1)
  • Predictable (Default)– Trims all “ctl00” strings in the Client Id property.
  • Static – Full control over the Client ID (developer can set the Client Id and it will not be changed after the control renders)
  • Inherit – Allow control to inherit the behavior from its parent control

Client ID property can be set in three different ways;

  • Directly on individual control
  • On the container control. (All the child controls will inherit the settings from parent/container control)
  • Page or User Control level using <%@ Page%>  or <%@ Control %> directives.
  • Directly in the web.config file. All the controls within the web application will inherit the settings.

New ClientIDRowSuffix property on databound controls also gives a similar functionality when rendering an each data item. Once you set the relevant databound property to ClientIDRowSuffix, the value will be added as a suffix to individual row elements.

After the control renders the “State” value will be added as a suffix to each data row element.

Web.config refactoring

Over the past few years web.config file has grown significantly as ASP.NET has used it for more and more features such as routing, Ajax, IIS 7 and version compatibility. This has made it trickier to maintain even with the Visual Studio environment.

With ASP.NET 4, most of the major elements have been moved to the machine.config file. This has enabled developers to maintain a cleaner, less cluttered, web.config file. The new web.config file is either empty, or includes just the .NET framework version details as shown in the following example.

<?xml version=”1.0″?>  <configuration>   <system.web>    <compilation targetFramework=”4.0″ />    </system.web>  </configuration>

Auto-Start ASP.NET Applications

Most application requires initial data load or caching operations to be done before serving the client requests. Typical this happens only when the first user request a page. However, often developers and web administrators write fake requests to keep the application alive to increase the response time. To overcome this issue, ASP.NET 4 introduce new Auto-Start feature. Auto-start feature available with IIS 7.5 and it initialize the ASP.NET application to accept requests.

To configure the Auto-start, you need to configure the “Application pool” worker process by setting the startMode attribute to “AlwaysRunning” in the applicationHost.config file. (C:\Windows\System32\inetsrv\config\applicationHost.config)

As soon you save the applicationHost.config file the worker process will start and initialize the required application operations before the first user has been served.

Improvements on Microsoft Ajax Library

Microsoft Ajax library is client side library which includes high performance server –based user controls and asynchronous page rendering controls. Ajax Library enables developers to easily and quickly write responsive database-driven applications.

There are some significant improvements in the Ajax Library in the ASP.NET 4. of which the most important seem to be…

  • Scrip Loader – the new script loader control enable developers to load all the required scripts only once, thereby eliminating the unnecessary subsequent requests to the server. It supports the ‘lazy load’ pattern which loads scripts only when necessary, and loads scripts in combination, in order to increase the performance of loading a page. It also supports the jQuery script and custom scripts.
  • JQuery IntegrationJQuery is very popular third party javascript library. ASP.NET 4 extensively supports the integration for jQuery by mixing the jQuery and Ajax plug-ins seamlessly.
  • Client Data Access – by using pre-defined client controls inside the Ajax Library, developers can easily build asynchronous data-driven applications. For example client DataView control will display one or more records by consuming a WCF service. All the relevant time-consuming operations will be handled by the Ajax library asynchronously.

Conclusion

ASP.NET 4 includes plethora of new features which will enable developers to write high performance, search-engine friendly web application quickly. The features I’ve mentioned seem to be the most important of all the new features in ASP.NET 4. By upgrading your existing web applications to up-coming ASP.NET 4, you are likely to see an improvement in performance and search-engine optimization.

Advertisements

Dot Net Certification Details: Microsoft MCTS(70-528, 70-536), MCP , MCPD (70-547), MCSE, MVP AND MCSD

Very confusing. Every aspirant has to search a lot to demystified the best exams etc. Here in next few paragraph i am going to demystify Microsoft Certification .net 2.0
In .net Microsoft offers many categories

.net certificationList

* MCTS
* MCPD
* MCSD
* MCP
* MVP

MCTS – The Microsoft Certified Technology Specialist. its comes under .net 2.0 certification. This is the fresh exam and do not require any previous exams to clear it. So a new developer can start from this exam.

Following are the specialization and exams under those

.NET Framework 2.0 Web Applications

one has to pass the following examinations:

* Exam 70–536: TS: Microsoft .NET Framework 2.0 – Application Development Foundation

* Exam 70–528: TS: Microsoft .NET Framework 2.0 – Web-Based Client Development

.NET Framework 2.0 Windows Applications

one has to pass the following examinations:

* Exam 70–536: TS: Microsoft .NET Framework 2.0 – Application Development Foundation

* Exam 70-526: TS: Microsoft .NET Framework 2.0 – Windows-Based Client Development

.NET Framework 2.0 Distributed Applications
one has to pass the following examinations:

* Exam 70–536: TS: Microsoft .NET Framework 2.0 – Application Development Foundation

* Exam 70–529: TS: Microsoft .NET Framework 2.0 – Distributed Application Development
——————————————————————————————–

MCPD -Microsoft Certified Professional Developer

It also comes under .net 2.0 certification
this is next step to the MCTS, so to clear it you firstly need to have MCTS in your tally
Folloings are .NET 2.0, Visual Studio 2005 and SQL Server 2005.

Professional Developer: Web Developer
* Prerequisite: MCTS: .NET Framework 2.0 Web Applications
* Exam 70-547: PRO: Designing and Developing Web Applications by Using the Microsoft .NET Framework

Professional Developer: Windows Developer
Following examinations:

* Prerequisite: MCTS: .NET Framework 2.0 Windows Applications
* Exam 70–548: PRO: Designing and Developing Windows Applications by Using the Microsoft .NET Framework

Professional Developer: Enterprise Applications Developer
Following examinations:

* Prerequisite: MCTS: .NET Framework 2.0 Web Applications
* Prerequisite: MCTS: .NET Framework 2.0 Windows Applications
* Prerequisite: MCTS: .NET Framework 2.0 Distributed Applications
* Exam 70–549: PRO: Designing and Developing Enterprise Applications by Using the
Microsoft .NET Framework

MCP Microsoft Certified Professional. Person having any ms certification is called MCP

MVP Microsoft Most Valuable Professional. This does not require any exam. It is related with how you contributed in the microsoft communties or any site that promote ms technologies. You could be MVP of any of the these c#,asp.net,web services,word,excel,

Exploring Sessions..

This article will give you a very good understanding of session. In this article I have covered basic of session, different types of storing session object, Session behavior in web farm scenarios , Session on Load Balancer etc. I have also explained details of Session Behavior in a Live production environment. Hope you will enjoy this article and provide your valuable suggestion and feedback.

What is Session ?

Web is Stateless, which means a new instance of the 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 the client information on page. If user inserts some information, and move to the next page, that data will be lost and user would not able to retrieve the information. So what we need? we need to store information. Session provides that facility to store information on server memory. It can support any type of object to store along with our custom object. For every client Session data store separately, means session data is stored as per client basis. Have a look at the following diagram.

explor2.jpg

Fig : For every client session data store separately

State Management using session is one of the asp.net best features, because it is secure, transparent from users and we can store any kind of object with in it. Along with advantages, some times session can causes performance issue for heavy traffic sites because its stored on server memory and clients read data from the server itself. Now lets have a look at the advantages and disadvantages of using session in our web application.

Advantages and Disadvantages of Session ?

Following are the basic advantages and disadvantages of using session. I have describe in details with each type of session at later point of time.

Advantages :

  • It helps to maintain user states and data to all over the application.
  • It can easily be implemented and we can store any kind of object.
  • Stores every client data separately.
  • Session is secure and transparent from user.

Disadvantages :

  • Performance overhead in case of large volume of user, because of session data stored in server memory.
  • Overhead involved in serializing and De-Serializing session Data. because In case of StateServer and SQLServer session mode we need to serialize the object before store.

Besides these, there are many advantages and disadvantages of session that are based of session Types. I have Discussed all of them.

Storing and Retrieving values  from Session

Storing and Retrieving values in session are quite similar with ViewState. We can interact with Session State with  System.Web.SessionState.HttpSessionState class, because this provides built in Session Object with Asp.Net Pages.

Following code is used for storing a value to session

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

Now, let see how we can retrieve values from Session

Collapse
//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 some other object in Session. Following Example shows how to store a DataSet in session.

Collapse
         //Storing dataset on Session
        Session["DataSet"] = _objDataSet;

and following code shows how we can retrieve that dataset from the session

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

Ref & for more Information: Read Session Variable Section

Session ID

Asp.Net use 120 bit identifier to track each session. This is secure enough and can’t be reverse engineered. When client communicate with server, only  session id is transmitted, between them. When client request for data, ASP.NET looks on to session ID and retrieves corresponding data. This is done in following steps,

  • Client hits web site and some information is stored in session.
  • Server creates a unique session ID for that clients and stored in Session State Provider .
  • Again client request For some information with that unique session ID from Server.
  • Server,looks on Session Providers, and retrieve the serialized data from state server  and type cast the object .

Just have a look on the pictorial flow,

Fig : Communication of Client, web server, and State Provider

Ref. & for more Information: SessionID in MSDN

Session Mode  and State Provider

In ASP.NET there are following session mode available,

  • InProc
  • StateServer
  • SQLServer
  • Custom

For every session State, there is Session Provider. Following diagram will show you how they are related.

Fig : Session State Architecture

we can choose the session State Provider based on which session state we are selecting. When ASP.NET request for any information based on session ID, session state and its corresponding provider are responsible for sending the proper information based on user. Following tables show, the session mode along with there provider Name.

Session State Mode State Provider
InProc In-Memory Object
StateServer Aspnet_state.exe
SQLServer DataBase
Custom CustomProvider

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 that four session State Mode.

Ref. & for more Information: Session State Providers

Session States

If we consider about session state, It means all the settings that you have made for your web application for maintaining the session. Session State, it self is a big thing, It says all about your session configuration, Either in web.config or from code behind. In web.config, <SessionState> elements used for setting the configuration of session. Some of them are Mode, Timeout, StateConnectionStringCustom provider etc. I have discussed about each and ever section of connection string. Before I discussed Session Mode, just take a brief overview of Session Event

Session Event

There are two types of session events available in asp.net

  • Session_Start
  • Session_End

you  can handle both this event in  global.asax file of  your web application. When a new session initiate session_start event raised and Session_End event raised when a session is abandoned or expired.

Collapse
  void Session_Start(object sender, EventArgs e) 
    {
        // Code that runs when a new session is started

    }

    void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends. 

    }

Ref. and for more Information : Application and Session Events

Session Mode

I have already discussed about the session mode in ASP.NET, Following are the different types of session modes available in ASP.Net.

  • Off
  • InProc
  • StateServer
  • SQLServer
  • Custom

If we set Session Mode="off" in web.config, Session will be disabled to all over the application. For this we need to configure web.config in following way

 

 

 

 

 

InPorc Session Mode :

This is the default session mode in Asp.Net. Its stores session Information in Current Application Domain. This is the best session mode which is based on web application Performance. But main disadvantage is that, It will lose the data if we restart the server. There are some more advantages and disadvantages of InProc session mode. I will come to those points again .

Overview of InProc Session Mode :

As I have already discussed  InProc mode session data will be stored on the current application domain. So It is easily and quickly available.

So, InProc session mode store its session data in a memory object on that application domain. This is handled by worker process in application pool. So If we restart the server we will lose the session data. If Client request for the data , state provide read the data from In-Memory Object and return it to the client. In web.config we have to mention Session mode  and also we have to set the Timeout.

explor3.gif

This Session TimeOut Setting keeps session alive for 30 minute. This can be configurable from Code behind too.

Collapse
Session.TimeOut=30;

There are two type of session events available in asp.net Session_Start() and Session_End. It is the only mode that supports the Session_End() event. These events will call after the session timeout period is over. The general flow for the InProc Session State is some thing like this.

Now, when the Session_End() will call that depends on Session Time Out. This is a very fast mechanism because no serialization occurs for storing and retrieving data, and data are staying inside the same application domain.

When Should we use InProc Session Mode ?

InProc is the default session mode. It can be very helpful for a small web sites and where the number of user are very less, We should avoid InProc in case of Web Garden (I will come to this topic in details) Scenario .

Advantages and Disadvantages

Advantages :

  • It store Session data in memory object of current application domain. So  accessing data is very fast and data is easily available.
  • There is not requirements of serialization to store data in InProc Session Mode.
  • Implementation is very easy, just similar to using View State.

Disadvantages :

although InProc Session is fastest, common and default mechanism, It has lots of limitation.

  • If the worker Process or application domain recycles all session data will be lost.
  • Though its fastest, but more session data and more users can affects performance, because of memory.
  • we can’t use it in web Garden scenarios .
  • This session mode is not suitable for web farm scenarios also.

So as per above discussion, we can conclude InProc is very fast session storing mechanism but suitable for small web application. InProc Session Data will get lost if we Restart the server, application domain recycles It is also not suitable for Web Farm and Web Garden Scenarios.

Now have a look that what are the other option  available to overcome these problem. First Come to StateServer Mode.

StateServer Session Mode :

Overview of StateServer Session Mode :

This is also called Out-Proc session mode. StateServer uses a stand-alone Windows Services, which is Independent to IIS and can also run on a separate server. This session state is totally managed by aspnet_state.exe. This server may runs on the same system, but it’s out side of that main  application domain where your web application is running. This allow if you restart your asp.net process restarted your session data will be alive. This approaches has several disadvantages due to the overhead of serialization and de-serialization, its also increases the cost of data access because of every time when user retrieves session data, our application hits a different process.

 

Configuration for StateServer Session Mode

In StateServer the Session data is stored in a separate Server which is Independent to IIS and Its handled by aspnet_state.exe. This process is run as windows Services. you can start this service from windows MMC or from command prompt.

By default  “Startup Type” of ASP.NET state service is set to manual, we have to set it as  “Automatic”  startup type.

from command from just typing "net start aspnet_state". By default this services listen TCP Port 42424 , but we can change the port from registry editor as given in below picture .

Now have a look on the web.config configuration for StateServer Setting. For State Server Setting we need have to specify the stateConnectionString. This will identify the system that is running state server. By default stateConnectionString used ip as 127.0.0.1 (localhost) and Port 42424.

explor9.gif
When we are using StateServer, we can configure stateNetworkTimeOut attributes to specify the maximum number of seconds to wait for the service to respond before canceling the request. Default time is 10 seconds.

explor10.gif

 

For using StateServer, the object which we are going to store that should be serialized and at the time of retrieving  we need to De-Serialize. I have described it with an Example.

How StateServer Session Mode Works?

We used StateServer Session Mode to avoid unnecessary session data loss during restart of web Server. StateServer is maintained by process aspnet_state.exe as a windows Services. This process maintains the all the session data. But need to serialize the data before storing it in StateServer Session Mode.

As shown in above figure, that client request to the web server, then web server stores the session data on state server. StateServer may be the current system or may be the different system. But it is totally independent of IIS. Destination of StateServer will  depend on the web.config stateConnectionString attribute settings. If we set it as 127.0.0.1:42424, It will store data on that local system itself. For change the StateServer destination, we need to change the IP. and make sure, aspnet_state.exe is up and running on that system. other wise you will get the following exception while trying to store data on session.

When we are storing any object on session, that should be serialized. That data will be stored to StateServer system using State Provider. and at the time of retrieving the data, State provider will return the data. The complete flow is given in the below picture.

Example Of StateServer Session Mode :

Here is one simple example of  using StateServer Session mode. I have created this sample web application directly on the IIS so that we can easily understand its usage.

Step 1 : Open Visual Studio > File > New > Web Sites . Choose Location as HTTP and create the web application .

Now if you open the IIS you will see a Virtual Directory created with the name of your web application , as in my case it is StateServer.

Step 2 : Create s simple UI that will take Roll No and Name of a student . We will store the name and roll in a state server session. I have also create one same class “StudentInfo" .  This class is given below

Collapse
[Serializable]
public class StudentInfo
{
    //Default Constructor
    public StudentInfo()
    {

    }
    /// <summary>
	/// Create object of student Class
	/// </summary>
	/// <param name="intRoll">Int RollNumber</param>
	/// <param name="strName">String Name</param>
    public StudentInfo(int intRoll, string strName)
	{
        this.Roll = intRoll;
        this.Name = strName;
	}

    private int intRoll;
    private string strName;
    public int Roll
    {
        get
        {
            return intRoll;
        }
        set
        {
            intRoll = value;
        }
    }

    public string Name
    {
        get
        {
            return strName;
        }
        set
        {
            strName = value;
        }
    }
}

Now , have a look on the code behind code. I have just added two button one for storing session and another for retrieving session.

Collapse
protected void btnSubmit_Click(object sender, EventArgs e)
    {

        StudentInfo _objStudentInfo = new StudentInfo(Int32.Parse( txtRoll.Text) ,txtUserName.Text);
        Session["objStudentInfo"] = _objStudentInfo;
        ResetField();
    }
    protected void btnRestore_Click(object sender, EventArgs e)
    {
        StudentInfo _objStudentInfo = (StudentInfo) Session["objStudentInfo"];
        txtRoll.Text = _objStudentInfo.Roll.ToString();
        txtUserName.Text = _objStudentInfo.Name;

    }

Step 3 : Please Configure your web.config for state server. As I have already discussed.  And Please make sure aspnet_state.exe is up and running on that configured server.

Step 4 : Run the Application

Enter the data, Click on Submit.

Now there are following Test that I have made which will totally clear your doubts that how exactly StateServer is useful.

First :Remove the [ Serializable ] key word from the studentinfo class and try to run the application. When you will click on Submit Button you will get following error

Which clearly says that you should have to serialize the object before store.

Second: Run the Application, Store data by clicking on Submit Button. Restart IIS

Now, In case of InProc, you have already lost your session data, But Its StateServer, Click on Restore Session, You will get your original data. Because State server data does not depend on IIS. Its keeps it separately.

Third : Stop the aspnet_state.exe from the Windows Services MMC and Submit the Data. You will get following error,

Because your State Server Process is not running.

So, Please keep in mind about those three points .

Advantages and Disadvantages.

So based on the above discussion

Advantages :

  • Its keeps the data separate from IIS so, any Issue with IIS does not hamper Session data.
  • It is useful in web farm and web garden scenarios.

Disadvantages :

  • Process is slow due to Serialization and De-Serialization
  • State Server always need to be up and running.

Now, I am stopping here on StateServer, You will find some more interesting points on Load balancer, Web Farm, Web Garden Section.

Ref & for more Information:

SQL Server Session Mode :

Overview of SQL Server Session Mode :

This session mode provide us more secure and reliable Session management in asp.net. In this session  mode, the Session data is serialized and stored in the SQL Server database.  Main disadvantages of this session storage methods is overhead related with Data Serialization and De-Serialization. It is the best option for using in the web farms.

To setup SQL Server we need to take help of  two sql Script.

  • For Installing: InstallSqlState.sql
  • For Un-Installing: UninstallSQLState.sql

The most easiest way to configure SQL Server, is using aspnet_regsql command.

I have explained the detailed use of these file in configuration section. This is the most useful state management in the web farm scenario.

When should we use SQL Server Session Mode ?

  • SQL Server Session mode is more reliable and secure session state management.
  • Its keeps data in a centralized location (database).
  • We should use SQL server session mode when we need to implement Session with some more security.
  • If  there happens to be  frequent server Restart we can implement SQL server.
  • This is perfect mode that fits in web farm and web garden scenarios (I have explained in details later) .
  • we can use SQL server Session mode when we need to share session between two different application .

Configuration for SQL Server Session Mode

In SQL Server  Session mode, we are storing session data in a SQL Server, so we need to first provide the database connection string in web.config . sqlConnectionString attribute is used to provide the connection string in web.config.

 

After setup the connection string we need to configure the SQL Server. I am explaining how to configure your your SQL server using aspnet_regsql command.

Step 1: From Command prompt, Go to your Framework Version Directory

E.g :c:\windows\microsoft.net\framework\<version>.

Step 2 : Run aspnet_regsql command with following parameters

Have a look on the parameter and there uses

Parameters Description
-ssadd Add support for SQLServer mode session state.
-sstype p P is stands for Persisted. Its persist the session data on server
-S Specify Server Name
-U Specify User Name
-P Specify Password

After run you will get the following message,

that’s all .

Step 3 : Open SQL Server Management Studio, Check, A new database ASPState has been created  and there should be two tables,

  • ASPStateTempApplications
  • ASPStateTempSessions

Now, Just change the configuration string of the State Server Example and Run the same application that  I have explained in State Server.

Just store Roll and User Name and Click on Submit button, and open ASPStateTempSessions Table from SQL Server Management Studio.. WoW… here is your session data,

Now. do the following Test that I have already explained in State Server Mode.

  1. Remove The Serialize Key word from StydentInfo Class
  2. Reset IIS and Click on Restore Session
  3. Stop the SQL Server Services

I think I have explained the SQL Server Session mode well.

Advantages and Disadvantages

Advantages :

  • Session data do not  affected if we restart the IIS.
  • It is the most reliable and secure session management.
  • It keeps data located centrally ,  It can be easily accessible from other application.
  • It is  very useful in web farm and web garden scenarios.

Disadvantages :

  • Processing is very slow in nature.
  • Object serialization and de-serialization creates overhead  for application.
  • As the session data is handled in different server, so we have to take care of SQL server. It should be always up and running.

Ref & for more Information : Read SQL Server Mode

Custom Session Mode

Overview of Custom Session Mode :

Generally we use either of InProc, StateServer or SQL Server  Session mode for our application, but we also  need to know the fundamental of Custom Session mode. This session mode is quite interesting, because Custom session gives full control to us to create every thing even session ID. you can write your own algorithm to generate session ID.

You can implement custom providers that store session data in other storage mechanisms simply by deriving from SessionStateStoreProviderBase Class. You can also Generate New Session Id by Implementing ISessionIDManager.

This are the following methods  are called  during  implementation of Custom Session

In Initialize methods we can set the Custom Provider. This will initialize the connection with that specified provider. SetItemExpireCallback used to set SessionTimeOut, we can register any methods that will call at the time of session expire. InitializeRequest is called on every request and CreateNewStoreData used to create a new instance of SessionStateStoreData .

When should we use Custom Session Mode ?

we can use custom session mode in following of the cases,

  • We want to store session data rather than SQL Server.
  • When we have to use some Existing table to store session data.
  • When we need to create our own session ID.

What configuration do we need for it?

We need to configure our web.config like below,

If you want to Explore some thing more please Check Further study section

Advantages and Disadvantages

Advantages :

  • We can use some existing Table for the store session data, It is useful when we have to use some old database rather than SQL Server.
  • It’s not depending on IIS , So Restarting web server does not make any effects on session data.
  • We can crate our own algorithm for generating Session ID.

Disadvantages :

  • Processing of Data is very slow.
  • Creating a custom state provider is a low-level task that needs to be handled carefully to ensure security.

Its always recommended to use any third party provider rather than creating your own.

Ref and More Information : Custom Mode

If you want to know more about details session Mode please Read this MSDN Article

Overview of Production Deployment

Generally Production environments means when we deploy the application on our live production server. This is a major and Big Challenge for the web developer to deploy there application on Live Server. because in a Big production environment there are no of user and its not possible to handle the load of so many users by a single server. Here the concepts came of Web Farm, Load Balancer , Web Garden etc.

Just few month back I have deployed one of our web application In a live production environment which is accessible by  million of user and there were more than 10 Active Directory, more than 10 Web Server Over  Load Balancer and Many DB Server, Exchange  Server, LCS Server etc. If we look at the number of web server, this is multiple. The major risk involves in multiple server is Session Management. Following picture shows the general diagram for a Production environments.

I will try to explain the different scenario that you need to keep in mind while deploying your application.

Application Pool :

This is one of the most important thing that you should create for your own application in Production environment. Application pools used to separate sets of IIS worker processes that share the same configuration. Application pools enable us to isolate our web application for better security, reliability, and availability. The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected.

Identity Of Application Pool

Application pool identity configuration is an important aspect of security in IIS 6.0  and IIS 7.0, because it determines the identity of the worker process when the process is accessing resource. This Settings comes from IIS 6.0 In IIS 7.0 there are Three predefine Identity , that are same with IIS 6.0.

Applicationpool Identity Description
LocalSystem LocalSystem is a built-in account that has administrative privileges on the server. It can access both local and remote resources. For any kind accessing of server files or resources we have to set the Identity of application pool to Local System.
LocalServices LocalServices Built-in account has privileges of an authenticated local user account. It does not have any network access permission
NetworkServices This is the default Identity of Application Pool NetworkServices has privileges of authenticated local user account.

 

Creating and Assigning Application Pool

Open IIS Console, Right Click on Application Pool Folder > Create New

Give the Application Pool ID and Click Ok.

Now, Right Click on the Virtual Directory (I am using StateServer Web sites) and assign the StateServerAppPool to StateServer Virtual Directory.

So, this StateServer Web sites  will run independently with StateServerAppPool. So any problem related with other application does not affects your Application. This is the main advantages of creating application pool separately.

Web Garden

By default Each Application Pool runs with a Single Worker Process (W3Wp.exe). We can Assign multiple Worker Process With a Single Application Pool. An Application Poll with multiple Worker process called Web Gardens.  Many worker processes with same Application Pool can sometimes provide better throughput performance and application response time. And Each Worker Process Should have there own Thread and Own Memory space.

As Given in Picture, in IIS Server there may be multiple Applicationpool and each application pool having at least a single Worker Process. Web Garden should contain multiple Worker process.

There are some Certain Restriction to use Web Garden with your web application. If we use Session Mode to "in proc", our application will not work correctly because session will be handled by different Worker Process. For Avoid this Type of problem we should have to use Session Mode “out proc" and we can use “Session State Server” or “SQL-Server Session State“.

Main Advantage : The worker processes in a Web garden share the requests that arrive for that particular application pool. If a worker process fails, another worker process can continue to process requests.

How To Create Web Garden ?

Right Click on the Application Pool > Go To Performance Tab > Check Web Garden Section (Highlighted in Picture )

By default it would be 1 , Just change it to more than one .

How Session Depends on Web Garden ?

I have already discuss that, InProc is handled by Worker Process. Its keeps data insides its memory object. Now If we have multiple Worker Process, then It would be very difficult to handled the session . because, Each and every Worker process has it own memory, so If my first request goes to WP1 and its keep my session data and Second Request goes to WP2 and I am trying to retrieve session data, it will not able to return . Which will throw error. So please avoid Web Garden in InProc Session Mode.

we can use StateServer or SQLServer Session mode in case of Web Garden , because I have already explained these two session mode does  not depends on Worker Process . In my example, I have also explain, If you restart the IIS then also you are able to get session data.

In Short ,

Session Mode Recommended
InProc No
StateServer Yes
SQLServer Yes

Web Farm and Load Balancer:

This is the most common term that is used in production deployment . This terms comes, when we are using Multiple Web Server for deploying our product. The main reason behind the scene is to distribute the load over the multiple server. Load balancer is used to distribute the load on those server.

If we check the diagram, Client request the url and it will hit a Load Balancer, which decides which server to access.  Load balancer will distribute the traffic over the all web server.

Now how does it affects  session

Handling Session in Web Farm and Load Balancer Scenarios

Handling session is one of the most challenging job in web farm .

InProc : In InProc session mode, session data stored in In-Memory Object of worker process.  So each and every server have its own Worker process and they keep session data inside the memory.

If One server is  down in time and request come to different server, user is not able to get session data. So, it is not recommended to use InProc in Web Farm .

StateServer :I have already explained that what a state server is, how to configure a  StateServer etc. Now From this Web farm scenarios you can easily understand that how much it is important, because all session data will be stored in a Single location .

Remember, In a web farm, make sure you have the same <machinekey> in all your web servers. and Other things are all same as I have describe earlier.  All web.config having the same configuration (stateConnectionString) for Session State.

SQL Server : This is another approach  even best one that we can use in web farm. We need to configure the data base first. The steps I have already covered .

explor37.jpg

 

as shown in the above picture, all web server session data will be stored in a single SQL Server Database. And it can be easily accessible. Keep one thing in mind, you should serialize object in both state server and SQL Server mode. Any time if one of the web server goes down, Load balancer distribute the loads to other server and that user can able to read session data from server, because data is stored in a centralized DB server.

In summary, we can use either of state server or SQL server session mode in web farm . We should avoid the InProc

Session And Cookies

Clients use cookies to work with session. because the client needs to present the appropriate session ID with each request. we can do it in following ways

Using cookies: ASP.NET creates a special cookies named ASP.NET_SessionId automatically when the session collection is used. This is the default. Session ID is transmitted through that cookies .

Cookie Munging : Some older browser doest not support cookies or user may disable cookies in there browser, in that case ASP.Net  transmitted session ID  in a specially modified (or “munged”) URL.

How Cookie Munging Works ?

When user request for a page on a server, Server  encoded the session id and add it with every  href link  in page. When user click any links ASP.NET decodes that session id and passes it to the page that user requesting. Now the requesting page can retrieve any session variable. This all happens automatically, if ASP.NET detects that the users browser does not support cookies.

How to Implement Cookie Munging ?

For that we have to make session state  Cookie less.

 

Removing Session From Session Variable

Following are the list of methods that are used to removing the session .

Method Description
Session.Remove(strSessionName); Remove an Item from Session State Collection
Session.RemoveAll() Remove all items from session collection
Session.Clear() Remove all items from session collection  Note: There is no difference between Clear and RemoveAll. RemoveAll() calls Clear(), internally.
Session.Abandon() Cancels the Current Session

Enabling and Disabling Session :

For performance optimization we can enable or disable session. because each and every page read and write access of the page, and this involves some performance overhead. So its always better to enable and disable session based on requirements rather than make it enable always. we can  enable and disable the session State in two ways:

  • Page Level
  • Application Level

Page Level :

we can disable session state in page level using EnableSessionState attributes with in Page directive.

explor38.gif

This will disable the session activities for that particular page

Same way we can make it read only also , It will permit to access session data, but it will not allow writing data on session.

explor39.gif

Application Level :

Session state can be disabled for all over the web application using EnableSessionState property in Web.Config .

explor40.gif

Generally we are use Page level, because some of page may not require any session data or may be only read the session data.

Ref. & for more Information : How To Disable ASP.Net Session State in ASP.NET

Summary

Now hope you are familiar with Session, Use of it, how to apply it in web farms etc in ASP.NET 2.0. So as a summary,

  • The In-Process(InProc) Session provider is the fastest method, because  of  everything stored  inside the memory. Session data will be loss if we restart web server  or if Worker Process Recycles. You can use in small web application where number of users are less. Do not use InProc in Web Farm.
  • In StateServer Session modes Session data maintain by aspnet_state.exe. Its keeps session data out of Web server. So any  issue with web server does not affect  session data. You need to Serialized object before storing data  in StateServer Session. we can use it in web farm also.
  • SQLServer Session modes store data in SQL Server, we need to provide the connection string. Here we also need to serialize the data before storing it to session. This is very useful in production environment with web farm mode.
  • we can use Custom provider for custom data source or when we need to use some existing table to store session data. We can also create our custom sessionID in Custom mode. But it is not recommended to create your own custom provider. Its recommended to use any third party provider.