Saturday, July 28, 2012

Value type polymorphism

.NET value types are objects descending from Object; but, they cannot inherit from other types. They can implement interfaces. Thus, primitives—such as Int32— can implement the IComparable interface, for example, making them comparable.

How to set PopUp Window size of current Page

window.resizeTo(iWidth, iHeight) 

How to set PopUp Window size of current Page

window.resizeTo(iWidth, iHeight) 

Suppose there is two versions of a assembly, how your application will decide which version to use?

  In web.config under binding give old version and new version

Will finally blocks be executed if returning from try or catch blocks


Yes, the finally block is executed however the flow leaves the try block - whether by reaching the end, returning, or throwing an exception.The return value is determined before the finally block is executed though, so if you did this:

int Test()  
{  
    int result = 4;  
    try  
    {  
        return result;  
    }  
    finally  
    {  
        // Attempt to change value result  
        result = 1;  
    }  
}
  
the value 4 will still be returned, not 1 .- the assignment in the finally block will have no effect the return result but it will be executed.A finally block will always be executed and this will happen before returning from the method, so you can safely write code

ASP.net button text to wrap to second line?

Some times we have more matter to write on Asp.net Button and the button becomes longer in width.. if we make its width small then text will be truncated (complete text will not be visible). so to do this here is solution:Lets say you want to write following line on page in this way:Submit here if you are an Engineerto write text in above format in asp button write it in below format:Submit here if you are an 
 Engineerso the answer is use : 
 to new line in asp button

What is XHTML? what is its advantages?


XHTML Elements Must Be Properly Nested

In HTML, some elements can be improperly nested within each other, like this:
< b >< i >This text is bold and italic< /b >< /i >

In XHTML, all elements must be properly nested within each other, like this:
< b >< i >This text is bold and italic< /i >< /b >

Note: A common mistake with nested lists, is to forget that the inside list must be within < li > and < /li > tags.

This is wrong:
< ul >
< li >Coffee< /li >
< li >Tea
< ul >
< li >Black tea< /li >
< li >Green tea< /li >
< /ul >
< li >Milk< /li >
< /ul >

This is correct:
< ul >
< li >Coffee< /li >
< li >Tea
< ul >
< li >Black tea< /li >
< li >Green tea< /li >
< /ul >
< /li >
< li >Milk< /li >
< /ul >

Notice that we have inserted a < /li > tag after the < /ul > tag in the "correct" code example.
XHTML Elements Must Always Be Closed

Non-empty elements must have a closing tag.

This is wrong:
< p >This is a paragraph
< p >This is another paragraph

This is correct:
< p >This is a paragraph< /p >
< p >This is another paragraph< /p >

Empty Elements Must Also Be Closed

Empty elements must also be closed.

This is wrong:
A break: < br >
A horizontal rule: < hr >
An image: < img src="happy.gif" alt="Happy face" >

This is correct:
A break: < br / >
A horizontal rule: < hr / >
An image: < img src="happy.gif" alt="Happy face" / >

XHTML Elements Must Be In Lower Case

Tag names and attributes must be in lower case.

This is wrong:
< BODY >
< P >This is a paragraph< /P >
< /BODY >

This is correct:
< body >
< p >This is a paragraph< /p >
< /body >

XHTML Documents Must Have One Root Element

All XHTML elements must be nested within the < html > root element. Child elements must be in pairs and correctly nested within their parent element.

The basic document structure is:
< html >
< head > ... < /head >
< body > ... < /body >
< /html >
HTML Vs. XHTML

Both languages come in three flavors: Frameset, Transitional and Strict. The “strict” version is strongly recommended by the W3C for regular documents. Using strict versions removes problematic elements as well as forcing a significant separation between the structure of your document and its presentation. Transitional versions allow deprecated elements to assist those implementers to upgrade smoothly their software or their content.
Using the right tool for the job

Is there any advantage to using HTML 4.01 over XHTML 1.0? There is no simple answer and the benefits you will gain are tied to how you’re using the language in a given situation.

Switching from HTML 4.01 to XHTML 1.0 brings almost no direct benefits for the visitors of your Web site; still, there are several good reasons for Web authors to make the switch:
XHTML is easier to maintain

XML syntax rules are far more rigorous than HTML. As a result, XHTML makes authors work more precisely, having to address issues such as:

* all elements and attribute names must appear in lower case
* all attribute values must be quoted
* non-Empty Elements require a closing tag
* empty elements are terminated using a space and a trailing slash
* no attribute minimization is allowed
* in strict XHTML, all inline elements must be contained in a block element

In HTML, case, quotes, termination of many elements and uncontained elements are allowed and commonplace. The margin for errors in HTML is much broader than in XHTML, where the rules are very clear. As a result, XHTML is easier to author and to maintain, since the structure is more apparent and problem syntax is easier to spot.
XHTML is XSL ready 
as you are probably aware by now, XHTML 1.0 is the reformulation of HTML 4.01 in XML. Therefore, XHTML documents are hypertext documents and XML documents. A powerful technology has been developed at W3C to manipulate and transform XML documents: the Extensible Style sheet Language Transformations (XSLT). This technology is tremendously useful to create various new resources automatically from an XHTML document. For example

* You can create a table of contents for a long document
* Get a quick overview of a page by listing its languages and structural outlines! See the Semantics extractor for this page, created by W3C QA Working Group member Dominique HazaĆ«l-Massieux
* You can provide a printable version of your documents by using the XSL-FO features of XSL
* You can produce an RSS feed directly from your page, check out the QA RSS feed to see this in action

XHTML is easier to teach and to learn

The syntax rules defined by XML are far more consistent than those found in HTML and therefore easier to explain than the SGML rules on which HTML is based.
XHTML is ready for the future

When the new version of XHTML becomes a recommendation, XHTML 1.0 documents will be easily upgradable to this new version, to allow to take advantages of its exciting new features. It’s likely that an XSLT style sheet will be available by then to help you move your XHTML 1.0 (strict) documents to XHTML 2.0 documents.

What is difference between Custom Controls and User Controls?


Difference between user controls and custom controls in .net (vb, c# net with asp.net)
User controls:

It is newly concept in .net it same like as inheritance concept in oops. In asp.net the base class is  system.web.ui.page object When ever creating user control that will be converting as a class, and this class become Subclasses of System.web.ui.page class at compile time User control extension with .ascx
Let us see program how build (at end I will mention difference between user control and
Custom control)

Now this save as labeltextbox.ascx (user control). Now this user control can be used for any page in your web application

Custom control:
Creating user controls, which are essentially reusable small web pages,
You can also create your own compiled custom controls.
There are three ways to create custom controls:
1) Create a derived custom control by deriving from an existing control.
2) Create a composite control by grouping existing controls together into a new compiled control.
3) Create a full custom control by deriving from System.Web.UI.WebControls.WebControl

Composite controls are most similar to user controls. The key difference is that composite
Controls are compiled into a DLL and used as you would any server control.
Let us programmatically that will help how to build:

Let us see differences
User control
1) Reusability web page
2) We can’t add to toolbox
3) Just drag and drop from solution explorer to page (aspx)
4) U can register user control to. Aspx page by Register tag
5) A separate copy of the control is required in each application
6) Good for static layout
7) Easier to create
8)Not complied into DLL
9) Here page (user page) can be converted as control then
We can use as control in aspx
Custom controls
1) Reusability of control (or extend functionalities of existing control)
2) We can add toolbox
3) Just drag and drop from toolbox
4) U can register user control to. Aspx page by Register tag
5) A single copy of the control is required in each application
6) Good for dynamics layout
7) Hard to create
8) Compiled in to dll.



What method do you use to explicitly kill a user Session?


Abandon 
The Abandon method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out.
Syntax Session.Abandon

Remarks 
When the Abandon method is called, the current Session object is queued for deletion, but is not actually deleted until all of the script commands on the current page have been processed. This means that you can access variables stored in the Session object on the same page as the call to Abandon, but not in any subsequent Web pages.
For example, in the following script, the third line prints the value Mary. This is because the Session object is not destroyed until the server has finished processing the script.
<%
Session.Abandon
Session("MyName") = "Mary"
Reponse.Write(Session("MyName"))
%>

Contents.Remove 
The Remove method deletes a specific item from the Session object's Contents collection. Syntax
Session.Contents.Remove( Item|Index )

Parameter 
Item - The name of the member to remove from the collection.
Index - The index entry for the member to remove from the collection.

Remarks 
The Contents.Remove method takes either a string or an integer as an input parameter. If the input parameter is a string, the method will search the contents collection for an item with that name and remove it. If the input parameter is an integer, the method counts that number of items from the start of the collection, and removes the corresponding item.

Example 
The following example adds and removes a variable called myName to the Session.Contents collection.
<%
Session("myName") = " "
Session.Contents.Remove("myName")
%>

Contents.RemoveAll 
The RemoveAll method deletes all items that have been added to the Session object's Contents collection.
Syntax
Session.Contents.RemoveAll ()

Example 
The following example removes all items that have been added to the Session.contents collection:
<%Session.Contents.RemoveAll()%>

How will decide the design consideration to take a Datagrid , datalist or repeater? OR What’s difference between Datagrid , Datalist and repeater?


Many make a blind choice of choosing datagrid directly , but that's not the right way.

Datagrid provides ability to allow the end-user to sort, page, and edit its data. But it comes at a cost of speed.Second the display format is simple that is in row and columns.

Real life scenarios can be more demanding that With its templates, the DataList provides more control over the look and feel of the displayed data than the DataGrid.It offers better performance than datagrid Repeater control allows for complete and total control. With the Repeater, the only HTML emitted are the values of the databinding statements in the templates along with the HTML markup specified in the templates—no "extra" HTML is emitted, as with the DataGrid and DataList. By requiring the developer to specify the complete generated HTML markup, the Repeater often requires the longest development time.But repeater does not provide editing features like datagrid so everything has to be coded by programmer . However, the Repeater does boast the best performance of the three data Web controls.

Repeater is fastest followed by Datalist and finally datagrid.
A Datagrid, Datalist and Repeater are all ASP.NET data Web controls.
They have many things in common like DataSource Property , DataBind Method ItemDataBound and ItemCreated.

When you assign the DataSource Property of a Datagrid to a DataSet then each DataRow present in the DataRow Collection of DataTable is assigned to a corresponding

DataGridItem and this is same for the rest of the two controls also.But The HTML code generated for a Datagrid has an HTML TABLE element created for the particular DataRow and its a Table form representation with Columns and Rows. For a Datalist its an Array of Rows and based on the Template Selected and the
RepeatColumn Property value We can specify how many DataSource records should appear per HTML < table > row. In short in datagrid we have one record per row, but in datalist we can have five or six rows per row.
For a Repeater Control,The Datarecords to be displayed depends upon the Templates specified and the only HTML generated is the due to the Templates.
In addition to these , Datagrid has a in-built support for Sort,Filter and paging the Data ,which is not possible when using a DataList and for a Repeater Control we would require to write an explicit code to do paging.

What is the .Net framework?


.Net framework is the technology on which .Net applications are developed and deployed. 
The framework consist of three main components –

1. CLR (Comman Langauge Runtime) 
2. Unified Classes (Framework Base Classes) 
3. User and Program Interface (ASP.Net, Winforms)

What is a runtime host in ASP.Net?


.Net framework supports different type of applications like Web, windows, console etc,.  Each type of application needs a runtime host to start it. This runtime host loads the runtime into a process, creates the application with in the process and loads the application code into the process. Runtime hosts included in .Net framework are
ASP.Net: It loads the runtime that can handle a web request into the process. ASP.NET also creates an application domain for each Web application that will run on a Web server.

Microsoft Internet Explorer: It creates an application domain to run managed controls.
Shell executables: When ever a runtime executable is launched from the shell, this executable invokes the corresponding runtime host.

Special folders in ASP.Net


With the release of ASP.NET 2.0, Microsoft has greatly increased the power of ASP.Net by introducing a suite of new features and functionalities.

ASP.Net defines several special folders. When a new Web site is created the App_Data folder is created by default; it can contain a SQL Server 2005 Express Edition database, another database, or an XML data file that will be used in the Web site.

These folders are also data directories.

~:App_Browsers  folder - Contains browser definitions (.browser files) files that ASP.Net uses to identify individual browsers and determine their capabilities. Browser definition files are used to determine the client browser capabilities. These files are often used to help support mobile application.
~:App_Data folder - App_Data folder is used to store file that can be used as database files (.mdf, .mdb and xml files). The user account that is used to run the application (for example, the local ASPNET account) has permissions to read, write, and create files in this folder. Various ASP.NET application features, such as the providers for membership and roles, as well as the Web Site Administration Tool, are configured to work with the App_Data folder specifically.

~:Bin folder - Contains compiled assemblies (.dll files), for code that you want to reference in your application, as in earlier versions of Visual Studio. Any classes represented by code in the Bin folder are automatically referenced in your Web site.

~:App_LocalResources folder - Contains .resx files that are bound to a specific page. You can define multiple .resx files for each page, each .resx file representing a different language or language/culture combination.

~:App_GlobalResource folder - Like the App_LocalResources folders, but contains .resx files that are not bound to a specific page. Resource values in .resx files in the App_GlobalResource folders can be accessed programmatically from application code.

~:App_Code folder - Contains source code files. The code is compiled as part of your application and is referenced automatically. The App_Code folder works much like the Bin folder, except that you can put source code in it instead of compiled code. While you are working in Visual Web Developer, the source code in the App_Code folder is compiled dynamically so that IntelliSense can reference any classes defined in the files.

~:App_Themes folder - Contain sub-folders that each defines a specific theme or look and feel for you Web site. Sub-folders consist of a collection of files (such as .skin, .css and image files) that define the appearance of ASP.Net Web pages and controls.

~:App_WebReferences folder - Contains files used to create a reference to a Web service (in the same project or external to the project), including .disco, .xsd, .discomap and .wsdl files.

Note: Special folders can be added to a Web site from the Visual Studio menu system. Typically this involves right-clicking the Web Application project and selecting Add ASP.NET folder.

What is Difference between ScriptManager & ScriptManagerProxy



ScriptManager
A server control that makes script resources available to the browser, including the Microsoft AJAX Library and the functionality that enables partial-page rendering.


ScriptManagerProxy


A server control that enables nested components to add script and service references if the page already contains a ScriptManager control.

Difference between website project and webapplication project in VS2008


In the web**site** project,  you typically work off a directory on your diskThere is no "project" file that defines the project's structure. Anything that's in that directory and any of its subdirectories automatically becomes part of your site - which can be a good or a bad thing.

A website project usually doesn't live inside a namespace, e.g. any code in your App_Code subdirectory will typically not have a namespace associated with it, which makes it sort of tricky and messy to use and reference from other places.

The web**application** project on the other hand is a real, true-blue projectcomplete with a project file and all. Anything that's in your project file will become  part of your project - if you want to add something, you have to do so explicitly - it's not just automagically part of your project just because it's in your project directory. Again - this can be a good thing or a bad thing, depending on your style of development.

In my personal opinion, I would prefer the web application over the web site, mainly for the fact that I have more and more explicit control over what happens. A file doesn't just get added to my project (and potentially wreck havoc) just because it's lying around on disk. I have namespace and all - I have more control over what happens, when it happens

Difference between <%# Bind(””) %> and <%# Eval(””) %>

EVal is one way binding, Bind is two wayIf you bind a value using Eval, it is like a read only. You can only view the data.If you bind a value using Bind, and if you do some change on the value it will reflect on the database alsoso when ever you just want to show metter on grid that time you should use Eval and if you want that user should be able to change the content and that should be reflect in database then we should use BindConclusion:Bind is Two way binding so data will go in both way from Database to Application and Application to Database.Eval is One way binding so data will go in one way only, which is database to Application

What is the maximum possible length of a query string?


Many of times this question have been asked while interview or we also should know that how much characters a query string can contain....

Although the specification of the HTTP protocol does not specify any maximum length, practical limits are imposed by web browser and server software.

Microsoft Internet Explorer (Browser)

Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. In my tests, attempts to use URLs longer than this produced a clear error message in Internet Explorer.

Firefox (Browser)

After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. I stopped testing after 100,000 characters.

Safari (Browser)

At least 80,000 characters will work. I stopped testing after 80,000 characters.

Opera (Browser)

At least 190,000 characters will work. I stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable, copyable and pasteable URL in the location bar even at 190,000 characters.

Apache (Server)

My early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. I used the current up to date Apache build found in Red Hat Enterprise Linux 4. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.

Microsoft Internet Information Server (Server)

The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.

Perl HTTP::Daemon (Server)

Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.

What is use of === and !== in javascript




=== and !== are strict comparison operators:JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
Two numbers are strictly equal when they are numerically equal (have the same number value).

NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
Two Boolean operands are strictly equal if both are true or both are false.
Two objects are strictly equal if they refer to the same Object.
Null and Undefined types are == (but not ===).






Constants in .NET


There are two types of constants available in c#:
Compile-time constants and runtime constants. They have different behaviors and
using wrong one will cost you performance or correctness.
But Runtime constants are always preferable over
compile-time constants. Though the compile-time constants are slightly faster
but they are not flexible with compare to runtime constants.
The compile-time constants are preferable when performance
is really required and you don’t have any requirements to change the value of
that constant.
Compile-time constant are declared using “const” keyword:
Eg: public const int a=10;
Run-time constants are declared using “readonly” keyword:
Eg: public readonly int a=10;



       CONSTANT                                          READONLY
compile-time – “Const”
run-time – “readonly”
compile-time


constant can be declared at class 


level
Run-time
constant can be declared at class level
compile-time


constant can be declared at

method 

level
Run-time
constant Cannot be declared at method level
A compile-time constant is 


replaced with the value of that

constant in object code.


Eg: 

public const int a=10; 

int b=20;   
if(b==a)   
compiles to the same IL as if you   had written this:   
if(b==10)// means instead of     comparing with variable ‘a’ it  
will write its value in compiler-    generated IL. Which increase     speed but for  
various situations its not     preferable.   
Runtime constants are evaluated at runtime. The IL generated
when you reference a read-only constant references the “readonly “
variable,
not the value.
Eg:
public const int a=10;
int b=20;
if(b==a)
compiles to the same IL as if you had written this:
if(b==a)// so instead of placing its value as like it do with
“const”,  its place variable for “readonly” variables in compiler-generated
IL.
compile-time constant cannot     initialize using thenew operator,  
even when the type being   initialized is a value type.  
runtime constants can be of any type, They
must
be initialized using constructor, or using initializer.
Compile-time constants can be   used only for primitive types  
(built-in integral and floating-    point types), enums, or strings.  

These are the only types that     enable you to assign meaningful  
constant values in initializers.  

As we know that for “const” type   in compiler-generated IL the  
variables get replaces with vales   so,these primitive types are the   only ones  
that can be replaced with literal    values. in the compiler-generated   IL.
runtime
constants can be of any type.
Read-only values are also constants, in that they cannot be
modified after the constructor
has executed. But read-only values are different in that they
are assigned at runtime.
Compile-time constants are much    more better in performance but     less flexible with compare    
to run-time constants.    
Run-time constants are much more flexible but its performance is slower with compare to compile-time constants.
Compile-time constants are, by   definition, static    
constants.    
readonly values can be used for instance constants,
storing different values for each instance of a class type.
Every time application assembly    need to be rebuilt whenever    library assembly which contains      constant gets its constant value    changed ( as the compiler-      generated IL contains values of      compile-time constants instead of   
     referring variable)  
No need to rebuild Application assembly which is referring a library assembly which contains run-time constants whose value is changed and its assembly is rebuilt.


The final advantage of using const over readonly is
performance: Known constant values can generate slightly more efficient code
than the variable accesses necessary for readonly values.
However, any gains are slight and should be weighed against the decreased
flexibility. Be sure to profile performance differences before giving up the
flexibility.



Difference in GET and FORM method in posting data


We can send data to the data processing page by both the GET and POST methods of a form. Both methods are used in form data handling where each one has some difference on the way they work. We will discuss some of the differences. 

As you have seen there is a character restriction of 255 in the URL. This is mostly the old browsers restriction and new ones can handle more than that. But we can't be sure that all our visitors are using new browsers. So when we show a text area or a text box asking users to enter some data, then there will be a problem if more data is entered. This restriction is not there in POST method. 

In GET method data gets transferred to the processing page in name value pairs through URL, so it is exposed and can be easily traced by visiting history pages of the browser. So any login details with password should never be posted by using GET method. 

As the data transfers through address bar ( URL ) there are some restrictions in using space, some characters like ampersand ( & ) etc in the GET method of posting data. We have to take special care for encoding ( while sending ) and decoding ( while receiving ) data if such special characters are present. 

There are some special cases where advantage of using GET method is , one can store the name value pairs as bookmark and directly use them by bypassing the form. 

What is difference between Private and Sealed Classes


Sealed Class:

"Sealed" keyword provide us facility to prevent a class to be inherited by other classes, so "Sealed" classes cannot be inherited by any other class.
You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.
"Sealed" class can have constructor, and they can only be used by its object (non-static methods).

Private Class:
Private class cannot be used directly under any namespace, means we can only create private class as a nested class, to make it available only to class to whom its nested.
the only/mostly use of Private class/structure is to create a user-defined type, which you wants to be accessible to that class only. 
NOTE:Nested/inner class can be public also and that can be accessible to inherited class or by object where as private nested/inner class is only accessible to its outer class .

Connection Pooling


Table of Contents

· ADO.NET Connection Pooling at a Glance
· Connection Pool Creation
· Connection Pool Deletion / Clearing Connection Pool
· Controlling Connection Pool through Connection String
o Sample Connection String with Pooling Related Keywords
· Simple Ways to View Connections in the Pool Created by ADO.NET
· Common Issues/Exceptions/Errors with Connection Pooling
· Points to Ponder
· Other Useful Reads/References on Connection Pooling
· Wrapping up

ADO.NET Connection Pooling at a Glance

Establishing a connection with a database server is a hefty and high resource consuming process. If any application needs to fire any query against any database server, we need to first establish a connection with the server and then execute the query against that database server.
Not sure whether you felt like this or not; when you are writing any stored proc or a query, the query returns the results with better response time than the response time, when you execute that same query from any of your client applications. I believe, one of the reasons for such behavior is the overheads involved in getting the desired results from the database server to the client application; and one of such overheads is establishing the connection between the ADO.
Web applications frequently establish the database connection and close them as soon as they are done. Also notice how most of us write the database driven client applications. Usually, we have a configuration file specific to our application and keep the static information like Connection String in it. That in turn means that most of the time we want to connect to the same database server, same database, and with the same user name and password, for every small and big data.
ADO.NET with IIS uses a technique called connection pooling, which is very helpful in applications with such designs. What it does is, on first request to database, it serves the database call. Once it is done and when the client application requests for closing the connection, ADO.NET does not destroy the complete connection, rather it creates a connection pool and puts the released connection object in the pool and holds the reference to it. And next time when the request to execute any query/stored proc comes up, it bypasses the hefty process of establishing the connection and just picks up the connection from the connection pool and uses that for this database call. This way, it can return the results comparatively faster.
Let us see Connection Pooling Creation Mechanism in more detail.

Connection Pool Creation

Connection pool and connection string go hand in hand. Every connection pool is associated with a distinct connection string and that too, it is specific to the application. In turn, what it means is – a separate connection pool is maintained for every distinct process, app domain and connection string.
When any database request is made through ADO.NET, ADO.NET searches for the pool associated with the exact match for the connection string, in the same app domain and process. If such a pool is not found, ADO.NET creates a new one for it, however, if it is found, it tries to fetch the usable connection from that pool. If no usable free connection is found in the pool, a new connection is created and added to the pool. This way, new connections keep on adding to the pool till Max Pool Size is reached, after that when ADO.NET gets request for further connections, it waits for Connection Timeout time and then errors out.
Now the next question that arises is - How is any connection released to the pool to be available for such occasions? Once any connection has served and is closed/disposed, the connection goes to the connection pool and becomes usable. At times, connections are not closed/disposed explicitly, these connections do not go to the pool immediately. We can explicitly close the connection by using Close() or Dispose() methods of connection object or by using the using statement in C# to instantiate the connection object. It is highly recommended that we close or dispose (don't wait for GC or connection pooler to do it for you) the connection once it has served the purpose.

Connection Pool Deletion / Clearing Connection Pool

Connection pool is removed as soon as the associated app domain is unloaded. Once the app domain is unloaded, all the connections from the connection pool become invalid and are thus removed. Say for example, if you have an ASP.NET application, the connection pool gets created as soon as you hit the database for the very first time, and the connection pool is destroyed as soon as we do iisreset. We'll see it later with example. Note that connection pooling has to do with IIS Web Server and not with the Dev Environment, so do not expect the connection pool to be cleared automatically by closing your Visual Studio .NET dev environment.
ADO.NET 2.0 introduces two new methods to clear the pool: ClearAllPools and ClearPool. ClearAllPoolsclears the connection pools for a given provider, and ClearPool clears the connection pool that is associated with a specific connection. If there are connections in use at the time of the call, they are marked appropriately. When they are closed, they are discarded instead of being returned to the pool.
Refer to the section "Simple Ways to View Connections in the Pool Created by ADO.NET" for details on how to determine the status of the pool.

Controlling Connection Pool through Connection String

Connection string plays a vital role in connection pooling. The handshake between ADO.NET and database server happens on the basis of this connection string only. Below is the table with important Connection pooling specific keywords of the connection strings with their description.



Name
Default
Description
Connection Lifetime
0
When a connection is returned to the
 pool, its creation time is compared with 
the current time, and the connection is 
destroyed if that time span (in seconds) 
exceeds the value specified 
byConnection Lifetime. A value of zero 
(0) causes pooled connections to have 
(1) the maximum connection timeout.
Connection Timeout
15
Maximum Time (in secs) to wait for a 
free connection from the pool
Enlist
'true'
When true, the pooler automatically 
enlists the connection in the creation 
thread's current transaction context. 
Recognized values aretrue, false, yes
and no. Set Enlist = "false" to ensure 
that connection is not context specific.
Max Pool Size
100
The maximum number of connections
 allowed in the pool.
Min Pool Size
0
The minimum number of connections 
allowed in the pool.
Pooling
'true'
When true, the SQLConnection object is
 drawn from the appropriate pool, or if it 
is required, is created and added to the 
appropriate pool. Recognized values 
are true, false, yes, and no.
Incr Pool Size
5
Controls the number of connections that 
are established when all the connections 
are used.
Decr Pool Size
1
Controls the number of connections that 
are closed when an excessive amount of 
established connections are unused.







* Some table contents are extracted from Microsoft MSDN Library for reference.
Other than the above mentioned keywords, one important thing to note here. If you are using Integrated Security, then the connection pool is created for each user accessing the client system, whereas, when you use user id and password in the connection string, single connection pool is maintained across for the application. In the later case, each user can use the connections of the pool created and then released to the pool by other users. Thus using user id and password are recommended for better end user performance experience.

Sample Connection String with Pooling Related Keywords

The connection string with the pooling related keywords would look somewhat like this
 Collapse | Copy Code
initial catalog=Northwind; Data Source=localhost; Connection Timeout=30; 
User Id=MYUSER; Password=PASSWORD; Min Pool Size=20; Max Pool Size=200; 
Incr Pool Size=10; Decr Pool Size=5;

Simple Ways to View Connections in the Pool Created by ADO.NET

We can keep a watch on the connections in the pool by determining the active connections in the database after closing the client application. This is database specific stuff, so to see the active connections in the database server we must have to use database specific queries. This is with the exception that connection pool is perfectly valid and none of the connections in the pool is corrupted.
For Microsoft SQL Server: Open the Query Analyser and execute the query : EXEC SP_WHO.
For Oracle : Open SQL Plus or any other editor like PL/SQL Developer or TOAD and execute the following query --SELECT * FROM V$SESSION WHERE PROGRAM IS NOT NULL.
All right, let us do it with SQL Server 2000:
1. Create a Sample ASP.NET Web Application
2. Open an instance of Query Analyzer and run the EXEC SP_WHO query. Note the loginname column, and look for MACHINENAME\ASPNET. If you have not run any other ASP.NET application, you will get no rows withloginname as MACHINENAME\ASPNET.
3. On Page load of default startup page, add a method that makes a database call. Say your connection string is"initial catalog=Northwind; Min Pool Size=20;Max Pool Size=500; data source=localhost; Connection Timeout=30; Integrated security=sspi".
4. Run your ASP.NET application
5. Now repeat Step 2 and observe that there are exactly 20 (Min Pool Size) connections in the results. Note that you made the database call only once.
6. Close the Web page of your Web application and repeat step 2. Observe that even after you closed the instance of the Web page, connections persist.
7. Now Reset the IIS. You can do that by executing the command iisreset on the Run Command.
8. Now Repeat Step 2 and observe that all the 20 connections are gone. This is because your app domain has got unloaded with IIS reset.

Common Issues/Exceptions/Errors with Connection Pooling

1. You receive the exception with the message: "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached" in your .NET client application.
This occurs when you try using more than Max Pool Size connections. By default, the max pool size is 100. If we try to obtain connections more than max pool size, then ADO.NET waits for Connection Timeout for the connection from the pool. If even after that connection is not available, we get the above exception.
Solution(s):
1. The very first step that we should do is – Ensure that every connection that is opened, is closed explicitly. At times what happens is, we open the connection, perform the desired database operation, but we do not close the connection explicitly. Internally it cannot be used as an available valid connection from the pool. The application would have to wait for GC to claim it, until then it is not marked as available from the pool. In such case, even though you are not using max pool size number of connection simultaneously, you may get this error. This is the most probable cause of this issue.
2. Increase Max Pool Size value to a sufficient Max value. You can do so by including "Max Pool Size = N;" in the connection string, where N is the new Max Pool size.
3. Set the pooling Off. Well, this indeed is not a good idea as connection pooling puts a positive performance effect, but it definitely is better than getting any such exceptions.
2. You receive the exception with the message: "A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - Shared Memory Provider: )" in your ASP.NET application with Microsoft SQL Server.
This occurs when Microsoft SQL Server 2000 encounters some issues and has to refresh all the connections and ADO.NET still expects the connection from the pool. Basically, it occurs when connection pool gets corrupted. What in turn happens is, ADO.NET thinks that the valid connection exists with the database server, but actually, due to database server getting restarted it has lost all the connections.
Solution(s):
1. If you are working with .NET and Oracle using ODP.NET v 9.2.0.4 or above, you can probably try adding"Validate Connection=true" in the connection string. Well, in couple of places, I noticed people saying use "validcon=true" works for them for prior versions on ODP.NET. See which works for you. With ODP.NET v 9.2.0.4, "validcon=true" errors out and "Validate Connection=true" works just fine.
2. If you are working with .NET 2.0 and Microsoft SQL Server, You can clear a specific connection pool by using the static (shared in Visual Basic .NET) method SqlConnection.ClearPool or clear all of the connection pools in an appdomain by using the SqlConnection.ClearPools method. Both SqlClient and OracleClient implement this functionality.
3. If you are working with .NET 1.1 and Microsoft SQL Server:
1. In the connection string, at run time, append a blank space and try establishing the connection again. What in turn it would do is, a new connection pool would be created and will be used by your application, In the meantime the prior pool will get removed if it's not getting used.
2. Do exception handling, and as soon as you get this error try connection afresh repeatedly in the loop. With time, ADO.NET and database server will automatically get in sync. 
Well, I am not totally convinced with either approach, but frankly speaking, I could not get any better workable solution for this so far.
3. Leaking Connections
When we do not close/dispose the connection, GC collects them in its own time, such connections are considered as leaked from pooling point of view. There is a strange possibility that we reach max pool size value and at that given moment of time without actually using all of them, having couple of them leaked and waiting for GC to work upon them. This would actually lead to the exception mentioned above, even if we are not using max pool size number of connections.
Solution:
1. Ensure that we Close/Dispose the connections once its usage is over.

Other Useful Reads/References on Connection Pooling

Wrapping Up

In a nutshell, connection pooling can increase the performance of any application by using active connections of the pool for consecutive requests, rather than creating a new connection each time. By default, ADO.NET enables and uses connection pooling due to its positive impact. And at the same time, the developer who is the best judge of his/her application, can configure the connection pooling features, or can even switch it off, based on the applications need by simply using power keywords of connection string.
Please spare some time to rate and provide feedback about this article. Your couple of minutes can help in enhancing the quality of this article.
If interested, click here to view all my published articles.