Since then, he has dedicated himself to learning all there is to know about programming, and using every programming language he couldfind, including Pascal, C, C++, Scheme, LISP, ADA, P
Trang 1By Kevin Hoffman
Publisher: Sams Pub Date: May 09, 2006 Print ISBN-10: 0-672-32776-7 Print ISBN-13: 978-0-672-32776-6 Pages: 720
Table of Contents | Index
Setting the standard for a premium C# reference, Microsoft Visual C# 2005 Unleashed
provides practical examples for virtually every aspect of the C# programming language The book is structured for progressive learning, so it can be read cover-to-cover or used as
a comprehensive reference guide You will be exposed to everything from low-level
information on the Garbage Collector to advanced concepts, such as creating applications that use Enterprise Services, creating Web Services, and even advanced Windows GUI Chapters include:
Trang 2By Kevin Hoffman
Publisher: Sams Pub Date: May 09, 2006 Print ISBN-10: 0-672-32776-7 Print ISBN-13: 978-0-672-32776-6 Pages: 720
Trang 10Microsoft® Visual C# 2005 Unleashed
Copyright © 2006 by Sams Publishing
All rights reserved No part of this book shall be reproduced,stored in a retrieval system, or transmitted by any means,
electronic, mechanical, photocopying, recording, or otherwise,without written permission from the publisher No patent
liability is assumed with respect to the use of the informationcontained herein Although every precaution has been taken inthe preparation of this book, the publisher and author assume
no responsibility for errors or omissions Nor is any liabilityassumed for damages resulting from the use of the informationcontained herein
regarded as affecting the validity of any trademark or servicemark
Microsoft is a registered trademark of Microsoft Corporation
Trang 11Every effort has been made to make this book as complete and
as accurate as possible, but no warranty or fitness is implied.The information provided is on an "as is" basis The author andthe publisher shall have neither liability nor responsibility to anyperson or entity with respect to any loss or damages arisingfrom the information contained in this book
Bulk Sales
Sams Publishing offers excellent discounts on this book whenordered in quantity for bulk purchases or special sales For
Trang 12Regardless of where the inspiration comes from or what it produces, it's still a highly creative process that is subject to writer's block and fits of irritability, crankiness, defeatism, and being so absorbed in a particular topic that the world around
Trang 13It truly is a battle, "me vs the technology." The problem is that this battle requires a huge time investment Somehow my wife has managed to tolerate me being in the same room but simply
"not being there" while I type away in order to defeat the
chapters that loom before me, daring me to take them on My daughter, Jerrah, has her own keyboard so that she can
pretend to "be busy" just like Daddy There's something
bittersweet about the fact that she wants to be like me, but that her impression of me is one of being busy and typing all the time.
My wife's patience, love, caring, and support have been
invaluable Without her support, I would've given up on writing before I even got started And certainly without her I never
would have been able to write this book, the single largest and most time-consuming book I've ever written.
Regardless of which deity you believe in, or whether you believe
in one, you must concede the existence of angels After all, I
am married to one.
Trang 14Kevin Hoffman has been programming for more than 20
years He got started when his grandfather repaired a discardedCommodore VIC-20 and he got right to work creating text-
based role-playing games in BASIC Since then, he has
dedicated himself to learning all there is to know about
programming, and using every programming language he couldfind, including Pascal, C, C++, Scheme, LISP, ADA, Perl,
Python, Java, and many others When he first saw a pre-betarelease of C# 1.0, he was hooked He knew at that momentthat the NET Framework would revolutionize how developerscreated software and how people designed software, and wouldenable new types of applications and new functionality that
either used to be impossible or too cost-prohibitive to even
attempt As a result of his passion for the NET Framework, hehas dubbed himself the ".NET Addict."
Trang 15
As the reader of this book, you are our most important critic
and commentator We value your opinion and want to know
what we're doing right, what we could do better, what areasyou'd like to see us publish in, and any other words of wisdomyou're willing to pass our way
As a publisher for Sams Publishing, I welcome your comments.You can email or write me directly to let me know what you did
or didn't like about this bookas well as what we can do to makeour books better
Please note that I cannot help you with technical problems
related to the topic of this book We do have a User Services group, however, where I will forward specific technical
questions related to the book.
When you write, please be sure to include this book's title andauthor as well as your name, email address, and phone number
I will carefully review your comments and share them with theauthor and editors who worked on the book
Trang 16Visit our website and register this book at
www.samspublishing.com/register for convenient access to anyupdates, downloads, or errata that might be available for thisbook
Trang 17
If you can force yourself to think back 10 years, think about theproliferation of technology in just that short period of time
Back in the "good ole" days, you could walk down a busy citystreet, and you probably wouldn't see anyone talking on a cellphone You wouldn't see people busily tapping at their PDAs.You definitely didn't see anyone sitting in an Internet café using
a Tablet PC to send hand-sketched application designs halfwayaround the world to a remote development team
Connectivity between applications and application componentsused to be something that required the use of extremely skilled,highly expensive development efforts Sure, we had
technologies like CORBA, but they had limited use
Today, connectivity itself has become so ubiquitous that it is
demanded When people turn on their PDA in an Internet-enabled coffee shop, they fully expect that they will be able toconnect to the Internet from there If they don'tthey will
complain to the owner When people flip open their brand newcellular phone, not only do they expect it to take photographs,but they expect to be able to upload their photos to a centrallocation to be shared with friends, family, or the entire Internet.They expect that they can download ringtones, games, evenmusic and videos If they can'tthey want their money back
This same demand for connectivity, performance, and modernfeatures can be found in desktop software and web software aswell People want their applications to follow the "It Just Works"principle They should be able to beat on and otherwise abusethat application without fear of retribution in the form of lost orcorrupted data Users want their Windows applications to workproperly whether they're connected to the Internet or not Theywant their web applications to be more responsive than theyused to be, they want them to look great, and they want them
Trang 18In short, the demands modern users are placing on the quality,features, and functionality of the applications they use havenever been more strict Programmers today must create some
of the most powerful applications ever written, and they need to
do it quickly, reliably, and cheaply
This book will take the developer through an in-depth
exploration of the features, power, and capabilities of Visual C#.NET 2005, the latest and most powerful version of the C#
language running on the NET Framework 2.0
Among many other things, by reading this book you will
Learn the fundamentals of the C# language and the corefeatures of the NET Framework 2.0, such as object-
oriented programming, generics, and other basics such asdelegates and event-driven programming
Trang 19Use remoting and/or COM+ to create distributed, connectedapplications
This book is crammed full of information on how to get you up
to speed on the newest technology It also provides you withpractical application of the technology As we all know, applying
a technology just because it's new or interesting isn't
necessarily the right thing to do As you read this book, you will
be introduced to the new technology from the ground up
(learning to walk before you can run), as well as learning wherethat technology makes sense and when it should be applied
Trang 20However, many of the later chapters in the book build on
technologies and techniques introduced in earlier chapters,
making this book ideally suited to being read from start to
finish
Trang 22If you already have a working knowledge of the C# languagefrom your experience with previous versions (either 1.0 or 1.1),you can skip this chapter and move on Take care not to skiptoo many of the early chapters, as there have been
enhancements to the language that are covered early on in thebook, such as generics and anonymous methods This chapteralso skips over some details that you may not be aware of ifyou have very little exposure to programming If you have
never written software on the Windows platform (either
Windows or Web-based), this is the wrong chapter, and perhapsthe wrong book, for you
Trang 23Before you learn the mechanics of the C# language itself, it isimportant that you learn the evolution of technologies that
created the need for a language like C# This section takes you
on a quick tour of the history of C#, followed by an explanation
of the Common Language Runtime, the Common Type System,and concluding with an overview of garbage-collected
environments
The Evolution of NET
Before the NET Framework was released to the public, the
majority of component-oriented development for the Windowsplatform took the form of COM objects Component Object
Model (COM), a binary standard for creating reusable
components, allowed developers to write code that solved
smaller problems in smaller problem domains By breaking
down the problem into components, the solution often becameeasier and the components used to solve the problem could bereused to solve other similar problems
COM offered many advantages and disadvantages One of themost common problems with the COM standard was
appropriately dubbed "DLL hell." DLL hell arose when COM
interfaces were indexed in the registry and then newer versions
of those components were released Versioning often causeddevelopers headaches due to the tightly coupled, binary nature
of the standard In addition, if a DLL's location changed on thefile system without the information in the registry being
modified, the COM interfaces contained within that DLL wouldbecome inaccessible You could see examples of this when anew application was installed with a different version of someshared component, and it would not only break the new
Trang 24Other problems with development at the time included thingslike difficulty managing memory, slow development times, GUIcontrols that were typically insufficient for many tasks, as well
as a lack of interoperability between languages such as C++and Visual Basic
As a solution to this and countless other problems with
development at the time, Microsoft began working on what was
then referred to as COM+ 2.0 The solution would provide a
managed environment in which code would be executed thatwould provide for enhanced type safety, security, and an
incredibly extensive library of useful classes and functions tomake the lives of developers much easier Eventually this
solution became what is now the NET Framework Versions 1.0and 1.1 have been released and now version 2.0 is available Inthe next few sections, some of the key aspects of the NET
Framework will be discussed: the Common Language Runtime,the Common Type System, and the concept of garbage-
collected managed code
The Common Language Runtime
Before talking about the basics of C#, you need to know a littlebit about how C# (and all other NET languages) works and
where it sits in relation to the various components that makethe entire NET Framework run
One such component is the Common Language Runtime (almost
exclusively referred to as the CLR) Unlike previous versions ofC++ and similar languages, C# runs in a managed
environment Code that you write in C# runs inside the context
of the Common Language Runtime The runtime is responsiblefor managing things like memory and security and isolating
Trang 25Library The BCL (Base Class Library) is the collection of classesand utilities written in the NET Framework that provide youwith the fundamentals you need in order to create your
applications, such as code to allow you to deal with encryption,data access, file I/O, web applications, Windows applications,and much more As you will see throughout the book, much ofthe task of learning C# isn't learning the language syntax; it'slearning about the vast library of the BCL In short, the CLR isthe managed execution engine that drives the code written inthe BCL and any applications you create
Don Box has written an excellent book on the Common
Language Runtime that gives all the detail you can possibly
imagine on what the CLR is and how it works The book is called
Essential NET Volume I: The Common Language Runtime
Trang 26The Common Type System
A common problem in many programming languages is the
inability to exchange data between programs written in differentlanguages For example, you have to take special precautionswhen invoking C methods from Pascal, and Pascal methods
from C because of parameter ordering In addition, strings in Cconsist of an array of characters that are terminated with theASCII NULL (typically represented as \0) In Pascal, the firstbyte of a string actually contains the length of the string Theseproblems are just the tip of the iceberg As you can tell, gettingdifferent languages to communicate with each other can be anightmarish task (and, historically, it has been)
languages creates an environment where VB.NET and C# codecan coexist side by side without any communication issues
Taking Out the Trash: Coding in a Garbage-Collected Environment
As I mentioned earlier in this section, the CLR does quite a bit
of memory management on your behalf If you have used C#1.0 or 1.1, you will be familiar with this concept One of the
components of the CLR is the Garbage Collector When you
Trang 27collection cycle takes place, the Garbage Collector examinesyour variables and if they are no longer in use, it will dispose of
them (referred to as a collection) In Chapter 16, "Optimizingyour NET 2.0 Code," you will learn more about the GarbageCollector (GC) and how awareness of its presence while codingand designing can improve the speed of your applications Fornow, it is good enough to know that the GC is there managingyour memory and cleaning up after you and your variables
Trang 28
My favorite analogy for explaining variables is the "bucket"
analogy Think of a variable as a bucket Into that bucket, youcan place data Some buckets don't care what kind of data youplace in them, and other buckets have specific requirements onthe type of data you can place in them You can move data fromone bucket to another Unfortunately, the bucket analogy gets alittle confusing when you take into account that one bucket cancontain a little note inside that reads "see Bucket B for actualdata" (you'll read about reference types shortly in the section
"Value Types vs Reference Types")
To declare a variable in C#, you can use the following syntax:type variable_name;
virtually unlimited
Trang 29Table 1.1 Core NET Data Types Data Type Description
Trang 30organizes all types into namespaces A namespace is a logical
container that provides name distinction for data types Thesecore data types all exist in the "System" namespace You'll seemore namespaces throughout the book as you learn aboutmore specific aspects of NET
Type Shortcuts
C# provides you with some shortcuts to make declaring some
word lowercase aliases that, when compiled, will still represent
of the core data types easier These shortcuts are simple one-a core NET type Table 1.2 lists some data type shortcuts andtheir corresponding NET types
Trang 31experience) the actual data contained in the heap Reference
types are generally larger and slower than value types Learningwhen to use a reference type and when to use a value type issomething that comes with practice and experience
Trang 33You will learn a lot of C# syntax tricks as you progress throughthe book This section introduces you to the most basic
concepts required to create the simplest C# applicationthe
canonical "Hello World" sample
Code Blocks
As you know, all programming languages work on the samebasic principle: individual instructions are executed in sequence
to produce some result Instructions can be anything from
defining a class to printing information to the Console output
In C#, multiple lines of code are grouped together into a logicalexecution block by wrapping the lines of code with the "curlybrackets" or braces: the { and } symbols
The Canonical "Hello World" Sample
It seems as though virtually every book on a programming
language starts off with a program that prints the phrase "HelloWorld" to the console Rather than risk horrible karma and
unknown repercussions from breaking with tradition, I am going
to inflict my own version of "Hello World" upon you
To start, open up whatever 2005 IDE you have (C# Express
2005, or any of the Visual Studio 2005 editions) and create anew Console Application (make sure you select C# if you havemultiple languages installed) called HelloWorld Make sure thatyour code looks the same as the code shown in Listing 1.1
Trang 36Web applications Create amazingly powerful, rich, full-featured web applications in the shortest amount of timeever, taking advantage of new features like Web Parts,
Mobile applications Create web applications that
automatically recognize mobile platforms and adapt to thesmall form factor and limited capacity of PocketPCs andcellular phones
Mobile clients Create applications that target the PocketPCplatform and can not only communicate with other desktopapplications, but can also communicate with the Internet,consume web services, and interact with SQL databases
Trang 37productivity, performance, and reliability
Integration applications Take advantage of COM
Interoperability as well as NET-based APIs to integrate yourown code with other applications such as Office 2003,
SharePoint Portal Server 2003, and much, much more
Trang 38
This chapter provided you with a brief introduction to the world
of the NET Framework and C# 2.0 You read about how the.NET Framework evolved as well as what it is now In addition,you were introduced to the Common Language Runtime, theGarbage Collector, the Common Type System, and finally a verysmall introductory application
This chapter has provided you with the basic foundation thatyou will need in order to continue learning about C# 2005 byprogressing through this book
Trang 39
of how to accomplish both of these types of tasks using the C#language
If you have any familiarity with programming languages at all,the concepts discussed in this chapter should seem familiar andwill be easy for you to pick up the C# syntax If you have
already been using C# for some time, you should be able toskim this chapter briefly as a refresher before continuing onthrough the rest of the book
Trang 40Every modern programming language supports the notion ofbranching and conditional logic This gives your applications theability to do different things based on current input, events,error conditions, or any condition that can be expressed
logically This section first shows you how C# allows you to formlogical expressions and how to create code blocks that are
executed conditionally based on those expressions Then you'llsee a couple of shortcuts and extras that C# contains to makeusing certain types of common logic statements even easier
Introduction to Boolean Expressions
A Boolean expression is a code statement that will eventuallyevaluate to either true or false At the most basic level, all
Boolean expressions, no matter how long or complex, are stillgoing to evaluate to either true or false
The simplest of all Boolean expressions is equality This
expression is used to test whether or not one value is
equivalent to another value This can be something simple, suchas
2 == 4
This expression will evaluate to false because 2 is not equal to
4 It can also be something complex, such as
MyObject.MyProperty == YourObject.YourProperty