MA CHAPTER 1: Visual Studio 2010 TE RI Language Constructs and Environment AL PART I CHAPTER 2: Objects and Visual Basic TE D CHAPTER 3: Custom Objects CHAPTER 4: The Common Language Runtime GH CHAPTER 5: Declarative Programming with Visual Basic RI CHAPTER 6: Exception Handling and Debugging CO PY CHAPTER 7: Test-Driven Development
1 Visual Studio 2010 WHAT YOU WILL LEARN IN THIS CHAPTER ➤ Versions of Visual Studio ➤ An introduction to key Visual Basic terms ➤ Targeting a runtime environment ➤ Creating a baseline Visual Basic Windows Form ➤ Project templates ➤ Project properties — application, compilation, debug ➤ Setting properties ➤ IntelliSense, code expansion, and code snippets ➤ Debugging ➤ Recording and using macros ➤ The Class Designer ➤ Team Foundation Server — Team Explorer You can work with Visual Ba
❘ CHAPTER 1 VISUAL STUDIO 2010 it later for advanced topics that you glossed over your fi rst time through. Visual Studio is a powerful and, at times, complex tool and you aren’t expected to master it on your fi rst read through this chapter. When Visual Studio 2005 was released, Microsoft expanded on the different versions of Visual Studio available for use. At the low- cost end, and currently free, is Visual Basic Express Edition.
Visual Studio 2010: Express through Ultimate ❘5 However, as you’ll discover, this support doesn’t mean that Visual Studio 2010 isn’t tightly coupled to a specific version of each 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 when projects from previous versions of Visual Studio are converted to the Visual Studio 2010 format, they cannot be reopened by a previous version.
❘ CHAPTER 1 VISUAL STUDIO 2010 TABLE 1 -1: Visual Studio Editions 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 Basic Keywords and Syntax ❘7 and Microsoft Office 2010 to extend these office productivity tools with application-like 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.
❘ CHAPTER 1 VISUAL STUDIO 2010 TABLE 1-2 (continued) KEY WORD DESCRIPTION Nothing Used to indicate that a variable has no value. Equivalent to null in other languages and databases. Me A reference to the instance of the object within which a method is executing Console A type of application that relies on a command-line interface. Console applications are commonly used for simple test frames. Also refers to a .
Visual Basic Keywords and Syntax ❘9 A class consists of both state and behavior. State is a fancy way of referring to the fact that the class has one or more values also known as properties associated with it. Embedded in the class defi nition are zero or more Dim statements that create variables used to store the properties of the class. When you create an instance of this class, you create these variables; and in most cases the class contains logic to populate them.
❘ CHAPTER 1 VISUAL STUDIO 2010 You may have noticed that in all the sample code presented thus far, each line is a complete command. If you’re familiar with another programming language, then you may be used to seeing a specific character that indicates the end of a complete set of commands. Several popular languages use a semicolon to indicate the end of a command line. Visual Basic doesn’t use visible punctuation to end each line.
Visual Basic Keywords and Syntax ❘ 11 Dim line = Console.ReadLine() End Sub End Module A Module isn’t truly a class, but rather a block of code that can contain methods, which are then referenced by code in classes or other modules — or, as in this case, it can represent the execution start for a program. A Module is similar to having a Shared class. The Shared keyword indicates that only a single instance of a given item exists.
❘ CHAPTER 1 VISUAL STUDIO 2010 The start page looks similar regardless of which version of Visual Studio 2010 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 fi rst project.
Visual Basic Keywords and Syntax ❘ 13 FIGURE 1 -3 Not only can you choose to target a specific version of the framework when creating a new project, but this window has a new feature that you’ll fi nd all over the place in Visual Studio 2010. In the upper-right corner, there is a control that enables you to search for a specific template.
❘ CHAPTER 1 VISUAL STUDIO 2010 ➤ 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.
Visual Basic Keywords and Syntax ❘ 15 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. For now however, you have a new project and an initial Windows Form, Form1, available in the Solution Explorer. In this case, the Form1.vb fi le is the primary fi le associated with the default Windows form Form1.
❘ CHAPTER 1 VISUAL STUDIO 2010 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. Finally, 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.
Visual Basic Keywords and Syntax ❘ 17 ATTRIBUTE DESCRIPTION Assembly 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 34. COM Visible This attribute is used to indicate whether this assembly should be registered and made available to COM applications.
❘ CHAPTER 1 VISUAL STUDIO 2010 This presented a challenge because this wasn’t the situation for any other set of Visual Studio settings; and Visual Basic developers were sometimes caught- out when sending what they thought was the latest build of their source code. If on their last “build” they were testing a fi x and starting the debugger, then they hadn’t rebuilt the release version.
Visual Basic Keywords and Syntax ❘ 19 From the properties page Option Explicit, Option Strict, Option Compare, and Option Infer can be set to either On or Off for your project. Visual Studio 2010 makes it easy for you to customize specific compiler conditions for your entire project. However, as noted, you can also make changes to the individual compiler checks that are set using something like Option Strict.
❘ CHAPTER 1 VISUAL STUDIO 2010 set it equal to another object, and the AS Integer portion of your declaration isn’t required, it is inferred as part of the assignment operation. Be careful with Option Infer; if abused it can make your code obscure, since it reduces readability by potentially hiding the true type associated with a variable. Some developers prefer to limit Option Infer to per file declarations to limit its use to when it is needed, for example with LINQ.
Visual Basic Keywords and Syntax ❘ 21 Note that this check occurs when adding references; there is no check when you change this value to see whether your updated value confl icts 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 4.
❘ CHAPTER 1 VISUAL STUDIO 2010 As noted, Visual Studio 2010 provides support for remote debugging, although such debugging is involved and not configured for simple scenarios. Remote Debugging can be a useful tool when working with an integration test environment where developers are prevented from installing Visual Studio but need to be able to debug issues. However, you shouldn’t be limited by just using the debugger for understanding what is occurring in your application at runtime.
Visual Basic Keywords and Syntax ❘ 23 The preceding list of referenced libraries is for .NET 4, so if you instead create a project that targets .NET 2.0, this list will be shorter. Keep in mind that changing your target framework does not update any existing references. 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 than 2.0.0.0. References such as System.
❘ CHAPTER 1 VISUAL STUDIO 2010 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.
Visual Basic Keywords and Syntax ❘ 25 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 fi le and automatically open Microsoft Paint (for Express Edition developers); this enables you to actually create the image that will be in the image fi le. Users of Visual Studio 2010 have additional capabilities not supported by Visual Basic’s Express Edition.
❘ CHAPTER 1 VISUAL STUDIO 2010 FIGURE 1 -12 Figure 1-12 illustrates several elements related to the application settings capabilities of Visual Basic. The fi rst 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 Studio 2010 you can create a setting that has a well- defi ned type.
Visual Basic Keywords and Syntax ❘ 27 PAGE 28❘ CHAPTER 1 VISUAL STUDIO 2010 but also to arrange to encrypt those settings, although this behavior is outside the scope of what you can do from Visual Studio. Other Project Property Tabs In addition to the tabs that have been examined in detail, there are other tabs which are more specific. In most cases these tabs are used only in specific situations that do not apply to all projects. Signing This tab is typically used in conjunction with deployment.
Project ProVB_VS2010 FIGURE 1 -13 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 1-14). 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 defi ne this as a property.
❘ CHAPTER 1 VISUAL STUDIO 2010 Visual Studio places all the generated source code for your form in the fi le Form1.Designer.vb. Because the “Designer” portion of this name is a convention that Visual Studio recognizes, it hides these fi les by default when you review your project in the Solution Explorer. As noted earlier, by asking Visual Studio to “show all fi les,” you can fi nd these generated fi les. If you open a “Designer.
Project ProVB_VS2010 ❘ 31 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.
❘ CHAPTER 1 VISUAL STUDIO 2010 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.
Project ProVB_VS2010 ❘ 33 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. More so than in any previous version, the capability to modify the environment has been enhanced. With Visual Studio 2010, the user interface components have been rewritten using WPF so that the entire display provides a much more graphical environment and better designer support.
❘ CHAPTER 1 VISUAL STUDIO 2010 are unfamiliar with Visual Studio might just assume that “productivity” refers to organizing and starting projects. Certainly, as shown by 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.
Project ProVB_VS2010 ❘ 35 Finally, note that IntelliSense is based on your editing context. While editing a fi le, you may reach a point where you are looking for a specific item to show up in IntelliSense but when you repeatedly type slightly different versions, nothing appears.
❘ CHAPTER 1 VISUAL STUDIO 2010 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 extremely useful.
Project ProVB_VS2010 ❘ 37 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 fi le. However, unlike code expansion, these snippets aren’t triggered by a keyword.
❘ CHAPTER 1 VISUAL STUDIO 2010 FIGURE 1 -21 FIGURE 1 -22
Project ProVB_VS2010 ❘ 39 As you can see, this code snippet is specific to reading the Application Log. This snippet is useful because 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.
❘ CHAPTER 1 VISUAL STUDIO 2010 ENHANCING A SAMPLE APPLICATION To start enhancing the application, you are going to use the control Toolbox. Close the Form1.designer.vb fi le and switch your display to the Form1.vb [Design] tab. The Toolbox window is available whenever a form is in Design view. By default, the Toolbox, shown in Figure 1-23, is docked to the left side of Visual Studio as a tab. When you click this tab, the control window expands, and you can drag controls onto your form.
Enhancing a Sample Application ❘ 41 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. When controls are added to the Toolbox they typically appear in their own custom categories 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.
❘ CHAPTER 1 VISUAL STUDIO 2010 Visual Studio adds code to the Form1.Designer.vb fi le. These changes occur in addition to the default method implementation shown in the editable portion of your source code. Adding XML Comments One of Visual Studio’s features is the capability to generate an XML comments template for Visual Basic. XML comments are a much more powerful feature than you might realize, because they are also recognized by Visual Studio for use in IntelliSense.
Enhancing a Sample Application ❘ 43 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: _ Partial Class Form1 Inherits System.Windows.Forms.
❘ CHAPTER 1 VISUAL STUDIO 2010 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.
Enhancing a Sample Application ❘ 45 Public Class Form1 Private m_count As Integer Public Property Count() As Integer Get Return m_count End Get Set(ByVal value As Integer) m_count = value End Set End Property ''' ''' ''' ''' ''' ''' Private Sub ButtonTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonTest.Click Count += 1 MessageBox.Show("Hello World shown " + Count.
❘ CHAPTER 1 VISUAL STUDIO 2010 environment will open. As shown in Figure 1-25, it displays status messages associated with the build process. This window should indicate your success in building the application. If problems are encountered while 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 (refer to Figure 1-25).
Enhancing a Sample Application ❘ 47 The true 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 1-26).
❘ CHAPTER 1 VISUAL STUDIO 2010 FIGURE 1 -28 FIGURE 1 -29
Enhancing a Sample Application ❘ 49 This isn’t the end of it. As you’ll note in Figure 1-29, by clicking on the down arrows you see on the right hand side of your new custom watch window, just below the pin, you can add one or more comments to your custom watch window for this value. You also have the option to unpin the initial placement of this window and move it off of your Code view display. Not only that but, the custom watch window is persistent in Debug mode.
❘ CHAPTER 1 VISUAL STUDIO 2010 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 the 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.
Enhancing a Sample Application ❘ 51 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.
❘ CHAPTER 1 VISUAL STUDIO 2010 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 values. It is also possible to modify the value of a variable from within a Watch window.
Enhancing a Sample Application FIGURE 1 -33 FIGURE 1 -34 ❘ 53
❘ CHAPTER 1 VISUAL STUDIO 2010 Additionally, you can follow the example shown here, which is to access the font property for the textbox and increase the size of the font from the default to 14pt. This was done only to make the sample results more readable within the screenshots used for the book. It has no other impact on the application.
Useful Features of Visual Studio 2010 ❘ 55 configuration(s). Thus, when Release is selected, any changes are applied only to the settings for the Release build. If, conversely, 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. FIGURE 1 -35 Alongside this is a Platform drop - down.
❘ CHAPTER 1 VISUAL STUDIO 2010 FIGURE 1 -36 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 enabling or disabling 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.
Useful Features of Visual Studio 2010 ❘ 57 In early versions of Visual Studio, the Task List window was used to display compilation errors, but starting with 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.
❘ CHAPTER 1 VISUAL STUDIO 2010 Recording and Using Macros in Visual Studio 2010 Visual Studio macros are part of the environment and are available to any language. Macro options are accessible from the Tools ➪ Macros menu, as shown in Figure 1-38. The concept of macros is simple: Record a series of keystrokes and/or menu actions, and then play them back by pressing a certain keystroke combination.
Useful Features of Visual Studio 2010 ❘ 59 7. In the small toolbar, press the Stop button. 8. Select Tools ➪ Macros ➪ Macro Explorer. The Macro Explorer will appear (in the location normally occupied by the Solution Explorer), with the new macro in it (see Figure 1-40). You can name the macro anything you like. Note that the Macro Explorer ships with several sample macros that you can “explore.” FIGURE 1 -40 9. Right- click the macro and select Edit to get to the Macro Editor.
❘ CHAPTER 1 VISUAL STUDIO 2010 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.
Useful Features of Visual Studio 2010 ❘ 61 Adding such a fi le to your project creates a dynamically updated representation of your project ’s classes. As shown in Figure 1- 42, the current class structures for even a simple project are immediately represented when you create the diagram. It is possible to add multiple class diagrams to your project. The class diagram graphically displays the relationships between objects — for example, when one object contains another object or even object inheritance.
❘ CHAPTER 1 VISUAL STUDIO 2010 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.
Useful Features of Visual Studio 2010 ❘ 63 FIGURE 1 -43 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 1-43 shows the optional Code Analysis screen.
❘ CHAPTER 1 VISUAL STUDIO 2010 FIGURE 1 -44 Within the rule set you see that there is a set of categories, each of which contains one or more rules. When expanded, next to each category and rule is a check box to indicate if that particular rule will be checked. By default, Visual Studio issue warnings if your code fails to meet the requirements associated with a rule. However, you can change the default — for example, by selecting an error status if a given rule fails.
Useful Features of Visual Studio 2010 FIGURE 1 -45 FIGURE 1 -46 ❘ 65
❘ CHAPTER 1 VISUAL STUDIO 2010 Concurrency checks are designed to detect issues with multi-threaded applications. The concurrency checks support two modes. The fi rst checks for resource contention issues. This occurs when two threads are, for example, attempting to write output to the same data fi le or data table, thus forcing your parallel processing to behave in a serial manner. The second mode enables you to better track how threaded events are behaving.