जगदीश खोलिया

Wednesday, May 16, 2012

Asp.net frequently asked question


What is the difference between a DLL and an EXE?
In .NET, an assembly may become a DLL or an EXE. Yet, there is a major underlying difference between the two.
An
EXE is an executable file, that may run on its own. Its independant. Where as a DLL is a Dynamic Link Library, that binds to an exe, or another DLL at runtime.

A DLL has an exposed interface, through which members of the assembly may be accessed by those objects that require it.
A
DLL runs in tandem with the application space in memory, as the application references it. Whereas an EXE is independant, and runs as an independant process.


What is the difference between a Thread and Process?
A process is a collection of virtual memory space, code, data, and system resources. A thread is code that is to be serially executed within a process. A processor executes threads, not processes, so each application has at least one process, and a process always has at least one thread of execution, known as the primary thread. A process can have multiple threads in addition to the primary thread. Prior to the introduction of multiple threads of execution, applications were all designed to run on a single thread of execution.

When a thread begins to execute, it continues until it is killed or until it is interrupted by a thread with higher priority (by a user action or the kernel’s thread scheduler). Each thread can run separate sections of code, or multiple threads can execute the same section of code. Threads executing the same block of code maintain separate stacks. Each thread in a process shares that process’s global variables and resources.



What is the difference between Authorization and Authentication?
Both Authentication and Authorization are concepts of providing permission to users to maintain different levels of security, as per the application requirement.

Authentication is the mechanism whereby systems may securely identify their users. Authentication systems depend on some unique bit of information known only to the individual being authenticated and the authentication system.

Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system.

When a user logs on to an application/system, the user is first Authenticated, and then Authorized.

ASP.NET has 3 ways to Authenticate a user:
1) Forms Authentication
2) Windows Authentication
3) Passport Authentication (This is obsolete in .NET 2.0)
The 4th way is "None" (means no authentication)

The Authentication Provider performs the task of verifying the credentials of the user ans decides whether a user is authenticated or not. The authentication may be set using the web.config file.

Windows Authentication provider is the default authentication provider for ASP.NET applications. When a user using this authentication logs in to an application, the credentials are matched with the Windows domain through IIS.

There are 4 types of Windows Authentication methods:
1) Anonymous Authentication - IIS allows any user
2) Basic Authentication - A windows username and password has to be sent across the network (in plain text format, hence not very secure).
3) Digest Authentication - Same as Basic Authentication, but the credentials are encrypted. Works only on IE 5 or above
4) Integrated Windows Authentication - Relies on Kerberos technology, with strong credential encryption

Forms Authentication - This authentication relies on code written by a developer, where credentials are matched against a database. Credentials are entered on web forms, and are matched with the database table that contains the user information.

Authorization in .NET - There are two types:

FileAuthorization - this depends on the NTFS system for granting permission
UrlAuthorization - Authorization rules may be explicitly specified in web.config for different web URLs.
What is the difference between Server.Transfer and Server.Execute?
Both Server.Transfer and Server.Execute were introduced in Classic ASP 3.0 (and still work in ASP.NET).

When Server.Execute is used, a URL is passed to it as a parameter, and the control moves to this new page. Execution of code happens on the new page. Once code execution gets over, the control returns to the initial page, just after where it was called. However, in the case of Server.Transfer, it works very much the same, the difference being the execution stops at the new page itself (means the control is'nt returned to the calling page).

In both the cases, the URL in the browser remains the first page url (does'nt refresh to the new page URL) as the browser is'nt requested to do so.



What is the difference between Server.Transfer and Response.Redirect?
Both "Server" and "Response" are objects of ASP.NET. Server.Transfer and Response.Redirect both are used to transfer a user from one page to another. But there is an underlying difference.
//Usage of Server.Transfer & Response.Redirect
Server.Transfer("Page2.aspx");
Response.Redirect("Page2.aspx");
The Response.Redirect statement sends a command back to the browser to request the next page from the server. This extra round-trip is often inefficient and unnecessary, but this established standard works very well. By the time Page2 is requested, Page1 has been flushed from the server’s memory and no information can be retrieved about it unless the developer explicitly saved the information using some technique like session, cookie, application, cache etc.

The more efficient Server.Transfer method simply renders the next page to the browser without an extra round trip. Variables can stay in scope and Page2 can read properties directly from Page1 because it’s still in memory. This technique would be ideal if it wasn’t for the fact that the browser is never notified that the page has changed. Therefore, the address bar in the browser will still show “Page1.aspx” even though the Server.Transfer statement actually caused Page2.aspx to be rendered instead. This may occasionally be a good thing from a security perspective, it often causes problems related to the browser being out of touch with the server. Say, the user reloads the page, the browser will request Page1.aspx instead of the true page (Page2.aspx) that they were viewing. In most cases, Response.Redirect and Server.Transfer can be used interchangeably. But in some cases, efficiency or usability may be the deciding factor in choosing.



What is the difference between Trace and Debug?
Trace and Debug - There are two main classes that deal with tracing - Debug and Trace. They both work in a similar way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds.

Tracing is actually the process of collecting information about the program's execution. Debugging is the process of finding & fixing errors in our program. Tracing is the ability of an application to generate information about its own execution. The idea is that subsequent analysis of this information may help us understand why a part of the application is not behaving as it should and allow identification of the source of the error.

We shall look at two different ways of implementing tracing in .NET via the System.Web.TraceContext class via the System.Diagnostics.Trace and System.Diagnostics.Debug classes. Tracing can be thought of as a better alternative to the response.writes we used to put in our classic ASP3.0 code to help debug pages.

If we set the Tracing attribute of the Page Directive to True, then Tracing is enabled. The output is appended in the web form output. Messeges can be displayed in the Trace output using Trace.Warn & Trace.Write.

NOTE The only difference between Trace.Warn & Trace.Write is that the former has output in red color. If the trace is false, there is another way to enable tracing. This is done through the application level. We can use the web.config file and set the trace attribute to true. Here we can set <trace enabled=false .../>

Note that the Page Directive Trace attribute has precedence over th application level trace attribute of web.config. While using application level tracing, we can view the trace output in the trace.axd file of the project.



What is the difference between a Public Assembly and a Private Assembly?
An assembly is the basic building block in .NET. It is the compiled format of a class, that contains Metadata, Manisfest & Intermediate Language code.

An assembly may be either Public or Private. A public assembly means the same as Shared Assembly.

Private Assembly - This type of assembly is used by a single application. It is stored in the application's directory or the applications sub-directory. There is no version constraint in a private assembly.

Shared Assembly or Public Assembly - A shared assembly has version constraint. It is stored in the Global Assembly Cache (GAC). GAC is a repository of shared assemblies maintained by the .NET runtime. It is located at C:\Windows\Assembly OR C:\Winnt\Assembly. The shared assemblies may be used by many applications. To make an assembly a shared assembly, it has to be strongly named. In order to share an assembly with many applications, it must have a strong name.

A Strong Name assembly is an assembly that has its own identity, through its version and uniqueness.

In order to convert a private assembly to a shared assembly, i.e. to create a strongly named assembly, follow the steps below...

1) Create a strong key using the sn.exe tool. This is used to created a cryptographic key pair. The key pair that is generated by the Strong Name tool can be kept in a file or we can store it our your local machine's Crytographic Service Provider (CSP). For this, goto the .NET command interpreter, and type the following...
sn -k C:\samplekey.snk
This will create a strong key and save it to the location C:\samplekey.snk 2) If the key is stored in a file, just like we have done above, we use the attribute AssemblyKeyFileAttribute. This belongs to the namespace System.Reflection.AssemblyKeyFileAttribute. If the key was in the CSP, we would make use of System.Reflection.AssemblyKeyNameAttribute.

Go to the assemblyinfo.vb file of your project. Open this file. Make the following changes in this file...
<assembly: assemblykeyfileattribute("C:\samplekey.snk")>

We may write this in our code as well, like this...

Imports System.Reflection
<assembly: assemblykeyfileattribute("C:\samplekey.snk")>
Namespace StrongName
 Public class Sample
 End Class
End Namespace
3) Build your project. Your assembly is now strongly named.
Installing the Shared assembly in GAC...
Go to .NET command interpreter, use the tool gacutil.exe
Type the following...
gacutil /i sampleclass.dll
To uninstall it, use... gacutil /u sampleclass.dll. Visual Studio.NET provides a GUI tool for viewing all shared assemblies in the GAC.

Q) Which exception will catch first and what about finally statement?

try
{
    int b = 0;
    int c = 10 / b;
}
catch (Exception e)
{
}
catch (DivideByZeroException ae)
{
}
finally
{
}

Ans)
Multiple catch blocks are evaluated from top to bottom, but only one catch block is executed for each exception thrown. The order of your catch blocks is important because .NET will go to the first catch block that is polymorphically compatible with the thrown exception. It is important to place catch blocks with the most specific — most derived — exception classes first.

In your example, the 1st catch is type of Exception of which is base class for all exceptions and thereby polymorphically compatible with all thrown exceptions. so 2nd catch never can get execute.

And regarding finally block, it always executes after the try and catch blocks execute. A finally block is always executed, regardless of whether an exception is thrown or whether a catch block matching the exception type is found.

Primary key without clustered index

There are three methods by which we can achieve this.

Method 1:

Using this method we can specify it while creating the table schema itself.

Create Table tblTest
(
Field1 int Identity not null primary key nonclustered,
Field2 varchar(30),
Field3 int null
)
Go

Method 2:

Using this method also we could specify it while creating the table schema. It just depends on your preference.

Create Table tblTest
(
Field1 int Identity not null,
Field2 varchar(30),
Field3 int null
Constraint pk_parent primary key nonclustered (Field1)
)
Go

Method 3:

If at all you already have a table which have a clustered index on a PK field then you might want to opt for this method.

Step 1: Find the contraint name

sp_helpconstraint tblTest

/*
This way we could find out the constraint name.
 Lets assume that our constraint name is PK_tblTest_Name
*/

Step 2: First drop the existing constaint

Alter table tblTest drop constraint PK_tblTest_Name

Step 3: Add the new nonclustered index to that field now

Alter table tblTest add constraint PK_parent1 primary key nonclustered (Field1)

Tuesday, May 15, 2012

Is it possible to store view state in server side?

Yes, we can implement server side viewstate.

For this we have to override two virtual methods LoadPageStateFromPersistenceMedium() and SavePageStateToPersistenceMedium() of System.Web.UI.Page (on your aspx page)

However, it is not straightforward, because a user can visit a page in browser, hit the back button to a previous page and push a button (which would require the viewstate for that page). We have to handle such scenarios carefully.

Sample code:


//overriding method of Page class
protected override object LoadPageStateFromPersistenceMedium()
{
    //If server side enabled use it, otherwise use original base class implementation
    if (ConfigurationManager.AppSettings["ServerSideEnabled"].Equals("true"))
    {
        //Your implementation here.
    }
    else
    {
        return base.LoadPageStateFromPersistenceMedium();
    }
}


protected override void SavePageStateToPersistenceMedium(object state)
{
    //If server side enabled use it, otherwise use original base class implementation
    if (ConfigurationManager.AppSettings["ServerSideEnabled"].Equals("true"))
    {
        //Your implementation here.
    }
    else
    {
        base.SavePageStateToPersistenceMedium(state);
    }
}

Few Object Oriented Question

1. Can we call a base class method without creating instance?
Answer :
Its possible If its a static method.
Its possible by inheriting from that class also.
Its possible from derived classes using base keyword.

2. What is Method Overriding? How to override a function in C#?
Answer :
Use the override modifier to modify a method, a property, an indexer, or an event. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override

3. What’s an abstract class?
Answer :
A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.

4. When do you absolutely have to declare a class as abstract?
Answer :
1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
2. When at least one of the methods in the class is abstract.

5. What is an interface class?
Answer :
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.

6. What happens if you inherit multiple interfaces and they have conflicting method names?
Answer :
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares it is okay.

7. What’s the difference between an interface and abstract class?
Answer :
In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.

8. How is method overriding different from method overloading?
Answer :
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.

9. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?
Answer :
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

10. What are the different ways a method can be overloaded?
Answer :
Different parameter data types, different number of parameters, different order of parameters.

11. Can you prevent your class from being inherited by another class?
Answer :
Yes. The keyword “sealed” will prevent the class from being inherited.

12. What’s the C# syntax to catch any possible exception?
Answer :
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}

13. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
Answer :
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element’s object, resulting in a different, yet identacle object.

14. What’s the advantage of using System.Text.StringBuilder over System.String?
Answer :
StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.

15. What’s the difference between System.String and System.Text.StringBuilder classes?
Answer :
System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

16. What does the term immutable mean?
Answer :
The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

Monday, May 14, 2012

Access the base class method with derived class objects (when using shadowing)

When you are using shadowing if you want to access the base class method with derived class objects how can you access it?

First cast the derived class object to base class type and if you call method it invokes base class method.Please note that it works only when derived class method is shadowed.
observe the bold lines below:

public class BaseClass
{
public void Method1()
{
string a = "Base method";
}
}
public class DerivedClass : BaseClass
{
public new void Method1()
{
string a = "Derived Method";
}
}
public class TestApp
{
public static void main()
{
DerivedClass derivedObj = new DerivedClass();
BaseClass obj2 = (BaseClass)derivedObj;
obj2.Method1(); // invokes Baseclass method

}
}

Friday, May 4, 2012

Count total rows in a table

Number of ways to count rows in a table :  

*) select count(*) from LifeEmailQuotesXML

*) select count(1) from LifeEmailQuotesXML
 
*) select sum(1) from LifeEmailQuotesXML

*) select object_name(id), rows from sys.sysindexes where object_name(id) = 'LifeEmailQuotesXML' and indid < 2

*) exec sp_spaceused 'LifeEmailQuotesXML'

*) DBCC CHECKTABLE('LifeEmailQuotesXML')

*) DBCC UPDATEUSAGE ('BimaExpress','LifeEmailQuotesXML') WITH COUNT_ROWS

What are Generations in Garbage Collector?

Generations in the Garbage Collector is a way of enhancing the garbage collection performance. In .NET, all resources are allocated space (memory) from the heap. Objects are automatically freed from the managed heap when they are no longer required by the application.

When objects are no longer being used by the application, the .NET runtime's garbage collector performs the task of collection, to determine the status of the objects. Necessary operations are performed to relieve the memory, in case the object is no longer in use. This is identified by the GC by examining the metadata of the object. For this, the GC has to know the location of the roots that represent the object. Roots are actually the location of the object on the managed heap. There are two types of memory references, strong & weak. When a root references an object, it is said to be a strong reference as the object is being pointed to by application code. The other type of object, that is not being referenced by the application code is called the weak reference, and this may be collected by the GC. However, this may still be accessed by the application code if required. But for the application to access the weakly referenced object, this has to be converted to a strong reference (and note that this has to be done before the GC collects the weakly referenced object).

So what are Generations in the GC? Its a feature of the GC that enhances its performance. There are 3 Generations...0,1,2.

Generation 0 - When an object is initialized, its in generation 0. These are new objects that have never been played around with by the GC. As and when more objects get created, the process of Garbage Collection is invoked by the CLR.
Generation 1 - The objects that survive the garbage collection process are considered to be in generation 1. These are the old objects.
Generation 2 - As more new objects get created and added to the memory, the new objects are added to generation 0, the generation 1 old objects become older, and so are considered to be in generation 2. Generation 2 is the highest level generation in the garbage collection process. Any further garbage collection process occuring causes the level 1 objects promoted to level 2, and the level 2 objects stay in level 2 itself, as this generation level is the highest level.

So what is the importance & use of the generations process? Its actually the priority the GC gives to objects while freeing objects from the heap. During every GC cycle, the objects in the Generation 0 are scanned first -> Followed by Generation 1 and then 2. This is because the generation 0 objects are usually short term objects, that need to be freed. The newer an object, the shorter its life is. The older an object, longer its life is.

This process also helps in categorizing the memory heap as to where the de-allocation needs to be done first and where next.

Thursday, May 3, 2012

Why finalize for cleanup is not suitable?

Problem with finalize is that garbage collection has to make two rounds in order to remove objects which have finalize methods.
Below figure will make things clear regarding the two rounds of garbage collection rounds performed for the objects having finalized methods.
g1
Figure: – Garbage collection in actions
In this scenario there are three objects Object1, Object2, and Object3. Object2 has the finalize method overridden and remaining objects do not have the finalize method overridden.
Now when garbage collector runs for the first time it searches for objects whose memory has to free. He can see three objects but only cleans the memory for Object1 and Object3. Object2 it pushes to the finalization queue.
Now garbage collector runs for the second time. He see’s there are no objects to be released and then checks for the finalization queue and at this moment, it clears object2 from the memory.
So if you notice that object2 was released from memory in the second round and not first. That is why the best practice is not to write clean up Non.NET resources in Finalize method rather use the DISPOSE.

Friday, April 27, 2012

Difference between function and stored procedure

Functions or UDFs can contain single or multiple SQL statements depending on its type. A Scalar UDF & Inline UDF can only have a single SELECT statement. And a Multi-Statement UDF can contain a body with multiple SQL statements including SELECTS, IF-ELSE, WHILE loops and DMLs but limited to manipulating table variables only.UDFs return a single Scalar value or a Table variable to the calling SELECT statement.

Stored Procedures can contain a single SQL statement or a group of SQL statements with data flow control logic containing IF-ELSE, WHILE loop constructs, TRY-CATCH, transactions, etc.
SPs are used to return one or many result-sets to its calling application.


Below are some common differences between an Function & Stored Procedure:

Functions:
* Cannot be used to change server configuration
* Cannot have transaction within function 
* Not returning output parameter but returns Table variables 
* Can only be used with SELECT statement, JOINS & APPLY (CROSS & OUTER).
* Cannot execute an SP inside a UDF.
* Can only read data, cannot modify the database.
* Cannot use a Temporary Table, only Table Variables can be used.
* Cannot use a Dynamic SQL inside a UDF.
* Can JOIN a UDF in a SELECT statement.
* Cannot be used with XML FOR clause.
* Can be used to create Constraints while creating a table.
* Cannot execute some non-deterministic built-in functions, like GETDATE().

Stored Procedures:
* Have to use EXEC or EXECUTE, cannot be used with SELECT statement.
* Can create table but won’t return Table Variables
* Cannot JOIN a SP in a SELECT statement.
* Can be used to read and modify data.
* Can use Table Variables as well as Temporary Tables inside an SP.
* Can use transactions inside (BEGIN TRANSACTION, COMMIT, ROLLBACK) an SP.
* Can use a UDF inside a SP in SELECT statement.
* Can create and use Dynamic SQL.
* Can use used with XML FOR clause.
* Cannot be used to create constraints while creating a table.
* Can execute all kinds of functions, be it deterministic or non-deterministic.

Wednesday, December 14, 2011

What is the difference between Web Farm and Web Garden ?

I have been asked this question many times by different readers of my blog. They wanted to know about the fundamentals of Web Farms and Web Garden . In this blog post  I am going to explain the what is the exact difference between web farm and web garden, what are the advantages and disadvantages of using them. I have also described how to create web garden in different version of IIS.
Overview :
Visual Studio having its own integrated ASP.NET engine which is used to run the ASP.NET Web application from Visual Studio. ASP.NET Development Server  is responsible for execute all the request and response from client. Now after the end of development, when you want to host the site on some server to allow other peoples to access, concept of web servers comes in between.  A web server is responsible for  provide the response for all the requests that are coming from clients. Below diagram showing the typical deployment structure of a ASP.NET Web application with a single IIS.
2 Clients request for resources and IIS Process the request and send back to clients.
Web Farm :
This is the case, where you have only one web server and multiple clients requesting for the resources from the same server. But when there is huge numbers of  incoming traffic for your web sites, one standalone server is not sufficient to process the request.  You may need to use multiple server to host the application and divide the traffic among them.  This is called “Web Farm” . So when you are hosting your single web site on multiple web server over load balancer called “Web Farm”. Below diagram showing the over all representation of Web Farms.
 Web Farms
In general web farm architecture, a single application is hosted on multiple IIS Server and those are connected with the VIP ( Virtual IP ) with Load Balancer. Load Balancer IP’s exposed to external worlds to access. So whenever some request will come to server from clients, it will first hit the Load Balancer, then based on the traffic on each server LB distributed the request to corresponding web server.  These web server may share same DB server or may be they can use replicated server in the back end.
So, In a single statement, When we host a web application over multiple web server to distributed the load among them  is called Web Farm.
Web Garden :
Now, let’s have a look, what is Web Garden ?  Both the terms  sounds same,  but they are totally different with each other.  Before starting with Web Garden, I hope you have fundamental idea of what is Application Pool and what is Worker Process. 
Just to recall,  When we are talking about requesting processing with in IIS, Worker Process (w3wp.exe ) takes care all of these. Worker Process runs the ASP.Net application in IIS. All the ASP.Net functionality inside IIS  runs under the scope of worker process. Worker Process is responsible for handling all kind of request, response, session data, cache data.  Application Pool is the container of worker process. Application pools is used to separate sets of IIS worker processes and enables a better security, reliability, and availability for any web application.
apppoolsNow, by default each and every Application pool contains a single worker process. Application which contains the multiple worker process called “Web Garden”. Below is the typical diagram for a web garden application.
WebGarden BasicIn the above diagram you can see, on of the application containing the  multiple worker process, which is now a web garden.
So, a Web application hosted on multiple server and access based on the load on servers is called Web Farms and When a single Application pool contain multiple Worker process is called web garden.
Create Web Garden in IIS 6 and IIS 7
Now, I am going to show how you can change the Number of Worker process In both IIS 6 and IIS 7.  For IIS 6,  Right Click on Application Pool > Properties > Goto  Performance Tab.
WebGardenIIS6
In the “Performance Tab” Section you would have one option called “Web Garden” where worker process sets to “1”, you can set the number of worker process that you required.
For IIS 7, Right Click on Application Pool > Go To Advance Settings > In Process Model section, you will have “Maximum Worker Processes” . You can change it more than 1 to make it as web garden.
WebGardenIIS7
In the above image you can also check the definition of Web Garden also.


Advantages of Web Farm and Web Garden :
Now, let’s have a look in to the advantages of both the Web farms and Web Garden.
Advantages of Web Farm
  • It provides high availability. If any of the server in the farm goes down, Load balancer can redirects the requests to other servers.
  • Provides high performance response for client requests.
  • Provides Better scalability of the web application and reduce the failure of application.
  • Session and other resource can be stored in a centralized location to access by the all server.
Advantages of Web Garden:
  • provides better application availability by sharing request between multiple worker process.
  • Web garden use processor affinity where application can swapped out based on preference and tag setting.
  • Less consumption of physical space for web garden configuration.
How to manage session in Web Farm Mode ?
While using session, requests are distributed among different servers. By default session mode is set to In Proc where session data stored inside worker process memory. But, In Web farm mode we can share the session among all the server using a single session store location my making it Out proc (State Server or SQL Server Mode). So, if some of the server goes down and request transferred to the other server by the Load balancer session data should be available for that request.
sessionWebfarmIn the above diagram,  you can see we can both the IIS server sharing the same session data which is stored in out of worker process.
How to manage session in Web Garden Mode ?
When we are using Web garden where request is being taking care by different worker process we have to make the session mode as out process session mode as described earlier. For Web Garden we have configure the out process with in same server but for different worker process.
webgardenSession2
While using Web garden with your application you need do couple of configuration settings in web.config in <process Model> section where you need to set certain properties like cpuMask, RequestLimit, webGarden, ClientConnectCheck etc.
Summary : When we host a web application over multiple web server to distributed the load among them  is called Web Farm and when One application having multiple worker worker process called Web garden.