HomeC# Testing and Debugging a Windows Forms Appl...
Testing and Debugging a Windows Forms Application
This article shows you how to revise, test, and debug a Windows form application. The third of three parts, it is excerpted from chapter three of the book Murach's C# 2005, written by Joel Murach (Murach, 2005; ISBN: 9781890774370).
How to refactor code As you work on the code for an application, you will often find that you want to revise your code. For example, you may want to change a name that you’ve used to identify a variable in your code to make the name more meaningful and readable. However, if you change the name in one place, you need to change it throughout your code. This is known as refactoring, and Visual Studio 2005 includes new features that make it much easier to refactor your code.
Figure 3-11 shows how you can use Visual Studio to quickly and easily change the names that you use within your code. In this figure, for example, the first screen shows the Code Editor after the name of the subtotal variable has been changed from subtotal to total. Here, a bar appears under the last letter of the newly renamed total variable. Then, the second screen shows the smart tag menu that can be displayed by pointing at the bar and clicking on the drop-down arrow that becomes available.
At this point, you can select the first command to rename the variable throughout the application. Or, you can select the second command to preview the changes. If you select the second command, a Preview Changes dialog box will be displayed. Then, you can preview the changes and deselect any changes that you don’t want to make.
Although this figure just shows how to change a name that’s used by the code, you can also use Visual Studio’s refactoring features to modify the structure of your code by extracting methods, encapsulating fields, and so on. To do that, you often begin by selecting a block of code. Then, you can right-click on the code and select the appropriate refactoring command. Or, you can select the appropriate command from the Refactor menu.
If you already have experience with another object-oriented language, these refactoring features should make sense to you. If not, don’t worry. You’ll learn more about these features as you progress through this book.
The bar that appears under a renamed variable
decimal total = Convert.ToDecimal (txtSubtotal.Text);
The menu that’s available from the bar
The Preview Changes dialog box
Figure 3-11.How to refactor code
Description
The process of revising and restructuring existing code is known as refactoring. Visual Studio 2005 provides many new features that make it easier to refactor your code.
When you change a name that’s used in your code, Visual Studio displays a bar beneath the modified name. Then, you can display a smart tag menu by moving the mouse pointer over the bar, and you can click on the drop-down list to display a menu that contains the appropriate refactoring commands.
You can also use Visual Studio’s refactoring features to modify the structure of your code by extracting methods, encapsulating fields, and so on. To do that, you often begin by selecting a block of code. Then, you can right-click on the code and select the appropriate command, or you can select the command from the Refactor menu.
Some refactoring commands display a dialog box that lets you preview the changes before you make them. Then, you can deselect any changes that you don’t want to make.
As you develop applications in C#, it’s likely that you’ll need some additional information about the IDE, the C# language, an object, property, method, event, or some other aspect of C# programming. Figure 3-12 shows several ways you can get that information.
When you’re working in the Code Editor or the Form Designer, the quickest way to get help information is to press F1 while the insertion point is in a keyword or an object is selected. Then, Visual Studio opens a separate Help window like the one shown in this figure and displays the available information about the selected keyword or object. Another way to launch a Help window is to select a command from Visual Studio’s Help menu such as the Search, Contents, or Index command.
The Help window is split into two panes. The right pane contains one or more tabbed windows, one for each help topic. In this figure, for example, the right pane displays a help topic that provides information about working with the Code Editor. In addition, this pane displays the tabs for other help topics, and you can display those topics by clicking on the tab.
The left pane, on the other hand, displays the Index, Contents, and Help Favorites tabs that help you locate help topics. In this figure, for example, the left pane displays the Index tab. At the top of this tab, the drop-down list has been used to filter help topics so they’re appropriate for C# programmers. In addition, “code edit” has been entered to navigate to the index entries that begin with those letters. This makes it easy to select the Code Editor entry.
In the left pane, you can click on the Contents tab to display a list of help topics that are grouped by category. Or, you can click on the Help Favorites tab to view a list of your favorite help topics. At first, the Help Favorites tab won’t contain any help topics. However, you can add topics to this tab by displaying a topic and clicking on the Add To Help Favorites button that’s available from the toolbar.
Although it isn’t shown in this figure, you can display a Search tab in the right pane by clicking on the Search button in the toolbar. From this tab, you can enter a word or phrase to search for. Then, when you click the Search button, the results are displayed in the tab. In addition, all index entries that match the search are displayed in the Index Results pane that’s displayed across the bottom of the screen. In this figure, for example, the Index Results window is displayed for a search string of “Code Editor.” To display the help topic for any of the listed index entries, just double-click on the entry.
When you display information in the Help window, you should realize that the Help window uses a built-in web browser to display help topics that are available from your computer and from the Internet. In addition, the Help window works much like a web browser. To jump to a related topic, you can click on a hyperlink. To move forward and backward through previously displayed topics, you can use the Forward and Back buttons. As a result, with a little practice, you shouldn’t have much trouble using this window.
The Help window
Figure 3-12. How to get help information
Description
You can display a Help window by selecting an object in the Form Designer or positioning the insertion point in a keyword in the Code Editor and pressing F1.
You can also display a Help window by selecting a command (such as Index, Contents, or Search) from Visual Studio’s Help menu.
The Help window works like a web browser and can display help topics that are available from your computer or from the Internet. You can use the buttons in its toolbar to navigate between help topics or to add topics to your list of favorite topics.
The Help window is divided into two panes. The left pane displays the Index, Content, and Help Favorites tabs that let you locate the help topics you want to display. The right pane displays each help topic in a separate window.
If you click on the Search button, the right pane will display a Search tab that lets you search for help topics by entering a word or phrase.
If you click on the How Do I button, the right pane will display a How Do I tab that lets you go to a topic by clicking on a link.
To close a tab, click on the Close button when the tab is active. To display a tab, click the tab or select it from the Active Files drop down list that’s next to the Close button.
How to run, test, and debug a project
After you enter the code for a project and correct any syntax errors that are detected as you enter this code, you can run the project. When the project runs, you can test it to make sure it works the way you want it to, and you can debug it to remove any programming errors you find.
As you learned in chapter 1, you can run a project by clicking the Start Debugging button in the Standard toolbar, selecting the Start Debugging command from the Debug menu, or pressing the F5 key. This builds the project if it hasn’t been built already and causes the project’s form to be displayed, as shown in figure 3-13. When you close this form, the application ends. Then, you’re returned to Visual Studio where you can continue working on your program.
You can also build a project without running it as described in this figure. In most cases, though, you’ll run the project so you can test and debug it.
If build errors are detected when you run a project, the errors are displayed in the Error List window, and you can use this window to identify and correct the errors. If it isn’t already displayed, you can display this window by clicking on the Error List tab that’s usually displayed at the bottom of the window. When you do that, you should realize that the errors will still be listed in the Error List window and highlighted in the Code Editor even after you’ve corrected them. The errors aren’t cleared until you build the project again.
The form that’s displayed when you run the Invoice Total project
Figure 3-13.How to run a project
Description
To run a project, click the Start Debugging button in the Standard toolbar, select the Debug->Start Debugging menu command, or press the F5 key. This causes Visual Studio to build the project and create an assembly. Then, assuming that there are no build errors, the assembly is run so the project’s form is displayed as shown above.
If syntax errors are detected when a project is built, they’re listed in the Error List window and the project does not run.
To locate the statement that contains the error, you can double-click on the error description in the Error List window. After you’ve corrected all the errors, run the project again to rebuild it and clear the errors.
You can build a project without running it by selecting the Build->Build Solution command.
When you build a project for the first time, all of the components of the project are built. After that, only the components that have changed are rebuilt. To rebuild all components whether or not they’ve changed, use the Build->Rebuild Solution command.
When you test a project, you run it and make sure the application works correctly. As you test your project, you should try every possible combination of input data and user actions to be certain that the project works correctly in every case. Figure 3-14 provides an overview of the testing process for C# applications.
To start, you should test the user interface. Make sure that each control is sized and positioned properly, that there are no spelling errors in any of the controls or in the form’s title bar, and that the navigation features such as the tab order and access keys work properly.
Next, subject your application to a carefully thought-out sequence of valid test data. Make sure you test every combination of data that the project will handle. If, for example, the project calculates the discount at different values based on the value of the subtotal, use subtotals that fall within each range.
Finally, test the program to make sure that it properly handles invalid data entered by users. For example, type text information into text boxes that expect numeric data. Leave fields blank. Use negative numbers where they shouldn’t be allowed. Remember that the goal of testing is to find all of the problems.
As you test your projects, you’ll eventually encounter runtime errors. These errors, also known as exceptions, occur when C# encounters a problem that prevents a statement from being executed. If, for example, a user enters “ABC” into the Subtotal text box on the Invoice Total form, a runtime error will occur when the program tries to assign that value to a decimal variable.
When a runtime error occurs, Visual Studio breaks into the debugger and displays an Exception Assistant window like the one in this figure. Then, you can use the debugging tools that you’ll be introduced to in the next figure to debug the error.
Runtime errors, though, should only occur when you’re testing a program. Before an application is put into production, it should be coded and tested so all runtime errors are caught by the application and appropriate messages are displayed to the user. You’ll learn how to do that in chapter 7 of this book.
The message that’s displayed when a runtime error occurs
Figure 3-14.How to test a project
How to test a project
Test the user interface. Visually check all the controls to make sure they are displayed properly with the correct text. Use the Tab key to make sure the tab order is set correctly, verify that the access keys work right, and make sure that the Enter and Esc keys work properly.
Test valid input data. For example, enter data that you would expect a user to enter.
Test invalid data or unexpected user actions. For example, leave required fields blank, enter text data into numeric input fields, and use negative numbers where they are not appropriate. Try everything you can think of to make the program fail.
Description
To test a project, you run the project to make sure it works properly no matter what combinations of valid or invalid data you enter or what sequence of controls you use.
If a statement in your application can’t be executed, a runtime error, or exception, occurs. Then, if the exception isn’t handled by your application, the statement that caused the exception is highlighted and an Exception Assistant window like the one above is displayed. At that point, you need to debug the application as explained in the next figure.
When a runtime error occurs, Visual Studio enters break mode. In that mode, Visual Studio displays the Code Editor and highlights the statement that couldn’t be executed, displays the Debug toolbar, and displays an Exception Assistant dialog box like the one shown in figure 3-15. This is designed to help you find the cause of the exception (the bug), and to debug the application by preventing the exception from occurring again or by handling the exception. For example, you can often handle an exception by displaying an appropriate message to the user. This message may give the user one or more options for dealing with the exception.
Often, you can figure out what caused the problem just by knowing what statement couldn’t be executed, by reading the message displayed by the Exception Assistant, or by reading the troubleshooting tips displayed by the Exception Assistant. But sometimes, it helps to find out what the current values in some of the variables or properties in the program are. To do that, you can place the mouse pointer over a variable or property in the code so a data tip is displayed. This tip displays the current value of the variable or property.
For example, if the current value of the Text property of the txtSubtotal control is “ABC”, the data tip will clearly show that the Text property does not contain numeric data. However, the variable named subtotal requires numeric data. As a result, you know that the highlighted statement can’t be executed because the user didn’t enter numeric data in the Subtotal text box.
Once you find the cause of a bug, you can correct it. But first, you must exit from break mode. To do that, you can click the Stop Debugging button in the Debug toolbar. Then, you can correct the problem in the Code Editor and test the application again.
For now, don’t worry if you don’t know how to correct the problem in this example. Instead, you can assume that the user will enter valid data. In chapter 7, though, you’ll learn how to catch exceptions and validate all user entries for an application because that’s what a professional application has to do.
How a project looks in break mode
Figure 3-15. How to debug runtime errors
Description
When an application encounters a runtime error, you need to fix the error. This is commonly referred to as debugging, and the error is commonly referred to as a bug.
When an application encounters a runtime error, it enters break mode. In break mode, the Debug toolbar is displayed along with other windows that provide debugging features.
When an application displays the Exception Assistant window, you can read a description of the error. This should give you an idea of what the error might be. You can also click on the links in the Troubleshooting Tips list to display more information in a Help window. You’ll learn more about debugging and the Exception Assistant window in chapter 11.
To display a data tip for a property or variable, move the mouse pointer over it in the C# code. Then, its value is displayed in the data tip.
To exit break mode and end the application, click the Stop Debugging button in the Debug toolbar or press Shift+F5. Then, you can attempt to fix the error, and you can run the application again when you’re done fixing the error.
If you can code and test the Invoice Total project that’s presented in this chapter, you’ve already learned a lot about C# programming. You know how to enter the code for the event handlers that make the user interface work the way you want it to. You know how to build and test a project. And you know some simple debugging techniques.
On the other hand, you’ve still got a lot to learn. For starters, you need to learn the C# language. So in the next six chapters, you’ll learn the essentials of the C# language. Then, in chapter 11, you’ll learn some debugging techniques that can be used with more advanced code.
Terms --------------------------------------
object-oriented programming syntax error object-oriented language build error object comment class single-line comment instance delimited comment instantiation comment out a line property bookmark method collapse event expand member code snippet dot operator refactoring dot build a project static member run a project event-driven application test a project event handler runtime error event wiring exception method declaration bug method name debug statement break mode block of code data tip
Exercise 3-1 Code and test the Invoice Total form
In this exercise, you’ll add code to the Invoice Total form that you designed in exercise 2-1. Then, you’ll build and test the project to be sure it works correctly. You’ll also experiment with debugging and review some help information.
Copy and open the Invoice Total application
Use the Windows Explorer to copy the Invoice Total project that you created for chapter 2 from the C:\C# 2005\Chapter 02 directory to the C:\C# 2005\Chapter 03 directory.
Open the Invoice Total solution (InvoiceTotal.sln) that’s now in the C:\C# 2005\Chapter 03\InvoiceTotal directory.
Add code to the form and correct syntax errors
Display the Invoice Total form in the Form Designer, and double-click on the Calculate button to open the Code Editor and generate the method declaration for the Click event of this object. Then, enter the code for this method as shown in figure 3-5. As you enter the code, be sure to take advantage of all of the Visual Studio features for coding including snippets.
Return to the Form Designer, and double-click the Exit button to generate the method declaration for the Click event of this object. Enter the statement shown in figure 3-5 for this event handler.
Open the Error List window as described in figure 3-6. If any syntax errors are listed in this window, double-click on each error to move to the error in the Code Editor. Then, correct the error.
Test the application
Press F5 to build and run the project. If you corrected all the syntax errors in step 5, the build should succeed and the Invoice Total form should appear. If not, you’ll need to correct the errors and press F5 again.
Enter a valid numeric value in the first text box and click the Calculate button or press the Enter key to activate this button. Assuming that the calculation works, click the Exit button or press the Esc key to end the application. If either of these methods doesn’t work right, of course, you need to debug the problems and test the application again.
Enter invalid data and display data tips in break mode
Start the application again. This time, enter “xx” for the subtotal. Then, click the Calculate button. This will cause Visual Studio to enter break mode and display the Exception Assistant as shown in figure 3-15.
Note the highlighted statement and read the message that’s displayed in the Exception Assistant. Then, move the mouse pointer over the variable and property in this statement to display their data tips. This shows that the code for this application needs to be enhanced so it checks for invalid data. You’ll learn how to do that in chapter 7. For now, though, click the Stop Debugging button in the Debug toolbar to end the application.
Create a syntax error and see how it affects the IDE
When you return to the Code Editor, hide the Error List window by clicking on its Auto Hide button. Next, change the name of the Subtotal text box from txtSubtotal to txtSubTotal. This creates an error since the capitalization doesn’t match the capitalization used by the Name property of the text box.
Try to run the application, and click No when Visual Studio tells you the build had errors and asks whether you want to continue with the last successful build. Then, double-click on the error in the Error List, correct the error, and run the application again to make sure the problem is fixed.
Use refactoring
Change the name of the subtotal variable from subtotal to invoiceSubtotal. When you do a bar will appear under the last letter of the variable. Point at this bar to display a drop-down arrow. Then, click on this arrow and select the Rename command. This should rename the subtotal variable throughout the form, but run the form to make sure it’s working correctly.
Generate and delete an event handler
Display the Form Designer for the Invoice Total form and double-click a blank area on the form. This should generate an event handler for the Load event of the form.
Delete the event handler for the Load event of the form. Then, run the application. When you do, you’ll get a build error that indicates that the form does not contain a definition for this event handler.
Double-click on the error. This opens the Designer.cs file for the form and jumps to the statement that wires the event handler. Delete this statement to correct the error.
If you’re curious, review the generated code that’s stored in the Designer.cs file for this simple form. Then, click the minus sign to the left of the region named “Windows Form Designer generated code” to collapse this region.
Run the form to make sure it’s working correctly. When you return to the Code Editor, close the Designer.cs file for the form.
Experiment with the Help feature
To see how context-sensitive help works, place the insertion point in the Focus method in the last statement of the first event handler and press F1. This should open a Help window that tells you more about this method.
In the left pane, select the Index tab to display the Index window. Type “focus” into the Look For box in this window to see the entries that are listed under this topic. Next, if Visual C# (or Visual C# Express Edition) isn’t selected in the Filter By drop-down list, select it to show just the topics for C#. Then, click on one or more topics to display them.
Continue experimenting with the Index, Contents, Help Favorites, and Search features to see how they work, and try using some of the buttons in the Web toolbar to see how they work. Then, close the Help window.
Exit from Visual Studio
Click the Close button for the Visual Studio window to exit from this application. If you did everything and got your application to work right, you’ve come a long way!