1 YEAR UPGRADE
BUYER PROTECTION PLAN
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
Environment (IDE)
Adrian Turtschi
DotThatCom.com
Jason Werry
Greg Hack
Joseph Albahari
Saurabh Nandu
Technical Editor
Wei Meng Lee
Series Editor
C# .NET
Web Developer’s Guide
With more than 1,500,000 copies of our MCSE, MCSD, CompTIA, and Cisco
study guides in print, we continue to look for ways we can better serve the
information needs of our readers. One way we do that is by listening.
Readers like yourself have been telling us they want an Internet-based ser-
vice that would extend and enhance the value of our books. Based on
reader feedback and our own strategic plan, we have created a Web site
that we hope will exceed your expectations.
is an interactive treasure trove of useful infor-
mation focusing on our book topics and related technologies. The site
offers the following features:
Technical Editor
Wei Meng Lee
Series Editor
C# .NET
Web Developer’s Guide
167_C#_FM.qxd 12/5/01 10:16 AM Page iii
Syngress 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
001 CDFE48952P
002 NHBN9436KH
003 BAEN24P7BV
004 HY9W84UJTA
005 RTW9B39RE4
006 JSE4FAHT82
007 VTS8TYCGF2
Karen Cross, Lance Tilford, Meaghan Cunningham, Kim Wylie, Harry Kirchner, Kevin
Votel, 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, Jonathan
Bunkell, and Klaus Beran of Harcourt International for making certain that our vision
remains worldwide in scope.
Annabel Dent of Harcourt Australia for all her help.
David Buckland,Wendi Wong, Marie Chieng, Lucy Chong, Leslie Lim, Audrey Gan, and
Joseph Chan of Transquest Publishers for the enthusiasm with which they receive our
books.
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 their
help and enthusiasm representing our product in Canada.
Lois Fraser, Connie McMenemy, and the rest of the great folks at Jaguar Book Group for
their help with distribution of Syngress books in Canada.
Acknowledgments
167_C#_FM.qxd 12/5/01 10:16 AM Page v
Contributors
Todd Carrico (MCDBA, MCSE) is a Senior Database Engineer for
Match.com. Match.com is a singles portal for the digital age. In addition to its
primary Web site, Match.com provides back-end services to AOL, MSN, and
many other Web sites in its affiliate program.Todd specializes in design and
development 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
Vocational 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 development
resources, and internships for students. He is currently working on a .NET
solution with contributing author David Jorgensen and nLogix. Patrick holds a
Bachelor’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. David
also 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 in
Puyallup,WA with his wife Lisa and their two sons Scott and Jacob.
Greg Hack is a Senior Software Engineer with Allscripts Healthcare Solutions.
Greg has over 15 years experience developing software on platforms ranging
from the mainframe to the desktop using a wide variety of languages and tech-
nologies. Recent work includes a Web-based application that allows patients to
view their medical records and a Pocket PC application that delivers clinical
information 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 consulting
throughout Europe. modulo3 is a process implementation specialist for the
major 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 anal-
ysis and development of multi-tiered applications in heterogeneous environments.
167_C#_FM.qxd 12/5/01 10:16 AM Page vii
viii
trates on teaching C# and .NET. He worked with HTML, JavaScript, Flash 5.0
before he started programming in Java. Saurabh has been impressed by the
power and flexibility of .NET. He is currently employed by YesSoftware Inc.
as Technical Evangelist.
Technical Editor’s Acknowledgements
I would like to thank my friend Nanu Jogi without whose direction I would
have 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 Lee is Series Editor for Syngress Publishing’s .NET Developer
Series. He is currently lecturing at The Center for Computer Studies, Ngee
Ann Polytechnic, Singapore.Wei Meng is actively involved in Web development
work 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
167_C#_FM.qxd 12/5/01 10:16 AM Page ix
x
This 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 the
Visual Studio.NET Beta2 IDE.
Look for this CD icon to obtain files used
in the book demonstrations.
167_C#_FM.qxd 12/5/01 10:16 AM Page xi
xii
From the Series Editor
For many years, C and C++ programmers have been searching for alternative pro-
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 the
language.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 low
level.The search has finally ended with Microsoft’s new language—C#, a member of
the .NET Framework.
C# is the revolutionary new language from Microsoft, designed solely to run on
the .NET framework. Drawing experiences from C, C++, and Visual Basic, C# was
designed 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 radically
simplified.With full access to the .NET Class Libraries, C# includes built-in support
for developing robust Web services and ASP.NET applications. (It was reportedly said
that Visual Studio.NET was built entirely using C# and that most of the examples in
MSDN 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 common
errors 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 program-
ming language.The best way to learn a new language is by trying out the examples
while you are reading this book.Within many chapters, you will find numerous code
examples used in various practical situations; this hands-on, code-intensive approach
allows you to have a deeper understanding of issues involved in C# Web develop-
Infrastructure (CLI)—and the C# specifications have been placed before ECMA for
standardization.
C# is defined as a simple, modern, object-oriented, and type-safe programming
language derived from C and C++. Developed by Anders Hejlsberg of Microsoft
especially for the .NET platform, C# derives its features from a number of languages
xxi
Foreword
167_C#_fore.qxd 12/4/01 2:49 PM Page xxi
xxii Preface
like C, C++, and Java. Specifically written to offer the simplicity of Visual Basic and
power of C++ as an object-oriented language, C# makes it easier for developers to
create, debug, and deploy enterprise applications. It has also been predicted that C#
will become the favored language for developing applications on the .NET platform.
Visual Studio.NET, the next version of Visual Studio IDE, is also a key compo-
nent of the .NET strategy.The Visual Studio.NET IDE has also been given a facelift
and packed with a wide variety of new functionalities. A bitmap editor, debugger,
Web Forms designer,Windows Forms designer,Web Services designer, XML editor,
HTML editor,Web browser, Server Resources Explorer, and multi-language support
have all been packed into one single IDE.
The focus of The C#.NET Web Developer’s Guide is not on teaching you the core
C# language, but rather providing you with code examples that will help you
leverage the functionalities of the .NET Framework Class Libraries.The .NET
Framework collection of base classes cover many of the multiple APIs. Although
impossible for one book to cover all the features, in this book we have covered the
key concepts, libraries, and APIs of the .NET Framework that we feel will help you
easily create new applications using C#.
You have a whole host of features to learn and master, so why wait? Let’s get
started!!
—Saurabh Nandu,Technical Editor
Founder, www.MasterCSharp.com
Assembly Cache 18
Reflection 19
Just In Time Compilation 19
Garbage Collection 20
Exploring the Code Cycle 21
The Pursuit of Standardization 24
Summary/Solutions Fast Track/Frequently Asked Questions 26
Chapter 2 Introducing C# Programming 33
Introduction 34
Getting Started 35
Creating Your First C# Program 37
Compiling and Executing 38
Defining a Class 40
Declaring the Main Method 43
Organizing Libraries with Namespaces 43
167_C#_TOC.qxd 12/5/01 11:44 AM Page xiii
xiv Contents
Using the using Keyword 44
Adding Comments 45
Introducing Data Types 47
Value Types 47
Primitive Data Types 47
Reference Types 48
Explaining Control Structures 49
Using 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
Properties Explorer 117
Solution Explorer 118
Object Browser 119
Dynamic Help 120
Task List Explorer 121
167_C#_TOC.qxd 12/5/01 11:44 AM Page xiv
Contents xv
Features of VS.NET 122
IntelliSense 122
XML Editor 124
Documentation Generation (XML Embedded Commenting) 127
Adding XML Document Comments to C# Pages 127
Customizing the IDE 129
Creating a Project 130
Projects 130
Creating a Project 130
Add Reference 131
Build the Project 131
Debugging a Project 132
Summary/Solutions Fast Track/Frequently Asked Questions 133
Chapter 4 Windows Forms 137
Introduction 138
Introducing Windows Forms 138
Writing a Simple Windows Forms Application 141
Adding Controls 142
Adding an Event Handler 145
Adding Controls at Runtime 147
Attaching an Event Handler at Runtime 152
Writing a Simple Text Editor 154
Starting the Project 154
Writing a Test Page 194
Summary/Solutions Fast Track/Frequently Asked Questions 196
Chapter 5 Network Programming:
Using TCP and UDP Protocols 203
Introduction 204
Introducing Networking and Sockets 204
Introduction to TCP 206
Introduction to UDP 208
Introduction to Ports 211
System.Net Namespace 212
System.Net.Sockets Namespace 213
Example TCP Command Transmission and Processing 214
General Usage of Needed .NET Classes 216
The Server 217
The Client 220
Compiling and Running the Example 226
Example UDP Command Transmission and Processing 227
General Usage of Needed .NET Classes 228
The Server 229
The Client 231
Compiling and Running the Example 234
Creating a News Ticker Using UDP Multicasting 235
General Usage of Needed .NET Classes 236
The Server 240
The Client 243
Compiling and Running the Example 250
Creating a UDP Client Server Chat Application 250
The TCPServerSession Class 253
The TCPServer Class 256
The Chat Protocol 260
Adding Event Logging and Error Handling 310
Using the soapsuds Tool 312
Using Configuration Files 313
Updating Configuration Files Using the .NET
Framework Configuration Tool 318
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 an Intranet Application 321
Object Lifetime and Leasing 321
Creating the CountServer Project 322
Creating the CountHost Project 325
Creating the CountClient Project 326
Understanding the Leasing and Sponsorship Code 329
Client Activated Objects 331
Sending and Receiving Objects by Value 332
Sending and Receiving Objects by Reference 333
Creating Service-Based Applications 334
Building a Versioned Remoting Application 334
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
Chapter 7 Message Queuing Using MSMQ 345
Introduction 346
Introducing MSMQ 346
MSMQ Architecture 348
Installing MSMQ 349
Using Visual Studio to Manage Queues 349
Creating a Simple Application 349
Using DataReaders 408
Using DataSets 414
Working with SQL.NET 418
Using Stored Procedures 419
Working with Odbc.NET 422
Using DSN Connection 423
Summary/Solutions Fast Track/Frequently Asked Questions 426
Chapter 9 Working with XML 431
Introduction 432
Introduction to XML 432
Explaining XML DOM 434
Explaining XPath 435
Explaining XSL 436
Explaining XML Schemas 437
XML Classes in the .NET Framework 437
Working with XML DOM 439
Creating an Empty XML DOM Document 442
Adding an Element to the XML Document 443
Updating an Element in the XML Document 446
Deleting an Element in the XML Document 450
Loading and Saving the XML Document 451
Working with XML and Relational Data 452
XML and the DataSet Class 456
XML Schemas and the DataSet Class 461
Traversing Relations in the DataSet Class 464
167_C#_TOC.qxd 12/5/01 11:44 AM Page xviii
Contents xix
Working with XPath and XSL Transformations 469
Working with XPath 469
Working with XSL 479
Why Web Services? 579
The World of Web Services 579
Web Service Standards 581
Wiring Up Distributed Objects—The SOAP Protocol 581
Creating Your Very First Web Service 581
Running Your Very First Web Service 589
Describing Web Services—WSDL 602
Discovering Web Services—DISCO 608
Publishing Web Services—UDDI 610
Working with Web Services 611
Passing Complex Data Types 611
Error Handling 614
Malformed SOAP Request 614
Wrong Argument Types 617
Exceptions in Server Code 617
167_C#_TOC.qxd 12/5/01 11:44 AM Page xix
xx Contents
Writing a SOAP Client Application 619
Passing Objects 626
Passing Relational Data 631
Passing XML Documents 635
Working with UDDI 639
SOAP Headers 646
Advanced Web Services 646
Maintaining State 647
State Information in the URL (URL Mangling) 648
State Information in the Http Header (Cookies) 651
State Information in the Http Body (SOAP Header) 653
Security 662
Summary/Solutions Fast Track/Frequently Asked Questions 664
Creating the Public Web Methods 748
Creating a Client Application 758
Some Ideas to Improve the Jokes Web Service 775
Summary/Solutions Fast Track/Frequently Asked Questions 776
Index 781
167_C#_TOC.qxd 12/5/01 11:44 AM Page xx
Introducing the
Microsoft .NET
Platform
Solutions in this chapter:
■
Introducing the .NET Platform
■
Features of the .NET Platform
■
Components of the .NET Architecture
■
Exploring the Code Cycle
■
The Pursuit of Standardization
; Summary
; Solutions Fast Track
; Frequently Asked Questions
Chapter 1
1
167_C#_01.qxd 12/3/01 5:42 PM Page 1
2 Chapter 1 • Introducing the Microsoft .NET Platform
Introduction
The .NET platform is the foundation upon which the next generation of soft-
ware will be built. Microsoft has invested a lot of capital in its development, and
Looking at the overall architecture, .NET consists of three primary
components:
www.syngress.com
167_C#_01.qxd 12/3/01 5:42 PM Page 2