Sue
Sue

Reputation: 47

Stored procedure executing even with the error message

I'm working with two stored procedures in an ASP.NET button function. While I get an error message based on the results that the invoice number is already dispatched from the other stored procedure, it still moves to the other stored procedure and executes it.

If the user gets this error message:

This invoice num was already dispatched!

then it shouldn't move on to this aspect of the function

protected void Button2_Click(object sender, EventArgs e)
{
    try
    {
        for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
        {
            var row = GridView2.Rows[i];

            CheckBox chk = row.FindControl("chkInvoice") as CheckBox;
            //CheckBox chk = (CheckBox)GridView2.Rows[i].Cells[0].FindControl("CheckBox3");

            if (chk != null && chk.Checked)
            {
                string strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();

                using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
                {
                    objConnection.Open();

                    using (SqlTransaction transaction = objConnection.BeginTransaction())
                    {
                        string SID = GridView2.Rows[i].Cells[3].Text.Trim();
                        SqlDataReader myReader = null;

                        using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
                        {
                            command.CommandType = CommandType.StoredProcedure;

                            command.Parameters.AddWithValue("@invoiceNum", SID);
                            command.Parameters.AddWithValue("@custPONum", GridView2.Rows[i].Cells[4].Text.Trim());

                            myReader = command.ExecuteReader();

                            if (myReader.Read())
                            {
                                string invoice1 = (myReader["status"].ToString());
                                if (invoice1 == "0")
                                {
                                    ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
                                }

                                myReader.Close();
                            }
                        }
                        else if (invoice1=="1")
                        {
                            using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
                            {
                                cmd.CommandType = CommandType.StoredProcedure;

                            cmd.Parameters.AddWithValue("@loadSheetNum", txtDispatchNum.Text);
                            cmd.Parameters.AddWithValue("@invoiceNum", SID);
                            cmd.Parameters.AddWithValue("@removeUser", lblUsername.Text.Replace("Welcome", ""));

                            **int a = cmd.ExecuteNonQuery();**

                            cmd.Dispose();

                            if (a > 0)
                            {
                                dt.Rows.RemoveAt(i);

                                ////Read invoice qty from grid view 2
                                string invoice = GridView2.Rows[i].Cells[5].Text.ToString();
                                decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
                                txtInvoiceTotal.Text = invoiceTotal.ToString();

                                ////Read invoice weight from grid view 2
                                string weight = GridView2.Rows[i].Cells[6].Text.ToString();
                                decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
                                txtQtyWeight.Text = invoiceWeight.ToString();
                                lblError.ForeColor = Color.Green;

                                lblError.Text = "Selected record(s) successfully updated";
                            }
                            else
                            {
                                lblError.ForeColor = Color.Red;
                                lblError.Text = " Record has not yet been recorded";
                            }
                        }

                        //objConnection.Close();
                        transaction.Commit();
                    }
                  }
                }

                //Button2.Visible = false;
                //showData();
                GridView2.DataSource = dt;
                GridView2.DataBind();

                txtInvoiceCount.Text = dt.Rows.Count.ToString();
            }
        }
    }
    catch (Exception ex)
    {
        if (ex.Message.StartsWith("Violation of PRIMARY KEY constraint"))
        {
            lblError.ForeColor = Color.Red;
            lblError.Text = " This invoice number was remove from dispatch sheet before!!";
        }
        else
        {
            // re-throw the error if you haven't handled it
            lblError.Text = ex.Message;
            throw;
        }
    }
}

Upvotes: 0

Views: 153

Answers (2)

John Wu
John Wu

Reputation: 52250

You have a very, very simple logic error, but it is incredibly hard to see because your code is such a mess. Therefore, my answer is:

REFACTOR REFACTOR REFACTOR

It is important to get into the habit of writing short functions and controlling their inputs and outputs. If you don't do this, even a fairly trivial operation like this one gets very confusing and error-prone.

Here is an example of how to organize things. We remove most of the code from the click handler:

protected void DeleteButton_Click(object sender, EventArgs e)
{
    for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
    {
        var row = GridView2.Rows[i];
        if (IsChecked(row))
        {
            var result = ProcessRow(row, i);
            DisplayResult(i, result);
        }
    }
}

Firstly, notice it has a meaningful name. These become very important as your application grows. Also, look how short it is! Where did all the code go? Well, it went into two separate methods, which are now short enough for us to view on one page-- a common requirement that IT organizations impose on their programmers, to avoid spaghetti code.

protected TransactionResult ProcessRow(GridViewRow row, int index)
{
    var SID = GridView2.Rows[index].Cells[3].Text.Trim();
    var custPONum = GridView2.Rows[index].Cells[4].Text.Trim();
    var loadSheetNum = txtDispatchNum.Text;
    var removeUser = lblUsername.Text.Replace("Welcome", "");

    return ExecuteInvoiceTransaction(SID, custPONum, loadSheetNum, removeUser);
}

And

public void DisplayResult(int rowIndex, TransactionResult result)
{
    switch result
    {
        case TransactionResult.Success:
            dt.Rows.RemoveAt(rowIndex);
            DisplayTotals(rowIndex);
            DisplaySuccess("Selected record(s) successfully updated");
            break;

        case TransactionResult.AlreadyDispatched;
            ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
            break;

        case TransactionResult.RecordNotRecorded;
            DisplayError("Record has not yet been recorded");
            break;

        case TransactionResult.AlreadyRemoved:
            DisplayError("This invoice number was remove from dispatch sheet before!!");
            break;
    }
}

These methods in turn call a variety of helper methods, each of which does one thing and one thing only. This could be referred to as separation of concerns, which is really important for structured code.

Here's the rest of the methods:

enum TransactionResult
{
    Success,
    AlreadyDispatched,
    RecordNotRecorded,
    AlreadyRemoved
}

private bool ExecuteSelectStatus(SqlConnection connection, SqlTransaction transaction, string invoiceNum, string custPONum)
{
    using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
    {
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.AddWithValue("@invoiceNum", invoiceNum);
        command.Parameters.AddWithValue("@custPONum", custPONum);
        using (var myReader = command.ExecuteReader())
        {
            if (myReader.Read())
            {
                string invoice1 = (myReader["status"].ToString());
                if (invoice1 == "0")
                {
                    return false;
                }
            }
        }
        return true;
    }
}

private int ExecuteRemoveInvoice(SqlConnection objConnection, SqlTransaction transaction, string loadSheetNum, string invoiceNum, string removeUser)
{
    try
    {
        using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@loadSheetNum", loadSheetNum);
            cmd.Parameters.AddWithValue("@invoiceNum", invoiceNum);
            cmd.Parameters.AddWithValue("@removeUser", removeUser);
            return cmd.ExecuteNonQuery();
        }
    }
    catch (SqlException ex)
    {
        if (ex.Number == 2627) //Primary key violation
        {
            return -1;
        }
    }
}

protected TransactionResult ExecuteInvoiceTransaction(string invoiceNum, string custPONum, string loadSheetNum, string removeUser)
{
    var strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();

    using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
    {
        objConnection.Open();

        using (SqlTransaction transaction = objConnection.BeginTransaction())
        {
            var ok = ExecuteSelectStatus(objConnection, transaction, invoiceNum, custPONum);
            if (!ok) return TransactionResult.AlreadyDispatched;

            var a = ExecuteRemoveInvoice(objConnection, transaction, loadSheetNum, invoiceNum, removeUser);
            switch a
            {
                case -1: 
                    return TransactionResult.AlreadyRemoved;
                case 0:
                    return TransactionResult.RecordNotRecorded;
                default:
                    transaction.Commit();
                    return TransactionResult.Success;
            }
        }
    }
}

public void DisplayTotals(int i)
{
    ////Read invoice qty from grid view 2
    string invoice = GridView2.Rows[i].Cells[5].Text;
    decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
    txtInvoiceTotal.Text = invoiceTotal.ToString();

    ////Read invoice weight from grid view 2
    string weight = GridView2.Rows[i].Cells[6].Text();
    decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
    txtQtyWeight.Text = invoiceWeight.ToString();
}

public void DisplaySuccess(string message)
{
    lblError.ForeColor = Color.Green;
    lblError.Text = message;
}

public void DisplayError(string message)
{
    lblError.ForeColor = Color.Red;
    lblError.Text = message;
}

A few things to note:

  • You don't need to call Dispose() if you are using using.
  • You should always catch the most specific exception possible, per Microsoft's guidance. My example does this.
  • The exception handling for the primary key error is isolated into the method that calls the stored procedure. The overall business logic shouldn't have to know details about the SQL implementation. I've shown how you can identify the specific error based on this post.
  • Because there are four possible outcomes, I added an enumeration called TransactionResult so we could return the status to the caller easily.
  • Some of these methods are short-- just two lines-- and that is OK. The main reason to separate them out is to give them a meaningful name and make the code shorter and easier to read.
  • This code is much more structured but it could still be improved! In many implementations, the code that accesses the database is actually moved to a completely different layer or project.

Upvotes: 1

Gauravsa
Gauravsa

Reputation: 6524

See if this works. Moved your if/else together:

protected void Button2_Click(object sender, EventArgs e)
    {
        try
        {
            for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
            {
                var row = GridView2.Rows[i];

                CheckBox chk = row.FindControl("chkInvoice") as CheckBox;

                if (chk != null && chk.Checked)
                {
                    string strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();

                    using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
                    {
                        objConnection.Open();

                        using (SqlTransaction transaction = objConnection.BeginTransaction())
                        {
                            string SID = GridView2.Rows[i].Cells[3].Text.Trim();
                            SqlDataReader myReader = null;
                            using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
                            {

                                command.CommandType = CommandType.StoredProcedure;

                                command.Parameters.AddWithValue("@invoiceNum", SID);
                                command.Parameters.AddWithValue("@custPONum", GridView2.Rows[i].Cells[4].Text.Trim());
                                myReader = command.ExecuteReader();

                                if (myReader.Read())
                                {

                                    string invoice1 = (myReader["status"].ToString());
                                    if (invoice1 == "0")
                                    {
                                        ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
                                    }

                                    else if (invoice1 == "1")
                                    {
                                        using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
                                        {
                                            cmd.CommandType = CommandType.StoredProcedure;

                                            cmd.Parameters.AddWithValue("@loadSheetNum", txtDispatchNum.Text);
                                            cmd.Parameters.AddWithValue("@invoiceNum", SID);
                                            cmd.Parameters.AddWithValue("@removeUser", lblUsername.Text.Replace("Welcome", ""));

                                            int a = cmd.ExecuteNonQuery();
                                            cmd.Dispose();

                                            if (a > 0)
                                            {
                                                dt.Rows.RemoveAt(i);

                                                ////Read invoice qty from grid view 2
                                                string invoice = GridView2.Rows[i].Cells[5].Text.ToString();
                                                decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
                                                txtInvoiceTotal.Text = invoiceTotal.ToString();

                                                ////Read invoice weight from grid view 2
                                                string weight = GridView2.Rows[i].Cells[6].Text.ToString();
                                                decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
                                                txtQtyWeight.Text = invoiceWeight.ToString();
                                                lblError.ForeColor = Color.Green;

                                                lblError.Text = "Selected record(s) successfully updated";
                                            }
                                            else
                                            {
                                                lblError.ForeColor = Color.Red;
                                                lblError.Text = " Record has not yet been recorded";
                                            }
                                        }
                                        //objConnection.Close();
                                        transaction.Commit();
                                    }


                                }
                            }

                            GridView2.DataSource = dt;
                            GridView2.DataBind();
                            txtInvoiceCount.Text = dt.Rows.Count.ToString();
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            if (ex.Message.StartsWith("Violation of PRIMARY KEY constraint"))
            {
                lblError.ForeColor = Color.Red;
                lblError.Text = " This invoice number was remove from dispatch sheet before!!";
            }
            else
            {
                // re-throw the error if you haven't handled it
                lblError.Text = ex.Message;
                throw;

            }
        }
    }

}

Upvotes: 0

Related Questions