Enhancing a Sample Application


To start enhancing the application, you are going to use the control Toolbox. Close the Form1 .designer.vb file and switch your display to the Form1.vb [Design] tab. The Toolbox window is available whenever a form is in Design mode. By default, the Toolbox, shown in Figure 13-22, lives on the left-hand side of Visual Studio as a tab. When you click this tab, the control window expands and you can then drag controls onto your form. Alternatively, if you have closed the Toolbox tab, you can go to the View menu and select Toolbox.

image from book
Figure 13-22

If you haven’t set up the Toolbox to be permanently visible, it will slide out of the way and disappear whenever focus is moved away from it. This helps maximize the available screen real estate. If you don’t like this feature and want the Toolbox to be permanently visible, just click the pushpin icon on the Toolbox’s title bar.

The Toolbox contains literally dozens of standard controls, and these controls have been categorized so it’s easier to find them. Figure 13-22 shows the result of dragging a Button control from the Toolbox and depositing it in the location where you want it on the form. The result is a new button displaying the text “Button1.” Adding another button would trigger the default naming and text of Button2.

Before customizing the first control added to this form, take a closer look at the Visual Studio Toolbox. An expanded view is shown in Figure 13-23. The tools are broken out by category, but this list of categories isn’t static. Visual Studio 2005 Standard and above editions enable you to create your own custom controls. When you create such controls, the IDE will - after they have been compiled - automatically add them to the display, when you are working in the same solution as the controls. These would be local references to controls that become available within the current solution.

image from book
Figure 13-23

Additionally, depending on whether you are working on a Web or a Windows Forms application, your list of controls in the Toolbox will vary. Windows Forms has a set of controls that leverages the power of the Windows operating system. Web applications, conversely, tend to have controls oriented to working in a disconnected environment.

It’s also possible to have third-party controls to your environment. Such controls can be registered with Visual Studio and are then displayed within every project you work on. The ASP.NET 2.0 AJAX controls are a good example of controls that can be added to your environment. Controls can add their own categories to the Toolbox so that they are grouped together and therefore easy to find.

Return to the button you’ve dragged onto the form; it’s ready to go in all respects. However, Visual Studio has no way of knowing how you want to customize it. Start by going to the Properties window and changing its text property to “Hello World.” You can then change the button’s (Name) property to ButtonHelloWorld. Having made these changes, double-click the button in the display view. Double-clicking tells Visual Studio that you want to add an event handler to this control, and by default Visual Studio adds an On_Click event handler for buttons. The IDE then shifts the display to the code view so that you can customize this handler (see Figure 13-24).

image from book
Figure 13-24

While the event handler can be added through the designer, it’s also possible to add event handlers from the code view. After you double-click the button, Visual Studio will transfer you to the code view and display your new event handler. Notice that in code view there are drop-down boxes on the top of the edit window. The boxes indicate the current object on the left - in this case, your new button; and the current method on the right - in this case, the click-event handler. You can add new handlers for other events on your button or form using these drop-down lists.

The drop-down box on the left-hand side lists the objects for which event handlers can be added. The drop-down box on the right-hand side lists all the events for the selected object. For now, you have created a new handler for your button’s click event, and it’s time to look at customizing the code associated with this event.

Customizing the Code

With the code window open to the newly added event handler for the “Hello World” button, you can start to customize this handler. Note that adding a control and event handler involves elements of generated code. Visual Studio adds code to the Form1.Designer.vb file. These changes occur in addition to the default method implementation you see in the editable portion of your source code.

Adding XML Comments

One of the new features of Visual Studio 2005 is the ability to create XML comments for Visual Basic. XML comments are a much more powerful feature than you probably realize, because they are also recognized by Visual Studio for use in IntelliSense. To add a new XML comment to your handler, go to the line before the handler and type three single quotation marks: '''. This triggers Visual Studio to replace your single quotation marks with the following block of comments. You can trigger these comments in front of any method, class, or property in your code:

  ''' <summary> ''' ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> 

Note that Visual Studio has provided a template that offers a place to include a summary of what this method does. It also provides placeholders to describe each parameter that is part of this method. Not only are the comments entered in these sections available within the source code, when it’s compiled you’ll also find an XML file in the project directory summarizing all your XML comments that can be used to generate documentation and help files for the said source code. By the way, if you refactor a method and add new parameters, the XML comments also support IntelliSense for the XML tags that represent your parameters.

Customizing the Event Handler

Now customize the code for the button handler, as this method doesn’t actually do anything by default. Add a command to open a message box and show the “Hello World” message. Use the System.Windows.Forms.MessageBox class. Fortunately, because that namespace is automatically imported into every source file in your project, thanks to your project references, you can reference the MessageBox.Show method directly. The Show method has several different parameters, and as shown in Figure 13-24, not only does the IDE provide a tooltip for the list of parameters, it also provides help on the appropriate value for individual parameters.

The completed call to MessageBox.Show should look similar to the following code block. Note that the underscore character is used to continue the command across multiple lines. Also note that unlike previous versions of Visual Basic, where parentheses were sometimes unnecessary, in .NET the syntax best practice is to use parentheses for every method call:

  MessageBox.Show("Hello World", _                "Hello World Message Box", _                MessageBoxButtons.OK, _                MessageBoxIcon.Information) 

Once you have entered this line of code, you may notice a squiggly line underneath some portion of your text. This occurs when there is an error in the line you have typed. In previous versions of Visual

Basic, the development environment would interrupt your progress with a dialog box, but with .NET, the IDE works more like the latest version of Word. Instead of interrupting your progress, it highlights the problem and allows you to continue working on your code. This is a feature of Visual Basic that isn’t available in other .NET languages such as C#. Visual Basic is constantly reviewing your code to ensure that it will compile; and when it encounters a problem it immediately notifies you of the location without interrupting your work.

Reviewing the Code

Now that you have created a simple Windows application, let’s review the elements of the code that have been added by the IDE. Following is the entire Form1.Designer.vb source listing. Highlighted in this listing are the lines of code that have changed since the original template was used to generate this project:

 <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Public Class Form1     Inherits System.Windows.Forms.Form     'Form overrides dispose to clean up the component list.     <System.Diagnostics.DebuggerNonUserCode()> _     Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)              If disposing AndAlso components IsNot Nothing Then                 components.Dispose()         End If         MyBase.Dispose(disposing)     End Sub     'Required by the Windows Form Designer     Private components As System.ComponentModel.Icontainer     'NOTE: The following procedure is required by the Windows Form Designer     'It can be modified using the Windows Form Designer.      'Do not modify it using the code editor.   <System.Diagnostics.DebuggerStepThrough()> _   Private Sub InitializeComponent()      Me. ButtonHelloWorld = New System.Windows.Forms.Button()      Me.SuspendLayout()      '      'ButtonHelloWorld      '      Me.ButtonHelloWorld.Location = New System.Drawing.Point(112, 112)      Me.ButtonHelloWorld.Name = "ButtonHelloWorld"      Me.ButtonHelloWorld.Size = New System.Drawing.Size(75, 23)      Me.ButtonHelloWorld.TabIndex = 0      Me.ButtonHelloWorld.Text = "Hello World"     '     'Form1     '     Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)     Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font    Me.ClientSize = New System.Drawing.Size(292, 273)     Me.Controls.Add(Me.ButtonHelloWorld)     Me.Name = "Form1"      Me.Text = "Professional VB.NET"      Me.ResumeLayout(False)   End Sub   Friend WithEvents ButtonHelloWorld As System.Windows.Forms.Button End Class

After the class declaration in the generated file, the first change made to the code is the addition of a new variable to represent the new button:

  Friend WithEvents ButtonHelloWorld As System.Windows.Forms.Button 

When any type of control is added to the form, a new variable is added to the form class. Controls are represented by variables; and, just as form properties are set in code, form controls are added in code. The Button class in the System.Windows.Forms namespace implements the button control on the Toolbox. Each control added to a form has a class that implements the functionality of the control. For the standard controls, these classes are usually found in the System.Windows.Forms namespace. The WithEvents keyword has been used in the declaration of the new variable so that it can respond to events raised by the button.

The bulk of the code changes are in the InitializeComponent procedure. Eight lines of code have been added to help set up and display the button control. The first addition to the procedure is a line that creates a new instance of the Button class and assigns it to the button variable:

  Me.ButtonHelloWorld = New System.Windows.Forms.Button() 

Before a button is added to the form, the form’s layout engine must be paused. This is done using the next line of code:

  Me.SuspendLayout() 

The next four lines of code set the properties of the button. The Location property of the Button class sets the location of the top-left corner of the button within the form:

  Me.ButtonHelloWorld.Location = New System.Drawing.Point(112, 112) 

The location of a control is expressed in terms of a Point structure. Next, the Name property of the button is set:

  Me.ButtonHelloWorld.Name = "ButtonHelloWorld" 

The Name property acts in exactly the same way as it did for the form, setting the textual name of the button. The Name property has no effect on how the button is displayed on the form; it is used to recognize the button’s context within the source code. The next two lines of code assign values to the TabIndex and Text properties of the button:

  Me.ButtonHelloWorld.TabIndex = 0 Me.ButtonHelloWorld.Text = "Hello World" 

The TabIndex property of the button is used to set the order in which the control is selected when a user cycles through the controls on the form using the Tab key. The higher the number, the later the control gains focus. Each control should have a unique number for its TabIndex property. The Text property of a button sets the text that appears on the button.

Once the properties of the button have been set, it needs to be added to the form. This is accomplished with the next line of code:

  Me.Controls.Add(Me.ButtonHelloWorld) 

The System.Windows.Forms.Form class (from which your Form1 class is derived) has a property called Controls that keeps track of all of the child controls of the form. Whenever you add a control to a form in the designer, a line similar to the preceding one is added automatically to the form’s initialization process.

Finally, near the bottom of the initialization logic is the final code change. The form is given permission to resume the layout logic:

  Me.ResumeLayout(False) 

In addition to the code that has been generated in the Form1.Designer.vb source file, you have created code that lives in the Form1.vb source file:

  Imports System.Windows.Forms Public Class Form1     ''' <summary>     '''     ''' </summary>     ''' <param name="sender"></param>     ''' <param name="e"></param>     ''' <remarks></remarks>    Private Sub ButtonHelloWorld_Click (ByVal sender As System.Object, _                                  ByVal e As System.EventArgs) _                                  Handles ButtonHelloWorld.Click      MessageBox.Show("Hello World", _                       "Hello World Message Box", _                       MessageBoxButtons.OK, _                       MessageBoxIcon.Information)   End Sub End Class 

This code reflects the event handler added for the button. The code contained in the handler was already covered, with the exception of the naming convention for event handlers. Event handlers have a naming convention similar to that in previous versions of Visual Basic: the control name is followed by an underscore and then the event name. The event itself may also have a standard set of parameters. At this point, you can test the application, but let’s first review your build options.

Building Applications

For this example, it is best just to build your sample application using the Debug build configuration. The first step is to ensure that Debug is selected as the active configuration in the Configuration drop-down list box discussed in the previous section. Visual Studio provides an entire Build menu with the various options available for building an application. There are essentially two options for building applications:

  • Build - This option uses the currently active build configuration to build the project or solution, depending upon what is available.

  • Publish - For Visual Basic developers this option starts the process of doing a release build, but note that it also ties in with the deployment of your application, in that you are asked to provide an URL where the application will be published.

The Build menu supports building for either the current project or the entire solution. Thus, you can choose to build only a single project in your solution or all of the projects that have been defined as part of the current configuration. Of course, anytime you choose to test-run your application, the compiler will automatically perform a compilation check to ensure that you run the most recent version of your code.

You can either select Build from the menu or use the Ctrl+Shift+B keyboard combination to initiate a build. When you build your application, the Output window along the bottom edge of the development environment will open. As shown in Figure 13-25, it displays status messages associated with the build process. This window indicates your success in building your application. Once your application has been built successfully, you will find the executable file located in the targeted directory. By default, for .NET applications this is the \bin subdirectory of your project directory.

image from book
Figure 13-25

If you encounter any problems building your application, Visual Studio provides a separate window to help track them. If an error occurs, the Task List window will open as a tabbed window in the same region occupied by the Output window shown in Figure 13-25. Each error triggers a separate item in the Task List; if you double-click an error, Visual Studio automatically repositions you on the line with the error. Once your application has been built successfully, you can run it.

Running an Application in the Debugger

As discussed earlier, there are several ways to start your application. Starting the application launches a series of events. First, Visual Studio looks for any modified files and saves those files automatically. It then verifies the build status of your solution and rebuilds any project that does not have an updated binary, including dependencies. Finally, it initiates a separate process space and starts your application with the Visual Studio debugger attached to that process.

When your application is running, the look and feel of Visual Studio’s IDE changes, with different windows and button bars becoming visible. While your solution and code remain visible, the IDE displays additional windows such as the Call Stack, Locals, and Watch windows (see the bottom section of Figure 13-26). Note that not all of these windows are available to users of Visual Studio Express Edition. These windows are used by the debugger for reviewing the current value of variables within your code.

image from book
Figure 13-26

At this point, the debugger doesn’t really play much of a role in running your application. The power of the Visual Studio debugger is its interactive debugging. To demonstrate this, with your application running, select Visual Studio as the active window. Change your display to the Form1.vb code view (not design view) and click in the border alongside the line of code you added to open a message box when the “Hello World” button is clicked. Doing this creates a breakpoint on the selected line (refer to Figure 13-26). Return to your application and then click the “Hello World” button. Visual Studio takes the active focus and within your code window, and the line with your breakpoint is now selected.

Breakpoints

You are seeing a breakpoint in action. The key to working with Visual Studio is to recognize the value of the debugger. It is, in fact, more important than any of the developer productivity features of Visual Studio. Once you are on this breakpoint you have control of every aspect of your running code. For example, move your mouse and hover over the parameter sender and you can see a reference to this object. More important, you see a small plus sign on the right-hand side, which if clicked expands the pop-up showing details about the properties of this object. You can do this for any local variable. Windows such as Locals and Autos display similar information on your variables, and you can use these to update those properties while the application is running.

Once at this breakpoint, you can control your application by leveraging the Debug toolbar. This toolbar comes with several options for managing the flow of your application. On the left is a run button and a stop button and a button that may remind you of a carriage return. That return arrow button restarts your application. The toolbar has three buttons that show arrows in relation to a series of lines. These are Step-In, Step-Over, and Step-Out, respectively.

Step-In tells the debugger to attempt to walk to whatever line of code is first within the next method or property you call. Keep in mind that if you pass a property value as a parameter to a method, the first such line of code is in the Get method of the parameter. Once there, you may want to step out. Stepping out of a method tells the debugger to execute the code in the current method and return you to the line that called this method. Thus, you could step out of the property and then step in again to get into the method you are actually interested in debugging.

Of course, sometimes you don’t want to step into a method; this is where the Step-Over button comes in. It enables you to call whatever method(s) are on the current line and step to the next sequential line of code in the method you are currently debugging. Each of the buttons shown on the debugging toolbar in Figure 13-25 has an accompanying shortcut key for experienced developers who want to move quickly through a series of breakpoints.

However, breakpoints go beyond what you can do with them at runtime. Visual Basic 2005 Express Edition does not support the advanced properties of breakpoints, but Visual Studio provides additional properties for working with them. As shown in Figure 13-27, it’s also possible to add specific properties to your breakpoints. The context menu shows several possible options. You can disable breakpoints that you don’t currently want to stop your application flow. You can also move a breakpoint, although it’s usually easier to just click and delete the current location, and then click and create a new breakpoint at the new location.

image from book
Figure 13-27

More important, it’s possible to specify that a given breakpoint should only execute if a certain value is defined (or undefined). In other words, you can make hitting a given breakpoint conditional, and a popup window enables you to define this condition. Similarly, if you’ve ever wanted to stop on the thirtyseventh iteration of a loop, you know the pain of repeatedly stopping at a breakpoint inside a loop. Visual Studio allows you to specify that a given breakpoint should only stop your application after some specified number of hits.

The next option is one of the more interesting options if you need to carry out a debug session in a live environment. It’s possible to create a breakpoint on the debug version of code and then add a filter that ensures you are the only user to stop on that breakpoint. This means that if you are in an environment where multiple people are working against the same executable, you can add a breakpoint that won’t interfere with the other users of the applications.

Similarly, instead of just stopping at a breakpoint, you can also tell the breakpoint to execute some other code, possibly even a Visual Studio macro, when a given breakpoint is reached. These actions are somewhat limited and are not frequently used, but in some situations this capability can be used to your advantage.

Note that breakpoints are saved when a solution is saved by the IDE. There is also a Breakpoints window, which provides a common location for managing breakpoints that you may have set across several different source files.

Other Debug-Related Windows

As noted earlier, when you run an application in Debug mode, Visual Studio .NET 2003 opens a series of windows related to debugging. Each of these windows provides a view of a limited set of the overall environment in which your application is running. From these windows, it is possible to find things such as the list of calls (stack) used to get to the current line of code or the present value of all the variables currently available. Visual Studio has a powerful debugger that is fully supported with IntelliSense, and these windows extend the debugger.

Output

Recall that the build process puts progress messages in this window. Similarly, your program can also place messages in it. Several options for accessing this window are discussed in later chapters, but at the simplest level the Console object echoes its output to this window during a debug session. For example, the following line of code can be added to your sample application:

  Console.WriteLine("This is printed in the Output Window") 

This line of code will cause the string This is printed in the Output Window to appear in the Output window when your application is running. You can verify this by adding this line in front of the command to open the message box. Then, run your application and have the debugger stop on the line where the message box is opened. Examining the contents of the Output window, you will find that your string is displayed.

Anything written to the Output window is shown only while running a program from the environment. During execution of the compiled module, no Output window is present, so nothing can be written to it. This is the basic concept behind other objects such as the Debug and Trace objects, which are covered in more detail in Chapter 9.

Call Stack

The Call Stack window lists the procedures that are currently calling other procedures and waiting for their return. The call stack represents the path through your code that has led to the currently executing command. This can be a valuable tool when you are trying to determine what code is executing a line of code that you didn’t expect to execute.

Locals

The Locals window is used to monitor the value of all variables that are currently in scope. This is a fairly self-explanatory window that shows a list of the current local variables and next to each item the value of the variable. As in previous versions of Visual Studio, this display supports the examination of the contents of objects and arrays via a tree-control interface. It also supports the editing of those values, so if you want to change a string from empty to what you thought it would be, just to see what else might be broken, then feel free to do so from here.

Watch Windows

There are four Watch windows, called Watch 1 to Watch 4. Each window can hold a set of variables or expressions for which you want to monitor the value. It is also possible to modify the value of a variable from within a Watch window. The display can be set to show variable values in decimal or hexadecimal format. To add a variable to a Watch window, right-click the variable in the Code Editor and then select Add Watch from the pop-up menu.

Immediate Window

The Immediate window, as its name implies, allows you to evaluate expressions. This window becomes available while you are in Debug mode. This is a powerful window, one which can save or ruin a debug session. For example, using the sample from earlier in this chapter, you can start the application and press the button to stop on the breakpoint. Go to the Immediate Window, and enter ?Button1.Text = “Click Me” and press return. You should get a response of false as the Immediate window evaluates this statement.

Notice the preceding ?, which tells the debugger to evaluate your statement, rather than execute it. Repeat the preceding but omit the question mark: Button1.Text = “Click Me”. Press F5 or click the Run button to return control to your application, and notice the caption on your button. From the Immediate window you have updated this value. This window can be very useful if you are working in Debug mode and need to modify a value that is part of a running application.

Autos

Finally, as the chapter prepares to transition to features that are only available in Visual Studio and not Visual Basic 2005 Express, there is the Autos window. The Autos window displays variables used in the statement currently being executed and the statement just before it. These variables are identified and listed for you automatically, hence the window’s name. This window shows more than just your local variables. For example, if you are in Debug mode on the line to open the MessageBox in the ProVB.NET sample, then the MessageBox constants referenced on this line are shown in this window. This window enables you to see the content of every variable involved in the currently executing command. As with the Locals window, you can edit the value of a variable during a debug session. However, this window is in fact specific to Visual Studio and not available to users of Visual Basic 2005 Express.




Professional VB 2005 with. NET 3. 0
Professional VB 2005 with .NET 3.0 (Programmer to Programmer)
ISBN: 0470124709
EAN: 2147483647
Year: 2004
Pages: 267

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