GetPedia - VIK Wiki

Transcription

www.GetPedia.comClick on your interest section for more information :Acne Advertising Aerobics & Cardio Affiliate Revenue Alternative Medicine Attraction Online Auction Streaming Audio & Online Music Aviation & Flying Babies & Toddler Beauty Blogging, RSS & Feeds Book Marketing Book Reviews Branding Breast Cancer Broadband Internet Muscle Building & Bodybuilding Careers, Jobs & Employment Casino & Gambling Coaching Coffee College & University Cooking Tips Copywriting Crafts & Hobbies Creativity Credit Cruising & Sailing Currency Trading Customer Service Data Recovery & ComputerBackup Dating Debt Consolidation Debt Relief Depression Diabetes Divorce Domain Name E-Book E-commerce Elder Care Email Marketing Entrepreneur Ethics Exercise & Fitness Ezine Marketing Ezine Publishing Fashion & Style Fishing Fitness Equipment Forums Game Goal Setting Golf Dealing with Grief & Loss Hair Loss Finding Happiness Computer Hardware Holiday Home Improvement Home Security Humanities Humor & Entertainment Innovation Inspirational Insurance Interior Design & Decorating Internet Marketing Investing Landscaping & Gardening Language Leadership Leases & Leasing Loan Mesothelioma & AsbestosCancer Business Management Marketing Marriage & Wedding Martial Arts Medicine Meditation Mobile & Cell Phone Mortgage Refinance Motivation Motorcycle Music & MP3 Negotiation Network Marketing Networking Nutrition Get Organized - Organization Outdoors Parenting Personal Finance Personal Technology Pet Philosophy Photography Poetry Political Positive Attitude Tips Pay-Per-Click Advertising Public Relations Pregnancy Presentation Psychology Public Speaking Real Estate Recipes & Food and Drink Relationship Religion Sales Sales Management Sales Telemarketing Sales Training Satellite TV Science Articles Internet Security Search Engine Optimization(SEO) Sexuality Web Site Promotion Small Business Software Spam Blocking Spirituality Stocks & Mutual Fund Strategic Planning Stress Management Structured Settlements Success Nutritional Supplements Tax Team Building Time Management Top Quick Tips Traffic Building Vacation Rental Video Conferencing Video Streaming VOIP Wealth Building Web Design Web Development Web Hosting Weight Loss Wine & Spirits Writing Article Writing Yoga

C# BibleJeff Ferguson, Brian Patterson, Jason Beres,Pierre Boutquin, and Meeta GuptaPublished byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.comCopyright 2002 by Wiley Publishing, Inc., Indianapolis, IndianaPublished simultaneously in CanadaLibrary of Congress Control Number: 2001092884ISBN: 0-7645-4834-4Manufactured in the United States of America10 9 8 7 6 5 4 3 2 11B/ST/QX/QS/INNo part of this publication may be reproduced, stored in a retrieval system or transmitted inany form or by any means, electronic, mechanical, photocopying, recording, scanning orotherwise, except as permitted under Sections 107 or 108 of the 1976 United States CopyrightAct, without either the prior written permission of the Publisher, or authorization throughpayment of the appropriate per-copy fee to the Copyright Clearance Center, 222 RosewoodDrive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4744. Requests to the Publisherfor permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-Mail:permcoordinator@wiley.com.LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: WHILE THE PUBLISHER ANDAUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK, THEYMAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THEACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK ANDSPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITYOR FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATEDOR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS.THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLEFOR YOUR SITUATION. YOU SHOULD CONSULT WITH A PROFESSIONAL WHEREAPPROPRIATE. NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FORANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDINGBUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHERDAMAGES.

For general information on our other products and services or to obtain technical support,please contact our Customer Care Department within the U.S. at 800-762-2974, outside theU.S. at (317) 572-3993 or fax (317) 572-4002.Wiley also publishes its books in a variety of electronic formats. Some content that appears inprint may not be available in electronic books.Trademarks: Wiley, the Wiley Publishing logo and related trade dress are trademarks orregistered trademarks of Wiley Publishing, Inc., in the United States and other countries, andmay not be used without written permission. All other trademarks are the property of theirrespective owners. Wiley Publishing, Inc., is not associated with any product or vendormentioned in this book.About the AuthorsJeff Ferguson is a senior consultant with Magenic Technologies, a software consultingcompany dedicated to solving business problems exclusively using Microsoft tools andtechnologies. He has been a professional software developer since 1989 and has developedsoftware using C, C , and C# for Unix, DOS, and Windows systems. Send e-mail to Jeff atJeffF@magenic.com (remember to include all three "F"s in the name portion of the address).Brian Patterson currently works for Affina, Inc., as a Technical Team Leader, where he isgenerally working with C on HP-UX or Windows development with any number of theVisual Studio languages. Brian has been writing for various Visual Basic publications since1994 and has co-written several .NET-related books, including Migrating to Visual Basic.NET and .NET Enterprise Development with VB.NET. You can generally find him posting inthe MSDN newsgroups or you can reach him by e-mail at BrianDPatterson@msn.com.Jason Beres has been a software developer for 10 years. He is currently a consultant in southFlorida and works exclusively with Microsoft technologies. Jason holds the MCT, MCSD,and MCDBA certifications from Microsoft. When he is not teaching, consulting, or writing,he is formatting his hard drive, installing the latest beta products from Microsoft, and keepingup with the latest episodes of "Star Trek."Pierre Boutquin is a senior software architect in the treasury of a major Canadian bank,where he helps develop leading-edge market risk management software. He has more than adecade of experience implementing PC-based computer systems, with in-depth knowledge ofdistributed systems design, data warehousing, Visual Basic, Visual C , and SQL. He has cowritten many programming books and has contributed material on VB, COM , XML, andSQL to other books. Koshka and Sasha, his two adorable Burmese cats, own most of Pierre'sspare time. While petting them, he often thinks how nice it would be to find more time andget back into chess or keep up with news from Belgium, his native country. You can reachhim at boutquin@hotmail.com.Meeta Gupta has a master's degree in computer engineering. Networking is her first love.She is presently working at NIIT Ltd., where she designs, develops, and authors books on avaried range of subjects. She has co-written books on TCP/IP, A Certification, ASP.NET,and PHP. She also has an extensive experience in designing and developing ILTs. Besideswriting, Meeta has conducted courses on C , Sybase, Windows NT, Unix, and HTML for adiverse audience, from students to corporate clients.

NIIT is a global IT solutions company that creates customized multimedia training productsand has more than 2,000 training centers worldwide. NIIT has more than 4,000 employees in37 countries and has strategic partnerships with a number of major corporations, includingMicrosoft and AT&T.About the Series EditorMichael Lane Thomas is an active development community and computer industry analystwho presently spends a great deal of time spreading the gospel of Microsoft .NET in hiscurrent role as a .NET technology evangelist for Microsoft. In working with over a half-dozenpublishing companies, Michael has written numerous technical articles and written orcontributed to almost 20 books on numerous technical topics, including Visual Basic, VisualC , and .NET technologies. He is a prolific supporter of the Microsoft certificationprograms, having earned his MCSD, MCSE I, MCT, MCP SB, and MCDBA.In addition to technical writing, Michael can also be heard over the airwaves from time totime, including two weekly radio programs on Entercom (http://www.entercom.com/)stations, including most often in Kansas City on News Radio 980KMBZ(http://www.kmbz.com/). He can also occasionally be caught on the Internet doing an MSDNWebcast (http://www.microsoft.com/usa/webcasts/) discussing .NET, the next generation ofWeb application technologies.Michael started his journey through the technical ranks back in college at the University ofKansas, where he earned his stripes and a couple of degrees. After a brief stint as a technicaland business consultant to Tokyo-based Global Online Japan, he returned to the States toclimb the corporate ladder. He has held assorted roles, including those of IT manager, fieldengineer, trainer, independent consultant, and even a brief stint as Interim CTO of a

successful dot-com, although he believes his current role as .NET evangelist for Microsoft isthe best of the lot. He can be reached via e-mail at mlthomas@microsoft.com.CreditsSenior Acquisitions EditorSharon CoxProject EditorEric NewmanDevelopment EditorSydney JonesCopy EditorLuann RouffTechnical EditorSundar RajanEditorial ManagerMary Beth WakefieldVice President & Executive Group PublisherRichard SwadleyVice President and PublisherJoseph B. WikertProject CoordinatorRyan T. SteffenGraphics and Production SpecialistsBeth Brooks, Melanie DesJardins,Joyce Haughey, Barry Offringa,Laurie Petrone, Betty Schulte,Jeremey UngerQuality Control TechniciansLaura Albert, Susan MoritzProofreading and IndexingTECHBOOKS Production ServicesFor my family and my friends.Jeff FergusonThis book is dedicated to my uncle, Brian Weston, who didn't seem tomind when I came to visit and spent all day with his TRS-80 Model II.Brian Patterson

To Nitin, who was the driving force.Meeta GuptaPrefaceMicrosoft's .NET Framework represents the most significant change in software developmentmethodology for a Microsoft operating system since the introduction of Windows. It is builtusing an architecture that allows software languages to work together, sharing resources andcode, to provide developers with the advanced tools necessary to build the next generation ofdesktop and Internet-enabled applications. Microsoft's Visual Studio .NET product includesnew versions of their Visual Basic and C compiler products that target .NET development,as well as a brand new language called C# (pronounced "C-sharp").C# Bible will show you how to write code using this brand new language. Languageconstructs such as statements, variables, control loops, and classes are all covered. In addition,the book will show you how to apply C# to programming tasks that developers often face inthe real world. The final portions of the book will show you how to use C# to develop Websites, access databases, work with legacy COM and COM objects, develop Windowsdesktop applications, work with various .NET Framework concepts, and more.The primary focus of this book is .NET development using C# as the implementationlanguage and the .NET Framework's C# command-line compiler as the primary developmenttool. C# development using the Visual Studio .NET tool is not covered in this book, althoughthe task of using Visual Studio .NET to develop C# applications can be easily mastered oncethe fundamentals of .NET development using C# are well understood.Who Should Read This BookThis book was written with both the novice and experienced developer in mind. If you knownothing at all about the basics of software development, this book will get you started with thefundamentals, teaching you how variables, control loops, and classes work. The book willalso speak to developers of any skill level, showing you the .NET tools available for C#development and providing you with tips to make your own C# applications work seamlesslywithin the .NET Framework development guidelines.If you already have delved into the world of creating .NET applications, you will find thisbook a useful resource, because it covers almost every aspect of .NET development in depth.The first three parts of the book serve as an illustrative reference to using features of the C#language. By contrast, the final two portions of the book are dedicated to showcasing C# as anapplication development platform, illustrating the role of C# in desktop-, Web-, database-,and component-based applications.This book assumes that you are seeing C# for the very first time and aims to provide anunderstanding of the language without requiring any previous language expertise. The bookdoes assume, however, that you are familiar with the application environments used inconjunction with your C# applications. The final portions of this book cover the use of C#with desktop, Web, database and component applications, but does not explain thoseplatforms in detail. Rather, the book assumes that you have a working knowledge of thoseapplication platforms.

How This Book Is OrganizedThis book is organized into five parts, plus an appendix.Part I: C# Language FundamentalsThis first part of the book provides a brief overview of the C family of programminglanguages and moves to discuss basic syntax issues with C#. Variables, statements, flowcontrol loops, and method calls are all discussed. First-time developers will also find adiscussion of the usage of these syntax elements and will be able to understand how to buildcode using these constructs.Part II: Object-Oriented Programming with C#The chapters in Part II cover the notion of a class in C#. The class is the fundamental unit ofcode in a C# application, and understanding classes is key to the construction of a working C#application. Part II covers topics such as class design, base classes, derived classes, andoperator overloading.Part III: Advanced C#The third part of the book focuses on specific language features employed by more advancedC# applications. Topics such as exception handling, interface implementation, namespaces,attributes, and unsafe code are all covered. The final chapter in Part III is devoted topresenting some tough programming problems and solutions implemented using C#.Part IV: Developing .NET Solutions Using C#Part IV shows how to use C# in applications that make use of various parts of the .NETFramework. This part of the book is a departure from the other sections, which are devoted topresenting the language features of C#. Part IV uses C# to build applications using a varietyof .NET application platforms, from Windows forms to Web Forms to ASP.NET applicationsand database access. We will also take a look at working with some advanced .NETtechnologies using C#, including threading, assemblies, and reflection.Part V: C# and the .NET FrameworkThe final part of the book describes how C# can be used to work with the .NET Frameworkitself. Framework concepts such as assemblies, reflection, threading, and COM/COM component interoperability are explained. Each chapter explains the appropriate Frameworkconcept and also shows how to take advantage of the technology using C# as theimplementation language.AppendixThe final section of the book is devoted to an appendix, "XML Primer," which provides anoverview of the eXtensible Markup Language (XML). It provides an overview of the historyof XML and how developers can take advantage of XML to describe data in a standardized

way. Many .NET projects make use of XML in one form or another, and several .NETconfiguration files are based on the XML infrastructure.Companion Web siteThis book provides a companion Web site from which you can download the code fromvarious chapters. All the code listings reside in a single WinZip file that you can download bygoing to www.wiley.com/extras and selecting the C# Bible link. After you download the file,and if you have WinZip already on your system, you can open it and extract the contents bydouble-clicking. If you don't currently have WinZip, you can download an evaluation versionfrom www.winzip.com.How to Approach This BookReaders who are completely new to software development (readers coming from aWebmaster background, perhaps) will get the most benefit from this book by first readingParts I and II to get a good handle on how the mechanics of a software application work. Itwill be important for new developers to understand the basics of software development andhow all of the pieces fit together to construct a complete C# application.Readers approaching C# with a background in C will find C# very familiar. C# was builtwith C and C in mind, and the syntax resembles that of these older languages. Thesereaders might wish to skim through Parts I and II to get a feel for the variance in syntax, andthen might want to dive right in to Part III to understand the advanced features of thelanguage. Many of the topics in Part III delve into concepts that distinguish C# from itspredecessors.Developers already familiar with C# will also find useful material. Parts IV and V showcasethe use of C# in a variety of .NET platform applications and present several examples thatillustrate C# code that can be used to perform a variety of tasks. These final two parts movethe book from a theoretical language level to a practical level and are ideal for developers ofany level wishing to understand how C# can be used to implement a variety of applications.Conventions Used in This BookEach chapter in this book begins with a heads-up of the topics covered in the chapter and endswith a summary of what you should have learned by reading the chapter.Throughout this book, you will find icons in the margins that highlight special or importantinformation. Keep an eye out for the following icons:Caution A Caution icon indicates a procedure that could potentially cause difficulty or evendata loss; pay careful attention to Caution icons to avoid common and not-socommon programming pitfalls.Cross-Reference Cross-Reference icons point to additional information about a topic,which you can find in other sections of the book.Note A Note icon highlights interesting or supplementary information and often containsextra bits of technical information about a subject.Tip Tip icons draw attention to handy suggestions, helpful hints, and useful pieces of advice.

In addition to the icons listed previously, the following typographical conventions are usedthroughout the book: Code examples appear in a fixed width font.Other code elements, such as data structures and variable names, appear in fixedwidth.File names and World Wide Web addresses (URLs) also appear in fixed width.The first occurrence of an important term in a chapter is highlighted with italic text.Italic is also used for placeholders — for example, ICON icon file name , where icon file name represents the name of a bitmap file.Menu commands are indicated in hierarchical order, with each menu commandseparated by an arrow. For example, File Open means to click the File command onthe menu bar, and then select Open.Keyboard shortcuts are indicated with the following syntax: Ctrl C.What Is a Sidebar?Topics in sidebars provide additional information. Sidebar text contains discussion that isrelated to the main text of a chapter, but not vital to understanding the main text.AcknowledgmentsJeff Ferguson: Few books of this size and scope are ever the work of a single individual, andthis one is no exception. I owe a debt of gratitude to many people for their help andencouragement in writing this book.First, I must thank my parents for the upbringing that I received. Without their parentalguidance, I would not have turned out to be the person I am today and would not have beenable to complete tasks of any size. I am always grateful not only to you but also to the entirefamily for the love and support I always receive.I would like to thank everyone at Wiley for their leadership in the production of this material.Thank you, Andrea Boucher, Sharon Cox, Eric Newman, and Chris Webb, for leading methrough the daunting world of technical book publishing. Thanks also go to Rolf Crozier, whoinitially discussed this project with me in the early days. I owe a special thank you to mycolleague Bob Knutson, who reviewed drafts of the material in this book.Thanks go to Greg Frankenfield and Paul Fridman for creating a top-notch Microsoft-basedconsulting organization that allows me to work on client projects as well as my own. Thetechnical growth I have experienced throughout my time at Magenic has been immeasurable.Here's to Magenic's continued success.Thanks to everyone on the DOTNET mailing lists and newsgroups on the Internet. I amlearning a tremendous amount about the .NET Framework and C# simply by reading yourposts. The banter sent back and forth has given me a better understanding of how all of thesenew pieces fit together.Brian Patterson: I'd like to thank my wife, Aimee, for allowing me the many hours hiddenaway in the computer so I could complete my work on this book. A special thanks to Steve

Cisco for the hard work he put into this book, which led the way for the rest of us; to SharonCox, the acquisitions editor, who constantly kept me on track; to the project editor, EricNewman, for keeping all my ducks in a row; and to the series editor, Michael Lane Thomas,who reviewed each and every chapter, making some very good suggestions and providingsome valuable insight into Microsoft and the .NET framework.Pierre Boutquin: Much hard work goes into the creation of a book, and not just from thepeople mentioned on the cover. I must especially thank the Wiley team for their tremendousdedication to produce a quality book. The reviewers deserve a lot of credit for making melook like an accomplished writer.Finally, this effort would not have been possible without the support from my family andfriends: Sandra, Andrea, Jennifer and Paul, Tindy and Doel, Marcel and Diana Ban, MargaretFekete, and John and Nadine Marshall.Meeta Gupta: I thank Anita for giving me the opportunity. However, my biggest thanks go toNitin for, well, everything.Part I: C# Language FundamentalsChapter ListChapter 1: An Introduction to C#Chapter 2: Writing Your First C# ProgramChapter 3: Working with VariablesChapter 4: ExpressionsChapter 5: Controlling the Flow of Your CodeChapter 6: Working with MethodsChapter 7: Grouping Data Using StructuresChapter 1: An Introduction to C#In This ChapterFor the past 20 years, C and C have been the languages of choice for commercial andcritical business applications. These languages provided a severe degree of control to thedeveloper by letting them use pointers and many low-level system functions. However, whenyou compare languages. such as Microsoft Visual Basic to C/C , you come to realize thatwhile C and C are much more powerful languages, it takes a great deal longer to developapplications. Many C/C programmers have dreaded the notion of switching to languagessuch as Visual Basic because they would lose much of the low level control they are used to.What the developer community needed was a language that fell somewhere in between thesetwo. A language that would help with rapid application development but would also allow fora great deal of control and a language that would integrate well with Web-applicationdevelopment, XML, and many of the emerging technologies.

Easing the transition for existing C/C programmers, while also providing an easy-to-learnlanguage for inexperienced programmers are only two of the benefits to the new language onthe block, C#. Microsoft introduced C# to the public at the Professional Developer'sConference in Orlando, Florida, in the summer of 2000. C# combines the best ideas fromlanguages such as C, C , and Java with the productivity enhancements found in theMicrosoft .NET Framework and provides a very productive coding experience for both newand seasoned developers.This chapter dives into the four components that make up the .NET platform as well asexplores the support for emerging Web technologies. It then briefly discusses many of thefeatures found in the C# language and how it compares to other popular languages.The .NET FrameworkMicrosoft designed C# from the ground up to take advantage of its new .NET Framework.Because C# is a player in this new .NET world, you should have a good understanding ofwhat the .NET Framework provides and how it increases your productivity.The .NET Framework is made up of four parts, as shown in Figure 1-1: the CommonLanguage Runtime, a set of class libraries, a set of programming languages, and the ASP.NETenvironment. The .NET Framework was designed with three goals in mind. First, it wasintended to make Windows applications much more reliable, while also providing anapplication with a greater degree of security. Second, it was intended to simplify thedevelopment of Web applications and services that not only work in the traditional sense, buton mobile devices as well. Lastly, the framework was designed to provide a single set oflibraries that would work with multiple languages. The following sections examine each ofthe .NET Framework components.Figure 1-1: The four components of the .NET FrameworkWeb developmentThe .NET Framework was designed with one thing in mind: to fuel Internet development.This new fuel to add to Internet development is called Web Services. You can think of WebServices as a Web site that interacts with programs, rather than people. Instead of deliveringWeb pages, a Web Service takes a request formatted as XML, performs a particular function,and then returns a response to the requester as an XML message.Note XML or eXtensible Markup Language is a self describing language much like that ofHTML. XML on the other hand has no predefined tags thus allowing it great flexibilityin representing a wide variety of objects.

A typical application for a Web Service would be to sit as a layer on top of a corporate billingsystem. When a user surfing the Web purchases products from your Internet site, the purchaseinformation is then sent to the Web Services, which totals all the products, adds a record tothe accounts receivable database, and then returns a response with an order confirmationnumber. Not only can this Web Service interact with Web pages, it can interact with otherWeb Services, such as a corporate accounts payable system.In order for the Web Service model to survive the natural evolution of programminglanguages, it must include much more than a simple interface to the Web. The Web servicemodel also includes protocols that enable applications to find Web Services available across aLAN or the Internet. This protocol also enables the application to explore the Web Serviceand determine how to communicate with it, as well as how to exchange information. Toenable Web Service discovery, the Universal Discovery, Description and Integration (UDDI)was established. This allows Web Services to be registered and searched, based on keyinformation such as company name, type of service, and geographic location.Application developmentAside from Web development, you can still build traditional Windows applications with the.NET Framework. Windows applications created with the .NET Framework are based uponWindows Forms. These Windows Forms are somewhat of a crossbreed between Visual Basic6 forms and the forms of Visual C . Though forms look the same as their predecessors, theyare completely object-oriented and class-based, much like form objects in the MicrosoftFoundation Class.These new Windows Forms now support many classic controls found in Visual Studio, suchas the Button, TextBox, and Label, as well as ActiveX controls. Aside from the traditionalcontrols, new components such as PrintPreview, LinkLabel, ColorDialog, andOpenFileDialog are also supported.Building applications with .NET also provides you with many enhancements not found inother languages, such as security. These security measures can determine whether anapplication can write or read a disk file. They also enable you to embed digital signatures intothe application to ensure that the application was written by a trusted source. The .NETFramework also enables you to embed component information, and version information,within the actual code. This makes it possible for software to install on demand,automatically, or with no user intervention at all. Together, all of these features greatly reducesupport costs within the enterprise.Common Language RuntimeProgramming languages usually consist of both a compiler and a runtime environment. Thecompiler turns the code that you write into executable code that can be run by users. Theruntime environment provides a set of operating system services to your executable code.These services are built into a runtime layer so that your code does not need to worry aboutthe low-level details of working with the operating system. Operations such as memorymanagement and file I/O are good examples of services that might be provided by a runtimeenvironment.

Before .NET came along, each language shipped with its own runtime environment. VisualBasic shipped with a runtime called MSVBVM60.DLL. Visual C shipped with a DLLcalled MSVCRT.DLL. Each of these runtime modules provided a set of low-level services tocode that developers wrote. Developers would write code and then build that code with theappropriate runtime in mind. The e

Ezine Marketing . Pierre Boutquin is a senior software architect in the treasury of a major Canadian bank, where he helps develop leading-edge market risk management software.