Friday, July 8, 2011

Methods in the .NET Framework

PadLeft Right-aligns the characters in this string, padding on the left with
spaces or a specified character to a specified total length.
PadRight Left-aligns the characters in this string, padding on the right with
spaces or a specified character to a specified total length.
Remove Deletes the specified number of characters from this string,
beginning at the specified location.
Replace Replaces all occurrences of a substring with a different substring.
Split Splits a string into an array of substrings.
StartsWith Determines whether a specified substring starts the string.
Substring Returns a substring from the current string from the position
indicated.
ToCharArray Copies the characters in this string to a character array.
ToLower Returns a lowercase copy of this string.
ToUpper Returns an uppercase copy of this string.
Trim Either removes spaces or removes all occurrences of a set of
characters specified in a Unicode character array from the
beginning and end of the string.
TrimEnd Either removes spaces or all occurrences of a set of characters specified
in a Unicode character array from the end of the string.
TrimStart Either removes spaces or all occurrences of a set of characters
specified in a Unicode character array from the beginning of
the string

Strings

String variables hold groups of Unicode characters. A string can contain up to
about 2 billion (2 ^ 31) Unicode characters. As you have seen, you now assign a
string to a variable using double quotes:
Dim message as String
message = "Help"
and the simplest way to concatenate (join them together) is to use the &. The older will also work, but can lead to major problems if you leave Option Strict off, so
we do not recommend using a + sign for string concatenation. The older way to
identify string variables (which are occasionally still used for temporary variables)
is to use a dollar sign ($) at the end of the variable name: aStringVariable$.
CAUTION Rather than being base type, strings in VB .NET are instances of the
String class. We offer more on their subtleties in the Chapter 4, but here is a hint
of what you need to know to use VB .NET efficiently: every time you make a
change to a string in VB .NET, a new string must be created. Because this could
cause a big performance penalty whenever a string needs to be repeatedly
changed, VB .NET comes with a StringBuilder class to manipulate strings that
require change (such as picking up data from a buffer and stringing it together
in a variable).
NOTE VB .NET does not support fixed-length strings as did earlier versions of VB.
String Functions
You have access to all the traditional VB6 string functions, such as Left, Right, Mid,
and so on, but note that the versions of these functions that end with $ are now
gone. The most important functions in the String class that can be used to replace
the VB6 string functions are summarized in Table 3-5. (Keep in mind that, if you
have to modify a string repeatedly with Mid, such as in a loop, you should use the
StringBuilder class described in Chapter 4.) Note that some of these methods rely
on arrays, which we cover later in this chapter.
Table 3-5. String Functions in the VB Compatibility Layer
FUNCTION DESCRIPTION
Asc Returns the character code corresponding to the first letter in
a string.
Chr Converts a number to Unicode.
Filter Takes a string array and a string to search for, returns a onedimensional
array containing all the elements that match the
search text.
GetChar Returns a Char representing a character from a specified index
in a string. The index for GetChar begins with 1. Example:
GetChar("Hello", 2) returns a Char containing the character “e.”
InStr Returns the position of the first occurrence of one string
within another.
InStrRev Returns the position of the last occurrence of one string
within another.
Join Lets you build a larger string out of smaller strings.
LCase Converts a string to lowercase.
Left Finds or removes a specified number of characters from the beginning
of a string.
Len Gives the length of a string.
LTrim Removes spaces from the beginning of a string.
Mid Finds or removes characters from a string.
Replace Replaces one or more occurrence of a string inside another.
Right Finds or removes a specified number of characters from the end of
a string.
RTrim Removes spaces from the end of a string.

Conversion between Values

Most programmers thought that earlier versions of VB were way too permissive
when it came to converting between types. This led to the phenomena of “evil
type conversion” where, for example, VB6 allowed you to multiply, say, a string of
numerals by an integer.
The option you have in VB .NET to make type conversion safe is called
Option Strict. You can turn this feature on by using:
Option Strict On
as the first line of code in any program you write. (You can also use the Build tab
of the Projects Properties dialog box.) Once you turn this option on (and you
should!), VB .NET requires you to explicitly make a conversion (sometimes called
a cast) whenever there is the possibility of loss of information (a lossy conversion,
to say it in the jargon). For example, when you convert a Single to an Integer, there
is the possibility of losing information. On the other hand, if there is no potential
of information loss (for instance, from an Integer to a Long or Decimal), VB .NET
automatically makes the conversion. The documentation for VB .NET refers to
these lossless conversions as widening conversions. Table 3–3 lists the permissible
widening conversions for basic types.
What is more, if you have the default of Option Strict on, then you cannot
have lines of code like:
Dim foo As Boolean
foo = 3
Table 3–3. Permissible Widening Conversions for Basic Types
TYPE WIDENS TO
Byte Byte, Short, Integer, Long, Decimal, Single, Double
Short Short, Integer, Long, Decimal, Single, Double
Integer Integer, Long, Decimal, Single, Double
Long Long, Single, Decimal, Double

Working with a Solution

The file named vb_ide_01.vbproj, which is actually written in XML, contains
information about the project, including descriptions of properties. These can
usually be changed by choosing Project|Properties or by right-clicking on the
project name in the Solution Explorer.
Here is what a project file looks like in text form. Notice the constant repetition of
the keyword Assembly. We explain the other important keywords used here,
 Non-Numeric Literals
Non-numeric literals include Boolean, Date, and Char data types. The Boolean
data type represents True or False and takes up four bytes in VB .NET, as opposed
to two bytes in VB6.
Table 3-2. Correspondence between Numeric Types
VB .NET TYPE .NET FRAMEWORK TYPE VB6 TYPE
Byte System.Byte Byte
Boolean System.Boolean Boolean
Decimal System.Decimal NONE
NONE NONE Currency
Double System.Double Double
Short System.Int16 Integer
Integer System.Int32 Long
Long System.Int64 NONE
Single System.Single Single
CAUTION In VB .NET Beta 1, True was +1 (as in other .NET languages). Starting
in Beta 2, it goes back to –1. More precisely, in "logical operations" in VB and in
conversions to numeric types, True will be –1, not 1. However, when a Boolean in
VB .NET is passed out of VB , it is treated as 1 when it is converted to a number in
that language. We think this was the wrong decision, because the point of .NET
is to have as much cross-language compatibility as possible. As long as you use
the built-in constants for True and False, you will be fine. If you use numeric values,
you may run into problems!
Expressions, Operators, and Control Flow
59
The Date data type represents a date and/or a time. As in VB5, you surround a
literal that represents a date and time by two #s, as in #Jan 1, 20001#. If you do not
specify a time, the date literal will be assumed to be that date at midnight.
The Char data type represents a single Unicode character. The Unicode system
allows 65,536 characters, which is enough to encompass all known alphabets. Characters
are usually surrounded by single quotes followed by a C, as in: “H”C, but if
you want to get an actual Unicode character, simply use the Chr built-in function.
For example, Chr(&H2153) is a 1⁄3 in the Unicode charts, although you may not see
it as such on some operating systems when the program runs. Note that if you use
one character within quotes without the “C” suffix, you get a String rather than a
Char and the two are not automatically convertible (more on Option Strict later in
this chapter).
Declaring Variables
The way to declare a variable in VB .NET within a procedure or function is with the
Dim plus As keywords, just as in VB6. You use the equals sign to make the assignment:
Dim foo As String
foo = "bar"
Note that unless you change the defaults for VB .NET, you must declare a variable
before using it. (The optional Option Explicit introduced in VB4 is now the default.)
In VB .NET, you can initialize a variable when you declare it. For example:
Dim salesTax As Decimal = 0.0825D
declares a variable called salesTax and gives it the initial value .0825 of the new
Decimal type. You can also use any valid VB .NET expression to give the initial
assignment. For example:
Dim startAngle As Decimal = Math.PI
gives startAngle the built-in value for the mathematical constant π by using a constant
built into the System.Math class.

Properties Window

The Properties window in VS .NET (also shown in Figure 2-14) is now much more
than the place where you go to set properties of controls. The item you select
determines what the Properties window shows. The combo box at the top of the
Properties window describes the item you are working with. To edit a property,
click in the cell to its right and start typing. The usual Windows editing shortcuts
work within the Properties window.
As you can see in Figure 2-14, the Properties window now lets you set the properties
of the Module1.vb file. You can also use it to set the properties of designers such as
the ones you use for building Web applications or server-side solutions.
ICON DESCRIPTION
Displays a Property Page for the property if one is supplied. (As in VB6,
Property Pages are an aid to setting more complicated properties.)
Gives an alphabetical list of all properties and property values arranged by
category. Categories can be collapsed or expanded at will.
Sorts the properties and events.
Displays the properties for an object. When you are dealing with objects
that have events associated with them, you can see them here as well.
NOTE Later in the book you will see how the IDE deals with designing forms
and how it knows which parts of a file are visual and which parts are not. For
now, you need only know that all VB .NET files end in .vb.
TIP You can create an empty solution without first creating a project by choosing
the Visual Studio Solutions|Blank Solution option from the New Project dialog
box. Using this option is the easiest way to create a solution when you do not want
the solution to have to have the same name as one of the projects.
Chapter 2
26
References and the Reference Window
If you look at the list of files in the Solution Explorer, you can see that there is a
branch of the Solution Explorer tree named References that holds a list of the current
assemblies you can use. (Think of an assembly as being analogous to a DLL.
Chapter 13 has a lot more about assemblies.) Think of the References dialog box
in a VB .NET solution as being analogous to the References dialog box you used to
import COM libraries into your VB6 project.) Visual Studio always includes a reference
to the basic .NET assemblies needed for any project, and they are the ones
currently listed in the Solution Explorer. If you expand the tree by clicking on the
+ icon, you should see something similar to Figure 2-15. Notice that almost all of
the assemblies that Visual Studio is referencing are named System..
Now right-click on the References branch of the Solution Explorer tree and
choose Add Reference. (You can also choose Project|Add Reference.) You will see a
dialog box like the one pictured in Figure 2-16. Notice that you can add three types of
references: .NET, COM, and Projects.
Figure 2-15. Drilling down in the Solution Explorer
NOTE Yes, you can use traditional COM components in your .NET apps and thus
use ActiveX controls, including ones you may have built yourself. This is done
through the magic of “interop”; see Chapter 13. However, just because you can do
something does not necessarily mean that you should do it. Using COM components
in .NET applications adds significant overhead to your application.
The VB .NET IDE: Visual Studio .NET
27
Output Window and Command Window
The Output window (choose View|Other Windows or Ctrl+Alt+O) displays status
messages. When you (try to) build a solution (see the section on this later in this
chapter) this where you see the results of the compilation process, both good
and bad.
The Command window (choose View|Other Windows or Ctrl+Alt+A) is analogous
to VB6’s Immediate window and remains useful when debugging (more on
this later). Unfortunately we think it fair to say that the Command window is
much less useful than the Immediate window was in VB6, mostly because it does
not supply real IntelliSense, nor does it work at design time. (IntelliSense does
work in a very limited way when you use the Command window but only for
menus and macros, and not for objects or while debugging.)
However, the Command window has gained the ability to interact with the
IDE environment. You can actually issue commands like this:
File.AddNewProject
which brings up the New Project dialog box (although we are not sure why anyone
would do this).
The Command window has two modes: Command and Immediate. You switch
back and forth between them by typing either a greater-than sign (>) followed by
Figure 2-16. The Add Reference tabbed dialog box
Chapter 2
28
cmd into the window or typing immed into the window (without the greater-than sign).
You can navigate through the Command window using the following keystrokes

The Clipboard Ring

You now have the ability to collect multiple items in a Clipboard Ring (Office 2000
and Office XP have similar features).Whenever you cut or copy text, it goes into
the Clipboard Ring that is available on the Toolbox. You can see what is in the ring
by clicking the Clipboard Ring tab on the Toolbox. The ring holds the last fifteen
pieces of text that you cut or copied. To use the Clipboard Ring:
• Use Ctrl+Shift+V to paste the current item into the current document.
Repeatedly pressing Ctrl+Shift+V lets you cycle through the Clipboard Ring.
Each time you press Ctrl+Shift+V, the previous entry you pasted from the Clipboard
Ring is replaced by the current item.
Code Fragments
You can store any piece of code for instant reuse in the Toolbox. (Most people use
the General tab for this, but you can easily create your own tab by right-clicking
and choosing Add Tab from the context menu.) Storing code can be incredibly
useful since it is very common to repeatedly use the same code fragment inside
programs, and it is time consuming to constantly retype it. You store code fragments
by highlighting them and dragging them to the Toolbox (see Figure 2-12). The fragments
remain in the Toolbox until you delete them using the context menu. To reuse
code, simply drag a fragment back to the correct insertion point in the Code window,
or select the insertion point first and then double-click on the code fragment.
Figure 2-12. Code stored in the Toolbox
The VB .NET IDE: Visual Studio .NET
23
Task List and TODO, HACK, and UNDONE Comments
Visual Studio now comes with a Task List feature that it inherited from Visual
InterDev and Visual J++. The idea is that you can list in a comment what you need
to do using special keywords right after the comment symbol. The built-in task
comments include TODO, HACK, and UNDONE. These comments will then show up
in the Task List window, which you display by choosing View|Other Windows|Task
List (or Ctrl+Alt+K). An example is shown in Figure 2-13.
Figure 2-13. Task List at work
Chapter 2
24
You can set up a custom keyword for use in the Task List such as “FOR_KEN”
if it is code that Ken needs to look over. (Note that no spaces are allowed in Task
keywords, hence the underscore). To set up a custom keyword for the Task List:
1. Select Tools|Options|Environment|Task List.
2. Enter FOR_KEN for your custom token (this enables the Add button).
3. Select the priority level.
4. Click Add and then OK.
The Solution Explorer
The Solution Explorer window, shown in Figure 2-14, lets you browse the files that
make up your solutions. The default name of the solution is the same as the first
project created in it. As you can see in the Solution Explorer window, we also have
a project named vb_ide_01, which contains a file named Module1.vb.
Figure 2-14. Solution Explorer and Properties windows for File Properties

code editor

The code editor has all the features you might expect in a program editor, such as
cut, paste, search, and replace.2 You access these features via the usual Windows
shortcuts (Ctrl+X for cut, Ctrl+V for paste, and so on). If you like icons, you have
them as well, on the context menu inside the Code window or the Edit menu.
Check out the Edit menu for the keyboard shortcuts or look at the Help topic on
“Editing, shortcut keys” for a full list. The shortcut Ctrl+I activates an incremental
search facility, for example.
You also have the amazingly useful IntelliSense feature, which tells you what
methods are available for a given object or what parameters are needed for a
function, as you can see in Figure 2-9. You usually see IntelliSense at work when
you hit the “.”, which is ubiquitous in accessing functionality in Visual Basic.
2. You can even automatically add line numbers by working with the dialog box you get by
choosing Tools|Option|Text Editor
TIP If you are accustomed to using the incredibly useful Comment Block and
Uncomment Block tools introduced in VB5, they are again available. Only now,
thankfully, these default to being available in the standard toolbars that show up
in the IDE as opposed to being on the Edit toolbar, where they were relegated to
obscurity in VB6.
NOTE Certain options, such as Option Explicit, are now the defaults and do not
show up in your Code window as they did in VB6. (Although we still have a habit
of putting them in to make sure!) See the next chapter for more on these options.
Chapter 2
20
You usually get the global features of the editor by working with the Tools|Options
dialog box and choosing the Text Editor option, as shown in Figure 2-10. This
Options dialog box is quite different from its counterpart in earlier versions of
VB6, so we suggest exploring it carefully. To set tab stops, for instance, click on the
Text Editor option as shown in Figure 2-10. Once you do that, you can either set
tabs on a language-by-language basis or solely for VB. You can also change how the
indentation of the previous line affects the next line from None to Block (where
the cursor aligns the next line with the previous line) to a Smart setting (where the
body of a loop is automatically indented) as good programming style would indicate.
(You can select tabs and apply smart formatting after the fact using Ctrl+K, Ctrl +F
or via the Edit|Advanced|Format Selection option. Note that when you are using
Smart Tabs, selecting a region and pressing Shift+Tab (to manage indents) also
reformats.)
Figure 2-9. IntelliSense at work
Figure 2-10. The Options dialog box
The VB .NET IDE: Visual Studio .NET
21
One neat new feature in the Editor is the ability to “collapse” regions of code
so that all you see is the header. Notice the lines of code in Figure 2-11 with the + signs
next to them. Clicking on one of these would expand the region, as it is called in
VS .NET. Hovering the mouse over the ellipses (the three dots) would show the
collapsed code. The Edit|Outlining submenu controls this feature.
There are a few other nifty features of the VS .NET editor that will be new to
experienced VB programmers, and we take them up next.
Figure 2-11. Collapsed regions in the editor
TIP You can create your own named regions as well by simply mimicking what
you see in Figure 2-11. Place a #Region "NameOfRegion" at the beginning of the
block you want to potentially collapse, and place a # End Region line after it.
TIP The online help topic called “Editing Code and Text” and its various links
are particularly useful for learning how to use the editor in the IDE. There are
quite a few very useful rapid navigation features available, for example.

The basic Visual Studio IDE

TIP Remember that the IDE has context-sensitive help. For example, Figure 2-4
shows you roughly what you will see if you hit F1 when the focus is in the Solution
Explorer. There is also a “Dynamic Help” (use Ctrl+F1) feature that automatically
monitors what you are doing and attempts to put likely help topics into
focus. Figure 2-5 shows the list of dynamic help topics you see when you are
starting to work with a project. The downside to dynamic help is that it is CPU
intensive. Once you get comfortable with the IDE, you might want to turn it off
to improve performance.
Chapter 2
16
The View menu on the main menu bar is always available to bring a specific
window of the IDE into view (and into focus). Note that all windows on the IDE
can be dragged around and actually “free float.” Interestingly enough, these are
not MDI (multiple document interface) child windows that must live inside a
parent window—you can move any window in the IDE outside the main window.
Figure 2-4. Context-sensitive help at work
Figure 2-5. Dynamic help at work
The VB .NET IDE: Visual Studio .NET
17
Another cool feature is that if you dock a window and it completely overlaps
an existing window, you are not as lost as you sometimes were in VB6. The reason
is that you automatically see the hidden windows as tabs. As an example, notice
where the cursor is pointing in Figure 2-6. To reveal one of the hidden windows
simply click and drag on the tab for that window. To recombine windows—for
example, to preserve real estate—simply drag one on top of the other. The use of
tabs in this way is a welcome change from the VB6 IDE, where overzealous
docking occasionally caused the IDE to become practically unusable, forcing you
to tweak the Registry in order to get things back to normal. Also note the use of
tabs in the main window gives you another way to access the IDE Start page.
A Tour of the Main Windows in the IDE
We cover the basic windows in this section and address specialized windows, such as
the ones for debugging, later in this chapter or in subsequent chapters. Before we go
Figure 2-6. Docked windows with tabs
Chapter 2
18
any further, however, we want to remind you that in the VS .NET IDE, as with most
modern Windows applications, you get context menus by right clicking. We strongly
suggest that you do a little clicking to become comfortable with each context menu.
For example, the context menu available in the editor is shown in Figure 2-7.
As you can see, this context menu makes a mixture of editing tools and
debugging tools available.
Next, the various icons on the menu bars have tool tips.1 A few of the icons
have little arrows on them indicating they actually serve as mini menus. For example,
the second item (Add New Item) has a list of the items you can add to a solution,
as you can see in Figure 2-8.
1. It has struck us, from time to time, that the need for tool tips shows that GUIs have their
limitations. We wonder if the next trend in UI design will be to have these things called
words on buttons dispensing with the icons completely??

The VB .NET IDE:

IF YOU ARE ACCUSTOMED TO using an earlier version of VB, then the .NET IDE
(integrated development environment)—Visual Studio .NET—will look somewhat
familiar. The concept of a rapid application development (RAD) tool with
controls that you to drag onto forms is certainly still there, and pressing F5 will
still run your program, but much has changed and mostly for the better. For
example, the horrid Menu Editor that essentially has been unchanged since VB1
has been replaced by an in-place menu editing system that is a dream to use (see
Chapter 8).
Also, VB .NET, unlike earlier versions of VB, can build many kinds of applications
other than just GUI-intensive ones. For example, you can build Web-based applications,
server-side applications, and even console-based (in what looks like an
old-fashioned DOS window) applications. Moreover, there is finally a unified
development environment for all of the “Visual” languages from Microsoft. The
days when there were different IDEs for VC++, VJ++, Visual InterDev, Visual Basic,
and DevStudio are gone. (Actually, Visual Interdev is now subsumed into VS
.NET.) Another nice feature of the new IDE is the customization possible via an
enhanced extensibility model. VS .NET can be set up to look much like the IDE
from VB6, or any of the other IDEs, if you like those better.
The purpose of this chapter is to give you an overview of the IDE, not to bore
you to death with details. The best way to get comfortable with the IDE is to use it,
working with the online help as needed. We suggest skimming this chapter and
returning to it for reference as needed. Also, note that the parts of the IDE that are
connected with specific programming elements such as GUI design are covered
in greater depth in later chapters.
Getting Started
Users of earlier versions of VB (like us, for example) will probably want the IDE to
resemble and work like the traditional VB6 IDE as much as possible. You can do
this by selecting Visual Basic Developer from the Profile dropdown list on the My
Profile link on the VS home page, as shown in Figure 2-1.
Notice that you can also customize the keyboard and the window layout for the
IDE, and that you can save these in different profiles. You can always change your
profile by going to Help|Show Start Page and then choosing My Profile.
In VB .NET, every project is part of what Microsoft calls a solution. You cannot
do anything in the VB .NET IDE without your code being part of a specific solution.
Think of a solution as the container that holds all information needed to compile
your code into a usable form. This means a solution will contain one or more
projects; various associated files such as images, resource files, metadata (data
Figure 2-1. Visual Studio home page
The VB .NET IDE: Visual Studio .NET
13
that describes the data in your program), XML documentation; and just about
anything else you can think of. (People coming from VB5 or 6 should think of a
solution as analogous to a program group.) Although solutions are cumbersome
at first, and in all honesty are always cumbersome for small projects, once you get
used to using solutions, enterprise development will be much easier. This is
because with a solution-based approach you can more easily dictate which files
you need to deploy in order to solve a specific problem.
Creating a New Solution
The first step in creating a new solution is to select File|New. At this point you have
two choices: create a New Project or a Blank Solution. Note that even when you
choose New Project, you get a solution. The difference is that the VS .NET IDE
builds a bunch of bookkeeping files and adds them to the solution container if
you choose a specific type of project. (The kind of files you get depends on what
kind of project you choose.)
Most of the time you will choose New Project. When you do so, you will see a
dialog box like the one shown in Figure 2-2, where we scrolled roughly halfway
through the list of possible projects. This dialog box shows the many different
kinds of projects VB .NET can build. (As we write this, there are ten types.) These
project templates work in much the same way as templates did in VB6. For
example, they often contain skeleton code but always contain bookkeeping information
such as which files are part of the solution.

Thursday, July 7, 2011

Coding Work

 Page=3,4,5
What we mean is that instead of having to write code that worked more or less
like this:
Select Case kindOfEmployee
Case Secretary
RaiseSalary 5%
Case Manager
RaiseSalary 10%
Case Programmer
RaiseSalary 15%
Case Architect
RaiseSalary 20%
'etc
End Select
which was a pain to maintain because whenever you added a new type of employee
you had to change all the corresponding Select Case statements, the compiler
could do the work for you. This was finally possible because starting with VB5,
you could use the magic of interface polymorphism (see Chapter 5 for more on
this) and write code like this:
For Each employee in Employees
employee.RaiseSalary
Next
and know that the compiler would look inside your objects to find the right
RaiseSalary method.
Classes let you create VB apps in a much more efficient and maintainable
manner. Whether you stick with VB5 or shift to VB .NET we cannot imagine
writing a serious VB app without them.
The .NET Mentality Shift
What does all of this have to do with .NET? Quite a lot. You see, .NET is going to
change the way you design your applications as much as the introduction of
classes to VB changed the best way to build your VB5 or 6 applications. And just as
we VB programmers suffered through the change from the classless to classenabled
incarnations of VB, so will we feel some pain in the transition to .NET!4
4. There is a conversion tool supplied with VB .NET, but we guarantee it will not ease the pain much.
Any serious program will not convert well—you’re better off redoing them from scratch.
Chapter 1
4
With that in mind, let us look at some of the things to watch out for—or take
advantage of—when switching from VB6 to VB .NET.
The Common Language Runtime
Visual Basic has always used a runtime, so it may seem strange to say that the
biggest change to VB that comes with .NET is the change to a Common Language
Runtime (CLR) shared by all .NET languages. The reason is that while on the surface
the CLR is a runtime library just like the C Runtime library, MSVCRTXX.DLL,
or the VB Runtime library, MSVBVMXX.DLL, it is much larger and has greater
functionality. Because of its richness, writing programs that take full advantage of
the CLR often seems like you are writing for a whole new operating system API.5
Since all languages that are .NET-compliant use the same CLR, there is no
need for a language-specific runtime. What is more, code that is CLR can be written
in any language and still be used equally well by all .NET CLR-compliant languages.6
Your VB code can be used by C# programmers and vice versa with no extra work.
Next, there is a common file format for .NET executable code, called Microsoft
Intermediate Language (MSIL, or just IL). MSIL is a semicompiled language that
gets compiled into native code by the .NET runtime at execution time. This is a
vast extension of what existed in all versions of VB prior to version 5. VB apps used
to be compiled to p-code (or pseudo code, a machine language for a hypothetical
machine), which was an intermediate representation of the final executable code.
The various VB runtime engines, interpreted the p-code when a user ran the
program. People always complained that VB was too slow because of this,7 and
therefore, constantly begged Microsoft to add native compilation to VB. This
happened starting in version 5, when you had a choice of p-code (small) or
native code (bigger but presumably faster). The key point is that .NET languages
combine the best features of a p-code language with the best features of compiled
languages. By having all languages write to MSIL, a kind of p-code, and then
compile the resulting MSIL to native code, it makes it relatively easy to have
cross-language compatibility. But by ultimately generating native code you still
get good performance.
5. Dan Appleman, the wizard of the VB API, intends to write a book called something like The VB
.NET Programmers Guide to Avoiding the Windows API. The .NET Framework is so fullfeatured
that you almost never need the API.
6. Thus, the main difference between .NET and Java is that with .NET you can use any language,
as long as you write it for the CLR; with Java, you can write for any platform (theoretically at
least—in practice there are some problems) as long as you write in Java. We think .NET will be
successful precisely because it leverages existing language skills.
7. Actually, this was not the bottleneck in a lot of cases. People can only click so fast and
compiled code was irrelevant in most UI situations.
Introduction
5
Completely Object Oriented
The object-oriented features in VB5 and VB6 were (to be polite) somewhat limited.
One key issue was that these versions of VB could not automatically initialize the
data inside a class when creating an instance of a class. This led to classes being
created in an indeterminate (potentially buggy) state and required the programmer
to exercise extra care when using objects. To resolve this, VB .NET adds an important
feature called parameterized constructors (see Chapter 4).
Another problem was the lack of true inheritance. (We cover inheritance in
Chapter 5.8) Inheritance is a form of code reuse where you use certain objects that
are really more specialized versions of existing objects. Inheritance is thus the
perfect tool when building something like a better textbox based on an existing
textbox. In VB5 and 6 you did not have inheritance, so you had to rely on a fairly
cumbersome wizard to help make the process of building a better textbox tolerable.
As another example of when inheritance should be used is if you want to
build a special-purpose collection class. In VB5 or 6, if you wanted to build one
that held only strings, you had to add a private instance field that you used for
the delegation process:
Private mCollection As Collection 'for delegation
Then you had to have Initialize and Terminate events to set up and reclaim the
memory used for the private collection to which you delegated the work. Next,
you needed to write the delegation code for the various members of the specialized
collection that you wanted to expose to the outside world. For example:
Sub Add(Item As String)
mCollection.Add Item
End Sub
This code shows delegation at work; we delegated the Add method to the private
collection that we used as an instance field.
The sticky part came when you wanted a For-Each. To do this you had to add
the following code to the class module:
Public Function NewEnum As IUnknown
Set NewEnum = mCollection.[_NewEnum]
End Function
and then you needed to set the Procedure ID for this code to be –4!
8. Inheritance is useful , but you should know that this is not the be-all, end-all of object-oriented
programming, as some people would have you believe. It is a major improvement in VB .NET
but not the major improvement.

Introduction

 Page=1 & 2
WE HOPE THIS BOOK will be useful to experienced programmers of all languages,
but this introduction is primarily aimed at Visual Basic programmers. Other
programmers can jump to Chapter 2, to begin delving into an incredibly rich
integrated development environment (IDE) backed by the first modern fully
object-oriented language in the BASIC1 family. Programmers accustomed to
Visual Basic for Windows may need some convincing that all the work they face
in moving to VB .NET is worth it. Hence this chapter.
Visual Basic Then and Now
Visual Basic for Windows is a little over ten years old. It debuted on March 20, 1991,
at a show called “Windows World,” although its roots go back to a tool called Ruby
that Alan Cooper developed in 1988.2
There is no question that Visual Basic caused a stir. Our favorite quotes came
from Steve Gibson, who wrote in InfoWorld that Visual Basic was a “stunning new
miracle” and would “dramatically change the way people feel about and use
Microsoft Windows.” Charles Petzold, author of one of the standard books on
Windows programming in C, was quoted in the New York Times as saying: “For those
of us who make our living explaining the complexities of Windows programming to
programmers, Visual Basic poses a real threat to our livelihood.” (Petzold’s comments
are ironic, considering the millions of VB books sold since that fateful day
in 1991.) But another quote made at Visual Basic’s debut by Stewart Alsop is more
telling: Alsop described Visual Basic as “the perfect programming environment
for the 1990s.”
But we do not live in the 1990s anymore, so it should come as no surprise that
Visual Basic .NET is as different from Visual Basic for Windows as Visual Basic for
Windows Version 1 was from its predecessor QuickBasic. While we certainly feel
there is a lot of knowledge you can carry over from your Visual Basic for Windows
programming experience, there are as many changes in programming for the
1. Read BASIC as meaning “very readable-with no ugly braces.…”
2. Its code name, “Thunder,” appeared on one of the rarest T-shirts around—it says “Thunder
unlocks Windows” with a lightning bolt image. You may also see a cool screen saver that looks
like the shirt.
Chapter 1
2
.NET platform3 using Visual Basic.NET (or VB .NET for short) as there were in
moving from QuickBasic for DOS to VB1 for Windows.
The Versions of Visual Basic
The first two versions of Visual Basic for Windows were quite good for building
prototypes and demo applications—but not much else. Both versions tied excellent
IDEs with relatively easy languages to learn. The languages themselves had relatively
small feature sets. When VB 3 was released with a way to access databases
that required learning a new programming model, the first reaction of many
people was, “Oh great, they’ve messed up VB!” With the benefit of hindsight, the
database features added to VB3 were necessary for it to grow beyond the toy stage
into a serious tool. With VB4 came a limited ability to create objects and hence a
very limited form of object-oriented programming. With VB5 and VB6 came more
features from object-oriented programming, and it now had the ability to build
controls and to use interfaces. But the structure was getting pretty rickety since
the object-oriented features were bolted on to a substructure that lacked support
for it. For example, there was no way to guarantee that objects were created correctly
in VB—you had to use a convention instead of the constructor approach used by
practically every other object-oriented language. (See Chapter 4 for more on what
a constructor does.) Ultimately the designers of VB saw that, if they were going to
have a VB-ish tool for their new .NET platform, more changes were needed since,
for example, the .NET Framework depends on having full object orientation.
We feel that the hardest part of dealing with the various changes in VB over
the years is not so much in that the IDE changed a little or a lot, or that there were
a few new keywords to learn, the pain was in having to change the way that you
thought about your VB programs. In particular, to take full advantage of VB5 and
VB6, you had to begin to move from an object-based language with an extremely
limited ability to create your own objects to more of an object-oriented language
where, for example, interfaces was a vital part of the toolset. The trouble really
was that many VB programmers who grew up with the product had never programmed
using the principles of object-oriented programming before. When
classes were introduced in VB, most VB developers had no idea what a class really
was—never mind why they would ever want to use one.
Still, even with the limited object-oriented features available to you in VB5
and 6, when you learned how to use them they made programming large projects
easier. For example, you could build reusable objects like controls, or on a more
prosaic level, you could do neat things to help make maintaining your programs
easier. You could also banish the Select Case statement from maintenance hell.
3. Microsoft takes the word platform seriously. It even calls Windows a platform.

Acknowledgments

ONEOF THE BEST PARTS of writing a book is when the author gets to thank those who
have helped him or her, for rarely (and certainly not in this case) is a book solely
the product of the names featured so prominently on the cover. First and foremost, I
have to thank my friends and colleagues at Apress, but especially Grace Wong,
whose efforts to get this book out under quite stressful conditions was nothing
short of amazing! I would also like to thank Steve Wilent, Tracy Brown Collins,
Susan Glinert Stevens, Valerie Haynes Perry for all their efforts on my behalf.
Next, Ken Getz did an amazingly thorough job of reviewing this book under terribly
tight constraints. He caught dozens of obscurities and helped me avoid dozens of
false steps (any errors that remain are solely my responsibility!). Karen Watterson
and Tim Walton made comments that were very useful as well. Rob Macdonald,
Carsten Thomsen, and Bill Vaughn all helped me to understand how ADO .NET
relates to classic ADO. Thanks also go to my friend Dan Appleman—suffice it to say
that not only have I learned an immense amount about every version of Visual
Basic from him, but his general guidance on so many things have helped me over
many difficult spots during these stressful times. While my friend Jonathan Morrison
had to step away from this project before it could be completed, his insights into
VB were very helpful as I worked to finish this book.
Finally, thanks to all my family and friends who put up with my strange ways
and my occasionally short temper for lo so many months.
Gary Cornell
Berkeley, CA
September 2001
About This Book
THIS BOOK IS ACOMPREHENSIVE, hands-on guide to the Visual Basic .NET programming
language addressed to readers with some programming background. No background
in Visual Basic is required, however.
While I show you the syntax of VB .NET, this book is not designed to teach you
syntax. I have taken this approach because trying to force VB .NET into the framework
of older versions of VB is ultimately self-defeating—you cannot take advantage of
its power if you continue to think within an older paradigm.
First off, I have tried to give you a complete treatment of object-oriented
programming in the context of the VB .NET language. I feel pretty strongly that
without a firm foundation here, it is impossible to take full advantage of the power
that VB .NET can bring to you.
Also, I have tried to cover at the least the fundamentals of every technique that a
professional VB .NET developer will need to master. This includes topics like multithreading,
which are too often skimped on in most books. This does not mean that
I cover all the possible (or even the majority of) applications of VB .NET to the .NET
platform; that would take a book two or three times the size of this one. This is a book
about the techniques you need to master, not the applications themselves. (I have
tried to make most of the examples realistic, avoiding toy code as much as possible.)
Finally, since most people reading this book will have programmed with some
version of Visual Basic before, I have also tried to be as clear about the differences
between VB .NET and earlier versions of VB as I could. However, I want to stress
that this book does not assume any knowledge of earlier versions of VB, just some
programming experience.
How This Book Is Organized
Chapter 1, “Introduction,” explains what is so different about VB .NET. Experienced
VB programmers will benefit from reading this chapter.
Chapter 2, “The VB .NET IDE: Visual Studio .NET,” introduces you to the Visual
Studio .NET Integrated Development Environment (IDE).
Chapter 3, “Expressions, Operators, and Control Flow,” covers what I like to call
the “vocabulary” of VB .NET. This is the basic syntax for code including variables,
loops, and operators.
Chapter 4, “Classes and Objects (with a Very Short Introduction to Object-Oriented
Programming),” is the first of the core object-oriented programming chapters. It
shows you how to construct objects and use them.
Chapter 5, “Inheritance and Interfaces,” covers the other key parts of object-oriented
programming in VB .NET: inheritance and interfaces. This chapter also contains an
introduction to the useful .NET collection classes which allow you to efficiently
manage data inside a program.
Chapter 6, “Event Handling and Delegates,” takes up events and the new .NET
notion of a delegate. Event-driven programming is still the key to good user interface
design, and .NET depends on it just as much as Windows did.
Chapter 7, “Error Handling the VB .NET Way: Living with Exceptions,” covers
exceptions, the modern way of dealing with errors that lets you banish the archaic
On Error GoTo syntax that has plagued VB since its start.
Chapter 8, “Windows Forms, Drawing, and Printing,,” takes up building Windows
user interfaces, graphics and printing. Although the browser is obviously becoming
more important as a delivery platform, traditional Windows-based clients aren’t going
away, and this chapter gives you a firm foundation to build them under .NET.
Chapter 9, “Input/Output,” presents I/O, with a complete treatment of streams,
which are at the root of .NET’s way of handling I/O.
Chapter 10, “Multithreading,” is a concise treatment of the fundamentals of multithreading.
Multithreading is an amazingly powerful technique of programming
that is nonetheless fraught with peril. I hope this chapter does not just teach you
enough “to be dangerous,” but rather, enough so that you can use this powerful
technique safely and effectively in your programs.
Chapter 11, “A Brief Introduction to Database Access with VB .NET,” and Chapter 12,
“A Brief Overview of ASP .NET,” are very brief introductions to two of the most
important applications of .NET: ASP .NET and ADO .NET. Please note these chapters
are designed to give you just a taste, and you will have to look at more detailed
books to learn how to use ASP .NET or ADO .NET in production-level code.
Chapter 13, “.NET Assemblies, Deployment, and COM Interop,” is a brief introduction
to what goes on under the hood in .NET that includes a look the idea of
assemblies and COM Interop. While I have tried to give you a flavor of these
important topics, you will also need to consult a more advanced book to learn
more about the topics.
Contacting Me
I would love to hear about your experiences with this book, suggestions for
improvements, and any errata you may find. (The current list of errata may be found
at the Apress Web site at www.apress.com). You can contact me at gary@thecornells.com.
Gary Cornell
Berkeley, CA

Contents

Dedication............................................................................................................iii
Acknowledgments............................................................................................ xiii
About This Book .............................................................................................. xv
Chapter 1 Introduction ........................................................................ 1
Visual Basic Then and Now .............................................................................. 1
The Versions of Visual Basic ........................................................................ 2
The .NET Mentality Shift ................................................................................ 3
The Common Language Runtime ...................................................................... 4
Completely Object Oriented ............................................................................... 5
Automatic Garbage Collection: Fewer Memory Leaks ..................................... 6
Structured Exception Handling ..................................................................... 6
True Multithreading ........................................................................................... 6
Why You Will Need To Learn a Whole Lot of New Concepts
to Use VB .NET ............................................................................................... 7
Should You Use C# and Not Bother with VB .NET? ................................ 9
Chapter 2 The VB .NET IDE: Visual Studio .NET ........... 11
Getting Started .................................................................................................. 12
Creating a New Solution ................................................................................... 13
A Tour of the Main Windows in the IDE .................................................. 17
The Editor ........................................................................................................... 19
The Solution Explorer ........................................................................................ 24
Properties Window ............................................................................................ 25
References and the Reference Window ........................................................... 26
Output Window and Command Window ........................................................ 27
Working with a Solution ................................................................................ 28
Adding Projects to a Solution ............................................................................ 33
Compiling ............................................................................................................... 34
Multiple Compilations ...................................................................................... 36
Build Options ..................................................................................................... 38
Debug vs. Release Versions ............................................................................... 39
Output Files ........................................................................................................ 40
Contents
vi
Debugging in VB .NET ........................................................................................40
New Debugger Features .....................................................................................41
Chapter 3 Expressions, Operators,
and Control Flow .............................................................47
Console Applications ........................................................................................48
Statements in VB .NET ......................................................................................51
Comments ..................................................................................................................52
Variables and Variable Assignments .........................................................52
Literals and Their Associated Data Types ............................................54
Non-Numeric Literals ........................................................................................58
Declaring Variables ..........................................................................................59
Conversion between Values of Different Types ...............................................61
Strings ....................................................................................................................64
String Functions .................................................................................................65
Formatting Data .................................................................................................68
Arithmetic Operators ........................................................................................69
Parentheses and Precedence .............................................................................72
Math Functions and Math Constants ...............................................................73
Constants ................................................................................................................75
Repeating Operations—Loops ...........................................................................75
Determinate Loops .............................................................................................75
Indeterminate Loops ..........................................................................................77
Conditionals—Making Decisions ....................................................................79
Scoping Changes ................................................................................................80
Short Circuiting ..................................................................................................81
Select Case ...........................................................................................................81
The GoTo ..................................................................................................................82
The Logical Operators on the Bit Level ................................................83
Arrays ......................................................................................................................84
The For-Each Construct ....................................................................................86
Arrays with More than One Dimension ............................................................87
Procedures: User-Defined Functions and Subs .....................................87
Functions ............................................................................................................88
Sub Procedures ...................................................................................................90
Using Arrays with Functions and Procedures ..................................................92
Procedures with a Variable or Optional Number of Arguments ....................93
Recursion ................................................................................................................94
Contents
vii
Chapter 4 Classes and Objects (with a Short
Introduction to Object-Oriented
Programming) ...................................................................... 97
Introduction to OOP ......................................................................................... 98
Classes As (Smart) User-Defined Types ........................................................... 99
The Vocabulary of OOP ................................................................................... 101
The Relationships between Classes in Your Programs ................................. 101
How to Objectify Your Programs ............................................................... 107
What about Individual Objects? ............................................................... 109
Advantages to OOP ............................................................................................ 110
Creating Object Instances in VB .NET .................................................. 111
More on Constructors: Parameterized Constructors ................................... 114
Example: The String Class .............................................................................. 115
Example: The StringBuilder Class .................................................................. 115
Namespaces ........................................................................................................... 120
Imports ............................................................................................................. 120
Help and the (Vast) .NET Framework ...................................................... 124
Example: The Framework Collection Classes ............................................... 127
More on Object Variables ............................................................................ 134
Is and Nothing .................................................................................................. 136
TypeName and TypeOf ......................................................................................... 137
Subtleties of Passing Object Variables by Value ............................................ 138
Building Your Own Classes .......................................................................... 140
Overloading Class Members ........................................................................... 144
More on Constructors ..................................................................................... 147
More on Properties .......................................................................................... 148
Scope of Variables ............................................................................................ 150
Nested Classes .................................................................................................. 152
Shared Data and Shared Members Inside Classes .............................. 155
Shared Members .............................................................................................. 157
The Object Life Cycle ................................................................................... 158
Object Death .................................................................................................... 160
Value Types ......................................................................................................... 161
Enums ............................................................................................................... 163
Structure Types ................................................................................................ 165
Namespaces for Classes You Create ......................................................... 168
The Class View Window ................................................................................... 169
Debugging Object-Based Programs ............................................................. 170
Summary ................................................................................................................. 175
Contents
viii
Chapter 5 Inheritance and Interfaces .................................177
Inheritance Basics ..........................................................................................178
Getting Started with Inheritance .....................................................................180
Overriding Properties and Methods ...............................................................184
Abstract Base Classes .......................................................................................195
Object: The Ultimate Base Class ..............................................................201
The Most Useful Members of Object ..............................................................202
The Fragile Base Class Problem: Versioning ......................................209
Overview of Interfaces .................................................................................215
Mechanics of Implementing an Interface ......................................................217
When to Use Interfaces, When To Use Inheritance? .........................222
Important Interfaces in the .NET Framework ......................................222
ICloneable .........................................................................................................223
IDisposable .......................................................................................................225
Collections .........................................................................................................225
For Each and IEnumerable ..............................................................................226
Chapter 6 Event Handling and Delegates ............................237
Event Handling from an OOP Point of View ..........................................237
What Goes into the Functions Called by Events? ..........................................239
Basic Event Raising ........................................................................................241
Hooking Up the Listener Objects to Event Source Objects ..........................243
Building Your Own Event Classes ...................................................................247
Dynamic Event Handling ................................................................................249
Handling Events in an Inheritance Chain ......................................................253
Delegates ..............................................................................................................254
Building Up a Delegate ....................................................................................255
A More Realistic Example: Special Sorting .....................................................257
Delegates and Events .......................................................................................264
Chapter 7 Error Handling the VB .NET Way:
Living with Exceptions ...........................................265
Error Checking vs. Exception Handling .................................................266
First Steps in Exception Handling ...................................................................267
Analyzing the Exception ..................................................................................269
Multiple Catch Clauses ....................................................................................269
Throwing Exceptions ........................................................................................272
Exceptions in the Food Chain .........................................................................275
And Finally…Finally Blocks .........................................................................277
Some Tips for Using Exceptions ................................................................278
Contents
ix
Chapter 8 Windows Forms, Drawing,
and Printing....................................................................... 279
First, Some History ....................................................................................... 280
Form Designer Basics ..................................................................................... 281
Keeping Things in Proportion: The Anchor and Dock Properties ............... 284
The Tab Order Menu ....................................................................................... 287
Returning to a Simple Program ................................................................. 287
More Form Properties ..................................................................................... 292
Menu Controls and the New Visual Studio Menu Editor ................. 294
Context Menus ................................................................................................. 297
MDI Forms ....................................................................................................... 298
ColorDialog ...................................................................................................... 301
FontDialog ........................................................................................................ 302
FileDialogs ........................................................................................................ 302
Adding Controls at Run Time ......................................................................... 303
Form Inheritance: AKA Visual Inheritance ......................................... 305
Building Custom Controls through Control Inheritance ............... 306
Overriding an Event ......................................................................................... 306
The Inheritance Chains in the
System.Windows.Forms Assembly .......................................................... 313
Basic Control Class Functionality .................................................................. 316
Graphics: Using GDI+ ..................................................................................... 318
Simple Drawing ............................................................................................... 320
Drawing Text .................................................................................................... 321
Printing ............................................................................................................... 325
Chapter 9 Input/Output .................................................................... 333
Directories and Files ................................................................................... 334
The Path Class .................................................................................................. 335
The Directory Class .......................................................................................... 336
The File Class ................................................................................................... 338
The DirectoryInfo and FileInfo Classes .............................................. 340
Working Recursively through a Directory Tree ............................................. 341
The Most Useful Members of the FileSystemInfo, FileInfo,
and DirectoryInfo Classes ...................................................................... 344
Streams ................................................................................................................. 347
Writing to Files: File Streams .......................................................................... 350
Getting Binary Data into and out of Streams:
BinaryReader and BinaryWriter ................................................................ 355
TextReader, TextWriter, and Their Derived Classes ....................................... 358
Object Streams: Persisting Objects ................................................................ 361
Simple Serialization ......................................................................................... 362
Contents
x
Simple Deserialization .....................................................................................364
Network Streams ..............................................................................................370
Writing a File System Monitor ..................................................................375
Going Further with File Monitoring ...............................................................378
Chapter 10 Multithreading ................................................................379
Getting Started with Multithreading .....................................................380
The Mechanics of Thread Creation ................................................................383
Join .....................................................................................................................388
Thread Names, CurrentThread, and ThreadState .........................................389
The Threads Window .......................................................................................390
Putting a Thread to Sleep .................................................................................391
Ending or Interrupting a Thread .....................................................................392
A More Serious Example: Screen Scraping Redux .........................................394
The Big Danger: Shared Data ......................................................................397
The Solution: Synchronization ........................................................................401
More on SyncLock and the Monitor Class .....................................................403
Deadlock: the Danger of Synchronization .....................................................404
Sharing Data as It Is Produced ........................................................................410
Multithreading a GUI Program ....................................................................415
Chapter 11 A Brief Introduction to Database Access
with VB .NET .....................................................................423
Why ADO .NET Is Not ADO++ ...........................................................................423
Disconnected Data Sets: The New Way to Use Databases ................424
The Classes in System.Data.DLL ................................................................425
System.Data.OleDb ..........................................................................................425
System.Data.SqlClient .....................................................................................429
Calling a Stored Procedure .........................................................................430
A More Complete VB .NET Database Application .................................431
Chapter 12 A Brief Overview of ASP .NET ............................443
Some History .......................................................................................................443
A Simple ASP .NET Web Application .........................................................444
What Gets Sent to the Client? ..........................................................................448
The Web.config File ..........................................................................................451
A Simple Web Service ......................................................................................455
Client-Side Use of a Web Service ....................................................................458
Contents
xi
Chapter 13 .NET Assemblies, Deployment,
and COM Interop............................................................... 463
How COM Works .................................................................................................... 464
.NET Assemblies ................................................................................................ 465
The Manifest .................................................................................................... 467
Drilling Down into a Manifest ........................................................................ 469
Shared Assemblies and the GAC ................................................................. 471
Adding and Removing Assemblies from the GAC ......................................... 473
Strong Names = Shared Names ...................................................................... 473
Generating a Key Pair ...................................................................................... 474
Signing an Assembly ........................................................................................ 476
COM Interoperability and Native DLL Function Calls ................... 476
DLL Function Calls .......................................................................................... 477

Programming VB.NET

Programming VB.NET: A Guide for Experienced Programmers
Copyright ©2002 by Gary Cornell
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any
means, electronic or mechanical, including photocopying, recording, or by any information
storage or retrieval system, without the prior written permission of the copyright owner and the
publisher.
ISBN (pbk): 1-893115-99-2
Printed and bound in the United States of America 12345678910
Trademarked names may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, we use the names only in an editorial fashion and to the
benefit of the trademark owner, with no intention of infringement of the trademark.
Editorial Directors: Dan Appleman, Gary Cornell, Jason Gilmore, Karen Watterson
Technical Reviewers: Ken Getz, Tim Walton
Managing Editor and Production Editor: Grace Wong
Copy Editors: Steve Wilent, Tracy Brown Collins
Compositor: Susan Glinert Stevens
Artist: Allan Rasmussen
Indexer: Valerie Haynes Perry
Cover Designer: Karl Miyajima
Marketing Manager: Stephanie Rodriguez
Distributed to the book trade in the United States by Springer-Verlag New York, Inc.,175 Fifth
Avenue, New York, NY, 10010
and outside the United States by Springer-Verlag GmbH & Co. KG, Tiergartenstr. 17, 69112
Heidelberg, Germany
In the United States, phone 1-800-SPRINGER, email orders@springer-ny.com, or visit
http://www.springer-ny.com.
Outside the United States, fax +49 6221 345229, email orders@springer.de, or visit
http://www.springer.de.
For information on translations, please contact Apress directly at 901 Grayson Street, Suite 204,
Berkeley, CA 94710.
Phone 510-549-5930, fax: 510-549-5939, email info@apress.com, or visit http://www.apress.com.
The information in this book is distributed on an “as is” basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author nor Apress shall
have any liability to any person or entity with respect to any loss or damage caused or alleged to
be caused directly or indirectly by the information contained in this work.
The source code for this book is available to readers at http://www.apress.com in the Downloads
section.
Dedication
To the people at Apress: the best group of people I can ever imagine working with.
Contents at a Glance
Dedication .............................................................................................................. iii
Contents ....................................................................................................................v
Acknowledgments ................................................................................................. viii
About This Book......................................................................................................ix
Chapter 1 Introduction.....................................................................................1
Chapter 2 The VB .NET IDE: Visual Studio .NET ..............................11
Chapter 3 Expressions, Operators, and Control Flow ...................47
Chapter 4 Classes and Objects (with a Short Introduction
to Object-Oriented Programming) .......................................97
Chapter 5 Inheritance and Interfaces................................................. 177
Chapter 6 Event Handling and Delegates ...........................................237
Chapter 7 Error Handling the VB .NET Way:
Living with Exceptions .........................................................265
Chapter 8 Windows Forms, Drawing, and Printing ..........................279
Chapter 9 Input/Output ..............................................................................333
Chapter 10 Multithreading ..........................................................................379
Chapter 11 A Brief Introduction to Database Access
with VB .NET ..............................................................................423
Chapter 12 A Brief Overview of ASP .NET ...........................................443
Chapter 13 .NET Assemblies, Deployment, and COM Interop .........463

Wednesday, July 6, 2011

hardware requirements

hat are the hardware requirements of Windows operating systems?
This section outlines the typical hardware requirements for the Windows operating systems. You should be aware that these are recommended figures, and in actual practice more memory and disk space is recommended if you intend to run applications and programs in addition to the base Windows operating system. System requirements for Windows 95
386DX or higher
4MB memory or higher [8MB recommended]
35-40MB disk space
3.5" floppy drive or CD-ROM
VGA or higher resolution graphics card
System requirements for Windows 98
486DX/66MHz or higher
16MB memory or higher
195MB disk space
CD-ROM
VGA or higher resolution graphics card
System requirements for Windows NT Workstation 4.0
16 MB RAM Recommended
486/25MHz or higher processor
110 MB available hard-disk space
VGA, Super VGA, or video graphics adapter
CD-ROM drive.
System requirements for Windows 2000 Professional
Not known at time of printing. Software still in beta.

What are the general features of Windows operating systems?
This section outlines some of the more general features found in the Windows 95/98 and Windows NT Workstation 4.0 operating systems.
Easy installation
Windows can be installed from floppy disk, CDROM, or via a network. Windows uses an installation wizard, a graphical program designed to make installation of the operating system simpler and friendlier.
Previously, when installing MSDOS or Windows 3.1 operating systems, additional programs need to be run after installation to add support for devices like CD-ROM's or sound cards. The Windows wizard takes care of this, automatically searching the computer for hardware devices like printers, network cards, CD-ROM drives, sound cards and modems then installs the software for these at installation time. This means Windows is easier to install and configure than previous operating systems.
As the Windows installation wizard detects what the computer hardware is, it modifies the display screens accordingly. Using a set of easy to follow menus and dialog boxes, it guides the installer through the installation process. When the installation wizard is finished, it prompts the installer to reboot the computer. At this stage, the computer has been fully installed with the operating system and will be ready to use after the reboot. It takes approximately 20-30 minutes to install Windows from CD-ROM.

Graphical Interface
Windows offers an improved user interface called the desktop. The desktop consists of a screen area, and a taskbar, which is by default at the bottom of the screen.
The taskbar is used for starting programs, or switching between programs. As the user starts each program, the name of the program is displayed on the taskbar. Clicking on the name of the program on the taskbar will display the window associated with that program on the desktop.
Task bar for program switching
The far right end of the task bar also displays the current time and other controls.
The Start button on the taskbar displays a cascading menu of program choices. When a user clicks on the Start button, a pop up menu appears. This provides easy access to installed applications.
The My Computer Icon on the desktop is a shortcut to viewing what is on your computer. Double-clicking an icon on the desktop displays the information within a window.
The Recycle Bin Icon on the desktop is used to hold recently deleted files. When you delete a program or file, it is saved in the recycle bin just in case you deleted it by accident. This allows you to recover from mistakes when you delete something you should not have.
The Network Neighborhood Icon on the desktop is used to display the various resources like servers and applications available on the network (assuming the computer is network enabled).

Plug and Play Support
Windows makes it much easier to add new hardware. It supports Plug and Play technology, which means new hardware can be added to the computer and Windows will automatically detect the new hardware and install software support for it when rebooted. Please note that adding new hardware first requires the computer to be turned off before the hardware is added.

Add/Remove Programs
Adding and removing programs is also easier. Previously, the removal of programs was very difficult. Under Windows, a record is kept track of the files installed and used by programs. The use of installation wizards helps install and remove programs, so that when a program is removed, parts used by other programs are left intact.

Networking Support
Windows supports a wide number of protocols and networks. This allows easy connection to both Microsoft and non-Microsoft networks.
Internet Ready: Dial up networking and Internet Explorer
Windows comes with Dial-up network support, making an Internet connection to an Internet service provider (ISP) an easy task via a setup wizard. In addition, under Windows, a user can configure the dial-up networking to support more than one ISP.

Window Buttons

The Minimize Maximize Close Window Buttons
These buttons are located on the top right corner of each window. Clicking on them once performs the desired action associated with the button.
  • The minimize button minimize button reduces the window and places it on the taskbar at the bottom of the window.
  • The maximize button maximize button expands the window to fill the entire desktop screen area.
  • The close button close button closes the window.
Tip: To minimize all windows on the desktop area, right mouse click on an empty portion of the taskbar and select Minimize all Windows from the menu.

The Menu BarPop up menu
The menu bar presents a number of options that the program associated with the Window supports. Clicking on an option on the menu bar will popup a submenu of choices that you can select from.

The Windows Borders
The windows borders show the dimensions of the window. Any window can be resized, either made smaller or larger, by dragging the window border appropriately.
  • To make the window taller or shorter:
    Move the mouse pointer to either the top or bottom window border, and when it changes to a resize arrow Vertical resize cursor, then hold the left mouse button down and drag the window border to its new position, then let release the left mouse button.
  • To make the window narrower or wider
    Move the mouse pointer to either the left or right window border, and when it changes to a resize arrow Horizontal resize cursor, then hold the left mouse button down and drag the window border to its new position, then let release the left mouse button.

Moving a Window
A window can be repositioned on the desktop screen display area by moving the mouse cursor into the title bar area, then holding the left mouse button down and dragging the window to the new position, then releasing the left mouse button.

Switching between Windows
When you have multiple windows displayed on the desktop screen area, you can switch between windows by clicking on the programs icon on the taskbar or pressing ALT-TAB keys on the keyboard. When you press ALT-TAB, it will pop up a window of the available programs. Hold the ALT key down, and pressing the tab key will move the selection to the next window in the list. When the desired window is highlighted, release the ALT key and that window will become active.
Clicking on the applications icon on the taskbar can also do switching to another application. The following picture shows the Windows taskbar, located at the bottom of the screen.

Fundamentals Window

Window Fundamentals
In a graphical operating system, information is represented in graphical ways. Little symbols or pictures (called icons) are used to display programs or information. Information is displayed inside windows, each of which has similar properties.
It is possible to have more than one window on the screen at one time, and windows may be cascaded (on top of one another) or tiled (all displayed at once and all visible).
In this picture, the windows have been cascaded. This makes each window appear on top of each other, one after the other.
The front most window is considered to be the active window, ie, the window to which the users commands will be sent.
In Windows95 or WindowsNT, the titlebar of the window is shown in the default color Blue.
Cascaded Windows
Tiled Windows In this picture, the images have been tiled.
This makes all windows visible at the same time, but resizes the dimensions of each window so that they all fit on the available screen space at once.
Tip: To cascade or tile all windows on the desktop area, right mouse click on an empty portion of the taskbar and select Cascade Windows or Tile Windows from the menu.

Window Properties
Each window has the same properties and behaves the same way. This provides a consistent interface to the user, as all commands are the same for each window and the operations that the user performs on each window are identical.
In the diagram below, we see the basic window as presented by Windows 95 or Windows NT. Each property is listed on the diagram, and below is an explanation for each of the window components.
Basic Window
The Title Bar
This normally displays the name of the program associated with the window. If the background color of the title bar is blue, the window is active and any user commands will be processed by that window. You can also toggle between a maximized window size and the windows normal size by double clicking in the title bar area.
The Control Menu
Clicking on the Control Menu pops up a small Window of selectable options, which include the operations of Restore, Move, Size, Maximize, Minimize and Close the Window.
The Horizontal and Vertical Scroll Bars
When the amount of information displayed in the window exceeds the viewing space of the window, scroll bars are automatically to the side and bottom of the window. This allows the user to scroll the contents of the window in order to view the remaining information. Arrows are used to indicate the direction of scrolling on the scroll bar, and an indicator bar represents the relative position of the viewing area compared to the total size of the information.
Clicking on the arrows associated with the scroll bar move the viewing window up or down one line, or across or back one character position. You can also click on the small indicator bar within the scroll bar and drag it with the mouse to quickly scroll the windows contents.

Features of Graphical Interfaces

Basic Features of Graphical Interfaces
Graphical systems use windows to display information and thus allow more than one window to be displayed at any time. Each window is associated with a running program. User input is derived from a keyboard and mouse.
The mouse
The mouse, invented in 1963 at the Stanford Research Institute by Douglas Engelbart, has done much to enhance the use of the personal computer. Engelbart's prototype, made of wood, with metal disks for rollers that detected the motion of the mouse, was further developed by Xerox at it's Palo Alto Research Center in the early 1970's under the direction of Jack S Hawley.
Microsoft Mouse
Most mice have two or more buttons, which users depress to select items from a menu or click on graphical objects on the computer screen, thus sending commands to the computer.
The mouse is held in the hand and moved across a flat surface. As the mouse is moved, its movement is detected and translated into both X and Y movements, which updates the indicated position of the mouse pointer on the computer screen accordingly.

The mouse cursor
The position of the mouse is shown on the screen as the mouse cursor and is denoted by a number of symbols.
Mouse Pointer Standard mouse pointer
Mouse Busy Indicates computer is busy

Selecting items with the Mouse
Single Click
A single mouse click refers to moving the mouse pointer over the desired item and quickly pressing the left mouse button once.
Double Click
A double mouse click refers to moving the mouse pointer over the desired item and quickly pressing the left mouse button twice in rapid succession.
Drag
A drag or move operation is performed by moving the mouse pointer over the desired item and holding the left mouse button down. The mouse is then used to move to drag the object or window to the new position, then the left mouse button is released.