Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project....

24
Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-1 Chapter 2 Creating a Console Application with Visual Studio At a Glance Table of Contents Overview Chapter Objectives Instructor Notes Quick Quiz Discussion Questions Key Terms

Transcript of Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project....

Page 1: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-1

Chapter 2

Creating a Console Application with Visual Studio At a Glance Table of Contents • Overview • Chapter Objectives • Instructor Notes • Quick Quiz

• Discussion Questions • Key Terms

Page 2: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-2

Lecture Notes Overview In this chapter, the student learns how to use the Visual Studio IDE to create a console application. This is roughly the same application that the student created in Chapter 1. In addition, the student learns how to use the Visual Studio Help system and how the Help system is organized. Finally, the student learns how Visual Studio organizes an application into a project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to:

• Configure Visual Studio for use with Visual Basic

• Navigate the Visual Studio Help system

• Use the Visual Studio Object Browser to find the members of namespaces and classes

quickly

• Explore the different types of Visual Studio applications

• Work with Visual Studio solutions and projects

• Explore Visual Studio and its windows

• Use Visual Studio to create and compile a Visual Basic project

• Create application comments and work with the My object

Instructor Notes Introduction to Visual Studio This section introduces the Visual Studio IDE and its windows. Consider emphasizing to the student that Visual Studio works with the following programming languages:

• Visual Basic • Visual C++ • C# • J#

Page 3: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-3

Teaching Tip

Students may wonder about the benefit of choosing one Visual Studio programming language over another. Each .NET language has nearly the same capabilities, and the same intermediate language is generated by the compiler. Thus, for the most part, choosing a Visual Studio programming language is a matter of personal choice.

Microsoft distributes Visual Studio 2008 in several editions. Consider noting the characteristics of the various Visual Studio editions:

• The Visual Basic Express edition has a streamlined Help system and a simplified developer interface designed for the hobbyist.

• There are Express editions for the other .NET programming languages (C#, J#). o The Express editions can be freely downloaded from www.msdn.microsoft.com.

• The Visual Studio Professional edition contains complete menus and complete Help files.

o The Visual Studio Professional edition is available from the Microsoft Academic Alliance program.

o It is optionally distributed with this book. • The various Visual Studio Team editions have all of the features of the Professional

edition plus development tools designed for workgroups. Figure 2-1 on page 59 shows Visual Studio and selected windows as follows:

• The Solution Explorer manages the files that make up an application. • A menu bar, toolbars, and a status bar appear, as found in most applications. • The Code Editor is used to edit the code files that make up a Visual Basic program.

o The Code Editor is nothing more than an intelligent text editor. Configuring Visual Studio for Use with Visual Basic The Options dialog box supplies a drill-down interface with which Visual Studio can be configured. The available configuration options vary based on the installed Visual Studio edition. Consider discussing the following options:

• Enable strict type checking (Option Strict On). o This book will use strict type checking in all applications.

• Enable explicit variable declaration (Option Explicit On). o Explicit variable declaration is enabled by default.

• Use Tabbed documents mode instead of MDI mode. • In the Build and Run subfolder, make sure that Always Build is selected to prevent

execution of an out-of-date project.

Page 4: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-4

• Note that there are hundreds of configurable options. For the most part, the default values work well.

o The configurable options vary based on the Visual Studio edition being used.

Teaching Tip

In the lab environment, students tend to change settings, so presenting a consistent environment from one computer to the next is nearly impossible. In this book, we attempt to use the default environment that appears when Visual Studio is first installed.

Teaching Tip

When using a classroom projector, increase the font size for all tool and document windows using the following dialog box:

Introduction to the Visual Studio Help System Students seem reluctant to use the Help system, possibly because of its sheer size and complexity. However, the Help system contains a wealth of information and numerous code samples.

Page 5: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-5

Consider making the following points about the Help system:

• Help pages can be categorized into the following types: o Language Help pages document the Visual Basic language.

Reserved words appear in a monospace courier font. Square brackets [ ] surround optional data. Placeholder data appears in italics. Figure 2-10 on page 68 shows a Language Help page.

o Class Help pages document the members of classes and other types, such as structures and interfaces.

Figure 2-11 on page 69 shows the Class Help page for the System.Console class.

o Members Help pages are related to Class Help pages and document the methods, properties, and events supported by a particular type (class).

Each method, property, and event contains a link to another Help page. Figure 2-13 on page 71 shows the Console Members Help page.

• Help pages are divided into sections, which can be expanded or collapsed. o Many section names are standard from one Help page to the next. o The Platforms and Version Information sections appear on most Help pages and

show compatibility between Windows versions and .NET Framework class library versions.

Note that several new classes and other types have been added to Visual Studio 2005 and Visual Studio 2008.

• Most Help pages contain code samples that can be copied and pasted into an application.

Page 6: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-6

Teaching Tip

As previously mentioned, understanding inheritance and the relationships between .NET Framework class library types is critical. Consider discussing the Inheritance section of various Help pages. For example, the System.Console class inherits from System.Object. The System.Windows.Forms.Form class is more interesting, as shown in the following figure:

Page 7: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-7

Help filters are mentioned in this section. Help filters restrict the topics displayed to those applicable to the .NET Framework class library or a particular Visual Studio language. Help filters can be both helpful and problematic to the introductory student.

• Consider setting the Help filter to .NET Framework or Visual Basic. • Different Help filters exist for each Visual Studio language. • Students might mistakenly set a Help filter and wonder why well-known Help topics do

not appear. • The Help filters differ between the Visual Studio Express edition and the other Visual

Studio editions. The following list describes the different ways to navigate through the Help system:

• The Contents window displays a table of contents. o The table of contents is hierarchical. o Figures 2-16 and 2-17 on pages 75 and 76 show the Help Contents window with

callouts to some pertinent topics. • The Index window displays an alphabetical index.

o Note that most classes and other types can be located using the fully qualified reference to the class name.

System.Console, for example o Figure 2-18 on page 77 shows the Help Index window.

• The Search window is used to perform keyword searches. o Use keyword searches to find Help topics when a particular topic name is not

known. o Figure 2-19 on page 78 shows the Search window. o Note that keyword searches can produce a very long list of results.

• How Do I Help provides task-based Help rather than feature-based Help. o Figure 2-20 on page 79 shows the How Do I Help window.

• Help Favorites is used to maintain a list of favorite Help topics. o The interface is similar to Internet Explorer.

• Dynamic Help provides context-sensitive help. Dynamic Help can be very useful for first-time users.

o Dynamic Help is not that useful for more advanced users or advanced topics.

Teaching Tip

How Do I Help has several tutorials and sample applications. Consider pointing these out to students as a way to gain additional proficiency.

Page 8: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-8

Introduction to the Visual Studio Object Browser The Visual Studio Object Browser is used to examine the types that make up the .NET Framework class library and the types appearing in developer-created programs. In this chapter, the student looks at selected members of the System.Console class. The following points can be made about the Object Browser:

• Select components in the upper-left drop-down box. o Note that all members can be selected, or it’s possible to select only members of

the .NET Framework class library or the current project. • In the left pane, select namespaces, classes, or other types.

o The left pane has a drill-down interface. • In the upper-right pane, select members of the class or other type. • The lower-right pane displays the syntax of the selected member. • Figure 2-23 on page 81 shows the Object Browser.

o Note that icons appear to denote the type of the member (namespace, class, property, etc.)

Page 9: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-9

Teaching Tip

The Object Browser can be a good teaching tool and a means to discuss the members of a class or other type. Consider an in-class exercise to explore other members of the .NET Framework class library. For example, use the Object Browser to explore the members of the System.Windows.Forms.SystemInformation type. A demo of the Object Browser, showing the components of the current project, can help explain the mechanics of a project as follows:

• The ConsoleApplication contains a Module named Module1. • The right pane lists the members of the Module. • Note that the Main procedure appears in the list. • Students may ask why the other members appear. The answer is

simple. A Console application inherits from System.Object. • Consider showing the Help page for the System.Object class.

Types of Visual Studio Applications In this section, application templates are discussed. Consider emphasizing to the student that it is possible to create all of these applications from scratch instead of using a template. Chapter 1 discussed how to call the Visual Basic compiler directly. All projects could be created in this way. In other words, templates contain predefined code and the necessary configuration files to build the application.

Page 10: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-10

The following types of Visual Studio applications are mentioned in this chapter:

• Console Application projects are used to create applications that are executed from a Command Prompt window.

o The student will create a Console Application project in this chapter. • Windows Forms Application projects are used to create forms-based desktop

applications. o Chapter 3 discusses Windows Forms Application projects.

• Class Libraries are used to create components designed for use by other applications and developers.

• ASP.NET Web applications are used to create applications designed for use over the Internet.

o For example, an ASP.NET application could be used to create an online shopping cart.

• A Web service is created using a Web Service Application project. Web services are really nothing more than a way to call procedures running on other computers using Internet protocols.

o Web services are supported by many development platforms other than Visual Studio.

o Sun’s Java product supports Web services, for example. • There are templates for Pocket PCs and other mobile devices.

Introduction to Visual Studio Solutions and Projects Chapter 1 discussed how to create a program using Notepad and calling the Visual Basic compiler directly. This technique of creating programs is not suitable for anything but the simplest application. Some time spent discussing the files that make up a solution, and the organization of a solution, can help students prevent errors that arise when copying files from one computer to another. In addition, explaining these files helps the student to better understand how Visual Studio compiles a project. The following points are relevant to a solution and the files it manages:

• A solution contains one or more projects. • Each project contains one or more modules. • Some files are the same for all applications, whereas other files vary from application to

application.

Page 11: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-11

The following code segment shows the solution file for a solution named Chapter02ApplicationLessonPreview. The file is named Chapter02ApplicationLessonPreview.sln. Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "Chapter02ApplicationLessonPreview", "Chapter02ApplicationLessonPreview\Chapter02ApplicationLessonPreview.vbproj", "{961D82BD-FBA8-43DD-8767-A2F4C018446D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {961D82BD-FBA8-43DD-8767-A2F4C018446D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {961D82BD-FBA8-43DD-8767-A2F4C018446D}.Debug|Any CPU.Build.0 = Debug|Any CPU {961D82BD-FBA8-43DD-8767-A2F4C018446D}.Release|Any CPU.ActiveCfg = Release|Any CPU {961D82BD-FBA8-43DD-8767-A2F4C018446D}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal

The following points can be made of the preceding solution file:

• It is a block-structured file. • The solution file contains a reference to the project in the Project, EndProject

sections. • The project reference appears on the third and fourth lines. • The project name (Chapter02ApplicationLessonPreview), along with the file containing

the project (Chapter02ApplicationLessonPreview\Chapter02ApplicationLessonPreview.vbproj) also appears in this statement.

• The long number is called a globally unique identifier. o Every project created has a different value for the globally unique identifier,

hence the term. • The two GlobalSection declarations describe how Visual Studio will compile the

project. o The online Deployment appendix describes the Configuration Manager. It is the

Configuration Manager that is used to define these settings. The following code segment shows the default project file named ConsoleApplication1.vbproj: <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{961D82BD-FBA8-43DD-8767-A2F4C018446D}</ProjectGuid> <OutputType>Exe</OutputType> <StartupObject>Chapter02ApplicationLessonPreview.Module1</StartupObject> <RootNamespace>Chapter02ApplicationLessonPreview</RootNamespace> <AssemblyName>Chapter02ApplicationLessonPreview</AssemblyName> <FileAlignment>512</FileAlignment> <MyType>Console</MyType> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>

Page 12: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-12

<OptionExplicit>On</OptionExplicit> <OptionCompare>Binary</OptionCompare> <OptionStrict>Off</OptionStrict> <OptionInfer>On</OptionInfer> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <DefineDebug>true</DefineDebug> <DefineTrace>true</DefineTrace> <OutputPath>bin\Debug\</OutputPath> <DocumentationFile>Chapter02ApplicationLessonPreview.xml</DocumentationFile> <NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <DefineDebug>false</DefineDebug> <DefineTrace>true</DefineTrace> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DocumentationFile>Chapter02ApplicationLessonPreview.xml</DocumentationFile> <NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Data" /> <Reference Include="System.Deployment" /> <Reference Include="System.Xml" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> </ItemGroup> <ItemGroup> <Import Include="Microsoft.VisualBasic" /> <Import Include="System" /> <Import Include="System.Collections" /> <Import Include="System.Collections.Generic" /> <Import Include="System.Data" /> <Import Include="System.Diagnostics" /> <Import Include="System.Linq" /> <Import Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="Module1.vb" /> <Compile Include="My Project\AssemblyInfo.vb" /> <Compile Include="My Project\Application.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Application.myapp</DependentUpon> </Compile> <Compile Include="My Project\Resources.Designer.vb"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> <DependentUpon>Resources.resx</DependentUpon> </Compile> <Compile Include="My Project\Settings.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Settings.settings</DependentUpon> <DesignTimeSharedInput>True</DesignTimeSharedInput> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Include="My Project\Resources.resx"> <Generator>VbMyResourcesResXFileCodeGenerator</Generator> <LastGenOutput>Resources.Designer.vb</LastGenOutput> <CustomToolNamespace>My.Resources</CustomToolNamespace> <SubType>Designer</SubType> </EmbeddedResource>

Page 13: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-13

</ItemGroup> <ItemGroup> <None Include="My Project\Application.myapp"> <Generator>MyApplicationCodeGenerator</Generator> <LastGenOutput>Application.Designer.vb</LastGenOutput> </None> <None Include="My Project\Settings.settings"> <Generator>SettingsSingleFileGenerator</Generator> <CustomToolNamespace>My</CustomToolNamespace> <LastGenOutput>Settings.Designer.vb</LastGenOutput> </None> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>

While understanding every element in a project file is beyond the scope of this chapter, the following points can be made about a project:

• The project file is an XML document. • The <StartupObject> element defines the startup object. In the preceding example,

the startup object is a Module block. • The <Reference> elements define the namespace references. • The <Compile> elements define the files that contain the source code for the project.

o Note the reference to Module1.vb.

Page 14: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-14

Teaching Tip

Using Notepad or a text editor of your choosing, open various files that make up a project to help explain what Visual Studio is doing and the relationships between the solution file, the project file, and the subordinate files.

Teaching Tip

By default, a folder is created having the same name as the solution file. Stress to the student that the structure of the files that make up a solution must not be altered or Visual Studio will be unable to load the project. Make sure that the student does not modify or move files using Windows Explorer. Files should only be renamed using the Solution Explorer.

The following general points can be made about a solution and project file:

• A solution file contains references to one or more project files. • A project file contains references to the module files that comprise the project.

o Many module files are managed by Visual Studio and its visual designers. XML documents such as resource files Module files Form files

o Project-related properties are set using the Project’s property pages. Use the Application tab to set properties such as the program’s entry

point, the name of the executable file, and the name of the root namespace.

Figure 2-26 on page 86 shows the Application tab of the Project's property page.

Consider comparing these settings to those used when calling the compiler directly.

• The /main directive is the same as setting Sub Main to the project's entry point.

• The /out directive is the same as the name of the executable file (assembly name).

• The concept of the root namespace is the same too. Use the References tab to add additional namespace references.

• All .NET applications that call members of the .NET Framework class library require references to namespaces.

• Figure 2-27 on page 87 shows the References tab of the Project's property page.

o Note to the student that several references are automatically added from the Console Application template.

Page 15: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-15

• A project file contains references to the assemblies and namespaces used by the application.

The topics of creating and saving a Visual Studio solution are discussed in this section. Consider making the following points related to creating and saving a solution file:

• For the Express edition, click File, New Project to create a new solution. • For the Professional edition, click File, New, Project to create a new solution.

o Select the type of project from the list of defined templates. o Figure 2-28 on page 88 shows the New Project dialog box.

• Click File, Save All to save the project for the first time. o In the New Project dialog box, select the folder where the solution and project

will be saved. o Figure 2-29 on page 89 shows the Save Project dialog box.

Teaching Tip

Students will often work at home, with friends, or on lab computers. Thus, knowing how to copy a project from one computer to another is essential. Using Windows Explorer, show how to copy a solution directory from one location to another. We suggest not copying the files individually. Rather, show the student how to copy the entire solution folder from one disk to another.

The Solution Explorer is used to manage the files that make up the solution. The following list describes selected file types:

• The solution file appears at the top of the hierarchy. • The My Project folder contains files that are global to the project.

o For example, the file named Application.myapp is an XML document containing global application configuration information.

• The file named AssemblyInfo.vb contains attributes used to store assembly metadata. • The file named Resources.resx is also an XML document. It contains application-wide

resource declarations. • The References folder lists the namespace references. These namespace references are

physically stored in the project file (.vbproj). • The bin\Debug folder contains the compiled application. • Files having a suffix of .vb contain Visual Basic code. • Figure 2-30 on page 90 shows the Solution Explorer with the folders expanded. • Figure 2-31 on page 91 shows Windows Explorer displaying selected files from the

solution shown in Figure 2-30.

Page 16: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-16

The following list describes how to use the Solution Explorer:

• The Solution Explorer has a drill-down interface. • The toolbar contains the following buttons:

o The Properties button displays the Properties window. o The View Code button displays the Code Editor.

Not all files have associated code. o The View Designer button displays a visual designer.

The visual designer varies based on the file contents. Not all files support a visual designer.

o The Refresh button is used to synchronize files. • In addition to the toolbar buttons, it's possible to click an item and select options from

the available context menus. Visual Studio Windows All of the Visual Studio windows can be categorized into two types. A window's type defines where the window appears in Visual Studio and how the window works.

• Document windows appear on group tabs just below the toolbars. o The Windows Forms Designer and Code Editor are both document windows. o The XML Designer is another visual designer. o Each open document (file) appears on its own tab.

• Tool windows appear in different ways, depending on their configuration. o Tool windows can appear as floating windows.

Floating windows appear anywhere on the desktop. o Tools windows can be docked.

Docked windows are anchored along an edge of the desktop. Figure 2-33 on page 94 shows the anchors used to dock tool windows.

o Tool windows can appear as Auto Hidden windows. Auto Hidden windows appear on a tab along an edge of the Visual

Studio IDE. An Auto Hidden window is made visible when the mouse hovers over

the Auto Hidden window's icon. o Figure 2-32 on page 94 shows the appearance of tool windows.

The following list describes common tool windows:

• The Solution Explorer is a tool window and is typically docked along the right edge of the main Visual Studio window.

• The Properties window is used to set selected solution and object properties. o The Properties window is also typically docked along the right edge of the main

Visual Studio window. o The Properties window is discussed in greater detail in Chapter 3.

Page 17: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-17

• The Toolbox contains controls that are created on a form. o The Toolbox is typically Auto Hidden along the left edge of the main Visual

Studio window. • There are numerous debugging windows.

o Refer to Appendix A for a discussion of debugging and the Visual Studio debugging windows.

• The Error List window lists any syntax errors. • The Output window displays information as a project is compiled.

Use the items on the View menu to display common tool windows. Use the items on the View, Other Windows menu to view less commonly used windows. The Code Editor is a document window used to edit the code for a module. The Code Editor is used to edit the same text files that the student edited with Notepad in Chapter 1. The following points can be made about the Code Editor:

• Statement indentation is automatic. • Procedures may be expanded or collapsed by clicking the plus or minus signs to the left

of a procedure. • Procedures may be grouped into blocks using the #Region and #End Region

directives. These directives allow the programmer to expand or collapse large blocks of code. Note to the student that if they create their own #Region and #End Region directives, they must not appear inside of a procedure.

• Syntax errors appear with a jagged blue underscore. • A description of each syntax error also appears in the Error List window. We suggest

that as students write statements in the Code Editor, they leave the Error List Window open. This way, all syntax errors will appear along with a brief description.

• Figure 2-34 on page 95 shows the Code Editor. Intellisense is a student's best friend. The following ToolTips and pop-up lists appear through Intellisense:

• Class and class member names appear as a namespace name or class name is typed in the Code Editor.

o Intellisense displays a default class name or method name. o Figure 2-35 on page 96 shows an Intellisense pop-up menu.

• Arguments to method names appear once the opening parenthesis is entered, marking the beginning of the argument list.

o Figure 2-36 also shows an Intellisense ToolTip to display the arguments to the WriteLine method.

Page 18: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-18

Teaching Tip

Intellisense is another good way to explore the members of a class (type). Consider explaining why the Object Browser and Intellisense technology work. All the types that make up an assembly are stored in the assembly itself. Both the Object Browser and Intellisense technology use this assembly data, called metadata, to display the members of a class (type).

Teaching Tip

As the Code Editor performs many tasks automatically, its features are best addressed using an interactive demonstration. Consider showing the student how to perform the following tasks:

• Make sure the student knows that executable statements must be entered between the Private Sub and End Sub lines that mark the beginning and end of a procedure (event handler).

• Stress and emphasize the usefulness of IntelliSense technology. This technology supports command completion and provides suggestions for the properties and methods pertaining to objects by displaying those properties in a list box.

• Note the use of color. Reserved words appear in different colors (typically blue). While comments have not been discussed yet, they appear in green.

• Note how Visual Studio automatically capitalizes the names of reserved words.

• The Code Editor makes consistent the capitalization of method and property names.

o While not apparent yet, Visual Studio also makes the capitalization consistent for variable names.

• The Code Editor completes statement blocks. o The Code Editor will close Namespace and Module

blocks. o When writing an If statement, the Code Editor

automatically creates the corresponding End If statement. The same is true for Do loops and For loops.

• As a final note, the Options dialog box allows the developer to change the fonts and colors for code. These options are set using the Fonts and Colors page in the Environment folder.

Page 19: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-19

Syntax errors plague students. The Code Editor does well checking the syntax of each statement as it is written.

• After a statement is entered and the cursor is moved to the next line, Visual Studio checks the syntax of the statement just entered.

o Jagged blue lines appear if the statement is not correct. o The syntax error also appears in the Error List window.

In the Error List window, double-click a syntax error to position the cursor to the offending statement in the Code Editor.

In the Error List window, right-click on a syntax error and click Show Error Help to display extended Help for the error.

o Figure 2-37 on page 98 shows syntax errors appearing in these two windows. Compiling and Executing a Visual Basic Project with Visual Studio Visual Studio will compile a project based on the settings of various project-related properties. The compiler called by Visual Studio is the same Visual Basic compiler discussed in Chapter 1. Figure 2-38 on page 99 shows the Output window displaying the results of a successful compile. A project can be executed in various ways:

• Press F5. The project will be compiled, if necessary. • Click the Start Debugging button on the Standard toolbar. Again, the project will be

compiled, if necessary. Creating Application Comments Comments are an important part of any program. For brevity, the student is not asked to enter comments in the hands-on steps after Chapter 3. However, in this chapter, comments appear as part of the steps, so as to familiarize the student with their syntax. The following rules apply to comments:

• Visual Studio displays comments in green text, by default. o This default color may be changed using the Environment, Fonts and Colors

folder in the Options dialog box. • Any line beginning with an apostrophe (') is a comment.

o The comment character need not appear on a blank line. • Characters following an apostrophe on a line are considered a comment. In such a case,

a space must precede the comment character. o The Code Editor typically inserts this space.

• The comment must end the line. That is, another statement cannot follow a comment on a line.

• Continuation lines may not have trailing comments. • Comments do not affect the performance of a program. They are removed when the

program is compiled.

Page 20: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-20

• Comments often account for more than 50% of a program's statements. The following statements illustrate two forms of comments: ' This line is a comment. System.Console.WriteLine("Hello") ' Write a string. The following statements show invalid use of comments because the comment attempts to break up a continuation line. System.Console. _ ' Write a string. WriteLine("Hello")

Teaching Tip

As an exercise, consider an in-class discussion about when to use comments, beyond those items discussed in the text:

• Recording the date a change was made to the program • Recording the name of the person who made the change to the

program • Noting bugs or errors that are known to exist in a program • Document why changes were made • Document why a procedure may be made obsolete • Document work that needs to be completed

Avoid nondescriptive comments like the following. ' Call the WriteLine method. System.Console.WriteLine()

Introduction to the My Object The My object was introduced in Visual Studio 2005. The My object is a convenience object. That is, the My object references types that appear elsewhere in the .NET Framework class library. The following list describes objects referenced by the My object:

• The My.Application object has properties to get information about the current application.

• The My.Computer object gets configuration information about the computer. • The My.Computer.Network object gets information about the network and is used

to perform network-related tasks. • The My.User object gets information about the current user.

Page 21: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-21

The My.Application object gets information about the current application. Some of the information is defined in the AssemblyInfo.vb file in the form of attributes as follows: <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("Course Technology")> <Assembly: AssemblyProduct( _ "Visual Basic .NET – An Object-Oriented Approach")> <Assembly: AssemblyCopyright( _ "Copyright @ Course Technology 2006")> <Assembly: AssemblyTrademark("")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")> One purpose of attributes is to store assembly metadata.

• Attributes appear between less than and greater than signs (<>). • The syntax of an attribute declaration is similar to the syntax of a method call. • Note that attributes have many uses beyond those discussed in this chapter.

The following statements get the information about the assembly and print it to the console window: System.Console.WriteLine(My.Application.Info.Title) System.Console.WriteLine(My.Application.Info.Description) System.Console.WriteLine(My.Application.Info.CompanyName) System.Console.WriteLine(My.Application.Info.ProductName) System.Console.WriteLine(My.Application.Info.Copyright) System.Console.WriteLine(My.Application.Info.Trademark) System.Console.WriteLine(My.Application.Info.Version) The My.Computer object has properties to get information about the computer as follows:

• The AvailablePhysicalMemory property returns the amount of physical memory not in use. The unit of measure is bytes.

• The AvailableVirtualMemory property returns the amount of virtual memory not in use.

• The TotalPhysicalMemory property returns the amount of physical memory installed.

• The TotalVirtualMemory property returns the total amount of virtual memory installed.

• The OSFullName property stores the name of the operating system. • The OSPlatform property returns the current operating system family. • The OSVersion property returns the version of Windows running on the computer.

Page 22: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-22

Application Lesson In this application lesson, the student creates a simple Console Application project similar to the one created in Chapter 1.

• Figure 2-39 on page 106 shows the flowchart for the application. • Figure 2-40 on page 107 shows the application output. • The student configures the assembly information in the AssemblyInfo.vb file. • The student calls methods of the My.Application object and the My.Computer

object to display system information. Quick Quiz 1. Indicate which of the following statements correctly and incorrectly use a comment:

Statements Valid / Invalid ' Demonstration comment Module Demo End Module

Valid

System.Console. _ ' Print a blank line WriteLine()

Invalid – a comment cannot follow a continuation character

' Print a blank line System.Console.WriteLine() Invalid – the call to the WriteLine method will be considered a comment

2. Have the students identify which of the following are valid My objects:

Object Valid / Invalid My.Computer.Name Valid My.Computer.System Invalid My.Network.Exists Invalid My.Application.Info.Description Valid My.Application.Name Invalid My.OperatingSystem Invalid Discussion Questions

The My.Computer object has additional objects beyond those discussed in this chapter. Have students explore the Help page for the My.Computer.Audio object. Discuss how the following statement will play an audio file. My.Computer.Audio.Play("c:\Windows\Media\chimes.wav")

Page 23: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-23

The My.Settings object is used to get and save settings applicable to an application. Have students explore the Help system for the My.Settings object. Use the Help system to answer the following questions:

o How is an application setting created? o How is an application setting persisted (saved)? o How is an application setting read?

Have the student use the Object Browser to discover the methods of a class. For example,

have the student explore the methods of the System.Object class as shown in the following figure:

Key Terms attribute—Data that describes the project or a procedure in a project. Attributes store descriptive information about an assembly, such as the assembly description and version number. Assembly attributes are typically stored in the file named AssemblyInfo.vb. Code Editor—A document window specifically designed to edit Visual Basic code and code written in other .NET languages. comment—A full or partial line of text used to document an application’s code. Comments are ignored by the Visual Basic compiler. An apostrophe is used to denote a Visual Basic comment. document window—A window that is used to display and edit the individual files that make up a project. Document windows provide the means to create an application’s code (via the Code Editor) and the visual interface for an application (via the Windows Forms Designer).

Page 24: Chapter 2 Creating a Console Application with Visual Studio...project and the parts of a project. Chapter Objectives After completing the chapter, the student will be able to: •

Programming with Microsoft Visual Basic 2008: An Object-Oriented Approach – Third Edition 2-24

Help filter—A filter that restricts the Help topics being displayed to those of a particular language or the .NET Framework class library. Intellisense—The technology that helps you write Visual Basic statements by completing or suggesting class members and method arguments as you are typing the code. Object Browser—A Visual Studio tool that allows you to look at the members of the .NET Framework class library or the members of the assemblies that you create. overloaded method—A method that can be called without arguments or with different arguments. project—A file that contains the necessary information to compile an application into an assembly (executable file). solution—A solution is a physical file that contains references to the projects that make up an application. A solution file is the building block for all Visual Basic applications and is made up of one or more projects. Solutions are managed using the Solution Explorer. tool window—A window, such as the Solution Explorer or the Properties window, that provides common tools used to create all applications. Tool windows operate the same way no matter the Visual Studio language being used or the type of project being created. Visual Studio IDE—The integrated development environment used to create, compile, test, and deploy applications.