Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Visual CSharp .NET Developer's Handbook (2002) [eng]

.pdf
Скачиваний:
35
Добавлен:
16.08.2013
Размер:
4.94 Mб
Скачать

Visual C# .NET Developer's Handbook

John Paul Mueller

Associate Publisher: Richard Mills

Acquisitions and Developmental Editor: Denise Santoro Lincoln

Editor: Colleen Wheeler Strand

Production Editor: Kylie Johnston

Technical Editor: Ross Russell Mullen

Graphic Illustrator: Tony Jonick

Electronic Publishing Specialist: Nila Nichols

Proofreaders: Amey Garber, Dave Nash, Laurie O'Connell, Yariv Rabinovitch, Nancy

Riddiough

Indexer: Ron Strauss

CD Coordinator: Dan Mummert

CD Technician: Kevin Ly

Cover Designer: Carol Gorska/Gorska Design

Cover Photographer: Glen Allison/PhotoDisc

Copyright © 2002 SYBEX Inc., 1151 Marina Village Parkway, Alameda, CA 94501. World rights reserved. The author created reusable code in this publication expressly for reuse by readers. Sybex grants readers limited permission to reuse the code found in this publication or its accompanying CD-ROM so long as the author is attributed in any application containing the reusable code and the code itself is never distributed, posted online by electronic transmission, sold, or commercially exploited as a stand-alone product. Aside from this specific exception concerning reusable code, no part of this publication may be stored in a retrieval system, transmitted, or reproduced in any way, including but not limited to photocopy, photograph, magnetic, or other record, without the prior agreement and written permission of the publisher.

Library of Congress Card Number: 2002103166

ISBN: 0-7821-4047-5

SYBEX and the SYBEX logo are either registered trademarks or trademarks of SYBEX Inc. in the United States and/or other countries.Screen reproductions produced with FullShot 99. FullShot 99 © 1991-1999 Inbit Incorporated. All rights reserved.FullShot is a trademark of Inbit Incorporated.

The CD interface was created using Macromedia Director, COPYRIGHT 1994, 1997-1999 Macromedia Inc. For more information on Macromedia and Macromedia Director, visit http://www.macromedia.com.

Internet screen shot(s) using Microsoft Internet Explorer 5.5 reprinted by permission from Microsoft Corporation.

TRADEMARKS: SYBEX has attempted throughout this book to distinguish proprietary trademarks from descriptive terms by following the capitalization style used by the manufacturer.

The author and publisher have made their best efforts to prepare this book, and the content is based upon final release software whenever possible. Portions of the manuscript may be based upon pre-release versions supplied by software manufacturer(s). The author and the publisher make no representation or warranties of any kind with regard to the completeness or accuracy of the contents herein and accept no liability of any kind including but not limited to performance, merchantability, fitness for any particular purpose, or any losses or damages of any kind caused or alleged to be caused directly or indirectly from this book.

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2 1

SOFTWARE LICENSE AGREEMENT: TERMS AND CONDITIONS

The media and/or any online materials accompanying this book that are available now or in the future contain programs and/or text files (the "Software") to be used in connection with the book. SYBEX hereby grants to you a license to use the Software, subject to the terms that follow. Your purchase, acceptance, or use of the Software will constitute your acceptance of such terms.

The Software compilation is the property of SYBEX unless otherwise indicated and is protected by copyright to SYBEX or other copyright owner(s) as indicated in the media files (the "Owner(s)"). You are hereby granted a single-user license to use the Software for your personal, noncommercial use only. You may not reproduce, sell, distribute, publish, circulate, or commercially exploit the Software, or any portion thereof, without the written consent of SYBEX and the specific copyright owner(s) of any component software included on this media.

In the event that the Software or components include specific license requirements or end-user agreements, statements of condition, disclaimers, limitations or warranties ("End-User License"), those End-User Licenses supersede the terms and conditions herein as to that particular Software component. Your purchase, acceptance, or use of the Software will constitute your acceptance of such End-User Licenses.

By purchase, use or acceptance of the Software you further agree to comply with all export laws and regulations of the United States as such laws and regulations may exist from time to time.

Reusable Code in This Book

The author(s) created reusable code in this publication expressly for reuse by readers. Sybex grants readers limited permission to reuse the code found in this publication or its accompanying CD-ROM so long as the author(s) are attributed in any application containing the reusable code and the code itself is never distributed, posted online by electronic transmission, sold, or commercially exploited as a stand-alone product.

Software Support

Components of the supplemental Software and any offers associated with them may be supported by the specific Owner(s) of that material, but they are not supported by SYBEX.

Information regarding any available support may be obtained from the Owner(s) using the information provided in the appropriate read.me files or listed elsewhere on the media.

Should the manufacturer(s) or other Owner(s) cease to offer support or decline to honor any offer, SYBEX bears no responsibility. This notice concerning support for the Software is provided for your information only. SYBEX is not the agent or principal of the Owner(s), and SYBEX is in no way responsible for providing any support for the Software, nor is it liable or responsible for any support provided, or not provided, by the Owner(s).

Warranty

SYBEX warrants the enclosed media to be free of physical defects for a period of ninety (90) days after purchase. The Software is not available from SYBEX in any other form or media than that enclosed herein or posted to www.sybex.com. If you discover a defect in the media during this warranty period, you may obtain a replacement of identical format at no charge by sending the defective media, postage prepaid, with proof of purchase to:

SYBEX Inc.

Product Support Department 1151 Marina Village Parkway Alameda, CA 94501

Web: http://www.sybex.com

After the 90-day period, you can obtain replacement media of identical format by sending us the defective disk, proof of purchase, and a check or money order for $10, payable to SYBEX.

Disclaimer

SYBEX makes no warranty or representation, either expressed or implied, with respect to the Software or its contents, quality, performance, merchantability, or fitness for a particular purpose. In no event will SYBEX, its distributors, or dealers be liable to you or any other party for direct, indirect, special, incidental, consequential, or other damages arising out of the use of or inability to use the Software or its contents even if advised of the possibility of such damage. In the event that the Software includes an online update feature, SYBEX further disclaims any obligation to provide this feature for any specific duration other than the initial posting.

The exclusion of implied warranties is not permitted by some states. Therefore, the above exclusion may not apply to you. This warranty provides you with specific legal rights; there may be other rights that you may have that vary from state to state. The pricing of the book with the Software by SYBEX reflects the allocation of risk and limitations on liability contained in this agreement of Terms and Conditions.

The GIF Construction Set and Graphic Workshop software included with this publication is provided as shareware for your evaluation. If you try this software and find it useful, you are requested to register it as discussed in its documentation and in the "About" screen(s) of the application(s). Sybex has not paid the registration fee for this software.

Shareware Distribution

This Software may contain various programs that are distributed as shareware. Copyright laws apply to both shareware and ordinary commercial software, and the copyright Owner(s) retains all rights. If you try a shareware program and continue using it, you are expected to register it. Individual programs differ on details of trial periods, registration, and payment. Please observe the requirements stated in appropriate files.

Copy Protection

The Software in whole or in part may or may not be copy-protected or encrypted. However, in all cases, reselling or redistributing these files without authorization is expressly forbidden except as specifically provided for by the Owner(s) therein.

This book is in loving memory of Esther Darneal (1916-2002).

Acknowledgments

Thanks to my wife, Rebecca, for working with me to get this book completed during an exceptionally difficult time. I really don't know what I would have done without her help in researching and compiling some of the information that appears in this book (especially the Glossary). She also did a fine job of proofreading my rough draft and page-proofing the final result.

Russ Mullen deserves thanks for his technical edit of this book. He greatly added to the accuracy and depth of the material you see here. I really appreciated the time he devoted to checking my code for accuracy. Russ also supplied some of the URLs you see in the book and other helpful tips and hints.

Matt Wagner, my agent, deserves credit for helping me get the contract in the first place and taking care of all the details that most authors don't really consider. I always appreciate his help. It's good to know that someone wants to help.

Finally, I would like to thank Denise Santoro Lincoln, Kylie Johnston, Colleen Strand, and the rest of the Sybex production staff, including Nila Nichols, Kevin Ly, and Dan Mummert, for their assistance in bringing this book to print. It's always nice to work with such a great group of professionals.

Introduction

Frustration! It's one word that I've used to describe many of my development experiences.

Anyone who's worked with Visual Studio fully knows about the two-language dilemma that it poses. At the one end of the development experience, Visual Basic makes development relatively easy and fast, but it lacks the low-end connectivity I often need without performing a lot of additional programming. At the other end of the development continuum, Visual C++ makes it relatively easy to gain low-level access to anything in the Windows environment, but development is a time-intensive task requiring Machiavellian expertise.

What most developers need is a Reese's Peanut Butter Cup programming experience-two tastes in one. C# provides that flavor-combining programming experience in many ways; you

gain the rapid application development environment of Visual Basic combined with the lowlevel language support of Visual C++. One of the main purposes of this book is to share that two-tastes-in-one experience with you.

Take the Grand Tour

I'm assuming that many of you have already programmed in Visual Basic or Visual C++ (or perhaps even both) and found the experience lacking in some fundamental way. C# is a great development language, but it's by no means perfect. I'll still use Visual C++ to develop native unmanaged applications and components that need that last ounce of performance. Visual Basic is still my development language of choice for quick prototyping and some database management tasks. However, for the vast majority of my programming needs, C# fills a need that the other two languages can't (without a lot of extra effort). Of course, the trick is learning where C# fits into your language toolkit.

We'll take the grand tour of C# programming capabilities in this book. I won't bore you with fundamentals such as basic code construction or learning how to create programming loops. We will discuss everything from basic utility applications to complex database applications that use OLE-DB, ODBC.NET, ADO, or ADO.NET as a basis for communication. Some of the applications will provide a view of the local programming environment, while others will provide a view of the Internet and distributed application development in all its glory. By the time you finish Chapter 17, you'll know that C# is a language for every environment-from the desktop to the PDA.

Some Extras to Consider

You'll also find three interesting appendices in the back of the book. The first two will help those of you who are used to working with Visual C++ or Visual Basic make the adjustment to C#. You'll learn how C# differs from these two languages and about some of the common problems that other developers have faced when making the transition. The third appendix will show how you can create a complex application that Microsoft doesn't even mention in the Visual Studio .NET help files-the Microsoft Management Console (MMC) snap-in. I placed this example in an appendix because it isn't a pure C# application-some applications still require the use of Visual C++ to make some underlying connections, and this is one of them.

C# is a new programming language. While it does resemble languages of the past, it's truly a new language for a new age of application development. This book is your guide to a larger world of C# application development. You'll learn how to create many types of applications, but more importantly, you'll learn how unique C# is and how it can help you overcome modern application development problems that older languages are ill equipped to handle.

Who Should Read This Book?

I'll begin by saying that, as I write this, there are many good books for novices on the market, and I have consequently decided not to discuss the same issues that those other texts already cover. This book specifically addresses the needs of those who already know something about C# or at least those who have decided to move from another Visual Studio language such as Visual C++ or Visual Basic. If you've never programmed before, you'll probably find that you'll get lost by the time you reach the end of the first chapter.

As mentioned in the first part of the Introduction, this book provides the grand tour of C#. I've designed it to show you how to put a variety of application types together in a short time and with little effort. We'll explore the capabilities of C# by looking at a wealth of programming examples. Every chapter has several examples, most of which show a specific set of C# features. Most intermediate-to-expert level developers who have some experience in other languages and want to learn what C# can do for them will gain something by reading this book.

Some experts will find that this book doesn't answer every question. If you have already read every C# book on the market and regularly develop complex applications using C#, I don't have a lot to offer in the way of truly strange development tricks (unless you consider the example in Appendix C). This is a book that shows how to perform typical programming tasks. For example, the database examples show how to create multiple views of the same data, add, remove, and update records, and perform some mandatory tasks such as printing. The example won't show you how to create a complex connection between your mainframe, a minicomputer, and several web server farms-I simply don't get into that much detail.

Tools Required

There are some assumptions that I've made while writing the application programming examples in this book. You need at least two machines: a workstation and a server. This twomachine setup is the only way that you'll see C# in action and truly know it works as anticipated. In addition, your development workstation and server must meet the minimum

.NET requirements (and hopefully provide more than the minimum). You might experience problems with the database and other large examples if you're running a minimal machine configuration.

During the writing of this book, I used a Windows 2000 and Windows XP workstation. There's no guarantee that any of the code in the book will work with Windows 9x, although most of it will. The server was loaded with Windows 2000 Server with the latest patches and service packs installed. You'll need a Pocket PC-compatible PDA to work with the examples in Chapter 17. You must install the latest service packs for all products before the examples will work properly. .NET is a new technology and relies on the latest versions of many DLLs and the .NET Framework.

Note Many of the concepts you'll learn in this book won't appear in your online documentation. Some of it's so new that it only appears on selected websites. You'll find either a tip or a note alerting you to the location of such information throughout the book. In addition, Microsoft made some material available only through selected channels like MSDN subscriptions. Other pieces of information are simply undocumented, and you won't find them anywhere except within a newsgroup when someone finds a feature accidentally.

I tested all of the examples in this book with Visual Studio .NET Enterprise Architect Edition. None of these examples are guaranteed to work with any other programming language products and none of them will work with the educational versions of Visual Studio.

Some of the example programs rely on a database manager. I used Microsoft Access for many of the examples in this book for the sake of simplicity. Other examples rely on SQL Server 2000 so that you can see the power C# when working in the database management

environment. The CD contains copies of all of the Access databases and scripts for reproducing the SQL Server 2000 databases used in this book.

Conventions Used in This Book

It always helps to know what the special text means in a book. In this section we'll cover usage conventions. This book uses the following conventions:

Inline Code Some code will appear in the running text of the book to help explain application functionality. The code appears in a special typeface that makes it easy to see. This monospaced font also makes the code easier to read.

Inline Variable As with source code, variables that appear inline will also use a special typeface that makes them stand out from the rest of the text. When you see monospaced text in an italic typeface, you can be sure it's a variable of some sort.

User Input Sometimes I'll ask you to type something and designate it with this typeface. For example, you might need to type a particular value into the field of a dialog box. This special font helps you see what you need to type.

[Filename] When you see square brackets around a value, switch, or command, it means that it's an optional component. You don't have to include it as part of the command line or dialog field unless you want the additional functionality that the value, switch, or command provides.

Filename A variable name is a value that you need to replace with something else. For example, you might need to provide the name of your server as part of a command-line argument. Because I don't know the name of your server, I'll provide a variable name instead. The variable name you'll see usually provides a clue as to what kind of information you need to supply. In this case, you'll need to provide a particular filename.

FileOpen Menus and the selections on them appear with a special menu arrow symbol. "FileOpen" means "Access the File menu and choose Open."

italic You'll normally see words in italic if they have special meaning or this is the first use of the term and its accompanying definition. Always pay special attention to words in italic, because they're unique in some way.

monospace Some words appear in a monospace font because they're easier to see, they require emphasis of some type, or to immediately let you know they aren't standard English words. For example, all filenames in the book appear in a monospace font to make them easier to read.

URLs URLs will normally appear highlighted so that you can see and refer back to them with greater ease. The URLs in this book provide sources of additional information designed to make your development experience better. URLs often provide sources of interesting information as well.

Notes, Tips, and Warnings

This book contains many notes, tips, and warnings to provide you with particularly significant information. The following paragraphs describe the purpose of each.

Note Notes tell you about interesting facts that don't necessarily affect your ability to use the other information in the book. I use note boxes to give you bits of information that I've picked up while using C#, Windows 9x, Windows 2000, or Windows XP.

Tip Everyone likes tips because they tell you new ways of doing things that you might not have thought about before. A tip box might also provide an alternative way of doing something that you might like better than the first approach I provided.

Warning Warnings almost always tell you about some kind of system or data damage that'll occur if you perform a certain action (or fail to perform others). Make sure you understand a warning thoroughly before you follow any instructions that come after it.

You'll also find that I use notes and tips to hold amplifying information. For example, many of the URLs in this book appear as part of a note or a tip. The Internet contains a wealth of information, but finding it can be difficult, to say the least. URLs within notes and tips help you find new sources of information on the Internet that you can use to improve your programming or to learn new techniques. You'll also find newsgroup URLs that tell where you can find other people to talk with about C#. Finally, URLs will help you find utility programs that'll make programming faster and easier than before.

About the Author

I really enjoy learning computer technology and telling others what I have learned. So far, I've produced 54 books and over 200 articles that help other people understand computers and the computer industry. The topics I've covered range from networking to artificial intelligence and from database management to heads-down programming. Variety is the spice of life, so I've also written a number of user-level books. As part of my personal development, I've helped over 25 of my fellow authors by technically reviewing their books. Besides providing technical editing services to both Data Based Advisor and Coast Compute magazines, I've also contributed articles to magazines like SQL Server Professional, Visual C++ Developer, and Visual Basic Developer. I'm currently the editor of the .NET electronic newsletter for Pinnacle Publishing.

When I'm not working at the computer, you can find me in my workshop, enjoying woodworking and candle-making. On any given afternoon, I might be working at a lathe or putting the finishing touches on a bookcase. One of my newest craft projects is glycerin soap making, which comes in handy for gift baskets.

How to Contact the Author

You can e-mail me with your suggestions and comments at JMueller@mwt.net. I'm also setting up a website at http://www.mwt.net/~jmueller/. Feel free to look and make suggestions on how I can improve it. One of my current projects is creating book FAQ sheets that should help you find the book information you need much faster.

Part I: An Overview of C#

Chapter List

Chapter 1: Introduction to C#

Chapter 2: Working with the .NET Architecture

Chapter 3: A Quick View of Classes

Chapter 4: Advanced Class Topics

Chapter 1: Introduction to C#

Overview

Most developers have at least heard about C#, and many have already written a "Hello World" application or two with it. C# is the newest language in the developer's toolbox. This is an exciting language because it fixes problems that developers have had with older languages when working in the distributed application environment. Microsoft designed C# from the ground up for use in a distributed application environment of the sort that developers use today. You'll find that C# combines the ease-of-use features of Visual Basic with the lowlevel programmability of C++. This chapter provides you with a brief overview of why C# is important and when you would use it. You can easily skip this chapter if you want to start coding right away.

Why Introduce Another Language?

One of the biggest questions that developers need to answer is why they need yet another language. The computer world is literally swimming in computer languages of various types. You can find a language to do just about anything today, and some of them do more than one task well. However, the problem isn't one of a need for new language constructs. Languages such as Visual Basic, Java, and C++ have the bases covered in that arena. In fact, C# detractors rightly point out that C# is the Microsoft version of Java, although we'll see that the similarities are superficial as the book progresses.

C# is an answer to a new problem: developers need a language that works well in a distributed programming environment. Applications no longer sit alone on local area networks (LANs) or in remote access scenarios between satellite offices. The application you build today might be in use on a partner corporation desktop tomorrow. The biggest problem developers face is that they really don't know where the application will end up. The application they create at design time may end up performing other tasks later on. The decision to move the application comes later, long after you've finished writing it. Consequently, the application has to be robust enough to work in remote settings across company boundaries.

Companies also force developers to complete applications faster today. In days gone by, it wasn't unusual for an application development cycle to last a few years. Today, companies measure application delivery schedules in months, and the developer doesn't get many of them. C# helps developers produce more code more quickly than ever before. However, producing code quickly doesn't buy you much on its own; the code must also be free of bugs, and C# helps answer that need as well.

Note Don't believe all the hype about C#-it doesn't free you from every bug that ever existed and the presence of a debugger in Visual Studio .NET is confirmation of this fact. Microsoft has made vast improvements in debugging and application automation with C#. However, bugs are an ever-present enemy of the developer, and it's unlikely this situation will change any time soon. It's true that C# reduces the chance of a memory error because the .NET Framework provides management resources in this area. Unfortunately, the need to access existing API functionality means you don't always gain the full .NET Framework functionality, and the .NET Framework introduces new problems such as non-deterministic finalization-the inability of the developer to determine when the .NET Framework will destroy an object. Bugs are part of C#, they just have a new form.

In some respects, Microsoft is attempting to create that mystical language that serves all needs for everyone. When they first began to talk about C#, Microsoft presented it as a wonder language. The truth is that C# sits somewhere between Visual Basic and Visual C++ in capabilities. You gain the programming environment of Visual Basic with C#. Developing an application is no longer a painful experience fraught with odd coding techniques that create even odder bugs. On the other hand, you also gain much of the low-level functionality of C++. Unlike Visual Basic, where every attempt to use the Windows API is a major development experience, C# provides the same level of access that C++ does.

The question is whether C# is actually the wonder language that Microsoft thinks it is. For the most part, C# is a vast improvement over previous languages and it has many new features to offer. You'll find that it's a valuable addition to your programmer toolkit. However, I'd stop short of saying it's a one-size-fits-all language. For one thing, you can't create a native EXE file with C#, which is a problem for certain types of application development. In short, C# is a new addition to your existing toolkit, but you'll probably want to keep Visual C++ and Visual Basic around as well.

Design Goals for C#

Like any other development scenario, Microsoft had specific goals in mind when it created C#. The programmers at Microsoft realized that current languages lacked features that developers needed when writing applications for distributed environments. In addition, existing development needs, like tools for creating components, were often slow and cumbersome because of a lack of language functionality. In short, one of the overriding goals for C# was to create a language that would allow developers to become more productive. C# is a language that will allow fast development of today's applications. The following list looks at some of the other design goals for C#.

Improved productivity Visual C++ is one of the most widely used languages for low-level development and in application development where flexibility is key. Unfortunately, that flexibility comes at the price of developer productivity. For example, writing a component in Visual C++ requires easily three or four times the amount of code than that of a comparable Visual Basic component. While you gain better control over the component code execution, you pay for it with extra code and the time/complexity that comes with that extra code. The goal of C# is to provide the same level of flexibility with increased developer productivity. (C# won't work for native EXEs; see the "Native Executable Development" section for details.)