Lab: Adding Exception Handling to an Application

Lab: Adding Exception Handling to an Application

In this lab, you ll add exception-handling features to the preexisting Contact Management data application. When the Contact Management application was introduced in Chapter 5, Storing and Retrieving Data with ADO.NET, it used some simple exception-handling blocks to deal with problems that might occur while updating records in a database. This lab extends those exception-handling structures to deal with specific types of data errors and implements tracing to view how errors are handled.

Estimated lesson time: 30 minutes

Exercise 1: Extend Exception Handling

The Contact Management application deals with database exceptions in a very simple way: if an exception is encountered, the application displays the error and then lets the user cancel the operation. The following code fragment shows this approach as implemented in the butAdd_Click event procedure of the AddContact Web form:

Visual Basic .NET

Try ' Modify the database. adptContacts.Update(dsContacts) ' Show success. litStatus.Text = rowNew.FirstName & " " & rowNew.LastName & _  " added successfully.<br>" ' Clear fields. ClearTextBoxes() ' Occurs if ContactID is not unique. Catch ex As Exception litStatus.Text = "The following database error occurred:<br>" & _ ex.Message & "<br>" & _  "Correct the error and click Add to add the contact " & _  "or click Cancel to abort.<br>" End Try

Visual C#

try { // Modify the database. adptContacts.Update(dsContacts); // Show success. litStatus.Text = rowNew.FirstName + " " + rowNew.LastName +  " added successfully.<br>"; // Redisplay page to clear fields. ClearTextBoxes(); } catch(Exception ex) { litStatus.Text = "The following database error occurred:<br>" + ex.Message + "<br>" +  "Correct the error and click Add to add the contact " +  "or click Cancel to abort.<br>"; }

To create more detailed handling for data exceptions, edit the Catch/catch statements in the application to handle the following possible exceptions:

  • ConstraintException

    This exception occurs if the data set s unique key field constraint is violated. In practice, this can happen if two users are adding a contact at nearly the same time and they both get the same ContactID. When the second user tries to update the database, the ConstraintException exception occurs because the first user has already added a contact with that ContactID. To handle this situation, get another ContactID and try the update again, as shown in the following code:

    Visual Basic .NET

    Catch ex As ConstraintException ' Get another contact ID. rowNew.ContactID = GetNewID(dsContacts.Tables("Contacts")) ' Try again. Try adptContacts.Update(dsContacts) ' Show success. litStatus.Text = rowNew.FirstName & " " & rowNew.LastName & _  " added successfully.<br>" Catch litStatus.Text = "The record could not be added. " & _  "Click Add to try again or click Cancel to abort." End Try

    Visual C#

    catch (ConstraintException) { // Get another contact ID. rowNew.ContactID = GetNewID(dsContacts.Tables["Contacts"]); // Try again. try { adptContacts.Update(dsContacts); // Show success. litStatus.Text = rowNew.FirstName + " " + rowNew.LastName +  " added successfully.<br>"; } catch { litStatus.Text = "The record could not be added. " +  "Click Add to try again or click Cancel to abort."; } }

  • DBConcurrencyException

    This exception can occur if a user tries to update the database while another user has exclusive access. In this case, it s best to notify the first user that the update was not made and allow that user to resubmit the change, as shown in the following code:

    Visual Basic .NET

    Catch ex As DBConcurrencyException ' The database may be locked by another session, so let the user try 'again. litStatus.Text = "The database is currently locked. Wait a few " & _  " seconds and then click Add again."

    Visual C#

    // The database may be locked by another session, // so let the user try again. catch (DBConcurrencyException ) { litStatus.Text = "The database is currently locked. Wait " +  "a few seconds and then click Add again."; }

  • DataException

    This is the general exception for data-related tasks. Handle this exception as a way to intercept problems you might not have thought of. The following code displays a message to the user and then records the exception for viewing in the trace log as a diagnostic tool:

    Visual Basic .NET

    Catch ex As DataException litStatus.Text = "The following database error occurred:<br>" & _ ex.Message & "<br>" & _  "Correct the error and click Add to add the contact " & _  "or click Cancel to abort.<br>" Trace.Warn("Error", "Data exception", ex) End Try

    Visual C#

    // General data exception, so report it. catch(DataException ex) { litStatus.Text = "The following database error occurred:<br>" + ex.Message + "<br>" +  "Correct the error and click Add to add the contact " +  "or click Cancel to abort.<br>"; Trace.Warn("Error", "Data exception", ex); }

The preceding changes to the butAdd_Click event procedure leave non-data-related exceptions unhandled. For the purpose of this lab, we ll handle those possible exceptions in Error event procedures in the following exercise.

Exercise 2: Add an Error Event Procedure

After handling the possible data exceptions in the butAdd_Click event procedure of the Contacts Web form, you should provide a way to handle and record unanticipated exceptions through the form s Error event procedure. This serves two purposes:

  • It prevents the user from seeing technical error messages and replaces the error messages with more helpful information.

  • It keeps information about unanticipated errors in a trace log that you can use as a diagnostic tool to help determine whether you need to handle other exceptions.

To handle unanticipated exceptions using the Error event procedure of the AddContact Web form

  1. Add a Page_Error event procedure to the Web form to deal with all other exceptions on the page. The following code saves information about the exception to the trace log, creates an error message to display, and clears the error so that the application can continue:

    Visual Basic .NET

    Private Sub Page_Error(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles MyBase.Error ' Write the error to the trace log. Trace.Warn("Error", "Error event", Server.GetLastError()) ' Save a message to display as a Session state variable. Session("Error") = "An unexpected error occurred." + _ 'Try your task again." ' Clear the error. Server.ClearError() ' Clear text fields on this page. ClearTextBoxes() End Sub

    Visual C#

    private void Page_Error(object sender, System.EventArgs e) { // Write the error to the trace log. Trace.Warn("Error", "Error event", Server.GetLastError()); // Save a message to display as a Session state variable. Session["Error"] = "<p>An unexpected error occurred. " +  "Try your task again.</p>"; // Clear the error. Server.ClearError(); }

  2. Modify the Page_Load event procedure to display the error message that was saved as a Session state variable in step 1. The following code shows the modified Page_Load procedure, with the additions in boldface:

    Visual Basic .NET

    Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Get the Cached variables. adptContacts = Cache("adptContacts") dsContacts = Cache("dsContacts") dsContactTypes = Cache("dsContactTypes") If Not IsPostBack Then ' Bind to data -- 'populates the drpContactTypes and drpState lists. drpContactTypes.DataBind() drpStates.DataBind() End If  ' If there was an unhandled error, display it. If Session("Error") <> "" Then litStatus.Text = Session("Error") ' Reset the error message. Session("Error") = Nothing End IfEnd Sub

    Visual C#

    private void Page_Load(object sender, System.EventArgs e) { // Get the Cached variables. adptContacts = (SqlDataAdapter) Cache["adptContacts"]; dsContacts = (MCSDWebAppsCS.Chapter05.dsContacts) Cache["dsContacts"]; dsContactTypes = (MCSDWebAppsCS.Chapter05.dsContactTypes) Cache["dsContactTypes"]; if (!IsPostBack) { // Bind to data -- populates drpContactTypes and drpState. drpContactTypes.DataBind(); drpStates.DataBind(); }  // If there was an unhandled error, display it. if(Session["Error"] != null) { litStatus.Text = Session["Error"].ToString(); // Reset the error message. Session["Error"] = null; }}

Exercise 3: Create and View the Trace Log

Exercises 1 and 2 wrote messages to the trace log to help you catch unanticipated errors when people start using your application. To make these messages viewable, enable tracing and add a link within the application to display the trace log, as described in the following procedure.

To create viewable messages

  1. Modify the Web.config file to enable tracing. The following <trace> element enables tracing, saves the output as Trace.axd, increases the number of requests recorded to 20, and enables the trace log to be viewed remotely:

    <trace enabled="true" requestLimit="20" pageOutput="false"  traceMode="SortByTime" localOnly="false" />

  2. Add a link to the SwitchBoard Web form to conditionally display the trace log. The following HTML creates the link as a Hyperlink server control so that you can make the link visible or invisible at run time, depending on the <trace> element setting:

    <asp:HyperLink NavigateUrl="Trace.axd"  runat="server"  text="View trace log." Visible="false"></asp:HyperLink>

  3. Add the following (boldface) code to the SwitchBoard Web form s Page_Load event procedure to control the display of the trace log link:

    Visual Basic .NET

    Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load  ' Display the trace link if tracing is enabled. If Trace.IsEnabled Then hypTrace.Visible = True End If ' The first time this page is displayed... If Not IsPostBack Then AddToCache("adptCalls", SqlDataAdapter1) AddToCache("adptContactTypes", SqlDataAdapter2) AddToCache("adptContacts", SqlDataAdapter3) ' Fill data sets and add them to Cache. SqlDataAdapter1.Fill(DsCalls1) AddToCache("dsCalls", DsCalls1) SqlDataAdapter2.Fill(DsContactTypes1) AddToCache("dsContactTypes", DsContactTypes1) SqlDataAdapter3.Fill(DsContacts1) AddToCache("dsContacts", DsContacts1) End If End Sub

    Visual C#

    private void Page_Load(object sender, System.EventArgs e) {  // Display the trace link if tracing is enabled. if (Trace.IsEnabled) hypTrace.Visible = true; // The first time this page is displayed... if (!IsPostBack) { AddToCache("adptCalls", sqlDataAdapter1); AddToCache("adptContactTypes", sqlDataAdapter2); AddToCache("adptContacts", sqlDataAdapter3); // Fill data sets and add them to Cache. sqlDataAdapter1.Fill(dsCalls1); AddToCache("dsCalls", dsCalls1); sqlDataAdapter2.Fill(dsContactTypes1); AddToCache("dsContactTypes", dsContactTypes1); sqlDataAdapter3.Fill(dsContacts1); AddToCache("dsContacts", dsContacts1); } }

Exercise 4: Extend Exception Handling to Other Web Forms

So far, this lab has shown you how to add exception handling in a step-by-step fashion. Now it s time to strike out on your own! Extend the exception handling on the Calls, DeleteContact, and ContactTypes Web forms by yourself. These Web forms should perform the following tasks:

  • Handle possible data exceptions using exception-handling structures, as demonstrated in Exercise 1.

  • Add Error event procedures to capture and record unanticipated exceptions, as demonstrated in Exercise 2.

When you have finished, compare your results to the Contact Management application included on the companion CD. Good luck!



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net