473,581 Members | 2,497 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Leaking Database Connections from ASP.NET 2 Web App

Problem:
Database connections are not being reused properly. SP_WHO2 shows upwards
of 200 connections being created per page request. Most connections exist for
60 seconds then close without being reused. A few connections are reused. SQL
System Profiler shows many “Audit Login” and many “RPC: Completed” records
for each page request – often involving the exact same SQL statement called
in exactly the same manner from within a single program loop.

System Description:
• SQL Server 2005 (SP1)
• ASP.NET 2 (2.0.50727)
• IIS 6
• Windows 2003 Server (64bit production, x86 development – both having the
same issue)
• All critical updates applied

Connection String:
• Globally called from web.config
• Never modified
• Provider=SQLNCL I;Data Source=localhos t;Initial Catalog=XDATABA SE;User
Id=XUSERNAME;Pa ssword=XPASSWOR D;DataTypeCompa tibility=80;

Connection Details:
• All database connections connect through a common DB Connection class.
• All database calls are in the form of stored procedures
• All connections are closed and disposed

Page Example:

Dim myOLE As New OLESQL()
myOLE.SetSQL("s pStoredProc " & intSomeParam)
myOLE.SetTableN ame("TableName" )
Dim dsResults As DataSet = myOLE.ExDataSet ()
'Do somthing with the dataset ...

For Each x In xGroup
myOLE.SetSQL("s pStoredProc2 " & x.ToString)
intReturn = myOLE.ExScalar( )

myOLE.SetSQL("s pStoredProc3 " & x.ToString)
myOLE.ExNonQuer y()
Next

myOLE.Close()

Database Connection Class:

Imports Microsoft.Visua lBasic
Imports System.Data.Ole Db
Imports System.Data
Imports System
Imports System.Web.UI.P age

Public Class OLESQL

'Class fields
Public strSQL As String
Public strTableName As String
Public cnMP As OleDbConnection
Public sConnectionStri ng As String =
ConfigurationMa nager.AppSettin gs("MPSQL")

'Initializer
Public Sub New()

cnMP = New OleDbConnection (sConnectionStr ing)
cnMP.Open()

End Sub

'Close the database connection
Public Sub Close()

If cnMP.State = ConnectionState .Open Then
cnMP.Close()
cnMP.Dispose()
cnMP = Nothing
End If

End Sub

'Set the SQL value
Public Sub SetSQL(ByVal inSQL)
strSQL = inSQL
End Sub

'Set the table name value
Public Sub SetTableName(By Val inTableName)
strTableName = inTableName
End Sub

'Execute a non query
Public Sub ExNonQuery()
Dim cmdData As New OleDbCommand(st rSQL, cnMP)
cmdData.Execute NonQuery()
cmdData.Dispose ()
cmdData = Nothing
End Sub

'Execute a scalar function
Public Function ExScalar() As String
Dim cmdData As New OleDbCommand(st rSQL, cnMP)
Dim strOutput As String
strOutput = cmdData.Execute Scalar
Return strOutput
cmdData.Dispose ()
cmdData = Nothing
End Function

'Execute and return a dataset function
Public Function ExDataSet() As DataSet
Dim daGetData As New OleDbDataAdapte r(strSQL, sConnectionStri ng)
Dim dsData As New DataSet()
daGetData.Fill( dsData, strTableName)
Return dsData
daGetData.Dispo se()
daGetData = Nothing
End Function

End Class
Oct 17 '06 #1
4 1956
you have shouldn't open a connecton on your constructor. all routines need a
try/catch to close the connection on errors.

-- bruce (sqlwork.com)

"Sierra" <Si****@discuss ions.microsoft. comwrote in message
news:F7******** *************** ***********@mic rosoft.com...
Problem:
Database connections are not being reused properly. SP_WHO2 shows upwards
of 200 connections being created per page request. Most connections exist
for
60 seconds then close without being reused. A few connections are reused.
SQL
System Profiler shows many "Audit Login" and many "RPC: Completed" records
for each page request - often involving the exact same SQL statement
called
in exactly the same manner from within a single program loop.

System Description:
. SQL Server 2005 (SP1)
. ASP.NET 2 (2.0.50727)
. IIS 6
. Windows 2003 Server (64bit production, x86 development - both having the
same issue)
. All critical updates applied

Connection String:
. Globally called from web.config
. Never modified
. Provider=SQLNCL I;Data Source=localhos t;Initial Catalog=XDATABA SE;User
Id=XUSERNAME;Pa ssword=XPASSWOR D;DataTypeCompa tibility=80;

Connection Details:
. All database connections connect through a common DB Connection class.
. All database calls are in the form of stored procedures
. All connections are closed and disposed

Page Example:

Dim myOLE As New OLESQL()
myOLE.SetSQL("s pStoredProc " & intSomeParam)
myOLE.SetTableN ame("TableName" )
Dim dsResults As DataSet = myOLE.ExDataSet ()
'Do somthing with the dataset ...

For Each x In xGroup
myOLE.SetSQL("s pStoredProc2 " & x.ToString)
intReturn = myOLE.ExScalar( )

myOLE.SetSQL("s pStoredProc3 " & x.ToString)
myOLE.ExNonQuer y()
Next

myOLE.Close()

Database Connection Class:

Imports Microsoft.Visua lBasic
Imports System.Data.Ole Db
Imports System.Data
Imports System
Imports System.Web.UI.P age

Public Class OLESQL

'Class fields
Public strSQL As String
Public strTableName As String
Public cnMP As OleDbConnection
Public sConnectionStri ng As String =
ConfigurationMa nager.AppSettin gs("MPSQL")

'Initializer
Public Sub New()

cnMP = New OleDbConnection (sConnectionStr ing)
cnMP.Open()

End Sub

'Close the database connection
Public Sub Close()

If cnMP.State = ConnectionState .Open Then
cnMP.Close()
cnMP.Dispose()
cnMP = Nothing
End If

End Sub

'Set the SQL value
Public Sub SetSQL(ByVal inSQL)
strSQL = inSQL
End Sub

'Set the table name value
Public Sub SetTableName(By Val inTableName)
strTableName = inTableName
End Sub

'Execute a non query
Public Sub ExNonQuery()
Dim cmdData As New OleDbCommand(st rSQL, cnMP)
cmdData.Execute NonQuery()
cmdData.Dispose ()
cmdData = Nothing
End Sub

'Execute a scalar function
Public Function ExScalar() As String
Dim cmdData As New OleDbCommand(st rSQL, cnMP)
Dim strOutput As String
strOutput = cmdData.Execute Scalar
Return strOutput
cmdData.Dispose ()
cmdData = Nothing
End Function

'Execute and return a dataset function
Public Function ExDataSet() As DataSet
Dim daGetData As New OleDbDataAdapte r(strSQL, sConnectionStri ng)
Dim dsData As New DataSet()
daGetData.Fill( dsData, strTableName)
Return dsData
daGetData.Dispo se()
daGetData = Nothing
End Function

End Class

Oct 17 '06 #2
Agreed.
Public Sub New()

cnMP = New OleDbConnection (sConnectionStr ing)
cnMP.Open()

End Sub
store the connection string, and do not open the connection here
private m_connectionStr ing as string = string.empty

public sub new( connectionStrin g as string )

me.m_connection String = connectionStrin g

end sub

OPEN LATE , CLOSE EARLY.

"bruce barker (sqlwork.com)" <b_************ *************@s qlwork.comwrote
in message news:Od******** ******@TK2MSFTN GP05.phx.gbl...
you have shouldn't open a connecton on your constructor. all routines need
a
try/catch to close the connection on errors.

-- bruce (sqlwork.com)

"Sierra" <Si****@discuss ions.microsoft. comwrote in message
news:F7******** *************** ***********@mic rosoft.com...
Problem:
Database connections are not being reused properly. SP_WHO2 shows
upwards
of 200 connections being created per page request. Most connections
exist
for
60 seconds then close without being reused. A few connections are
reused.
SQL
System Profiler shows many "Audit Login" and many "RPC: Completed"
records
for each page request - often involving the exact same SQL statement
called
in exactly the same manner from within a single program loop.

System Description:
. SQL Server 2005 (SP1)
. ASP.NET 2 (2.0.50727)
. IIS 6
. Windows 2003 Server (64bit production, x86 development - both having
the
same issue)
. All critical updates applied

Connection String:
. Globally called from web.config
. Never modified
. Provider=SQLNCL I;Data Source=localhos t;Initial Catalog=XDATABA SE;User
Id=XUSERNAME;Pa ssword=XPASSWOR D;DataTypeCompa tibility=80;

Connection Details:
. All database connections connect through a common DB Connection class.
. All database calls are in the form of stored procedures
. All connections are closed and disposed

Page Example:

Dim myOLE As New OLESQL()
myOLE.SetSQL("s pStoredProc " & intSomeParam)
myOLE.SetTableN ame("TableName" )
Dim dsResults As DataSet = myOLE.ExDataSet ()
'Do somthing with the dataset ...

For Each x In xGroup
myOLE.SetSQL("s pStoredProc2 " & x.ToString)
intReturn = myOLE.ExScalar( )

myOLE.SetSQL("s pStoredProc3 " & x.ToString)
myOLE.ExNonQuer y()
Next

myOLE.Close()

Database Connection Class:

Imports Microsoft.Visua lBasic
Imports System.Data.Ole Db
Imports System.Data
Imports System
Imports System.Web.UI.P age

Public Class OLESQL

'Class fields
Public strSQL As String
Public strTableName As String
Public cnMP As OleDbConnection
Public sConnectionStri ng As String =
ConfigurationMa nager.AppSettin gs("MPSQL")

'Initializer
Public Sub New()

cnMP = New OleDbConnection (sConnectionStr ing)
cnMP.Open()

End Sub

'Close the database connection
Public Sub Close()

If cnMP.State = ConnectionState .Open Then
cnMP.Close()
cnMP.Dispose()
cnMP = Nothing
End If

End Sub

'Set the SQL value
Public Sub SetSQL(ByVal inSQL)
strSQL = inSQL
End Sub

'Set the table name value
Public Sub SetTableName(By Val inTableName)
strTableName = inTableName
End Sub

'Execute a non query
Public Sub ExNonQuery()
Dim cmdData As New OleDbCommand(st rSQL, cnMP)
cmdData.Execute NonQuery()
cmdData.Dispose ()
cmdData = Nothing
End Sub

'Execute a scalar function
Public Function ExScalar() As String
Dim cmdData As New OleDbCommand(st rSQL, cnMP)
Dim strOutput As String
strOutput = cmdData.Execute Scalar
Return strOutput
cmdData.Dispose ()
cmdData = Nothing
End Function

'Execute and return a dataset function
Public Function ExDataSet() As DataSet
Dim daGetData As New OleDbDataAdapte r(strSQL, sConnectionStri ng)
Dim dsData As New DataSet()
daGetData.Fill( dsData, strTableName)
Return dsData
daGetData.Dispo se()
daGetData = Nothing
End Function

End Class


Oct 17 '06 #3
1) The Microsoft Database Access Application Block ("MS DAAB") works
great and will solve all your db-connect and connection pooling
problems. Download it as part of the MS Enterprise Library. Highly
recommended. Give it a try. The latest version is a huge improvement
over previous versions.

2) In an asp.net app, you shouldn't be making that many round-trips to
the db anyway, regardless of whether your connection pooling is
working. Consider making a single round-trip to the db if possible.
Where you have the "for each x in xGroup" loop, my guess is that you
don't really need to keep coming back to the web server... You could
gather up all of your "x" strings/ints and pass them to the db at once.
Then do something will all of them at once on the db side.

Oct 18 '06 #4
Thanks all.

Bruce and sloans' suggestions cut down on the number of connections created,
but only partially. Installing and using MS DAAB knocked them out of the park
completely without the need for a massive code overhaul. As an added benefit
the DAAB class replicated most of the functionality I was trying to implement
with my DB access class in the first place, but did it better!

"GroupReade r" wrote:
1) The Microsoft Database Access Application Block ("MS DAAB") works
great and will solve all your db-connect and connection pooling
problems. Download it as part of the MS Enterprise Library. Highly
recommended. Give it a try. The latest version is a huge improvement
over previous versions.

2) In an asp.net app, you shouldn't be making that many round-trips to
the db anyway, regardless of whether your connection pooling is
working. Consider making a single round-trip to the db if possible.
Where you have the "for each x in xGroup" loop, my guess is that you
don't really need to keep coming back to the web server... You could
gather up all of your "x" strings/ints and pass them to the db at once.
Then do something will all of them at once on the db side.

Oct 18 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2402
by: Mudge | last post by:
Hi, My hosting provider only allows me to use 50 connections to my MySQL database that my Web site will use. I don't know what this 50 connections means exactly. Does this mean that only 50 visitors to my Web site can access my database through my Web site at one time? Or does this mean that in my code I can only use 50 connections? ...
4
2584
by: dustin lee | last post by:
Over the years I've gotten out of the habit of explicitly closing file objects (whether for reading or writing) since the right thing always seems to happen auto-magically (e.g. files get written to disk with no missing data). I've recently started do the same thing with database connections. I'm wondering if anyone has had trouble with this...
11
3625
by: Rohit | last post by:
Hi, Threads in the .NET Framework 1.1 (and possibly in 1.0 also) leak "Event" handles, by Event handles I mean Win32 Event handles which can be monitored using the ProcessExplorer from www.sysinternals.com, or even simply look at the Handle count in the good old windows TaskManager. To demonstrate the problem, all I did was created a basic...
3
10285
by: Martin B | last post by:
Hallo! I'm working with C# .NET 2.0, implementing Client/Server Applications which are connecting via Network to SQL-Server or Oracle Databases. To stay independent from the underlaying Database I use System.Data.Common.DBConnection and .DBCommand. How can I keep aware from connection losses (network not availeable, db-server not...
35
4823
by: Terry Jolly | last post by:
Web Solution Goal: Have a global database connection Why: (There will be 30+ tables, represented by 30+ classes) I only want to reference the database connection once. I put the connection string in the web.config. I created a class with a static database connection and the class opens and closes the database.
5
2171
by: John | last post by:
I have an ASP.NET 2.0 application developed in VB.net, that accesses an Microsoft Access database. When the database is on the same IIS server all works just fine. BUT when it tried to access the same database on a different server I get a permission error. I've created a shared drive on the other server and give it permission with all...
5
3376
by: Usman Jamil | last post by:
Hi I've a class that creates a connection to a database, gets and loop on a dataset given a query and then close the connection. When I use netstat viewer to see if there is any connection open left, I always see that there are 2 connections open and in "ESTABLISHED" state. Here is the piece of code that I'm using, please tell where I'm...
8
2826
by: BD | last post by:
I am developing C# win form app to work with remote database on SQL Server 2005. Problem scenario is as follows: 1. a form is open that has downloaded dataset to local cache 2. computer is put into stand-by or hibernation 3. later, computer is brought out of stand-by or hibernation 4. when trying to save or close form, SQL exception...
9
6264
by: Gordon | last post by:
I want to add a feature to a project I'm working on where i have multiple users set up on my Postgres database with varying levels of access. At the bare minimum there will be a login user who only has read access to the users table so that users can log in. Once a user has been logged in successfully I want to escalate that user's access...
0
7868
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main...
0
8304
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7899
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6553
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5364
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3805
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3827
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2301
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1403
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.