-1

I am getting this error

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.

I read this question and it states that the exception is caused because of not closing the connection. However, i close all the connection in my code

This is my code, it is simple

  public partial class index : System.Web.UI.Page
    {

        private static string defaultReason = "reason not selected";
        protected override object SaveViewState()
        {
            //save view state right after the dynamic controlss added
            var viewState = new object[1];
            viewState[0] = base.SaveViewState();
            return viewState;
        }

        protected override void LoadViewState(object savedState)
        {
            //load data frm saved viewstate
            if (savedState is object[] && ((object[])savedState).Length == 1)
            {
                var viewState = (object[])savedState;
                fillReasons();
                base.LoadViewState(viewState[0]);
            }
            else
            {
                base.LoadViewState(savedState);
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                string callIDValue = Request.QueryString["CallID"];
                string callerIDValue = Request.QueryString["CallerID"];
                if (!String.IsNullOrEmpty(callerIDValue))
                {
                    callerID.Value = callerIDValue;
                    if (!String.IsNullOrEmpty(callIDValue))
                    {
                        string query = "INSERT INTO Reason (callerID, callID, reason,  timestamp) VALUES (@callerID, @callID, @reason,  @timestamp)";
                        SqlConnection con = getConnection();

                        SqlCommand command = new SqlCommand(query, con);
                        command.Parameters.AddWithValue("@callerID", callerIDValue);
                        command.Parameters.AddWithValue("@callID", callIDValue);
                        command.Parameters.AddWithValue("@reason", defaultReason);
                        command.Parameters.AddWithValue("@timestamp", DateTime.Now.ToString());
                        try
                        {
                            con.Open();
                            command.ExecuteNonQuery();
                            command.Dispose();
                            con.Close();
                        }
                        catch (Exception ee)
                        {
                            command.Dispose();
                            con.Close();
                            message.InnerHtml = ee.Message;
                        }
                    }
                    else
                    {
                        message.InnerHtml = "Call ID is empty";
                    }
                }
                else
                {
                    callerID.Value = "Undefined";
                    message.InnerHtml = "Caller ID is empty";
                }
                fillReasons();
            }
            else
            {

            }
        }

        private void fillReasons()
        {

            string query = "SELECT * FROM wrapuplist WHERE isEnabled = @isEnabled";
            SqlConnection con = new SqlConnection(getConnectionString());
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.Parameters.AddWithValue("isEnabled", true);
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable results = new DataTable();
            da.Fill(results);
            int numberOfReasons = 0; // a integer variable to know if the number of the reasons becomes able to be divided by four
            HtmlGenericControl div = null;
            foreach (DataRow row in results.Rows)
            {
                numberOfReasons++;

                if ((numberOfReasons % 4) == 1)
                {
                    div = new HtmlGenericControl("div");
                    div.Attributes.Add("class", "oneLine");
                }

                RadioButton radioButton = new RadioButton();
                radioButton.ID = "reason_" + row["reasonName"].ToString();
                radioButton.GroupName = "reason";
                radioButton.Text = row["reasonName"].ToString();

                div.Controls.Add(radioButton);
                if (numberOfReasons % 4 == 0)
                {
                    myValueDiv.Controls.Add(div);
                    //numberOfReasons = 0;
                }
                else if (numberOfReasons == results.Rows.Count)
                {
                    myValueDiv.Controls.Add(div);
                    //numberOfReasons = 0;
                }
            }
            cmd.Dispose();
            da.Dispose();
            con.Close();
        }

        private SqlConnection getConnection()
        {
            return new SqlConnection(ConfigurationManager.ConnectionStrings["vmpcon"].ConnectionString);
        }

        private string getConnectionString()
        {
            return ConfigurationManager.ConnectionStrings["wrapupconnection"].ConnectionString.ToString();
        }

        protected void buttonSaveClose_Click(object sender, EventArgs e)
        {
            var divcontrols = myValueDiv.Controls.OfType<HtmlGenericControl>();
            bool isFound = false;
            RadioButton checkedRadioButton = null;
            foreach (HtmlGenericControl loHTML in divcontrols)
            {
                var checkedRadioButtons = loHTML.Controls.OfType<RadioButton>().Where(radButton => radButton.Checked).ToList();
                foreach (RadioButton lobtn in checkedRadioButtons)
                {
                    if (lobtn.Checked)
                    {
                        isFound = true;
                        checkedRadioButton = lobtn;
                    }
                }
            }


            if (isFound)
            {
                sReasonError.InnerText = "";
                string reason = "";
                reason = checkedRadioButton.Text;
                string callIDValue = Request.QueryString["CallID"];
                string callerIDValue = Request.QueryString["CallerID"];

                if (String.IsNullOrEmpty(callIDValue))
                {
                    message.InnerText = "Call ID is empty";
                }
                else if (String.IsNullOrEmpty(callerIDValue))
                {
                    message.InnerText = "Caller ID is empty";
                }
                else
                {
                    message.InnerText = "";

                    string query2 = "SELECT * FROM Reason WHERE callID = @callID AND reason != @reason";
                    SqlConnection con = getConnection();
                    SqlCommand command2 = new SqlCommand(query2, con);
                    command2.Parameters.AddWithValue("@callID", callIDValue);
                    command2.Parameters.AddWithValue("@reason", defaultReason);
                    con.Open();
                    if (command2.ExecuteScalar() != null)
                    {
                        message.InnerText = "Already saved";
                        command2.Dispose();
                        con.Close();
                    }
                    else
                    {
                        command2.Dispose();
                        con.Close();
                        string notes = taNotes.InnerText;
                        string query = "UPDATE Reason SET reason = @reason, notes = @notes, timestamp = @timestamp WHERE callID = @callID";
                        SqlCommand command = new SqlCommand(query, con);
                        command.Parameters.AddWithValue("@callID", callIDValue);
                        command.Parameters.AddWithValue("@reason", reason);
                        command.Parameters.AddWithValue("@notes", notes);
                        command.Parameters.AddWithValue("@timestamp", DateTime.Now.ToString());
                        try
                        {
                            con.Open();
                            command.ExecuteNonQuery();
                            command.Dispose();
                            con.Close();
                            message.InnerText = "Done Successfully";
                            //ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>");
                            ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true);
                        }
                        catch (Exception ee)
                        {
                            command.Dispose();
                            con.Close();
                            message.InnerText = "Error, " + ee.Message;
                        }
                    }
                }
            }
            else
            {   
                sReasonError.InnerText = "Required";
                message.InnerText = "Select a reason";
                //fillReasons();
            }
        }

    }

as you see, all the connection are being closed, what wrong did I do please?

Community
  • 1
  • 1
Marco Dinatsoli
  • 10,322
  • 37
  • 139
  • 253

1 Answers1

0

Closing connections and disposing should be in a finally block while using a try catch.

or use a using block like the one below using(SqlConnection con = getConnection()) { con.Open(); //Do your operation here. The connection will be closed and disposed automatically when the using scope is exited }

XtremeBytes
  • 1,469
  • 8
  • 12