473,769 Members | 6,926 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"Timeout expired" for simple ADO.NET SQL Server query

Hi,

I've made a HttpModule which deals with user authentication. On the first
request in a users session, it fetches data from a SQL Server using the
following code:
using (SqlConnection connection = new
SqlConnection(C onfigurationSet tings.AppSettin gs["Database.Conne ction"]))
{
connection.Open ();
SqlCommand sqlCommand = new SqlCommand("Get AdvisorEnterpri seLogin",
connection);
sqlCommand.Comm andType = CommandType.Sto redProcedure;
sqlCommand.Para meters.Add("@In putUsername",
HttpContext.Cur rent.User.Ident ity.Name);
SqlDataReader reader = sqlCommand.Exec uteReader();
reader.Read();
username = (string) reader["Username"];
password = (string) reader["Password"];
reader.Close();
}

The "GetAdvisorEnte rpriseLogin" procedure is a really simple one, and hardly
takes 0.1 second to run.
However, the first 1-3 times I access the page after a recompile (and once
in a while otherwise), I get the following exception:

Timeout expired. The timeout period elapsed prior to completion of the
operation or the server is not responding. Description: An unhandled
exception occurred during the execution of the current web request. Please
review the stack trace for more information about the error and where it
originated in the code.

Exception Details: System.Data.Sql Client.SqlExcep tion: Timeout expired. The
timeout period elapsed prior to completion of the operation or the server is
not responding.

I also get the exception after not using the system for a while, but I
haven't experienced when the system is "in use", i.e. when the previous
request was no more than a couple of minutes ago.

Does anyone know what could cause this error, and how I can prevent it from
happening?

Regards,
Nils Magnus Englund
Nov 19 '05 #1
3 13995
This can be alleviated by increasing the CommandTimeout. Of course, this
isn't necessarily the best thing to do, but it can be done piecemeal (on a
per-Command basis in your code), in the web.config file, or at a higher
level, although I wouldn't recommend that.

One way to diagnose the issue is to log the time that the Command takes to
execute. This can be done by getting DateTime.Now prior to opening the
Connection, and using DateTime.Subtra ct() after executing the Command, to
get the TimeSpan elapsed during execution. Example (Hope you don't mind if I
didn't cut out all the stuff you're not interested in):

Overloads Shared Function ExecuteSP(ByVal strProcedureNam e As String, _
ByVal UseTransaction As Boolean, ByVal CommandTimeout As Integer, _
ByRef SecondsToRun As Integer, Optional ByVal aryParameters As sParam()
= Nothing, _
Optional ByVal p_strConnection String As String = "") As Boolean

Dim objConn As SqlConnection
Dim objCommand As SqlCommand
Dim objTrans As SqlTransaction = Nothing
Dim strCString As String = p_strConnection String
Dim intCt As Integer
Dim d As System.DateTime = System.DateTime .Now()
Dim ts As TimeSpan

Try
If strCString = "" Then strCString = ConnectionStrin g
objConn = New SqlConnection(s trCString)
objConn.Open()
objCommand = objConn.CreateC ommand()
If UseTransaction Then
objTrans = objConn.BeginTr ansaction()
End If
objCommand.Conn ection = objConn
If UseTransaction Then
objCommand.Tran saction = objTrans
End If
If CommandTimeout > 0 Then objCommand.Comm andTimeout =
CommandTimeout

Try
objCommand.Comm andText = strProcedureNam e
objCommand.Comm andType = CommandType.Sto redProcedure
If Not IsNothing(aryPa rameters) Then
For intCt = 0 To aryParameters.L ength - 1
objCommand.Para meters.Add(aryP arameters(intCt ).Name,
aryParameters(i ntCt).Type).Val ue = aryParameters(i ntCt).Value
objCommand.Para meters(objComma nd.Parameters.C ount -
1).Direction = aryParameters(i ntCt).Direction
objCommand.Para meters(objComma nd.Parameters.C ount -
1).Size = aryParameters(i ntCt).Size
Next
End If
objCommand.Exec uteNonQuery()
If UseTransaction Then
objTrans.Commit ()
End If
Catch ex0 As SqlException
Utilities.LogEr ror(GetSqlExcep tion(ex0))
Utilities.Handl eError(ex0, False, "Exception " & _
" occurred Rolling Back Stored Procedure " & _
strProcedureNam e)
If UseTransaction AndAlso ex0.Message.Ind exOf("Timeout
expired") < 0 Then
Try
objTrans.Rollba ck()
Catch ex1 As SqlException
Utilities.LogEr ror(GetSqlExcep tion(ex0))
Utilities.Handl eError(ex0, False, "Exception " & _
" occurred Rolling Back Stored Procedure " & _
strProcedureNam e)
Return False
Catch invex As InvalidOperatio nException
Utilities.Handl eError(invex, False, _
"InvalidOperati on Exception occurred during
rollback of transaction associated with Stored Procedure '" & _
strProcedureNam e & "'")
Return False
Catch ex As Exception
Utilities.Handl eError(ex, True, "Exception of Type "
& _
ex.GetType().To String() & " occurred Executing
Stored Procedure " & _
strProcedureNam e)
Return False
End Try
End If
Return False
End Try
Return True
Catch ex2 As Exception
Utilities.Handl eError(ex2, True, "Exception of Type " & _
ex2.GetType().T oString() & " occurred Executing Stored
Procedure " & _
strProcedureNam e)
Return False
Finally
CloseConn(objCo nn, objCommand)
If Not IsNothing(objTr ans) Then objTrans.Dispos e()
ts = System.DateTime .Now.Subtract(d )
SecondsToRun = CInt(ts.TotalSe conds)
End Try
End Function

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Neither a follower nor a lender be.

"Nils Magnus Englund" <ni************ *****@orkfin.no > wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
Hi,

I've made a HttpModule which deals with user authentication. On the first
request in a users session, it fetches data from a SQL Server using the
following code:
using (SqlConnection connection = new
SqlConnection(C onfigurationSet tings.AppSettin gs["Database.Conne ction"]))
{
connection.Open ();
SqlCommand sqlCommand = new SqlCommand("Get AdvisorEnterpri seLogin",
connection);
sqlCommand.Comm andType = CommandType.Sto redProcedure;
sqlCommand.Para meters.Add("@In putUsername",
HttpContext.Cur rent.User.Ident ity.Name);
SqlDataReader reader = sqlCommand.Exec uteReader();
reader.Read();
username = (string) reader["Username"];
password = (string) reader["Password"];
reader.Close();
}

The "GetAdvisorEnte rpriseLogin" procedure is a really simple one, and
hardly
takes 0.1 second to run.
However, the first 1-3 times I access the page after a recompile (and once
in a while otherwise), I get the following exception:

Timeout expired. The timeout period elapsed prior to completion of the
operation or the server is not responding. Description: An unhandled
exception occurred during the execution of the current web request. Please
review the stack trace for more information about the error and where it
originated in the code.

Exception Details: System.Data.Sql Client.SqlExcep tion: Timeout expired.
The
timeout period elapsed prior to completion of the operation or the server
is
not responding.

I also get the exception after not using the system for a while, but I
haven't experienced when the system is "in use", i.e. when the previous
request was no more than a couple of minutes ago.

Does anyone know what could cause this error, and how I can prevent it
from
happening?

Regards,
Nils Magnus Englund

Nov 19 '05 #2
"Kevin Spencer" <ke***@DIESPAMM ERSDIEtakempis. com> wrote:
This can be alleviated by increasing the CommandTimeout. Of course, this
isn't necessarily the best thing to do, but it can be done piecemeal (on a
per-Command basis in your code), in the web.config file, or at a higher
level, although I wouldn't recommend that.

Hi Kevin,

Thanks for your reply, but unfortunately, increasing CommandTimeout or
setting it to 0 didn't help at all. When the code doesn't throw a Timeout
exception, the procedure takes under 0.1 seconds to run - which should be
well within the default CommandTimeout (which I believe is 30 seconds)?
Regards,
Nils Magnus Englund


Nov 19 '05 #3
Hi Nils,

It sounds like the problem may be on your SQL Server. You'll have to do some
diagnosis there. Sometimes, for example, a SQL Server can get very busy
doing database backups, Transaction Log backups, or even handling other jobs
or client tasks. Another possible issue might be network latency. If the
network connection goes down, or gets bogged down for some reason, it can
cause the Command to time out eventually. The CommandTimeout is a property
of the SqlCommand class, and indicates how long it will wait for a response.
It does nothing on the SQL Server itself.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Neither a follower nor a lender be.

"Nils Magnus Englund" <ni************ *****@orkfin.no > wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
"Kevin Spencer" <ke***@DIESPAMM ERSDIEtakempis. com> wrote:
This can be alleviated by increasing the CommandTimeout. Of course, this
isn't necessarily the best thing to do, but it can be done piecemeal (on
a per-Command basis in your code), in the web.config file, or at a higher
level, although I wouldn't recommend that.

Hi Kevin,

Thanks for your reply, but unfortunately, increasing CommandTimeout or
setting it to 0 didn't help at all. When the code doesn't throw a Timeout
exception, the procedure takes under 0.1 seconds to run - which should be
well within the default CommandTimeout (which I believe is 30 seconds)?
Regards,
Nils Magnus Englund

Nov 19 '05 #4

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

Similar topics

3
2786
by: Ed Burns | last post by:
Hi. I am trying to disable a user from going back to a previous page and displaying information previously shown. I want to give them the typical "Page has Expired" warning message. I am using Win Server 2003. Does anyone know what you have to do so that the user can only see the page once and not to be able to click back and see a cached page. Thanks! Ed
0
1508
by: Sham Yemul | last post by:
Hello, We developed an application that has many data entry forms and data controls in Vb.net and Sql Server2000 as backend. For this application we created connection object on load event of every form. The application runs on Server machine with no errors. We got some errors when the application/.exe run on client node, There is no error till log-in happens, the log-in form uses connection object. After that , when we click to open...
3
4563
by: Carpe Diem | last post by:
Hello I have an aspx page that loses Session("user") value after a few minutes even after I set <sessionState mode="InProc" cookieless="false" timeout="300"> in web.config and wrote function Session_Start() { Session.Timeout = 3000; } in global.asax
2
4590
by: Chris Langston | last post by:
I have a Web Server running IIS 5 or 6 on Windows 2K and Windows 2003 Server that is experiencing strange shutdown problems. We are using ASP.NET v1.1 and our application is written in VB.NET Here's the scenario: 1. .NET Windows Client on a remote machine makes a web service call to update tables on a Web Server running SQL Server 2000. 2. The Update is updating about 1000 - 3000 records doing simple update statements like "Update...
2
2398
by: Nils Magnus Englund | last post by:
Hi, I've made a HttpModule which deals with user authentication. On the first request in a users session, it fetches data from a SQL Server using the following code: using (SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings)) {
3
1490
by: Agnes | last post by:
My client said when he got "Timeout Expired", once he press the button. whole applciation is quit. I want to "produce the same error " in my development environment but don't know how to do ? Thanks a lot .
20
3488
by: Wes Groleau | last post by:
I was doing update statements in SQL Server 2000. I have a table with over 16 million rows. It came from several hundred delimited text files, and two of the columns are file ID (int) and Line # (int) Structure is X12 (835). For those unfamiliar with that, each file has one to many BPR lines; each BPR line has zero to many CLP lines, each of those has zero to many
1
5878
by: ahmnasa | last post by:
I have a website that has been running for over 1 year now that has never had these issues. Its running MS SQL Server 2005 Express Edition and IIS6 ASP 3 coded. All running from one server. I am starting to randomly get the following errors: Microsoft OLE DB Provider for SQL Server error '80004005' Timeout expired
1
1266
by: anudu | last post by:
hi all, I am developing a system using asp.net(c#). I am using "left" "top" & "Middle" design in my system. I want to set a time out mechanism. when the user has expired the configured time the user is derected to a tomeout mesassage page. at the moment i am using fillowing code in page load metod in all middle pages. if (Session != null) { if (!IsPostBack) {
0
9589
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, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10048
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9996
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8872
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 project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7410
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6674
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5304
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3963
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
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.