Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 7 pptx

90 279 0
Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 7 pptx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

The following code shows the syntax for using the ToString() method of the Convert class: SomeVariable = Convert.ToString(SomeInteger); 'Convert Integer to String Try to Break Your Code This can be a more difficult task than expected. It is often difficult for the developer to anticipate all the unusual things a user might attempt to do with the application, such as accidentally typing in letters when numbers are required, or supplying an answer that was longer than anticipated, or even deliberately trying to break it. So, when it is time to test your application, try to think like a user who isn't too computer literate. You can break down your testing strategy into two main approaches: ❑ Be nice to your program: Supply your program with legal values, or values that your program is designed to expect and handle. For instance, if your program contains an age field, supply only numbers, not letters. Watch how your program behaves – does it respond as you expect it to with the legal values supplied to it? ❑ Try to break your program: This is the fun part. Supply your program with illegal values. For instance, provide string values where integers are expected. This ensures that your program handles all illegal values appropriately. Depending on the kind of data you are expecting in your program, you could to do anything from a simple numeric or alphabetic check to a validity check (such as inserting invalid dates into a date field). If your program spans several pages, then surf to some of the pages out of the expected sequence. Both these techniques can be used to help standardize and improve the readability of your code. Many basic errors can be avoided in this way. However, even if you follow all these suggestions, your code still can't be guaranteed to be bug-free. Let's look at some of the errors that may plague your code. Conversion Function Return Datatype Convert.ToDecimal Decimal Convert.ToInt16 16 bit signed Integer Convert.ToInt32 32 bit signed Integer Convert.ToInt64 64 bit signed Integer Convert.ToSingle Single Convert.ToString String 513 Debugging and Error Handling Sources of Errors The errors that occur in an ASP.NET page can be grouped into four categories: ❑ Parser errors: These occur because of incorrect syntax or bad grammar within the ASP.NET page. ❑ Compilation errors: These are also syntax errors, but they occur due to statements that are not recognized by the language compiler, rather than ASP.NET itself. For example, using If (capital I) instead of if, or not providing a closing bracket to a for loop, will result in a compilation error. The difference between the parser error and compilation error is that the parser error occurs when there is a syntax error in the ASP.NET page, and the ASP.NET parser catches it, whereas the compilation error occurs when there is a syntax error in the C# code block. ❑ Configuration errors: These occur because of the incorrect syntax or structure of a configuration file. An ASP.NET configuration file is a text file in XML format, and contains a hierarchical structure that stores application-wide configuration settings. There can be one configuration file for every application on your Web server. These configuration files are all named web.config, irrespective of the application's name. There is also a single configuration file called machine.config that contains information that applies to every application on a single machine. We will discuss configuration files in detail in Chapter 15, although we do touch upon them again later in this chapter. ❑ Runtime or logical errors: As the name implies, these errors are not detected during compilation or parsing, but occur during execution. For example, when the user enters letters into a field that expects numbers, and your program assigns that entry to an integer variable, you will get a runtime error when the code tries to execute. These are also known as logical errors. Now let's look at some specific examples that fall into the above categories. Syntax Errors As the name suggests, these errors occur when there are problems in the syntax of the code. Parser and compilation errors fall under this category. These are usually the first errors encountered when developing ASP.NET pages. There are several reasons why these errors occur: ❑ A typo or bad grammar in the code syntax: For example, instead of typing <asp:textbox> for creating a TextBox control in your page, you type <asp:textbx>, then the browser shows an error. ❑ Incorrect code syntax: For instance, when creating a textbox control, you might forget to close the tag (as <asp:TextBox id="txtName" runat="server"> when it should actually be <asp:TextBox id="txtName" runat="server" />) ❑ Combining or splitting keywords between languages: I make this error quite a lot. If you've been coding in another language and come back to coding in C#, you might forget brackets, or type keywords in the wrong case. ❑ Not closing a construct properly: This error occurs if we forget to close a construct, such as a for loop or a nested if statement. Take a look at this example: if condition1 { 514 Chapter 14 //do this } else condition2 { //do this if condition2a { //do this } else { //do this } Did you catch the error in the above code? We're missing a closing-bracket. Imagine how difficult it would be to spot this if we had the above code block set amongst hundreds of other lines of code. It's another good argument for formatting your code correctly too. If it had been indented, it would have been easier to spot the error. Let's look at an example of creating a syntax error (a parser error) and then see how ASP.NET responds to it. Try It Out Syntax Error 1. Open Web Matrix and type the following lines of code into the All Window. Make a spelling mistake when creating the textbox control, as highlighted in the following code: <html> <head> <title>Syntax Error Example </title> </head> <body> <form method="post" action="syntaxerror.aspx" runat="server"> <asp:TetBox id="txtQuantity" runat="server" /> </form> </body> </html> 2. Save this file as syntaxerror.aspx and load the file using a browser. You expect to see a textbox in the browser, as shown in Figure 14-1: Figure 14-1 515 Debugging and Error Handling However, what you actually see is Figure 14-2: Figure 14-2 How It Works As the error message clearly states, the ASP.NET parser points to Line 7, and asks us to check the details. You can see that a spelling mistake exists, Tetbox instead of TextBox. If you correct the spelling mistake and rerun the code, you'll get the expected result. Errors of this kind are very common but are usually quick and easy to fix, since the error message provides a detailed breakdown of the error and the line on which it occurs. Now we will look at a syntax error that will generate a compilation error. Try It Out Generate a Compiler Error 1. Create a new file called compilationerror.aspx, and type the following code into the Web Matrix All window: 516 Chapter 14 <%@ Page language="C#" Debug="true" %> <script language="C#" runat="server"> public void CompleteOrder(Object sender, EventArgs e) { If (txtQuantity.Text == "") { lblOrderConfirm.Text = "Please provide an Order Quantity."; } else if (Convert.ToInt32(txtQuantity.Text) <= 0) { lblOrderConfirm.Text = "Please provide a Quantity greater than 0."; } else if (Convert.ToInt32(txtQuantity.Text) > 0) { lblOrderConfirm.Text = "Order Successfully placed."; } } </script> <html> <head> <title>Compiliation Error Example</title> </head> <body> <form method="post" action="manualtrapping.aspx" runat="server"> <asp:Label text="Order Quantity" runat="server" /> <asp:TextBox id="txtQuantity" runat="server" /> <br /> <asp:Button id="btnComplete_Order" Text="Complete Order" onclick="CompleteOrder" runat="server"/> <br /> <asp:Label id="lblOrderConfirm" runat="server"/> </form> </body> </html> 2. Save and view the compilationerror.aspx file with a browser. The page displayed is as shown in Figure 14-3: 517 Debugging and Error Handling Figure 14-3 How It Works We typed If at the beginning of our control block instead of if. As expected, when we tried to run the compilationerror.aspx file in the browser, we got an error message. It tells us we have a compiler error in Line 5 and even attempts to tell us how to fix it. (In this case it is rather misleading as it tells us we are missing a semicolon, when in fact, the if statement is the part that is incorrect!) These are just a few common examples of syntax errors. There is no way we could provide a list of all possible syntax errors that you might encounter, but the good news is that syntax errors are easy to find and fix. Logical (Runtime) Errors The second type of error is the Logical Error. Unfortunately, it is relatively more difficult to find and fix. Logical errors become apparent during runtime. As the name implies, these errors occur due to mistakes in programming logic. Some of the more common reasons for these errors are: 518 Chapter 14 ❑ Division by zero: This dreaded error that has been around since the days of valve-based computers. It occurs when your program divides a number by zero. But why in the world do we divide a number by zero? In most cases, this occurs because the program divides a number by an integer that should contain a non-zero number, but for some reason, contains a zero. ❑ Type mismatch: Type mismatch errors occur when you try to work with incompatible data types and inadvertently try to add a string to a number, or store a string in a date data type. It is possible to avoid this error by explicitly converting the data type of a value before operating on it. We will talk about variable data type conversion later in this chapter. ❑ Incorrect output: This type of error occurs when you use a function that returns output that's different from what you are expecting in your program. ❑ Use of a non-existent object: This type of error occurs when you try to use an object that was never created, or when an attempt to create the object failed. ❑ Mistaken assumptions: This is another common error, and should be corrected during the testing phase (if one exists). This type of error occurs when the programmer uses an incorrect assumption in the program. This can happen, for instance, in a program that adds withdrawal amounts to a current balance, instead of subtracting them. ❑ Processing invalid data: This type of error occurs when the program accepts invalid data. An example of this would be a library checkout program that accepts a book's return date as February 29, 2003, in which case, you may not have to return the book for a while! While this is far from being a complete list of all possible logical errors, it should give you a feel for what to look out for when testing your code. Try It Out Generate a Runtime Error 1. Open compilationerror.aspx in Web Matrix, go to the All Window, and make the following change to the case of the if statement: public void CompleteOrder(Object sender, EventArgs e) { if (txtQuantity.Text == "") { lblOrderConfirm.Text = "Please provide an Order Quantity."; } else if (Convert.ToInt32(txtQuantity.Text) <= 0) { lblOrderConfirm.Text = "Please provide a Quantity greater than 0."; } else if (Convert.ToInt32(txtQuantity.Text) > 0) { lblOrderConfirm.Text = "Order Successfully placed."; } } 2. Save the file as runtimeError.aspx. 3. View the runtimeError.aspx file using the browser. Provide a non-numeric value, such as ABC, to the order quantity textbox, and click the Complete Order button. Figure 14-4 shows the result: 519 Debugging and Error Handling Figure 14-4 How It Works Our control block validates input for null values, and for numeric values that are equal to or less than zero. It does not check input for other non-numeric input values. The code generated a runtime error when the ConvertTo.Int32() function tried to convert a non-numeric entry to an integer field. The process of checking for this type of errors is called validation. To validate the data entry values, your control block should have an extra couple of lines as follows: else if (Convert.ToInt32(txtQuantity.Text) <= 0) { lblOrderConfirm.Text = "Please provide a Quantity greater than 0."; } Let's take a closer look at validating user input. Trapping Invalid Data Testing your code by supplying both legal and illegal values is crucial for the proper functioning of your program. Your program should return expected results when providing legal values, and handle errors when supplied with illegal values. In this section, we'll talk about ways to handle the illegal values supplied to your program. We have two objectives here: 520 Chapter 14 ❑ Prevent the occurrence of errors that may leave you with many disgruntled users ❑ Prevent your program from accepting and using illegal values There are two main techniques used to fulfill these objectives: manual trapping and using validation controls. Manual Trapping When building the application, you could create error traps to catch illegal values before they get into the page execution, where they might halt the execution of the page or provide invalid results. How do you block illegal values from sneaking into page processing? Let's develop a page that accepts order quantity from the user. Try It Out Catching Illegal Values 1. Open runtimeError.aspx in Web Matrix and make the following changes in the All Window: <%@ Page Language="c#" Debug="true" %> <script Language="c#" runat="server"> void CompleteOrder(object sender, EventArgs e) { if (txtQuantity.Text!= "") { if (!(Char.IsNumber(txtQuantity.Text,0))) { if (txtQuantity.Text.Substring(0,1)!= "-") { lblOrderConfirm.Text = "Please provide only numbers in Quantity field."; } else { lblOrderConfirm.Text = "Please provide a Quantity greater than 0."; } } else if (Convert.ToInt32(txtQuantity.Text) == 0) { lblOrderConfirm.Text = "Please provide a Quantity greater than 0."; } else if (Convert.ToInt32(txtQuantity.Text) > 0) { lblOrderConfirm.Text = "Order Successfully placed."; } } else { lblOrderConfirm.Text = "Please provide an Order Quantity."; } } </script> <html> <head> <title>Manual Trapping Example</title> </head> 521 Debugging and Error Handling [...]... Next in C#, and the short answer is, no you cannot! C#' s built-in error handling syntax is based on structured exception handling Structured exception handling in C# does not allow you to simply skip the line of code producing the error and proceed with the next one Such a function is OK for a script-based application such as a traditional ASP page, but for the object-oriented world of C# and ASP.NET, ... lack of server memory When an error occurs in an ASP.NET page, the error details are sent to the client However, ASP.NET by default shows detailed error information only to a local client A local client is a browser running on the same machine as the Web server and therefore only viewable by the site administrator For instance, if you create the ASP.NET examples in this book on a machine running a... second guessing of typical mistakes a user might make System Errors These errors are generated by ASP.NET itself They may be due to malfunctioning code, a bug in ASP.NET, or even one in the CLR Although you could find this type of error, rectifying it is usually not possible – particularly if it is an ASP.NET or CLR error Other errors that can be placed in this category are those that arise due to the... dependent on the way the code is structured Indeed, it is possible for code written in Visual Basic NET to throw an exception that is then handled by code written in C# Handling Errors Programmatically We can now handle errors using try…catch blocks, but some exceptions may still sneak through ASP.NET provides us with two more methods that can be used to handle any errors that are unaccounted for, and... preceded with catch (Exception e) always come last in the set? Well, no – you can define a catch block that is even more general that this one The catch (Exception e) block can deal with any NET-related exception but it cannot deal with any exceptions thrown by objects outside NET, such as the ones from the Windows operating system (OS) To trap any error at all, regardless of its origin, C# allows... Goto Label syntax as well C# also does not have any equivalent to the Visual Basic Err object Structured Error Handling We have already come across structured exception handling in this book wherever we have actually needed it: ❑ We used it to deal with situations where conversion between data types might fail and generate a run-time error ❑ We mentioned it as a means of dealing with situations where conversion... Page Trace = "true" %> Tracing can be disabled using: When tracing is enabled, the trace information is displayed underneath the page's contents Let's create a simple ASP.NET page with a TextBox and a Label control, and enable tracing at the page level Try It Out Enabling Trace at the Page Level 1 Open Web Matrix, create a page called pageleveltracing.aspx, and type in the... that occur because of your program using a null (unknown value), when it is expecting an ’entry’ from the user 523 Chapter 14 By using one of the many validation controls provided by ASP.NET, you could present the users with a message informing them about the incorrect value supplied, and the value your program is expecting This prevents the program from processing an illegal value and developing an... Web server, and access them using a browser on the same machine (as you would do with Web Matrix), then the browser is a local client If this was deployed on a network using IIS, you might see the error, but other users on the network would just receive a generic "something's wrong" kind of message So, the fact that ASP.NET sends detailed information about errors to local clients is actually very helpful... general purpose error handler, that is able to deal with any error at all In C#, this is achieved by stacking catch blocks one after another If an exception is thrown from the try block, the code will pass the Exception object created down the chain of catch blocks until there is a match On the other hand, if there is no match, the exception is passed to the.NET runtime and you will get an unhandled exception . shown in Figure 14 -1: Figure 14 -1 515 Debugging and Error Handling However, what you actually see is Figure 14 -2: Figure 14 -2 How It Works As the error message clearly states, the ASP. NET parser points. page: Figure 14 -13 ❑ Headers Collection: As shown in Figure 14 -14 , this section displays the various HTTP headers sent by the client to the server, along with the request: Figure 14 -14 5 31 Debugging. the compilationerror.aspx file with a browser. The page displayed is as shown in Figure 14 -3: 5 17 Debugging and Error Handling Figure 14 -3 How It Works We typed If at the beginning of our control

Ngày đăng: 13/08/2014, 04:21

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan