He has been working on the Microsoft .NETplatform since fall 2000, specializing in developing enterprise systems using WebServices.. He holds a Bachelor’s degree in Information Systems a
Trang 11 YEAR UPGRADE
B U Y E R P R O T E C T I O N P L A N
Develop and Deliver Enterprise-Critical Desktop and Web
Applications with C# NET
• Complete Case Studies with Ready-to-Run Source Code and Full Explanations
• Hundreds of Developing & Deploying, Migrating, and Debugging Sidebars,
Security Alerts, and C# NET FAQs
• Complete Coverage of Web Services and the Integrated Development
Saurabh Nandu Technical Editor
Wei Meng Lee Series Editor
C # N E T
We b D e v e l o p e r ’s G u i d e
Trang 2s o l u t i o n s @ s y n g r e s s c o m
With more than 1,500,000 copies of our MCSE, MCSD, CompTIA, and Ciscostudy guides in print, we continue to look for ways we can better serve theinformation needs of our readers One way we do that is by listening
Readers like yourself have been telling us they want an Internet-based vice that would extend and enhance the value of our books Based onreader feedback and our own strategic plan, we have created a Web sitethat we hope will exceed your expectations
ser-Solutions@syngress.com is an interactive treasure trove of useful
infor-mation focusing on our book topics and related technologies The siteoffers the following features:
■ One-year warranty against content obsolescence due to vendorproduct upgrades You can access online updates for any affectedchapters
■ “Ask the Author” customer query forms that enable you to postquestions to our authors and editors
■ Exclusive monthly mailings in which our experts provide answers toreader queries and clear explanations of complex material
■ Regularly updated links to sites specially selected by our editors forreaders desiring additional reliable information on key topics
Best of all, the book you’re now holding is your key to this amazing site
Just go to www.syngress.com/solutions, and keep this book handy when
you register to verify your purchase
Thank you for giving us the opportunity to serve your needs And be sure
to let us know if there’s anything else we can do to help you get the maximum value from your investment We’re listening
www.syngress.com/solutions
Trang 4Saurabh Nandu Technical Editor
Wei Meng Lee Series Editor
C # N E T
We b D e v e l o p e r ’s G u i d e
Trang 5Syngress Publishing, Inc., the author(s), and any person or firm involved in the writing, editing, or
production (collectively “Makers”) of this book (“the Work”) do not guarantee or warrant the results to be obtained from the Work.
There is no guarantee of any kind, expressed or implied, regarding the Work or its contents.The Work is sold AS IS and WITHOUT WARRANTY You may have other legal rights, which vary from state to state.
In no event will Makers be liable to you for damages, including any loss of profits, lost savings, or other incidental or consequential damages arising out from the Work or its contents Because some states do not allow the exclusion or limitation of liability for consequential or incidental damages, the above limitation may not apply to you.
You should always use reasonable care, including backup and other appropriate precautions, when working with computers, networks, data, and files.
Syngress Media®, Syngress®,“Career Advancement Through Skill Enhancement®,” and “Ask the Author UPDATE®,” are registered trademarks of Syngress Publishing, Inc “Mission Critical™,”“Hack Proofing™,” and “The Only Way to Stop a Hacker is to Think Like One™” are trademarks of Syngress Publishing, Inc Brands and product names mentioned in this book are trademarks or service marks of their respective companies.
KEY SERIAL NUMBER
C# NET Web Developer’s Guide
Copyright © 2002 by Syngress Publishing, Inc All rights reserved Printed in the United States of America Except as permitted under the Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher, with the exception that the program listings may be entered, stored, and executed in a computer system, but they may not be reproduced for publication.
Printed in the United States of America
1 2 3 4 5 6 7 8 9 0
ISBN: 1-928994-50-4
Technical Editor: Saurabh Nandu Freelance Editorial Manager: Maribeth Corona-Evans Co-Publisher: Richard Kristof Cover Designer: Michael Kavish
Acquisitions Editor: Catherine B Nolan Page Layout and Art by: Shannon Tozier
Developmental Editor: Kate Glennon Copy Editor: Darren Meiss
CD Production: Michael Donovan Indexer: Rich Carlson
Distributed by Publishers Group West in the United States and Jaguar Book Group in Canada.
Trang 6We would like to acknowledge the following people for their kindness and support inmaking this book possible:
Richard Kristof and Duncan Anderson of Global Knowledge, for their generous access
to the IT industry’s best courses, instructors, and training facilities
Ralph Troupe, Rhonda St John, and the team at Callisma for their invaluable insight intothe challenges of designing, deploying and supporting world-class enterprise networks.Karen Cross, Lance Tilford, Meaghan Cunningham, Kim Wylie, Harry Kirchner, KevinVotel, Kent Anderson, and Frida Yara of Publishers Group West for sharing their
incredible marketing experience and expertise
Mary Ging, Caroline Hird, Simon Beale, Caroline Wheeler,Victoria Fuller, JonathanBunkell, and Klaus Beran of Harcourt International for making certain that our visionremains worldwide in scope
Annabel Dent of Harcourt Australia for all her help
David Buckland,Wendi Wong, Marie Chieng, Lucy Chong, Leslie Lim, Audrey Gan, andJoseph Chan of Transquest Publishers for the enthusiasm with which they receive ourbooks
Kwon Sung June at Acorn Publishing for his support
Ethan Atkin at Cranbury International for his help in expanding the Syngress program.Jackie Gross, Gayle Vocey, Alexia Penny, Anik Robitaille, Craig Siddall, Darlene Morrow,Iolanda Miller, Jane Mackay, and Marie Skelly at Jackie Gross & Associates for all theirhelp and enthusiasm representing our product in Canada
Lois Fraser, Connie McMenemy, and the rest of the great folks at Jaguar Book Group fortheir help with distribution of Syngress books in Canada
Acknowledgments
Trang 7Todd Carrico(MCDBA, MCSE) is a Senior Database Engineer for
Match.com Match.com is a singles portal for the digital age In addition to itsprimary Web site, Match.com provides back-end services to AOL, MSN, andmany other Web sites in its affiliate program.Todd specializes in design anddevelopment of high-performance, high-availability data architectures primarily
on the Microsoft technology His background includes designing, developing,consulting, and project management for companies such as Fujitsu, Accenture,International Paper, and GroceryWorks.com In addition to his contribution to
C# NET Web Developer’s Guide,Todd has also contributed chapters to other
books in the Syngress NET Series including the ASP NET Web Developer’s
Guide, and the VB NET Developer’s Guide.Todd resides in Sachse,TX, with his
wife and two children
Mark Tuttis a Senior Software Engineer with MICROS Systems MICROSprovides complete information management solutions for the hospitality
industry, including software, hardware, enterprise systems integration, consulting,and support Mark is the principle designer of a number of software packages,including Guest Service Solution, a customer relationship management systemfor the MICROS Restaurant Enterprise Series platform In addition to hisproduct development duties, Mark is a key contributor to the design and devel-opment of system integration software and customer-specific product exten-sions that allow MICROS clients to fully integrate MICROS products intotheir overall technology plans Mark currently resides in Baltimore, Marylandwith his wife Malinda and their twin sons, Fred and Jackson
Jason Werry(MCSD) runs a consulting firm, Synergy Data Solutions, inAustralia He currently provides strategic and technical consulting to his clientsand specializes in Windows-based enterprise systems development Jason has anextensive background using Microsoft technologies and is currently developingstate-of-the-art,Web-based applications on the NET platform His clients haveranged from a Taiwanese multimedia company to various government depart-ments and local startups A natural born programmer, Jason started coding Z80 processors in Assembly at age 13 Since then he has used most popular
vi
Trang 8programming languages and presently enjoys working with SQL Server, MTS,IIS,Visual Basic, and C# Jason holds a bachelor’s degree in Mathematics/Computer Science from The University of Queensland He dedicates his
writing to his loving wife, LiHsing
Patrick Coelho(MCP) is an Instructor at The University of WashingtonExtension, North Seattle Community College, Puget Sound Center, and SeattleVocational Institute, where he teaches courses in Web Development (DHTML,ASP, XML, XSLT, C#, and ASP NET) Patrick is a Co-Founder of
DotThatCom.com, a company that provides consulting, online developmentresources, and internships for students He is currently working on a NETsolution with contributing author David Jorgensen and nLogix Patrick holds aBachelor’s of Science degree from the University of Washington, Bothell.Patrick lives in Puyallup,WA with his wife Angela
David Jorgensen (MCP) is an Instructor at North Seattle Community
College, University of Washington extension campus, and Puget Sound Centers
He is also developing courses for Seattle Vocational Institute, which teaches.NET and Web development to the underprivileged in the Seattle area Davidalso provides internship opportunities through his company DotThatCom.com,which does online sample classes and chapters of books David holds a bach-elor’s degree in Computer Science from St Martin’s College and resides inPuyallup,WA with his wife Lisa and their two sons Scott and Jacob
Greg Hackis a Senior Software Engineer with Allscripts Healthcare Solutions.Greg has over 15 years experience developing software on platforms rangingfrom the mainframe to the desktop using a wide variety of languages and tech-nologies Recent work includes a Web-based application that allows patients toview their medical records and a Pocket PC application that delivers clinicalinformation to physicians at the point of care
Axel Goldbach is a Senior Consultant with modulo3 GmbH, a consulting
company based in Germany and specializing in project management consultingthroughout Europe modulo3 is a process implementation specialist for themajor networking frameworks, including eXtreme Programming, MSF and
V Modell Axel currently provides senior-level strategic and technical consulting
to all modulo3 clients in Germany and Central Europe His duties include ysis and development of multi-tiered applications in heterogeneous environments
Trang 9Axel also works as a technical scout and trainer for modulo3 His training cialties include programming languages, networking, and academic fields such asdevelopment methodology, parser- and interpreter-technology, theory of com-plexity, and provable correct software
spe-Joseph Albahariis a freelance consultant and developer with over 10 yearsexperience in designing networked systems He has led a string of successfulprojects, from custom application frameworks for start-up companies, to high-performance OLAP and data warehousing systems for telecommunicationsgiants His knowledge in object-oriented user interface design has been calledupon in the planning or production of many large and complex systems, wherewell-balanced abstractions are of key importance Joseph is also experienced inSQL Server database administration, and has developed high-performance solu-tions for clients with specialized requirements—such as a replication systemproviding field level synchronization, or a high-throughput bulk-copying agent.Joseph holds a Bachelor’s degree in computer science and physics
Adrian Turtschi (MCSE, MCSD) is Lead Architect Solution Developmentwith Avanade (Germany), where he is responsible for the solution offering inthe mobile computing space He has been working on the Microsoft NETplatform since fall 2000, specializing in developing enterprise systems using WebServices He is particularly interested in using Web Services to bridge platformand system boundaries Prior to joining Avanade, Adrian worked for KPMG’sGlobal Knowledge Exchange in Boston, where he helped design and developKPMG's global knowledge management and collaboration solution, used by its100,000 professionals world-wide Adrian has work experience in Switzerland,the Netherlands, and the US He has degrees in Mathematics and ComputerScience He currently lives in Berlin, Germany
Trang 10Technical Editor and Reviewer
Saurabh Nanduis the Founder of www.MasterCSharp.com which trates on teaching C# and NET He worked with HTML, JavaScript, Flash 5.0before he started programming in Java Saurabh has been impressed by thepower and flexibility of NET He is currently employed by YesSoftware Inc
concen-as Technical Evangelist
Technical Editor’s Acknowledgements
I would like to thank my friend Nanu Jogi without whose direction I wouldhave never got into working on the NET Platform I would also like to thank
my family, especially my brother Pritesh, for their support
Wei Meng Leeis Series Editor for Syngress Publishing’s NET DeveloperSeries He is currently lecturing at The Center for Computer Studies, NgeeAnn Polytechnic, Singapore.Wei Meng is actively involved in Web developmentwork and conducts training for Web developers and Visual Basic programmers
He has co-authored two books on WAP He holds a Bachelor’s degree in
Information Systems and Computer Science from the National University of
Singapore.The first and second books of the NET series, VB NET Developer’s
Guide (ISBN: 1-928994-48-2), and ASP NET Developer’s Guide (ISBN:
1-928994-51-2) are currently available from Syngress Publishing
Series Editor
Trang 11This CD-ROM contains the code files that are used in each chapter of this book.The
code files for each chapter are located in a chXX directory (for example, the files for Chapter 8 are in the ch08 directory) Any further directory structure depends on the pro-
jects that are presented within the chapter
To work with the examples provided, you will need at least the Windows 2000 or
Windows XP Professional operating system with the latest service packs, IIS 5.x, and IE 6.0, since ASP.NET and Web Services (a part of ASP.NET) are not supported on earlier operating systems such as Windows 9x/WindowsME/WindowsNT Also needed is the
.NET SDK Beta2 (the latest public release available while writing this book) and theVisual Studio.NET Beta2 IDE
The C# NET Web Developer’s Guide provides you with extensive examples that will
help solve the problems you might face while developing applications for the NETPlatform rather than concentrating on the theory of C# and NET programming.Therefore code is the main feature of this book
The chapters contain both code snippets and sample programs that illustrate theprinciples discussed Chapter 2 presents a series of sample programs that introduce con-cepts in C# that are different from other object-oriented languages Chapter 4 helps youunderstand the basics of building Graphical User Interface (GUI)-rich Windows Formsapplications; the examples presented in this chapter are the launch pad for WindowsForms applications used in other chapters Similarly, code presented in Chapter 8 helpsyou to interact with various databases using ADO.NET; again, this chapter acts as a foun-dation for further chapters’ database coverage Chapter 9 will acquaint you with using.NET Class Libraries to interact with XML and its related technologies
Chapters 5, 6, and 11 discuss technologies and Application Program Interfaces (APIs)that help two applications to communicate and interact with each other Chapter 5
focuses on enabling applications to communicate over the TCP and UDP protocols andprovides an overview of the techniques used to interact with Web pages programmatically.Code examples in Chapter 6 and Chapter 11 concentrate on using Simple Object AccessProtocol (SOAP) and object serialization and deserialization
About the CD
Trang 12func-Lastly, to end on a lighter note, Chapter 12 takes you through building a Jokes WebService.The code in this chapter helps you build both the Jokes Web Service as well asthe Windows Forms Client for the service.
Look for this CD icon to obtain files used
in the book demonstrations.
Trang 13From the Series Editor
For many years, C and C++ programmers have been searching for alternative gramming languages that offer the same kind of flexibility and power of C and C++,but without the complexities and steep learning curve required for mastery of thelanguage.What many programmers desired was a language that would allow applica-tions to be built rapidly, but at the same time giving them the ability to code at lowlevel.The search has finally ended with Microsoft’s new language—C#, a member ofthe NET Framework
pro-C# is the revolutionary new language from Microsoft, designed solely to run onthe NET framework Drawing experiences from C, C++, and Visual Basic, C# wasdesigned to be a simple and modern object oriented programming language
But why learn C#? With the integration of C# and the Visual Studio.NET(known as Visual C#), developing Windows and Web applications has been radicallysimplified.With full access to the NET Class Libraries, C# includes built-in supportfor developing robust Web services and ASP.NET applications (It was reportedly saidthat Visual Studio.NET was built entirely using C# and that most of the examples inMSDN were coded in C#.That in and of itself is a very good reason to learn C#!)Besides this, C# enhances the productivity of programmers by eliminating commonerrors often associated with C and C++
While many of the earlier C# books have primarily focused on the language
syntax, The C# NET Web Developer’s Guide illustrates the uses of C# for Web
devel-opers looking to harness the new functionality and ease of this powerful ming language.The best way to learn a new language is by trying out the exampleswhile you are reading this book.Within many chapters, you will find numerous codeexamples used in various practical situations; this hands-on, code-intensive approachallows you to have a deeper understanding of issues involved in C# Web develop-ment, and at the same time allows you to cut and paste portions of applicable codeinto your current projects, thereby shortening development time
program-We are constantly working hard to produce the best technical books needed byprofessional programmers like you I sincerely hope you will enjoy reading this book
as much as the authors did writing it!
Wei Meng Lee, Series Editor Syngress NET Developer Series
Trang 14Assemblies 16 Metadata 16
Reflection 19
Summary/Solutions Fast Track/Frequently Asked Questions 26
Introduction 34
Declaring the Main Method 43
xiii
Trang 15Using the if Statement 49 Using the if-else Statement 50 Using the switch case Statement 50 Using the for Statement 51 Using the while Statement 52 Using the do while Statement 52 Using the break Statement 52 Using the continue Statement 53 Using the return Statement 54 Using the goto Statement 55
Delegates 70
Multicast 75 Events 79
Using the try Block 89 Using the catch Block 89 Using the finally Block 89 Using the throw Statement 89
Summary/Solutions Fast Track/Frequently Asked Questions 104
Trang 16Contents xv
IntelliSense 122
Documentation Generation (XML Embedded Commenting) 127
Summary/Solutions Fast Track/Frequently Asked Questions 133
Introduction 138
Trang 17xvi Contents
Summary/Solutions Fast Track/Frequently Asked Questions 196
Chapter 5 Network Programming:
Example TCP Command Transmission and Processing 214
Example UDP Command Transmission and Processing 227
The TCPServerSession Class 253 The TCPServer Class 256
The ChatServer Class 260 The ChatClient Class 265
The RemoteFileStreamServer Class 272 The RemoteFileStreamProxy Class 276 The FileSharingPeer Class 279
Redirection 290
Trang 18Contents xvii
Authentication 291 Cookies 291 Summary/Solutions Fast Track/Frequently Asked Questions 292
Introduction 300
Updating Configuration Files Using the NET
Changing the Hosting Application to a Service 319 Using the TCP Channel with the Binary Formatter 321 Summary of the Improved Sample Application 321
Creating the CountServer Project 322 Creating the CountHost Project 325 Creating the CountClient Project 326
Understanding the Leasing and Sponsorship Code 329
Sending and Receiving Objects by Reference 333
Creating the VersionHost Project 336 Creating the VersionClient Project 337
Testing Side-By-Side Execution of Remote Objects 339 Summary/Solution Fast Track/Frequently Asked Questions 340
Introduction 346
Sending and Receiving Messages with Complex Objects 356
Trang 19xviii Contents
Creating the DrawingSender Project 369 Creating the DrawingReceiver Project 373
Using Public Queues While Disconnected from the Network 378 Summary/Solutions Fast Track/Frequently Asked Questions 379
Summary/Solutions Fast Track/Frequently Asked Questions 426
XML and the DataSet Class 456 XML Schemas and the DataSet Class 461 Traversing Relations in the DataSet Class 464
Trang 20Contents xix
Summary/Solutions Fast Track/Frequently Asked Questions 490
Introduction 496
Using VS.NET to Validate Form Input with a Regular Expression 538
Summary/Solutions Fast Track/Frequently Asked Questions 571
Introduction 576
Wiring Up Distributed Objects—The SOAP Protocol 581