Getting started with .NET development using C#

salmonbrisketSoftware and s/w Development

Nov 2, 2013 (3 years and 9 months ago)

209 views

Chapter
3

Getting started with .NET
development using C#

T

ime to set yourself up for a successful journey through the
world of .NET development using C#. And obvious first thing to
tackle is to get the .NET Framework and the necessary tools i
n-
stalled to
start running and obviously writing code. One tool we'll
spend a good amount of attention to is Visual Studio 2010, but at
the same time we'll cover other useful tools as well.

To get our hands dirty, we'll write a simple C# applicat ion and
highlight some
of the important language elements, go through the
process of building it using various tools and look at how we can
debug code.

Installing the .NET Framework

The first logical step to get started with writing code target ing the
.NET Framework is to instal
l it on your development machine. At
this point, we'll skip the in
-
dept h discussion on how to deploy the
.NET Framework to the machines where your applicat ion code is to
run ultimat ely, be it a client comput er, a web server or even the
cloud. We'll defer t
his important discussion till further in the book
when we cover applicat ion deployment end
-
to
-
end.

The .NET Framework version landscape

Over the years, various versions of the .NET Framework have been
released. In this book, we cover the [em] at the time o
f writing [em]
latest release of the .NET Framework, version 4, which goes hand
in hand with the Visual Studio 2010 release.

Does that mean you can't use the knowledge you gain from .NET 4
programming to target older releases of the framework? Certainly
no
t! Though the .NET Framework has grown release after release,
the core principles have remained the same and a good part of the
IN THIS CHAPTER

[lb]

.NET Framework 4

[lb]

Handy tools


[lb]

Your first C# program


[lb]

Visual Studio 2010

evolut ion is to be found at the level of additional APIs that are made available through
the class libraries. A similar observat
ion of evolution obviously holds on the level of
the managed languages: features are added every time around that often require add
i-
tional framework support (e.g. LINQ in C# 3.0, dynamic in version 4). As you can i
m-
agine, keeping track of all those version
s and their key different iat ing features isn't
always easy. To make things more clear, have a look at the following table:

TABLE 3.1


.NET platform version history

Version

Codename

Visual St
u
dio

C#

VB

Flagship fe
a
tures

1.0

Lightning

2002 (7.0)

1.0

7.0

Man
aged code

1.1

Everett

2003 (7.1)

1.0

7.0


2.0

Whidbey

2005 (8.0)

2.0

8.0

Generics

3.0

WinFX

2005 (8.0)

2.0

8.0

WPF, WCF, WF

3.5

Orcas

2008 (9.0)

3.0

9.0

LINQ

4.0

Dev10

2010 (10.0)

4.0

10.0

Dynamic


Notice new releas es of the .NET Framewor k typically
go hand in hand with updates to
the Visual Studio tooling support. A notable except ion to this rule was the .NET 3.0
r
e
leas e, where Visual Studio 2005 additions were made to support the newly added
featur es, e.g. by providing designer support for Windows P
resent at ion Foundat ion. On
the other hand, notice how the managed languages evolve at a slightly slower pace. It's
perfect ly imaginable a future releas e of the .NET Framewor k will still be using C# 4.0
and VB.NET 10.0. History will tell...

WHAT ABOUT OPERA
TING SYSTEM INTEGRAT
ION?

Being a logical extension to the Win32 API for Windows programming, it very
much makes sense to have the framework components readily available together
with various versions of the Windows operating system. However, Windows and
th
e .NET Framework evolve at a different pace, so the innovation on the level of
the .NET Framework is not immediately available with the operating system out
there at that point in time.

One first little piece of integration with the operating system happen
ed with Wi
n-
dows XP, where the image loaded was made aware of the existence of managed
code in order to be able to load managed executables with less roundabouts than
would be otherwise required. In the Windows Server 2003 timeframe, the 1.1 r
e-
lease of the
.NET Framework was brought to the operating system, so that the
ASP.NET web stack was available out of the box for use in web server install
a-
tions.

The bigger integration story happened around the Vista timeframe, driven by the
WinFX vision of enhancing co
re system capabilities like windowing (with WPF)
and communication (with WCF). For a long time during the development of Vista
[em] known as Longhorn at the time [em] WinFX formed a core pillar of the next
-
generation operating system and development procee
ded hand in hand with the
operating system. Only later, WinFX was decoupled from Vista and ported back to
other platforms, resulting in what became to be known as .NET Framework 3.0.
This said, the .NET Framework 3.0 components still shipped with Windows V
ista
as an optional Windows component that can be turned on or off. The same holds
for Windows Server 2008.

With the release of Windows 7, this tradition continues by making the .NET
Framework 3.5 components available out of the box, and one shouldn't be s
u
r-
prised to see the .NET Framework 4 release integrated with a future release of
the operating system.

This integration has several advantages, the most important of which is the d
e-
creased framework deployment cost when targeting these operating systems fo
r
managed code applications. But also for the operating system developers, this
means managed code becomes an option to write new functionality in.

What the table above doesn't show is the versioning of the CLR. There's a very i
m-
po
r
tant point to be made ab
out this: the CLR evolves at a much slower pace than the
libr
a
ries and languages built on top of it. Although slower most often has a pejorat ive
feel to it, for the CLR this is a good thing: the less churn is made to the core of runtime,
the more guarant ee
s can be made about compat ibility of existing code across different
ve
r
sions of the .NET Framework. This can be illustrat ed nicely based on the .NET
Framework 3.x history:


<<03fig01.jpg>>



Figure
3
.
1

.NET Framework 3.x is built on CLR 2.0


From this f
igure you can see how both .NET Framework 3.0 and .NET Framework 3.5
are built to run on top of the existing CLR 2.0 runtime bits. This means that for all the
goodness that ships with those versions of the .NET Framework, no changes were r
e-
quired to the co
re execution engine, a good sign of having a solid runtime that's ready
to take on a big job.

RED BITS VERSUS GREE
N BITS

A concept you might sometimes hear from Microsoft people in the context of
framework versioning is that of red bits and green bits. The

categorization of
framework assemblies in red bits and green bits was introduced in the .NET 3.x
timeframe to distinguish between new assemblies (green bits) and modifications
to existing ones (red bits). Although .NET 3.x mostly added new library functio
nal
i-
ty to the existing .NET 2.0 layer, some updates were required to assemblies that
had already shipped. With the distinction between red bits and green bits, deve
l-
opment teams kept track of those modifications also to minimize the changes r
e-
quired to red

bits to reduce the risk of breaking existing applications.

What all of this means in practice is that .NET 3.0 is a superset of .NET 2.0, but
with some updates to the .NET 2.0 binaries, under the form of a Service Pack.
Those service packs are also made a
vailable by themselves as they contain very
valuable fixes and optimizations, and are designed to be fully backwards compa
t-
ible as not to break existing code. Windows Update automatically deploys these
service packs to machines that already have the framew
ork installed.

LOST IN TRANSLATI ON

Even more remarkable than the ability to add gigantic libraries like WPF and WCF
on an already existing runtime without requiring modifications to it, is the fact that
very powerful language extensions have been made in .
NET 3.5 with the introdu
c-
tion of LINQ. However, none of those new language additions required changes
to the runtime or IL language. Therefore C# 3.0 and VB 9.0 programs can run on
the .NET 2.0 CLR. Even more, it's theoretically possible to cross
-
compile C
# 3.0
programs into C# 2.0 code with an equivalent meaning. A paper proving this claim
was written by a group of language designers at Microsoft and is titled "Lost in
translation".

One caveat though: don't take this to mean that C# 3.0 programs can be por
ted
blin
d
ly to .NET 2.0, as implementations of various LINQ providers ship in various
.NET 3.5 a
s
semblies.

Another advant age that comes from keeping the runtime the same across a set of
framework releases is the ability to reuse existing tooling infrastruc
t ure, e.g. for d
e-
bugging. With the release of Visual Studio 2008, this capability became visible to
.NET developers under the form of multi
-
t arget ing support. What this feature enables
is to use Visual Studio 2008 to target .NET Framework 2.0, 3.0 and 3.5

using the same
comfort able tooling environment. And with .NET 4.0 [em] as we'll see later in this
chapter when exploring Visual Studio 2010 [em] multi
-
t argeting has been extended to
support all releases from .NET 2.0 to 4.0.

What about .NET Framework 1.x
you may wonder? Development target ing those pla
t-
forms will always be tied to the use of the releases of Visual Studio that shipped with
it, i.e. Visual Studio .NET versions 2002 and 2003. Too many fundament al changes to
runtime infrastruct ure were made bet
ween versions 1.x and 2.0 of the CLR, making
multi
-
t arget ing support for .NET 1.x infeasible. Luckily nowadays, the use of .NET 1.x
has vanished mostly from the surface of the .NET globe. If you still have .NET 1.x
applicat ion around, now is the time to po
rt them to a more recent version of the pla
t-
form (preferably .NET 4.0 of course).

But why should someone care to target an older release of the .NET Framework? Most
commonly the answer is to be found in deployment constraints within companies, web
hosting
providers, and so on. Having tooling support to facilit at e this multi
-
t arget ing is
pure goodness and also means you can benefit from core enhancements to the Visual
St
u
dio tools while targeting older releases of the .NET Framework.

.NET Framework 4

The par
ticular version of the .NET Framework we'll target in this book is .NET 4, u
s-
ing Visual Studio 2010 and C# 4.0. Other than the .NET 3.x releases, .NET 4.0 has a
new version of the CLR underneat h it, and obviously [em] in the grand tradition [em] it
comes w
ith a bunch of new class libraries that will make life easier for developers.

Two keywords about .NET 4.0 are import ant to point out here:

[lb]

Side
-
by
-
si de

means .NET 4.0 can be installed next to existing versions of the
.NET Framework. What's so special
about this, compared to .NET 3.x? The
key difference is updates to existing class library assemblies are no longer ca
r-
ried out in
-
place, but new versions are put next to the existing ones.

[lb]

Backwards
-
compati ble

is a core success factor to the managed c
ode develo
p-
er. In practice it means that existing code that was compiled against .NET 2.0
or 3.x in the past can now be targeted at .NET 4.0 without requiring source
-
level code changes.

Figure 3
-
2 illustrat es a machine with all the versions of the .NET Fra
mework installed
next to one another.

WHAT'S UP WITH THOSE

VERSION NUMBERS?

The full version numbers of the CLR and .NET Framework installations and bin
a-
ries can be somewhat distracting at first sight. Where do they come from?

In the .NET Framework 1.x tim
eframe, the build number (the third component of
the version number) was simply created incrementally. Version 1.0 released at
build 3705 and version 1.1 ended up at build 4322.

With .NET 2.0, it made sense to give more meaning to the build number, and the

pattern ymmdd was chosen: 1 digit for the year (2005), two digits for the month
(July) and two for the day (27).

This approach worked very nicely, till the theoretical 35th day of the 55th month of
the year 2006: the metadata encoding for build numbers ca
nnot exceed 65535, so
we're out of luck using this pattern in its full glory. The result was a compromise:
the month and year encodings are kept the same, but the year is now considered
relative to the start of the release. For the .NET 4.0 release, the st
art of the r
e-
lease was in 2007, so from the screenshot below one can infer I'm using the 2009
April 24th build at the time of wri
t
ing.


<<03fig02.png>>



Figure
3
.
2

Side
-
by
-
side installation of .NET Framework versions

Besides having various versions of t
he .NET Framework, .NET 4.0 also pioneers the
availability of different "flavors". Around the .NET 3.5 timeframe it became apparent
the size of the .NET Framework had grown too large to enable fast friction
-
free installs
which are especially important for
client applicat ion deployments. Significant factors
for such deployments are download times and installation times.

In order to streamline typical deployments of the framework, a split has been made of
the .NET Framework class libraries, factoring out a so
-
called Client Profile set of a
s-
semblies. Inside the Client Profile bubble one finds the BCL assemblies, things like
WPF and WCF, C# 4.0 language support, amongst other assemblies that are relevant
for client applicat ion development. The remainder portion
contains features like
ASP.NET that client applications typica
l
ly don't need.

In practice, developers either target the full framework or the Client Profile subset of it.
Both packages have their own redistribut able installers where obviously the Client Pr
o-
file package is the smaller of the two and installs faster. Internally, the "Full package"
is just an increment on top of the "Client Profile package", the result being a layered
cake as shown in the figure below. The nice thing about this organizat ion is

that it's
possible to upgrade a Client Profile machine to the full framework installat ion.

FOUR, POINT
-
OH?

The careful reader will have noticed I'm mixing the use of ".NET Framework 4"
and ".NET 4.0". Why this distinction and where's the ".0" portion in t
he former?
The answer is marketing: it was decided to call the fourth version of the .NET
Framework simply "4", although internally assemblies obviously have a minor ve
r-
sion number as well. So whenever I'm referring to the product as a whole, I'm u
s-
ing ".N
ET Framework 4", while for the more technical reference to the current 4.x
release I'm using ".NET 4.0".


<<03fig03.png>>



Figure
3
.
3

Client Profile subset of the .NET Framework

With this split, w
ithout doubt you'll wonder whether you need to memorize what's
available in what subset of the .NET Framework. The fortunat e answer is "No", as
Visual Studio 2010 extends its notion of multi
-
t argeting to the various "profiles" of the
.NET Framework. When t
he Client Profile subset is select ed, Visual Studio 2010 pr
e-
vents assemblies from the Full framework to be referenced.


.NET FRAMEWORK 3.5 C
LIENT PROFILE

Chances are you have heard about the .NET 3.5 Client Profile. This subset of the
3.5 version of the fr
amework was the precursor for the idea of having different
subsets of the product, and was realized in the .NET 3.5 SP1 timeframe. Unfort
u-
nately the applicability of the Client Profile 3.5 was rather limited because of arch
i-
tectural constraints: only on Wi
ndows XP machines with no prior version of the
framework installed, the subset could be applied. In other cases, the Client Profile
installer simply fell back to the installation of the complete .NET Framework.

With .NET 4.0, those constraints do not longe
r apply [em] thanks to an archite
c-
tural overhaul of the installer and the framework structure itself [em] and the Client
Profile subset can be installed on any operating system supporting the .NET
Framework. Even more, this exercise has been applied for ot
her scenarios too: on
server deployments, various client
-
specific APIs do not make sense, so a sep
a-
rate refactoring has been made to lower the footprint on server installs too.

Running the installer

Playtime! In order to write code on the .NET Framework 4,

let's start by installing the
Full .NET Framework package. That's really all you need to get started with managed
code development.

Where to get it? Just browse to http://msdn.microsoft.com/netframework and click the
link to the .NET Framework 4 download.

The installer itself should be straightforward
to run: accept the license agreement, get a cup of coffee, and you're ready to go.




TODO: INSERT IMAGE O
F THE INSTALLER



<<03fig04.png>>



Figure
3
.
4

.NET Framework 4 installation



What got installed?

Once the installation is complet e, it's good to have a quick look at what got installed to
familiarize ourselves with the various locations to find stuff. An overview of the most
interest ing hot spots
.

The runtime shim

The runtime shim is really somet hing one shouldn't care about much, but it's a conv
e
n-
ient way to find out the latest version of the installed CLR on the machine. The pu
r-
pose of the shim is to load the right version of the CLR to execut e
a given applicat ion,
a particularly import ant task if multiple versions of the runtime are installed.

You can find the shim under %windir%
\
syst em32, where it listens to the name
"msc
o
ree.dll". By looking at the file properties, you'll find out about the la
test CLR
version on the machine.



<<03fig05.png>>



Figure
3
.
5

The version of the CLR runtime shim

Though the file description states "Microsoft .NET Runtime Execut ion Engine", this is
not t
he CLR itself, so where does the runtime itself live?

The .NET 4.0 CLR

Having a runtime shim is one thing, having the runtime itself is invaluable. All runtime
installat ions live side
-
by
-
side in the %windir%
\
Microsoft.NET
\
Framework folder. On
64
-
bit system
s there's a parallel Framework64 folder structure. Having two "bitnesses"
of the CLR and accompanying libraries is required to allow applicat ions to run either
as 32
-
bit (Windows On Windows, or WOW) or 64
-
bit.

Starting with .NET 4.0, the CLR itself is call
ed clr.dll (previously it was known as
mscorwks.dll).



<<03fig06.png>>



Figure
3
.
6

The CLR itself

The Global Assembly Cache

The GAC is where class library assemblies are loaded from for use in .N
ET applic
a-
tions. One can view the GAC under %windir%
\
assembly, but a command
-
line direct
o-
ry listing reveals the structure of the GAC in more detail. We'll discuss the role of the
GAC and the impact on your own applicat ions exhaustively further on.



<<03fig07.png>>



Figure
3
.
7

Inside the GAC

Figure 3
-
7 shows the structure of the GAC that's keeping track of the .NET 2.0 and 4.0
versions of the System.dll assembly, one of the most commonly used assem
blies in the
world of managed code development.

GAC SPLITTING

Notice the v4.0 prefix in the name of the folder containing the .NET 4.0 version of
System.dll above? This is an artifact of the "GAC splitting" carried out in .NET 4.0.
This simple naming trick

hides assemblies targeting different versions of the
ru
n
time, so that a specific version of the CLR doesn't try to load an assembly
that's incompatible with it. In the sample above, CLR 2.0 will only recognize the
first folder as a valid entry in the GAC
, while CLR 4.0 only recognizes the second
one. This truly shows the side
-
by
-
side nature of the different runtimes.

Tools

Besides the runtime and class library, a bunch of tools get installed to the framework
-
specific folder under %windir%
\
Microsoft.NET
\
Fr
amework. Though you'll only use a
fraction of those on a regular basis [em] also because most of those are ind
i
rect ly used
through the Visual Studio 2010 GUI [em] the author is of the op
i
nion it's good to know
what tools he has within reach. Our favorit e t
ool is without doubt the C# compiler,
csc.exe.



<<03fig08.png>>



Figure
3
.
8

One of the .NET Framework tools: the C# compiler

Other tools than can be found here include other compilers, the IL asse
mbler,
MSBuild, the NGEN native image generat or tool, etc.

We'll explore quite a few of the tools that come with the .NET Framework throughout
the book, so make sure to add this folder to your favorit es.

Your first application [en] take one

With the .NET F
ramework installation in place, we're ready to develop our first .NET
applicat ion. But wait a minute ... where are the development tools to make our lives
easy? That's right, for just this once we'll lead a life without development tools and go
the hardcor
e route of Notepad
-
type editors and command
-
line compilation, to illustrat e
that .NET development is not tightly bound to the use of specific tools like Visual St
u-
dio 2010. Further on in this chapter we'll get our feet back on the ground and explore
the Vi
sual Studio 2010 tooling support, which will become your habitat as a .NET d
e-
veloper moving forward.

THE POWER OF NOTEPAD

AND THE COMMAND
-
LINE

Personally, I'm a huge fan of coding with the bare minimum tools required. Any
text editor, the good old command
-
line interpreter and the C# compiler suffice to
get the job done. True, colleagues have attributed me the ability to endure a lot of
pain induced by this approach, but I'm a true believer.

But why? For a couple of reasons really. For one thing, it helps me

to memorize
co
m
monly
-
used APIs (for the more specialized ones, I keep MSDN online open).
But more importantly, the uncooperative editor forces me into a coding mode
where thinking precedes typing a single character.

For any decently sized project size, th
is approach becomes far less attractive
though. The ability to navigate code efficiently, use of auto
-
completion features,
source control support, an integrated debugging experience, etc make the use of
a professional editor like Visual Studio 2010 invalua
ble.

Yet, I'd recommend everyone to go back to the old
-
fashioned world of Notepad
and command
-
line once in a while. One day you might find yourself on an editor
-
free m
a
chine solving some hot issue and the ability to fall back to some primitive
development
mode will come in handy for sure. Anyway, that's my 5 cents.

In order not to complicat e matters, we'll stick with a simple
command
-
line console a
p-
plication for now. Most likely the majority of the applicat ions you'll write will either be
GUI applicat ions o
r web applicat ions, but console applicat ions form a great ground for
experiment at ion and prototyping.

Our workflow for building this first applicat ion will be:

[lb]

Writing the code, using Notepad.

[lb]

Using the C# command
-
line compiler to compile it.

[lb
]

Running the resulting program

Writing the code

Clichés need to be honored from time to time, so what's better than starting with a good
old "Hello World" program? Okay, let's make it a little more complicat ed by making it
a generalized "Hello" program, a
sking the user for a name to send a greet ing to.

Open up Notepad, enter the following code and save it to a file called Hello.cs:

using System;


class Program

{


static void Main()


{


Console.Write("Enter your name: ");


string name =
Console.ReadLine();


Console.WriteLine("Hello " + name);


}

}

Make sure to respect casing, as C# is a case
-
sensit ive language. In particular, if you
come from a Java or C/C++ background, make sure to spell Main with a capital M.
Without diving to

deep into the specific of the language just yet, let's go over the code
really quickly.

On the first line we have a
using directive
, used to import the System namespace. This
allows us to refer to the Console
type
further on in the code without having to
type its
full name System.Console instead.

Next, we're declaring a
class
named Program. The name doesn't really matter, but it's
common practice to name the class containing the entry
-
point of the application Pr
o-
gram. Notice the use of curly braces to mark

the start and end of the class declaration.

Inside the Program class, we declare a
static method

called Main. This special method
is recognized by the CLR as the entry
-
point of the managed code program and is where
execut ion of the program will start. Not
ice the method declarat ion is indent ed relative
to the containing class declaration. Though C# is not a white
-
space sensitive language,
it's good to be consist ent about indent at ion.

Finally, inside the Main method we've written a couple of
statements
. The
first one
makes a
method call
to the Write method on the Console type, printing the string "E
n-
ter your name: " (without the double quotes) to the screen. In the second line, we read
the user's name from the console input and
assign

it to a
local variable

c
alled name.
This variable is used in the last statement where we concat enat e it to the string "Hello "
using the +
operator
, in order to print it to the console by using the WriteLine method
on the Console type.

Compiling it

In order to run the code, we ne
ed to compile it since C# is a compiled language (at
least in today's world without an interact ive REPL loop C# tool). The act of compiling
the code will resulting in an assembly that's ready to be execut ed on the .NET runtime.

Open up a Command Prompt win
dow and change the direct ory to the place where you
saved the Hello.cs file. As an aside, the use of .cs as the extension is not a requirement
for the C# compiler, it's just a best practice to store C# code files as such.

As the search path doesn't contain

the .NET Framework installat ion folder we'll have to
enter the fully qualified path to the C# compiler, csc.exe. Recall it lives under the
framework version folder in %windir%
\
Microsoft.NET
\
Framework. Simply run the
csc.exe command, passing in Hello.cs as

the argument, as illustrat ed b
e
low:



<<03fig09.png>>



Figure
3
.
9

Running the C# compiler

MSBUILD

As we'll see further on, it happens very rarely you'll invoke the command
-
line
compilers directly
. Instead MSBuild project files are used to drive build processes.

Running it

The result of the compilat ion is an execut able called hello.exe, meaning we can run it
straight away as a Windows applicat ion. This is different from platforms like Java
where a
separat e applicat ion is required to run the compiled code.



<<03fig10.png>>



Figure
3
.
10

Our program in action

That wasn't too hard, was it? To satisfy our technical curiosity, let's have a look

at the
produced assembly.

Inspecting our assembly with .NET Reflector

Knowing how things work will make you a better developer for sure. One great thing
about the use of an intermediat e language format in the .NET world is the ability to
inspect compiled
assemblies at any point in time without requiring the original source
code.

Two commonly used tools to inspect assemblies include the .NET Framework IL Di
s-
assembler tool (ildasm.exe) and .NET Reflect or from Red Gate. For the time being,
we'll use .NET Refl
ect or which can be downloaded from the Red Gate websit e at
http://www.
red
-
gat e.com/product s/reflect or.

When you run the tool for the first time, a dialog like the one shown in Figure 3
-
11 will
appear. Here you can populate the initial list of assemblies di
splayed by .NET Refle
c-
tor. The choice doesn't really matter for our purposes, but I'd recommend to select the
v4.0 framework version as that's the one we'll be dealing with mostly exclusively in
this book.



<<03fig11.png>>



Figure
3
.
11

Populating .NET Reflector's initial assembly list

COMPACT FRAMEWORK AN
D SILVERLIGHT

There are more CLR flavors than you might expect. The CLR we're using for our
application is known as the "desktop CLR". That one
by itself has some subcat
e-
gories with optimization targeting client applications versus server workloads. B
e-
sides the desktop CLR, a trimmed down runtime exists for mobile devices
targeting ARM processors, and yet another used by Silverlight to run managed

code in various browsers. Not to mention the various other variations that exist
within M
i
crosoft for research and incubation projects. But one thing they all have
in common is support for the ECMA CLI sta
n
dard.

Once you've done this, you'll see a short l
ist of commonly used .NET assemblies being
loaded from the GAC ready for inspection. At this point, we're not really interest ed in
those assemblies but want to load our own hello.exe using File, Open. This adds "he
l-
lo" to the list of loaded assemblies, aft
er which we can start to drill down into the a
s-
sembly's structure as shown in Figure 3
-
12.



<<03fig12.png>>



Figure
3
.
12

Inspecting the assembly structure in .NET Reflector

Looking at this struc
ture gives us a good opportunity to explain a few concept s briefly.
As we drill down in the tree view, we start from the "hello"
assembly

we just compiled.
A
s
semblies are just CLR concepts by themselves and don't have direct affinity to file
-
based storage.

Indeed, it's possible to load assemblies from databases or in
-
memory
data streams as well. Hence, the assembly's name does not contain a file extension.

In our case, the assembly has been stored on disk as a file, more specifically as a file
called "hello
.exe". In .NET Reflect or we can observe this by the child node to our a
s-
sembly, which is the "hello.exe"
module
. Assemblies can consist of one or more mo
d-
ules, but the most common case is to have just one module. We won't go in detail on
this topic for now
.

Next, we encount er a node with a {} logo. This indicat es a
namespace

and is a result of
.NET Reflect or's decompilat ion intelligence, as the CLR does not know about
name
s
paces by itself. Namespaces are a way to organize the structure of APIs by
grouping t
ypes in a hierarchical tree of namespaces, for instance Sy
s-
tem.Windows.Forms. To the CLR, types are always referred to [em] e.g. in IL code
[em] by their fully
-
qualified name (like Sy
s
tem.Windows.Forms.Label). In our little
hello.exe program we didn't both
er to declare the Program class in a separate
namespace, hence .NET Reflect or shows a "
-
" to indicat e the global namespace.

Finally we arrive at our Program type with the Main method inside it. Let's have a look
at the Main method now. Select the tree node

for Main and hit the spacebar key. The
result is shown in Figure 3
-
13.



<<03fig13.png>>



Figure
3
.
13

Disassembling the Main method

The right
-
hand side pane shows the decompiled code back in C#.

It's import ant to rea
l-
ize this didn't use the hello.cs source code file at all. The hello.exe assembly doesn't
have any link back to the source files it was compiled from. "All" .NET Reflect or does,
is reconst ructing the C# code from the IL code inside th
e assembly. You can clearly
see that's the case since the Main method does only contain two statements according
to .NET Reflector, though we wrote it with three statement s instead. .NET Reflect or's
view on our assembly is semantically correct though; we c
ould equally well have wri
t-
ten the code like this.

Notice the dropdown box in the toolbar at the top. Over there we can switch to other
views on the disassembled code, e.g. plain IL. Let's have a look at that as well.



<<03fig14.png>>



Figure
3
.
14

IL disassembler for the Main method

What you're looking at now is the code as the runtime sees it in order to execut e it. A
few things to notice here are:

[lb]

Metadat a is stored with the compiled metho
d to indicat e its charact eristics:
.method tells it's a method, private controls visibility, cil reveals the use of IL
code in the method code, etc;

[lb]

The execution model of the CLR is based on an evaluat ion stack, as revealed
by the .maxst ack direct ive

and naming of certain IL instruct ions (pop and
push, not shown in our little sample);

[lb]

Method calls obviously refer to the methods being called, but observe how
there's no trace left of the C# using
-
direct ive namespace import and how all
names of meth
ods are fully
-
qualified;

[lb]

Our local variable "name" has lost its name as the execut ion engine does only
need to know about the exist ence (and type) of local variables, not their names
(the fact it shows up as "str" is due to .NET Reflect or's attempt to

be smart).

The attentive reader will have noticed a few strange things in the IL instructions for the
Main method: why are those "nop" (which stands for "no
-
operat ion") instruct ions r
e-
quired? The answer lies in the way we compiled our applicat ion, with op
timizat ions
turned off. This default mode causes the compiler to preserve the structure of the input
code as much as possible to make debugging easier. In this particular case, the curly
braces surrounding the Main method code body were emitted as nop inst
ructions,
which allows a breakpoint to be set on that line.

TIP

Explore the csc.exe command
-
line options (/?) to find a way to turn on optimiz
a-
tion and recompile the application. Take a look at the disassembler again (you
can hit F5 in .NET Reflector to re
load the assemblies from disk) and observe the
nop i
n
structions are gone.

Visual Studio 2010

Now that we've seen the hardcore way of building applicat ions using plain old text ed
i-
tors and the C# command
-
line compiler, it's time to get more realist ic by hav
ing a look
at professional tooling support provided by the Visual Studio 2010 products.


<<03figa.png>>



Ever since the very beginning of software develop ment on the Microsoft platform,
Visual Stud
io has been an invaluable tool to simplify everyday develop ment tasks si
g-
nificantly. One core reason for this is its Integrat ed Develop ment Environment (IDE)
concept, which is really an expensive word with an overloaded meaning today. While it
originally s
tood for the combinat ion of source code editing and debugging support,
today's IDE has capabilit ies that stretch a whole gamma of features such as:

[lb]

S
ource code editing

with built
-
in language su
p
port for various languages such
as C#, Visual Basic, F# a
nd C++, including things like syntax coloring, Inte
l-
liSense auto
-
complet ion, etc.

[lb]

Refactoring support

is one of the powerful tools that makes manipulat ing
code easier and allows for the restruct uring of existing code with just a few
clicks, in a (most
ly) risk
-
free manner.

[lb]

Expl ori ng code

is what developers do most of their time in the editor. Nav
i-
gating between source files is just the tip of the iceberg, with the editor provi
d-
ing means to n
a
vigat e to specific types and members.

[lb]

Visualization
of project structures bridges the gap between archit ect ure, design
and implement at ion of software. In the spirit of UML,
class designers and
architecture explorers

are available right i
n
side the tool.

[lb]

Designers

come in play when code is to be generat e
d for common tasks that
benefit from a visual development approach. Typical samples include GUI d
e-
sign, web page layout, object/relat ional mappings, workflow diagrams, etc.

[lb]

Debugging facilities

are the bread and butter for every developer to tame the
complexit ies of analyzing code behavior and (hopefully not too many) bugs by
stepping through code and analyzing the state of execut ion.

[lb]

P
roject

management

keeps track of the various items that are part of a sof
t-
ware development project, including sou
rce files, designer
-
generat ed files,
project
-
level settings, etc.

[lb]

Integrat ed
build support

is tightly integrat ed with project management fe
a-
tures and allows immediat e invocat ion of the build process to produce execu
t -
able code and feed build errors and

warnings back to the IDE.

[lb]

Source control

and
work item track
ing

are enterprise
-
level features to ma
n-
age large
-
scale collaborat ive software development project s, providing means
to check in/out code, open and close bugs, etc.

[lb]

Extensi bility

is may
be not the most visible feature of the IDE, but provides a
huge opportunity for third parties to provide extensions for virtually every a
s-
pect of the tooling support.


Editions

I feel like a market ing guy to say so, but to "differentiat e between the needs
for var
i
ous
software development groups", Visual Studio 2010 is available in different ed
i
tions.
An overview:

[lb]

Visual Studio E
xpress

Editions

are targeted at hobbyist developers and st
u-
dents, providing a great way to get rich tooling support to explore

the .NET
platform and various languages. Individual downloads for Visual C#, Visual
Basic, Visual C++ and Visual Web Developer (target ing ASP.NET web site
development ) can be found at http://www.microsoft.com/express. Notice
there's also an Express Editio
n of SQL Server, giving access to a superb rel
a-
tional database e
n
gine (with a couple of enforced restrictions).


[lb]

Visual Studio Standard Edition

is the entry
-
level edition for individual d
e-
velopers and small teams, with all the essentials for rich appl
icat ion develo
p-
ment on the .NET platform, using any of the available programming
languages. It has rich debugger support, project templat es for Windows and
web applicat ions, but lacks features like unit testing.

[lb]

Visual Studio Professi onal Edition

is a
imed at the professional developer,
giving access to the various languages in the same package. It has rich tooling
capabilit ies that stretch beyond those of the Standard Edition, including unit
testing, support for Visual Studio Tools for Office (VSTO) to

extend the O
f-
fice products using managed code, mobile device development, SQL database
project templat es, various types of applicat ion deplo
y
ment projects.

[lb]

Visual Studio Team System

is the collect ive name for the largest editions
available, target ing

large
-
scale team development. Different flavors exist, ta
r-
geting various roles within a development organizat ion, such as developers,
testers, architects and database professionals. Unique features include source
control integration, rich performance anal
ysis tools, quality metric tools, etc.
The
Visual Studio Team Suite Edition

contains all of this bundled in one
package and hence is the largest Visual Studio edition available, being a s
u-
perset of all the above. On the server side, there's
Team Foundati on

Server

(TFS) providing the necessary infrast ruct ure for work item tracking, source
control, document libraries, project metrics reporting, etc.

TLA OF THE DAY: SKU

The different editions of Visual Studio [em] and similarly for other products [em]
are ofte
n referred to as SKUs by Microsoft representatives. SKU is a TLA, a
three
-
letter acronym that is, for shelve
-
kept unit. It comes from the days software
was mostly distributed in carton board boxes that were kept on shelves in the
software store around the
corner. Today though, lots of developers get their tools
through downloads, MSDN su
b
scriptions or enterprise agreements.

In this book, we'll mainly focus on language
-

and framework
-
level aspects of pr
o-
gramming on the .NET platform, which are separat e from
the tooling support. Howe
v-
er, when covering tooling support we'll assume the reader has access to at least the
Profe
s
sional edition of Visual Studio 2010. This said, lots of the features covered (such
as debu
g
ging support to name an essential one) are avai
lable in the Express edition too.
From time to time, we'll have a peek at Team System level features as well, but in a
rather limited fashion.

Oh, and by the way, Visual Studio is available in different (natural) languages beyond
just English. Needless to
say this book will refer to the English vocabulary used in
m
e
nus, dialogs and so on.

VISUAL STUDIO SHELL

In fact, Visual Studio is a highly extensible shell for all sorts of development and
ma
n
agement tool. A sample of a tool that's built on the Visual Stu
dio environment
is the SQL Server Management Studio. To allow the use of this infrastructure for
use by 3rd party tools as well, there's the so
-
called Visual Studio Shell. One can
go even further and embed Visual Studio capabilities in a separate applicati
on by
using the Visual Studio for A
p
plications (VSTA) platform.

Expression

Applicat ions with graphical user interfaces, either for Windows or the web, are typica
l-
ly not just built by development teams. An important peer to the developer involved in
GUI dev
elopment is a professional designer working on the look and feel for the appl
i-
cation's user experience.

Platform
-
level technologies like Windows Present at ion Foundat ion (WPF), Silverlight
and ASP.NET are built with this fact in mind, allowing for rich styl
ing capabilit ies and
a separation between developer code and UI definitions, e.g. in terms of XAML. This
is a very powerful concept that enables the ability to have developers and designer
work in parallel with one another.

Though this book focuses on the
developer aspect of .NET application development,
it's important to know about the Expression family of tools that can be used by your
designer peers. More information about those tools can be found at
http://www.microsoft.com/expression.

Installing Visual

Studio 2010

Installat ion of Visual Studio 2010 should be straight forward. Assuming the reader is
using at least the Professional Edition of the product, checkboxes will be shown to i
n-
stall managed code and/or native code development support. Make sure to
check the
managed code option, or switch the options page to the more verbose mode where i
n-
dividual features can be turned on or off.



<<03fig15.png>>



Figure
3
.
15

Visual Studio 2010 Team Suite
installation options


Depending on the number of features you select (I typically do a full installation to
avoid DVD or other install media hunts afterwards), installat ion might take a while. If
you don't already have those installed, various prerequisit e
s such as the .NET Fram
e-
work will get installed as well, potentially requiring a reboot or two. But it's more than
worth the wait.

Once Visual Studio setup has complet ed, make sure to the product document ation, also
known as the MSDN Library, as well. Thou
gh the Visual Studio help system can hook
up to the online version of MSDN seamlessly, it's convenient to have the document
a-
tion installed locally if you can afford the disk space.



<<03fig16.png>>



Figure
3
.
16

MSDN Library installation option

Finally, have a go at the "Check for Service Releases" link as you might well be rea
d-
ing this book at a point where Service Packs have been released.

A quick tour through Visual Studio 2010

With Visual Stud
io 2010 installed, let's have a quick tour through the IDE you'll be
spending a lot of your time as a developer in.

What got installed

Depending on the edition you have installed, a number of tools will have been installed
in parallel with the Visual Studi
o 2010 editor itself. Figure 3
-
17 shows the Start menu
entry for Visual Studio 2010 for a Team Suite installation on a 64
-
bit machine. A few
notable entries here are:

[lb]

Visual Studio 2010 Command Prompt

provides a command prompt window
with several envi
ronment variables set, including additions to the search path
to locat e various tools such as the command
-
line compilers.

[lb]

Visual Studio 2010 Remote Debugger

is one of the author's favorit e tools
when debugging services or other types of applicat ion th
at run on a remot e
machine. It allows you to enable debugging applicat ions over the network
right from inside Visual Studio 2010.



<<03fig17.png>>



Figure
3
.
17

Visual Studio 2010 Start menu entr
ies


TIP

Have a go at the Visual Studio 2010 Command Prompt to re
-
compile our first a
p-
plic
a
tion we created earlier in this chapter. You should find that csc.exe is on the
search path so you can simply invoke it without specifying the full path.

Another too
l that got installed is ildasm.exe, the IL Disassembler. Go ahead and
use it to inspect the hello.exe assembly, looking for the Main method's IL code. As
we'll be using this tool from time to time it's good to know where you can launch it
from.

Splash scre
en and Start Page

Silly as it seems, the splash screen of Visual Studio 2010 has something useful to it,
showing the different packages that got installed. Recall Visual Studio is highly exte
n-
s
ible, so don't be surprised to see other packages showing up th
ere if you install some
extensions. A current example includes Microsoft Azure development tools (for cloud
comput ing development ) which provide various project templat es and tools that get
i
n
tegrat ed with the Visual Studio environment. This informat ion is

available from the
Help, About menu as well.



<<03fig18.png>>



Figure
3
.
18

Visual Studio 2010 splash screen

New and notable packages in Visual Studio 2010 are the built
-
in Silverlight Projects
a
nd out
-
of
-
the box support for the F# language.

CHOOSE YOUR MOTHER T
ONGUE

If this is the first time you start Visual Studio 2010, you'll be presented with a d
i
a-
log to select a settings template to configure the IDE for a specific programming
language. You c
an either stick with a general settings template, or indicate your
preferred language, your programming mother tongue so to speak. If you're pr
e-
sented with this option, feel free to go ahead and select the C# template.

All this means is some settings will
be optimized for C# projects, e.g. the default
language selection in the New Project dialog, but other languages are still avail
a-
ble to you at any point in time. Hence the word "preference".

The first thing you'll see in Visual Studio is the Start Page as
shown in Figure 3
-
19. It
pr
o
vides you with links to various tasks, e.g. to reload recent ly used projects. An RSS
feed shows news items from the MSDN websit e.

Core UI elements

The menu and toolbar contain a wealth of features we'll only cover the esse
n
tial
ones
from. Make sure to explore the menu a bit for things that catch your eyes. As we hav
e-
n't loaded any project yet, various toolbars are not vi
s
ible yet.

On the borders, various collapsible panels are docked. There are a lot of those but only
a few are v
isible at this point: Toolbox, Solut ion Explorer and Error List are the ones
we'll interact with regularly. More panels can be enabled through the View menu but
most panels have a context ual nature and will appear spontaneously when invoking
certain action
s (e.g. while debugging). Figure 3
-
20 shows how panels can be docked at
various spots in the editor. The little pushpin button on the title bar of a panel can be
used to pr
e
vent it from collapsing. As you get more familiar with the editor, you'll start
rea
rranging things quite bit to adapt to your needs.


<<03fig19.png>>



Figure
3
.
19

Visual Studio 2010 Start Page

"INNOVATION THROUGH
INTEGRATION" WITH WP
F

If you've used previous releases of Visual
Studio, you'll without doubt have n
o-
ticed the different look and feel of the IDE in the 2010 version. Starting with Visual
Studio 2010 large portions of the user interface have been redesigned to use
Windows Presentation Foundation technology.

This has sev
eral advantages on both the short and long term, and today we're
seeing just the tip of the iceberg of capabilities this unlocks. For example, by ha
v-
ing the code editor in WPF, whole new sets of visualizations become possible. To
name just one sample, i
m
ag
ine what it'd be like to have code comments with rich
diagrams in it to illustrate some data flow or architectural design.

It's worth pointing out explicitly that Visual Studio is a hybrid managed and native
(mostly for historical reasons) code application
. An increasing number of comp
o-
nents are written using managed code, and new extensibility APIs are added u
s-
ing the new Managed Extensibility Framework (MEF). Another great reason to
use managed code!



<<03fig20.png>>



Figure
3
.
20

Customizing the look and feel by docking panels

Your first application [en] take two

In order to continue our tour through Visual Studio 2010, let's make things a bit more
concret e and redo our little Hello C# applicat io
n inside the IDE.

New Project dialog

The starting point to create a new applicat ion is the New Project dialog which can be
found through File, New, Project or be invoked by CTRL
-
SHIFT
-
N. A link is available
from the Projects tab on the Start Page too.

A wh
ole load of different project types are available, also depending on the edition
used and the installat ion options select ed. Actually the number of available project
templat es has grown so much over the years, the dialog was redesigned group up in
Visual S
tudio 2010 to include features like search.

As I've select ed Visual C# as my preferred language at the first start of Visual Studio
2010, the C# templat es are shown immediat ely (for other languages, scroll down to the
"Other Languages" entry on the left).
Subcat egories are used to organize the various
templat es. Let's go over a few commonly used types of projects:

[lb]

Console Applicat ion is used to creat e command
-
line applicat ion execut ables.
This is what we'll use for our Hello applicat ion.

[lb]

Class Lib
rary provides a way to build assemblies with a .dll exte
n
sion that can
be used from various other applicat ions, e.g. to provide APIs.

[lb]

Windows Forms Applicat ion creates a project for a GUI
-
driven applicat ion
based on the Windows Forms technology.

[lb]

WPF Applicat ion is another templat e for GUI applicat ions, but based on the
new and more powerful WPF framework.

[lb]

ASP.NET Web Applicat ion provides a way to create web applicat ions and
deploy them to an ASP.NET capable web server.

As time passed by, we'l
l cover other types of templat es too, but for now those are the
most important ones to be aware of.



<<03fig21.png>>



Figure
3
.
21

New Project dialog

Notice the drop
-
down box at the top that says

".NET Framework 4.0"? This is where
the multi
-
t arget ing support of Visual Studio comes in. In this list you can select to ta
r-
get older versions of the framework, all the way back to 2.0 Give it a try and select the
2.0 ve
r
sion of the framework to see how

the dialog filters out project types that are not
supported on that version of the framework. Recall things like WPF and WCF were
added in the .NET Framework 3.0 ("WinFX") timeframe, so those won't show up when
.NET Framework 2.0 is s
e
lect ed.

For now, kee
p .NET Framework 4.0 select ed, mark the Console Application templat e
and specify Hello as the name for the project. Notice the "Creat e direct ory for solution"
checkbox? Stay tuned. We'll get to the concept of projects and solutions in a while. Just
leave i
t as
-
is for the time being. The result of creating the new project is shown in the
Figure 3
-
22.



<<03fig22.png>>



Figure
3
.
22

A new Console Application project


Once the project has been created
, it will get loaded and the first (and in this case only)
relevant file of the project will show up. In our little Console Applicat ion this is the
Program.cs file containing the managed code entry point.

Notice how an additional toolbar (known as the Text

Editor toolbar), extra toolbar
items (mainly for debugging) and menus have been made visible based on the context
we're in now.

Solution Explorer

With the new project created and loaded, make the Solution Explorer (typically docked
on the right side) visi
ble. Slightly simplified, Solut ion Explorer is a mini file explorer
showing all the files that are part of the project. In this case, that's just Program.cs. B
e-
sides the files in the project, other nodes are show as well:

[lb]

Properties

provides access to

the project
-
level settings (see further) and r
e-
veals a code file called AssemblyInfo.cs that contains assembly
-
level attri
b-
utes, somet hing we'll dive into later on.

[lb]

References

is a collect ion of assemblies the application depends on. Notice by
defaul
t quite a few references to commonly
-
used class libraries are added to
the project, also depending on the project type.



<<03fig23.png>>



Figure
3
.
23

Solution Explorer

WORRIED ABOUT UNUSED

REFER
ENCES?

People sometimes freak out when they see a lot of unused references. Our si
m-
ple Hello application will actually only use the System assembly (which contains
things like the basic data types and the Console type), so there's definitely
grounds for su
ch a worry. However, rest assured there's no performance impact
in having unused assembly references as the CLR only loads referenced asse
m-
blies when they're actually used. As time goes on, you'll get more familiar with the
role of the various assemblies t
hat have been included by default.

So, what's the relation between a solution and a project? Fairly easy: solutions are co
n-
tainers for one or more projects. In our little sample we have just a single Console A
p-
plication project within its own solution. The

goal of solutions is to be able to express
relationships between dependent projects. For example, a Class Library project might
be referred to by a Console Application in the same solution. Having them in the same
solution makes it possible to build the w
hole set of projects all at once.

SOURCE CONTROL

For those of you who'll be using Visual Studio 2010 Team System, Solution E
x-
plorer is also one of the gateways to source control, allowing to perform check
in/out oper
a
tions on items in the solution just to
name one thing.

Project Properties

Though we don't need to reconfigure project properties at this point, let's have a
glimpse at the project configurat ion system. Double
-
click the Properties node for our
Hello project in Solution Explorer (or right
-
click a
nd select Properties from the context
menu).



<<03fig24.png>>



Figure
3
.
24

Project properties


As a concret e sample of some settings, I've select ed the Build tab on the left, but feel
free to ex
plore the other tabs at this point. The reason I'm highlighting the Build co
n-
f
i
gurat ion at this point is to stress the relationship between projects and build support,
as will be detailed further on.

Code editor

Time to have a look at the center of our dev
elopment activities: writing code. Switch
back to Program.cs and have a look at the skeleton code that has been provided:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;


namespace Hello

{


class Program


{



static void Main(string[] args)


{


}


}

}

There are a few differences with the code we started from when writing our little co
n-
sole applicat ion manually.

First of all, more namespaces with commonly used types have been imported by mean
s
of using directives. Secondly, a namespace declarat ion is generat ed to contain the Pr
o-
gram class. We'll talk about namespaces in more detail in the next chapters, so don't
worry about this for now. Finally, the Main entry
-
point has a different
signature
:

i
n-
stead of not taking in any
arguments
, it now does take in a string
array

that will be
populated with command
-
line arguments passed to the resulting e
x
ecut able. As we
don't really want to use command
-
line argument s, this doesn't matter much to us. We'll
discuss the possible signat ures for the managed code entry
-
point later on.

Let's write the code for our applicat ion now. Recall the three lines we wrote before:


static void Main(string[] args)


{


Console.Write("Enter your name: "
);


string name = Console.ReadLine();


Console.WriteLine("Hello " + name);


}

As you enter this code in the editor, you'll observe a couple of things. One little feature
is auto
-
indent at ion that positions the cursor inside the
Main method indent ed a bit more
to the right than the opening curly brace of the method body. This enforces good inde
n-
tation practices (the behavior of which you can control through the Tools, Options d
i
a-
log). More visible is the presence of IntelliSense.
As soon as you type the
member
lookup

dot operator after the Console type name, a list of available members appears
that fi
l
ters out as you type.



<<03fig25.png>>



Figure
3
.
25

IntelliSense while

typing code

Once you've select ed the Write
method

from the list (note you can press ENTER or
SPACE as soon as the desired member is select ed in the list to complet e it further) and
you type the left parenthesis to supply the
arguments

to the
method call
,
IntelliSense
pops up again showing all the available
overloads

of the method. We'll learn about
overloading later on, so just type the "Enter your name: " string.

IntelliSense will help you with the next two lines of code in a very similar way as it did
fo
r the first. As you type, notice different
tokens

get colorized differently. Built
-
in la
n-
guage
keywords

are marked with blue,
type names

(like Console) have a color I don't
know the name of but looks kind of light er blue
-
ish and
string literals

are colored

with
a red
-
brown color. Actually, all of those colors can be changed through the Tools, O
p-
tions dialog.

WORRIED ABOUT UNUSED

NAMESPACE IMPORTS?

Just as with unused references, people sometimes freak out when they see a lot
of unused namespace imports. Aga
in this is not something to worry about, but for
a different reason this time. Namespaces are a compile
-
time aid only, hinting the
compiler at where to look for types that are used throughout the code. Even
though the code above has imported the System.Tex
t namespace, you won't find
a trace of it in the compiled code as we're not using any of the types defined in
that namespace.

Agreed, unused namespace imports can be disturbing when reading code, and so
Visual Studio comes with an option to weed out unused

namespace imports by
right
-
clicking the code and selecting Organize Usings, Remove Unused Usings:



<<03figb.png>>


If you try this on our code, you'll see that only the System namespace import r
e-
m
ains as we're using the Console type that resides in that namespace.

Another great feature about the code editor is its background compilation support.
While you type, a special C# compiler is running constant ly in the background to spot
code defects early
. Say we have a typo when referring to the name
variable
, it shows
up almost immediat ely being marked by red squiggles.



<<03fig26.png>>



Figure
3
.
26

The background compiler detecting a typo

In c
ase you wonder what the yellow border on the side means, it simply indicat es the
lines of code you've changed since the file was opened and was last saved. If you press
CTRL
-
S to save the file now, you'll see the lines being marked as green. This feature
h
elps you finding code you've touched in a file during a coding session by providing a
visual clue, which is quite handy if you're dealing with large code files.

Build support

As complexity of software grows, so does the build process:
besides the use of la
rge
number
s

of source files, extra tools are used to generat e code du
r
ing build, reference
s

to dependencies need to be taken care of, resulting assemblies must be signed, and so
on.

I guess the reader doesn't need to be convinced further that having integr
at ed build
support right inside the IDE is a great thing.

In Visual Studio, build is integrat ed tightly with the project system, as that's ultimat ely
the place where source files live, references are added and properties are set. To invoke
a build process,

either use the Build menu or right
-
click on the solution or a specific
project node in Solution Explorer. A shortcut to invoke a build for the entire solution is
F6. In our sample project, it doesn't really matter which way you go as the sol
u
tion
only con
sists of a single project. We'll see more complex build configurat ions in a later
chapter, where the order of the projects built as part of a solution matters.



<<03fig27.png>>



Figure
3
.
27

Star
ting a build from the project node context menu


TIP

Though launching a build after every few lines of code you write might be temp
t-
ing, I'd recommend against such a practice. For large projects this is not feasible
as build times might be quite long (thou
gh C# code compilation is relatively fast),
but more importantly this style has the dangerous potential [em] at least in the a
u-
thor's opinion [em] of making developers think less about the code they write.

Personally I try to challenge myself into writing
code that compiles straight away
without errors or even warnings. The background compilation support introduced
for C# since Visual Studio 2008 SP1 helps greatly to achieve this goal, catching
silly typos early, leaving the more fundamental code flaws some
thing to worry
about.

Behind the scenes, this build process figures out what files need to compiled, which
additional tasks need to be run, etc. Ultimat ely calls are made to various tools such as
the C# compiler. This is not a one
-
way process: warnings and

errors produced by the
underlying tools are bubbled up through the build system into the IDE, allowing for a
truly interactive development experience.



<<03fig28.png>>



Figure
3
.
28

The Error Li
st pane showing a build error

Starting
with Visual Studio 2005
,
the build system is based on a .NET Framework
technology known as
MSBuild
. One of the rationales for this integration is to decouple
the concept of project files from exclusive use in Visual S
tudio. To accomplish this, the
project file (for C# that is a file with .csproj extension) serves two goals: it's natively
recognized by MSBuild to drive build processes for the project, and Visual Studio uses
it to keep track of the project configuration
and all the files contained in it.

To illustrat e the project system, right
-
click the project node in Solut ion Explorer and
choose Unload Project. Next, select Edit Hello.csproj from the same context menu:



<<03fig29.png>>



Figure
3
.
29

Showing the proj
ect definition file



<<03fig30.png>>



Figure
3
.
30

Project file in the XML editor

In Figure 3
-
30, I've collapsed a few XML nodes in the XML editor which is built
-
in to
Visual Studio. As you can s
ee, the IDE is aware of many file format s. Also notice the
additional menus and toolbar buttons that have been enabled as we've opened an XML
file.

From this we can see that
MSBuild projects are XML files that describe the structure
of the project being bu
ild: what the source files are, required dependencies, and so
forth. Visual St
u
dio uses MSBuild files to store a project's structure and to drive its
build.

A few notable entries in this file include:

[lb]

The
Project

tag specifies the tool version (in thi
s case version 4.0 of the .NET
Framework tools, including MSBuild itself) amongst other build settings.

[lb]

PropertyGroup
s are used to define name
-
value pairs with various project
-
level configurat ion settings.

[lb]

ItemGroup
s contain a variety of items su
ch as references to other assemblies
as well as the files included in the project.

[lb]

Using an
Import

element a targets file is specified that contains the descri
p-
tion on how to build certain types of files, e.g. using the C# compiler.

You'll rarely touc
h up project files direct ly using the XML editor, but for advanced
scenarios it comes in handy to know about its exist ence. We'll have a look at MSBuild
in more depth later in this book.

Now that we know how to inspect the MSBuild project file, go ahead an
d choose "R
e-
l
oad Project" from the project's node context menu in Solution Explorer. Assuming a
successful build (correct the silly typo illustrat ed before), where can the resulting bin
a-
ries be found? Have a look at the project's folder, where you'll find
a subfolder called
"bin". Underneat h this one, different build flavors have their own subfolder:



<<03fig31.png>>



Figure
3
.
31

Build output folder


For now, we've just built one particular build

flavor: Debug. Two build flavors, more
officially known as "Solut ion Configurations", are available by default. In Debug
mode, symbol files with additional debugging informat ion are built. In Release mode
that's not the case, and optimizat ions are turned
on too. This is just the default config
u-
ration though: one can tweak settings and even creat e custom configurat ions altoget her.



<<03fig32.png>>



Figure
3
.
32
Changing the solution configuration

THE ROLE OF PDB FILE
S IN MANAGED CODE

In the introductory chapters on the CLR and managed code we stressed the i
m-
portant role metadata plays, accommodating various capabilities such a Inte
l-
l
i
Sense, rich type information, reflection facilities, etc. Given a
ll this rich
information, you might wonder how much more information is required to support
full
-
fledged debugging support. The mere fact managed code assemblies still
have PDB files [em] Program Database files, that is [em] reveals there's a need
for addi
tional "debugging symbols". One such use is to map compiled code back
to lines in the sources. Another one is to keep track of names of local variable
names, something the CLR doesn't provide metadata storage for.

One of the biggest niceties of the MSBuild

technology is the fact build can be done
without the use of Visual Studio or other tools. In fact, MSBuild ships with the .NET
Framework itself. This means one can take any Visual Studio project (since ve
r
sion
2005 to be precise) and run MSBuild direct ly
on it. That's right: Visual Studio doesn't
even need to be installed. Not only does this allow you to share out your projects with
others who may not have the IDE installed, this also opens up for automat ed build pr
o-
cesses, e.g. by Team Foundation Server (
TFS).

In fact, MSBuild is nothing more than a generic build task execut ion platform that has
built
-
in notions of dependency tracking and timestamp checking to see what parts of an
existing build are out
-
of
-
dat e (to facility increment al, and hence faster, b
uilds). The
fact it can invoke tools such as the C# compiler is because the right configurat ion files,
so
-
called target files, are present that declare how to run the compiler. Being written in
managed code, MSBuild can also be extended easily, something w
e'll have a look at
further on.

To see a command
-
line build in action, open up a Visual Studio 2010 command
prompt from the Start menu, change the directory to the location of the Hello.csproj
file and invoke msbuild.exe. The fact there's only one recogniz
ed project file extension
will cause MSBuild to invoke the build of that particular project file.



<<03fig33.png>>



Figure
3
.
33

MSBuild invoked from the command
-
line

As we already invoked a buil
d through Visual Studio for the project before, all targets
are up
-
to
-
dat e and the increment al build support will avoid rebuilding the project alt
o-
gether.

TIP

Want to see a more substantial build in action? First clean the project's build ou
t-
put by invokin
g msbuild /target:clean. Next, you can simply rebuild by issuing the
msbuild command again.

To convince yourself the C# compiler got invoked behind the scenes, turn on ve
r-
bose logging by running msbuild /verbosity:detailed. This will cause a spew of
output

to be emitted to the console, in which you'll find an invocation of csc.exe
with a bunch of parameters.

Debugging support

One of the first features that found a home under the big umbrella of the Integrat ed
D
e
velopment Environment (IDE) concept was integr
at ed debugging support on top of
the editor. This is obviously no different in Visual Studio 2010, with fabulous debu
g-
ging support facilit ies, you'll live and breathe on a day
-
to
-
day basis as a professional
developer on the .NET Framework.

The most commonl
y used debugging technique is to run the code with breakpoints set
at various places of interest. Doing so right inside a source code file is plain easy by
putting the cursor on the line of interest and pressing F9. Alternat ive approaches i
n-
clude clicking
in the gray margin on the left or using any of the toolbar or menu item
options to set breakpoint s.



<<03fig34.png>>



Figure
3
.
34

Code editor with a breakpoint set

To start a debugging session,
press F5 or click the button with the VCR Play icon
(luckily, Visual Studio is easier to program than such a retarded device). Code will run
till a breakpoint is encount ered, at which point you'll break in the debugger. This is
illustrat ed in Figure 3
-
35.

Notice a couple of the debugging facilit ies that have become available as we entered
the debugging mode:

[lb]

The
Call Stack pane

shows where we are in the execut ion of the applicat ion
code. In this simple example, there's only one stack frame for the Main

m
e
t
h-
od, but in typical debugging sessions call stacks get much deeper. By double
-
clicking entries in the call stack list one can switch back and forth b
e
tween di
f-
ferent stack frames to i
n
spect the state of the program.

[lb]

The
Locals pane

shows all the l
ocal variables that are in scope, together with
their values. More complex object types will result in more advanced visual
i-
zations and the ability to drill down into the internal structure of the object
kept in a local variable. Also, when hovering over a

local variable in the ed
i-
tor, its current value is show to make inspection of program state much easier.

[lb]

The
Debug toolbar

has become visible, providing options to continue or stop
execut ion and step through code in various ways: one line at a time,
stepping
into or over methods calls, etc.



<<03fig35.png>>



Figure
3
.
35

Hitting a breakpoint in the debugger

More advanced uses of the debugger will be topic of a later chapter, but let's highli
ght
a few from a 10,000 feet view nevert heless:


[lb]

The
Immediate Window

allows to evaluat e expressions, little snippets of
code if you want, to inspect more complex state that might not be immediat ely
apparent. For example, one could execut e a method to

find out about state in
another part of the system.

[lb]

The
Breakpoi nts
window

simply displays all breakpoints that are current ly set
and provides options for breakpoint management: the ability to remove brea
k-
points, enable or disable them.

[lb]

The
Memo
ry
window

and
Regist
ers
window

are more advanced means to
look at the precise state of the machine by inspecting memory or processor
regist ers. In the world of managed code, you won't use those very much.

[lb]

The
Disassembl y

window can be used to show the

processor instruct ions e
x
e-
cuted by the program. Again, in the world of managed code this is less rel
e-
vant (recall the role of the JIT compiler) but all in all the Visual Studio debu
g-
ger is both usable for managed and native code debugging.

[lb]

The
Thread
s Window

shows all the threads execut ing in a multi
-
t hreaded
applicat ion. Since .NET Framework 4, new concurrency libraries have been
added to System.Threading and new
Parallel Stacks and Parallel Tasks

windows have been added to assist in debugging those
as well.

Debugging is not necessarily initiated by running the application straight from inside
the editor. Instead you can attach to an already running process, even on a remot e m
a-
chine using the Remot e Debugger.

New in Visual Studio 2010 is the Debug His
tory feature which enables a time travel
mechanism to inspect the program's state at an earlier point in the execution, e.g. to
find out about some state corrupt ion that happened long before a breakpoint was hit. If
all of this sounds like voodoo, don't wo
rry as we'll explore this area in much depth.

ALTERNATIVE DEBUGGER
S

The Visual Studio IDE is not the only debugger capable of dealing with managed
code, although it's likely the most convenient one due to its rich graphical nature
allowing direct visual in
spection of various pieces of state and such.

Command
-
line savvy developers on the Windows platform will without doubt have
heard about CDB and its graphical counterpart, WinDbg. Both are available from
the Microsoft website as a separate download known a
s the "Debugger Tools for
Windows".

While the original target audience for CDB and WinDbg consist of Win32 native
code developers and driver writers, an extension for managed code ships right
with the .NET Framework. This debugger extension is known as SOS
, which
stands for "Son of Strike", with Strike being an old code
-
name for the CLR. One
can find it under the framework installation folder in a file called sos.dll. We'll have
a look at the use of SOS in the chapter on advanced debugging techniques.

Besid
es SOS, there's also a purely managed code debugger called MDbg, which
stands for Managed Debugger. This one too comes as a command
-
line d
e
bugger.
Originally meant as a sample to illustrate the use of the CLR d
e
bugger APIs, I find
it a useful tool from tim
e to time when I don't have Visual Studio installed.

Given the typical mix of technologies and tools applications are written in nowadays,
it's all important to be able to flawlessly step through various types of code, during the
same debugging session. In

the world of managed code, one natural interpret at ion of
this is the ability to step through pieces of code written in different managed languages,
such as C# and Visual Basic. But Visual Studio goes even further by providing the
ability to step through o
ther pieces of code: T
-
SQL database stored procedures, wor
k-
flow code in WF, JavaScript code in the browser, etc. Core pillars in enabling this are
the ability to debug different processes simult aneously (e.g. a web service in some web
server process, the S
QL Server database process, the web browser process running J
a-
vaScript, and so on) and the potential for setting up remote debugging sessions.

Object Browser

With the .NET Framework class libraries ever growing and lots of other libraries being
used in man
aged code applicat ions, the ability to browse through available libraries
becomes ever so import ant. We've already seen IntelliSense as a way to show available
types and their available members, but for more global searches different visualizat ions
are des
irable. Visual Studio's built
-
in Object Browser is one such tool.



<<03fig36.png>>



Figure
3
.
36

Object Browser visualizing the System.Core assembly


This tool feels a lot like .NET Reflect or wit
h the ability to add assemblies for inspe
c-
tion, browse namespaces, types and members and a way to search across all of those. It
doesn't have decompilat ion support though.

.NET FRAMEWORK SOURC
E CODE

Want to see the .NET Framework source code itself? This h
as been a longstan
d-
ing request from the community to help boost the understanding of framework
functionality and to answer to this request, Microsoft has started to make parts of
the source code for the .NET Framework available through a shared source pr
o-
g
ram starting from the .NET 3.5 release on. Even more so, Visual Studio has
been e
n
hanced to be able to step through .NET Framework source code available
from the Microsoft servers.

More information can be found on the Microsoft Shared Source Initiative for

the
.NET Framework site at
http://referencesource.microsoft.com/netframework.aspx
.

Code insight

An all
-
import ant set of features that form an integral part of IDE functionality today is
what one can refer to collect ively as "code insight" features. No mat
ter how attractive
the act of writing code may look [em] as that's what we, developers, are so excit ed
about, aren't we? [em] the reality is we spend much more time reading existing code in
an attempt to underst and it, debug or extend it. Therefore, the ab
ility to look at the code
from di
f
ferent angles is an invaluable asset to modern IDEs.

NOTE

For the samples below, we shy away from our simple Hello application since its
simplicity does not allow us to illustrate more complex software projects. Instead,
w
e use one of the sample applications that ships with Visual Studio 2010 in the
"
Microsoft Visual Studio 10.0
\
Samples
\
1033
\
CSharpSamples.zip
" compressed
file, under "

Lin
q
Samples
\
SampleQueries
".

To start with, three closely related features are directly int
egrat ed with the code editor
through the context menu. These enable navigat ing through source code in a very e