Steve Danielson Steve has been involved with programming since being introduced to theTRS-80 Model I computer in 1980 during the 6th grade, and began programming for Microsoft Windows wi
Trang 2quotations embodied in critical articles or reviews
The author and publisher have made every effort in the preparation ofthis book to ensure the accuracy of the information However, the
information contained in this book is sold without warranty, either express
or implied Neither the authors, Wrox Press, nor its dealers or distributorswill be held liable for any damages caused or alleged to be caused eitherdirectly or indirectly by this book
Trang 4Juan Ramon RavirosaJon Reid
Trang 5realized how much money was in computers compared to sports
massage, and therefore, rapidly got a job as a C++
programmer/researcher instead Simon is clearly the charitable, deep,spiritual type, who understands the true meaning of life
His programming work eventually lead him into writing, and he now
makes a living mostly from writing great books for programmers He is agreat enthusiast for C#, which he firmly believes is set to revolutionizeprogramming His spare time is spent either at dance classes (he lovesperforming arts) or on his pet project writing a computer strategy game.With what little time is left, he is an honorary research associate at
Lancaster University, where he does research in computational fluid
dynamics with the environmental science department You can visit
Simon's web site at http://www.SimonRobinson.com
Apart from the editors who've been great to work with, and who've worked incredibly hard to help bring this book out, I'd like to thank:
Joe Crump at Microsoft, for some very useful technical input andgetting a number of queries answered
Morgan Skinner for some useful suggestions for Chapter 5
Jason Sickler, a student at MIT, and alias Darrius, President of
Trang 6me used in one of the samples in Chapter 12
K Scott Allen
Over the last 10 years Scott Allen has designed software for Windows,embedded hardware, web applications, and massive multiplayer onlinegames
Scott holds an MS degree in Computer Science and an MCSD
certification He lives in Hagerstown, Maryland, with his wife Vicky, andsons Alex and Christopher
Ollie Cornes
Ollie has been working with the Internet and the Microsoft platform sincethe early 90's In 1999 he co-founded a business-to-business Internetcompany and until recently, was their Chief Technical Officer
Prior to that, his various roles involved programming, technical authoring,network management, writing, leading development projects, and
consulting He has worked with Demon Internet, Microsoft, Saab, Tesco,Travelstore, and Vodafone Ollie has a degree in computer science and isMicrosoft certified
When he's not working he spends his time devouring books on humanpotential, practicing Chinese internal martial arts, meditating, and jugglingfire
I want to say thank you to my friends and family for the support and love you've given me Life throws the good and the bad at us all, and you have made the bad stuff much easier to get past.
Jay Glynn
Jay started developing software in the late 1980's, writing applications forthe Pick operating system in Pick BASIC Since then he has created
applications using Paradox PAL and Object PAL, Delphi, Pascal, C/C++,Java, VBA, and Visual Basic Currently, Jay is a Project Coordinator and
Trang 7computers and, more recently, for ASP and server-based systems Whennot sitting in front of a keyboard, Jay is busy restoring a house in Franklin
various technologies including COM+, MSMQ, BizTalk, XML, and the.NET Framework Zach's hobbies include traveling, caving, and playinghis new XBox He can be reached at zachg@magenic.com
In 1998, Burt served as the founding editor of an online journal of
scientific research, Scientia His Master's thesis, "The Outlaw Method for
Solving Multimodal Functions with Parallel Genetic Algorithms", was
presented at the International Conference on Evolutionary Computation,and Burt has spoken on C# at Wrox conferences in Las Vegas and
Amsterdam
Trang 8Burt currently resides in Nashville, Tennessee, and can be reached at
kbharvey@mindspring.com This is his third book
Christian Nagel
Christian Nagel works as a trainer and consultant for Global Knowledge,the largest independent information technology training provider
Christian started his computing career with PDP 11 and VAX/VMS
platforms Since then he has used a variety of languages and platforms,including Pascal, C, X-Windows, Motif, C++, Java, COM/ATL, COM+,and currently C# and NET With his profound knowledge of Microsofttechnologies - he's certified as Microsoft Certified Trainer (MCT), SolutionDeveloper (MCSD), and Systems Engineer (MCSE) - he enjoys teachingothers programming and architecting distributed solutions As founder ofthe NET User Group Austria and as MSDN Regional Director he is
speaker at European conferences (TechEd, VCDC), and is contacted bymany developers for coaching, consulting, and teaching customized
courses and boot camps You will find Christian's web site at
http://christian.nagel.net/
I would like to thank the people at Wrox who got me started writing books, and Christian Seidler who supports my activities at Global
Knowledge Special thanks are also sent to the people at Microsoft, primarily to Alex Holy in Vienna for his organization of Visual Studio events and for his support of the NET user community Finally, and most importantly, I would like to thank my wife Elisabeth for her love and support.
Morgan Skinner
I started my computing at a tender age on a ZX80 at school, where I wasunderwhelmed by some code my teacher had put together and decided Icould do better in assembly language After getting hooked on Z80 (much
Trang 9Since then I've used all sorts of languages and platforms, including VAXMacro Assembler (way cool!), Pascal, Modula2, Smalltalk, x86 assemblylanguage, PowerBuilder, C/C++, Visual Basic, and currently C# I've
managed to stay in the same company for nearly 12 years, largely down
to the diversity of the job and a good working environment
In my spare time I'm a bit of a DIY nut, I spend lots of money on bicycles,and 'relax' by fighting weeds on my allotment
I can be reached by e-mail at morgan.skinner@totalise.co.uk
Karli Watson
Karli Watson is an in-house author for Wrox Press with a penchant formulticolored clothing He started out with the intention of becoming aworld famous nanotechnologist, so perhaps one day you might recognizehis name as he receives a Nobel Prize For now, though, Karli's
computing interests include all things mobile, and upcoming technologiessuch as C# He can often be found preaching about these technologies
at conferences, as well as after hours in drinking establishments Karli isalso a snowboarding enthusiast, and wishes he had a cat
Thanks go to the Wrox team, both for helping me get into writing,
and then for dealing with the results when I started Finally, and most importantly, thanks to my wife, Donna, for continuing to put up with me.
Steve Danielson
Steve has been involved with programming since being introduced to theTRS-80 Model I computer in 1980 during the 6th grade, and began
programming for Microsoft Windows with the release of Visual Basic 3.0
He is currently the Director of Architecture and Technology for Zeris
Interactive, where he develops distributed applications for Zeris' clientsusing the gamut of Microsoft DNA tools and technologies
Trang 10whenever he gets a chance He lives with his family in Wake Forest, NC,and can be reached at steve_danielson@hotmail.com
Trang 11Professional C#, Second Edition
bySimon Robinsonet al.
ISBN:0764543989
Wrox Press 2002 (1223 pages)
This book is the ideal introduction to the C#
language and the NET Framework, and will become an indispensable companion for any user of C# and NET.
Trang 13bySimon Robinsonet al Wrox Press 2002
Trang 14Introduction
Trang 15If we were to describe the C# language and its associated environment,the NET Framework, as the most important new technology for
developers for many years, we would not be exaggerating .NET is
designed to provide a new environment within which you can developalmost any application to run on Windows, and possibly in the future onother platforms too, while C# is a new programming language that hasbeen designed specifically to work with NET Using C# you can, for
example, write a dynamic web page, a component of a distributed
application, a database access component, or a classic Windows
desktop application
Don't be fooled by the NET label The NET bit in the name is there toemphasize that Microsoft believes that distributed applications, in whichthe processing is distributed between client and server, are the way
aware applications It provides a means for you to code up almost anytype of software or component that you might need to write for the
forward, but C# is not just a language for writing Internet or network-Windows platform Between them, C# and NET are set both to
revolutionize the way that you write programs, and to make programming
on Windows much easier than it has ever been
That's quite a substantial claim, and needs to be justified After all, we allknow how quickly computer technology changes Every year Microsoftbrings out new software, programming tools, or versions of Windows,with the claim that these will be hugely beneficial to developers So
what's different about NET and C#?
Trang 16bySimon Robinsonet al Wrox Press 2002
Trang 17In order to understand the significance of NET it is useful to remind
ourselves of the nature of many of the Windows technologies that haveappeared in the last ten years or so Although they may look quite
different on the surface, all of the Windows operating systems from
Windows 3.1 (introduced in 1992) through to Windows XP have the samefamiliar Windows API at their core As we've progressed through newversions of Windows, huge numbers of new functions have been added
to the API, but this has been a process of evolving and extending the APIrather than replacing it
The same can be said for many of the technologies and frameworks that
we've used to develop software for Windows too For example, COM (Component Object Model) originated as OLE (Object Linking and Embedding) At the time it was, to a large extent, simply a means by
which different types of office documents could be linked together, so thatfor example you could place a small Excel spreadsheet in your Word
a huge base of third-party software has been written for Windows, andWindows wouldn't have enjoyed the success it has had if every time
Microsoft introduced a new technology it broke the existing code base!While this backward compatibility issue has been a crucial feature ofWindows technologies and one of the strengths of Windows, it does have
a big disadvantage Every time some technology evolves and adds newfeatures, it ends up a bit more complicated than it was before
It is clear that something had to change Microsoft couldn't go on foreverextending the same development tools and languages, always makingthem more and more complex in order to satisfy the conflicting demands
of keeping up with the newest hardware, and maintaining backward
Trang 18in the early 1990s There comes a point where you have to start with aclean slate if you want a simple yet sophisticated set of languages,
environments, and developer tools, which make it easy for developers towrite state-of-the-art software
This fresh start is what C# and NET are all about Roughly speaking,.NET is a new framework - a new API - for programming on Windows.And C# is a new language that has been designed from scratch to workwith NET, as well as to take advantage of all the progress in developerenvironments and in our understanding of object-oriented programmingprinciples that has taken place over the last 20 years
Before we continue, we should make it clear that backward compatibilityhas not been lost in the process Existing programs will continue to work,and NET was designed with the ability to work with existing software.Communication between software components on Windows now almostentirely takes place using COM Taking account of this, NET does havethe ability to provide wrappers around existing COM components so that.NET components can talk to them
It is true that you don't need to learn C# in order to write code for NET.Microsoft has extended C++, and made substantial changes to VB to turn
code for J++ developers who prefer to migrate to C#.
Important If you learn the C# language, and familiarize yourself with
the NET Framework, you will find that in many cases
Trang 19coding in C# is a far more pleasant and efficient businessthan it ever was using the older languages of C++ andVB.
Trang 20bySimon Robinsonet al Wrox Press 2002
Trang 21We can best answer the question, "what is NET?" by comparing it withWindows and asking what Windows is to developers The answer to that
is twofold In the first instance, Windows is a library; it is the set of allfunction calls in the Windows API, which are available for you to use inyour program These functions provide common features such as
displaying dialog boxes, multiple-document-interface and single-document-interface windows, accessing base functions such as securityfeatures or component services, and so on In the second instance,
Windows is the environment in which your application runs, as well as theoperating system itself
In a similar way, NET is two things First, it is a library, one that is just asextensive as the Windows API You can use it to call up all the samesorts of features that have traditionally been the role of the Windows
operating system: displaying windows and dialog boxes, verifying
security credentials, calling on base operating system services, creatingthreads, and so on, as well as newer areas such as accessing databases
or connecting to the Internet or providing web services
Second, NET provides the environment ("the NET runtime") in whichyour program is run When NET-aware code is executed, it will be NETthat starts up your code, manages the running threads, provides variousbackground services, and in a real sense is the immediate environmentseen by the code You can therefore view NET as something that
provides a level of abstraction from the operating system
We should stress, however, that NET is not itself an operating system.The operating system is still Windows at least until (and unless) NETgets ported to other systems, and the Windows API is still there behindthe scenes The NET environment sits as a layer between the Windows
oriented, and easy to use framework for developing and running code Ofcourse, older applications which are not NET-aware, will continue towork with Windows and the Windows API directly just as they alwayshave done
Trang 22We've talked in general terms about how great NET is, but we haven'tsaid much about how it helps to make your life as a developer easier Inthis section, we'll discuss some of the improved features of NET in brief
Efficient Data Access – a set of NET components, collectively
known as ADO.NET, provide efficient access to relational
databases and a variety of data sources Components are alsoavailable to allow access to the file system, and to directories Inparticular, XML support is built into NET, allowing you to
Windows platforms
Trang 23security information that can indicate precisely who or what
category of user or process is allowed to call which methods onwhich classes This gives you a very fine degree of control overhow the assemblies that you deploy can be used
Zero Impact Installation – there are two types of assembly:
shared and private Shared assemblies are common librariesavailable to all software, while private assemblies are intendedonly for use with particular software A private assembly is
entirely self-contained, so the process of installing it is simple.There are no registry entries; the appropriate files are simplyplaced in the appropriate folder in the file system
Support for Web Services – NET has fully integrated support
for developing web services as easily as you'd develop any othertype of application
Visual Studio NET – NET comes with a new developer
environment, Visual Studio NET, which can cope equally wellwith C++, C#, and VB.NET, as well as with ASP.NET code VisualStudio.NET integrates all the best features of the respective
language-specific environments of Visual Studio 6
C# – C# is a new object-oriented language intended for use with
.NET
We will be looking more closely at the benefits of the NET architecture inChapter 1
Trang 24bySimon Robinsonet al Wrox Press 2002
Trang 25In one sense, C# can be seen as being the same thing to programminglanguages as NET is to the Windows environment Just as Microsoft hasbeen adding more and more features to Windows and the Windows APIover the last decade, VB and C++ have undergone expansion Although
VB and C++ have ended up as hugely powerful languages as a result ofthis, both languages also suffer from problems due to the legacies of howthey have evolved
In the case of Visual Basic, the main strength of the language is the factthat it is simple to understand, and does make many programming taskseasy, largely hiding the details of the Windows API and the COM
component infrastructure from the developer The downside to this is thatVisual Basic has never truly been object-oriented, so that large
applications quickly become disorganized and hard to maintain As well
as this, because VB's syntax was inherited from early versions of BASIC(which, in turn, was designed to be intuitively simple for beginning
become official, but it comes close Unfortunately, this has lead to twoproblems First, ANSI C++ has its roots in the state of technology over adecade ago and this shows up in a lack of support for modern concepts(such as Unicode strings and generating XML documentation), and insome archaic syntax structures designed for the compilers of yesteryear(such as the separation of declaration from definition of member
functions) Secondly, Microsoft has been simultaneously trying to evolveC++ into a language that is designed for high-performance tasks on
Windows, and in order to achieve that they've been forced to add a hugenumber of Microsoft-specific keywords as well as various libraries to thelanguage The result is that on Windows, the language has become acomplete mess Just ask a C++ developer how many definitions for a
Trang 26semicolons to separate statements The first impression of a piece of C#code is that it looks visually quite like C++ or Java code Behind that
initial similarity, however, C# is a lot easier to learn than C++, and of
comparable difficulty to Java Its design is more in tune with modern
developer tools than both of those other languages, and it has been
designed to give us simultaneously, the ease of use of Visual Basic, andthe high-performance, low-level memory access of C++ if required Some
of the features of C# include:
Full support for classes and object-oriented programming,
including both interface and implementation inheritance, virtualfunctions, and operator overloading
A consistent and well-defined set of basic types
Inbuilt support for automatic generation of XML documentation.Automatic cleanup of dynamically allocated memory
Trang 27attributes This can be useful for documentation and can havesome effects on compilation (for example, marking methods to becompiled only in debug builds)
Full access to the NET base class library, as well as easy access
to the Windows API (if you really need it, which won't be all thatoften)
Pointers and direct memory access are available if required, butthe language has been designed in such a way that you can workwithout them in almost all cases
Support for properties and events in the style of VB
Just by changing the compiler options, you can compile either to
an executable or to a library of NET components that can becalled up by other code in the same way as ActiveX controls
(COM components)
C# can be used to write ASP.NET dynamic web pages
Most of the above statements it should be pointed out do also apply toVB.NET and Managed C++ The fact that C# is designed from the start towork with NET, however, means that its support for the features of NET
is both more complete, and offered within the context of a more suitablesyntax than for those other languages While the C# language itself isvery similar to Java, there are some improvements: in particular, Java isnot designed to work with the NET environment
Before we leave the subject, we should point out a couple of limitations ofC# The one area the language is not designed for is time-critical or
extremely high performance code - the kind where you really are worriedabout whether a loop takes 1000 or 1050 machine cycles to run through,and you need to clean up your resources the millisecond they are nolonger needed C++ is likely to continue to reign supreme among low-level languages in this area C# lacks certain key facilities needed forextremely high performance apps, including the ability to specify inlinefunctions and destructors that are guaranteed to run at particular points in
Trang 28the code However, the proportion of applications that fall into thiscategory are very low.
Trang 29bySimon Robinsonet al Wrox Press 2002
Trang 30.NET will run on Windows 98, 2000, or XP In order to write code using.NET, you will need to install the NET SDK Unless you are intending towrite your C# code using a text editor or some other third party developerenvironment, you will almost certainly also want Visual Studio NET Thefull SDK isn't needed to run managed code, but the NET runtime is
needed You may find you need to distribute the NET runtime with yourcode for the benefit of those clients who do not have it already installed
Trang 31bySimon Robinsonet al Wrox Press 2002
Trang 32In this book, we start by reviewing the overall architecture of NET in thenext chapter in order to give us the background we need to be able towrite managed code After that the book is divided into a number of
sections that cover both the C# language and its application in a variety
of areas
Section I - The C# Language
This section gives us a good grounding in the C# language itself Thissection doesn't presume knowledge of any particular language, although
it does assume you are an experienced programmer We start by looking
at C#'s basic syntax and datatypes, and then discuss the object-orientedfeatures of C# before moving on to look at more advanced C#
Section III - Data Access
We look at accessing databases with ADO.NET, and at interacting withdirectories and Active Directory We also extensively cover support in.NET for XML and on the Windows operating system side, file and
registry access
Section IV - Internet Programming
Trang 33Section V - Components
Backward compatibility with COM is an important part of NET Not onlythat, but COM+ is not strictly legacy - it will still be responsible for
transactions, object pooling, and message queuing In this section we'lllook at the support NET offers for working with COM and COM+, as well
as discussing how to write C# code that interacts with these
technologies
Section VI - Advanced NET Programming
This section is the concluding part of the main body of the book andcovers some miscellaneous advanced topics These include advancedgraphics with GDI+, Windows services (formerly known as NT services),remoting, and security
Trang 34bySimon Robinsonet al Wrox Press 2002
Trang 36values to be inserted; the square braces indicate optional parameters.
Trang 37bySimon Robinsonet al Wrox Press 2002
Trang 38If you wish to directly query a problem in the book with an expert whoknows it in detail then e-mail support@wrox.com with the title of the bookand the last four numbers of the ISBN in the subject field A typical e-mailshould include the following things:
Customer Support - Your message is delivered to one of our
customer support staff, who are the first people to read it Theyhave files on most frequently asked questions and will answeranything general about the book or the web site immediately
Editorial - Deeper queries are forwarded to the technical editor
responsible for that book They have experience with the
programming language or particular product, and are able toanswer detailed technical questions on the subject Once an
issue has been resolved, the editor can post the errata to the website
The Wrox support process can only offer support to issues that are
directly pertinent to the content of our published title Support for
Trang 39questions that fall outside the scope of normal book support is providedvia the community lists of our http://p2p.wrox.com/ forum.
Trang 40bySimon Robinsonet al Wrox Press 2002