google ads

Tuesday, May 19, 2009

AN INTRODUCTION TO THE .NET

WHAT IS .NET?
.NET is Microsoft’s new strategy for the development and deployment
of software. Depending on your interests and development background,
you may already have a number of preconceived notions regarding
.NET. As we will see throughout this CodeNote:
• .NET fundamentally changes the way applications execute under
the Windows Operating System.
• With .NET Microsoft is, in effect, abandoning its traditional
stance, one which favors compiled components, and is embracing
interpreted technology (similar, in many ways, to the Java
paradigm).
• .NET brings about significant changes to both C++ and Visual
Basic, and introduces a new language called C# (pronounced
“C sharp”).
• .NET is built from the ground up with the Internet in mind, embracing
open Internet standards such as XML and HTTP. XML
is also used throughout the framework as both a messaging instrument
and for configuration files.

These are all noteworthy features of .NET, or more accurately the .NET
Framework, which consists of the platform and tools needed to develop
and deploy .NET applications. The .NET Framework can be distilled
into the following three entities:

1. The Common Language Runtime (CLR), which is the executionenvironment for all programs in the .NET Framework. The CLR is similar to a Java Virtual Machine (VM) in that it interprets
byte code and executes it on the fly, while simultaneously
providing services such as garbage collection and exception
handling. Unlike a Java VM, which is limited to the Java language,
the CLR is accessible from any compiler that produces
Microsoft Intermediate Language (IL) code, which is similar to
Java byte code. Code that executes inside the CLR is referred to
as managed code. Code that executes outside its boundaries is
called unmanaged code.

2. The Runtime classes, which provide hundreds of prewritten services
that clients can use. The Runtime classes are the building
blocks for .NET applications. Many technologies you may have
used in the past (ADO, for example) are now accessed through
these Runtime classes, as are basic operations such as I/O. Traditionally,
every language had its own unique supporting libraries,
accessible only from that particular language. String
manipulation, for example, was afforded to VB programmers
via the Visual Basic runtime, whereas C++ programmers depended
on libraries such as STL for similar functionality. The
.NET Runtime classes remove this limitation by uniformly offering
services to any compiler that targets the CLR. Those familiar
with Java will find the Runtime classes analogous to the
Java Class Libraries.

3. Visual Studio.NET (VS.NET), which is Microsoft’s newest version
of Visual Studio. VS.NET includes VB.NET, “managed”
C++, and C#, all of which translate source code into IL code.
VB.NET and VC.NET are the new versions of Visual Basic and
Visual C++, respectively. C# is a new Microsoft language that at
first glance appears to be a hybrid of C++ and Java. .NET development
does not have to be limited to these languages, however.
Any component or program produced by an IL-aware
compiler can run within the .NET Framework. (As of this writing,
other companies have announced IL compilers for Perl,
Python, and COBOL.) VS.NET also comes with a fully Integrated
Development Environment (IDE), which we will examine
in Chapter 7. Note the VS.NET IDE now houses the
development environments for both Visual C++ and Visual Basic.
OUTLINE OF THE BOOK
In this chapter we will examine the three fundamentals of the .NET
Framework previously listed.

Chapter 2 provides brief installation instructions. Because .NET was
still in beta release at the time of writing, these instructions may be out
of date. Readers are encouraged to consult the online instructions at
aNET010001.
One of the goals of .NET was to eliminate the versioning problems of
traditional Win32 DLLs (a problem sometimes referred to as DLL Hell).
This is realized through a new type of component in the .NET Framework
called the assembly, the subject of
Chapter 3. .NET eradicates DLL Hell from the Windows environment by enforcing the versioning
of assemblies through public key cryptography.

In Chapter 4, we will look at some of the new language features in the
.NET Framework, such as attributes, which are nonprogrammatic code
statements that can be used to influence application behavior, and delegates,
the new type-safe callback mechanism in the managed environment.
Garbage collection, a service performed by the CLR, will also be
investigated, as will reflection, the ability to ascertain type information
about an application at runtime.
The .NET Framework does not preclude the use of traditional COM
and Win32 components that have already been developed. Mechanisms
exist to allow these “unmanaged” components (those that do not run
under the auspices of the CLR) to run alongside their .NET counterparts.
Such mechanisms will be investigated in Chapter 5.
Chapter 6 looks at ADO.NET, the new data access model for the
.NET Framework. ADO.NET is a disconnected data access model,
which means that data manipulation is performed outside the context of
an open database connection. This model is especially appropriate for
web applications that are loosely coupled to their data sources. As its
name suggests, ADO.NET is an evolution of Microsoft’s ActiveX Data
Object (ADO) model.
.NET also exposes new methodologies for developing standard
Win32 applications. Windows Forms, the subject of Chapter 7, is the
new way to construct desktop GUI applications for the Windows environment.
Internet developers will also welcome Web Forms, which brings the
traditional ease and versatility of Visual Basic forms to Internet applications.
Web Forms is a feature of ASP.NET, the topic of Chapter 8.
ASP.NET is Microsoft’s new generation Active Server Page (ASP)
framework for developing robust web applications.
Chapter 9 examines Web Services and an emerging communication
An Introduction to the .NET Framework . 5
protocol called SOAP, which allow components to interact (i.e., transfer
data, perform RPC calls) via open Internet standards such as XML and
HTTP.
CORE CONCEPTS

Visual Studio.NET
Producing .NET applications and components requires a compiler that
translates source code into IL code. VS.NET, Microsoft’s new version of
Visual Studio, contains three such compilers: VB.NET, C#, and managed
C++. While a full examination of these languages is beyond the
scope of a CodeNote, each language is briefly discussed below. Code
examples throughout this book will demonstrate some of the nuances of
each language and the syntactical differences between them.
In addition to the IDE, VS.NET contains a large assortment of command
line utilities. Some of these utilities are directly incorporated into
the development environment, while others are stand-alone. We will examine
some of these utilities throughout this CodeNote.

Visual Basic.NET
VB.NET is the most recent version of Visual Basic, what was once
thought of as VB7. VB.NET is the first version of Visual Basic to support
true object-oriented inheritance, which means it has the ability to
inherit and extend the interface and behavior of any class produced by
an IL compiler. This is significant, as previous versions of Visual Basic
could only inherit from classes written in VB itself. This feature is not
really an enhancement of VB.NET but a byproduct of the language neutrality
of the CLR, which gives all IL compilers the ability to inherit
classes from one another. VB.NET also includes exception handling
constructs (try/catch) similar to those found in Java and C++.
Unfortunately, VB.NET also brings about some syntax changes that
will break compatibility with old VB source code. Procedure parameters,
for example, are now passed by value (ByVal) by default, not by
reference (ByRef). Certain syntax elements such as GoSub, IsNull, and
IsMissing have been removed from the language altogether. For a complete
list of syntax changes, see aNET010002. Clearly, a considerable
amount of effort will be required to migrate existing Visual Basic projects
to the .NET Framework.
Although not exclusive to VB.NET, most VB users will be interested
in the Windows Forms (Chapter 7) portion of this book, which investigates
the new way Win32 screens are developed in the .NET Framework.
Windows Forms completely replaces the traditional Visual Basic
Forms editor. Finally, VB.NET now ships with a command line compiler
(VBC.EXE), allowing one to write applications outside the development
environment (using NOTEPAD, for example). In the first
example in this chapter, we will investigate VB.NET’s new compiler.

Managed C++
Managed C++ is a set of extensions added to the C++ language to allow
one to produce “managed code” (code that executes under the auspices
of the CLR). The most notable extension is the introduction of “managed
types,” which shift the burden of memory management from the
C++ programmer onto the CLR. Placing the __gc extension in front of
the declaration of a class, for example, allows instances of the class to be
garbage collected by the CLR. This convenience comes at a cost, however,
as the “managed” class must adhere to the restrictions of CLR
types. It cannot, for example, inherit from two classes, even though multiple
inheritance is a feature of the C++ language.
Another extension is that of managed arrays, which allows these data
structures to be managed by the CLR. Managed exception handling is
another amendment, differing from C++ exception handling in both
syntax and behavior. Examples of managed extensions can be found at
aNET010003. Managed C++ is a part of Visual C++ .NET, which is the
only tool in the new Visual Studio suite capable of producing unmanaged
code. It is thus the only choice for producing applications that contain
both managed and unmanaged code, as is discussed in the online
article at aNET010010.

C#
C# (pronounced “C-sharp”) is a new language that Microsoft has touted
as a simplified version of C and C++. In this respect, C# is very much
like Java, eliminating some of the more complex features of C++ such as
pointers and multiple inheritance. Most of the examples in this Code-
Note are written in C# (and VB.NET), to give you a look at this new language.
Like Java and C++, C# is an object-oriented (OO) language and
contains expected OO features such as inheritance (the ability of a class
to extend another class), polymorphism (the ability to separate an interface
from its implementation), and encapsulation (the ability of objects
to hide certain methods and instance variables from other objects).
Java and C++ developers will be immediately comfortable with C#,
while the language may present some challenges for Visual Basic developers.
Even if you choose to develop in another language under the
.NET Framework, it is worthwhile to understand C#, as the majority of
MSDN .NET code is written in C#. In this sense, C# can be considered
the “intrinsic” language of the .NET Framework, as it was developed
An Introduction to the .NET Framework . 7
solely for the managed environment, as opposed to C++ and Visual
Basic, which had to evolve into their .NET manifestations.

.NET and COM
While the .NET Framework is intended to simplify many of the complexities
that existed with COM, it in no way renders COM obsolete. All
versions of Windows today remain heavily dependent on COM, and
while Microsoft’s long-term vision may be to eradicate this component
model, it is not going anywhere soon. Chapter 5 will investigate how
.NET applications can call traditional COM components using Runtime
Callable Wrappers (RCWs).

.NET and COM+
COM+ services such as transactions, object pooling, and Just-in-Time
activation can be used from the .NET Framework and are accessed
through the System.EnterpriseServices namespace. Examples of managed
code using these services can be found at aNET010004.
The .NET Runtime also implicitly uses COM+ to support some of its
services. In the Transactions section of Chapter 6, we will see how the
.NET Runtime automatically uses COM+ services behind the scenes to
provide transactional capability for managed classes.

SIMPLE APPLICATION
In this section we look at the proverbial “Hello World” program. For the
purposes of comparison, source code for all three .NET languages
(VB.NET, C#, and managed C++) is given below. Readers might want
to consult Chapter 2 to install the .NET Framework before proceeding.

VB.NET Application
Visual Basic developers are reminded that VB.NET now includes a
command-line compiler (VBC.EXE), allowing one to develop applications
outside the Visual Basic environment. In other words, you can
write the following program in a text editor such as Notepad. VB users
will also see from this example that VB.NET has the ability to produce
console applications, something previous versions of Visual Basic were
unable to do.
'VB.NET "Hello World" Program.
Module HelloWorld
Sub Main
'Use the .NET Runtime Console method WriteLine,
'to output "Hello World" on the screen:
System.Console.WriteLine("Hello World!")
End Sub
End Module
Listing 1.1 VB.NET Hello World program

C# Application
As with the Visual Basic example, you can write this code using any text
editor. Notice that the syntax is very similar to C++ in that class definitions
and methods are encapsulated within curly braces and individual
lines of code end with semicolons.
// C# "Hello World" Program.
public class HelloWorld {
static public void Main () {
System.Console.WriteLine("Hello World!");
}
}
Listing 1.2 C# Hello World program

Managed C++ Application
Managed C++ is almost identical to normal C++. Notice that you must
use the a::b notation for namespaces, rather than the a.b notation of Visual
Basic and C#.
// Managed C++ "Hello World" Program.
// Reference the .NET Runtime Library,
// for Console Input/Output functionality.

#using
void main() {
System::Console::WriteLine("Hello World!");
}
Listing 1.3 Managed C++ Hello World program

Compiling and Running the Example
Assuming that these files were called Hello-World.vb, Hello-World.cs,
and Hello-World.cpp, respectively, .NET console applications could be
An Introduction to the .NET Framework . 9
created by invoking each language’s compiler from the command line as
shown below (alternatively, you could create VB.NET, C#, and C++
console projects and compile them from the VS.NET IDE).
• VB.NET: vbc.exe /t:exe Hello-World.vb
• C#: csc.exe /t:exe Hello-World.cs
• Managed C++: cl.exe /CLR Hello-World.cpp
The /t:exe option informs both the VB.NET and C# compilers to produce
executable files, while the /CLR switch instructs the Visual C++
compiler to produce IL code (this option is OFF by default).

Source Analysis
The most notable difference between the three programs is that the managed
C++ example must explicitly reference the .NET Runtime classes,
which is implicitly done by the VB and C# compilers. This is accomplished
by inserting the following line at the top of all managed
C++ programs: #using . C++ COM/ATL developers
will find this command very similar to the #import directive used in Visual
C++.
Syntactical differences aside, the three programs are remarkably
similar in that they all use the Runtime Console method WriteLine() to
print “Hello World” on the screen. Such uniformity is a virtue of the
.NET Runtime—all three languages use a consistent set of classes to accomplish
the same thing. The only difference lies in the way such
classes are accessed. C++ users might recognize that we had to tell the
compiler which namespace the Console class could be found in. The
concept of namespaces and their importance to the Runtime is addressed
in the .NET Runtime section of this chapter.
Topic: The Common Language Runtime
At the heart of the .NET Framework is the Common Language Runtime
(CLR). In addition to acting as a virtual machine, interpreting and executing
IL code on the fly, the CLR performs numerous other functions,
such as type safety checking, application memory isolation, memory
management, garbage collection, and crosslanguage exception handling.

THE COMMON TYPE SYSTEM
The CLR greatly simplifies crosslanguage communication through the
introduction of the Common Type System (CTS). The CTS defines all of
the basic types that can be used in the .NET Framework and the operations
that can be performed on those types. Applications can create more
complex types, but they must be built from the types defined by the
CTS.
All CTS types are classes that derive from a base class called System.
Object (this is true even for “primitive” types such as integer and
floating point variables). This means that any object executing inside the
CLR can utilize the member functions of the System.Object class. The
methods of System.Object can be found at aNET010005, but for
the purposes of illustration we will consider the Equals() method of this
class, which can be used to test two objects for equality.
Consider the following straightforward C# fragment:
int a=5;
int b=5;
if (a==b) {
System.Console.WriteLine("a is the same as b");
}
Since all types inherit from System.Object, the code could be rewritten
as:
int a=5;
int b=5;
if (a.Equals(b)) {
System.Console.WriteLine("a is the same as b");
}

COMMON LANGUAGE SPECIFICATION
A subsection of the CTS called the Common Language Specification
(CLS) specifies how .NET languages share and extend one another’s libraries.
The example at the end of this chapter demonstrates how a class
written in one language can be inherited and extended by a class written
in another.
An Introduction to the .NET Framework . 11

CODE ACCESS SECURITY
The CLR is also burdened with the responsibility of security. An integral
part of the .NET Runtime is something called Code Access Security
(CAS), which associates a certain amount of “trust” with code, depending
on the code’s origins (the local file system, intranet, Internet, etc.).
The CLR is responsible for making sure that the code it executes stays
within its designated security boundaries. This could include such
things as reading and writing files from the user’s hard drive, making
registry entries, and so forth.
You can modify the permissions that are granted to code from a certain
location using a utility called CASPOL.EXE. You could specify, for
example, that all code originating from www.codenotes.com be granted
more privileges than other code that comes from the Internet. Examples
of CASPOL.EXE and an in-depth discussion of Code Access Security
can be found at aNET010006.

Topic: .NET Runtime Classes
In the example earlier in this chapter, all three languages used the Console.
WriteLine() method to print “Hello World” to the screen. The
.NET Runtime classes eliminate the need to master a different set of
APIs for different languages. Instead, developers need only familiarize
themselves with the appropriate Runtime classes and then call them
from the language of their choice.
The .NET Runtime includes classes for many programmatic tasks,
including data access, GUI design, messaging, and many more. It also
acts as a wrapper around the Win32 API, eliminating the need to directly
communicate with this cryptic C-style interface. The most difficult part
of using the Runtime is figuring out which class you need to accomplish
the task at hand. A complete list of the .NET Runtime classes can be
found at aNET010007.

NAMESPACES
The .NET Runtime classes are organized in hierarchical manner using
namespaces. Namespaces provide a scope (or container) in which types
are defined. All of the .NET Runtime classes, for example, can be found
in the System namespace. In the “Hello World” example we had to in-
form the compiler that the Console class could be found in the System
namespace by qualifying it (System.Console). Namespaces can also be
nested. The System.IO namespace, for example, contains a number of
classes for I/O operations, whereas the System.Collections namespace
contains classes for common data structures such as arrays.
In the Hello World example we directly addressed the namespace.
You will frequently see code that uses implicit namespace referencing to
make it more concise. Each language uses a different keyword to include
the contents of a namespace. We could have written the Hello
World program in VB.NET as follows:
'VB.NET "Hello World" Program.

Imports System
Module HelloWorld
Sub Main
'Use the .NET Runtime Console method WriteLine,
'to output "Hello World" on the screen:
Console.WriteLine("Hello World!")
End Sub
End Module
Listing 1.4 VB.NET Hello World program using namespaces
Notice that we added the Imports System line and no longer have to
qualify the Console object as System.Console. In C#, you can perform
the same action with the “using” keyword:
// C# "Hello World" Program.
// Implicit namespace referencing
using System;
public class HelloWorld {
static public void Main () {
Console.WriteLine("Hello World.");
}
}
Listing 1.5 C# Hello World program using namespaces
As you can see, implicitly referencing namespaces can save you a lot of
typing and make your code easier to read. You will use namespaces
throughout the .NET framework to:
An Introduction to the .NET Framework . 13
• Access the .NET Runtime classes
• Access custom classes authored by other developers
• Provide a namespace for your own classes, to avoid naming conflicts
with other classes and namespaces
We will use namespaces throughout this CodeNote as we develop our
own .NET components.

ASSIGNING A NAMESPACE
When you want to assign a particular class to a namespace, you use the
namespace keyword. For example, the following class is assigned to the
CodeNotes.HelloWorld namespace:
//C# hello world
namespace CodeNotes.HelloWorld
//rest of class
You would address any of the methods or fields of this class by using the
CodeNotes.HelloWorld prefix. This naming command is identical for all
three languages.

EXAMPLE
Sorting an array of numbers is something every programmer must do at
some point in his or her career. C and C++ programmers have traditionally
relied on the C runtime library (i.e., qsort ()) for such functionality.
The universality of the .NET Runtime means that Visual Basic
programmers can also enjoy the luxury of prewritten routines. The VB
example below uses the .NET Runtime to sort through a list of ten random
numbers. C# and C++ examples can be found at aNET010008.
'VB.NET Example that uses the .NET collection classes
'Use the System and System.Collections namespaces

Imports System
Imports System.Collections
Module SortingExample
Sub Main()
dim k as integer
dim oArray as ArrayList
dim oRandom as Random
oArray = new ArrayList()
oRandom = new Random()
'Add ten random numbers (0-99) to the list:
for k = 0 to 9
oArray.Add(oRandom.Next() mod 100)
next
oArray.Sort() 'That's it!
'Print out the sorted numbers:
for k= 0 to 9
Console.Write(oArray(k))
Console.Write(",")
next
End Sub
end module
Listing 1.6 Using the .NET Runtime classes to sort numbers
Compiling and running this program produces output similar to the following:
10,11,61,63,74,77,80,90,94,98,
The bolded portions of Listing 1.6, illustrating areas where the .NET
Runtime is being utilized, are worth more explanation.
Imports System
Imports System.Collections
The first two lines (above) inform Visual Basic that we will be using the
System and System.Collection namespaces. Recall that namespaces are
a syntactical shortcut; they save us from having to fully qualify the Runtime
class names when we reference them. The following two lines instantiate
the Runtime classes that we will use.
An Introduction to the .NET Framework . 15
oArray = new ArrayList() 'no Set !
oRandom = new Random()
The ArrayList class is like a collection; elements can be added and removed
and it will automatically resize itself. The Random class generates
the random numbers that we will sort. Note that the new Visual Basic
syntax does not require the Set keyword when instantiating classes.
for k = 0 to 9
oArray.Add(oRandom.Next() mod 100)
next
oArray.Sort() 'That's it!
The last code fragment adds ten random numbers to the list and sorts
the array. This simply involves calling the Sort() method against the
ArrayList class; the underlying operation is handled by the .NET Runtime.
As can be seen from Listing 1.6, using the .NET Runtime is simply a
matter of understanding the conventions of the classes you will be calling.
In the example above, the functionality of the program (sorting and
output) is provided by the Runtime; Visual Basic simply acts as a forum
to call it. To a large degree, your choice of .NET development language
will be a function of syntactical preference, due to the universal access
offered by the Runtime.
You may be wondering why we did not use Visual Basic’s built-in Rnd
function to generate random numbers. While we could have done this
(see the How and Why section), the general practice under the .NET
Framework is to use the Runtime classes where we can. In several instances,
VB.NET has dropped intrinsic elements of the languages as
they have been made redundant by the Runtime Classes. For details, see
aNET010009.

HOW AND WHY

Can I Still Use Intrinsic Elements (Like Rnd, Round) in My VB
Programs?
To mitigate the effort required to convert existing VB projects, Microsoft
has provided the Microsoft.VisualBasic.Compatibility runtime
DLL, which allows you to use some intrinsic elements of the Visual
Basic language. For examples, see aNET010009. However, not all intrinsic
elements are supported. See aNET10009 for details.

The .NET Runtime is a collection of classes that can be uniformly accessed
by any language capable of producing IL code. Functionality that
was traditionally provided by the language environment is now supplied
by the Runtime classes. This greatly simplifies the development process,
as one only has to familiarize oneself with a common framework, instead
of a language-dependent API. The Runtime classes are organized
using namespaces, which makes them easier to access and syntactically
more concise. We will also use namespaces when we design our own
components in the .NET Framework.

Chapter Summary
The .NET Framework consists of the platform and tools needed to develop
and deploy .NET applications. It includes an execution environment
for .NET programs (the Common Language Runtime, or CLR for
short), prewritten services that programs can access from this environment
(the .NET Runtime classes), and the development tools to produce
such programs (VS.NET).
Unlike traditional Windows applications, .NET applications are not
compiled to native machine code but are compiled to interpreted code
called Microsoft Intermediate Language (IL). IL code is the inherent
language of the CLR, which is similar to a Java VM, acting as an operating
system on the operating system, interpreting the IL code in real
time. Since IL code is interpreted, responsibilities such as memory allocation
and exception handling become property of the CLR and not the
programmer. For this reason, IL code is referred to as “managed” code,
whereas native machine code is said to be “unmanaged.”
One of the compelling reasons to develop applications in the .NET
Framework is the .NET Runtime classes. Similar to the Java Class Libraries,
these classes are the building blocks for writing .NET applications.
Throughout this book we will use the Runtime classes for more
complex operations such as database access and remote messaging. The
new .NET versions of traditional technologies such as ADO are also accessed
through the .NET Runtime, as we will see in Chapter 6.
An Introduction to the .NET Framework . 17

No comments:

Post a Comment