KEMBAR78
ASP.NET 05 - Exception Handling And Validation Controls | PPT
Chapter 5 Exception Handling and Validation Controls No one is so brave that he is not perturbed by the unexpected. Julius Caesar,  De Bello Gallico , 6.39.
Overview Exception handling in C# Exception handling in ASP.NET Validation controls
Error Handling Even the best written Web application can suffer from runtime errors.  Most complex Web applications must interact with external systems such as databases, Web services, RSS feeds, email servers, file system, and other externalities that are beyond your control.  A failure in any one of these systems means that your application can also no longer run successfully.  It is vitally important that your applications can gracefully handle such problems.
.NET Exception Handling When an error occurs, something called an  exception  is raised, or  thrown  in the nomenclature of .NET.  When an error occurs, either the system or the currently executing application reports it by throwing an exception containing information about the error.  When thrown, an exception can be handled by the application or by ASP.NET itself.
Exception Handling Model In the .NET exception handling model, exceptions are represented as objects.  The ancestor class for all exceptions is  Exception .  This class has many subclasses.  Every  Exception  object contains information about the error.
Default Error Page When an exception is raised but not handled by the application, ASP.NET displays the  default error page .  This page displays: the exception message the exception type the line that it occurred on stack trace
Default Error Page
Handling Exceptions Although this ASP.NET default error page is quite useful when developing and debugging an application, you might not always want to display this page when an exception occurs.  Instead, you might want to  handle  the exception.  There are three different ways or levels where you can do so: At the class level  At the page level At the application level.
Class level exception handling All .NET languages provide a mechanism for separating regular program code from exception handling code.  In C#, this is accomplished via the  try…catch  block.  If a runtime error occurs during the execution of any code placed within a try block, the program does not crash … … but instead tries to execute the code contained in one of the catch blocks.
try…catch block try { double dVal1 = Convert.ToDouble(txtValue1.Text); double dVal2 = Convert.ToDouble(txtValue2.Text); double result = dVal1 / dVal2; labMessage.Text = txtValue1.Text + "/" + txtValue2.Text; labMessage.Text += "=" + result; } catch (FormatException ex1) { labMessage.Text = "Please enter a valid number"; } catch (Exception ex2) { labMessage.Text = "Unable to compute a value with these values"; }
finally block There may be times when you want to execute some block of code regardless of whether an exception occurred.  The classic example is closing a database connection no matter whether the SQL operation was successful or generated an exception.  In such a case, you can use the optional  finally  block
finally block try { // Open a database connection // Execute SQL statement } catch (DbException ex) { // Handle database exception } finally  { // Close database connection if it exists }
Cost of Exceptions Throwing exceptions is relatively expensive in terms of CPU cycles and resource usage. As a result, one should try to use exceptions to handle only exceptional situations.  If your code relies on throwing an exception as part of its normal flow, you should refactor the code to avoid exceptions, perhaps by using a return code or some other similar mechanism instead.
Using Exceptions try  { SomeBusinessObject.Login(email); // Other code dependent upon a successful login } catch (Exception ex) { // Display message that email was not found } bool okay = SomeBusinessObject.Login(email); if (! okay) { // Display error message on page  } else { // Other code dependent upon a successful login } bad good
Exception Handling Strategies  If you design your code so that exceptions are thrown only in truly exceptional situations, what do you when one of these exceptional exceptions occurs?
Exception Handling Strategies  Possible strategies: “ Swallow” the exception by catching and ignoring the exception by continuing normal execution. Almost never appropriate. Completely handle the exception within the catch block. Ignore the exception by not catching it (and thus let some other class handle it).  Catch the exception and rethrow it for some other class to handle it.
Exception Handling Strategies  You may want to know when an exception occurs in a production application so that you can change the code to prevent it from occurring in the future.  In this case, you might not want to catch the exception but instead let some other class “higher” in the calling stack handle it, perhaps by recording the exception to some type of exception log.  Even if you are not recording an exception log, you should remember that in general, you should not catch exceptions in a method unless it can handle them, such as by: logging exception details,  performing some type of page redirection, retrying the operation,  performing some other sensible action.
Page Level Exception Handling ASP.NET allows the developer to handle errors on a page basis via the page’s  Page_Error  event handler.  The  Page_Error  event handler is called whenever an uncaught exception occurs during the exception of the page.
Page_Error event handler public partial class PageExceptionTest : System.Web.UI.Page { … private void Page_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); Response.Write(&quot;<h1>An error has occurred</h1>&quot;); Response.Write(&quot;<h2>&quot; + ex.Message + &quot;</h2>&quot;); Response.Write(&quot;<pre>&quot; + ex.StackTrace + &quot;</pre>&quot;); Context.ClearError(); } }
Application level exception handling There are two different ways that you can handle an exception at the application level:  using a  Application_Error  event handler using the ASP.NET error page redirection mechanism.
Using the Application_Error Handler ASP.NET allows the developer to handle errors on an application-wide basis via the  Application_Error  event handler.  This handler resides in the application’s  Global.asax  file and is often the preferred location to handle uncaught exceptions in an application.  Because you often want to do the same thing for all unhandled exceptions in your application.  Rather than have the same type of error-logging code on every single page, it makes sense to centralize this code into a single spot.
Custom Error Page To use a custom error page, you can change the settings of the  <customErrors>  element in the  Web.config  file.  In this element, you can specify the custom page that is to be displayed. <system.web> <customErrors mode=&quot;On&quot; defaultRedirect=&quot;FriendlyErrorPage.aspx&quot; /> … </system.web>
Custom Error Pages You can create custom error pages for different HTTP error codes.  For example, a common feature of many Web sites is to provide custom HTTP 404 (requested page not found) and HTTP 500 (server error) error pages.  You can specify custom pages for HTTP error codes within the  <customErrors>  element.  <customErrors mode=&quot;On&quot; defaultRedirect=&quot;FriendlyErrorPage.aspx&quot; > <error statusCode=&quot;404&quot; redirect=&quot;custom404.aspx&quot; /> <error statusCode=&quot;500&quot; redirect=&quot;custom500.aspx&quot; /> </customErrors>
Validation Server Controls  These are a special type of Web server control.  They significantly reduce some of the work involved in validating user data.  They are used to validate or verify that certain input server controls (such as  TextBox ,  RadioButtonList , or  DropDownList ) contain correct data.
Validation Server Controls  RequiredFieldValidator   Ensures that the input control is not empty. CompareValidator Compares a user entry against another value or control.  RangeValidator   Checks if a user entry is between a lower and upper boundary. RegularExpressionValidator   Checks if a user entry matches a pattern defined by a regular expression  CustomValidator   Checks a user entry using custom validation logic.  ValidationSummary   Displays the error messages from all validation controls in a single location.
Validation Server Controls  You use validation server controls as you do other server controls.  That is, you add the markup to your .aspx file where you would like an error indicator to be displayed (typically adjacent to the field it is validating).  Each validation control references another input server control elsewhere on the page.  <asp:TextBox ID=&quot;txtUserName&quot; runat=&quot;server&quot; /> <asp:RequiredFieldValidator Id=&quot;reqUser&quot; runat=&quot;server&quot;  ControlToValidate=&quot;txtUserName&quot;  Text=&quot;Please enter a User Name&quot; />
Form Validation Process  When a form that uses these validators is submitted, the user’s input is validated first by using Javascript on the client side if enabled and if supported by the browser.  If there is an error, an error message is displayed without a round-trip to the server.  If no error (or no Javascript or if client validation is disabled), the data is passed to the server and the data is checked once again on the server side.  If the data is not valid, an error message is generated and ultimately sent back to the browser (along with all the other form data).
Form Validation Process  Why is both client-side and server-side data validation necessary?  Client-side validation is useful because it reduces round-trips to the server.  This provides immediate feedback to the user as well as improves server performance.  Client-side validation by itself is not sufficient. The user could be using a browser that does not support scripting. that is, using an ancient browser or, more commonly, has scripting turned off via the browser preferences.  Client-side scripting is also potentially vulnerable to “script exploits.”
Form Validation Process User data must thus be validated on both the client and the server side.  Validation controls automatically generate the Javascript necessary for client-side validation as well as perform, behind the scenes, the server-side validation.
Validation Controls See pages 280-308

ASP.NET 05 - Exception Handling And Validation Controls

  • 1.
    Chapter 5 ExceptionHandling and Validation Controls No one is so brave that he is not perturbed by the unexpected. Julius Caesar, De Bello Gallico , 6.39.
  • 2.
    Overview Exception handlingin C# Exception handling in ASP.NET Validation controls
  • 3.
    Error Handling Eventhe best written Web application can suffer from runtime errors. Most complex Web applications must interact with external systems such as databases, Web services, RSS feeds, email servers, file system, and other externalities that are beyond your control. A failure in any one of these systems means that your application can also no longer run successfully. It is vitally important that your applications can gracefully handle such problems.
  • 4.
    .NET Exception HandlingWhen an error occurs, something called an exception is raised, or thrown in the nomenclature of .NET. When an error occurs, either the system or the currently executing application reports it by throwing an exception containing information about the error. When thrown, an exception can be handled by the application or by ASP.NET itself.
  • 5.
    Exception Handling ModelIn the .NET exception handling model, exceptions are represented as objects. The ancestor class for all exceptions is Exception . This class has many subclasses. Every Exception object contains information about the error.
  • 6.
    Default Error PageWhen an exception is raised but not handled by the application, ASP.NET displays the default error page . This page displays: the exception message the exception type the line that it occurred on stack trace
  • 7.
  • 8.
    Handling Exceptions Althoughthis ASP.NET default error page is quite useful when developing and debugging an application, you might not always want to display this page when an exception occurs. Instead, you might want to handle the exception. There are three different ways or levels where you can do so: At the class level At the page level At the application level.
  • 9.
    Class level exceptionhandling All .NET languages provide a mechanism for separating regular program code from exception handling code. In C#, this is accomplished via the try…catch block. If a runtime error occurs during the execution of any code placed within a try block, the program does not crash … … but instead tries to execute the code contained in one of the catch blocks.
  • 10.
    try…catch block try{ double dVal1 = Convert.ToDouble(txtValue1.Text); double dVal2 = Convert.ToDouble(txtValue2.Text); double result = dVal1 / dVal2; labMessage.Text = txtValue1.Text + &quot;/&quot; + txtValue2.Text; labMessage.Text += &quot;=&quot; + result; } catch (FormatException ex1) { labMessage.Text = &quot;Please enter a valid number&quot;; } catch (Exception ex2) { labMessage.Text = &quot;Unable to compute a value with these values&quot;; }
  • 11.
    finally block Theremay be times when you want to execute some block of code regardless of whether an exception occurred. The classic example is closing a database connection no matter whether the SQL operation was successful or generated an exception. In such a case, you can use the optional finally block
  • 12.
    finally block try{ // Open a database connection // Execute SQL statement } catch (DbException ex) { // Handle database exception } finally { // Close database connection if it exists }
  • 13.
    Cost of ExceptionsThrowing exceptions is relatively expensive in terms of CPU cycles and resource usage. As a result, one should try to use exceptions to handle only exceptional situations. If your code relies on throwing an exception as part of its normal flow, you should refactor the code to avoid exceptions, perhaps by using a return code or some other similar mechanism instead.
  • 14.
    Using Exceptions try { SomeBusinessObject.Login(email); // Other code dependent upon a successful login } catch (Exception ex) { // Display message that email was not found } bool okay = SomeBusinessObject.Login(email); if (! okay) { // Display error message on page } else { // Other code dependent upon a successful login } bad good
  • 15.
    Exception Handling Strategies If you design your code so that exceptions are thrown only in truly exceptional situations, what do you when one of these exceptional exceptions occurs?
  • 16.
    Exception Handling Strategies Possible strategies: “ Swallow” the exception by catching and ignoring the exception by continuing normal execution. Almost never appropriate. Completely handle the exception within the catch block. Ignore the exception by not catching it (and thus let some other class handle it). Catch the exception and rethrow it for some other class to handle it.
  • 17.
    Exception Handling Strategies You may want to know when an exception occurs in a production application so that you can change the code to prevent it from occurring in the future. In this case, you might not want to catch the exception but instead let some other class “higher” in the calling stack handle it, perhaps by recording the exception to some type of exception log. Even if you are not recording an exception log, you should remember that in general, you should not catch exceptions in a method unless it can handle them, such as by: logging exception details, performing some type of page redirection, retrying the operation, performing some other sensible action.
  • 18.
    Page Level ExceptionHandling ASP.NET allows the developer to handle errors on a page basis via the page’s Page_Error event handler. The Page_Error event handler is called whenever an uncaught exception occurs during the exception of the page.
  • 19.
    Page_Error event handlerpublic partial class PageExceptionTest : System.Web.UI.Page { … private void Page_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); Response.Write(&quot;<h1>An error has occurred</h1>&quot;); Response.Write(&quot;<h2>&quot; + ex.Message + &quot;</h2>&quot;); Response.Write(&quot;<pre>&quot; + ex.StackTrace + &quot;</pre>&quot;); Context.ClearError(); } }
  • 20.
    Application level exceptionhandling There are two different ways that you can handle an exception at the application level: using a Application_Error event handler using the ASP.NET error page redirection mechanism.
  • 21.
    Using the Application_ErrorHandler ASP.NET allows the developer to handle errors on an application-wide basis via the Application_Error event handler. This handler resides in the application’s Global.asax file and is often the preferred location to handle uncaught exceptions in an application. Because you often want to do the same thing for all unhandled exceptions in your application. Rather than have the same type of error-logging code on every single page, it makes sense to centralize this code into a single spot.
  • 22.
    Custom Error PageTo use a custom error page, you can change the settings of the <customErrors> element in the Web.config file. In this element, you can specify the custom page that is to be displayed. <system.web> <customErrors mode=&quot;On&quot; defaultRedirect=&quot;FriendlyErrorPage.aspx&quot; /> … </system.web>
  • 23.
    Custom Error PagesYou can create custom error pages for different HTTP error codes. For example, a common feature of many Web sites is to provide custom HTTP 404 (requested page not found) and HTTP 500 (server error) error pages. You can specify custom pages for HTTP error codes within the <customErrors> element. <customErrors mode=&quot;On&quot; defaultRedirect=&quot;FriendlyErrorPage.aspx&quot; > <error statusCode=&quot;404&quot; redirect=&quot;custom404.aspx&quot; /> <error statusCode=&quot;500&quot; redirect=&quot;custom500.aspx&quot; /> </customErrors>
  • 24.
    Validation Server Controls These are a special type of Web server control. They significantly reduce some of the work involved in validating user data. They are used to validate or verify that certain input server controls (such as TextBox , RadioButtonList , or DropDownList ) contain correct data.
  • 25.
    Validation Server Controls RequiredFieldValidator Ensures that the input control is not empty. CompareValidator Compares a user entry against another value or control. RangeValidator Checks if a user entry is between a lower and upper boundary. RegularExpressionValidator Checks if a user entry matches a pattern defined by a regular expression CustomValidator Checks a user entry using custom validation logic. ValidationSummary Displays the error messages from all validation controls in a single location.
  • 26.
    Validation Server Controls You use validation server controls as you do other server controls. That is, you add the markup to your .aspx file where you would like an error indicator to be displayed (typically adjacent to the field it is validating). Each validation control references another input server control elsewhere on the page. <asp:TextBox ID=&quot;txtUserName&quot; runat=&quot;server&quot; /> <asp:RequiredFieldValidator Id=&quot;reqUser&quot; runat=&quot;server&quot; ControlToValidate=&quot;txtUserName&quot; Text=&quot;Please enter a User Name&quot; />
  • 27.
    Form Validation Process When a form that uses these validators is submitted, the user’s input is validated first by using Javascript on the client side if enabled and if supported by the browser. If there is an error, an error message is displayed without a round-trip to the server. If no error (or no Javascript or if client validation is disabled), the data is passed to the server and the data is checked once again on the server side. If the data is not valid, an error message is generated and ultimately sent back to the browser (along with all the other form data).
  • 28.
    Form Validation Process Why is both client-side and server-side data validation necessary? Client-side validation is useful because it reduces round-trips to the server. This provides immediate feedback to the user as well as improves server performance. Client-side validation by itself is not sufficient. The user could be using a browser that does not support scripting. that is, using an ancient browser or, more commonly, has scripting turned off via the browser preferences. Client-side scripting is also potentially vulnerable to “script exploits.”
  • 29.
    Form Validation ProcessUser data must thus be validated on both the client and the server side. Validation controls automatically generate the Javascript necessary for client-side validation as well as perform, behind the scenes, the server-side validation.
  • 30.