Chapter 13. Visual Studio 2008

It's possible to work with Visual Basic without Visual Studio. In practice, however, the two are almost inseparable; without a version of Visual Studio, you're forced to work from the command line to create project files by hand, to make calls to the associated compilers, and to manually address the tools necessary to build your application. Thus, while it is possible, Visual Studio 2008 is the preferred environment for developing Visual Basic applications.

With the release of Visual Studio 2005, Microsoft expanded on the different versions of Visual Studio available for use. Unlike the early versions, they've expanded what we'll call the high-end and low-end packages associated with Visual Studio. At the low-cost end, currently free, is Visual Basic Express Edition. This tool enables you to build desktop applications with Visual Basic only. Its companion for Web development is Visual Web Developer Express, which enables you to build ASP.NET applications. At the high end, Microsoft offers Visual Studio Team System, available only with a high-cost MSDN subscription, which includes many tools that extend Visual Studio beyond the core Integrated Development Environment (IDE) to help improve design, testing, and collaboration between developers.

Of course, the focus of this chapter is how Visual Studio enables you to use Visual Basic to build applications geared toward "better, faster, cheaper" business goals. To this end, we'll be examining features of Visual Studio starting with those in the core Visual Basic 2008 Express Edition and building up to the full Visual Studio Team Suite. Topics in this chapter include the following:

  • Versions of Visual Studio

  • Project templates

  • Project properties — application, compilation, debug, and so on

  • Setting properties

  • IntelliSense, code expansion, and code snippets

  • Targeting a runtime environment

  • Debugging

  • Recording and using macros

  • The Class Designer

  • Visual Studio tools for Office

  • Team System — Team Suite Client Tools

  • Team Foundation Server — Team Explorer

This chapter provides an overview of many of the capabilities of Visual Studio 2008, with a brief introduction to the features available by using one of the more feature-rich versions of Visual Studio. The goal is to demonstrate how Visual Studio makes you, as a developer, more productive and successful.

Visual Studio 2008: Express through Team Suite

Visual Studio 2003 was focused on .NET 1.1, and Visual Studio .NET (2002) was focused on .NET 1.0, so each version of Visual Studio has been optimized for a particular version of .NET. Similarly, Visual Studio 2005 was optimized for .NET 2.0, and with the exception of unsupported add-ons, didn't support the new features of .NET 3.0.

Fortunately, Microsoft chose to keep Visual Basic and ASP.NET unchanged for the .NET 3.0 Framework release. However, when you looked at the new .NET 3.0 Framework elements, such as Windows Presentation Foundation, Windows Communication Foundation, and Windows Workflow Foundation, you saw those items needed to be addressed outside of Visual Studio. Thus, while Visual Studio 2005 was separate from Visual Basic and .NET development, in practical terms the two were tightly coupled.

With Visual Studio 2008, Microsoft provides robust support for the ability to target any of three different versions of the .NET Framework. Visual Studio 2008 enables you to target an application to run on .NET 2.0, .NET 3.0, or .NET 3.5. However, as you'll discover, this support doesn't mean that Visual Studio 2008 isn't tightly coupled to its own compiler. In fact, the new support for targeting frameworks is designed to support a runtime environment, not a compile-time environment. This is important because Visual Studio 2005 projects are converted to the Visual Studio 2008 format when you open them, after which they cannot be reopened by Visual Studio 2005.

The reason for this is that the underlying build engine used by Visual Studio 2008 accepts syntax changes and even language feature changes such as XML literals, but the Visual Studio 2005 engine does not recognize these new elements of the language. Thus, if you move source code written in Visual Studio 2008 to Visual Studio 2005, you face a strong possibility that it would fail to compile. There are ways to manually work with a project across versions 2005 and 2008 of Visual Studio on the same team, but they are not supported. Bill Sheldon, one of the authors of this book, has a blog post from August 2007 that deals with his experience doing this titled "Working with Both VS 2005 and VS 2008 B2 on the Same Project": http://blogs.interknowlogy.com/billsheldon/archive/2007/08/29/21175.aspx.

Multitargeting support by Visual Studio 2008 ensures that your application will run on a specific version of the framework. Thus, if your organization is not supporting .NET 3.0 or .NET 3.5, you can still use Visual Studio 2008 and be reasonably certain that your application will not reference files from one of those other framework versions. Multitargeting is what enables you to safely deploy without requiring your customers to download additional framework components they don't need.

With those ground rules in place, what versions of Visual Studio 2008 are available and what are the primary differences between them? As already mentioned, Visual Basic 2008 Express is at the bottom tier in terms of price and features. It is accompanied there by Visual Web Developer 2008 Express Edition, for those developers who are developing Web applications, rather than desktop applications. These two tools are separate, but both support developing different types of Visual Basic applications, and coincidentally both are free. Note, however, that neither is extensible; these tools are meant to be introductory, and Microsoft's license prevents vendors from extending these tools with productivity enhancements.

However, each of the Express edition development tools also ships with two additional components covered briefly here: MSDN Express Edition and SQL Server 2005 Express Edition. MSDN is, of course, the Microsoft Developer Network, which has placed most of its content online. It's the source for not only the core language documentation for Visual Basic, but also articles on almost every product oriented to developers using Microsoft technology. Full versions of Visual Studio ship with the full MSDN library so that you can access its content locally. However, the Express Edition tools actually ship with a pared-down 200 MB set of documentation files — of course, that's still a lot of documentation.

Similar to the language and Web-based tools, Microsoft has a SQL Server Express Edition package. This package actually has a history, in that it replaces the MSDE database engine that was available with SQL Server 2000. The SQL Server Express engine provides the core SQL Server 2005 database engine. Unlike MSDE, it also offers a free management application available via a separate download from Microsoft.

When you install Visual Studio 2008, including the Express Editions, you also have the opportunity to install this core database engine. The elements of this engine are freely redistributable, so if you are looking for a set of core database features based on ADO.NET, you can create your application and deploy your SQL Server 2005 Express Edition database without being concerned about licensing. SQL Server is covered in more detail in Chapter 14.

Getting back to the differences in versions, the Express Edition tools provide the core components necessary to create Visual Basic applications (Windows or Web) based on the core IDE. The following table provides a quick summary of what versions are available, including a description of how each extends Visual Studio:

Visual Studio Edition

Description

Visual Basic 2008 Express Edition

This is the core set of functionality required for creating Windows-based applications. It includes the IDE with full local debugging support and support for five project types: Windows Forms Application, Dynamic Link Library, WPF Application, WPF Browser Application, and Console Application.

Visual Web Developer 2008 Express Edition

The core set of functionality required for building Web applications. It supports both Visual Basic and C# and allows for local debugging of your Web application.

Visual Studio 2008 Standard Edition

Provides a combined development language for the core Visual Studio languages (J#, VB, C# and C++). It adds the Object Modeling tool, and provides combined support for both Windows and Web applications. It also provides additional support for application deployment, and support for Mobile Application Development, integration with a source control tool, and macros within Visual Studio; it is also extensible.

Visual Studio 2008 Professional Edition

Expands on Visual Studio Standard Edition with additional integration to SQL Server and support for XSLTs. It also includes support for Visual Studio Tools for Office, which enables you to create custom client (Word, Excel, Outlook, etc.) and SharePoint Workflow applications. This version also allows for remote debugging of Web applications.

Visual Studio 2008 Team Edition for*

When Visual Studio 2005 was released, Microsoft provided three specialized versions of Visual Studio 2005 Team Suite, each of which contained everything from the previously mentioned versions plus a subset of the Team Suite client tools. The editions were Team Edition for Architects, Team Edition for Developers, and Team Edition for Testers. Since then, Microsoft released a fourth edition that is available with Visual Studio 2008: Team Edition for Database Developers. Each edition contains a subset of the full Team Suite of tools, and includes a client license for Microsoft Team Foundation Server. These must be purchased as part of an annual MSDN package.

Visual Studio 2008 Team Suite

The full Team Suite includes all of the core features of Visual Studio 2008 Professional Edition and Visual Studio Tools for Office. It also includes all the tools from Visual Studio Team Suite: static code analysis, code profiling (performance testing), unit tests (which may be written in Visual Basic), application and deployment graphical design tools, Web and load-testing tools, and a variety of related tools to enhance development. This tool, like the Team Edition versions of Visual Studio, is focused on enabling developers to be productive in a shared collaborative environment. It works best when combined with Microsoft Team Foundation Server for source control and collaboration capabilities.

The Express Edition tools are best described as targeting students and hobbyists, not because you can't create serious applications but because they provide only limited support for team development, have limited extensibility, and offer a standalone environment. The Express Tools are oriented toward developers who work independently, while still providing full access to features of the Visual Basic language. This chapter begins working in the IDE using this version, which is essentially the lowest common denominator, and then extends beyond the capabilities of this free tool.

Eventually, however, a developer needs additional tools and projects. This is where the full versions of Visual Studio 2008 (Standard and Professional) come in. With an increasing level of support for team development, these feature rich versions add macro support, and, more important, an Object Modeling tool. As discussed later in this chapter, the Object Modeling tool enables you to create a visual representation of the classes in your solution and then convert that representation into code. Moreover, the tool supports what is known as round-trip engineering. This means that not only can you use the graphical model to generate code, you can also take a project's source files and regenerate an updated version of the graphical model — that is, edit that model in its graphical format and then update the associated source files.

For those choosing Visual Studio 2008 Professional or above, Visual Studio Tools for Office (VSTO) is targeted primarily at enterprise developers, those who work in corporate organizations (either as employees or consultant/contractors). This tool provides a way for users of the enterprise editions of Microsoft Office 2003 and Microsoft Office 2007 to extend these office productivity tools with applicationlike features. Many organizations use Microsoft Office for tasks that border on custom applications. This is especially true for Microsoft Excel. VSTO provides project templates based on these Microsoft Office products that enable, for example, a spreadsheet to retrieve its contents from an SQL Server database instead of the local file system. These tools provide the capability not only to manipulate data retrieval and saving, but also to customize the user interface, including direct access to the task pane and custom toolbar options within Microsoft Office products; they are covered in more detail in Chapter 22.

Visual Studio 2008 Team Suite and the various Team Edition products focus on extending a developer's reach beyond just writing code. These tools are used to examine code for flaws, manage the deployment environment, and define relationships between applications. The suite is focused on tools that support repeatable software processes and best practices. They are geared toward examining source code for hidden flaws that might not cause the code to fail but might hide a hidden security flaw or make it difficult to maintain or deploy the application. More important, the suite includes tools for creating unit test tools that attempt to cause the code to fail, whether through bad input data or heavy load. The Team Suite tools are focused on automating software development best practices for application teams, as opposed to actually writing the application.

Complete coverage of all of Team System warrants a book of its own, especially when you take into account all of the collaborative features introduced by Team Foundation Server and its tight integration with both Team Build and SharePoint Server. Team Foundation Server goes beyond just being a replacement for Visual Source Safe. It is the basis for true process-driven development, and it even includes documentation to help train your organization on two process models supported by Microsoft. The Team System extensions to the Microsoft software development suite are nontrivial, and are discussed in more detail at the end of this chapter.

Creating a Project from a Project Template

While it is possible to create a Visual Basic application working entirely outside of Visual Studio 2008, it is much easier to start from Visual Studio 2008. After you install Visual Studio you are presented with a screen similar to the one shown in Figure 13-1 for Visual Studio 2008 Express Edition. The starting default behavior is for the IDE to display the start page in its central section. The start page lists your most recent projects in the upper-left corner, some tips for getting started below that, and a headline section below that. You may or may not immediately recognize that this content is HTML text; more important, the content is based on an RSS feed that retrieves and caches articles appropriate for your version of Visual Studio.

The start page looks similar regardless of which version of Visual Studio 2008 you are running. Conceptually, it provides a generic starting point either to select the application you intend to work on, to quickly receive vital news related to offers, as shown in the figure, or to connect with external resources via the community links.

Once here, the next step is to create your first project. Selecting File

Creating a Project from a Project Template
Figure 13-1

Figure 13.1. Figure 13-1

Figure 13-2

Figure 13.2. Figure 13-2

One of the ongoing challenges with describing the menu options for Visual Studio is that the various versions have slight differences in look and feel too numerous to mention. For example File

Figure 13-2

Noteworthy in Figure 13-2 is something that is missing: the ability to target different versions of the .NET Framework. With the Express editions, Microsoft has made it so that you will always target the current .NET 3.5 version of the .NET Framework when you create your project. However, as you'll see later in this chapter, you can retarget your application via the Compile Settings.

Another important item to note is that unlike Visual Basic 2005 Express Edition, there are no Starter Kits. These kits went beyond just the basic files associated with a generic project template and included source files associated with a specific application. You'll also note that the dialog includes a reference to My Templates. This section of the New Project window enables you to find and install additional templates. For example, the Microsoft site for Visual Basic enables you to download several additional Starter Kits for everything from PayPal and Amazon.com interfaces to Blackjack and Lego Mindstorms, plus others you can install. Additionally, third parties such as Dot Net Nuke provide custom templates associated with their application. Dot Net Nuke is an excellent example of this type of jump start for your projects.

In order to keep the discussion of project templates in context, Figure 13-3 is an example of the same dialog opened from Visual Studio 2008 Team Suite. In this context, note that not only do you have additional project templates related to Visual Basic, but another pane that groups the templates into project types has been added. Figures 13-2 and 13-3 have different display options selected in the upper-right corner related to the size of the template icons only. The Visual Studio 2008 version of the New Project dialog also includes, in the upper-right corner, an option for you to select which version of the .NET Framework you are targeting.

Figure 13-3

Figure 13.3. Figure 13-3

A quick note regarding the New Project dialog: In Visual Studio 2005, if you wanted to create an ASP.NET 2.0 website, you needed to start that process by creating a new website instead of creating a new project. Under Visual Studio 2008, the Web projects have been restored to participants as project types; however, to create an ASP.NET website that isn't project-based, you will still want to access the New Website menu item instead of the New Project menu item on the file menu.

Note that in Figure 13-3 the New Project dialog is targeting a .NET 2.0 project, and there are six common project types at the top level of the Visual Basic hierarchy. In Figure 13-4, the target has been changed to .NET 3.5 and the number of available project types has doubled. Targeting keeps you from attempting to create a project for WPF without recognizing that you also need at least .NET 3.0 available on the client. Although you can change your target after you create your project, be very careful when trying to reduce the version number, as the controls to prevent you from selecting dependencies don't check your existing code base for violations. Changing your targeted framework version is covered in more detail later in this chapter.

Figure 13-4

Figure 13.4. Figure 13-4

Expanding the top level of the Visual Basic tree in Figure 13-4 shows that a project type can be further separated into a series of categories:

  • Windows — These are projects used to create applications that run on the local computer within the CLR. Because such projects can run on any operating system (OS) hosting the framework, the category "Windows" is something of a misnomer when compared to, for example, "Desktop."

  • Web — The original .NET 1.x websites relied on a project file. In .NET 2.0 this project style was briefly removed, but it's back again. You can create these projects, including Web services, from this section of the New Project dialog.

  • Smart Device — These are projects that target the .NET Compact Framework. Such applications may run on one or more handheld devices and make use of a different runtime environment from full .NET applications.

  • Office — Visual Studio Tools for Office (VSTO). These are .NET applications that are hosted under Office. Visual Studio 2008 includes a set of templates you can use to target Office 2003, as well as a separate section for templates that target Office 2007. Note that the project types in Office 2007 include not only client applications but also SharePoint Workflow projects.

  • Database — This template creates a project that supports classes that will run within SQL Server 2005. All versions of SQL Server 2005 (from Express through Enterprise) support the .NET Framework as part of their runtime, and such projects have a unique set of runtime constraints. This is a very different project template from the Database project template provided under the Other Project Types option.

  • Reporting — This is a new project type that enables you to create a Reports application.

  • Test — This section is available only to those using Visual Studio Team Suite. It contains the template for a Visual Basic Unit Test project.

  • WCF — This is the section where you can create Windows Communication Foundation projects.

  • Workflow — This is the section where you can create Windows Workflow Foundation (WF) projects. The templates in this section also include templates for connecting with the SharePoint workflow engine.

Visual Studio has other categories for projects, and you have access to other development languages and far more project types than this chapter has room for. For now, you can select a Windows Application project template to use as an example project for this chapter.

For this example, use ProVB_VS as the project name and then click OK. Visual Studio takes over and uses the Windows Application template to create a new Windows Forms project. The project contains a blank form that can be customized, and a variety of other elements that you can explore. Before customizing any code, let's first look at the elements of this new project.

The Solution Explorer

While the solution window both exists and is applicable for Express Edition users, it will never contain more than a single project. Those with a version of Visual Studio above the Express Edition level have the capability to leverage multiple projects in a single solution. A .NET solution can contain projects of any .NET language and can include the database, testing, and installation projects as part of the overall solution. The advantage of combining these projects is that it is easier to debug projects that reside in a common solution.

Before discussing these files in detail, let's take a look at the next step, which is to reveal a few additional details about your project. Click the second button on the left in Solution Explorer to display all of the project files, as shown in Figure 13-5. As this image shows, many other files make up your project. Some of these, such as those under the My Project grouping, don't require you to edit them directly. Instead, you can double-click on the My Project entry in the Solution Explorer and open the pages to edit your project settings. You do not need to change any of the default settings for this project, but the next section of this chapter walks you through the various property screens.

The bin and obj directories shown are used when building your project. The obj directory contains the first-pass object files used by the compiler to create your final executable file. The "binary" or compiled version of your application is then placed in the bin directory by default. Of course, referring to the Microsoft Intermediate Language (MSIL) code as binary is something of a misnomer, as the actual translation to binary does not occur until runtime when your application is compiled by the just-in-time (JIT) compiler. However, Microsoft continues to use the bin directory as the default output directory for your project's compilation.

Figure 13-5 also shows that the project does not contain an app.config file by default. Most experienced ASP.NET developers are familiar with using web.config files. App.config files work on the same principle in that they contain XML, which is used to store project-specific settings such as database connection strings and other application-specific settings. Using a .config file instead of having your settings in the Windows registry enables your applications to run side by side with another version of the application without the settings from either version impacting the other. Because each version of your application resides in its own directory, its settings are contained in the directory with it, which enables the different versions to run with unique settings. Before we are done going through the project properties, we will add an App.Config file to this project.

Figure 13-5

Figure 13.5. Figure 13-5

Finally, the Solution Explorer includes your actual source file(s). In this case, the Form1.vb file is the primary file associated with the default Windows form. You'll be customizing this form shortly, but before looking at that, it would be useful to look at some of the settings available by opening your project properties. An easy way to do this is to double-click on the My Project heading shown in Figure 13-5.

My Project Properties

Visual Studio displays a vertically tabbed display for editing your project settings. The My Project display shown in Figure 13-6, which is the view for users of Express Edition, is the same for all versions of Visual Studio. The project properties give you access to several different aspects of your project. Some, such as Signing, Security, and Publish, are covered in later chapters. For now, just note that this display makes it easier to carry out several tasks that once required engineers to work outside the Visual Studio environment.

Notice that you can customize your assembly name from this screen, as well as reset the type of application and object to be referenced when starting your application. However, resetting the type of your application is not recommended. If you start with the wrong application type, it is better to create a new application, due to all the embedded settings in the application template.

In the next section you will look at a button for changing your assembly information, as well as the capability to define a root namespace for your application classes. Namespaces are covered in detail in Chapter 7. You also have two buttons, one of which is related to Assembly Information, which is covered in the next section. The other button refers to User Access Control settings, which enable you to specify that only certain users can successfully start your application. In short, you have the option to limit your application access to a specific set of users.

Figure 13-6

Figure 13.6. Figure 13-6

Finally, note that there is a section associated with enabling an application framework. The application framework is a set of optional components that enable you to extend your application with custom events and items, such as a splash screen, with minimal effort. Enabling the framework is the default, but unless you want to change the default settings, the behavior is the same as if the framework weren't enabled. Note that the View Application Events button adds a new source file, ApplicationEvents.vb, to your project, which includes documentation about which application events are available.

Assembly Information Screen

Selecting the Assembly Information button from within your My Project window opens the Assembly Information dialog box. Within this dialog, shown in Figure 13-7, you can define file properties, such as your company's name and versioning information, which will be embedded in the operating system's file attributes for your project's output. The frame of the assembly file shows that by default it contains several standard values.

Assembly Attributes

The AssemblyInfo.vb file contains attribute blocks, which are used to set information about the assembly. Each attribute block has an assembly modifier, shown in the following example:

<Assembly: AssemblyTitle("")>
Figure 13-7

Figure 13.7. Figure 13-7

All the attributes set within this file provide information that is contained within the assembly metadata. These properties are displayed in the Assembly Information dialog, which is opened from the project's properties page (select the Compile tab and then click the Assembly Information button). The attributes contained within the file are summarized in the following table:

Attribute

Description

Title

This sets the name of the assembly, which appears within the file properties of the compiled file as the description.

Description

This attribute is used to provide a textual description of the assembly, which is added to the Comments property for the file.

Company

This sets the name of the company that produced the assembly. The name set here appears within the Version tab of the file properties.

Product

This attribute sets the product name of the resulting assembly. The product name appears within the Version tab of the file properties.

Copyright

The copyright information for the assembly. This value appears on the Version tab of the file properties.

Trademark

Used to assign any trademark information to the assembly. This information appears on the Version tab of the file properties.

Assembly Version

This attribute is used to set the version number of the assembly. Assembly version numbers can be generated, which is the default setting for .NET applications. This is covered in more detail in chapter 23.

File Version

This attribute is used to set the version number of the executable files. This and other deployment-related settings are covered in more detail in chapter 24.

COM Visible

This attribute is used to indicate whether this assembly should be registered and made available to COM applications.

Guid

If the assembly is to be exposed as a traditional COM object, then the value of this attribute becomes the ID of the resulting type library.

Compile Settings

The Compile tab (see Figure 13-8) was previously shown in Chapter 1. Visual Basic Express Edition users may have noticed in that original image that near the bottom of this screen is an option to generate XML comments for your assembly. These comments are generated based on the XML comments that you enter for each of the classes, methods, and properties in your source file. Unfortunately, these last settings are not available for Visual Basic 2005 Express Edition developers, although creating such comments, as shown later in this chapter, is possible even for Express Edition users.

Figure 13-8

Figure 13.8. Figure 13-8

Below the grid of individual settings in Figure 13-8 is a series of check boxes. Unlike the full Visual Studio suite of options, Visual Basic Express has fewer check boxes; however, users do have access to the Advanced Compile Options button. This button opens the Advanced Compiler Settings dialog shown in Figure 13-9. Note a couple of key elements on this screen, the first being the Remove Integer Overflow Checks check box. In the past, this was enabled by default, and the result was a performance hit on Visual Basic applications. The new default matches that of C#, enabling Visual Basic to match C# for performance. The compilation constants are values you shouldn't need to touch normally unless you are into compiler options. Similarly, the generation of serialization assemblies is something that is probably best left in auto mode.

Figure 13-9

Figure 13.9. Figure 13-9

However, the last item on the screen enables you to target different environments. The screen shown in Figure 13-9 is taken from the Visual Basic Express Edition, and as you can see this option is available. This means that all Visual Basic developers have the option to target their application at a specific version of the .NET Framework. If you select a version prior to version 3.5, then when you begin to add references, the Add References tab recognizes which version of .NET you are targeting and adjusts the list of available references to exclude those that are part of version 3.5 — or 3.0 if you are targeting .NET 2.0.

Note that this check occurs when adding references; there is no check when you change this value to see whether your updated value conflicts with any existing references. Therefore, if you change this value, then make sure you update any of your existing references to remove any that are part of .NET 3.5. You are bound to have at least one because when the template creates your project it automatically adds a series of references determined in part by the target framework specified when you created your application.

Debug Properties

The Express Edition of Visual Basic 2008 supports local debugging. This means it supports not only the .NET-related Debug and Trace classes discussed in Chapter 8, but also actual breakpoints and the associated interactive debugging available in all versions of Visual Studio. However, as noted, the full versions of Visual Studio provide enhanced debugging options not available in Visual Basic 2008 Express Edition. Figures 13-10 and 13-11 show the project debugger startup options from Visual Basic Express and Visual Studio 2008 Team Suite, respectively. Note that the Express Edition page has only three of the settings that are part of the more expensive version of Visual Studio.

Figure 13-10

Figure 13.10. Figure 13-10

Figure 13-11

Figure 13.11. Figure 13-11

As shown in Figure 13-10, Express Edition users have three options related to starting the debugger. The first is to apply command-line arguments to the startup of a given application. This, of course, is most useful for console applications, but in some cases developers add command-line parameters to GUI applications. The second option is to select a different directory to be used to run the application. Generally, this isn't necessary, but it's desirable in some cases because of path or permission requirements or having an isolated runtime area.

Figure 13-11 shows additional options, beginning with Start Action. The default action shown is actually the only option available to Express users — which is to start the current project. However, Visual Studio 2008 developers have two additional options. The first is to start an external program. In other words, if you are working on a DLL or a user control, then you might want to have that application start, which can then execute your assembly. Doing this is essentially a shortcut, rather than needing to bind to a running process.

Similarly for Web development, you can reference a specific URL to start that Web application. This is often a mixed blessing, as with ASP.NET 2.0, Visual Studio automatically attempts to start an ASP.NET application based on the page you are currently editing. This is a change from ASP.NET 1.x, which allowed you to define a start page. Because ASP.NET 2.0 does not use project files, the new behavior was introduced. In most cases it works just fine, but if you have a Web application requiring authentication, then in most cases it makes more sense to actually place that URL into the debug settings for your application.

The next set of options aligns with those of the Express Edition, except for that third item — Use Remote Machine. As noted, Visual Studio 2008 provides support for remote debugging, although such debugging is often more trouble than it's worth. Using the Debug and Trace classes and effective error handling, it is generally easier to determine remote errors with existing tools. However, for those rare environments where an application only runs on a central server, and for which developers have the necessary permissions to run the debugger but not a copy of Visual Studio on that server, it is possible to leverage remote debugging.

Finally, as might be expected, users of Visual Studio 2008 who work with multiple languages and are given tools to tightly integrate with SQL Server have additional debuggers. The first of these is support for debugging outside of the CLR — what is known as unmanaged code. As a Visual Basic developer, the only time you should be using unmanaged code is when you are referencing legacy COM components. The developers most likely to use this debugger work in C++.

The next option turns on support for SQL Server debugging, a potentially useful feature. In short, it's possible, although the steps are not trivial, to have the Visual Studio debugging engine step directly into T-SQL stored procedures so that you can see the interim results as they occur within a complex stored procedure.

References

It's possible to add additional references as part of your project. Similar to the default code files that are created with a new project, each project template has a default set of referenced libraries. Actually, it has a set of imported namespaces and then a subset of the imported namespaces also referenced across the project. This means that while you can easily reference the classes in the referenced namespaces, you still need to fully qualify a reference to, for example, a System.Collections.Generics.List class. For Windows Forms applications, the list of default referenced namespaces that are common from projects that target .NET 2.0 through projects that target .NET 3.5 is fairly short:

Reference

Description

System

Often referred to as the root namespace. All the base data types (String, Object, and so on) are contained within the System namespace. This namespace also acts as the root for all other System classes.

System.Data

Classes associated with ADO.NET and database access. This namespace is the root for SQL Server, Oracle, and other data access classes.

System.Deployment

Classes used for One Touch Deployment. This namespace is covered in more detail in chapter 24.

System.Drawing

Provides access to the GDI+ graphics functionality

System.Windows.Forms

Classes used to create traditional Windows-based applications. This namespace is covered in more detail in Chapters 15 and 16.

System.XML

Root namespace for all of the XML classes

Note that the preceding list is the complete list of references you'll find in a project that was created to target .NET 2.0. If your project was created to target .NET 3.5, then as you'll see in Figure 13-12 your default list of referenced libraries is noticeably larger. Keep in mind that changing your target framework does not update any existing references.

To review the details of the imported and referenced namespaces, select the References tab in your My Project display, as shown in Figure 13-12. This tab enables you to check for unused references and even define reference paths. More important, it is from this tab that you select other .NET class libraries and applications, as well as COM components. Selecting the Add drop-down button gives you the option to add a reference to a local DLL or a Web service.

When referencing DLLs you have three options: reference an assembly from the GAC, reference an assembly based on a file path, or reference another assembly from within your current solution. Each of these options has advantages and disadvantages. The only challenge for assemblies that are in the GAC is that your application is dependent on what is potentially a shared resource. In general, however, for assemblies that are already in the GAC, referencing them is a straightforward, easily maintainable process.

Notice that the list shown in Figure 13-12 reflects what a Visual Basic Express Edition user sees once that user generates a project. If you are going to attempt to target the .NET 2.0 Framework, then you'll want to remove references that have a version higher then 2.0.0.0. References such as System.Core enable new features in the System namespace that are associated with .NET 3.5.

In addition to referencing libraries, you can reference other assemblies that are part of your solution. If your solution consists of more than a single project, then it is straightforward and highly recommended to use project references to allow those projects to reference each other. While you should avoid circular references — Project A references Project B which references Project A — using project references is preferred over file references. With project references, Visual Studio can map updates to these assemblies as they occur during a build of the solution. It's possible for Visual Studio to automatically update the referenced assemblies in your executable project to be the latest build of the referenced DLLs that are part of the same solution. Note that the target needs to be an executable. Visual Studio will automatically update references between DLL projects in a common solution.

Figure 13-12

Figure 13.12. Figure 13-12

This is different from adding a reference to a DLL that is located within a specified directory. When you create a reference via a path specification, Visual Studio can check that path for an updated copy of the reference, but your code is no longer as portable as it would be with a project reference. More important, unless there is a major revision, Visual Studio usually fails to detect the types of changes you are likely to make to that file during the development process. As a result, you'll need to manually update the referenced file in the local directory of the assembly that's referencing it. In general, unless you have only the compiled version of that assembly, it's best to leverage project references versus path-based references.

Resources

In addition to referencing other assemblies, it is quite common for a .NET application to need to reference things such as images, icons, audio, and other files. These files aren't used to provide application logic but are used at runtime to provide support for the look, feel, and even text used to communicate with the application's user. In theory, you can reference a series of images associated with your application by looking for those images based on the installed file path of your application. Doing so, however, places your application's runtime behavior at risk, because a user might choose to replace, copy for profit, or just delete your files.

This is where project references become useful. Instead of placing the raw files onto the operating system alongside your executable, Visual Studio will package these files into your executable so that they are less likely to be lost or damaged. Figure 13-13 shows the Resources tab, which enables you to review and edit all your existing resources within a project, as well as import files for use as resources in your project. It even allows you to create new resources from scratch.

Figure 13-13

Figure 13.13. Figure 13-13

Note one little-known feature of this tab: Using the Add Resource drop-down button and selecting an image (not an existing image but one based on one of the available image types) will create a new image file and automatically open Microsoft Paint (for Express Edition developers); this enables you to actually create the image that will be in the image file.

Users of Visual Studio 2008 have additional capabilities not supported by Visual Basic's Express Edition. For one thing, instead of using Paint, Visual Studio provides a basic image editing tool, so when Visual Studio developers add a new image (not from a file), this editor opens within Visual Studio.

Additionally, within the list of Add Resource items, Visual Studio users can select or create a new icon. Choosing to create a new icon opens Visual Studio's icon editor, which provides a basic set of tools for creating custom icons to use as part of your application. This makes working with .ico files easier in that you don't have to hunt for or purchase such files online; instead, you can create your own icons.

However, images aren't the only resources that you can embed with your executable. Resources also apply to the fixed text strings that your application uses. By default, people tend to embed this text directly into the source code so that it is easily accessible to the developer. Unfortunately, this leaves the application difficult to localize for use with a second language. The solution is to group all of those text strings together, thereby creating a resource file containing all of the text strings, which is still part of and easily accessible to the application source code. When the application is converted for use in another language, this list of strings can be converted, making the process of localization easier. Localization is covered in more detail in Chapter 5.

Settings

New support for application settings within .NET 2.0 is a major enhancement that is often overlooked. In .NET 1.x it was possible to create a settings file. As noted earlier in the discussion of the Solution Explorer, the default project template does not create any application settings; accordingly, an App.Config file is not needed and not created. App.Config files are XML files that define any custom application settings that a developer wants to be able to change without needing to recompile the application. Because these settings live in an XML file, they can be modified in between or even during application execution.

One original goal of .NET was to reduce the version conflict that occurs when a component has registered with global settings and two different applications are attempting to reference two different versions of that component. Because the settings were global and stored in the central system registry, the result was a conflict, as the different applications each wanted its specific component and related settings.

.NET provided the capability to place version-specific project references in a local directory with the application, enabling two different applications to reference the appropriate version of that component. However, the second part of the problem was the central application settings. The App.config file provides the same capability, but its goal is allowing for local storage of application settings. Under .NET 1.x, support for application settings was still minimal, as most developers were still looking to the central system registry for this purpose. At the same time, the developer tools associated with settings were also minimal.

Fortunately, under .NET 2.0 this changed dramatically. Visual Basic 2008 provides significant support for application settings, including the Settings tab shown in Figure 13-14. This tab enables Visual Basic developers to identify application settings and automatically create these settings within the App.config file.

Figure 13-14

Figure 13.14. Figure 13-14

Figure 13-14 illustrates several elements related to the application settings capabilities of Visual Basic. The first setting is of type String. Under .NET 1.x, all application settings were seen as strings, and this was considered a weakness. Accordingly, the second setting, LastLocation, exposes the Type drop-down, illustrating that under Visual Basic 2008 you can create a setting that has a well-defined type.

However, strongly typed settings are not the most significant set of changes related to application settings. The very next column defines the scope of a setting. There are two possible options: applicationwide or user specific. The settings defined with application scope are available to all users of the application. As shown in Figure 13-14, this example creates a sample connection string to store for the application.

The alternative is a user-specific setting. Such settings have a default value; in this case, the last location defaults to 0,0. However, once a user has read that default setting, the application generally updates and saves the user-specific value for that setting. As noted by the Last Location setting, each user of this application might close the application after having moved it to a new location on the screen, and the goal of such a setting would be to reopen the application in the same location it was last seen. Thus, the application would update this setting value, and Visual Basic makes it easy to do this, as shown in the following code:

My.Settings.LastLocation = Me.Location
My.Settings.Save()

That's right — all it takes in Visual Basic 2008 is two lines of code that leverage the My namespace for you to update a user's application setting and save the new value. Meanwhile, let's take a look at what is occurring within the newly generated App.config file. The following XML settings demonstrate how the App.config file defines the setting values that you manipulate from within Visual Studio:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.
UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" >
            <section name="ProVB_VS.My.MySettings" type="System.
Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser"
requirePermission="false" />
        </sectionGroup>
        <sectionGroup name="applicationSettings" type="System.Configuration.
ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" >
            <section name="ProVB_VS.My.MySettings" type="System.Configuration.
ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <system.diagnostics>
        <sources>
            <!-- This section defines the logging configuration for
My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
                <listeners>
                    <add name="FileLog"/>
                    <!-- Uncomment the below section to write to the Application
Event Log -->
                    <!--<add name="EventLog"/>-->
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="DefaultSwitch" value="Information" />
        </switches>
        <sharedListeners>
            <add name="FileLog"
                 type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.
VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,
processorArchitecture=MSIL"
                 initializeData="FileLogWriter"/>
            <!-- Uncomment the below section and replace APPLICATION_NAME with the
name of your application to write to the Application Event Log -->
            <!--<add name="EventLog"
type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/>
-->
        </sharedListeners>
    </system.diagnostics>
    <userSettings>
        <ProVB_VS.My.MySettings>
            <setting name="LastLocation" serializeAs="String">
                <value>0, 0</value>
            </setting>
        </ProVB_VS.My.MySettings>
    </userSettings>
    <applicationSettings>
        <ProVB_VS.My.MySettings>
            <setting name="ConnectionString" serializeAs="String">
                <value>server=(local);Database=AdventureWorks</value>
            </setting>
        </ProVB_VS.My.MySettings>
    </applicationSettings>
</configuration>

As shown here, Visual Studio automatically generated all the XML needed to define these settings and save the default values. Note that individual user settings are not saved back into the config file, but rather to a user-specific working directory. It is possible not only to update application settings with Visual Basic, but also to arrange to encrypt those settings, although this action is outside the scope of what you can do from Visual Studio.

There are additional tabs related to your project's properties, but these are primarily associated with deployment. Therefore, in the interest of getting to some code, let's look at the source files that were generated when you created the ProVB_VS project from the Windows application template.

Project ProVB_VS in Visual Studio

The Form Designer opens by default when a new project is created. If you have closed it, then you can easily reopen it by right-clicking Form1.vb in the Solution Explorer and selecting View Designer from the pop-up menu. From this window, you can also bring up the Code view for this form. However, Figure 13-15 illustrates the default view you get when your project template completes. On the screen is the design surface upon which you can drag controls from the Toolbox to build your user interface and update properties associated with your form.

Figure 13-15

Figure 13.15. Figure 13-15

The Properties pane, shown in more detail in Figure 13-16, is by default placed in the lower-right corner of the Visual Studio window. Like many of the other windows in the IDE, if you close it, it can be accessed through the View menu. Alternatively, you can use the F4 key to reopen this window. The Properties pane is used to set the properties of the currently selected item control in the display.

Each control you place on your form has its own distinct set of properties. For example, in the design view, select your form. You'll see the Properties window adjust to display the properties of Form1 (refer to Figure 13-16). This is the list of properties associated with your form. If you want to limit how small a user can reduce the display area of your form, then you can now define this as a property. For your sample, go to the Text property and change the default of Form1 to Professional VB.NET. Once you have accepted the property change, the new value is displayed as the caption of your form. Later in this section, you'll set form properties in code. You'll see that .NET properties are defined within your source file, unlike other environments where properties you edit through the user interface are hidden in some binary or proprietary portion of the project.

Figure 13-16

Figure 13.16. Figure 13-16

Now that you've looked at the form's properties, open the code associated with this file by either right-clicking Form1.vb in the Solution Explorer and selecting Code view, or right-clicking the form in the View Designer and selecting View Code from the pop-up menu.

You can see that the initial display of the form looks very simple. There is no code in the Form1.vb file. Visual Basic 2005 introduced a capability called partial classes. Partial classes are covered briefly in Chapter 2, and Visual Studio leverages them for the code, which is generated as part of the user interface designer.

Visual Studio places all the generated source code for your form in the file Form1.Designer.vb. Because the "Designer" portion of this name is a convention that Visual Studio recognizes, it hides these files by default when you review your project in the Solution Explorer. As noted earlier, by asking Visual Studio to "show all files," you can find these generated files. If you open a "Designer.vb" file, you'll see that quite a bit of custom code is generated by the Visual Studio already in your project.

To do this, go to the toolbar located in the Solution Explorer window and select the Show All Files button. This will change your project display and a small plus sign will appear next to the Form1.vb file. Expanding this entry displays the Form1.Designer.vb file, which you can open within the IDE. Doing this for Form1.Designer.vb for the ProVB_VS project you created will result in a window similar to the one shown in Figure 13-17.

Figure 13-17

Figure 13.17. Figure 13-17

Note that the contents of this file are generated. For now, don't try to make any changes. Visual Studio automatically regenerates the entire file when a property is changed, so any changes may be lost. The following lines start the declaration for your form in the file Form1.Designer.vb:

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

The first line is an attribute that can be ignored. Next is the line that actually declares a new class called Form1. Note that in spite of the naming convention used by Visual Studio to hide the generated UI class implementation, the name of your class and the file in which it exists are not tightly coupled. Thus, your form will be referenced in the code as Form1 unless you modify the name used in the class declaration. Similarly, you can rename the file that contains the class without changing the actual name of the class.

One powerful result of forms being implemented as classes is that you can now derive one form from another form. This technique is called visual inheritance, although the elements that are actually inherited may not be displayed.

Form Properties Set in Code

As noted earlier, Visual Studio keeps every object's custom property values in the source code. To do this, it adds a method to your form class called InitializeComponent. As the name suggests, this method handles the initialization of the components contained on the form. A comment before the procedure warns you that the Form Designer modifies the code contained in the procedure, and that you should not modify the code directly. This module is part of the Form1.Designer.vb source file, and Visual Studio updates this section as changes are made through the IDE.

'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.SuspendLayout()
  '
  '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, 266)
  Me.Name = "Form1"
  Me.Text = "Professional VB.NET"
  Me.ResumeLayout(False)

End Sub

The seven lines of the InitializeComponent procedure assign values to the properties of your Form1 class. All the properties of the form and controls are now set directly in code. When you change the value of a property of the form or a control through the Properties window, an entry is added to InitializeComponent that assigns that value to the property. Previously, while examining the Properties window, you set the Text property of the form to Professional VB.NET Intro, which caused the following line of code to be added automatically:

Me.Text = "Professional VB.NET"

The properties of the form class that are set in InitializeComponent by default are shown in the following table:

Property

Description

Suspend Layout

Specifies that the form should not make updates to what is displayed to the user. It is called so that as each change is made, the form doesn't seem to appear in pieces.

AutoScaleDimensions

Initializes the size of the font used to lay out the form at design time. At runtime, the font that is actually rendered is compared with this property, and the form is scaled accordingly.

AutoScaleMode

Indicates that the form will use fonts that are automatically scaled based on the display characteristics of the runtime environment

ClientSize

Sets the area in which controls can be placed (the client area). It is the size of the form minus the size of the title bar and form borders.

Name

This property is used to set the textual name of the form.

ResumeLayout

This tells the form that it should resume the normal layout and displaying of its contents.

Code Regions

Source files in Visual Studio allow you to collapse blocks of code. The idea is that in most cases you can reduce the amount of onscreen code, which seems to separate other modules within a given class, by collapsing the code so it isn't visible; this feature is known as outlining. For example, if you are comparing the load and save methods and in between you have several other blocks of code, then you can effectively "hide" this code, which isn't part of your current focus.

By default, there is a minus sign next to every method (sub or function). This makes it easy to hide or show code on a method-by-method basis. If the code for a method is hidden, the method declaration is still shown and has a plus sign next to it indicating that the body code is hidden. This feature is very useful when a developer is working on a few key methods in a module and wishes to avoid scrolling through many screens of code that are not relevant to the current task.

It is also possible to hide custom regions of code. The #Region directive is used for this within the IDE, though it has no effect on the actual application. A region of code is demarcated by the #Region directive at the top and the #End Region directive at the end. The #Region directive that is used to begin a region should include a description. The description appears next to the plus sign shown when the code is minimized.

The outlining enhancement was probably inspired by the fact that the Visual Studio designers generate a lot of code when a project is started. Being able to see the underpinnings of your generated UI does make it is easier to understand what is happening, and possibly to manipulate the process in special cases. However, as you can imagine, it can become problematic; hence the #Region directive, which can be used to organize groups of common code and then visually minimize them.

Visual Studio 2008 developers, but not Express Edition developers, can also control outlining throughout a source file. Outlining can be turned off by selecting Edit

Code Regions

Tabs versus MDI

You may have noticed in Figure 13-17 that the Code View and Form Designer windows open in a tabbed environment. This environment is the default for working with the code windows inside Visual Studio, but you can toggle this setting, which enables you to work with a more traditional MDI-based interface. Such an interface opens each code window within a separate frame instead of anchoring it to the tabbed display of the integrated development environment (IDE).

To change the arrangement that is used between the tabbed and MDI interface, use the Options dialog box (accessible via Tools

Tabs versus MDI

Running ProVB_VS

Now that you've reviewed the elements of your generated project, let's test the code before continuing. To run an application from within Visual Studio, you have several options; the first is to click the Start button, which looks like the Play button on a tape recorder. Alternatively, you can go to the Debug menu and select Start. Finally, the most common way of launching applications is to press F5.

Once the application starts, an empty form will be displayed with the standard control buttons (in the upper-right corner) from which you can control the application. The form name should be Professional VB.NET Intro, which you applied earlier. At this point, the sample doesn't have any custom code to examine, so the next step is to add some simple elements to this application.

Customizing the Text Editor

In addition to being able to customize the overall environment provided by Visual Studio, you can customize several specific elements related to your development environment. Both Visual Studio 2008 and Visual Basic 2008 Express Edition have a rich set of customizations related to a variety of different environment and developer settings. Admittedly, Visual Studio 2008's feature set results in a larger number of available options for editing, but rest assured that the Express Edition contains many more options for editing than most people expect. A good example that's common to both IDEs is the way the text editor allows for much more customization. If you've ever had to show code to an audience — for example, in a group code review — the capability to adjust things such as font size and other similar options is great.

To leverage Visual Studio's settings, go to the Tools menu and select Options to open the Options dialog box, shown in Figure 13-18. Within the dialog box, make sure the Show All Settings check box is selected. Next, select the Text Editor folder, and then select the All Languages folder. This section enables you to make changes to the text editor that are applied across every supported development language. Additionally, you can select the Basic folder to make changes that are specific to how the text editor will behave when you edit VB source code.

Figure 13-18

Figure 13.18. Figure 13-18

From this dialog box, it is possible to modify the number of spaces that each tab will insert into your source code and to manage several other elements of your editing environment. One little-known but useful capability of the text editor is line numbering. Checking the Line numbers check box will cause the editor to number all lines, which provides an easy way to unambiguously reference lines of code.

Visual Studio 2008 also provides a visual indicator so you can track your changes as you edit. Enabling the Track Changes setting under the Text Editor options causes Visual Studio to provide a colored indicator in places where you have modified a file. This indicator is a colored bar at the left margin of your display. It shows which portions of a source file have been recently edited and whether those changes have been saved to disk.

IntelliSense, Code Expansion, and Code Snippets

One of the reasons Microsoft Visual Studio is one of the most popular development environments is that it has been designed to support developer productivity. That sounds really good, but let's back it up. People who are unfamiliar with Visual Studio might just assume that "productivity" refers to organizing and starting projects. Certainly, as shown with the project templates and project settings discussed so far, this is true, but those features don't speed your development after you've created the project.

This section covers three features that target your productivity while writing code. They are of differing value and are specific to Visual Studio. The first, IntelliSense, has always been a popular feature of Microsoft tools and applications. The second feature, code expansion, is another popular feature available since Visual Studio 2005: It enables you to type a keyword, such as "select," and then press the Tab key to automatically insert a generic select-case code block, which you can then customize. Finally, going beyond this, you can use the right mouse button and insert a code snippet at the location of your mouse click. As you can tell, each of these builds on the developer productivity capabilities of Visual Studio.

IntelliSense

IntelliSense has been enhanced in Visual Studio 2008. In the past you needed to first identify a class or property in order to use IntelliSense. With Visual Studio 2008, IntelliSense starts with the first letter you type so that you quickly identify classes, commands, and keywords that you need. Once you've selected a class or keyword, IntelliSense continues, enabling you to not only work with the methods of a class, but also automatically display the list of possible values associated with an enumerated list of properties when one has been defined. IntelliSense also provides a tooltiplike list of parameter definitions when you are making a method call.

Figure 13-19 illustrates how IntelliSense becomes available with the first character you type. Note that the drop-down window has two tabs on the bottom; one is optimized for the items that you are likely to want, while the other shows you everything that is available. In addition, IntelliSense works with multiword commands. For example, if you type Exit and a space, IntelliSense displays a drop-down list of keywords that could follow Exit. Other keywords that offer drop-down lists to present available options include Goto, Implements, Option, and Declare. IntelliSense generally displays more tooltip information in the environment than before and helps developers match up pairs of parentheses, braces, and brackets.

Finally, note that IntelliSense is based on your editing context. While editing a file, there may come a point at which you are looking for a specific item to show up in IntelliSense but when you repeatedly type slightly different versions nothing appears. IntelliSense has recognized that you aren't in a method or are outside of the scope of a class, so it has removed items that are inappropriate for your current location in your source code from the list of items available from IntelliSense.

Code Expansion

Going beyond IntelliSense is code expansion. Code expansion recognizes that certain keywords are consistently associated with other lines of code. At the most basic level, this occurs when you declare a new Function or Sub: Visual Studio automatically inserts the End Sub or End Function line once you press Enter. Essentially, Visual Studio is expanding the declaration line to include its matching endpoint. However, real code expansion goes further than this.

Figure 13-19

Figure 13.19. Figure 13-19

With real code expansion, you can type a keyword such as For, ForEach, Select, or any of a number of Visual Basic keywords. If you then use the Tab key, Visual Studio will attempt to recognize that keyword and insert the block of code that you would otherwise need to remember and type yourself. For example, instead of needing to remember how to format the control values of a Select statement, you can just type this first part of the command and then press Tab to get the following code block:

Select Case VariableName
    Case 1

    Case 2

    Case Else
End Select

Unfortunately, this is a case where just showing you the code isn't enough. That's because the code that is inserted has active regions within it that represent key items you will customize. Thus, Figure 13-20 provides a better representation of what is inserted when you expand the Select keyword into a full Select Case statement.

When the block is inserted the editor automatically positions your cursor in the first highlighted block — VariableName. When you start typing the name of the variable that applies, the editor automatically clears that static VariableName string, which is acting as a placeholder. Once you have entered the variable name you want, you can just press Tab. At that point the editor automatically jumps to the next highlighted item. This capability to insert a block of boilerplate code and have it automatically respond to your customization is a great feature.

Figure 13-20

Figure 13.20. Figure 13-20

Code expansion enables you to quickly shift between the values that need to be customized, but these values are also linked where appropriate, as in the next example. Another code expansion shortcut creates a new property in a class. If at the class level you type the word property followed by Tab, you will find the code shown in Figure 13-21 inserted into your code. On the surface this code is very similar to what you see when you expand the Select statement. Note that although you type property, even the internal value is part of this code expansion.

Figure 13-21

Figure 13.21. Figure 13-21

The difference, however, is that the same value String in Figure 13-21 is repeated for the property. The value you see is actually not the default; the default everywhere you see String in Figure 13-21 is Integer. However, when you change the first such entry from Integer to String, Visual Studio automatically updates all three locations because it knows they are linked. Using the code shown in Figure 13-21, update the property value to be m_Count. Press Tab and change the type to Integer; press Tab again and label the new property Count. This gives you a simple property on this form for use later when debugging.

The completed code should look like the following block. Note that one final change was to initialize the value of the m_count value to zero so that it would be initialized when first referenced:

Private m_count As Integer = 0
Public Property Count() As Integer
    Get
        Return m_count
    End Get
    Set(ByVal value As Integer)
        m_count = value
    End Set
End Property

This capability to fully integrate the template supporting the expanded code with the highlighted elements, helping you navigate to the items you need to edit, makes code expansion such a valuable tool.

Code Snippets

You can, with a click of your mouse, browse a library of code blocks, which, as with code expansion, you can insert into your source file. However, unlike code expansion, these snippets aren't triggered by a keyword. Instead, you right-click and (as shown in Figure 13-22) select Insert Snippet from the context menu. This starts the selection process for whatever code you want to insert.

Figure 13-22

Figure 13.22. Figure 13-22

The snippet library is installed with Visual Studio and is fully expandable, as discussed later in this chapter. Snippets are categorized by the function on which each is focused. For example, all the code you can reach via code expansion is also available as snippets, but snippets go well beyond that list. There are snippet blocks for XML-related actions, for operating system interface code, for items related to Windows Forms, and, of course, a lot of data-access-related blocks. The whole idea is that, unlike code expansion, which enhances the language in a way similar to IntelliSense, code snippets are blocks of code focused on functions developers often write from scratch.

As shown in Figure 13-23, the insertion of a snippet triggers the creation of a placeholder tag and a context window showing the categories of snippets. Each of the folders can contain a combination of snippet files or subdirectories containing still more snippet files. Visual Basic 2008 Express contains a subset of the folders provided with Visual Studio 2008. Visual Studio includes additional categories not shown in Figure 13-23. In addition, Visual Studio includes the folder My Code Snippets, to which you can add your own custom snippet files.

Figure 13-23

Figure 13.23. Figure 13-23

Selecting a folder enables you to select from one of its subfolders or a snippet file. Once you select the snippet of interest, Visual Studio inserts the associated code into your source file. Figure 13-24 shows the result of adding an operating system snippet to some sample code. The specific snippet in question is the code within the sub ReviewAppErrors. The selected snippet was Windows Operating System>Event Logs>Read Entries Created by a Particular Application from the Event Log, which isn't included with Visual Basic 2008 Express, although the code is still valid.

As you can see, this code snippet isn't just a block of code that can be used anywhere. Instead, it is specific to reading the Application Log, and its use in the ReviewAppErrors method is based on the idea that many applications log their errors to the Event Log so that they can be reviewed either locally or from another machine in the local domain. The key, however, is that the snippet has pulled in the necessary class references, many of which might not be familiar to you, and has placed them in context. This speeds not only the time spent typing this code, but also the time spent recalling exactly which classes need to be referenced and which methods need to be called and customized.

Finally, it is also possible to shortcut the menu tree. Specifically, if you know the shortcut for a snippet, you can type that and press Tab to have Visual Studio insert that snippet. For example, typing evReadApp followed by pressing Tab will insert the same snippet shown in Figure 13-24.

Figure 13-24

Figure 13.24. Figure 13-24

Tools such as code snippets and especially code expansion are even more valuable when you work in multiple languages. Keep in mind, however, that Visual Studio isn't limited to the features that come in the box. It's possible to extend Visual Studio not only with additional controls and project templates, but also with additional editing features.

Additional Components for Visual Studio 2008

You might be interested in two additional tools that work with Visual Studio. Even better, both are free. The first is a tool for creating your own Visual Basic snippets. As discussed, snippets can be powerful tools when you need to replicate relatively small but commonly used blocks of code that will be customized. While Visual Studio ships with several such snippets, Microsoft probably hasn't thought of the snippet you want the most.

This is where the first tool comes in: a Snippet Editor for Visual Basic code snippets. This editor doesn't actually live within Visual Studio 2008; it just updates the snippet files you want to use from Visual Studio. Behind the scenes, snippets are actually XML files with embedded text that represents the code used in the snippet. What the Snippet Editor does is read that XML and interpret all of the embedded logic related to things such as replacement blocks. This tool makes it possible for Visual Basic developers to create custom snippets without worrying about the XML formatting details. It is available from MSDN at http://msdn2.microsoft.com/en-us/vbasic/ms789085.aspx.

The second tool is a true add-in to Visual Basic. When Microsoft was announcing features for .NET 2.0, it was apparent that Visual Basic and C# had different feature lists. As time went by, the developers in each community started to better understand what these features represented, and in many cases demanded their inclusion. One such feature was native support in C# for refactoring, the ability to modify a variable name — for example, to take "i" and call it "loopControl" so that it's more readable. Modifying code to improve structure, performance, and maintainability is referred to generically as refactoring.

Traditionally, such changes might make code more maintainable but were often more risk than reward; as a result they seldom were made. The problem, of course, is that a human tends to miss that one remaining reference to the old version of that method or variable name. More important, it was a time-consuming task to find all of the correct references. Fortunately, the compiler knows where these are, and that's the idea behind automated refactoring: You tell Visual Studio what you want to change and it goes through your code and makes all the necessary changes, using the same rules the compiler uses to compile your code.

This is a great maintenance tool; unfortunately, by the time most Visual Basic developers understood what it implied, it was too late for the Visual Basic team to implement a solution in Visual Studio 2005. However, the team did do better than just say, "So sad, too bad." They found a commercial product that actually had more features than what the C# team was developing from scratch. Then they bought a license for every Visual Studio developer, allowing free download of the tool. This solution worked so well for everyone involved that they chose to continue it in Visual Studio 2008. With refactoring, you can quickly clean up gnarly, hard-to-read code and turn it into well-structured logic that's much more maintainable. The free version of the refactoring tool is available at www.devexpress.com/Products/NET/IDETools/VBRefactor/.

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-25, lives on the left-hand side of Visual Studio as a tab. When you click this tab, the control window expands and you can drag controls onto your form. Alternatively, if you have closed the Toolbox tab, you can go to the View menu and select Toolbox.

Figure 13-25

Figure 13.25. Figure 13-25

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, which are categorized so it's easier to find them. Figure 13-25 shows the result of dragging a Button control from the Toolbox and depositing it on the form: 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. 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.

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 in your environment. Such controls can be registered with Visual Studio and are then displayed within every project you work on. 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 (Figure 13-26 shows the code for this event handler being edited).

Although the event handler can be added through the designer, it's also possible to add event handlers from Code view. After you double-click the button, Visual Studio will transfer you to code view and display your new event handler. Notice that in Code view there are drop-down lists 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 list on the left-hand side contains the objects for which event handlers can be added. The drop-down list on the right-hand side contains all the events for the selected object. For now, you have created a new handler for your button's click event, so let's 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 features of Visual Studio is the capability to generate an XML comments template 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, which summarizes all your XML comments and 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. Start by adding a new line of code to increment the Count property you added to the form earlier. Next, use the System.Windows.Forms.MessageBox class to open a message box and show the message indicating the number of times the Hello World button has been pressed. 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-26, not only does the IDE provide a tooltip for the list of parameters, it also provides help regarding 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. In addition, unlike previous versions of Visual Basic, for which parentheses were sometimes unnecessary, in .NET the syntax best practice is to use parentheses for every method call:

Count += 1
MessageBox.Show(""Hello World shown " + Count.ToString() + " times."", _
               "Hello World Message Box", _
               MessageBoxButtons.OK, _
               MessageBoxIcon.Information)

Once you have entered this line of code, you may notice a squiggly line underneath some portions 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.

Figure 13-26

Figure 13.26. Figure 13-26

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 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"
     Me.ButtonHelloWorld.UseVisualStyleBackColor = True
    '
    '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 three lines of code assign values to the TabIndex, Text, and UseVisualStyleBackColor properties of the button:

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

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. Finally, the UseVisualStyleBackColor property indicates that when this button is drawn, it uses the current visual style. This is a Boolean value and typically you can accept this default, but you can customize the background so that a given button doesn't default to the current visual style.

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 look at your build options.

Building Applications

For this example, it is best 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-27, it displays status messages associated with the build process. This window indicates your success in building the 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 in subdirectory of your project directory.

Figure 13-27

Figure 13.27. Figure 13-27

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-27. 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 (see Figure 13-28). While your solution and code remain visible, the IDE displays additional windows such as the Call Stack, Locals, and Watch windows. 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.

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 increment the count when the button is clicked. Doing this creates a breakpoint on the selected line (refer to Figure 13-28). Return to your application and then click the "Hello World" button. Visual Studio takes the active focus, returning you to the 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 recognizing the value of the debugger. It is, in fact, more important than any of the other developer productivity features of Visual Studio. Once you are on this breakpoint you have control of every aspect of your running code. By hovering over the property Count, as shown in Figure 13-28, Visual Studio provides a debug tooltip showing you the current value of this property. This "hover over" feature works on any variable in your local environment and is a great way to get a feel for the different values without needing to go to another window. 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.

Figure 13-28

Figure 13.28. Figure 13-28

Next, 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 to show details about the properties of this object. As shown in Figure 13-29, this is true even for parameters like sender, which you didn't define. However, Figure 13-29 illustrates a key point when looking at variable data. Notice how by expanding the top-level objects you can eventually get to the properties inside those objects. Next to some of those properties, on the right-hand side, is a little magnifying glass. That icon tells you that Visual Studio will open the potentially lengthy string value in any one of three visualization windows. When working with complex XML or other complex data, these visualizers offer significant productivity benefits by enabling you to review data.

Once you are at this breakpoint, you can control your application by leveraging the Debug toolbar buttons. These buttons, shown in Figure 13-30, provide several options for managing the flow of your application. From the left you find the following: a run button, a pause button, a stop button, and a button that looks like a carriage return next to a set of lines. That fourth button represents stepping into code. The toolbar has three buttons showing arrows in relation to a series of lines: Step-In, Step-Over, and Step-Out, respectively.

Step-In tells the debugger to jump 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, then 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. The final button, Step-Out, is useful if you know what the code in a method is going to do but want to find out which code called the current method. Stepping out takes you directly to the calling code block.

Figure 13-29

Figure 13.29. Figure 13-29

Figure 13-30

Figure 13.30. Figure 13-30

Each of the buttons shown on the debugging toolbar in Figure 13-30 has an accompanying shortcut key for experienced developers who want to move quickly through a series of breakpoints. Of course, the value of breakpoints goes beyond what you can do with them at runtime. Visual Basic 2008 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-31, 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.

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 pop-up window enables you to define this condition. Similarly, if you've ever wanted to stop on, for example, the thirty-seventh iteration of a loop, you know the pain of repeatedly stopping at a breakpoint inside a loop. Visual Studio enables 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. You can 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. For example, if you are in an environment where multiple people are working against the same executable, then you can add a breakpoint that won't affect the other users of the application.

Figure 13-31

Figure 13.31. Figure 13-31

Similarly, instead of just stopping at a breakpoint, you can also have the breakpoint execute some other code, possibly even a Visual Studio macro, when the given breakpoint is reached. These actions are rather 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.

Finally, at some point you are going to want to debug a process that isn't being started from Visual Studio — for example, if you have an existing website that is hosting a DLL you are interested in debugging. In this case you can leverage Visual Studio's capability to attach to a running process and debug that DLL. At or near the top (depending on your settings) of the Tools menu in Visual Studio is the Attach to Process option. (It is visible in Figure 13-35 later in this chapter.) This menu option opens a dialog showing all of your processes. You could then select the process and have the DLL project you want to debug loaded in Visual Studio. The next time your DLL is called by that process, Visual Studio will recognize the call and hit a breakpoint set in your code.

Other Debug-Related Windows

As noted earlier, when you run an application in Debug mode, Visual Studio .NET 2008 can open 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. If you check 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 Debug and Trace, which are covered in more detail in Chapter 8.

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 leads 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 currently in scope. This is a fairly self-explanatory window that shows a list of the current local variables, with the value next to each item. As in previous versions of Visual Studio, this display enables 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, numbered 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, enables you to evaluate expressions. It becomes available while you are in Debug mode. This is a powerful window, one that 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 text 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 2008 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_VS 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 2008 Express.

Useful Features of Visual Studio 2008

The focus of most of this chapter has been on creating a simple application, working in either Visual Basic 2008 Express Edition or Visual Studio 2008. It's now time to leave the set of features supported by the Express Edition and move on to some features that are available only to Visual Studio developers. These features include, but are not limited to, the following items, beginning with features available to all Visual Studio 2008 developers.

When Visual Studio 2008 is first started, you configure your custom IDE profile. Visual Studio enables you to select either a language-specific or task-specific profile and then change that profile whenever you desire.

Configuration settings are managed through the Tools

Useful Features of Visual Studio 2008

The Visual Studio settings file is an XML file that enables you to capture all your Visual Studio configuration settings. This might sound trivial, but it is not. This feature enables the standardization of Visual Studio across different team members. The advantages of a team sharing settings go beyond just a common look and feel.

Build Configurations

Prior to .NET, a Visual Basic project had only one set of properties. There was no way to have one set of properties for a debug build and a separate set for a release build. As a result, you had to manually change any environment-specific properties before you built the application. This has changed with the introduction of build configurations, which enable you to have different sets of project properties for debug and release builds. Visual Studio does not limit you to only two build configurations. It's possible to create additional custom configurations. The properties that can be set for a project have been split into two groups: those that are independent of build configuration and therefore apply to all build configurations, and those that apply only to the active build configuration. For example, the Project Name and Project Location properties are the same irrespective of what build configuration is active, whereas the code optimization options vary depending on the active build configuration. This isn't a new concept, and it has been available to Visual C++ developers for some time, but .NET was the first time it was available for VB developers.

The default settings for developers who choose to customize Visual Studio 2008 based on Visual Basic settings do not include the two build configuration settings in the project property pages. By default, Visual Basic applications are built in Debug mode until they are deployed. This enables the Visual Basic developer to be unaware of the build configuration settings. However, if a project's build type is changed, then the VB developer is by default unaware and unable to change the setting.

To display these settings in Visual Studio, select Tools

Build Configurations

The advantage of multiple configurations is that it's possible to turn off optimization while an application is in development and add symbolic debug information that helps locate and identify errors. When you are ready to ship the application, you can switch to the release configuration and create an executable that is optimized for production.

At the top of Figure 13-32 is a drop-down list box labeled Configuration. Typically, four options are listed in this box: the currently selected configuration, Active; the Debug and Release options; and a final option, All Configurations. When changes are made on this screen, they are applied only to the selected configuration(s). Thus, on the one hand, when Release is selected, any changes are applied only to the settings for the Release build. If, on the other hand, All Configurations is selected, then any changes made are applied to all of the configurations, Debug, and Release. Similarly, if Active is selected, then in the background the changes are made to the underlying configuration that is currently active.

Alongside this is a Platform drop-down. Typically, you should not change this setting; its purpose is to enable you to optimize the generation of your MSIL for a specific processor. For example, 32-bit processors have different optimization than 64-bit AMD processors, which differ from Intel's 64-bit Itanium processors. While the .NET CLR enables you to abstract these differences, Visual Studio enables you to target a specific platform's performance characteristics. In many cases, under Visual Studio 2008 this drop-down no longer has any options because .NET automatically handles processor targeting at JIT compilation.

The window below the two drop-downs displays the individual properties that are dependent on the active build configuration. The first such setting is the location where your project's binary files are sent. Notice that VB now defaults to separate bin/debug and bin/release directories, so you can keep separate copies of your executables. Below this is the Advanced button, which opens a window containing some low-level compiler optimizations. In most cases, you won't need to change these settings, but they are available for those working with low-level components.

Figure 13-32

Figure 13.32. Figure 13-32

Below these settings is the All Configurations section. This label is somewhat misleading, as it actually means "all of the available configuration settings." Of course, that's a bit long, but the point is that while these settings can be different for each configuration, the grid contains all of the primary configuration settings.

All of these settings are project-specific, but when you are working with a solution it is possible to have more than one project in the same solution. Although you are forced to manage these settings independently for each project, there is another form of project configuration related to multiple projects. You are most likely to use this when working with integrated Setup projects, where you might want to build only the Setup project when you are working on a release build.

To customize which projects are included in each build configuration, you need the Configuration Manager for the solution. Projects are assigned to build configurations through the Configuration Manager. You can access the Configuration Manager from the Build menu by selecting Configuration Manager. Alternatively, the Configuration Manager can be opened using the drop-down list box to the right of the Run button on the Visual Studio toolbar. The Active Configuration drop-down box contains the following options: Debug, Release, and Configuration Manager. The first two default options are the currently available configurations. Selecting the bottom option, Configuration Manager, opens the dialog box shown in Figure 13-33.

The Configuration Manager contains an entry for each project in the current solution. You can include or exclude a project from the selected configuration by clearing the check box in the Build column of the grid. This is a valuable capability when a solution has multiple projects, as time isn't wasted waiting while a project that isn't being worked on is recompiled. The build configuration is commonly used when a Setup project is added to a solution. The normal plan is to rebuild only the Setup package when a release version of the actual application project is created. Note that regardless of the build configuration, you can build any assembly by right-clicking that project and selecting the Build option from the pop-up menu.

Figure 13-33

Figure 13.33. Figure 13-33

The Task List

The Task List is a great productivity tool that tracks not only errors but also pending changes and additions. It's also a good way for the Visual Studio environment to communicate information that the developer needs to know, such as any current errors. The Task List is displayed by selecting Task List from the View menu. It offers two views, Comments and User Tasks, and it displays either group of tasks based on the selection in the drop-down box that is part of this window.

The Comment option is used for tasks embedded in code comments. This is done by creating a standard comment with the apostrophe and then starting the comment with the Visual Studio keyword TODO. The keyword can be followed with any text that describes what needs to be done. Once entered, the text of these comments shows up in the Task List. Note that users can create their own comment tokens in the options for Visual Studio via Tools

The Task List

Besides helping developers track these pending coding issues as tasks, leveraging comments embedded in code results in another benefit. Just as with errors, clicking a task in the Task List causes the code editor to jump to the location of the task without hunting through the code for it. Also of note, though we are not going to delve into it, the Task List is integrated with Team Foundation Server if you are using this for your collaboration and source control.

The second type of tasks are user tasks. These may not be related to a specific item within a single file. Examples are tasks associated with resolving a bug, or a new feature. It is possible to enter tasks into the Task List manually. Within the Task List is an image button showing a red check mark. Pressing this button creates a new task in the Task List, where you can edit the description of your new task.

In early versions of Visual Studio, the Task List window was used to display compilation errors, but under Visual Studio 2005 the Error List became a separate window.

The Command Window

The Command window can be opened from the Other Windows section of the View menu. When opened, the window displays a > prompt. This is a command prompt at which you can execute commands — specifically, Visual Studio commands. While Visual Studio is designed to be a GUI environment with limited shortcuts, the Command window enables you to type — with the assistance of IntelliSense — the specific command you want.

The Command window can be used to access Visual Studio menu options and commands by typing them instead of selecting them in the menu structure. For example, type File.AddNewProject and press Enter — the dialog box to add a new project will appear. Similarly, if you type Debug.Start, you initiate the same build and start actions that you would from the Visual Studio UI.

Server Explorer

As development has become more server-centric, developers have a greater need to discover and manipulate services on the network. The Server Explorer is a feature in Visual Studio that makes this easier. Visual Interdev started in this direction with a Server Object section in the Interdev toolbox. The Server Explorer in Visual Studio is more sophisticated in that it enables you to explore and even alter your application's database or your local registry values. With the assistance of an SQL Database project template (part of the Other Project types), it's possible to fully explore and alter an SQL Server database. You can define the tables, stored procedures, and other database objects as you might have previously done with the SQL Enterprise Manager.

You open the Server Explorer in much the same way you open the control Toolbox. When you hover over or click the Server Explorer's tab, the window expands from the left-hand side of the IDE. Once it is open, you will see a display similar to the one shown in Figure 13-34. Note that this display has two top-level entries. The first, Data Connections, is the starting point for setting up and configuring the database connection. If you installed SQL Server Express, then this database and its connection string have already been loaded into your list of available data connections. You can also right-click on the top-level Data Connections node and define new SQL Server connection settings that will be used in your application to connect to the database. The Server Explorer window provides a way to manage and view project-specific database connections such as those used in data binding.

The second top-level entry, Servers, focuses on other server data that may be of interest to you and your application. When you expand the list of available servers, you have access to several server resources. The Server Explorer even provides the capability to stop and restart services on the server. Note the wide variety of server resources that are available for inspection or use in the project. Having the Server Explorer available means you don't have to go to an outside resource to find, for example, what message queues are available.

By default, you have access to the resources on your local machine; but if you are in a domain, it is possible to add other machines, such as your Web server, to your display. Use the Add Server option to select and inspect a new server. To explore the Event Logs and registry of a server, you need to add this server to your display. Use the Add Server button in the button bar to open the dialog and identify the server to which you would like to connect. Once the connection is made, you can explore the properties of that server.

Recording and Using Macros in Visual Studio 2008

Visual Studio macros are part of the environment and are available to any language. Macro options are accessible from the Tools

Recording and Using Macros in Visual Studio 2008
Figure 13-34

Figure 13.34. Figure 13-34

Figure 13-35

Figure 13.35. Figure 13-35

For example, suppose that one particular function call with a complex set of arguments is constantly being called on in code, and the function call usually looks the same except for minor variations in the arguments. The keystrokes to code the function call could be recorded and played back as necessary, which would insert code to call the function, which could then be modified as necessary.

Macros can be far more complex than this, containing logic as well as keystrokes. The macro capabilities of Visual Studio are so comprehensive that macros have their own IDE (accessed via Tools

Figure 13-35

Macros can also be developed from scratch in this environment, but more commonly they are recorded using the Record Temporary Macro option on the Macros menu and then renamed and modified in the development environment. Here is an example of recording and modifying a macro:

  1. Start a new Windows Application project.

  2. In the new project, add a button to Form1, which was created with the project.

  3. Double-click the button to get to its Click event routine.

  4. Select Tool

    Figure 13-35
  5. Press Enter and then type the following line of code:

    Console.WriteLine("Macro   test")
  6. Press Enter again.

  7. In the small toolbar, press the Stop button.

  8. Select Tools

    Figure 13-35
  9. Right-click the macro and select Edit to get to the Macro Editor. You will see the following code in your macro:

    DTE.ActiveDocument.Selection.NewLine()
    DTE.ActiveDocument.Selection.Text = "Console.WriteLine(""Macro test"")"
    DTE.ActiveDocument.Selection.NewLine()

The code that appears in step 9 may vary depending on how you typed in the line. For example, if you made a mistake and backspaced, those actions will have their own corresponding lines of code. As a result, after you record a macro, it is worthwhile to examine the code and remove any unnecessary lines.

The code in a macro recorded this way is just standard VB code, and it can be modified as desired. However, there are some restrictions regarding what you can do inside the macro IDE. For example, you cannot refer to the namespace for setting up database connections, because this might constitute a security violation.

To run a macro, you can just double-click it in the Macro Explorer or select Tools

Figure 13-35

One final note on macros is that they essentially enable you to generate code that can then be transferred to a Visual Studio Add-In project. An Add-In project is a project designed to extend the properties of Visual Studio. To create a new Add-In project, open the New Project dialog and select Other Project Types — Extensibility. You can then create a Visual Studio Add-In project. Such a project enables you to essentially share your macro as a new feature of Visual Studio. For example, if Visual Studio 2008 didn't provide a standard way to get formatted comments, you might create an add-in that enables you to automatically generate your comment template so you wouldn't need to retype it repeatedly.

Class Diagrams

One of the features introduced with Visual Studio 2005 was the capability to generate class diagrams. A class diagram is a graphical representation of your application's objects. By right-clicking on your project in the Solution Explorer, you can select View Class Diagram from the context menu. Alternatively, you can choose to Add a New item to your project. In the same window where you can add a new class, you have the option to add a new class diagram. The class diagram uses a .cd file extension for its source files. It is a graphical display, as shown in Figure 13-36.

Figure 13-36

Figure 13.36. Figure 13-36

Adding such a file to your project creates a dynamically updated representation of your project's classes. As shown in Figure 13-36, the current class structures for even a simple project are immediately represented when you create the diagram. It is possible to add one class diagram per subdirectory in your project. The class diagram graphically displays the relationships between objects — for example, when one object contains another object or even object inheritance. When you change your source code the diagram is also updated. In other words, the diagram isn't something that you create once at the start of your project and then allow to become out of date as your actual implementation changes the class relationships.

More important, you can at any time open the class diagram, make changes to one or more of your existing objects, or create new objects and define their relationship to your existing objects, and when done Visual Studio will automatically update your existing source files and create new source files as necessary for the newly defined objects.

As shown in Figure 13-36, the class diagram files (*.cd) open in the same main display area used for the Visual Studio UI designer and viewing code. They are, however, a graphical design surface that behaves more like Visio than the User Interface designer. Individual objects can be compressed or have their property and method details exposed. Additionally, items such as the relationships between classes can be shown graphically instead of being represented as properties.

In addition to the editing surface, when working with the Class Designer a second window is displayed. As shown in Figure 13-36, the Class Details window is generally located in the same space as your Output, Tasks, and other windows. The Class Details window provides detailed information about each of the properties and methods of the classes you are working with in the Class Designer. You can add and edit methods, properties, fields, and even events associated with your classes. While you can't write code from this window, you can update parameter lists and property types. The Class Diagram tool is an excellent tool for reviewing your application structure.

Team System

The focus of this chapter has been on how you, as a Visual Basic developer, can leverage Visual Studio 2008. At the top end of the Visual Studio 2008 product line is the full Team Suite, and just below that are the various Team Editions. These are part of the umbrella of products referred to as Team System. In order to reduce confusion, this section takes a brief look at the tools from Team Suite that are part of the Visual Studio 2008 Team Edition for Software Developers. These tools are focused less on languages and developing code than on managing development and the development of applications.

Architecturally, Team System has two main elements: the server-side components, which operate under Team Foundation Server, and the client components, which are grouped under the Team Suite umbrella. Team Foundation Server (TFS) is in a sense the replacement for Visual Source Safe (VSS), although thinking of it only in those terms is a bit like thinking of the modern automobile as the replacement for the horse and carriage. Note that unlike Visual Source Safe, released in 2005, TFS was updated with a 2008 release and will be updated again in the future as part of the next release of the Team System tools. Understandably, the focus of TFS is on server-side components, but TFS includes a client installation package. This package ships with the server, but includes add-ins to Visual Studio as well as Visual Studio Tools for Office documents that you need in order to work with the server products.

Team Suite is a set of components that are integrated with and ship with Visual Studio 2008. These components were initially categorized into three roles: Architects, Developers, and Testers. Team Suite consolidates the tools appropriate for all these roles in a single product. Since its original release, Microsoft has announced and started offering technology previews for database developers. These tools are also available to users of Team Suite. The underlying concept is that each role needs certain tools in order to better carry out the associated daily tasks, and in some cases these tools overlap between roles.

While having a single product that incorporates all these tools is nice, cost can become an issue. Thus, Microsoft introduced the idea of Team Editions. To minimize the cost to the developer, these provide the same server components access to all of the roles, but on the client side they include only the tools appropriate for a specific role. Thus, from the standpoint of TFS and the server components of Team Suite, there are no differences between Team Suite and a Team Edition. The only differences exist in the tools provided as part of the client's version of Visual Studio.

Team Foundation Server (TFS)

The server components of Team System are not directly integrated into Visual Studio 2008, but it is appropriate to mention a couple of key attributes of TFS that extend it beyond VSS. Similar to VSS, the primary role most developers see for TFS is that of source control. This is the capability to ensure that if multiple people are working on the same project and with the same set of source files, then no two of them can make changes to the same file at the same time.

Actually, that's a bit of an oversimplification. The default mode for TFS is to allow two people to work on the same file, and then have the second person attempting to save changes merge his or her changes with the previously saved changes. The point of this is to ensure that developers check files in and out of source control so that they don't overwrite or lose each other's changes. In terms of its features and usability compared with VSS, TFS is much more capable of supporting remote team members. A project that literally takes hours to download remotely from VSS can download in a few minutes from TFS.

However, that covers just the source control features, and as mentioned previously TFS goes well beyond source control. The most obvious way is that TFS approaches project development from the role of the project manager. It doesn't consider a Visual Studio project file to represent the definition of a project. Instead, it recognizes that a project is based on a customer or contract relationship and may be made up of several seemingly unrelated projects in Visual Studio. Thus, when you define a project you create an area where all of the projects and solutions and their associated source files can be stored.

As part of the creation process you select a process template — and third-party templates are available — and create a SharePoint website based on that template. The SharePoint website becomes the central point of collaboration for the project's team. In addition to hosting the documentation associated with your selected software development process, this site acts as a central location for task lists, requirements, Microsoft project files, and other materials related to your project. In essence, TFS leverages SharePoint to add a group collaboration element to your projects.

As important as this is, an even more important capability TFS supports is that of a build lab. TFS provides another optional product called Team Build, which leverages the Visual Studio build engine to enable you to schedule automated builds. This isn't just a simple scheduling service; the Team Build engine not only retrieves and compiles your application files, but also sends update notices regarding the status of the build, and can be instructed to automatically leverage some of the Team Suite tools such as Code Analysis and Unit Testing. The capability to automate your builds and deploy them on a daily basis to a test environment encourages processes that focus on product quality and mirror industry best practices.

Finally, TFS ships with the Team Explorer. This is a Visual Studio add-in on steroids. It includes not only new menu items for Visual Studio, but also a new window similar in concept to the Solution Explorer but that instead provides access to your TFS projects. It also provides a series of windows in Visual Studio, some of which are related to source control, and others related to Tasks. TFS is in many ways the single most important tool in the Team System product line, even though it doesn't truly exist within Visual Studio.

Be aware that since TFS 2008 shipped with Visual Studio 2008, there is a new version of both TFS, including Team Build, which was enhanced significantly, and Team Explorer. The Team Explorer 2008 client is what you should integrate with Visual Studio 2008 to connect to either a TFS 2005 or a TFS 2008 server.

Team Editions

While TFS is available to all users of one of the versions of Team System, on the client side there are several different editions. As noted, Team Suite contains everything, but what about the role-based editions? There are currently three versions of the Team Edition packages: Team Edition for Architects, Team Edition for Software Developers, and Team Edition for Software Testers. These packages are described in detail on Microsoft's website, but here is a thumbnail review of the contents of each.

Team Edition for Architects isn't just focused on software architects. This edition contains tools oriented to the interaction of different applications, and the interaction between physical servers and the components that are installed on those servers. The architect tools essentially work at a level above the Class Designer. These tools enable you to define applications that can then become Visual Studio projects. The designers support designating the security requirements for deploying these applications and enable the architect to compare the requirements of a given application with the settings on a physical server. The goal is to enable an architect to determine quickly whether a new application will work when it is actually deployed into production, and to understand how different applications will interact.

Team Edition for Software Developers is an excellent subset of tools for developers. Details of this edition are the focus of the following sections in this chapter. In short, the Developers edition provides tools to analyze the quality of your source code, to test an application's performance in relation to the system resources it consumes, and to create automated unit tests. This last feature is in many ways the most important feature for improving your code quality.

Team Edition for Software Testers doesn't focus on documenting how an application should work so much as on coding and automating tests. It has all of the same unit testing capabilities of the Developers edition but includes additional test tools for Web applications and for load testing Web applications. It also includes some basic tools for documenting and defining tests; but just as with Team Build, the focus is on creating and customizing automated tests.

Team Edition for Developers

This set of tools, which has been integrated with Visual Studio, is focused on the needs of the application developer. Unlike the Architect tools, those for developers are to a large extent taken from existing, free tools. However, unlike those tools, the Team Suite versions have been fully integrated with Visual Studio and TFS. Don't be fooled by the fact that many of these tools are based on freely available tools; many modifications and improvements are included.

Code Analysis

Code analysis, or static code analysis, is a tool for reviewing your source code — although that's not quite how it works. The basic paradigm reflects the fact that there are certain common best practices when writing code, and that once these best practices have been documented, a tool can be written that examines source code and determines whether these practices have been followed. Visual Studio's static code analysis is incorporated into your project settings for Windows Forms–based projects, as shown in Figure 13-37. For Web applications, there isn't a project file to hold the project settings, so it is possible to configure and run static code analysis from the website menu in Visual Studio.

In fact, the tool doesn't actually look at your source code. Instead, it uses reflection; and once your project has been compiled, it queries the MSIL code your project generates. While this may seem surprising, remember that this tool is looking for several best practices, which may be implemented in different ways in your source code but will always compile in a standard manner.

Figure 13-37

Figure 13.37. Figure 13-37

Figure 13-37 shows the optional Code Analysis screen. Note that even when you have the code analysis tools available, they are by default not enabled for your project. This is because enabling code analysis significantly extends your compile time. In most cases you'll want to enable these settings for a build or two, and then disable the checks for most of your debug builds. As you can see, to enable analysis you merely check the Enable Code Analysis check box.

Below this check box is a new check box for Visual Studio 2008. One of the code analysis issues for which Microsoft was criticized was that if you used the standard project template to create your project and then ran Code Analysis, you would get certain warnings. The solution Microsoft chose was to enable you to automatically bypass checking their generated code, which at least enables you to avoid having to manually mark all of the issues related to the generated code as being suppressed.

Once you have enabled the code analysis checks, you also have the option to define exactly which rules you want to apply. The checks are divided into different categories of rules. Note that each of the categories can be enabled or disabled as part of your code analysis. You can expand the display to list the rules in each category.

When expanded, next to each category and rule is a check box. By default, Visual Studio issue warnings if your code fails. This enables you to have some rule violations act as compilation errors instead of warnings. You can also enable or disable having the analyzer check individual rules. Outside of the scope of this chapter is the capability to actually identify within your source code those items that may be flagged by the code analyzer but that are valid exceptions to the rule being checked.

Performance Tools

Performance checks are something every developer wants. Visual Studio provides dynamic code analysis, or performance, tools for your application. These tools are available from the Analyze menu, shown in Figure 13-38. The performance tools provide two runtime environments to measure the performance of your application: Sampling and Instrumented. Note that if you are working within a virtual PC, then you need to use the instrumented version of the performance tools.

Figure 13-38

Figure 13.38. Figure 13-38

Sampling for performance testing is a non-intrusive method of checking your application performance. Essentially, Visual Studio starts your application normally, but behind the scenes it is interfaced into the system performance counters. As your application runs, the performance monitoring engine captures system performance, and when your application completes it provides reports describing that performance. Details about what your application was actually doing to cause a behavior isn't available, but you can get a realistic feel of the impact on the system.

Instrumentation, conversely, is an intrusive form of performance monitoring. Choosing to make an instrumentation run the performance tools triggers the addition of special MSIL commands into your compiled executable. These calls are placed at the start and finish of methods and properties within your executable. Then, as your code executes, the performance engine can gauge how long it takes for specific calls within your application to execute.

Keep in mind that both methods of performance testing affect the underlying performance of the application. It is true that running a performance monitor of any type has built-in overhead that affects your application, but the goal of performance testing isn't to know the exact timing marks of your application, but rather to identify areas that deviate significantly from the norm, and, more important, to establish a baseline from which you can track any significant changes as code is modified.

Unit Tests

Automated unit tests are arguably the most important of the tools provided to the developer as part of Team Edition. To create a new Unit Test, select New Test from the Test menu in Visual Studio. This opens the Add New Test dialog, shown in Figure 13-39. Note that the dialog shown isn't from Visual Studio 2008 Team Edition for Software Developers, but from Visual Studio 2008 Team Suite, the difference being several more project templates, representing the full suite of templates available to a software tester. Developers will normally only see the Unit Test and Unit Test Wizard templates available in this screen. Given this, developers should work with the Unit Test Wizard to generate new tests. This wizard walks you through the process of generating a new test project.

Figure 13-39

Figure 13.39. Figure 13-39

Once you have completed the final step in the wizard to define your test project, you are presented with the screen shown in Figure 13-40. This screen shows each of your project's classes, and expands into the methods and properties available in that class. Note that the screen shown is based on the ProVB_VS sample application, which consists of a single form. Displayed are several inherited methods in addition to the custom methods on the form. In fact, the custom methods are not shown in the figure. This screen enables you to review those properties and methods that are part of the My namespace. Specifically, you can run tests against the settings and resources that you expect will be included in your project.

What's missing is any type of review of the actual UI elements with which users of your application would interact. The unit test engine that ships with Team System does not support actual UI testing; it is focused on testing methods that exist in your code. However, this screen enables Visual Studio to generate the source code associated with testing your application. Clicking the OK button triggers the generation of these tests, which are grouped in a new test project. Shown in Figure 13-41 is the newly generated ProVB_VS_Test project.

Figure 13-40

Figure 13.40. Figure 13-40

Figure 13-41

Figure 13.41. Figure 13-41

The creation of a Unit Test project is not a trivial event. Even though it occurs as quickly as any other project template, the results are significant. First, notice in the Solution Explorer shown in Figure 13-41 that another project has been added to the ProVB_VS solution. This new test project includes a documentation file, AuthoringTests.txt, with tips and instructions for writing unit tests. In addition, this screen shows a subset of the contents of the Form1Test.vb source file. It is opened to some of the comments accompanying the methods stubs to implement the tests for your selected methods.

Unit tests present a unique challenge — because you are writing test code, they are an expensive feature to initially implement. Therefore, even though automated unit tests are valuable, organizations often have trouble committing to their development. Nonetheless, a well-written set of tests more than pays for itself. How do you estimate that cost? As a rule of thumb, consider estimating as much time for writing tests as you expect to spend writing the code to be tested.

Summary

In this chapter, you have taken a dive into the versions and features of Visual Studio. This chapter was intended to help you explore the new Visual Studio IDE. It demonstrated how powerful the features of the IDE are, even in the freely available Visual Basic 2008 Express Edition. Following are some of the key points covered in this chapter:

  • How to create projects, and the different project templates available

  • Code regions and how you can use them to conceal code

  • Versions of Visual Studio 2008

  • The properties and settings of your Visual Studio 2008 projects

  • Running an application in Debug mode and working with breakpoints

  • Building configurations and modifying the build configuration of your project

  • The Class Designer

  • Team System: Team Foundation Server and Team Suite

  • Tools in Visual Studio 2008 Team Edition for Developers

  • Automated unit tests

You've seen that Visual Studio 2008 is highly customizable and comes in a variety of flavors. Numerous windows can be hidden, docked, or undocked. They can be layered in tabs and moved within the IDE. Visual Studio also contains many tools, including some that extend its core capabilities. Keep in mind that whether you are using Visual Basic 2008 Express Edition or Visual Studio 2008 Team Suite, the core elements associated with compiling your application are the same.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset