Is this code correctly closing/disposing connections?

  • Thread starter Thread starter GregGohl
  • Start date Start date
G

GregGohl

Guest
I'm getting the following error during the day sometimes: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

Everything I have read doesn't seem to answer why I'm getting the above error. 2 reasons I found it could happen 1 the query takes too long to happen. I'm 99.9% sure this isn't the case. 2 uncommitted transaction. maybe this is the reason, but I don't quite understand it. I'm not using a stored procedure, it is SQLCommand, so maybe there is a commit that I'm not doing in the below string?

Or, maybe there is a 3rd reason. I have researched it a lot, and I think the problem is because I'm not closing out my connections, and I'm running out of Application Pool connections. I have no idea how or where I can check this.

I have written my best version of an insert query, and just want to know if it is doing everything correctly so I can pretty much copy it through the rest of my code. Should I close the conn or not? Different people have different answers on the web. Because it is in a using? Should/can I close out the cmd?

Here is my code:

protected void insertnotes(string comment)
{
string query = "Insert Into [TblCSA_Journal] (incidentid,logtext, sysmoduser,sysmodtime) Select @incidentid,@logtext, @sysmoduser,@sysmodtime";
string connect = ConfigurationManager.ConnectionStrings["QCModuleConnectionString1"].ToString();
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("incidentid", HFCSAID.Value);
cmd.Parameters.AddWithValue("logtext", comment);
cmd.Parameters.AddWithValue("sysmoduser", oUser.NTID);
cmd.Parameters.AddWithValue("sysmodtime", getglenviewtime().ToString());

cmd.CommandTimeout = 90;
try
{
conn.Open();
cmd.ExecuteScalar();
}
catch (Exception ex)
{
String catchex = ex.ToString();
string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
oErrorEmail.Application_Error(catchex, oUser.UserEmail, Request.Path, method);
Response.Write(ex.Message);
}
finally
{
conn.Close();
conn.Dispose();
}
}
}

Continue reading...
 
Back
Top