A First Look at the Visual Basic .NET IDE

A First Look at the Visual Basic .NET IDE

We'll now start looking at how a very simple Visual Basic .NET program is written. This example is contrived on purpose, the intent being to provide an overview of the .NET environment and to preview some of the tools available to you—in other words, to let you get your mind around writing a program in this new way. Follow these steps to get started:

  1. Select File | New | Project to display the New Project dialog box. Your options might vary, but for this example select the Visual Basic Projects folder on the left. On the right, notice that several types of Visual Basic .NET project types are available—very much like previous versions of Visual Basic.

  2. Leave the default project name of WindowsApplication1 and select a new subdirectory to build and save the code, as shown in Figure 1-7. As you'll see, the IDE creates subdirectories below the directory in which you save WindowsApplication1. Click OK to create the project.

    The New Project dialog box.

After a few seconds of disk whirring, the basic project will be set up in the IDE. The various windows will be populated with items for your project. Notice that a Form1.vb [Design] tab is added to the main tabbed window, as shown in Figure 1-8. The tabbed window is where you'll do most of your work. This window displays both the graphical interface of your program as well as the code.

The new project in the Visual Basic .NET IDE.

To classic Visual Basic programmers, the Visual Studio .NET IDE looks streamlined and modern. It includes the graphical controls, Forms Designer, Properties, and Solution Explorer windows. If you have ever built a program in classic Visual Basic, you know that projects are the building blocks of applications. In the past, you used the Project Explorer to manage projects, and while you could add projects to the Project Explorer to create a "group," a group quickly became difficult to manage. Recognizing this, Microsoft added the Solution Explorer to the Visual Studio .NET IDE to take the place of the Project Explorer. The Solution Explorer handles the details of file management. It provides you with an organized view of your projects and their files. In addition, right-clicking on any item in the Solution Explorer provides ready access to the commands that pertain to it.

If a project is a building block for an application, you can think of a solution as the foundation. Keep in mind that a single solution can contain multiple projects. The Solution Explorer can easily manage the complexity of juggling multiple projects and the solution to which they belong. The Solution Explorer displays a hierarchical structure of your projects and depicts relationships between them. Of course, you can still manage your projects individually; however, the notion of a solution using the Solution Explorer facilitates managing the complexity of numerous tasks, especially for developers of a multiproject solution.

When you create an application that consists of multiple projects, you should create a local solution directory to contain your local (non-Web) projects, solution files (.sln and .suo), and any shared solution items. Such a directory-based structure mirrors the organization of your solution in Solution Explorer and so maintains the logical relationships of the components on disk. Depending on whether your application will be entirely local or potentially contain some Web-based projects, you can create a solution directory in one of two ways.

  • When you create a blank solution and later add projects and files to it.

  • When you create the first project in a solution with the New Project dialog box and select the Create Directory For Solution option.

Because the Solution Explorer is the IDE element through which you centrally organize and manage all the projects and files needed to design, develop, and deploy a .NET application, a solution is also used to manage the miscellaneous files—files external to your solution—that are opened outside the context of a solution or project. These files are not included in builds and cannot be included with a solution under source control. Miscellaneous files are, however, associated with a solution by reference. When you open a solution, all the miscellaneous files that were opened when the solution was last closed will be reopened. When we start building solutions later in the book, you will see just how handy this innovative touch can be.

Some Visual Basic .NET Code

Now let's take a look at the code underlying the form created by Visual Basic .NET. Double-click the form to bring up the Code window. Here you can start to see the real differences in how Visual Basic .NET forms and applications are built.

In classic Visual Basic, when you double-click a form to display the Code window, you are presented with an empty Form_Load event template that looks like this:

Private Sub Form_Load() End Sub

You started to write code in the prebuilt event procedures such as Form_Load. And, of course, events were handed down from the mountain top, never to be expanded on. You had to use what you were given and like it.

In a Visual Basic .NET project, however, you get the following template. All of the code and the comments are generated by the .NET Forms Designer. Each program you write that targets the desktop will start like this if you use the Forms Designer. Of course, you can write the code yourself when you get more familiar with the syntax.

Public Class Form1     Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code "     Public Sub New()         MyBase.New()         'This call is required by the Windows Form Designer.         InitializeComponent()         'Add any initialization after the         ' InitializeComponent() call     End Sub     'Form overrides dispose to clean up the component list.     Protected Overloads Overrides _     Sub Dispose(ByVal disposing As Boolean)         If disposing Then             If Not (components Is Nothing) Then                 components.Dispose()             End If         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()         '         'Form1         '         Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)         Me.ClientSize = New System.Drawing.Size(292, 266)         Me.Name = "Form1"         Me.Text = "Form1"     End Sub #End Region     Private Sub Form1_Load(ByVal sender As System.Object, _         ByVal e As System.EventArgs) Handles MyBase.Load     End Sub End Class

Don't be alarmed by all of this new code; it will become clear shortly. I'll review each line and discuss what it does and why.

In classic Visual Basic, all of the public global interfaces were hidden from developers. Much of what you are seeing in the code created by Visual Basic .NET was there one way or another in classic Visual Basic, but it was hidden from the programmer's view. While hiding much of what went on under the hood accounted for the simplicity of the language, it was also the limiting factor of the language. Although some of you might be saying to yourself about now, "But I liked it simple."

Notice that the tabbed window in the IDE now has a tab for both the design environment as well as the .vb code. Click on the designer tab and check that the form has the focus. The familiar Properties window is populated with the various properties you can set within it. Select the Start Position property, as shown in Figure 1-9, and then choose Center Parent. Change the Text property from Form1 to Visual Basic .NET— Our First Form.

Changing form properties.

Unlike with classic Visual Basic, you'll notice in Visual Basic .NET that the value of a property doesn't change until you either press Enter or move to another property. The timing of this change occurs because the IDE is actually writing the new property value to your source code. Rather than waste CPU cycles updating at every keystroke—having to handle backspaces, and so on—waiting until a property is completely changed is more efficient.

note

Look at the top drop-down box in the Properties window. It reads Form1 System.Windows.Forms.Form. I stated earlier that everything in .NET is an object and that all objects originate from the mother of all objects, the System object. A form is no different. It is also created from the System object.

Now you're ready to run your program. Of course, nothing will happen except you'll see a form with a custom caption displayed in the middle of the screen. Follow these steps:

  1. Select Debug | Start or simply press F5. (OK, I admit that it's not very important, but the new default icon is pretty cool.) The new form appears on your screen, as shown in Figure 1-10.

    The form we just created.

  2. Dismiss the form to return to design mode. If the output window is not displayed, select View | Other Windows | Output.

    You can see in Figure 1-11 all of the files used and loaded into memory that are required to run the program. The symbols loaded refer to namespaces, functions, and classes used in our program. We will be discussing these in detail starting in Chapter 2. Mscorlib.dll is the common language runtime.

    The files created by our program.

  3. Click the Design tab to display the form, and then double-click it to view the code. You'll see that the designer modified the source code for you.

Notice the expand buttons along the left side of the code window. These result from a handy new keyword named #Region, which lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio code editor. The Procedure View | Full Module View options for viewing source code in classic Visual Basic have been eliminated, so if you depended on these options, you should use #Region Name with a corresponding #End Region statement to bracket logical segments of code in Visual Basic .NET. You can then expand or contract these blocks of code for easy viewing.

The region in this view is collapsed, as shown in Figure 1-12. You can provide a descriptive name for your own regions to manage your own code. In this case, the IDE used the descriptive name Windows Form Designer generated code to let you know exactly what's in the region.

Regions defined in the Code window.

Look at the code that was modified by the IDE when the properties in the Properties window were changed. Notice how the designer changed the Text property and added the FormStartPosition property to the source code. Actually, if you didn't change FormStartPosition, it would still be used but with a default value. Because you changed the default value, the property is shown because the default behavior was modified.

#Region " Windows Form Designer generated code "     Public Sub New()         MyBase.New()         'This call is required by the Windows Form Designer.         InitializeComponent()         'Add any initialization after the         ' InitializeComponent() call     End Sub     'Form overrides dispose to clean up the component list.     Protected Overloads Overrides _     Sub Dispose(ByVal disposing As Boolean)         If disposing Then             If Not (components Is Nothing) Then                 components.Dispose()             End If         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()         '         'Form1         '         Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)         Me.ClientSize = New System.Drawing.Size(292, 266)         Me.Name = "Form1"         Me.StartPosition = _             System.Windows.Forms.FormStartPosition.CenterParent         Me.Text = "Visual Basic .NET - Our First form"     End Sub  #End Region

If you have used any of the wizards in Visual Basic before, you are no stranger to the commented code automatically added to your form. Pay heed to the warning about not modifying any code in the InitializeComponent procedure. Each and every entry there can and should be modified in the Properties window as you did when changing the form's text and starting position.

Now let's build the program into an executable and see what files are created. To do this, select Release from the drop-down box on the main menu, and then select Build from the Build menu. The program should build successfully, as shown in Figure 1-13.

Visual Basic .NET tells us that our program has been built successfully.

Notice the output from the Solution Builder. It is very much like a Visual C++ program showing the progress of the build. Not much could go wrong with this program, of course, because we changed only two properties on the form. The output tells you that the build succeeded.

Files Created by the IDE for Our First .NET Program

Open the Explorer in Windows and take a look at the directory in which you created this program. The Visual Basic .NET compiler automatically created several subdirectories and populated them with project files. As you can see in Figure 1-14, a project folder with the application name WindowsApplication1 was created in the directory where Visual Basic saved the project.

The folders our program created.

A Visual Basic .NET application uses a lot of new files. It's important to know what the IDE is doing with these files and why it's doing what it does. Our project directory, WindowsApplication1, contains the files required by the IDE to load the project. These are shown in Figure 1-15.

Figure 1-15

Inside the WindowsApplication1 folder are the files required by the IDE to load the project.

The Form1.vb file is the source code for our form. If you open it with WordPad, you can see the code. WindowsApplication1.sln is the Visual Studio Solution file. It stores information about the project that is used to both uniquely identify the project and provide general information about the project. This file contains entries such as the following:

Microsoft Visual Studio Solution File, Format Version 7.00 Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") =     "WindowsApplication1", "WindowsApplication1.vbproj",     "{4046615B-BE03-4966-B975-F539A394E7AD}" EndProject Global     GlobalSection(SolutionConfiguration) = preSolution         ConfigName.0 = Debug         ConfigName.1 = Release     EndGlobalSection     GlobalSection(ProjectDependencies) = postSolution     EndGlobalSection     GlobalSection(ProjectConfiguration) = postSolution         {4046615B-BE03-4966-B975-F539A394E7AD}.Debug.ActiveCfg =             Debug|.NET         {4046615B-BE03-4966-B975-F539A394E7AD}.Debug.Build.0 =             Debug|.NET         {4046615B-BE03-4966-B975-F539A394E7AD}.Release.ActiveCfg             = Release|.NET         {4046615B-BE03-4966-B975-F539A394E7AD}.Release.Build.0             = Release|.NET     EndGlobalSection     GlobalSection(ExtensibilityGlobals) = postSolution     EndGlobalSection     GlobalSection(ExtensibilityAddIns) = postSolution     EndGlobalSection EndGlobal

Another file in the directory, the .suo file, is a binary file and is used in part to store IDE solution configuration information.

WindowsApplication1.vbproj is the Visual Basic .Net Project file. The data in this file is stored in XML. For those of you familiar with HTML, XML probably almost makes sense. Earlier I mentioned that HTML is a markup language used for formatting and displaying information, and XML is a self-describing language that describes data. As you can see, the Visual Basic .NET Project file is conceptually like an .ini file in Windows 3.1 or registry entries in later versions of Windows. It contains headings such as Settings, Reference, Imports, and Files, with information elements that, prior to .NET, would have been stored in the registry. Here's what the data in the file looks like:

<VisualStudioProject>     <VisualBasic         ProjectType = "Local"         ProductVersion = "7.0.9254"         SchemaVersion = "1.0"         ProjectGuid = "{74315F66-BB05-499D-AEB3-F786953A49CB}"     >         <Build>             <Settings                 ApplicationIcon = ""                 AssemblyKeyContainerName = ""                 AssemblyName = "WindowsApplication1"                 AssemblyOriginatorKeyFile = ""                 AssemblyOriginatorKeyMode = "None"                 DefaultClientScript = "JScript"                 DefaultHTMLPageLayout = "Grid"                 DefaultTargetSchema = "IE50"                 DelaySign = "false"                 OutputType = "WinExe"                 OptionCompare = "Binary"                 OptionExplicit = "On"                 OptionStrict = "Off"                 RootNamespace = "WindowsApplication1"                 StartupObject = "WindowsApplication1.Form1"             >                 <Config                     Name = "Debug"                     BaseAddress = "285212672"                     ConfigurationOverrideFile = ""                     DefineConstants = ""                     DefineDebug = "true"                     DefineTrace = "true"                     DebugSymbols = "true"                     IncrementalBuild = "true"                     Optimize = "false"                     OutputPath = "bin\"                     RegisterForComInterop = "false"                     RemoveIntegerChecks = "false"                     TreatWarningsAsErrors = "false"                     WarningLevel = "1"                 />                 <Config                     Name = "Release"                     BaseAddress = "285212672"                     ConfigurationOverrideFile = ""                     DefineConstants = ""                     DefineDebug = "false"                     DefineTrace = "true"                     DebugSymbols = "false"                     IncrementalBuild = "false"                     Optimize = "false"                     OutputPath = "bin\"                     RegisterForComInterop = "false"                     RemoveIntegerChecks = "false"                     TreatWarningsAsErrors = "false"                     WarningLevel = "1"                 />             </Settings>             <References>                 <Reference                     Name = "System"                     AssemblyName = "System"                 />                 <Reference                     Name = "System.Data"                     AssemblyName = "System.Data"                 />                 <Reference                     Name = "System.Drawing"                     AssemblyName = "System.Drawing"                 />                 <Reference                     Name = "System.Windows.Forms"                     AssemblyName = "System.Windows.Forms"                 />                 <Reference                     Name = "System.XML"                     AssemblyName = "System.Xml"                 />             </References>             <Imports>                 <Import Namespace = "Microsoft.VisualBasic" />                 <Import Namespace = "System" />                 <Import Namespace = "System.Collections" />                 <Import Namespace = "System.Data" />                 <Import Namespace = "System.Drawing" />                 <Import Namespace = "System.Diagnostics" />                 <Import Namespace = "System.Windows.Forms" />             </Imports>         </Build>         <Files>             <Include>                 <File                     RelPath = "AssemblyInfo.vb"                     SubType = "Code"                     BuildAction = "Compile"                 />                 <File                     RelPath = "Form1.vb"                     SubType = "Form"                     BuildAction = "Compile"                 />                 <File                     RelPath = "Form1.resx"                     DependentUpon = "Form1.vb"                     BuildAction = "EmbeddedResource"                 />             </Include>         </Files>     </VisualBasic> </VisualStudioProject>

The executable file that Visual Basic .NET builds, WindowsApplication1.exe, can be found in the Obj\Release (or Obj\Debug) folder. Right-click on the file, and then select Properties. You'll see the properties dialog box for the program, shown in Figure 1-16. When you learn how to deploy production code, custom icons and a description will be added to the executable. For now, you're looking at a stock, no frills, bare bones .NET executable.

The properties dialog box for WindowsApplication1.exe.

Another Word on Assemblies

I mentioned earlier that .NET programs contain everything needed by the system to fully describe the application. Our assembly is the simplest example possible, as all the files that make up the assembly (namely WindowsApplication1.exe) are deployed in the application folder and are not shared by other applications. Our assembly can't be referenced by other assemblies outside the application directory. Also, our simple program does not undergo version checking. To uninstall our application, made up of a single-file assembly, we only need to delete the directory that contains it. Fortunately, for many software applications, an assembly with these options is all that is needed for deploying the program.

In Chapter 8, "Assemblies in Detail," I'll describe how you can create an assembly that can be shared by multiple applications. This type of assembly has a shared name and is deployed in the global assembly cache. In addition, you can determine what load-optimization setting best fits an application. But more on that later. Let's use the divide and conquer approach by taking these new concepts in pieces and building on them as we progress in .NET proficiency.

If you want to examine the assembly for WindowsApplication1.exe, you can use a utility provided with Visual Studio .NET. The IL disassembler, Ildasm.exe, allows you to peek into the intermediate language (IL) that was created by the Visual Basic .NET compiler.

tip

As you work through the examples in the rest of the book, I'd encourage you to poke around with the disassembler to get a feel for how things go together. This will be extremely helpful for learning about the underpinnings of your programs.

Recall that the IL is the intermediate file (namely WindowsApplication1.exe) that is sent to the CLR and that the JIT compiler compiles on demand. Don't worry if the IL looks like Klingon at this point. The terminology will become second nature by the time you finish reading this book. The disassembly of WindowsApplication1.exe is shown in Figure 1-17.

A peek inside the assembly.

At a glance you can see everything that is used in this assembly. You will soon be dreaming of these little symbols as you become more proficient with .NET development.

Symbol

Description

Manifest of the assembly. It lists everything contained in the assembly.

Namespace. In our simple program, the namespace is the name of our program.

Class. We have the hidden project and Form1 classes in our assembly.

Static method. A method shared among objects.

Field. A data element.

Method. Something the object can do.

Property. Something the object is.

Double-clicking Manifest in the assembly displays the manifest's contents. Figure 1-18 shows a small portion of the manifest of our assembly.

Inside the manifest.

Keeping in mind that a module is a physical file on disk, take a look at the last several lines of the manifest file. Our assembly has a single module, namely WindowsApplication1.exe. Complex assemblies might have many more modules. Although this example is extremely simple, with it we have covered all of the parts that .NET uses to take source code and convert it to a working application.



Coding Techniques for Microsoft Visual Basic. NET
Coding Techniques for Microsoft Visual Basic .NET
ISBN: 0735612544
EAN: 2147483647
Year: 2002
Pages: 123
Authors: John Connell

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