Joins in SQL Server 2005 Breafly


In this article, we are going to discuss SQL Server Joins.
A join is used to combine columns from two or more tables into a single result set. To join data from two tables you write the names of two tables in the FROM clause along with JOIN keyword and an ON phrase that specifies the join condition. The join condition indicates how two tables should be compared. In most cases they are compares on the base on the relationship of primary key of the first table and foreign key of the second table. In this article I will tell you about three important joins.
1.       Inner Join
2.       Outer Join
I have two tables - Vendor table and Advance table. This is how my database tables and data looks like. I will be using these tables in my samples below.
Vendor table:
Figure 1.
Advance table:
Figure 2.
Now we are going to apply joins on these tables and see the data results.

Inner Joins
An inner join requires each record in the two joined tables to have a matching record. An inner join essentially combines the records from two tables (A and B) based on a given join-predicate. The result of the join can be defined as the outcome of first taking the Cartesian product (or cross-join) of all records in the tables (combining every record in table A with every record in table B) - then return all records which satisfy the join predicate. Actual SQL implementations will normally use other approaches where possible, since computing the Cartesian product is not very efficient. This type of join occurs most commonly in applications, and represents the default join-type.
Example: This is explicit inner join:
Use Vendor
GO
SELECT v.VendorId, v.VendorFName, v.VendorLName, a.royality, a.advance
FROM dbo.Vendor as v
INNER JOIN advance as a
ON v.VendorId = a.VendorId
WHERE v.VendorId <= 5
GO

Output:
Figure 3.
Example: This is implicit inner join:
Use Vendor
GO
SELECT * FROM Vendor, advance
WHERE Vendor.VendorId = advance.VendorId AND Vendor.VendorId <= 5
GO
Output:
Figure 4.
Type of inner joins
1. Equi-Join
An equi-join, also known as an equijoin, is a specific type of comparator-based join, or theta join that uses only equality comparisons in the join-predicate. Using other comparison operators (such as <) disqualifies a join as an equi-join. The query shown above has already provided an example of an equi-join:
Example:
Use Vendor
GO
SELECT * FROM Vendor INNER JOIN advance
ON Vendor.VendorId = advance.VendorId
GO
2. Natural Join
A natural join offers a further specialization of equi-joins. The join predicate arises implicitly by comparing all columns in both tables that have the same column-name in the joined tables. The resulting joined table contains only one column for each pair of equally-named columns.
Example:
Use Vendor
GO
SELECT * FROM Vendor NATURAL JOIN advance
GO
3. Cross Join
A cross join, Cartesian join or product provides the foundation upon which all types of inner joins operate. A cross join returns the Cartesian product of the sets of records from the two joined tables. Thus, it equates to an inner join where the join-condition always evaluates to True or join-condition is absent in statement.
Example:
Use Vendor
GO
SELECT * FROM Vendor CROSS JOIN advance
GO
Use Vendor
GO
SELECT * FROM Vendor, advance
GO

Outer Joins
An outer join retrieves all rows that satisfy the join condition plus unmatched rows in one or both tables. In most cases you use the equal operator to retrieve rows with matching columns. However you can also use any of the other comparison operators. When row with unmatched columns is retrieved any columns from the other table that are included in the result are given null values.
Note1: The OUTER keyword is optional and typically omitted
Note2: You can also code left outer joins and right outer joins using the implicit syntax.
Three types of outer joins.
1. Left Outer Join
The result of a left outer join (or simply left join) for tables A and B always contains all records of the "left" table (A), even if the join-condition does not find any matching record in the "right" table (B). This means that if the ON clause matches 0 (zero) records in B, the join will still return a row in the result but with NULL in each column from B. This means that a left outer join returns all the values from the left table, plus matched values from the right table (or NULL in case of no matching join predicate).
Example:
Use Vendor
GO
SELECT VendorFName, Vendor.VendorId, VendorLName, Advance
FROM Vendor LEFT JOIN advance
ON Vendor.VendorId = advance.VendorId
GO
Output:
Figure 5.

2. Right Outer Join
A right outer join (or right join) closely resembles a left outer join, except with the tables reversed. Every record from the "right" table (B) will appear in the joined table at least once. If no matching row from the "left" table (A) exists, NULL will appear in columns from A for those records that have no match in A.
Example :
Use Vendor
GO
SELECT VendorFName, advance.VendorId, VendorLName, Advance
FROM Vendor RIGHT JOIN advance
ON Vendor.VendorId = advance.VendorId
GO

3. Full outer join
A full outer join combines the results of both left and right outer joins. The joined table will contain all records from both tables, and fill in NULLs for missing matches on either side.
Example: 
Use Vendor
GO
SELECT * FROM Vendor FULL OUTER JOIN advance
ON Vendor.VendorId = advance.VendorId
GO
OUTPUT:

Exploring Session in ASP.Net Breafly


Introduction

First of all I would like to thank all the readers who read and vote for my article. In Beginner's Guide series, I have written some articles on state management. Probably this is my last article on state management. Now coming back to the topic of this article  "Exploring Session in ASP.Net" . 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 customobject. 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 andSQLServer 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
      //Storing UserName in Session
       Session["UserName"] = txtUser.Text;
Now, let 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 some other object in Session. Following Example shows how to store a DataSet in session.
        //Storing dataset on Session
        Session["DataSet"] = _objDataSet;  
and following code shows how we can retrieve that dataset from the 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
        }
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 InformationSessionID 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 ModeState Provider
InProc In-Memory Object
StateServerAspnet_state.exe
SQLServerDataBase
CustomCustomProvider
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 InformationSession 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 ModeTimeoutStateConnectionString,  Custom 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 initiatesession_start event raised and Session_End event raised when a session is abandoned or expired.
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. Inweb.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. 
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 ofuser 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 byaspnet_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 Port42424 , 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 stateConnectionStringattribute 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
[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.
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
-ssaddAdd support for SQLServer mode session state.
-sstype pP is stands for Persisted. Its persist the session data on server
-SSpecify Server Name
-USpecify User Name
-PSpecify 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 fromSessionStateStoreProviderBase Class. You can also Generate New Session Id by ImplementingISessionIDManager.
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 CreateNewStoreDataused 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 thatwhen 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 IdentityDescription
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.
LocalServicesLocalServices Built-in account has privileges of an authenticated local user account. It does not have any network access permission
NetworkServicesThis 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 theStateServerAppPool 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
InProcNo
StateServerYes
SQLServerYes

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 .
MethodDescription
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 inWeb.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.
Hope you have enjoyed the article. Please give your suggestion and Feedback for further  improvement. Again Thanks for Reading .