BUY THIS BOOK
Add to Cart

Print Book $49.99


Add to Cart

PDF $39.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £35.50

What is this?

Looking to Reprint or License this content?


Visual Basic 2005 Cookbook
Visual Basic 2005 Cookbook Solutions for VB 2005 Programmers

By Tim Patrick, John Clark Craig
Book Price: $49.99 USD
£35.50 GBP
PDF Price: $39.99

Cover | Table of Contents


Table of Contents

Chapter 1: Visual Basic Programming
When Visual Basic 1.0 was introduced in the early 1990s, it greatly simplified Windows application development. Visual Basic 2005continues the tradition by providing a programmer-friendly environment in which you can write powerful desktop, web-based, and mobile applications quickly and easily.
In this introductory chapter you'll see just how easy it is to write a variety of applications by developing a simple application in three Visual Basic–supported flavors: a desktop application (" Windows Forms"), a console application, and a web-based application ("Web Forms" via ASP.NET).
The three recipes in this chapter are meant to be read as a set. The first recipe, which focuses on Windows Forms, includes additional background information concerning the logic of the application developed in all three recipes. Be sure to read this recipe first.
You want to develop a Windows Forms application that converts between the Fahrenheit, Celsius, and kelvin temperature systems.
Sample code folder: Chapter 01\Forms Version
Create a Windows Forms application, and add the appropriate controls and logic.
Start Visual Studio 2005, and then create a new project. The Start Page includes a link to do this, or you can use the File → New Project menu command. The New Project dialog appears, as shown in Figure 1-1.
Figure 1-1: Visual Studio's New Project dialog
Each template listed in this dialog starts with the most basic and empty Visual Basic project and adds just enough source code and configuration settings to get you started on the selected application type. You could choose the Blank Solution template and work your way up to the functionality provided through the Windows Application template, but that's more than we need to accomplish right now.
Select Visual Basic (or the Windows entry under Visual Basic) in the "Project types" field and Windows Application in the Templates field, enter the name of your project in the Name field (let's call ours "FormConvertTemp"), and click the OK button.
As Visual Studio works behind the scenes to configure the initial project features, let's take a few minutes to review some high school science. The three temperature systems in this program—Fahrenheit, Celsius, and kelvin—are often used to measure heat in the various scientific disciplines:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
When Visual Basic 1.0 was introduced in the early 1990s, it greatly simplified Windows application development. Visual Basic 2005continues the tradition by providing a programmer-friendly environment in which you can write powerful desktop, web-based, and mobile applications quickly and easily.
In this introductory chapter you'll see just how easy it is to write a variety of applications by developing a simple application in three Visual Basic–supported flavors: a desktop application (" Windows Forms"), a console application, and a web-based application ("Web Forms" via ASP.NET).
The three recipes in this chapter are meant to be read as a set. The first recipe, which focuses on Windows Forms, includes additional background information concerning the logic of the application developed in all three recipes. Be sure to read this recipe first.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a Windows Forms Application
You want to develop a Windows Forms application that converts between the Fahrenheit, Celsius, and kelvin temperature systems.
Sample code folder: Chapter 01\Forms Version
Create a Windows Forms application, and add the appropriate controls and logic.
Start Visual Studio 2005, and then create a new project. The Start Page includes a link to do this, or you can use the File → New Project menu command. The New Project dialog appears, as shown in Figure 1-1.
Figure 1-1: Visual Studio's New Project dialog
Each template listed in this dialog starts with the most basic and empty Visual Basic project and adds just enough source code and configuration settings to get you started on the selected application type. You could choose the Blank Solution template and work your way up to the functionality provided through the Windows Application template, but that's more than we need to accomplish right now.
Select Visual Basic (or the Windows entry under Visual Basic) in the "Project types" field and Windows Application in the Templates field, enter the name of your project in the Name field (let's call ours "FormConvertTemp"), and click the OK button.
As Visual Studio works behind the scenes to configure the initial project features, let's take a few minutes to review some high school science. The three temperature systems in this program—Fahrenheit, Celsius, and kelvin—are often used to measure heat in the various scientific disciplines:
  • In the Celsius (or Centigrade) scale, water freezes at 0°C and reaches its boiling point at 100°C. This makes it a pretty simple measurement system, at least where water is concerned. Celsius is used as the common temperature measurement system in most countries.
  • The Fahrenheit system uses the environment of its founder, Gabriel Fahrenheit, as its basis for measurement. 0°F, at the lower end of the 0-to-100 scale, is rumored to be the coldest temperature that Fahrenheit measured near his home one winter. The 100°F mark is based on his own body temperature. This system, used in America and a few other locations, is especially convenient if you are a German scientist with a slight fever.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a Console Application
You want to develop a Console application that converts between the Fahrenheit, Celsius, and kelvin temperature systems.
Sample code folder: Chapter 01\ Console Version
Create a Windows Console application, and add logic to perform all the calculations based on the user's input. First, read through Recipe 1.1 for background information on using Visual Studio and on converting between the various temperature systems.
Start Visual Studio 2005, and then use the File → New Project menu command to create a new project. Select the Windows project type, and then select the Console Application template. Click OK to create the new project. Since a console application doesn't have a special user interface, Visual Studio simply displays the default code block for the new project:
	 
Module Module1
	   Sub Main( )

	   End Sub
	End Module
There are a few different ways to rename the module. If you only want to change the name in the code, just replace the word "Module1" with something like "Convert-Temperature":
	Module ConvertTemperature
Unfortunately, this requires you to make a change to the project's properties. Before the change, Visual Studio planned to start the program from the Sub Main routine in the Module1 module. But since you changed the name, there is no longer a Module1 for Visual Studio to use.
To modify the properties, select the Project → ConsoleApplication1 Properties menu command, or double-click on the My Project item in the Solution Explorer panel. When the Project Properties window appears, the Application tab in that window should already be active. To change the starting code for the program, select "ConvertTemperature" from the "Startup object" field. Then close the Project Properties window, and return to the code.
If you want to avoid all of this unpleasantness, rename the module's filename instead of its name in the code. To do this, right-click the Module1.vb file in the Solution Explorer, choose the Rename command from the shortcut menu that appears, and give it a new name such as ConvertTemperature.vb. (Don't forget the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating an ASP.NET Web Forms Application
You want to develop a Web Forms application in ASP.NET that converts between the Fahrenheit, Celsius, and kelvin temperature systems.
Sample code folder: Chapter 01\Web Version
Create a new Web Forms application, and use ASP.NET development tools and coding methods to craft your application. First, read through Recipe 1.1 for background information on using Visual Studio and on converting between the various temperature systems.
Start Visual Studio 2005, and then create a new web site (not a "New Project"). You can use either the Create Web Site link on the Start Page or the File → New Web Site menu command. The New Web Site dialog appears, as shown in Figure 1-8.
Figure 1-8: Visual Studio's New Web Site dialog
Make sure that ASP.NET Web Site is selected in the list of templates, choose File System for the location type, enter the new directory name (or just use the default, although we're going to use "WebConvertTemp" as the final directory component), naturally select Visual Basic as the programming language, and then click the OK button.
Visual Studio does a little work and then presents you with a blank page. This is a web page document on which you will place your various web display elements. By default, it acts like a word processing document, in which added elements flow left to right, top to bottom. You can opt to place elements at specific locations, but we'll stick with the default placement mode for this program.
If it's not already in view, display the Toolbox through the View → Toolbox menu command. No doubt you've already seen the Toolbox used in Windows Forms applications. The tools displayed now are similar, although they are for specific use by ASP.NET applications only.
As with Windows Forms applications, Visual Studio presents the user interface to you, secretly writing the code behind the scenes. The generated code in Windows Forms is all Visual Basic code; you can write an entire Windows Forms application in Notepad using only Visual Basic statements. ASP.NET applications use Visual Basic for core logic and "code behind" event handlers, but the user interface is defined through an HTML/XML mix. You can modify this HTML yourself (click on the Source button at the bottom of the web page window to see the HTML generated so far) and have the changes reflected in the user interface.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: The Development Environment
Did you know that the Visual Basic 2005 compiler is available to you free of charge? You can download the .NET Framework with all included compilers directly from Microsoft's web site, and start using it immediately to develop and distribute your own .NET applications, all without shelling out a single penny.
Well, there are a few caveats. The main one is that you will have to use a tool such as Notepad to write all of your source code. And you will need to hand-type the statements that start the compilation process through the Windows Command Prompt. But other than that, it's a piece of cake. And it's still free.
If you're not that bold, you should probably fork over a little cash to obtain Visual Studio, the programming environment of choice for .NET application development. Although it's not free, you definitely get what you pay for.(Actually, Visual Basic 2005 Express Edition is free, so you get even more than you pay for.) Visual Studio is stuffed with features and support tools and visual designers and behind-the-scenes automatic code generation wizards, all of which let you concentrate on developing great code without having to worry about the picky details of setting up the compiler and deployment options.
This chapter discusses some of the snazzy features included with Visual Studio 2005. As with all the chapters in this book, we have concentrated on Visual Studio 2005 Professional Edition. However, most, if not all, recipes in this book should work with any edition of Visual Studio.
You know that Visual Studio came with a bunch of prewritten "snippets" that you can use in your applications, but you don't know where to find them in the vast Visual Studio menu system.
Code snippets are among the IntelliSense features included with Visual Studio. To find and insert a snippet, use the different snippet-related menus and keyboard sequences.
To insert a code snippet into your source code, right-click at the desired location with the mouse, choose Insert Snippet from the shortcut menu (Figure 2-1), and navigate to the snippet you want to use.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
Did you know that the Visual Basic 2005 compiler is available to you free of charge? You can download the .NET Framework with all included compilers directly from Microsoft's web site, and start using it immediately to develop and distribute your own .NET applications, all without shelling out a single penny.
Well, there are a few caveats. The main one is that you will have to use a tool such as Notepad to write all of your source code. And you will need to hand-type the statements that start the compilation process through the Windows Command Prompt. But other than that, it's a piece of cake. And it's still free.
If you're not that bold, you should probably fork over a little cash to obtain Visual Studio, the programming environment of choice for .NET application development. Although it's not free, you definitely get what you pay for.(Actually, Visual Basic 2005 Express Edition is free, so you get even more than you pay for.) Visual Studio is stuffed with features and support tools and visual designers and behind-the-scenes automatic code generation wizards, all of which let you concentrate on developing great code without having to worry about the picky details of setting up the compiler and deployment options.
This chapter discusses some of the snazzy features included with Visual Studio 2005. As with all the chapters in this book, we have concentrated on Visual Studio 2005 Professional Edition. However, most, if not all, recipes in this book should work with any edition of Visual Studio.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Discovering and Using a Code Snippet
You know that Visual Studio came with a bunch of prewritten "snippets" that you can use in your applications, but you don't know where to find them in the vast Visual Studio menu system.
Code snippets are among the IntelliSense features included with Visual Studio. To find and insert a snippet, use the different snippet-related menus and keyboard sequences.
To insert a code snippet into your source code, right-click at the desired location with the mouse, choose Insert Snippet from the shortcut menu (Figure 2-1), and navigate to the snippet you want to use.
Figure 2-1: Inserting a snippet with the mouse
An even faster method is to type a question mark ( ?) anywhere in the source code and then press the Tab key. The more formal location of this same command within the Visual Studio menu system is at Edit → IntelliSense → Insert Snippet. If you are in any way mouse-phobic when developing source code, you can use the default Visual Basic keyboard shortcut of Control-K followed by Control-X to get to the snippet picker.
Using any of these methods to access snippets presents the top-level set of snippet folders, as shown in Figure 2-2.
Figure 2-2: Primary snippet categories
To negotiate the hierarchy, use the mouse or arrow keys to select a folder or item in the pop-up list, or type a partial list name followed by the Enter key. Selecting a snip-pet folder updates the list with the items and subfolders in that selected folder. For example, in Figure 2-2, selecting "Math" with the mouse or typing "Math" from the keyboard followed by the Enter key, will open the "Math" snippet folder and display any folders or items contained within that folder. Selecting an item inserts the chosen snippet.
Each snippet contains a useful block of prewritten code, but many also include some intelligence. Some snippets include "fill in the blank" templates that provide areas for you to supply your custom values. For instance, the Data Types—defined by Visual Basic → Convert a Number to a Hexadecimal String snippet includes a field for the source value, moving the insertion point to that field immediately upon pasting the snippet in the code:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a New Snippet
You've written an especially useful block of source code, and you want to save it as a code snippet for use in other applications.
To save a block of code as a snippet for reuse, use the Code Snippet Editor for Visual Basic 2005 to create and store the snippet, or hand-code the required XML file yourself and place it in an appropriate directory.
To add a new snippet to the set of available snippets in your Visual Studio environment, fire up the Snippet Editor, and right-click on the folder where you want the snippet to appear, then select Add New Snippet from the shortcut menu.(An Add New Folder option lets you adjust the available folders. You can also create subordinate folders to a reasonable depth.) Type or paste your code into the blank pane of the Editor tab, using the Replacements tab to add any replaceable parameters. Click the Save icon near the top of the Snippet Editor to store your results. The new snippet will be available immediately within Visual Studio.
The Snippet Editor is a community-developed application available to you as a free download. You can contribute features to it yourself if you are so inclined. It's part of the "GotDotNet" Community, located at http://www.gotdotnet.com, in its "Workspaces" area.
It's also possible to code snippets yourself, using the markup specified by the Microsoft XML snippet schema. However, doing so is not for the faint of heart, and with few exceptions, the Snippet Editor is more than adequate.
Figure 2-3 shows the "Convert a Number to a Hexadecimal String" snippet used earlier, as presented in the Snippet Editor.
You are probably dying to see the actual XML that makes up a code snippet, so here is the XML for that snippet:
	<?xml version="1.0" encoding="UTF-8"?>
	<CodeSnippets xmlns=
	  "http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	  <CodeSnippet Format="1.0.0">
	    <Header>
	      <Title>Convert a Number to a Hexadecimal String</Title>
	      <Author>Microsoft Corporation</Author>
	      <Description>Returns the hexadecimal
	        representation of an integer.</Description>
	      <Shortcut>typeHex</Shortcut>
	    </Header>
	    <Snippet>
	      <Imports>
	        <Import>
	          <Namespace>System</Namespace>
	        </Import>
	        <Import>
	          <Namespace>Microsoft.VisualBasic</Namespace>
	        </Import>
	      </Imports>
	      <Declarations>
	        <Literal>
	          <ID>Number</ID>
	          <Type />
	          <ToolTip>Replace with an integer.</ToolTip>
	          <Default>48</Default>
	          <Function />
	        </Literal>
	      </Declarations>
	      <Code Language="VB" Kind="method body">
	        <![CDATA[Dim hexString As String = Hex($Number$)]]>
	      </Code>
	    </Snippet>
	  </CodeSnippet>
	</CodeSnippets>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Sharing Snippets
You've created a number of terrific code snippets, and you would like to share them with others.
The .snippet files used to store your code snippets are simple disk-based XML files. To share snippets with others, make copies of the files, and distribute them as needed.
The code snippet technology included in Visual Studio is pretty basic. It simply presents a list of code snippet files found in directories you specify. As long as snippet files appear in directories referenced by Visual Studio, those snippets are available for use.
On your system, you can probably find all the Microsoft-supplied snippets in the C:\Program Files\Microsoft Visual Studio 8\VB\Snippets\1033 folder.
Recipes 2.1, 2.2, and 2.4 provide additional information on code snippets.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Adding Snippet Files to Visual Studio
Someone else has chosen to share snippet files with you, and you're ready to use them.
Upon receiving one or more snippet files, you can integrate them into your own copy of Visual Studio using the Code Snippets Manager.
The Code Snippets Manager is accessed through Visual Studio's Tools → Code Snippets Manager menu command. The Add button on the form lets you add an entire directory of snippets to Visual Studio, while the Import button adds a single snippet file.
The quality of the code snippets you receive from others may be limited by the skill and trustworthiness of their developers. Caveat emptor.
Recipes 2.1, 2.2, and 2.3 provide additional information on code snippets.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting an Application's Version Number
You would like to display the version number of your application on its "About" form.
Sample code folder: Chapter 02\VersionNumbers
Use the My.Application.Info.Version object to access the version number of the application, and store the result in a Label control.
Visual Basic stores an application's version number as a four-part "dot"-delimited value, such as:
	1.2.3.4
The four components represent the major, minor, build, and revision numbers, respectively. They are made available through an instance of the System.Version class obtained from the My.Application.Info.Version object. You can use the members of this class to display version information when needed. The following code assumes your form has a label named VersionNumber:
	Public Class Form1
	   Private Sub Form1_Load(ByVal sender As System.Object, _
	         ByVal e As System.EventArgs) Handles MyBase.Load
	      With My.Application.Info.Version
	         VersionNumber.Text = "Version " & .Major & _
	            "." & .Minor & " (Build " & .Build & "." & _
	            .Revision & ")"
	      End With
	   End Sub
	End Class
Figure 2-4 displays the typical output for a version value set to 1.2.3.4.
Figure 2-4: Displaying an application version number
If you aren't concerned about the display format of the version number, have the Version object format itself:
	VersionNumber.Text = My.Application.Info.Version.ToString()
Each .NET assembly has a four-part version number, defined as an assembly attribute in the project's source code. In a typical Visual Basic 2005 application, this attribute is stored in the AssemblyInfo.vb file, which appears only when you have Show All Files enabled in Visual Studio's Solution Explorer panel. If you open this file, you will quickly find the line that sets the version number:
	<Assembly: AssemblyVersion("1.0.0.0")>
Altering the four-part number in the string modifies the assembly's version number. Visual Studio also provides a way to set this through a property form. From the Project Properties window, select the Application tab, and then click the Assembly Information button. The version number is set through the four fields named Assembly Version.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Letting Visual Studio Automatically Update an Application's Version Number
You want to ensure that the version number changes at least a little each time you build the application, but repeatedly updating the version number by hand is a hassle.
Let Visual Basic update the build and revision components of the version number for you. Instead of supplying digits for these components, use an asterisk for the build component:
	<Assembly: AssemblyVersion("1.2.*")>
If you want to control the build number but have Visual Basic generate the revision number, include the digits for the build component and use an asterisk for the revision component:
	<Assembly: AssemblyVersion("1.2.3.*")>
Visual Basic will auto-generate build and revision numbers for you if you supply an asterisk in place of actual digits. When auto-generating the build number, Visual Basic uses the number of days since January 1, 2000. When auto-generating the revision number, Visual Basic uses the number of seconds elapsed since midnight of the current day, divided by two. This value starts over at zero each midnight.
Although Visual Basic will update the build and revision numbers for you, you must supply the major and minor version numbers.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Setting the Startup Form for an Application
You want to indicate which of the several Windows Forms your application uses is the "main" form, the focal point of the application.
The application's main form is set through the Project Properties window. From that window, select the Application tab, and then use the " Startup form" field to select the form to use for the main form.
You can start up your Visual Basic application using the Windows Forms Application Framework, or without it. The " Enable application framework" field on the Application tab of the Project Properties window enables or disables this feature. When it's enabled, Visual Basic controls the startup process associated with your selected startup form. The Application Framework fires events during the startup process that you can use to include your own custom code. To access these events, click the View Application Events button on the Application panel of the Project Properties window.
If you disable the Application Framework, you have more control over the startup process. All Visual Basic applications begin by running a shared method named Main(), which will appear somewhere in your application's source code. You can use the "Startup form" field on the Application tab to tell Visual Basic to use the Main() method included with a specific form's code. If you do not supply such a method, Visual Basic will implicitly add one to the startup form, using code that looks something like this:
	Public Shared Sub Main()
	   Application.Run(My.Forms.Form1)
	End Sub
You may add such a method to your startup form and include additional code as needed.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Setting the Startup to a Sub Main Procedure
You decide, after all, that you want to run your own startup code and display the main form after doing some initial nonform processing.
Sample code folder: Chapter 02\SubMainStartup
Add a Main() method to a module in your application, and use that as the startup code. You will need to display forms on your own.
Add a module to your project, and then add the Main() method with at least the following code:
	Module Module1
	   Public Sub Main()
	      ' ----- Add startup code here, then…
	      Application.Run(My.Forms.Form1)
	      ' …passing the startup form as the argument.
	   End Sub
	End Module
Next, mark this Main() method as the startup code for your application, via the Application tab of the Project Properties window. Disable the Windows Forms Application Framework by clearing the "Enable application framework" field. Then set the "Startup form" field on that same tab to "Sub Main."
As discussed in the previous recipe, all applications begin from some shared method named Main(). You can supply your own Main() method, and it doesn't need to be part of a form. Adding it to a module with your own initialization code gives you the most control over the application's startup process.
The Application.Run() method runs the primary message loop for your application, a standard part of all Windows desktop programs. Pass an instance of your startup form as an argument; Visual Basic will display this form and keep the program running until the user closes this form.
Because you must disable the Application Framework to use a custom Main() method, some of the convenience and usability features included with the Framework will not be enabled by default. For instance, you will have to manually display and hide any "splash" form that appears during the initialization phase of your application.
See Recipe 2.7 for additional discussion about startup procedures in Visual Basic applications.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting an Application's Command Line
You've designed your program to support optional command-line arguments, and you want to process them.
There are a few different ways to examine and process the command-line options supplied to your program. The first and easiest of the methods involves the Visual Basic Command() function, part of the Microsoft.VisualBasic namespace. This function returns the entire set of command-line options as a String. For instance, if the user enters the following command:
	MyApp.exe /option1 /option2 filename.txt
the Command( ) function returns:
	/option1 /option2 filename.txt
The application name and extension are always removed from the string; Command( ) returns only the options, not the program name.
Because Command() returns a single string with the entire command-line option text, the responsibility for parsing each option from the string rests on your shoulders. However, Visual Basic also supplies a pre-parsed version of the options through the My.Application.CommandLineArgs collection. Each zero-based argument in the collection includes one of the original space-delimited options as entered by the user. Thus, using the example command line from just a few paragraphs ago, the following method call:
	MsgBox(My.Application.CommandLineArgs(1))
displays /option2, because the collection is zero-based.
Many applications support optional command-line arguments, generally to alter the initial view of the application on startup. Normally such arguments are entered through the Windows command prompt, cmd.exe. For example, the Notepad.exe program accepts a single command-line argument, a filename to open immediately:
	Notepad.exe c:\temp\DataFile.txt
Windows does provide some support for command-line option usage. If you create a shortcut to an application, the Target field in the shortcut's properties (accessed by right-clicking on the shortcut icon and selecting Properties) will accept commandline arguments after the executable name.
If you use the Windows File Explorer to drag and drop a file onto an application (EXE) icon, Windows starts the application, adding the dropped file's name as a command-line argument.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Testing an Application's Command Line
You have written an application that supports various custom command-line arguments, and you'd like to test the argument-parsing code from within the development environment.
Use the "Command line arguments" field in the Project Properties window to enter or modify the temporary testing command-line arguments.
You can test this code by setting a temporary command-line argument string for use in your program:
  1. Access the Debug tab of the Project Properties window.
  2. Type your temporary command line in the "Command line arguments" field.
This temporary argument string is used only when running programs within the Visual Studio development environment.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Obfuscating an Application
You've written a pretty cool application, and you'd like to sell it to customers. But you also know that the Intermediate Language (IL) code generated by the Visual Basic compiler can easily be read and turned back into reasonable source code by ne'er-do-wells intent on reaping ill-gotten rewards from your hard effort.
Use an obfuscator to alter the compiled application, making futile any attempt to reverse-engineer the application back into understandable source code. There are several third-party obfuscators on the market that target .NET-compiled applications.
These programs work with any compiled .NET application, whether they were written in Visual Basic, C#, or some other .NET-enabled language.
Visual Studio 2005 also includes an obfuscator you can use with your own applications. It's called Dotfuscator Community Edition, and although it comes with Visual Studio, it's actually developed by a separate company named PreEmptive Solutions.
It's pretty easy to perform a basic obfuscation using Dotfuscator. First, make sure you have built your application to an EXE executable (or DLL, if relevant). From Visual Studio, select the Tools → Dotfuscator Community Edition menu command. Once you get past some advertising, you will be prompted to create a new project. This is not a Visual Studio project, but a Dotfuscator project. A new project appears via the main Dotfuscator form, as shown in Figure 2-5.
Figure 2-5: A new Dotfuscator project
On the Input tab, use the left-most icon (the Open Folder icon) to locate your EXE assembly. Use the other tabs to fine-tune the obfuscation, if desired. Then use the File → Build menu command to generate an obfuscated version of the project. You'll be prompted to save the settings for this project. Once generated, the obfuscated version of the project appears in a directory named Dotfuscated in the same directory where you saved the settings.
We obfuscated a simple Windows Forms application that contained (1) a mostly empty form, (2) a static label on that form, and (3) a Click event handler for the label that just displays a message box. We used Microsoft's
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Determining if an Application Is Running in the Visual Studio Environment
Your application needs to respond one way if it is running in the Visual Studio development environment and another way if it is running as a standalone application. For instance, you might want to issue a Stop statement on errors when in the debugging environment but log the errors to a file when running as a standalone application.
There are a few different ways to determine the running environment of your application, but the simplest is to examine the System.Diagnostics.Debugger. IsAttached flag. If this property is True, your application is running in the development environment.
The IsAttached property indicates True whenever your application is running in a debugger that properly sets the underlying value of this flag. That means that if the flag is True, the program may be running in some environment other than Visual Studio. But if your program is running in some nonVisual Studio debugger, there are probably bigger issues of concern.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Accessing Environment Variables
Your program relies on data stored in DOS-style environment variables, and you're ready to retrieve some of those values.
Use the My.Application. GetEnvironmentVariable() method to retrieve specific environment variable values.
Microsoft's MS-DOS operating system predated Windows, and when Windows was first released, it needed to use and support many of the existing MS-DOS features. One such feature involved environment variables, a collection of name/value pairs that served as a set of global constants programs could read and use. For instance, the PATH variable stored a list of directories Windows used to locate programs. Other applications could read the PATH variable for their own use.
To retrieve the PATH environment variable from Visual Basic, use this statement:
	Dim thePath As String = _
	   My.Application.GetEnvironmentVariable("PATH")
An error occurs if you supply a variable name that does not exist. If it does exist, the method returns just the value of the variable, not its name.
Visual Basic also includes a built-in Environ() function that provides similar functionality:
	Dim thePath As String = Environ("PATH")
If the supplied variable name cannot be found, Environ() returns an empty string without raising an error.
Environ() also retrieves environment variables by numeric position. The following code scans through the set of environment variables until it hits a blank result, indicating the end of the set of variables:
	Dim counter As Integer
	Dim fullVariable As String
	Dim namePart As String
	Dim valuePart As String
	Dim equalsPosition As Integer

	For counter = 1 To 255
	    fullVariable = Environ(counter)
	    If (fullVariable = "") Then Exit For
	    equalsPosition = InStr(fullVariable, "=")
	    If (equalsPosition > 0) Then
	        namePart = Left(fullVariable, equalsPosition - 1)
	        valuePart = Mid(fullVariable, equalsPosition + 1)
	        ' ----- Use these values as needed.
	    End If
	Next counter
For additional information on environment variables, see the online help included with Microsoft Windows. On Windows XP, access help from the Start button (Start → Help), and search for "environment variables."
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Accessing the Registry
Although you have been warned that accessing the registry can lead to system instability, you need to store and retrieve values in one or more of the registry hives.
Use the registry features in the My.Computer. Registry object to read, write, and otherwise manipulate registry information.
The My.Computer.Registry object includes the following members:
ClassesRoot field
Returns a RegistryKey object that refers to the HKEY_CLASSES_ROOT top-level key of the registry.
CurrentConfig field
Returns a RegistryKey object that refers to the HKEY_CURRENT_CONFIG top-level key of the registry.
CurrentUser field
Returns a RegistryKey object that refers to the HKEY_CURRENT_USER top-level key of the registry.
DynData field
Returns a RegistryKey object that refers to the HKEY_DYN_DATA top-level key of the registry.
GetValue( ) method
Retrieves the data associated with a specific key and value somewhere in the registry.
LocalMachine field
Returns a RegistryKey object that refers to the HKEY_LOCAL_MACHINE top-level key of the registry.
PerformanceData field
Returns a RegistryKey object that refers to the HKEY_PERFORMANCE_DATA top-level key of the registry.
SetValue( ) method
Adds or updates the data associated with a specific key and value somewhere in the registry.
Users field
Returns a RegistryKey object that refers to the HKEY_USERS top-level key of the registry.
Most of the Registry members return a RegistryKey object, a generic object that can refer to any key within the registry. This object also has many useful members. Some members let you manipulate the keys that appear just below the one represented by the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting System Information
You've heard that .NET provides powerful access to the most essential features of Windows, but the Framework Class Library is huge, and you're not sure where to find the total amount of memory installed on the local system. How can you get system-specific information quickly and easily?
Use the various objects and members of Visual Basic's My namespace. Microsoft introduced this new feature in the 2005 release of the language.
The My namespace was added to Visual Basic to help restore some of the simplicity and accessibility of Visual Basic that was lost in its transition to .NET.
For example, to determine the amount of installed memory on the local system, use the following statement:
	Dim installedMemory As Long = _
	   My.Computer.Info.TotalPhysicalMemory
Another useful source of system settings is the System.Windows.Forms. SystemInformation object, which has dozens of informative members.
The My hierarchy makes an incredible number of features available in one easy-to-access place. Table 2-1 includes a small sampling of the information you can obtain from the My namespace.
Table 2-1: A sampling of My features
If you need to access this information…
…use this My namespace member
The command-line arguments used to start the program
My.Application.CommandLineArgs
The application version number
My.Application.Info.Version
The set of all forms currently open
My.Application.OpenForms
Features to read and write clipboard data
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting the User's Name
You need to obtain the name of the current Windows user.
Use the My.User.Name property to get the domain and login ID of the current user.
The My.User.Name property returns a string containing the current user ID and related domain name in the format "domain/user." If the user is part of a workgroup instead of a domain, the domain portion may be replaced by the local machine name. Applications written using ASP.NET do not have access to the same type of user information as desktop applications because Web Forms programs run in the context of a special web-application user.
If your application uses an authentication system other than the default Windows security scheme, My.User.Name may return information about the current user in a different format.
If you don't like the merged "domain/user" format, you can get the individual components from other areas within the .NET object hierarchy. These three properties will probably get you what you need:
  • System.Environment.MachineName
  • System.Environment.UserDomainName
  • System.Environment.UserName
If you are interested in identifying the registered owner of the local workstation, you can find that information in the system portion of the registry. The key is:
	\\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion
The RegisteredOrganization and RegisteredOwner values within that key supply the values that you often see when installing new software on your system.
Recipe 2.15 provides additional resources for gathering system-and user-specific details from .NET.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Application Organization
This chapter shows you how some of the object-oriented programming (OOP) features in Visual Basic 2005 are used to build Visual Basic applications. These features include class constructors, namespaces, and support for overloading. While you will spend most of your coding life writing the basic logic of your functions, properties, and Sub procedures, you wouldn't be able to do it without the basic container systems introduced here.
You would like to add some general methods and fields that are accessible to your entire application.
Add a code module—a construct that is similar to a class, but uses the Module key-word instead of Class—to your application.
Visual Basic includes three major code and value containers: classes, structures, and modules. All three types are based on the core definition of a class, but there are times when you'll want to choose one over another. Modules are useful for storing functions, subroutines, constants, and variable fields that are considered "global" to your entire application. In pre-.NET versions of Visual Basic, most nonform-specific code was stored in a similar "module file" (with a " .bas" file extension). Modules in .NET provide some of that same functionality but in an object-oriented context.
If you've already created a new project or opened an existing project in Visual Studio, you can add a new module through the Project → Add Module menu command. The Add New Item dialog (Figure 3-1) should already have the Module template selected. Simply give it a useful name in the Name field, then click the Add button.
Figure 3-1: Visual Studio's Add New Item dialog
Visual Studio presents you with the code for this new template:
	Module Module1

	End Module
You can start adding members to the module immediately. Supported members include Sub procedures, functions, properties, events, delegates, classes, structures, and enumerations. Before coding each member, decide the access you want to grant and prefix the definition with the appropriate access keyword ( Public, Shared, or Friend
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
This chapter shows you how some of the object-oriented programming (OOP) features in Visual Basic 2005 are used to build Visual Basic applications. These features include class constructors, namespaces, and support for overloading. While you will spend most of your coding life writing the basic logic of your functions, properties, and Sub procedures, you wouldn't be able to do it without the basic container systems introduced here.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a Code Module
You would like to add some general methods and fields that are accessible to your entire application.
Add a code module—a construct that is similar to a class, but uses the Module key-word instead of Class—to your application.
Visual Basic includes three major code and value containers: classes, structures, and modules. All three types are based on the core definition of a class, but there are times when you'll want to choose one over another. Modules are useful for storing functions, subroutines, constants, and variable fields that are considered "global" to your entire application. In pre-.NET versions of Visual Basic, most nonform-specific code was stored in a similar "module file" (with a " .bas" file extension). Modules in .NET provide some of that same functionality but in an object-oriented context.
If you've already created a new project or opened an existing project in Visual Studio, you can add a new module through the Project → Add Module menu command. The Add New Item dialog (Figure 3-1) should already have the Module template selected. Simply give it a useful name in the Name field, then click the Add button.
Figure 3-1: Visual Studio's Add New Item dialog
Visual Studio presents you with the code for this new template:
	Module Module1

	End Module
You can start adding members to the module immediately. Supported members include Sub procedures, functions, properties, events, delegates, classes, structures, and enumerations. Before coding each member, decide the access you want to grant and prefix the definition with the appropriate access keyword ( Public, Shared, or Friend). For instance, the following block of code adds a function to the module Module1 and assigns the function