locked
ASP.net, C#, Retries inside Try, Fail, Finally RRS feed

  • Question

  • User1045460610 posted

    I'm looking for an efficient way to allow retries to insert a record only 3 times and record the record of the attempts in a table. It looks like I can just count the number of retries and if over limit return. What's the method in c# to return after the retry limit counter has been reached and show the error message "Too many attempts" on the web page?

    code excerpt from listing below
    int count = cmd.ExecuteNonQuery();
    if (count == 1)
    lblMsg.Text = "Attendance Code[" + txtAttendanceCode.Text + "] [" + txtCourseCode.Text + "] has been added to log (Reporting.dbo.attendance)!"; //record logging of attendance code
    //count retries, if more than 3, stop inserting, go to else, too many tries

    else
    lblMsg.Text = "Could not add Code to log!"; 
    //lblMsg.Text = "Too many attempts";

    code listing
    using System;

    using System.Data;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;

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

    protected void Page_LoadComplete(object sender, EventArgs e)
    {

    {


    SqlConnection con = new SqlConnection(Database.ConnectionString);
    try
    {
    var returnUrl = Request.Params["ReturnUrl"];
    var hostID = Request.Params["HostID"];
    if (string.IsNullOrWhiteSpace(hostID))
    {
    if (!string.IsNullOrWhiteSpace(returnUrl))
    Response.Redirect(returnUrl);

    throw new Exception("Variable \"HostID\" not found in query params");
    }

    con.Open();

    var query = @"select distinct u.hostid as StudentID
    ,u.ID as UserID
    ,sd.scheduledaysid as CourseID
    ,sd.status
    ,sd.minutes
    ,sm.crs_cde as CourseCode
    ,sm.SHORT_CRS_TITLE_1 as CourseTitle
    ,sm.yr_cde
    ,sm.trm_cde
    ,sd.startTime AS CourseStartTime
    ,sd.startTime
    ,CONCAT(u.LastName, ', ',u.FirstName) AS StudentName
    ,u.Email
    ,nm.FIRST_NAME
    ,nm.MIDDLE_NAME
    ,CONCAT(nm.LAST_NAME, ', ',nm.FIRST_NAME) AS InstructorName
    from ics_net.dbo.ScheduleDays as sd
    inner join ics_net.dbo.lms_section as s on
    sd.sectionid = s.SectionID
    inner JOIN ics_net.dbo.LMS_Course AS c WITH (NOLOCK) ON s.CourseID = c.CourseID
    inner join tmprd.dbo.section_master as sm on
    c.CourseCode + ' ' + s.NAME = sm.crs_cde and
    left(s.erpcoursekey,4) = sm.yr_cde and
    substring(s.ERPCourseKey,6,2) = sm.trm_cde
    inner join tmprd.dbo.student_crs_hist as sch on
    sm.crs_cde = sch.crs_cde and
    sm.yr_cde = sch.yr_cde and
    sm.trm_cde = sch.trm_cde
    inner join ics_net.dbo.fwk_user as u on
    sch.id_num = u.hostid
    inner join tmprd.dbo.name_master as nm on
    sm.LEAD_INSTRUCTR_ID = nm.id_num
    where

    sd.startdate <= @Now
    and sd.enddate >= @Now

    and u.HostID = @HostID
    and sm.crs_cde not like 'ONSO%'
    AND sm.CRS_CDE NOT LIKE 'CLIN 7303 001'
    AND sm.CRS_CDE NOT LIKE 'CLIN 7203 001'
    AND sm.CRS_CDE NOT LIKE 'CLIN 8103 001'
    and sm.LOC_CDE = 'main'

    and u.HostID = @HostID
    and sm.crs_cde not like 'ONSO%'
    AND sm.CRS_CDE NOT LIKE 'CLIN 7303 001'
    AND sm.CRS_CDE NOT LIKE 'CLIN 7203 001'
    AND sm.CRS_CDE NOT LIKE 'CLIN 8103 001'
    and sm.LOC_CDE = 'main'";

    var cmd = new SqlCommand(query, con);
    cmd.Parameters.AddWithValue("HostID", hostID);
    cmd.Parameters.AddWithValue("now", DateTime.Now);
    string studentId = null, userId = null, studentName = null, courseId = null, courseCode = null, courseTitle = null, courseStartTime = null, instructorName = null;

    var reader = cmd.ExecuteReader();

    if (reader.Read())
    {
    studentId = reader["StudentID"].ToString();
    userId = reader["UserID"].ToString();
    studentName = reader["StudentName"].ToString();
    courseId = reader["CourseID"].ToString(); //courseId "86ab3a58-1d7c-4ced-82f9-d7ffacf17421" string
    courseCode = reader["CourseCode"].ToString();
    courseTitle = reader["CourseTitle"].ToString();
    courseStartTime = reader["CourseStartTime"].ToString();
    instructorName = reader["InstructorName"].ToString();


    txtCourseCode.Text = courseCode;
    txtCourseStartTime.Text = courseStartTime;
    txtCourseTitle.Text = courseTitle;
    txtInstructorName.Text = instructorName;
    txtRecordID.Text = courseId;
    txtStudentID.Text = studentId;
    txtUserID.Text = userId;
    txtStudentName.Text = studentName;
    }

    else
    {
    lblMsg.Text = "You do not have a class in the next hour.";

    }

    reader.Close();
    }
    catch (Exception ex)
    //catch (Exception)
    {
    lblMsg.Text = "Error --> " + ex.Message;

    }
    finally
    {
    con.Close();
    }


    }

    }


    protected void btnAdd_Click(object sender, EventArgs e)
    {
    SqlConnection con = new SqlConnection(Database.ConnectionString);
    try
    {
    con.Open(); //

    SqlCommand cmd = new SqlCommand("insert into Reporting.dbo.attendance(RecordID,StudentID,CourseID,CourseCode,AttendanceCode) values(newid(),@StudentID,@CourseID,@CourseCode,@AttendanceCode)", con); //101292

    cmd.Parameters.AddWithValue("@RecordID", txtRecordID.Text);
    cmd.Parameters.AddWithValue("@StudentID", txtStudentID.Text);
    cmd.Parameters.AddWithValue("@CourseID", txtRecordID.Text);
    cmd.Parameters.AddWithValue("@CourseCode", txtCourseCode.Text);
    cmd.Parameters.AddWithValue("@AttendanceCode", txtAttendanceCode.Text);

    int count = cmd.ExecuteNonQuery();
    if (count == 1)
    lblMsg.Text = "Attendance Code[" + txtAttendanceCode.Text + "] [" + txtCourseCode.Text + "] has been added to log (Reporting.dbo.attendance)!"; //record logging of attendance code
    //count retries, if more than 3, stop inserting, go to else, too many tries

    else
    lblMsg.Text = "Could not add Code to log!"; //showing message if there is some system error, the attendance code does not need to be validated here,
    //lblMsg.Text = "Too many attempts";

    //Insert to LMS_Attendance

    var query2 = "select 1 from Reporting.dbo.InstructorCourse where CourseID = @CourseID and CourseCode = @CourseCode and AttendanceCode = @AttendanceCode";
    var checkCmd2 = new SqlCommand(query2, con);
    checkCmd2.Parameters.AddWithValue("@CourseID", txtRecordID.Text);
    checkCmd2.Parameters.AddWithValue("@CourseCode", txtCourseCode.Text);
    checkCmd2.Parameters.AddWithValue("@AttendanceCode", txtAttendanceCode.Text);
    var reader2 = checkCmd2.ExecuteReader();

    if (reader2.Read())
    {
    SqlCommand cmd2 = new SqlCommand("insert into ics_net.dbo.attendance(attendanceID, userid, scheduledaysID, status) values(newid(),CAST(@UserID AS UNIQUEIDENTIFIER),CAST(@CourseID AS UNIQUEIDENTIFIER),'0')", con);
    cmd2.Parameters.AddWithValue("@RecordID", txtRecordID.Text);
    cmd2.Parameters.AddWithValue("@StudentID", txtStudentID.Text); //needs to be fwk.UserID
    cmd2.Parameters.AddWithValue("@UserID", txtUserID.Text);
    cmd2.Parameters.AddWithValue("@CourseID", txtRecordID.Text); //scheduledaysID
    cmd2.Parameters.AddWithValue("@AttendanceCode", txtAttendanceCode.Text);

    int count2 = cmd2.ExecuteNonQuery();
    if (count2 == 1)
    lblMsg2.Text = "Attendance Code[" + txtCourseCode.Text + "] ics_net.dbo.attendance has been added!";
    else
    lblMsg2.Text = "Attendance was not added.";
    }
    else
    {
    // attendance code invalid
    lblMsg2.Text = "Attendance Code is invalid.";
    }

    }
    catch (Exception ex)
    {
    lblMsg2.Text = "Error --> " + ex.Message;
    }
    finally
    {
    con.Close();
    }
    }
    }

    Wednesday, April 10, 2019 6:55 PM

Answers

  • User475983607 posted

    Tom4IT

    I'm looking for an efficient way to allow retries to insert a record only 3 times. It looks like I can just count the number of retries and if over limit return. What's the method in c# to return and stop allowing the user to try and add a record and show the error message on the web page?

    This is a typical state management question.  Use a querystring value, hidden field, Cookie, or Session to store the count between post backs.  I lean toward a hidden field since this is ASP.NET  Web Forms which manages input state automatically.  The Page_Load becomes pretty simple as you only have to increment the hidden field.

    Example

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PostCounterDemo.aspx.cs" Inherits="WebFormsApp.PostCounterDemo" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:HiddenField ID="PostCount" runat="server" />
                <asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click" />
            </div>
            <div>
                <asp:Label ID="Message" runat="server" Text=""></asp:Label>
            </div>
        </form>
    </body>
    </html>
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebFormsApp
    {
        public partial class PostCounterDemo : System.Web.UI.Page
        {
            public int Counter
            {
                get
                {
                    int count = 0;
                    if(int.TryParse(PostCount.Value, out count))
                    {
                        return count;
                    }
                    PostCount.Value = "0";
                    return count;
                }
                set
                {
                    PostCount.Value = value.ToString();
                }
            }
            protected void Page_Load(object sender, EventArgs e)
            {
                if (Page.IsPostBack)
                {
                    Counter++;
                }
                else
                {
                    Counter = 0;
                }
            }
    
            protected void Submit_Click(object sender, EventArgs e)
            {
                if(Counter > 3)
                {
                    Message.Text = $"You exceeded 3 tries.  Total tries {Counter}";
                }
                else
                {
                    Message.Text = $"Total tries {Counter}";
                }
            }
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 10, 2019 7:00 PM