BUY THIS BOOK
Add to Cart

Print Book $49.99


Add to Cart

Print+PDF $64.99

Add to Cart

PDF $39.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £30.99

What is this?

Looking to Reprint or License this content?


Programming Visual Basic 2008
Programming Visual Basic 2008 Build .NET 3.5 Applications with Microsoft's RAD Tool for Business By Tim Patrick
May 2008
Pages: 780

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introducing .NET
Welcome to .NET! I might as well have said, "Welcome to the universe," because like the universe, .NET is huge. And it's complex. And it's filled with black holes and other things that don't always make sense. Yet it (.NET, not the universe) turns out to be a fantastic system in which to develop software applications.
The .NET Framework was not developed in a vacuum (unlike the universe); Microsoft designed it and its related development languages—especially C# and Visual Basic—to address various issues that plagued Windows software developers and users. To fully understand why .NET was necessary, we need to take a short trip down computer memory lane.
Practical, general-purpose computers have been around since the mid-20th century. However, they were inaccessible to most people because (a) they cost millions of dollars; (b) they consumed gobs of electricity; (c) maintenance and programming could be done only by highly trained specialists; and (d) they tended to clash with the living room furniture.
Fast-forward about 30 years. IBM comes out with the "personal" computer. These "desktop" computers represented a great advance in technology, but only a minority of people ever used them. They continued to be expensive (thousands of dollars), and maintenance and programming still required significant investments in training. IBM PCs also looked hideous around the living room furniture.
Then came the Apple Macintosh. With its sleek design and its user-friendly functionality, it introduced the joy of computing to the masses. And while programming it was not always straightforward, it did give nice results. It's no wonder that Microsoft decided to copy—oops, I mean improve upon—its functionality.
Microsoft Windows 1.0 brought a greater level of usability to the IBM/Intel computing platform. But it wasn't a free ride for programmers. MS-DOS development was hard enough without the addition of the "message pumps" and the hundreds of Application Programming Interface (API) calls needed by Windows programs. Visual Basic 1.0, introduced in 1991, greatly simplified the development process, but with the advent of 32-bit systems, ActiveX and COM components, and the Web, even VB programmers soon felt overwhelmed.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Before .NET
Practical, general-purpose computers have been around since the mid-20th century. However, they were inaccessible to most people because (a) they cost millions of dollars; (b) they consumed gobs of electricity; (c) maintenance and programming could be done only by highly trained specialists; and (d) they tended to clash with the living room furniture.
Fast-forward about 30 years. IBM comes out with the "personal" computer. These "desktop" computers represented a great advance in technology, but only a minority of people ever used them. They continued to be expensive (thousands of dollars), and maintenance and programming still required significant investments in training. IBM PCs also looked hideous around the living room furniture.
Then came the Apple Macintosh. With its sleek design and its user-friendly functionality, it introduced the joy of computing to the masses. And while programming it was not always straightforward, it did give nice results. It's no wonder that Microsoft decided to copy—oops, I mean improve upon—its functionality.
Microsoft Windows 1.0 brought a greater level of usability to the IBM/Intel computing platform. But it wasn't a free ride for programmers. MS-DOS development was hard enough without the addition of the "message pumps" and the hundreds of Application Programming Interface (API) calls needed by Windows programs. Visual Basic 1.0, introduced in 1991, greatly simplified the development process, but with the advent of 32-bit systems, ActiveX and COM components, and the Web, even VB programmers soon felt overwhelmed.
Throughout the 1990s, the situation only seemed to worsen. Microsoft saw increased competition in the form of the Java™ language and the Linux operating system. Hackers were exploiting buffer overruns and other security issues present in the Windows platform. Users experienced myriad computer problems stemming from conflicting standards, competing data integration technologies, registry bloat, and "DLL hell." In frustration, an Excel user's group set fire to the entire Microsoft campus in Redmond.
Well, it didn't get that bad. But Microsoft did see that it needed to address the overall software development and usability issues on its beloved Windows platform. Its solution came in the form of the .NET Framework.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Back to Introducing .NET
When Microsoft announced its plans for .NET, it surprised many developers, especially Visual Basic developers, who saw it as a giant step backward for "Rapid Application Development." But the release of the .NET Framework version 1.0 in 2002 did bring many needed benefits:
.NET introduced a unified programming environment
All .NET-enabled languages compile to "Microsoft Intermediate Language" before being assembled into platform-specific machine code. Visual Basic, C#, and other .NET languages are wrappers around this common .NET "language." Since all .NET-enabled compilers speak the same underlying language, they no longer suffer from the many data and language conflicts inherent in other cross-language component-based systems such as COM. The .NET version of Visual Studio also unified the standard user interface that lets programmers craft source code.
.NET committed developers to object-oriented technologies
Not only does .NET fully embrace the object-oriented programming paradigm, but everything in .NET is contained in an object: all data values, all source code blocks, and the plumbing for all user-initiated events. Everything appears in the context of an object.
.NET simplified Windows programming
Programming in Visual Basic before .NET was easy enough, until it came time to interact with one of the API libraries, something that happened a lot in professional programming. With .NET, most of the regularly used APIs are replaced with a hierarchy of objects providing access to many commonly needed Windows features. Since the hierarchy is extensible, other vendors can add new functionality without disrupting the existing framework.
.NET enhanced security
Users and administrators can now establish security rules for different .NET features, to limit malicious programs from doing their damage. .NET's "managed" environment also resolves buffer overrun issues and memory leaks through features such as strong data typing and garbage collection.
.NET enhanced developer productivity through standards
The .NET Framework is built upon and uses many new and existing standards, such as XML and SOAP. This enhances data interchange not only on the Windows platform, but also in interactions with other platforms and systems.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The .NET Object
To fully understand software development in .NET, you must understand what an object is. (If you are familiar with object-oriented programming—OOP—you can probably skip down to the next section, although you will miss some really great content.) While some of this section's information will also appear in , it is so important to the discussion of .NET that a portion appears here as well.
From a programming standpoint, a computer performs four basic tasks:
  • It stores data in the computer's memory area.
  • It supports processing of this data through basic operations, including addition and subtraction, Boolean algebra, and text string manipulation.
  • It allows the user to interact with the data stored in memory.
  • It provides a way to bring the data in and out of memory, through input and output devices such as keyboards and printers, and through long-term storage media such as hard drives.
The core of these four activities is data. Computers exist to manipulate data. Operating systems provide the basic foundation for these activities, but it is software applications that make these features—the ability to manipulate data—real and meaningful to the user. High-level programming languages are the primary tools used to develop these applications, each of which uses some general methods to make data manipulation features available to the programmer. Back in the good old days of assembly language development, if you knew the memory address of a piece of data, you could access and manipulate it directly. In early flavors of BASIC and in most other "procedural" languages, data was accessed through variables.
As languages grew in complexity and purpose, so did their view of data. In the LISP (short for "List Processing" or "Lots of Irritating Silly Parentheses") language, any data value exists within a larger list or set of data. But in .NET languages, data is viewed through the object.
Objects are collections of data values and associated source code. While in older BASIC dialects, each data element was more or less independent through its named variable, related data values in OOP languages can be grouped into objects. Object implementations often include source code designed to manipulate the data values of that object.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Parts of the .NET Framework
So, now you know all about objects, and you are probably thinking it's time to toss this book into the pile and start programming. But there are a few more parts of the .NET Framework still to discuss. These parts show up ad nauseam in the .NET documentation, and they each have a three-letter acronym (TLA), or thereabouts.
At the center of the .NET Framework is the Common Language Runtime (CLR), so named not because it is common or ordinary, but because all .NET-enabled languages share it in common. Everything you do in a .NET program is managed by the CLR. When you create a variable, thank the CLR and its data management system. When you say goodbye to a piece of data, thank the CLR and how it manages the release of data through its garbage collection system. Did you notice how the word manage keeps showing up in those sentences? My editor sure did. But "manage" is the mot juste, since that is what the CLR does. In fact, software written for the .NET Framework is called managed code. Any code that falls outside the CLR's control, including COM (ActiveX) components used by your .NET application, is known as unmanaged code.
The CLR is a lot like Los Angeles International Airport. If you have ever been to LAX, you know that there is a whole lot of activity going on. Airplanes arrive and depart each minute. Cars by the thousands enter and leave the two-level roadway and the central parking structures. People and pickpockets move constantly among the eight main terminals and the massive international terminal. There's a lot happening, but so much of it is managed. Planes cannot take off or land without approval from the control tower. Access points and gates manage the roadways and parking garages. Friendly, courteous TSA agents manage the flow of passengers and pickpockets into and out of the secure areas of the terminals.
The control and management structures in place at LAX ensure an orderly and secure flow of people between their planes and the city of Los Angeles. The control and management structures of the CLR ensure an orderly and secure flow of data between .NET code and the rest of the computer or connected network.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
From Source Code to EXE
Now you know pretty much everything there is to know about .NET except for that pesky programming thing. Before delving into some actual code, let's take a little snack break and examine the lifetime of an application, from start to finish (see ).
Figure : The real Visual Basic development process
So, here's what happens, step by step:
  1. You, as the programmer, are responsible for preparing the basic ingredients (a) of the application. For Visual Basic programs, this means creating one or more source code files with a .vb extension. Your ingredients may also include other support files, such as resource files (text and graphics files, often used for multilanguage support).
  2. Your application is cooked by the Visual Basic compiler (b). The result is an assembly, complete with a manifest and metadata. The output is actually semicompiled MSIL and includes ready-to-execute versions of the original source code's types and members, including all member and type names. All this content can be "decompiled" (returned back to full MSIL, although not to full Visual Basic) using a tool named ildasm.exe (the Microsoft Intermediate Language Disassembler), which is included with the .NET Framework. Since you probably don't want just anyone disassembling your application and looking at the code, Microsoft (and other third parties) also supplies an obfuscator, which sufficiently scrambles the content of your code to make it just difficult enough to discourage prying eyes.
  3. The assembly (c) is deployed to the user's workstation. A few different methods are used to deploy the application, including (1) generating a standard Windows Installer setup package; (2) generating a ClickOnce deployment; or (3) performing an xcopy install, which involves nothing more than copying the EXE assembly itself to the destination machine. No matter which deployment method you choose, the .NET runtime (d) must also be installed on the user's workstation.
  4. The user eats—I mean runs—the program (e). The CLR does a final just-in-time (JIT) compile of the MSIL assembly, to prepare it for use on the local platform. It then presents the application to the user, and manages all aspects of the application while it runs. The user experiences a level of joy and satisfaction rarely encountered when using other software 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!
What About Visual Studio and Visual Basic?
Wait a minute, what about Visual Studio? That last section didn't even mention it. And it didn't need to, since you do not need to use Visual Studio to develop, compile, deploy, or run Visual Basic applications. The entire .NET Framework—including the Visual Basic compiler—is available for free from Microsoft's web site; download it and use it to develop and deploy applications that are every bit as powerful and complex as, well, Visual Studio.
The July 1983 issue of Datamation magazine includes an article from manly reader Ed Post, titled "Real Programmers Don't Use Pascal." I highly recommend that you read this article, as it will help you quickly separate the real programmers from the "quiche eaters." And when you do, run away as fast as you can from the real programmers. Oh, sure, they can reconstruct your source code from the obfuscated .NET assembly, but they will be useless on a team project using Visual Studio.
A "real programmer" could code any .NET application using Notepad, and it would run. Actually, real programmers would use Emacs or vi instead of Notepad (since Windows does not include a keypunch interface), but the results would be the same. They would growl as you blissfully type away in Visual Studio's elegant, well-designed, and fully customizable and extensible user interface. They would gripe and bare their cheese-cracker-with-peanut-butter-encrusted teeth at you while you use the IntelliSense and AutoCompletion features built into the Visual Studio code editor. They would consume another slice of quiche-shaped cold pizza while you drag-and-drop both Windows and web-based user interfaces.
Yes, the real programmer could generate full applications with just a text (or hex) editor and a .NET compiler, but you would get the glory, since you would be done in a fraction of the time it would take the FORTRAN lover to eek out his 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!
Visual Studio 2008
Since this is a book on Visual Basic development and not on Visual Studio usage, I won't be delving too much into Visual Studio's features or its user interface elements. It is a great application, and its tight integration with the .NET Framework makes it the best tool for developing applications with .NET. But as the real programmer would tell you, it is really just a glorified text editor. Visual Studio hides a lot of the complexity of .NET code, and its automatic generation of the code needed to build your application's user interface is a must-have. Most of its features exist to simplify the process of adding code to your application.
Although I will not be including a 20-page review of Visual Studio right here, you will find images of Visual Studio throughout the text, placed so as to advance your understanding of the topics under discussion in each chapter. When you start up Visual Studio for the first time, it displays the Start Page. (See . The screenshots in this book are taken from the Professional Edition of Visual Studio 2008.)
Figure : The Visual Studio Start Page
Visual Studio 2008 is the fourth major release of the product since .NET's initial introduction in 2002. Each release (in 2002, 2003, 2005, and 2008) corresponds to a related release of the .NET Framework (versions 1.0, 1.1, 2.0, and 3.5, respectively) and of the .NET implementation of Visual Basic. The 2008 release of Visual Studio is major. It is packed with new usability features, and comes in four delicious flavors:
Visual Studio 2008 Express Edition
This entry-level product is geared toward the home hobbyist or weekend programmer who wants to learn .NET and one of its core programming languages, but won't be snuggling up to it on a daily basis. Visual Studio 2008 Express Edition is actually multiple Express Edition language products promoted together, including Visual Basic 2008 Express Edition. Microsoft's goal is to introduce as many people as possible to the joys of .NET programming, so it offers the Express Edition products at no cost. This edition includes a simplified Visual Studio-like user interface, but it does impose a few restrictions on your program-crafting ability. You can still edit the source code directly and craft applications of any complexity, but the Express UI won't always assist you with this. For instance, you cannot develop web applications with the Visual Basic Express product unless you install the separate Visual Web Developer 2008 product. Also, Express doesn't include much support for deployment; applications designed with the Express Edition are generally expected to be used on your own workstation only.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
Nearly two decades ago, Visual Basic transformed the Windows development landscape with its drag-and-drop programming model and its glitzy event-driven development structure. But Windows has changed a lot since those days of Windows 3.x. As Windows has changed, Visual Basic has changed right along with it. Visual Basic 2008, through its association with the .NET Framework, provides access to the programming tools needed to develop quality applications for the Windows desktop, the Internet, and the next generation of mobile devices.
And Microsoft is not halting this progress with the 2008 release. The next version of Visual Basic, code-named both VBx and Hawaii, promises to include even more advanced features. That release will be built on top of Microsoft's Dynamic Language Runtime (DLR), allowing it to freely interact with libraries from languages such as Ruby and Python.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Project
Welcome to the "" section, the part of each chapter where you have an opportunity to get "hands-on" with Visual Studio 2008 and Visual Basic. Development of the Library Project, the main project focus of this book, formally begins in , but there's still project work to do in the meantime. In this chapter, I'll introduce you to the sample source code provided with this book, and we'll take a stab at using it.
Since most "" sections, including this one, will involve Visual Studio, make sure you have it installed and ready to use. Also, since each "" section is designed for you to use interactively with the supplied source code, I will assume that you have downloaded and installed the source code (see for instructions), and are viewing the source code with one eye while you read this section with the other. I will print sections of the source code in the book, but with tens of thousands of source code lines in the Library Project, I will not be able to print every line here. You will certainly get a lot out of each "" section by simply reading it, but you will get even more if you have access to the full source code.
In this chapter's project, we'll load a sample program into Visual Studio and run it. There are two ways to do this. The first way is just to open the existing project directly from the installation directory. Browse to the directory where you installed this book's source code, open the subdirectory, and double-click the Chapter1.vbproj file. This will open the project directly in Visual Studio, ready to use.
The second way is to use the chapter-specific project templates to create new projects in Visual Studio. The Setup program for this book's source code modifies your installation of Visual Studio, adding new entries in the New Project dialog window. Each of these new "project templates" can be used as the starting point for a new Visual Basic project. To load the sample program using the template, start Visual Studio. The Start Page will appear, as shown way back in . From the File menu, select New Project to display the New Project dialog window (see ).
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: Introducing Visual Basic
It was a dark and stormy night. Hector gazed wearily through his bloodshot eyes, through the black-rimmed corrective lenses, and through the haze of the fluorescent overhead lights at the phosphor-enriched display. Had it really been four months since he started the six-month project? Did his boss really threaten to fire him after seeing his progress? It seemed like all of those MS-DOS programs he had written for the company over the years meant nothing. Why did he promise to port the company's main internal system to Windows? In a moment of despair, tears streamed down his cheeks, diluting his last remaining can of Jolt Cola.
It's 8:00 a.m. A loud thump on Hector's desk brings him suddenly out of his slumber, the drool still trickling from the corner of his mouth. What's that? What's that box on his desk? "V-i-s-u-a-l B-a-s-i-c?" A note on the box says to rewrite his code in "this." Desperate to try anything, Hector installs the three floppy disks on his '386 powerhouse.
Six weeks later, Hector has completed the project, ahead of schedule, feature-complete, and with the accolades of his boss and department. And it's all due to Visual Basic. But VB didn't just improve his programming life. Overall, he's happier, has kicked the caffeine habit, is able to bench-press 300 pounds, no longer walks with a limp, has increased libido, and has whiter teeth. "Thank you, Visual Basic 1.0!"
It's possible that I got a few of the details wrong in Hector's life. But for many business developers, Visual Basic 1.0 was a breath of fresh air. It's not that they could do more with Visual Basic; programs written in C were more powerful and had greater flexibility. But business programmers didn't always need that flexibility back in the transition from MS-DOS. They just wanted to manage data, and they didn't want to worry about how to present every little pixel on the screen. Visual Basic provided the tools to write applications quickly and with much less effort than that required by other Windows development tools and languages.
Visual Basic's simplicity was embraced by developers everywhere, but the honeymoon quickly wore off. Given the speed at which programs of reasonable quality could be cranked out with Visual Basic, programmers and businesses began demanding more. And Microsoft responded. Visual Basic 2.0 and 3.0 were released in quick succession in 1992 and 1993, providing enhanced database integration and additional visual development features. Version 4.0, released in 1996, introduced 32-bit programming to the language, and support for the already-popular Windows 95 platform. Two more quick releases—Visual Basic 5.0 in 1997 and Visual Basic 6.0 in 1998—added even more features and complexity to the otherwise "basic" language, features supporting some but not all object-oriented programming (OOP) techniques, ActiveX control development, and web-based logic coding. Microsoft had even integrated the core Visual Basic engine—christened Visual Basic for Applications, or VBA—into its suite of Office products, proclaiming it as the new official macro language and making the engine available to any third party that wanted to do the same.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The History of the Visual Basic Revolution
It's possible that I got a few of the details wrong in Hector's life. But for many business developers, Visual Basic 1.0 was a breath of fresh air. It's not that they could do more with Visual Basic; programs written in C were more powerful and had greater flexibility. But business programmers didn't always need that flexibility back in the transition from MS-DOS. They just wanted to manage data, and they didn't want to worry about how to present every little pixel on the screen. Visual Basic provided the tools to write applications quickly and with much less effort than that required by other Windows development tools and languages.
Visual Basic's simplicity was embraced by developers everywhere, but the honeymoon quickly wore off. Given the speed at which programs of reasonable quality could be cranked out with Visual Basic, programmers and businesses began demanding more. And Microsoft responded. Visual Basic 2.0 and 3.0 were released in quick succession in 1992 and 1993, providing enhanced database integration and additional visual development features. Version 4.0, released in 1996, introduced 32-bit programming to the language, and support for the already-popular Windows 95 platform. Two more quick releases—Visual Basic 5.0 in 1997 and Visual Basic 6.0 in 1998—added even more features and complexity to the otherwise "basic" language, features supporting some but not all object-oriented programming (OOP) techniques, ActiveX control development, and web-based logic coding. Microsoft had even integrated the core Visual Basic engine—christened Visual Basic for Applications, or VBA—into its suite of Office products, proclaiming it as the new official macro language and making the engine available to any third party that wanted to do the same.
Seven years after its initial introduction, Visual Basic had taken the programming world by storm. Millions of developers were using the language, including in-house developers at Fortune 500 companies, writing applications that supported core business functions. VB still retained some of the flavor of the original BASIC language—a "beginner's" programming language developed by John Kemeny and Thomas Kurtz at Dartmouth College back in 1963. This caused no end of snickering from C and C++ developers and other cola addicts. But VB programmers could see a powerful future for their language of choice.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Visual Basic from the Inside Out
As a general-purpose development language, Visual Basic includes gobs of features that allow you to develop just about any type of application supported by the Microsoft Windows platform. As such, all of its features could never be covered in a concise, 20- or 30-page chapter, and I won't try. What I will do in this chapter is to introduce you to the basics of the language, and its core features. Features not covered in this chapter are discussed throughout the rest of the book. It has to be that way, since I don't want you to finish this chapter and then say to yourself, "That Tim Patrick is so amazing. I learned all I needed to know about Visual Basic in one chapter; I didn't even have to read the rest of the book." My publisher would not be amused.
In the remainder of this chapter, I will take the "from the inside out" approach, starting the discussion with the core concepts of logic and data, and adding layer after layer of Visual Basic functionality as you turn the pages.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Basics of Logic and Data
Lest you forget it, let me remind you again: computers are not really very smart. They know how to do only the simplest of tasks. If you want them to do anything remotely complex, you have to give precise, step-by-step instructions down to moving individual bits of data—only 1s and 0s, remember—around in memory. Fortunately, most of the code you would ever need at that low level has already been written for you, and incorporated into the Windows operating system and the .NET Framework. Microsoft- and third-party-supplied code libraries give you a lot of prewritten functionality that's available for use in your own programs. And that's good, because you would rather be hurtled into space on a giant bungee cord than have to write business applications at the machine code level all day long.
Even though you have all this great prewritten code in your arsenal, you still have to tell the computer precisely what you want it to do, in fine detail, or it won't do it. And that's where high-level languages like Visual Basic come in. They provide the grammar you need to communicate with the computer. For any given tasks that the computer needs to perform, your job as a programmer is to determine the individual steps to accomplish that task—the logic—and translate those steps into computer-ese using the programming language.
As an example, let's say you receive a request from the sales department for a program that will reverse all the letters in any chunk of text provided to the program. "Our customers are clamoring for this; we need it by Tuesday," they say. OK, so first you figure out the logic, and then you implement it in Visual Basic. Using pseudocode, an artificial programming language that you make up yourself to help you write programs, you can sketch out the basics of this task (with leading line numbers):
01  Obtain the original text (or string) from the user.
02  If the user didn't supply any content, then quit now.
03  Prepare a destination for the reversed string, empty for now.
04  Repeat the following until the original string is empty:
05     Copy the last character from the remaining original string.
06     Put that character onto the end of the destination string.
07     Shorten the original string, dropping the last character.
08  [End of repeat section]
09  Show the user the destination string.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Data Types and Variables
Take my data . . . please! Ha, ha, that one always cracks me up. But it's actually what I ask my Visual Basic application to do: take data from some source (keyboard, hard disk, Internet, etc.) and present it in some useful way. All programs I write will actively manage at least some data in memory. Each data value is stored in a specific area of the computer's memory, as determined by the Common Language Runtime (CLR). The statements in Visual Basic exist primarily to manage and manipulate this data in useful and complex ways.
All data managed by the CLR is stored in the computer's memory, with each data value separated and protected from all others. It's as though each data value had its own individual teacup, as in .
Figure : All types of teacups and data
All data values managed by the CLR have content and type. Content is the actual data: the text string "abc," the number 5, a sales invoice, orange pekoe. Whatever you put in the teacup, that's the content. In some cases, .NET allows you to store absolutely nothing in the teacup (for reference types as described shortly, or "nullable" value types as described in ).
Type indicates the kind of content stored in the teacup. In , this is shown by the shape of each teacup. Each teacup has limits on the type of data that can be poured into the teacup: a text string, an integer number, a customer invoice.
Some basic data values, such as numbers and text strings, can be entered into your source code and used just as they are. For instance, the MsgBox procedure displays a window with a supplied text message. The statement:
MsgBox("The answer is " & 42)
includes a literal string, "The answer is," and a literal integer value, 42. (The "&" symbol is an operator that connects two values together into a new string.) Literals are used once, and then they're gone. If I wanted to show the same "The answer is 42" message again, I would have to once again type the same literal values into a different part of the source code.
Visual Basic supports several types of basic literals. String literals are always surrounded by quote marks. If you want to include a quote mark itself in the middle of a string, include two instead of one:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Intermission
That was a lot to take in. Getting your mind around data and variables is probably the most complex part of programming in Visual Basic. Once you have the data in variables, it's pretty easy to manipulate.
Although the thought of a cup of tea may cause you to run out of the room like a raving lunatic, you might want to take a few minutes, grab a cup, glass, saucer, or mug of your beverage of choice, and relax. I'll see you in about 20 or 30 minutes.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Comments
If you're an opera fan, you know how exciting a good opera can be, especially a classic work presented with the original foreign language libretto. If you're not an opera fan, you know how irritating it can be to listen to several hours of a foreign language libretto. With the advent of "supra titles" conveying the English-language interpretation of the content, those who until now have gotten little joy out of the opera experience will still find it repulsive, only this time in their native tongue. But at least now they will know why they don't enjoy the story.
That's really what comments do: tell you in your own language what is actually going on in a foreign language. In this book, the foreign language is Visual Basic, and English is the vernacular. You may find a particular block of Visual Basic code to be poorly written or even detestable, but if the accompanying comments are accurate, you can be disgusted in your own language, with a human-language understanding of the process.
Comments normally appear on lines by themselves, but you may also attach a comment to the end of an existing code line. If a logical line is broken into multiple physical lines using the "_" line continuation character, a trailing comment is valid only at the end of the final physical line:
' ----- This is a standalone comment, on a line by itself.
Dim counter As Integer   ' This is a trailing comment.
MsgBox("The counter starts at " & _   ' INVALID COMMENT HERE!
   counter)  ' But this one is valid.
Comments begin with the comment character, the standard single quote character ('). Any text following the comment character is a comment, and is ignored when your code is compiled into a usable application. Any single quote that appears within a literal string is not used as a comment marker.
MsgBox("No 'comments' in this text.")
Comments can also begin with the REM keyword (as in "REMark"), but most programmers use the single-quote variation instead.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Option Statements
A few code examples ago you saw that Visual Basic would supply a default assignment to a variable—at least for value types—if you neglected to include one. In certain cases, Visual Basic will also supply the declaration if you leave it out. In the statement:
brandNewValue = 5
if there is no related Dim statement that defines brandNewValue, Visual Basic will declare the variable on your behalf, assigning it to the Object data type. Don't let this happen to you! You don't know what kind of trouble you will have if you allow such practices in your code. You will quickly find your code filled with mysterious logic bugs, esoteric data issues, recurrent head lice, and so on.
The problem is that Visual Basic will not complain if you mistype the name of your auto-declared variable. Left unchecked, such practices could lead to code such as this:
brandNewValue = 5
MsgBox(brandNewVlaue)
My, my, my, look at that spelling mistake on the second line. What? Visual Basic compiled without any error? And now your message box displays nothing instead of 5? You could avoid such trauma by judicious use of the Option statements included in the Visual Basic language. There are four such statements:
Option Explicit On
This statement forces you to declare all variables using Dim (or a similar statement) before use. It's possible to replace "On" with "Off" in the statement, but don't do it.
Option Strict On
Visual Basic will do some simple data conversions for you when needed. For instance, if you assign a 64-bit Long data value to a 32-bit Integer variable, Visual Basic will normally convert this data to the smaller size for you, complaining only if the data doesn't fit. This type of conversion—a narrowing conversion—is not always safe since the source data will sometimes fail to fit in the destination. (A widening conversion, as with storing Integer data in a Long, always works, since the destination can always hold the source value.) The Option Strict On statement turns off the automatic processing of narrowing conversions. You will be forced to use explicit conversion functions to perform narrowing conversions. This is good, since it forces you to think about the type of data your variables will hold. You can replace "On" with "Off" in this statement, but if I've warned you once, I've warned you twice: don't even try it.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Basic Operators
Visual Basic includes several basic operators that let you do what your code really wants to do: manipulate data. To use them, just dial zero from your phone. No, wait; those operators let you place operator-assisted calls for only $2.73 for the first minute. The Visual Basic operators let you perform mathematical, logical, bitwise, and string management functions, all at no additional cost.
The most basic operator is the assignment operator, represented by the equals sign (=). You've already seen this operator in use in this chapter. Use it to assign some value to a variable (or constant); whatever appears to the right of the operator gets assigned to the reference type or value type variable on the left. The statement:
fiveSquared = 25
assigns a value of 25 to the variable fiveSquared.
Most operators are binary operators—they operate on two distinct values, one to the operator's left and one to the right; the result is a single calculated value. It's as though the calculation is fully replaced by the calculated result. For instance, the addition operation:
seven = 3 + 4
becomes:
seven = 7
before the final application of the assignment (=) operator. A unary operator appears just to the left of its operand. For instance, the unary negation operator turns a positive number into a negative number:
negativeSeven = −7
I'll comment on each operator in detail in . But we'll need a quick summary for now so that we can manipulate data before we get to that chapter. lists the main Visual Basic operators and briefly describes the purpose of each one.
Table : Visual Basic operators
Operator
Description
+
The addition operator adds two numbers together.
+
The unary plus operator retains the sign of a numeric value. It's not very useful until you get into operator overloading, something covered in .
The subtraction operator subtracts the second operand from the first.
The unary negation operator reverses the sign of its associated numeric operand.
*
The multiplication operator multiplies two numeric values together.
/
The division operator divides the first numeric operand by the second, returning the quotient including any decimal remainder.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Functions and Subroutines
Years ago I worked for a software company that sometimes published software developed outside the organization, all for a non-Windows platform. While most of these programs were written in the C language, we also published software written in Pascal, assembly language, and good ol' BASIC. I inherited one such external application written entirely in BASIC, a program that assisted the user in 3D modeling and graphics rendering. It was a complex program, containing about 30,000 lines of source code. The problem was that it was one large block of 30,000 source code lines. No comments, no variable names longer than a few characters, no extra-strength buffered aspirin product. Just thousands of lines of code with flow control statements jumping this way and that. And, of course, it had a bug.
I was able to move past that event in my life without too much therapy, but at the time it was a shock to see code in that condition. And it was so unnecessary, since that flavor of BASIC was a procedural language, just like C and Pascal. Procedural languages allow you to break your code into named blocks of logic, called procedures. These procedures let you take a "divide and conquer" approach to programming; you write procedures that accomplish a specific logical portion of the code within your entire application, and then access these procedures from other procedures.
Visual Basic includes three types of procedures:
Subroutines
These procedures, also called subprocedures, do a bunch of work and then return to the calling procedure. Data can be sent into the subroutine through its argument list, and some values may come back through that same list, but the procedure does not send an official final result back. A subroutine does its work, and once it is complete, the calling code continues on its merry way.
Functions
Functions are just like subroutines, with one additional feature: you can return a single value or object instance from the function as its official result. Usually, the calling code takes this return value into consideration when it completes its own logic.
Properties
When used, properties actually look like variables. You assign and retrieve values to and from properties just like you would for a variable. However, properties include hidden code, often used to validate the data being assigned to the property.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conditions
Sometimes you have to make some choices, and conditional expressions will help you do just that. Visual Basic includes support for conditions, which use data tests to determine which code should be processed next.
The most common conditional statement is the If statement. It is equivalent to English questions in the form "If such-and-such is true, then do so-and-so." For instance, it can handle "If you have $20, then you can buy me dinner," but not "If a train departs Chicago at 45 miles per hour, when will it run out of coal?"
If statements have syntax that spans multiple source code lines:
01  If (hadAHammer = True) Then
02     DoHammer(inTheMorning, allOverThisLand)
03     DoHammer(inTheEvening, allOverThisLand)
04  ElseIf (hadAShovel = True) Then
05     DoShovel(inTheNoontime, allOverThisLand)
06  Else
07     TakeNap(allDayLong, onMySofa)
08  End If
The If statement lets you define branches in your code based on conditions. It is built from three main components:
Conditions
The expression found between the If (or ElseIf) keyword and the Then keyword is the condition. The sample includes two conditions, on lines 01 and 04. Conditions may be simple or complex, but they must always result in a Boolean True or False value. They can include calls to other functions and multiple logical and comparison operators.
If ((PlayersOnTeam(homeTeam) >= 9) And _
      (PlayersOnTeam(visitingTeam) >= 9)) Or _
      (justPracticing = True) Then
   PlayBall(  )
Else
   StadiumLights(turnOff)
End If
The original condition always follows the If keyword. If that conditions fails, you can specify additional conditions following an ElseIf keyword, as on line 04. You may include as many ElseIf clauses as you need. The optional Else condition doesn't let you specify a test expression. Instead, it matches everything not yet caught by the If or ElseIf clauses. Only one Else clause is allowed per If statement.
Branches
Each condition's Then keyword is followed by one or more Visual Basic statements that are processed if the associated condition evaluates to True. All statements up to the next Else
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Loops
Visual Basic includes three major types of loops: For...Next, For Each...Next, and Do...Loop. Just as conditions allow you to break up the sequential monotony of your code through branches, loops add to the usefulness of your code by letting you repeat a specific block of logic a fixed or variable number of times.
The For...Next loop uses a numeric counter that increments from a starting value to an ending value, processing the code within the loop once for each incremented value.
Dim whichMonth As Integer
For whichMonth = 1 To 12
   ProcessMonthlyData(whichMonth)
Next whichMonth
This sample loops 12 times (1 To 12), once for each month. You can specify any starting and ending values you wish; this range can also be specified using variables or functions that return numeric values. Once the starting and ending values are obtained, they are not recalculated each time through the loop, even if a function call is used to obtain one or both limits.
' ----- Month(Today) returns the numeric month
'       for the current date.
For whichMonth = 1 To Month(Today)
   ProcessMonthlyData(whichMonth)
Next whichMonth
Normally, the loop increments by one (1) each time through. You can alter this default by attaching a Step clause to the end of the For statement line:
For countDown = 60 To 0 Step −1
   ...
Next countDown
One additional syntax variation allows you to declare the loop counter variable within the statement itself. Such variables are available only within the loop, and cease to exist once the loop exits.
For whichMonth As Integer = 1 To 12
   ProcessMonthlyData(whichMonth)
Next whichMonth
A variation of the For loop, the For Each...Next loop scans through a set of ordered and related items, from the first item until the last. Arrays and collection objects also work, as does any object that supports the IEnumerable interface (all these topics are covered in ). The syntax is quite similar to the standard For statement:
For Each oneRecord In setOfRecords
   ProcessRecord(oneRecord)
Next oneRecord
Sometimes you want to repeat a block of code as long as a certain condition is true, or only until a condition is true. 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 Your Own Procedures
All logic statements in your code must appear within a procedure, whether in a subroutine, a function, or a property. Although there are thousands of prewritten procedures for you to choose from in the .NET Framework libraries, you can also add your own.
Subroutines begin with a Sub declaration statement and end with an End Sub statement. All of your subroutine's logic appears in between these two mighty jaws.
01  Sub ShowIngredients(ByVal gender As Char)
02     Dim theMessage As String = "Unknown."
03     If (gender = "M"c) Then
04        theMessage = "Snips and snails and puppy dog tails."
05     ElseIf (gender = "F"c) Then
06        theMessage = "Sugar and spice and everything nice."
07     End If
08     MsgBox(theMessage)
09  End Sub
Line 01 shows the subroutine's declaration line in its simplest form; throughout the book, you will find that there are additional keywords that decorate procedure declarations to change their behavior. The statement begins with the Sub keyword (for subroutine), followed by the name of the procedure, ShowIngredients.
The parentheses following this name contain the subroutine's parameters. Parameters allow another block of code that will use this procedure to pass data into the procedure, and optionally receive data back. You can include any number of parameters in the subroutine definition; simply separate them by commas. Each parameter specifies the name as it will be used in the procedure (gender in the sample) and its data type (Char). The arguments are treated as declared variables within the procedure, as is done with gender on lines 03 and 05.
The values supplied by the calling code are known as arguments. All arguments are passed by value or by reference. In the sample code, the argument passed into gender will be passed by value, as specified through the ByVal keyword. The related ByRef keyword indicates an argument to be passed by reference. If you don't include either keyword, ByVal is assumed. This passing method impacts whether changes made to the argument within the local procedure are propagated back to the calling code. However, the ability to update the original data is also influenced by whether the data is a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Other Flow Control Features
The loops and conditional statements available in Visual Basic let you reroute your code based on data. The language includes a few other statements that let you control the action in a more direct manner.
The GoTo statement lets you jump immediately to some other location within the current procedure. The destination of a jump is always a line label, a named line position in the current procedure. All line labels appear at the start of a logical line, and end with a colon.
PromptUser:
   GetValuesFromUser(numerator, denominator)
   If (denominator = 0) Then GoTo PromptUser
   quotient = numerator / denominator
In this sample, the GoTo statement jumps back to the PromptUser label when the code detects invalid data. Processing continues with the line immediately following the PromptUser label. You can't use the same label name twice in the same procedure, although you can reuse label names in different procedures. If you want, include another logic statement on the same line as your label, right after the colon, although your code will be somewhat easier to read if you keep labels on their own lines.
LabelAlone:
   MsgBox("It's all alone.")
LabelAndCode: MsgBox("Together again.")
It's all right to include as many labels in your code as you need, but the GoTo statement is one of those elements of Visual Basic that is monitored closely by pesky international software agencies, such as the International Committee to Keep GoTo Always Gone (ICK-GAG). That group also scans computer books looking for derogatory references to its organization name—not that it would find anything like that in this book. But its core issue is that overuse of GoTo statements can lead to spaghetti code, such as the following:
Dim importantMessage As String = "Do"
GoTo Step2
Step6: importantMessage &= "AG!"
GoTo Step7
Step3: importantMessage &= "wit"
GoTo Step4
Step2: importantMessage &= "wn "
GoTo Step3
Step5: importantMessage &= "CK-G"
GoTo Step6
Step4: importantMessage &= "h I"
GoTo Step5
Step7: MsgBox(importantMessage)
Some people say that such code is hard to read. Others call it job security. No matter what you call it, it does make code very hard to maintain and review. You should probably keep an eye on your use of
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Events and Event Handlers
Content preview·Buy PDF of this chapter|