MCAD Developing XML Web Services and Server Components with Visual Basic(R) .NET and the .NET Framework Exam Cram 2 (Exam Cram 70-310) 0789729008, 9780789729002, 9780768661439

This certification exam measures your ability to develop and implement middle-tier components, server components, and XM

326 71 26MB

English Pages 525 Year 2003

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Developing XML Web Services and Server Components with Visual Basic• .NET and the .NET Framework Exam Cram 2......Page 2
Copyright © 2004 by Que Certification......Page 3
A Note from Series Editor Ed Tittel......Page 4
About the Author......Page 7
About the Technical Editors......Page 8
Contents at a Glance......Page 10
Table of Contents......Page 12
We Want to Hear from You!......Page 21
Introduction......Page 22
Taking a Certification Exam......Page 23
How to Prepare for an Exam......Page 25
About This Book......Page 28
MCSDs in the Real World......Page 32
The Ideal MCSD Candidate......Page 33
Put Yourself to the Test......Page 34
Assessing Readiness for Exam 70-310......Page 38
What’s Next?......Page 39
CHAPTER 1 Microsoft Certification Exams......Page 40
Assessing Exam-Readiness......Page 41
What to Expect at the Testing Center......Page 42
Exam Layout and Design......Page 43
Microsoft’s Testing Formats......Page 52
Strategies for Different Testing Formats......Page 54
Question-Handling Strategies......Page 58
Additional Resources......Page 59
CHAPTER 2 Creating and Manipulating DataSets......Page 62
Manipulating a DataSet Schema......Page 63
Manipulating DataSet Relationships......Page 67
Creating and Using Strongly Typed DataSets......Page 70
Accessing and Manipulating SQL Server Data......Page 72
Exam Prep Questions......Page 89
Need to Know More?......Page 95
CHAPTER 3 Accessing and Manipulating XML Data......Page 96
Accessing an XML File......Page 97
The XmlDataDocument Class......Page 104
Understanding XPath......Page 107
Generating and Using XSD Schemas......Page 115
Using XML with SQL Server......Page 120
Exam Prep Questions......Page 128
Need to Know More?......Page 134
CHAPTER 4 .NET Remoting......Page 136
.NET Remoting Architecture......Page 137
Applying .NET Remoting......Page 143
Using IIS As an Activation Agent......Page 151
Exam Prep Questions......Page 154
Need to Know More?......Page 160
CHAPTER 5 Basic Web Services......Page 162
Understanding Web Services......Page 163
Calling a Web Service Asynchronously......Page 165
Creating Web Services......Page 166
Using Web Services......Page 168
Creating Proxy Classes with the Web Services Description Language Tool (wsdl.exe)......Page 170
Using Web References......Page 171
Exam Prep Questions......Page 173
Need to Know More?......Page 178
CHAPTER 6 Advanced Web Services......Page 180
Creating and Using SOAP Extensions......Page 181
Creating Asynchronous Web Methods......Page 188
Controlling XML Wire Format......Page 191
Exam Prep Questions......Page 199
Need to Know More?......Page 204
CHAPTER 7 Windows Services......Page 206
Architecture of Windows Services......Page 207
Creating a Windows Service Application......Page 208
Installing a Windows Service......Page 212
Using Tools to Monitor and Control a Windows Service......Page 215
Controlling a Windows Service......Page 217
Exam Prep Questions......Page 220
Need to Know More?......Page 225
CHAPTER 8 Component Services......Page 226
Features of COM+......Page 227
Exposing .NET Components to COM/COM+......Page 228
Architecture of Component Services......Page 229
Creating and Consuming a Serviced Component......Page 235
Understanding and Using Enterprise Services......Page 240
Exam Prep Questions......Page 249
Need to Know More?......Page 254
CHAPTER 9 Calling Unmanaged Code......Page 256
Using COM Components......Page 257
Using Platform Invoke......Page 262
Exam Prep Questions......Page 266
Need to Know More?......Page 272
CHAPTER 10 Testing and Debugging......Page 274
Testing......Page 275
Tracing......Page 276
ASP.NET Tracing......Page 281
Debugging......Page 286
Working with Event Logs......Page 294
Working with Performance Counters......Page 296
Exam Prep Questions......Page 298
Need to Know More?......Page 302
CHAPTER 11 Deployment......Page 304
Deploying Private Assemblies......Page 305
Deploying Shared Assemblies......Page 309
Packaging a .NET Application for Deployment......Page 313
Deploying Server Applications......Page 318
Exam Prep Questions......Page 322
Need to Know More?......Page 327
CHAPTER 12 Security Issues......Page 328
Configuring Security......Page 329
Configuring Authentication......Page 336
Configuring Authorization......Page 340
Security for Windows Services......Page 341
Security for Web Services......Page 343
Remoting Security......Page 346
Enterprise Services Security......Page 347
Exam Prep Questions......Page 349
Need to Know More?......Page 354
How to Take the Practice Exams......Page 356
Exam-taking Tips......Page 357
Practice Exam......Page 358
Answer Key......Page 388
Detailed Answers......Page 389
CHAPTER 15 Practice Exam #2......Page 408
Answer Key......Page 442
Detailed Answers......Page 443
ADO.NET Architecture......Page 462
The ADO.NET Object Model......Page 463
Using DataSets......Page 468
Editing Data with ADO.NET......Page 476
Need to Know More?......Page 480
Syntax of an XML Document......Page 482
Need to Know More?......Page 487
PrepLogic Practice Tests, Preview Edition......Page 488
Exam Simulation......Page 490
Software Requirements......Page 491
Using PrepLogic Practice Tests, Preview Edition......Page 492
Get More Exams......Page 495
Customer Service......Page 496
Glossary......Page 498
Index......Page 506
Recommend Papers

MCAD Developing XML Web Services and Server Components with Visual Basic(R) .NET and the .NET Framework Exam Cram 2 (Exam Cram 70-310)
 0789729008, 9780789729002, 9780768661439

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

Developing XML Web Services and Server Components with Visual Basic .NET and the .NET Framework 

Mike Gunderloy

MCAD/MCSD Developing XML Web Services and Server Components with Visual Basic .NET and the .NET Framework (Exam 70-310)

Publisher Paul Boger

Copyright  2004 by Que Certification All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. International Standard Book Number: 0-7897-2900-8

Executive Editor Jeff Riley

Development Editors Ginny Bess Munroe Grant Munroe

Managing Editor Charlotte Clapp

Library of Congress Catalog Card Number: 2003100976 Printed in the United States of America

Project Editor Tricia Liebig

First Printing: July 2003 06

05

04

03

4

3

2

1

Que Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact U.S. Corporate and Government Sales 1-800-382-3419

Copy Editor Bart Reed

Indexer John Sleeva

[email protected]

For sales outside of the U.S., please contact International Sales 1-317-581-3793 [email protected]

Proofreader Juli Cook

Technical Editors Ken Cox Steve Heckler

Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Que Certification cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

Team Coordinator Pamalee Nelson

Multimedia Developer Dan Scherf

Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The authors and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the CD or programs accompanying it.

Page Layout Kelly Maish

Graphics Tammy Graham

Que Certification • 201 West 103rd Street • Indianapolis, Indiana 46290

A Note from Series Editor Ed Tittel You know better than to trust your certification preparation to just anybody. That’s why you, and more than two million others, have purchased an Exam Cram book. As Series Editor for the new and improved Exam Cram 2 series, I have worked with the staff at Que Certification to ensure you won’t be disappointed. That’s why we’ve taken the world’s best-selling certification product—a finalist for “Best Study Guide” in a CertCities reader poll in 2002—and made it even better. As a “Favorite Study Guide Author” finalist in a 2002 poll of CertCities readers, I know the value of good books. You’ll be impressed with Que Certification’s stringent review process, which ensures the books are high-quality, relevant, and technically accurate. Rest assured that at least a dozen industry experts—including the panel of certification experts at CramSession—have reviewed this material, helping us deliver an excellent solution to your exam preparation needs. We’ve also added a preview edition of PrepLogic’s powerful, full-featured test engine, which is trusted by certification students throughout the world. As a 20-year-plus veteran of the computing industry and the original creator and editor of the Exam Cram series, I’ve brought my IT experience to bear on these books. During my tenure at Novell from 1989 to 1994, I worked with and around its excellent education and certification department. This experience helped push my writing and teaching activities heavily in the certification direction. Since then, I’ve worked on more than 70 certification-related books, and I write about certification topics for numerous Web sites and for Certification magazine. In 1996, while studying for various MCP exams, I became frustrated with the huge, unwieldy study guides that were the only preparation tools available. As an experienced IT professional and former instructor, I wanted “nothing but the facts” necessary to prepare for the exams. From this impetus, Exam Cram emerged in 1997. It quickly became the best-selling computer book series since “…For Dummies,” and the best-selling certification book series ever. By maintaining an intense focus on subject matter, tracking errata and updates quickly, and following the certification market closely, Exam Cram was able to establish the dominant position in cert prep books. You will not be disappointed in your decision to purchase this book. If you are, please contact me at [email protected]. All suggestions, ideas, input, or constructive criticism are welcome!

Need More In-Depth Study? Get a Training Guide at 40% Savings!! MCAD/MCSD Developing XML Web Services and Server Components with Visual Basic .NET and the .NET Framework Exam 70-310 Training Guide Mike Gunderloy ISBN 0-7897-2820-6 $49.99 US/$77.99 CAN/£36.50 Net UK

Your cost is only $29.99 US! Free shipping for US orders only.

Have you discovered that you need more in-depth study before taking that exam? Check out the Training Guide series, also from Que Certification. These comprehensive study guides get you up-to-speed on the information tested in the exam, as well as provide test-taking tips and advice for exam day. Inside you’ll find • Study and Exam Tips section at the start of the book • Exam objectives highlighted in every chapter • Step-by-step exercises for hands-on practice • Final review with Fast Facts and a Practice Exam • CD of PrepLogic Practice Tests for complete evaluation of your knowledge

Get 40%

off your next Training Guide purchase!

Here’s what to do: 1) Visit www.quepublishing.com 2) Select the Training Guide of your choice 3) Proceed to checkout 4) Enter coupon code TGUIDE321 when prompted Offer good on purchase of one Training Guide through December 31, 2003.

www.examcram.com

For Princess and Max, eternally faithful. ❧

About the Author

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Mike Gunderloy pursued his first Microsoft certification the year the program was introduced, and he has earned the MCP, MCT, MCSE, MCDBA, MCAD, and MCSD credentials in the decade since. As lead developer for Lark Group, Inc., Mike has worked with small businesses, nonprofit organizations, and Fortune 500 corporations alike, as well as trained many other developers in the use of Microsoft products. He got hooked on computers when you still had to build your own out of parts and is still passionately interested in cutting-edge software technology. As a long-time member of the editorial staff of MCP Magazine, Mike has remained in close touch with the certification community. Mike lives on a farm in eastern Washington state, along with his wife and children and an ever-changing array of horses, sheep, llamas, geese, turkeys, chickens, ducks, peacocks, cats, dogs, and guinea fowl. When he’s not busy testing and writing about software, Mike can usually be found in his garden or greenhouse, trying to persuade recalcitrant vegetables to grow, or out on the land, trying to persuade noxious weeds to stop growing. You can reach Mike at [email protected] or www.larkware.com.

About the Technical Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Ken Cox is a technical writer and Web applications programmer in Toronto, specializing in .NET technologies. For the past six years, Microsoft has selected him as a Most Valuable Professional (MVP) for ASP/ASP.NET. Ken is co-author of several books, including Inside ASP.NET (New Riders), Teach Yourself Object-Oriented Programming with Visual Basic .NET in 21 Days (Sams), and .NET Mobile Web Developer’s Guide (Syngress). His software reviews and articles appear frequently in Visual Studio Magazine. Ken has a bachelor’s degree in Radio and Television Arts and a college certificate in Technical Communication. In a previous life he was a broadcast journalist in Toronto and Quebec City. Steve Heckler is president of Accelebrate, an IT training and programming firm based in Atlanta. An avid ASP.NET, Java, and ColdFusion developer and trainer, Steve served more than six years as a senior manager and instructor at a leading East Coast IT training firm prior to founding Accelebrate. He holds bachelors and masters degrees from Stanford University.

Acknowledgments

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

This is the spot where the author traditionally explains that books don’t exist in a vacuum; without a good editorial staff, all the writing in the world won’t add up to a book. Well, who am I to break with tradition? Thanks to Jeff Riley for getting me into this project, and to Ginny Bess Munroe, Grant Munroe, Tricia Liebig, Bart Reed, and the rest of the editorial team for turning it into a book. And while I’m being traditional, yes, all of the errors in this book are my responsibility alone. In addition to the editorial staff, I owe thanks to the production staff for actually getting this stuff ready to print. So thanks to Juli Cook, John Sleeva, Tammy Graham, and Kelly Maish for somehow turning the final manuscript from a mass of Word documents and TIF images into a real printed book. I’ve been working with Microsoft software and certifications for over a decade now, which makes it impossible to even mention everyone who has contributed to my understanding. But high on any such list must be my former business partners Steve White, Ken Getz, Mary Chipman, and Brian Randell, as well as fellow MCP Magazine editors Dian Schaffhauser, Keith Ward, Michael Domingo, Becky Nagel, and Kris McCarthy. Amit Kalani was instrumental in shaping my view of remoting and serviced components, and also developed the practice exams for this book. I’ve also benefited from the dozens of developers now maintaining weblogs who spend their time sharing information with their peers, as well as those who contribute to various newsgroups and mailing lists. So thanks to the great mass of active developers who believe that sharing knowledge is a good thing. When I get away from the computer, I also have supportive people in my real life. My parents have always encouraged my writing, and my two wonderful kids, Adam and Kayla, at least put up with it (although they would rather hunt crocodiles and pull on my beard, respectively). And last on the list but first in importance is my dear wife, Dana, who supplies endless quantities of help, inspiration, and love to keep me going.

Contents at a Glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Introduction

xxi

Self-Assessment

xxxi

Chapter 1

Microsoft Certification Exams

1

Chapter 2

Creating and Manipulating DataSets

Chapter 3

Accessing and Manipulating XML Data

Chapter 4

.NET Remoting

Chapter 5

Basic Web Services

Chapter 6

Advanced Web Services

Chapter 7

Windows Services

Chapter 8

Component Services

Chapter 9

Calling Unmanaged Code

23

97 123 141

167 187 217

Chapter 10

Testing and Debugging

235

Chapter 11

Deployment

Chapter 12

Security Issues

Chapter 13

Practice Exam #1

Chapter 14

Answer Key for Practice Exam #1

Chapter 15

Practice Exam #2

Chapter 16

Answer Key for Practice Exam #2

Appendix A

ADO.NET Basics

Appendix B

XML Standards and Syntax

265 289 317 349

369

423 443

403

57

Appendix C

What’s on the CD

Appendix D

Using PrepLogic Practice Tests, Preview Edition Software 451 Glossary Index

459

467

449

Table of Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Introduction .....................................................................xxi Self-Assessment ..............................................................xxxi Chapter 1 Microsoft Certification Exams .................................................1 Assessing Exam-Readiness 2 What to Expect at the Testing Center 3 Exam Layout and Design 4 Multiple-Choice Question Format 5 Build-List-and-Reorder Question Format 6 Create-a-Tree Question Format 8 Drag-and-Connect Question Format 10 Select-and-Place Question Format 11 Hot Area 12 Microsoft’s Testing Formats 13 Strategies for Different Testing Formats 15 Case Study Exam Strategy 15 Fixed-Length and Short-Form Exam Strategy Adaptive Exam Strategy 18 Question-Handling Strategies 19 Mastering the Inner Game 20 Additional Resources 20

16

Chapter 2 Creating and Manipulating DataSets .......................................23 Manipulating a DataSet Schema 24 Creating a DataSet Schema 24 Elements and Attributes 25 Using Server Explorer with the XML Designer Manipulating DataSet Relationships 28 Adding Keys to a DataSet Schema 29 One-to-Many Relationships 29 Nested Relationships 30

27

xii

Table . . . .of. Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Creating and Using Strongly Typed DataSets 31 Using the Component Designer to Create a Strongly Typed DataSet 31 Creating a Strongly Typed DataSet from a DataSet Schema 32 Using a Strongly Typed DataSet 33 Accessing and Manipulating SQL Server Data 33 Using Ad Hoc Queries 34 Using Stored Procedures 45 Exam Prep Questions 50 Need to Know More? 56

Chapter 3 Accessing and Manipulating XML Data ....................................57 Accessing an XML File 58 Understanding the DOM 58 Using an XmlReader Object 59 The XMLNode Class 62 The XmlDocument Class 63 The XmlDataDocument Class 65 Understanding XPath 68 The XPath Language 68 Using the XPathNavigator Class 71 Generating and Using XSD Schemas 76 Generating an XSD Schema 76 Using an XSD Schema 78 Using XML with SQL Server 81 Generating XML with SQL Statements 81 Using ExecuteXmlReader 85 Updating SQL Server Data by Using XML 86 Exam Prep Questions 89 Need to Know More? 95

Chapter 4 .NET Remoting .................................................................97 Developing Distributed Applications Using the .NET Framework 98 .NET Remoting Architecture 98 Object Marshalling 100 Channels 101 Formatters 101 The Relationship Between Channels and Formatters

101

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Table . . .of. Contents . . . . .

Remote Object Activation 102 Lifetime Leases 103 Applying .NET Remoting 104 Creating a Remotable Class 104 Creating a Server-Activated Object 105 Creating a Client-Activated Object 108 Using Configuration Files to Configure the Remoting Framework 110 Using IIS As an Activation Agent 112 Exam Prep Questions 115 Need to Know More? 121

Chapter 5 Basic Web Services ..........................................................123 Understanding Web Services 124 SOAP 124 Disco and UDDI 125 WSDL 125 Invoking Your First Web Service 125 Calling a Web Service Asynchronously 126 Creating Web Services 127 Creating a Web Service Project 127 Testing the Web Service Project 128 Customizing the WebMethod Attribute 129 Using Web Services 129 Discovering Web Services with Disco and UDDI 130 Using the Web Services Discovery Tool (disco.exe) 130 Creating Proxy Classes with the Web Services Description Language Tool (wsdl.exe) 131 Using Web References 132 Exam Prep Questions 134 Need to Know More? 139

Chapter 6 Advanced Web Services ....................................................141 Creating and Using SOAP Extensions 142 Writing a SOAP Extension 143 Testing the SOAP Extension 148 Creating Asynchronous Web Methods 149 Using a Callback Delegate 150 Using the WaitHandle Object 150

xiii

xiv

Table . . . .of. Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Controlling XML Wire Format 152 Using Literal Parameter Formatting 153 Using Encoded Parameter Formatting 155 Using RPC-Style Body Formatting 156 Wrapped and Bare Parameters 158 Using the XmlElement Attribute 159 Exam Prep Questions 160 Need to Know More? 165

Chapter 7 Windows Services ...........................................................167 Understanding Windows Services 168 Architecture of Windows Services 168 .NET Framework Support for Windows Services 169 Creating a Windows Service Application 169 Understanding How the SCM Interacts with a Windows Service 170 Creating a Windows Service Application 171 Installing a Windows Service 173 The ServiceProcessInstaller and the ServiceInstaller Classes 173 Adding Installer Classes to a Windows Service Project 175 Using installutil.exe to Install a Windows Service Application 175 Using Tools to Monitor and Control a Windows Service 176 Using the Services MMC Snap-In 176 Using Visual Studio .NET Server Explorer 177 Using the NET Utility (net.exe) 177 Using the Service Control Utility (sc.exe) 178 Controlling a Windows Service 178 Exam Prep Questions 181 Need to Know More? 186

Chapter 8 Component Services .........................................................187 Features of COM+ 188 Exposing .NET Components to COM/COM+ 189 Calling a .NET Component from COM/COM+ 189 Exporting .NET Components As COM Type Libraries Architecture of Component Services 190 Serviced Components 191 Declarative Programming Model 191

190

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Table . . .of. Contents . . . . .

COM+ Applications 193 COM+ Catalog 194 Serviced Component Activation 194 Creating and Consuming a Serviced Component 196 Creating a Serviced Component 196 Consuming a Serviced Component 198 Understanding and Using Enterprise Services 201 Object Pooling 201 Just-in-Time Activation 203 Automatic Transaction Processing 205 Queued Components 208 Exam Prep Questions 210 Need to Know More? 215

Chapter 9 Calling Unmanaged Code ...................................................217 Using COM Components 218 Understanding Runtime Callable Wrappers 219 Registering a COM DLL 220 Using the Type Library Importer Tool (tlbimp.exe) Using COM Components Directly 222 Using Platform Invoke 223 Exam Prep Questions 227 Need to Know More? 233

220

Chapter 10 Testing and Debugging ......................................................235 Testing 236 Tracing 237 Using Trace and Debug to Display Information 238 Trace Listeners 238 Trace Switches 239 Conditional Compilation 241 ASP.NET Tracing 242 Debugging 247 Setting Breakpoints and Stepping Through Program Execution 247 Analyzing Program State to Resolve Errors 248 Debugging When an Exception Occurs 249 Debugging a Running Process 250 Debugging a Remote Process 251 Debugging the Code in DLL Files 252

xv

xvi

Table . . . .of. Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Debugging Client-Side Scripts 252 Debugging a Windows Service 253 Debugging a Serviced Component 253 Debugging a .NET Remoting Object 254 Debugging an XML Web Service 255 Working with Event Logs 255 Working with Performance Counters 257 Exam Prep Questions 259 Need to Know More? 263

Chapter 11 Deployment ...................................................................265 Deploying Private Assemblies 266 Binding Policy for Privately Deployed Assemblies 266 How the CLR Binds to a Privately Deployed Assembly 267 Using the .NET Framework Configuration Tool to Specify Additional Probing Locations 269 Deploying Shared Assemblies 270 Assigning a Strong Name to an Assembly 270 Delay Signing an Assembly 272 Adding an Assembly to the GAC 272 Binding Policy for Shared Assemblies 273 How the CLR Binds to a Shared Assembly 274 Packaging a .NET Application for Deployment 274 Packaging an Application for Deployment by Copying the Files 274 Packaging an Application for Deployment Using Microsoft Windows Installer 275 Creating a Setup Project 276 Customizing Visual Studio .NET Setup and Deployment Projects 278 Deploying Server Applications 279 Deploying a Web Service 279 Deploying Windows Services 280 Deploying a Serviced Component 280 Deploying a .NET Remoting Object 281 Exam Prep Questions 283 Need to Know More? 288

Chapter 12 Security Issues ...............................................................289 Configuring Security 290 Understanding Code Access Security

290

xvii . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Table . . .of. Contents . . . . .

Configuring Authentication 297 No Authentication 298 IIS and ASP.NET Authentication 298 Authentication Providers 299 Configuring IIS Authentication 300 Passport Authentication 300 Forms Authentication 301 Configuring Authorization 301 Implementing Impersonation 302 Security for Windows Services 302 Security for Web Services 304 Platform and Application Security 304 Configuring Web Services for Security 306 Remoting Security 307 Enterprise Services Security 308 Exam Prep Questions 310 Need to Know More? 315

Chapter 13 Practice Exam #1 .............................................................317 How to Take the Practice Exams Exam-taking Tips 318 Practice Exam 319

317

Chapter 14 Answer Key for Practice Exam #1 .........................................349 Answer Key 349 Detailed Answers 350

Chapter 15 Practice Exam #2 .............................................................369 Chapter 16 Answer Key for Practice Exam #2 ..........................................403 Answer Key 403 Detailed Answers 404

Appendix A ADO.NET Basics ..............................................................423 ADO.NET Architecture 423 The ADO.NET Object Model 424 Data Providers and Their Objects The DataSet Classes 427

424

xviii Table of Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Using DataSets 429 Populating a DataSet from a Database 430 Moving Around in DataSets and Retrieving Data DataSets with Multiple Tables 432 Editing Data with ADO.NET 437 Updating Data 437 Adding Data 438 Deleting Data 439 Need to Know More? 441

431

Appendix B XML Standards and Syntax .................................................443 Syntax of an XML Document 443 XML Declaration 444 XML Comments 444 XML Elements 445 XML Attributes 445 XML Naming Convention 446 Handling Special Characters in XML Data XML Namespaces 447 Need to Know More? 448

446

Appendix C What’s on the CD-ROM ......................................................449 PrepLogic Practice Tests, Preview Edition

449

Appendix D Using PrepLogic Practice Tests, Preview Edition Software ...........451 Exam Simulation 451 Question Quality 452 Interface Design 452 Effective Learning Environment 452 Software Requirements 452 Installing PrepLogic Practice Tests, Preview Edition 453 Removing PrepLogic Practice Tests, Preview Edition from Your Computer 453 Using PrepLogic Practice Tests, Preview Edition 453 Starting a Practice Test Mode Session 454 Starting a Flash Review Mode Session 455 Standard PrepLogic Practice Tests, Preview Edition Options 455

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Table . . .of. Contents . . . . .

Time Remaining 456 Your Examination Score Report 456 Reviewing Your Exam 456 Get More Exams 456 Contacting PrepLogic 457 Customer Service 457 Product Suggestions and Comments 457 License Agreement 457

Glossary .......................................................................459 Index ............................................................................467

xix

We Want to Hear from You!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way. As an executive editor for Que Certification, I welcome your comments. You can email or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books better. Please note that I cannot help you with technical problems related to the topic of this book. We do have a User Services group, however, where I will forward specific technical questions related to the book. When you write, please be sure to include this book’s title and author as well as your name, email address, and phone number. I will carefully review your comments and share them with the author and editors who worked on the book. Email: [email protected] Mail: Jeff Riley Executive Editor Que Publishing 800 East 96th Street Indianapolis, IN 46240 USA For more information about this book or another Que title, visit our Web site at www.quepublishing.com. Type the ISBN (excluding hyphens) or the title of a book in the Search field to find the page you’re looking for. For information about the Exam Cram 2 series, visit www.examcram2.com.

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Welcome to Microsoft’s 70-310 Exam Cram 2! Whether this is your first or your fifteenth Exam Cram 2 series book, you’ll find information here that will help ensure your success as you pursue knowledge, experience, and certification. This Introduction explains Microsoft’s certification programs in general and talks about how the Exam Cram 2 series can help you prepare for Microsoft’s Certified Application Developer and Certified Solution Developer exams. Chapters 1 through 12 are designed to remind you of everything you’ll need to know in order to take—and pass—the Developing XML Web Services and Server Components with Microsoft Visual Basic .NET and the Microsoft .NET Framework (70-310) Microsoft MCAD/MCSD certification exam. Appendixes A and B provide quick references on ADO.NET and XML, respectively. The two sample tests (Chapters 13 and 15) at the end of the book should give you a reasonably accurate assessment of your knowledge—and, yes, I’ve provided the answers and explanations to the sample tests’ questions (Chapters 14 and 16). Read the book and understand the material, and you’ll stand a very good chance of passing the test. Exam Cram 2 books help you understand and appreciate the subjects and materials you need to pass Microsoft certification exams. Exam Cram 2 books are aimed strictly at test preparation and review. They do not teach you everything you need to know about a topic. Instead, I’ll present and dissect the questions and problems I’ve found that you’re likely to encounter on a test. I’ve worked to bring together as much information as possible about Microsoft certification exams. Nevertheless, to completely prepare yourself for any Microsoft test, I recommend that you begin by taking the Self-Assessment included in this book, immediately following this introduction. The Self-Assessment tool will help you evaluate your knowledge base against the requirements for a Microsoft Certified Application Developer (MCAD) or Microsoft Certified Solution Developer (MCSD) under both ideal and real circumstances. Based on what you learn from the Self-Assessment, you might decide to begin your studies with some classroom training, some practice with Visual

xxii Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Basic .NET, or some background reading. On the other hand, you might decide to pick up and read one of the many study guides available from Microsoft or third-party vendors on certain topics, including the awardwinning MCAD Training Guide series from Que Publishing. I also recommend that you supplement your study program with visits to www.examcram2.com to receive additional practice questions, get advice, and track the MCAD and MCSD program. I also strongly recommend that you install, configure, and play around with the software you’ll be tested on, because nothing beats hands-on experience and familiarity when it comes to understanding the questions you’re likely to encounter on a certification test. Book learning is essential, but without a doubt, hands-on experience is the best teacher of all! To help you work with the product, I’ve arranged to include all the source code from Que’s MCAD 70-310 Training Guide on the CD-ROM in this book. This provides you an opportunity to read, understand, and extend a lot of additional code that demonstrates various concepts related to the 70-310 exam objectives. The CD-ROM also contains the PrepLogic Practice Tests, Preview Edition examsimulation software. The Preview Edition exhibits most of the full functionality of the Premium Edition but offers questions sufficient for only one practice exam. To get the complete set of practice questions and exam functionality, visit www.preplogic.com.

Taking a Certification Exam After you’ve prepared for your exam, you need to register with a testing center. Each computer-based MCP exam costs $125, and if you don’t pass, you can retest for an additional $125 for each additional try. In the United States and Canada, tests are administered by Prometric and by VUE. Here’s how you can contact them: ➤ Prometric—You can sign up for a test through the company’s Web site at www.prometric.com.

Within the United States and Canada, you can register by phone at 800-755-3926. If you live outside this region, you should check the Prometric Web site for the appropriate phone number. ➤ VUE—You can sign up for a test or get the phone numbers for local test-

ing centers through the Web at www.vue.com/ms. To sign up for a test, you must possess a valid credit card or contact either Prometric or VUE for mailing instructions to send a check (in the United States). Only when payment is verified or your check has cleared can you actually register for the test.

xxiii . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introduction . . . . . . .

To schedule an exam, you need to call the number or visit either of the Web pages at least one day in advance. To cancel or reschedule an exam, you must call before 7 p.m. Pacific standard time the day before the scheduled test time (otherwise, you might be charged, even if you don’t show up to take the test). When you want to schedule a test, you should have the following information ready: ➤ Your name, organization, and mailing address. ➤ Your Microsoft test ID. (Inside the United States, this usually means your

Social Security number; citizens of other nations should call ahead to find out what type of identification number is required to register for a test.) ➤ The name and number of the exam you want to take. ➤ A method of payment. (As mentioned previously, a credit card is the most

convenient method, but alternate means can be arranged in advance, if necessary.) After you sign up for a test, you are told when and where the test is scheduled. You should try to arrive at least 15 minutes early. You must supply two forms of identification—one of which must be a photo ID—and sign a nondisclosure agreement to be admitted into the testing room. All Microsoft exams are completely closed book. In fact, you are not permitted to take anything with you into the testing area, but you are given a blank sheet of paper and a pen (or in some cases an erasable plastic sheet and an erasable pen). I suggest that you immediately write down on that sheet of paper all the information you’ve memorized for the test. In Exam Cram 2 books, this information appears on a tear-out sheet inside the front cover of each book. You are given some time to compose yourself, record this information, and take a sample orientation exam before you begin the real thing. I suggest that you take the orientation test before taking your first exam, but because all the certification exams are more or less identical in layout, behavior, and controls, you probably don’t need to do this more than once. When you complete a Microsoft certification exam, the software tells you immediately whether you’ve passed or failed. If you need to retake an exam, you have to schedule a new test with Prometric or VUE and pay another $125. The first time you fail a test, you can retake the test as soon as the next day. However, if you fail a second time, you must wait 14 days before retaking that test. The 14-day waiting period remains in effect for all retakes after the second failure.

xxiv Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Tracking MCP Status As soon as you pass any Microsoft exam, you attain MCP status. Microsoft generates transcripts that indicate which exams you have passed. You can view a copy of your transcript at any time by going to the MCP secured site and selecting Transcript Tool. This tool enables you to print a copy of your current transcript and confirm your certification status. After you pass the necessary set of exams, you are certified. Official certification is normally granted after three to six weeks, so you shouldn’t expect to get your credentials overnight. The package for official certification that arrives includes a Welcome Kit that contains a number of elements (see Microsoft’s Web site for other benefits of specific certifications): ➤ A certificate that is suitable for framing, along with a wallet card and lapel

pin. ➤ A license to use the applicable logo, which means you can use the logo in

advertisements, promotions, and documents, and on letterhead, business cards, and so on. Along with the license comes a logo sheet, which includes camera-ready artwork. (Note that before you use any of the artwork, you must sign and return a licensing agreement that indicates you’ll abide by its terms and conditions.) ➤ A subscription to Microsoft Certified Professional Magazine, which provides

ongoing data about testing and certification activities, requirements, and changes to the program. Many people believe that the benefits of MCP certification go well beyond the perks that Microsoft provides to newly anointed members of this elite group. We’re starting to see more job listings that request or require applicants to have MCP, MCAD, and other certifications, and many individuals who complete Microsoft certification programs can qualify for increases in pay and/or responsibility. As an official recognition of hard work and broad knowledge, one of the MCP credentials is a badge of honor in many IT organizations.

How to Prepare for an Exam Preparing for any MCAD- or MCSD-related test (including Exam 70-310) requires that you obtain and study materials designed to provide comprehensive information about the product and its capabilities that will appear on

xxv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introduction . . . . . . .

the specific exam for which you are preparing. The following list of materials can help you study and prepare: ➤ The .NET Framework Software Development Kit (SDK). This SDK,

which you can download from

http://msdn.microsoft.com/downloads/

sample.asp?url=/msdn-files/027/000/976/msdncompositedoc.xml,

contains full documentation of .NET and should be a primary resource when you are preparing for the test. ➤ The exam-preparation materials, practice tests, and self-assessment exams

on the Microsoft Training & Services page at www.microsoft.com/traincert. The Exam Resources link offers examples of the new question types found on the MCAD and MCSD exams. You should find the materials, download them, and use them! ➤ The exam-preparation advice, practice tests, questions of the day, and dis-

cussion groups on the www.examcram2.com e-learning and certification destination Web site. In addition, you might find any or all of the following materials useful in your quest for Visual Basic .NET expertise: ➤ Microsoft training kits—Microsoft Press offers a training kit that specifical-

ly targets Exam 70-310. For more information, visit http://www. microsoft.com/mspress/certification/mcad.asp. This training kit contains information that you will find useful in preparing for the test. ➤ Microsoft Developer Network CD-ROM—This quarterly CD-ROM–based

or DVD-based publication delivers numerous electronic titles that include coverage of .NET Framework, Visual Basic .NET, and related topics. Its offerings include product facts, technical notes, tools and utilities, sample code, and much more. A subscription to the MSDN Library costs $199 per year, but it is well worth the price. Visit http://msdn. microsoft.com/subscriptions/prodinfo/overview.asp for more details. ➤ Study guides—Several publishers—including Que Publishing—offer certi-

fication titles. Que Publishing offers the following: ➤ The Exam Cram 2 series—These books give you information about

the material you need to know to pass the tests. ➤ The MCAD Training Guide series—These books provide a greater

level of detail than the Exam Cram 2 books and are designed to teach you everything you need to know about the subject covered by an exam. Each book comes with a CD-ROM that contains interactive practice exams in a variety of testing formats.

xxvi Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Together, these two series make a perfect pair. ➤ Classroom training—Certified Technical Education Centers (CTECs),

online partners, and third-party training companies (such as Wave Technologies, Learning Tree, and Data-Tech) all offer classroom training on Visual Basic .NET. These companies aim to help you prepare to pass Exam 70-310 (or other exams). Although such training runs upward of $350 per day in class, most of the individuals lucky enough to partake find this training to be quite worthwhile. ➤ Other publications—There’s no shortage of materials available about Visual

Basic .NET, XML, and the .NET Framework. The “Need to Know More?” resource sections at the end of each chapter in this book give you an idea of where I think you should look for further discussion. This set of required and recommended materials represents an unparalleled collection of sources and resources for Visual Basic .NET and related topics. I hope you’ll find that this book belongs in the same company.

What This Book Will Not Do This book will not teach you everything you need to know about computers, or even about a given topic. Nor is this book an introduction to computer technology. If you’re new to applications development and looking for an initial preparation guide, check out www.quepublishing.com, where you will find a whole section dedicated to the MCSD/MCAD certifications. This book will review what you need to know before you take the test, with the fundamental purpose dedicated to reviewing the information needed on the Microsoft 70-310 certification exam. This book uses a variety of teaching and memorization techniques to analyze the exam-related topics and to provide you with ways to input, index, and retrieve everything you’ll need to know in order to pass the test. Once again, it is not an introduction to application development.

What This Book Is Designed to Do This book is designed to be read as a pointer to the areas of knowledge you will be tested on. In other words, you may want to read the book one time, just to get an insight into how comprehensive your knowledge of computers is. The book is also designed to be read shortly before you go for the actual test and to give you a distillation of the entire field of Windows application development in as few pages as possible. I think you can use this book to get

xxvii . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introduction . . . . . . .

a sense of the underlying context of any topic in the chapters—or to skimread for Exam Alerts, bulleted points, summaries, and topic headings. I’ve drawn on material from Microsoft’s own listing of knowledge requirements, from other preparation guides, and from the exams themselves. I’ve also drawn from a battery of third-party test-preparation tools and technical Web sites as well as from my own experience with application development and the exam. My aim is to walk you through the knowledge you will need— looking over your shoulder, so to speak—and point out those things that are important for the exam (Exam Alerts, practice questions, and so on). The 70-310 exam makes a basic assumption that you already have a strong background of experience with the Windows development platform and its terminology. On the other hand, because the .NET development environment is so new, no one can be a complete expert. I’ve tried to demystify the jargon, acronyms, terms, and concepts. Also, wherever I think you’re likely to blur past an important concept, I’ve defined the assumptions and premises behind that concept.

About This Book If you’re preparing for the 70-310 certification exam for the first time, I’ve structured the topics in this book to build upon one another. Therefore, the topics covered in later chapters might refer to previous discussions in earlier chapters. I suggest you read this book from front to back. You won’t be wasting your time, because nothing I’ve written is a guess about an unknown exam. I’ve had to explain certain underlying information on such a regular basis that I’ve included those explanations here. Once you’ve read the book, you can brush up on a certain area by using the index or the table of contents to go straight to the topics and questions you want to reexamine. I’ve tried to use the headings and subheadings to provide outline information about each given topic. After you’ve been certified, I think you’ll find this book useful as a tightly focused reference and an essential foundation of .NET application development.

Chapter Formats Each Exam Cram 2 chapter follows a regular structure and provides graphical cues about especially important or useful material. The structure of a typical chapter is as follows:

xxviii Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ Opening hotlists—Each chapter begins with lists of the terms you’ll need to

understand and the concepts you’ll need to master before you can be fully conversant with the chapter’s subject matter. I follow the hotlists with a few introductory paragraphs, setting the stage for the rest of the chapter. ➤ Topical coverage—After the opening hotlists, each chapter covers the top-

ics related to the chapter’s subject. ➤ Alerts—Throughout the topical coverage section, I highlight material

most likely to appear on the exam by using a special Exam Alert layout that looks like this: This is what an Exam Alert looks like. An Exam Alert stresses concepts, terms, software, or activities that will most likely appear in one or more certification exam questions. For that reason, I think any information found offset in Exam Alert format is worthy of unusual attentiveness on your part.

Even if material isn’t flagged as an Exam Alert, all the content in this book is associated in some way with test-related material. What appears in the chapter content is critical knowledge. ➤ Notes—This book is an overall examination of computers. As such, I’ll dip

into many aspects of .NET application development. Where a body of knowledge is deeper than the scope of the book, I use notes to indicate areas of concern or specialty training. Cramming for an exam will get you through a test, but it won’t make you a competent IT professional. Although you can memorize just the facts you need in order to become certified, your daily work in the field will rapidly put you in water over your head if you don’t know the underlying principles of application development.

➤ Tips—I provide tips that will help you to build a better foundation of

knowledge or to focus your attention on an important concept that will reappear later in the book. Tips provide a helpful way to remind you of the context surrounding a particular area of a topic under discussion. You should also carefully read Chapter 1, “Microsoft Certification Exams,” for helpful strategies used in taking a test. The introduction to Chapter 13, “Sample Test #1,” contains additional tips on how to figure out the correct response to a question and what to do if you draw a complete blank.

xxix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introduction . . . . . . . ➤ Exam Prep Questions—This section presents a short list of test questions

related to the specific chapter topic. Each question has a following explanation of both correct and incorrect answers. The practice questions highlight the areas I found to be most important on the exam. ➤ Need to Know More?—Every chapter ends with a section titled “Need To

Know More?” This section provides pointers to resources that I found to be helpful in offering further details on the chapter’s subject matter. If you find a resource you like in this collection, use it, but don’t feel compelled to use all these resources. I use this section to recommend resources that I have used on a regular basis, so none of the recommendations will be a waste of your time or money. Because these resources may go out of print or be taken down (in the case of Web sites), I’ve tried to reference widely accepted resources. The bulk of the book follows this chapter structure, but there are a few other elements I would like to point out: ➤ Practice exams—The sample tests, which appear in Chapters 13 and 15

(with answer keys in Chapters 14 and 16), are very close approximations of the types of questions you are likely to see on the current 70-310 exam. ➤ Answer keys—These provide the answers to the sample tests, complete with

explanations of both the correct responses and the incorrect responses. ➤ Glossary—This is an extensive glossary of important terms used in this

book. ➤ The Cram Sheet—This appears as a tear-away sheet inside the front cover

of this Exam Cram 2 book. It is a valuable tool that represents a collection of the most difficult-to-remember facts and numbers I think you should memorize before taking the test. Remember, you can dump this information out of your head onto a piece of paper as soon as you enter the testing room. These are usually facts that I’ve found require brute-force memorization. You only need to remember this information long enough to write it down when you walk into the test room. Be advised that you will be asked to surrender all personal belongings before you enter the exam room itself. You might want to look at the Cram Sheet in your car or in the lobby of the testing center just before you walk into the testing center. The Cram Sheet is divided into headings, so you can review the appropriate parts just before the exam.

xxx Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ The CD-ROM—The CD-ROM includes many helpful code samples that

demonstrate all the topics on the exam. If you work through the samples on the CD-ROM, you’ll understand the techniques you’re likely to be tested on. The CD-ROM also contains the PrepLogic Practice Tests, Preview Edition exam-simulation software. The Preview Edition exhibits most of the full functionality of the Premium Edition but offers questions sufficient for only one practice exam. To get the complete set of practice questions and exam functionality, visit www.preplogic.com.

Codes and Commands Limitations of printed pages will, many times, require me to write code with smaller margins than you might use in practice. In these cases, I’ve used the Visual Basic .NET line continuation character (_) whenever possible so that the code you see on the printed page is syntactically correct. In some cases, the margins force me to introduce line continuations into code that’s automatically generated by Visual Basic .NET, even though you won’t see those continuations when you re-create the code in your own copy.

Contacting the Author I’ve tried to create a real-world tool that you can use to prepare for and pass the 70-310 MCAD/MCSD certification exam. I’m interested in any feedback you would care to share about the book, especially if you have ideas about how I can improve it for future test-takers. I’ll consider everything you say carefully and will respond to all reasonable suggestions and comments. You can reach me via email at [email protected]. Let me know if you found this book to be helpful in your preparation efforts. I’d also like to know how you felt about your chances of passing the exam before you read the book and then after you read the book. Of course, I’d love to hear that you passed the exam—and even if you just want to share your triumph, I’d be happy to hear from you. Thanks for choosing me as your personal trainer, and enjoy the book. I would wish you luck on the exam, but I know that if you read through all the chapters and work with the product, you won’t need luck—you’ll pass the test on the strength of real knowledge!

Self-Assessment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

The reason I included a Self-Assessment in this Exam Cram 2 book is to help you evaluate your readiness to tackle Microsoft certifications. It should also help you understand what you need to know to master the topic of this book—namely, Exam 70-310 “Developing XML Web Services and Server Components with Microsoft Visual Basic .NET and the Microsoft .NET Framework.” But before you tackle this Self-Assessment, let’s talk about concerns you may face when pursuing an MCSD (Microsoft Certified Solution Developer) or MCAD (Microsoft Certified Application Developer) for the .NET platform and what an ideal MCSD candidate might look like.

MCSDs in the Real World In the next section, I describe an ideal MCSD or MCAD candidate, knowing full well that only a few real candidates will meet this ideal. In fact, my description of that ideal candidate might seem downright scary, especially with the changes that have been made to the program to support the .NET development platform. But take heart: Although the requirements to obtain an MCSD may seem formidable, they are by no means impossible to meet. However, be keenly aware that it does take time, involves some expense, and requires real effort to get through the process. Remember, too, that you can get your MCAD on the way to your MCSD as you continue to develop your skills to the MCSD level. Increasing numbers of people are attaining Microsoft certifications, so the goal is within reach. You can get all the real-world motivation you need from knowing that many others have gone before, so you will be able to follow in their footsteps. If you’re willing to tackle the process seriously and do what it takes to obtain the necessary experience and knowledge, you can take—and pass—all the certification tests involved in obtaining an MCSD or MCAD. Besides MCSD and MCAD, other Microsoft certifications include the following:

xxxii

Self-Assessment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ MCSA (Microsoft Certified Systems Administrator)—This is the brand-new

certification that Microsoft has provided for those Microsoft professionals who are not going to design networks but rather administer them. This certification includes three core exams and a single elective. ➤ MCDBA (Microsoft Certified Database Administrator)—This is aimed at

database administrators and developers who work with Microsoft SQL Server. The MCDBA certification requires three core exams and one elective exam. ➤ Other Microsoft certifications—The requirements for these certifications

range from one test (MCP) to several tests (MCSE).

The Ideal MCSD Candidate The MCSD test is aimed at software developers. The requirements have recently been revised for .NET and include one exam on Web application development, one on Windows application development, one on XML and server development, one on solution architecture, and a fifth, elective exam drawn from a different, but limited, pool of options. The 70-310 exam that this book prepares you for fulfills the XML and server exam requirement for the MCSD. Just to give you some idea of what an ideal MCSD candidate is like, here are some relevant statistics about the background and experience such an individual might have: ➤ Academic or professional training in applications-development theory,

concepts, and operations. This includes everything from programming and deployment planning through database integration and Web deployment. ➤ Two or more years of lead development experience, including business

process analysis, deployment management planning, and solution architecture design within an enterprise. The .NET platform is somewhat different from previous versions of the Microsoft development languages; therefore, you’ll really need some hands-on experience. Due to the structural changes made in creating an object-based development environment built around a Common Language Runtime, the more hands-on experience you have, the better.

xxxiii . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Self-Assessment . . . . . . . . . ➤ Experience in developing applications designed to run within the

Windows 2000 Server, Windows 2000/XP Professional, and soon the Windows .NET Server environments. A solid understanding of each system’s architecture, installation, configuration, maintenance, and troubleshooting is also helpful when testing your code. ➤ A thorough understanding of the software-development lifecycle is

important, including analysis, design, development, testing, deployment, and maintenance of an application. ➤ An understanding of how to implement security for key network data in a

Windows 2000/XP environment. ➤ Experience developing XML and server components in the .NET envi-

ronment. ➤ Working knowledge of the .NET programming environment, preferably

with some hands-on experience with the Microsoft Visual Studio .NET development tools. The time you take practicing the use of Visual Studio .NET will be time very well spent! Don’t worry if you don’t meet these qualifications or don’t even come that close—this is a far-from-ideal world, and where you fall short is simply where you’ll have more work to do.

Fundamentally, this boils down to a bachelor’s degree in computer science (or equivalent experience on the job), plus two years’ experience working in a position involving applications design, testing, deployment, and maintenance, with some experience in database integration. I believe that well under half of all certification candidates meet these requirements and that, in fact, most meet less than half of these requirements—at least, when they begin the certification process. But because all the people who already have been certified have survived this ordeal, you can survive it, too—especially if you heed what this Self-Assessment can tell you about what you already know and what you need to learn.

Put Yourself to the Test The following series of questions and observations is designed to help you figure out how much work you must do to pursue Microsoft certification and what kinds of resources you should consult on your quest. Be absolutely honest in your answers; otherwise, you’ll end up wasting money on exams you’re

xxxiv Self-Assessment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

not yet ready to take. There are no right or wrong answers, only steps along the path to certification. Only you can decide where you really belong in the broad spectrum of aspiring candidates. Two things should be clear from the outset, however: ➤ Even a modest background in computer science and programming will be

helpful. ➤ Hands-on experience with Microsoft products and technologies is an

essential ingredient to Microsoft certification success.

Educational Background 1. Have you ever taken any computer-related classes? [Yes or No]

If Yes, proceed to Question 2; if No, proceed to Question 4. 2. Have you taken any classes on computer operating systems? [Yes or No]

If Yes, you will probably be able to handle Microsoft’s architecture and system component discussions. If you’re rusty, brush up on basic operating system concepts and general computer security topics. If No, consider some basic reading in this area. I strongly recommend a good general operating systems book, such as Operating System Concepts, 5th Edition, by Abraham Silberschatz and Peter Baer Galvin (John Wiley & Sons, 1998). If this title doesn’t appeal to you, check out reviews for other, similar titles at your favorite online bookstore. 3. Have you taken any programming classes, particularly ones focused on

Microsoft development languages and the .NET platform? [Yes or No] If Yes, you will probably be able to handle Microsoft’s terminology, concepts, and technologies (brace yourself for frequent departures from normal usage). If you’re rusty, brush up on basic programming concepts and terminology, with an eye toward the .NET development methodology. If No, you might want to read one or two books in this topic area. The best book that I know of is Applied Microsoft .NET Framework Programming, by Jeffrey Richter (Microsoft Press, 2002). 4. Have you done any reading on programming? [Yes or No]

If Yes, review the requirements stated in the first paragraphs after Questions 2 and 3. If you meet those requirements, move on to the next section.

xxxv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Self-Assessment . . . . . . . . .

If No, consult the recommended reading previously discussed in this section for both topics. A strong background will help you prepare for the Microsoft exams better than just about anything else.

Hands-on Experience The most important key to success on all the Microsoft tests is hands-on experience, especially with the Visual Studio .NET interface. If I leave you with only one realization after taking this Self-Assessment, it should be that there’s no substitute for time spent creating, configuring, and deploying applications created using the Visual Basic .NET product, upon which you’ll be tested repeatedly and in depth. You can download objectives, practice exams, and other data about Microsoft exams from the Training and Certification page at http://www.microsoft.com/ traincert/. Use the “Microsoft Certifications” link to obtain specific exam information.

5. Have you installed, configured, or used Visual Studio .NET and the

.NET Framework? [Yes or No] If Yes, you should be familiar with the main parts of the Visual Studio .NET Integrated Development Environment (IDE) and will be prepared to follow the examples in this book. If No, you must get some experience. Read on for suggestions on how to do this. Experience is a must with any Microsoft product exam, be it something as simple as FrontPage 2000 or as challenging as SQL Server 2000. For trial copies of other software, search Microsoft’s Web site using the name of the product as your search term. Also, search for bundles such as “BackOffice” or “Small Business Server.” 6. Have you developed any server-side components such as Web Services,

remoting objects, or serviced components? If Yes, you will be able to handle the sections of the exam dealing with these components. If No, you must get some experience with these particular types of components. The best experience is hands-on work in a client/server environment. You might also choose to work through a study guide such as the Que 70-310 Training Guide.

xxxvi Self-Assessment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7. Do you have experience creating and reading XML files?

If Yes, you’re ready to tackle the extensive XML content of the 70-310 exam. If No, you must ensure that you have a basic understanding of XML to pass this exam. Appendix B, “XML Standards and Syntax,” introduces you to the subject. You may also want to visit the Web site of the World Wide Web Consortium at http://www.w3c.org/ to view the many official specifications and documents relating to XML. If you have the funds, or your employer will pay your way, consider taking a class at a Certified Training and Education Center (CTEC). In addition to classroom exposure to the topic of your choice, you usually get a copy of the software that is the focus of your course, along with a trial version of whatever operating system it needs, with the training materials for that class.

Before you even think about taking any Microsoft exam, make sure you’ve spent enough time with the related software to understand how it may be installed, configured, and used. This will help you in the exam, and in real life!

Testing Your Exam-Readiness Whether you attend a formal class on a specific topic to get ready for an exam or use written materials to study on your own, some preparation for the Microsoft certification exams is essential. At $125 a try, pass or fail, you want to do everything you can to pass on your first try. That’s where studying comes in. I have included two practice exams in this book (Chapters 13 and 15), so if you don’t score that well on the first, you can study more and then tackle the second. For any given subject, consider taking a class if you’ve tackled self-study materials, taken the test, and failed anyway. The opportunity to interact with an instructor and fellow students can make all the difference in the world, if you can afford that privilege. For information about Microsoft classes, visit the Training and Certification page at http://www.microsoft.com/education/ partners/ctec.asp for Microsoft Certified Education Centers.

xxxvii . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Self-Assessment . . . . . . . . .

If you can’t afford to take a class, visit the Training page at http://www.microsoft.com/traincert/training/find/default.asp anyway, because it also includes pointers to free practice exams and to Microsoft Certified Professional Approved Study Guides and other self-study tools. And even if you can’t afford to spend much at all, you should still invest in some low-cost practice exams from commercial vendors. 8. Have you taken a practice exam on your chosen test subject? [Yes or No]

If Yes, and you scored 70% or better, you’re probably ready to tackle the real thing. If your score isn’t above that threshold, keep at it until you break that barrier. If No, obtain all the free and low-budget practice tests you can find and get to work. Keep at it until you can break the passing threshold comfortably. When it comes to assessing your test readiness, there is no better way than to take a good-quality practice exam and pass with a score of 70% or better. When I’m preparing myself, I shoot for 80% or more, just to leave room for the “weirdness factor” that sometimes shows up on Microsoft exams. That is, you can know the material and still miss a question because it is worded in a peculiar way.

Assessing Readiness for Exam 70-310 In addition to the general exam-readiness information in the previous section, there are several things you can do to prepare for the Developing XML Web Services and Server Components with Microsoft Visual Basic .NET and the .NET Framework exam. I suggest that you join an active Microsoft Developers mailing list, obtain a Microsoft Developer Network (MSDN) subscription, and regularly visit the MSDN Web site for new information (http://msdn.microsoft.com). Microsoft exam mavens also recommend checking the Microsoft Knowledge Base (integrated into the MSDN CD-ROM, or on the Microsoft Web site at http://support.microsoft.com/support/) for “meaningful technical support issues” that relate to your exam’s topics. Although I’m not sure exactly what the quoted phrase means, I have noticed some overlap between technical support questions on particular products and troubleshooting questions on the exams for those products.

xxxviii Self-Assessment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

What’s Next? After you’ve assessed your readiness, undertaken the right background studies, obtained the hands-on experience that will help you understand the products and technologies at work, and reviewed the many sources of information to help you prepare for a test, you’ll be ready to take a round of practice tests. When your scores come back positive enough to get you through the exam, you’re ready to go after the real thing. If you follow my assessment regime, you’ll not only know what you need to study but also when you’re ready to make a test date at Prometric (www.prometric.com) or VUE (www.vue.com). Good luck!

1 Microsoft Certification Exams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Terms you’ll need to understand: ✓ Case study ✓ Multiple-choice question formats ✓ Build-list-and-reorder question format ✓ Create-a-tree question format ✓ Drag-and-connect question format ✓ Select-and-place question format ✓ Fixed-length tests ✓ Simulations ✓ Adaptive tests ✓ Short-form tests

Techniques you’ll need to master: ✓ Assessing your exam readiness ✓ Answering Microsoft’s varying question types ✓ Altering your test strategy depending on the exam format ✓ Practicing (to make perfect) ✓ Making the best use of the testing software ✓ Budgeting your time ✓ Guessing (as a last resort)

2

Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Exam-taking is not something that most people anticipate eagerly, no matter how well prepared they may be. In most cases, familiarity helps offset test anxiety. In plain English, this means you probably won’t be as nervous when you take your fourth or fifth Microsoft certification exam as you’ll be when you take your first one. Whether it’s your first exam or your tenth, understanding the details of taking the new exam (how much time to spend on questions, the environment you’ll be in, and so on) and the new exam software will help you concentrate on the material rather than on the setting. Likewise, mastering a few basic exam-taking skills should help you recognize (and perhaps even outfox) some of the tricks and snares you’re bound to find in some exam questions. This chapter explains the exam environment and software and describes some proven exam-taking strategies you can use to your advantage.

Assessing Exam-Readiness I strongly recommend that you read through and take the Self-Assessment included with this book (it appears after the introduction in this book). This will help you compare your knowledge base to the requirements for obtaining an MCAD (Microsoft Certified Application Developer) or MCSD (Microsoft Certified Solution Developer), and it will also help you identify parts of your background or experience that may need improvement or enhancement as well as where you need further learning. If you get the right set of basics under your belt, obtaining Microsoft certification will be that much easier. After you’ve gone through the Self-Assessment, you can remedy those topical areas in which your background or experience may be lacking. You can also tackle subject matter for individual tests at the same time, so you can continue making progress while you’re catching up in some areas. After you’ve worked through an Exam Cram 2, have read the supplementary materials, and have taken the practice test, you’ll have a pretty clear idea of when you should be ready to take the real exam. Although I strongly recommend that you keep practicing until your scores top the 70% mark, 80% is a better goal because it gives some margin for error when you are in an actual, stressful exam situation. Keep taking practice tests and studying the materials until you attain that score. You’ll find more pointers on how to study and prepare in the Self-Assessment. But now, on to the exam itself.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . .

What to Expect at the Testing Center When you arrive at the testing center where you scheduled your exam, you must sign in with an exam coordinator and show two forms of identification, one of which must be a photo ID. After you’ve signed in and your time slot arrives, you’ll be asked to deposit any books, bags, cell phones, or other items you brought with you. Then, you’ll be escorted into a closed room. All exams are completely closed book. Although you are not permitted to take anything with you into the testing area, you are furnished with a blank sheet of paper and a pen (in some cases, an erasable plastic sheet and an erasable pen). Immediately before entering the testing center, try to memorize as much of the important material as you can so that you can write that information on the blank sheet as soon as you are seated in front of the computer. You can refer to this piece of paper during the test, but you’ll have to surrender the sheet when you leave the room. Because your timer does not start until you begin the testing process, it is best to do this first while the information is still fresh in your mind. You will have some time to compose yourself, write down information on the paper you’re given, and take a sample orientation exam before you begin the real thing. I suggest you take the orientation test before taking your first exam (because the exams are generally identical in layout, behavior, and controls, you probably won’t need to do this more than once). Typically, the room has one to six computers, and each workstation is separated from the others by dividers. Most test rooms feature a wall with a large picture window. This permits the exam coordinator to monitor the room, prevent exam-takers from talking to one another, and observe anything out of the ordinary. The exam coordinator will have preloaded the appropriate Microsoft certification exam (for this book, Exam 70-310), and you’ll be permitted to start as soon as you’re seated in front of the computer. All Microsoft certification exams allow a certain maximum amount of time in which to complete your work (this time is indicated on the exam by an onscreen counter/clock, so you can check the time remaining whenever you like). All Microsoft certification exams are computer generated. In addition to multiple choice, you may encounter select and place (drag and drop), create a tree (categorization and prioritization), drag and connect, and build list and reorder (list prioritization) on some exams. The questions are constructed to check your mastery of basic facts and figures about developing serverside solutions with Microsoft Visual Basic .NET and require you to evaluate

3

4

Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

one or more sets of circumstances or requirements. Often, you’ll be asked to give more than one answer to a question. You may also be asked to select the best or most effective solution to a problem from a range of choices, all of which are technically correct.

Exam Layout and Design The format of Microsoft exams can vary. For example, many exams consist of a series of case studies, with six types of questions regarding each presented case. Other exams may have the same six types of questions but no complex multi-question case studies. In this chapter, I’ll show you the wide range of questions that you might encounter on Microsoft exams, even though not all of these types of questions will appear on the 70-310 exam. For the Design exams, each case study presents a detailed problem that you must read and analyze. Figure 1.1 shows an example of what a case study looks like. You must select the different tabs in the case study to view the entire case.

Figure 1.1 This is a typical case study.

Following each case study is a set of questions related to the case study. These questions can be one of several types (which are discussed next). Careful attention to details provided in the case study is the key to success. Be prepared to toggle frequently between the case study and the questions as you work. Some of the case studies also include diagrams (called exhibits) that you’ll need to examine closely to understand how to answer the questions. After you complete a case study, you can review all the questions and your answers. However, when you move on to the next case study, you cannot return to the previous case study and make any changes.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . .

Following are the types of question formats: ➤ Multiple-choice, single answer ➤ Multiple-choice, multiple answers ➤ Build list and reorder (list prioritization) ➤ Create a tree ➤ Drag and connect ➤ Select and place (drag and drop) ➤ Hot area

Multiple-Choice Question Format Some exam questions require you to select a single answer, whereas others ask you to select multiple correct answers. The following multiple-choice question requires you to select a single correct answer. Following the question is a brief summary of each potential answer and why it is either right or wrong.

Question 1 You have three domains connected to an empty root domain under one contiguous domain name: tutu.com. This organization is formed into a forest arrangement with a secondary domain called frog.com. How many Schema Masters exist for this arrangement? ❍ A. One ❍ B. Two ❍ C. Three ❍ D. Four

Answer A is correct. Only one Schema Master is necessary for a forest arrangement. The other answers (B, C, and D) are misleading because you are led to believe that Schema Masters may be in each domain or that you should have one for each contiguous domain namespace.

5

6

Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

This sample question format corresponds closely to the Microsoft certification exam format (of course, questions are not followed by answer keys on the exam). To select an answer, you position the cursor over the radio button next to the answer and click the mouse button to select it. Let’s examine a question where one or more answers are possible. This type of question provides check boxes rather than radio buttons (circles) for marking all appropriate selections.

Question 2 How can you seize FSMO roles? [Select all correct answers.] ❑ A. By using the ntdsutil.exe utility ❑ B. By using the Replication Monitor ❑ C. By using the secedit.exe utility ❑ D. By using Active Directory Domains and Trusts

Answers A and B are correct. You can seize FSMO roles from a server that is still running through the Replication Monitor, or in the case of a server failure, you can seize roles with the ntdsutil.exe utility. The secedit.exe utility is used to force group policies into play; therefore, answer C is incorrect. Active Directory Domains and Trusts is a combination of truth and fiction; therefore, answer D is incorrect. For this particular question, two answers are required. Microsoft sometimes gives partial credit for partially correct answers. For Question 2, you have to check the boxes next to answers A and B to obtain credit for a correct answer. Notice that picking the right answers also means knowing why the other answers are wrong.

Build-List-and-Reorder Question Format Questions in the build-list-and-reorder format present two lists of items: one on the left and one on the right. To answer the question, you must move items from the list on the right to the list on the left. The final list must then be arranged into a specific order.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . .

These questions are usually in the form, “From the following list of choices, pick the choices that answer the question. Then arrange the list in a certain order.” To give you practice with this type of question, some questions of this type are included in this study guide. Here’s an example of how they appear in this book; for an example of how they appear on the test, see Figure 1.2.

Figure 1.2 This is how build-list-and-reorder questions appear.

Question 3 From the following list of famous people, pick those that have been elected President of the United States. Arrange the list in the order in which they served. Thomas Jefferson Ben Franklin Abe Lincoln George Washington Andrew Jackson Paul Revere

7

8

Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

The correct answer is: George Washington Thomas Jefferson Andrew Jackson Abe Lincoln On an actual exam, the entire list of famous people would initially appear in the list on the right. You would move the four correct answers to the list on the left and then reorder the list on the left. Notice that the answer to the question did not include all items from the initial list. However, this may not always be the case. To move an item from the right list to the left list, first select the item by clicking it and then clicking the Add button (left arrow). Once you move an item from one list to the other, you can move the item back by first selecting the item and then clicking the appropriate button (either the Add button or the Remove button). After items have been moved to the left list, you can reorder the list by selecting an item and clicking the up or down button.

Create-a-Tree Question Format Questions in the create-a-tree format also present two lists: one on the left and one on the right. The list on the right consists of individual items, and the list on the left consists of nodes in a tree. To answer the question, you must move items from the list on the right to the appropriate node in the tree. These questions are basically a matching exercise. Items from the list on the right are placed under the appropriate category in the list on the left. Here’s an example of how they appear in this book. For an example of how they appear on the test, see Figure 1.3.

Question 4 The calendar year is divided into four seasons: Winter Spring Summer Fall

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . .

Identify the season when each of the following holidays occurs: Christmas Fourth of July Labor Day Flag Day Memorial Day Washington’s Birthday Thanksgiving Easter

The correct answer is: Winter Christmas Washington’s Birthday Spring Flag Day Memorial Day Easter Summer Fourth of July Labor Day Fall Thanksgiving In this case, all the items in the list were used. However, this may not always be the case. To move an item from the right list to its appropriate location in the tree, you must first select the appropriate tree node by clicking it. Then, you select the item to be moved and click the Add button. If one or more items have been added to a tree node, the node is displayed with a plus sign (+) icon to the left of the node name. You can click this icon to expand the node and view whatever was added. If any item has been added to the wrong tree node, you can remove it by selecting it and clicking the Remove button (see Figure 1.3).

9

10

Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Figure 1.3 This is how create-a-tree questions appear.

Drag-and-Connect Question Format Questions in the drag-and-connect format present a group of objects and a list of “connections.” To answer the question, you must move the appropriate connections between the objects. This type of question is best described using graphics. Here’s an example:

Question 5 The following objects represent the different states of water:

Use items from the following list to connect the objects so that they are scientifically correct. Sublimates to form Freezes to form

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . .

Evaporates to form Boils to form Condenses to form Melts to form

The correct answer is:

For this type of question, it’s not necessary to use every object, but each connection can be used multiple times by dragging the answer to multiple locations. Dragging an answer away from its position removes it.

Select-and-Place Question Format Questions in the select-and-place (drag-and-drop) format present a diagram with blank boxes and a list of labels that must be dragged to fill in the blank boxes. To answer the question, you must move the labels to their appropriate positions on the diagram. This type of question is best described using graphics. Here’s an example:

Question 6 Place the items in their proper order, by number, on the following flowchart. Some items may be used more than once, and some items might not be used at all.

11

12

Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

The correct answer is:

Hot Area This type of question asks you to select one or more areas on a graphic to indicate the correct answer to a question. The hot spots on the graphic will be shaded when you move the mouse over them, and they are marked with an obvious border. To select or deselect an element, just click it. A simple hot-area question might present a screenshot of the Visual Studio .NET interface and ask you to indicate the tab that allows you to retrieve information on particular databases. In that case, you’d click the Server Explorer tab to answer the question.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . .

Microsoft’s Testing Formats Currently, Microsoft uses four different testing formats: ➤ Case study ➤ Fixed length ➤ Adaptive ➤ Short form

Currently, the 70-310 exam uses the fixed-length format, but you should be aware of the other formats as well. Microsoft revises popular exams from time to time and sometimes changes their format. As mentioned earlier, the case study approach is used with many of the newer Microsoft exams. These exams consist of a set of case studies that you must first analyze to answer questions related to the case studies. Such exams include one or more case studies (tabbed topic areas), each of which is followed by 4 to 10 questions. The question types for exams will be multiple choice, build list and reorder, create a tree, drag and connect, and select and place. Depending on the test topic, some exams are totally case based, whereas others are not at all. Other Microsoft exams employ advanced testing capabilities that may not be immediately apparent. Although the questions that appear are primarily multiple choice, the logic in fixed-length tests, which use a fixed sequence of questions, is more complex than that in older Microsoft tests. Some questions employ a sophisticated user interface (which Microsoft calls a simulation) to test your knowledge of particular software and systems in a simulated “live” environment that behaves just like the original. The Testing Innovations article at http://www.microsoft.com/TRAINCERT/mcpexams/faq/innovations.asp includes a downloadable series of demonstrations and examples. For some exams, Microsoft has turned to a well-known technique called adaptive testing to establish a test-taker’s level of knowledge and product competence. Adaptive exams look the same as fixed-length exams, but they determine the level of difficulty at which an individual test-taker can correctly answer questions. Test-takers with differing levels of knowledge or ability see different sets of questions; individuals with a high level of knowledge or ability are presented with a smaller set of more difficult questions, whereas individuals with a lower level of knowledge or ability are presented with a larger set of easier questions. Two individuals may answer the same percentage of

13

14

Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

questions correctly, but the test-taker with a higher knowledge or ability level scores higher because his or her questions are weighted more heavily. Also, lower-level test-takers may answer more questions than moreknowledgeable colleagues. This explains why adaptive tests use ranges of values to define the number of questions and the amount of time needed to complete the tests. Adaptive tests work by evaluating the test-taker’s most recent answer. A correct answer leads to a more difficult question and also raises the test software’s estimate of the test-taker’s knowledge and ability level. An incorrect answer leads to a less difficult question and also lowers the test software’s estimate of the test-taker’s knowledge and ability level. This process continues until the test targets the test-taker’s true ability level. The exam ends when the test-taker’s level of accuracy meets a statistically acceptable value (in other words, when his or her performance demonstrates an acceptable level of knowledge and ability) or when the maximum number of items has been presented (in which case, the test-taker is almost certain to fail). Microsoft has also introduced a short-form test for its most popular tests. This test consists of 25 to 30 questions, with a time limit of exactly 60 minutes. This type of exam is similar to a fixed-length test because it allows readers to jump ahead or return to earlier questions and to cycle through the questions until the test is done. Microsoft does not use adaptive logic in this test; it claims that statistical analysis of the question pool is such that the 25 to 30 questions delivered during a short-form exam conclusively measure a test-taker’s knowledge of the subject matter in much the same way as an adaptive test. The short-form test is like a “greatest hits exam” version (that is, the most important questions are covered) of an adaptive exam on the same topic. Some of the Microsoft exams may contain a combination of adaptive and fixed-length questions.

Because you won’t know in which form the Microsoft exam may be, you should be prepared for an adaptive exam instead of a fixed-length or a shortform exam. The penalties for answering incorrectly are built in to the test itself on an adaptive exam, whereas the layout remains the same for a fixed-length or short-form test, no matter how many questions you answer incorrectly. Most likely, you’ll see a fixed-length exam for 70-310. But be prepared, just in case!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . .

The biggest difference between adaptive tests and fixed-length and short-form tests is that you can mark and revisit questions on fixed-length and short-form tests after you’ve read them. On an adaptive test, you must answer the question when it is presented and cannot go back to that question later.

Strategies for Different Testing Formats Before you choose a test-taking strategy, you must determine what type of test it is—case study, fixed length, short form, or adaptive: ➤ Case study tests consist of a tabbed window that allows you to navigate

easily through the sections of the case. ➤ Fixed-length tests consist of 50 to 70 questions with a check box for

each question. You can return to these questions if you want. ➤ Short-form tests have 25 to 30 questions with a check box for each ques-

tion. You can return to these questions if you want. ➤ Adaptive tests are identified in the introductory material of the test.

Questions have no check boxes and can be visited (and answered) only once. Some tests contain a variety of testing formats. For example, a test may start with a set of adaptive questions, followed by fixed-length questions. As I mentioned earlier, the initial release of the 70-310 exam is fixed length, so you should concentrate on strategies for that type of exam. You’ll be able to tell for sure whether you are taking an adaptive, fixed-length, or short-form test by the first question. Fixed-length and short-form tests include a check box that allows you to mark the question for later review. Adaptive test questions include no such check box and can be visited (and answered) only once.

Case Study Exam Strategy Though you won’t find this kind of format for the 70-310 test, you might find the test-taking strategies beneficial, and if you ever take a case study exam, you’ll want to review this section. Most test-takers find that the case study type of exam is the most difficult to master. When it comes to studying for a case study test, your best bet is to approach each case study as a standalone test. The biggest challenge you’ll encounter is that you’ll feel you won’t have enough time to get through all the cases presented.

15

16

Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Each case provides a lot of material you’ll need to read and study before you can effectively answer the questions that follow. The trick to taking a case study exam is to first scan the case study to get the highlights. Make sure you read the overview section of the case so that you understand the context of the problem at hand. Then, quickly move on and scan the questions. As you are scanning the questions, make mental notes to yourself or notes on your paper so that you’ll remember which sections of the case study you should focus on. Some case studies may provide a fair amount of extra information that you don’t really need to answer the questions. The goal with this scanning approach is to avoid having to study and analyze material that is not completely relevant.

When studying a case, read the tabbed information carefully. It is important to answer each and every question. You will be able to toggle back and forth from case to questions, and from question to question, within a case testlet. However, after you leave the case and move on, you might not be able to return to it. I suggest that you take notes while reading useful information to help you when you tackle the test questions. It’s hard to go wrong with this strategy when taking any kind of Microsoft certification test.

Fixed-Length and Short-Form Exam Strategy A well-known principle when taking a fixed-length or short-form exam is first to read through the entire exam from start to finish. Answer only those questions that you feel absolutely sure you know. On subsequent passes, you can dive into complex questions more deeply, knowing how many such questions you have left and the amount of time remaining. There’s at least one potential benefit to reading the exam over completely before answering the trickier questions: Sometimes, information supplied in later questions sheds more light on earlier questions. At other times, information you read in later questions may jog your memory about facts, figures, or behaviors that help you answer earlier questions. Either way, you’ll come out ahead if you answer only those questions on the first pass that you’re absolutely confident about.

Fortunately, the Microsoft exam software for fixed-length and short-form tests makes the multiple-visit approach easy to implement. At the top-left corner of each question is a check box that permits you to mark that question for a later visit.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . . Marking questions makes later review easier, but you can return to any question by clicking the Forward or Back button repeatedly. Of course, on an adaptive exam, this isn’t possible.

Here are some question-handling strategies that apply to fixed-length and short-form tests. Use them if you have the chance: ➤ When returning to a question after your initial read-through, read every

word again; otherwise, your mind can miss important details. Sometimes, revisiting a question after turning your attention elsewhere lets you see something you missed, but the strong tendency is to see what you’ve seen before. Try to avoid that tendency at all costs. ➤ If you return to a question more than twice, try to articulate to yourself

what you don’t understand about the question, why answers don’t appear to make sense, or what appears to be missing. If you chew on the subject awhile, your subconscious may provide the missing details, or you may notice a “trick” that points to the right answer. As you work your way through the exam, another counter that Microsoft provides comes in handy—the number of questions completed and questions outstanding. For fixed-length and short-form tests, it’s wise to budget your time by making sure you’ve completed roughly one-quarter of the questions one-quarter of the way through the exam period, and three-quarters of the questions three-quarters of the way through. If you’re not finished when only 5 minutes remain, use that time to guess your way through any remaining questions. Remember, guessing is potentially more valuable than not answering. Blank answers are always wrong, but a guess may turn out to be right. If you don’t have a clue about any of the remaining questions, pick answers at random or choose all A’s, B’s, and so on. Questions left unanswered are counted as answered incorrectly, so a guess is better than nothing at all. At the very end of your exam period, you’re better off guessing than leaving questions unanswered.

17

18

Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Adaptive Exam Strategy This type of exam format will not appear in the 70-310 exam; however, an overview of how to approach adaptive exams might benefit you when taking a future version of the 70-310 exam or if you ever need to take an adaptive exam. If there’s one principle that applies to taking an adaptive test, it’s “Get it right the first time.” You cannot elect to skip a question and move on to the next one when taking an adaptive test, because the testing software uses your answer to the current question to select whatever question it plans to present next. You also cannot return to a question because the software gives you only one chance to answer the question. You can, however, take notes as you work through the test. Sometimes, information supplied in earlier questions may help you answer later questions. Also, when you answer a question correctly, you are presented with a more difficult question next, to help the software gauge your level of skill and ability. When you answer a question incorrectly, you are presented with a less difficult question, and the software lowers its current estimate of your skill and ability. This continues until the program settles into a reasonably accurate estimate of what you know and can do. The good news is that if you know the material, you’ll probably finish most adaptive tests in 30 minutes or so. The bad news is that you must really know the material well to do your best on an adaptive test. That’s because some questions are so convoluted, complex, or hard to follow that you’re bound to miss one or two, at a minimum. Therefore, the more you know, the better you’ll do on an adaptive test, even accounting for the occasionally strange or unfathomable questions that appear on these exams. Because you can’t always tell in advance whether a test is fixed length, short form, adaptive, or a combination of these, you should prepare for the exam as if it were adaptive. That way, you will be prepared to pass, no matter what kind of test you take. If the test turns out to be fixed length or short form, remember the tips from the preceding section, which will help you improve on what you could do on an adaptive test.

If you encounter a question on an adaptive test that you can’t answer, you must guess an answer quickly. (However, you may suffer for your guess on the next question if you guess correctly, because the software will give you a more difficult question next!)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . .

Question-Handling Strategies For those questions that have only one right answer, usually two or three of the answers will be obviously incorrect, and two of the answers will be plausible. Unless the answer leaps out at you (if it does, reread the question to look for a trick; sometimes those are the ones you’re most likely to get wrong), begin the process of answering by eliminating those answers that are most obviously wrong. At least one answer out of the possible choices for a question can usually be eliminated immediately because it matches one of these conditions: ➤ The answer does not apply to the situation. ➤ The answer describes a nonexistent issue, an invalid option, or an imagi-

nary state. After you eliminate all answers that are obviously wrong, you can apply your retained knowledge to eliminate further answers. Look for items that sound correct but refer to actions, commands, or features that are not present or not available in the situation the question describes. If you’re still faced with a blind guess among two or more potentially correct answers, reread the question. Try to picture how each of the possible remaining answers would alter the situation. Be especially sensitive to terminology; sometimes the choice of words (“remove” instead of “disable”) can make the difference between a right answer and a wrong one. You should guess at an answer only after you’ve exhausted your ability to eliminate answers and are still unclear about which of the remaining possibilities is correct. An unanswered question offers you no points, but guessing gives you at least some chance of getting a question right; just don’t be too hasty when making a blind guess. If you’re taking a fixed-length or a short-form test, you can wait until the last round of reviewing marked questions (just as you’re about to run out of time or unanswered questions) before you start making guesses. You will usually have the same option within each case study testlet (but once you leave a testlet, you may not be allowed to return to it). If you’re taking an adaptive test, you’ll have to guess to move on to the next question if you can’t figure out an answer some other way. Either way, guessing should be your technique of last resort!

Numerous questions assume that the default behavior of a particular utility is in effect. If you know the defaults and understand what they mean, this knowledge will help you cut through many Gordian knots. Simple “final”

19

20

Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

actions may be critical as well. If a utility must be restarted before proposed changes take effect, a correct answer may require this step as well.

Mastering the Inner Game In the final analysis, knowledge gives confidence, and confidence breeds success. If you study the materials in this book carefully and review all the practice questions at the end of each chapter, you should become aware of those areas where additional learning and study are required. After you’ve worked your way through the book, take the practice exams in the back of the book. Taking these tests provides a reality check and helps you identify areas to study further. Make sure you follow up and review materials related to the questions you miss on the practice exams before scheduling a real exam. Don’t schedule your exam appointment until after you’ve thoroughly studied the material and feel comfortable with the whole scope of the practice exams. You should score 80% or better on one of the practice exams before proceeding to the real thing (otherwise, obtain some additional practice tests so you can keep trying until you hit this magic number). If you take a practice exam and don’t get at least 80% of the questions correct, keep practicing. Microsoft provides links to practice exam providers and also selfassessment exams at http://www.microsoft.com/traincert/mcpexams/prepare/.

Armed with the information in this book and with the determination to augment your knowledge, you should be able to pass the certification exam. However, you need to work at it, or you’ll spend the exam fee more than once before you finally pass. If you prepare seriously, you should do well. The next section covers other sources you can use to prepare for the Microsoft certification exams.

Additional Resources A good source of information about Microsoft certification exams comes from Microsoft itself. Because its products and technologies—and the exams that go with them—change frequently, the best place to go for exam-related information is online.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . .

If you haven’t already visited the Microsoft Certified Professional site, do so right now. The MCP home page resides at http://www.microsoft.com/ traincert/default.asp (see Figure 1.4).

Figure 1.4 The Microsoft Certified Professional Training and Certification home page.

Coping with Change on the Web Sooner or later, all the information I’ve shared with you about the Microsoft Certified Professional pages and the other Web-based resources mentioned throughout the rest of this book will go stale or be replaced by newer information. In some cases, the URLs you find here may lead you to their replacements; in other cases, the URLs will go nowhere, leaving you with the dreaded “404 File not found” error message. When that happens, don’t give up. There’s always a way to find what you want on the Web if you’re willing to invest some time and energy. Most large or complex Web sites (such as the Microsoft site) offer a search engine. On all of Microsoft’s Web pages, a Search button appears along the top edge of the page. As long as you can get to the Microsoft site (it should stay at www.microsoft.com for a long time), you can use this tool to help you find what you need. The more focused you can make a search request, the more likely the results will include information you can use. For example, you can search for the string “training and certification”

21

22

Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . to produce a lot of data about the subject in general, but if you’re looking for the preparation guide for Exam 70-310, “Developing XML Web Services and Server Components with Microsoft Visual Basic .NET and the Microsoft .NET Framework,” you’ll be more likely to get there quickly if you use a search string similar to the following: “Exam 70-310” AND “preparation guide”

Likewise, if you want to find the Training and Certification downloads, try a search string such as this: “training and certification” AND “download page”

Finally, feel free to use general search tools—such as www.google.com, www.altavista.com, and www.excite.com—to look for related information. Although Microsoft offers great information about its certification exams online, there are plenty of third-party sources of information and assistance that need not follow Microsoft’s party line. Therefore, if you can’t find something immediately, intensify your search.

2 Creating and Manipulating DataSets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Terms you’ll need to understand: ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓

Attribute Ad hoc query DataSet DataSet schema Element Identity Key Metadata Nested relationship

✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓

One-to-many relationship Osql Parameter Simple type SQL-92 SQL Query Analyzer Stored procedure Strongly typed DataSet Transact-SQL (T-SQL)

Techniques you’ll need to master: ✓ Creating a DataSet schema by dragging and dropping a table from Server Explorer to a Visual Basic .NET application ✓ Using the schema designer to edit a DataSet schema ✓ Using the schema designer to create a relationship between two tables in a DataSet schema

✓ Creating a strongly typed DataSet from a DataSet schema ✓ Writing code that refers to data in a strongly typed DataSet ✓ Constructing and interpreting simple Transact-SQL statements, including SELECT, INSERT, UPDATE, and DELETE

24

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

The exam presumes that you already have a working knowledge of ADO.NET. (If you need a refresher course, refer to Appendix A, “ADO.NET Basics.”) The core object of ADO.NET is the DataSet, which provides a complete in-memory relational database. To pass the exam, you’ll need to know how to manipulate the schema of a DataSet, as well as how to instantiate a strongly typed DataSet from a schema. You’ll also need to know the basics of Structured Query Language (SQL). Any databases referred to on the exam will most likely use Microsoft SQL Server to store their data. Be sure you know how to select and alter data from a SQL Server database.

Manipulating a DataSet Schema A DataSet schema is an XML file that describes the structure of a DataSet. You can work with such files as raw XML, but if you have Visual Studio .NET, there’s a better way. Visual Studio .NET includes a specialized XML designer that provides a visual representation of DataSet schema files. The XML designer is also integrated with the database support in Server Explorer. You can add items to a DataSet schema file by dragging and dropping them from Server Explorer. To use the XML designer in Visual Studio .NET with a DataSet schema file, you’ll need to create a new Visual Studio .NET project to host the file. After you’ve done that, you can perform many design tasks, including the creation of new schemas and editing of existing schemas.

Creating a DataSet Schema Visual Studio .NET allows you to create a DataSet schema “from scratch” without reference to an existing DataSet or to a table stored on a database server. To do this, add a new DataSet item from the Local Project items category. The new DataSet schema file will open in a visual designer with a set of tools appropriate for creating new metadata, as shown in Figure 2.1. In the next section, you learn how to add information to the schema to help dictate the layout of the DataSet that it defines.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating . . . . .and . . Manipulating . . . . . . . DataSets . . . . .

Figure 2.1 The DataSet schema designer with an empty schema loaded.

Elements and Attributes Like other XML files, DataSet schema files are made up of XML elements. You can think of an element as a unit of information. In a DataSet, elements often map to columns in a database. To add an element to a schema, select the Element tool in the Toolbox and drag it to the schema designer. This will create an element named element1. You can rename the element by typing over the name. Drag another element and drop it on top of the first element to create a nested element. The designer assumes that the new element will be a complex element—that is, one that contains other elements. To change the new element to a simple element, select a data type from the drop-down list to the right of the element. Figure 2.2 shows a pair of elements in the designer. They’ve both been renamed from their defaults, and the inner element (CustomerID) has been defined as a string.

Figure 2.2 An element with a simple nested element.

25

26

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

As you work in the designer, you’re actually creating an XML file. At any time, you can use the XML tab at the bottom of the designer to see the raw XML. Here’s the XML that corresponds to the schema shown in Figure 2.2:











You should understand how to create schema files and be moderately familiar with their XML representation. However, there’s no need to memorize the complete XML syntax that Visual Studio .NET uses for these files.

You can also use the XML designer to add attributes to a DataSet schema. Attributes provide an alternative way to represent columns within a DataSet. To add an attribute, select the Attribute tool in the Toolbox. Drag the attribute from the Toolbox and drop it on top of an element in the schema. This will create an attribute named attribute1. You can rename the attribute by typing over the name. You’ll see that the attribute is assigned the string data type by default. Attributes cannot be used for complex data types. Given that you can represent columns by either elements or attributes within a DataSet schema file, how do you decide which representation to use? Here are some points to consider: ➤ If you need to exchange the schema file with other applications, you

must be sure that it is compatible with those applications. Microsoft Access, for example, can import a schema defined using elements but not one defined using attributes.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating . . . . .and . . Manipulating . . . . . . . DataSets . . . . . ➤ If your DataSet requires columns that are defined using a custom data

type, you must use elements for those columns. Attributes are restricted to the built-in data types defined by the World Wide Web Consortium (W3C). ➤ To represent a child table in a hierarchy, you must use an element. Visual Studio .NET always uses elements to represent database columns when you use it to create a DataSet schema.

Using Server Explorer with the XML Designer You can also create DataSet schemas quickly by using the Server Explorer, which allows you to interact directly with SQL Server and other databases. By default, the Server Explorer window in Visual Studio .NET is displayed as a small vertical tab to the left of the Toolbox. When you hover the mouse over this tab, the Server Explorer will slide out to cover the Toolbox. To work with DataSet schema files, you’ll use the Data Connection node in Server Explorer and its children. To start working with those objects, you’ll need to add a data connection to the Server Explorer tree. Here’s how to create a data connection to a SQL Server: 1. Open Server Explorer by hovering your mouse over its tab. 2. Right-click the Data Connections node and then select Add

Connection. This will open the Data Link Properties dialog box. 3. Fill in the connection information for your data source. The dialog box

will default to using the Microsoft OLE DB Provider for SQL Server, but you can change that on the Provider tab if you prefer. As an example, for a SQL Server data connection (the only kind I’ll be using in this book), you must select the server name from the drop-down list, fill in your username and password, and then select the database from the second drop-down list. You can use the Test Connection button to make sure you’ve successfully completed these steps. 4. Click OK to create the data connection. For ease in working with the

code in this chapter, you should create at least one data connection based on an instance of the SQL Server Northwind sample database.

27

28

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

If SQL Server is located on the same computer where you’re running Visual Basic .NET code, you can use the special name (local) to refer to the server in place of a machine name.

Visual Studio .NET remembers your data connections across sessions and projects. Any data connection you’ve created will appear in Server Explorer in all your projects unless you right-click the data connection and choose Delete. After you’ve created a data connection, you can use objects from that data connection in a DataSet schema design. For example, you can expand the Data Connection tree to show a server, then a database, and then the tables within the database. Drag tables from Server Explorer to the schema designer to bring them into the schema. Figure 2.3 shows the schema I’ve been working with after adding two tables from the Northwind sample database using this process. As you can see, there’s no problem in combining handbuilt tables with tables created by dragging and dropping.

Figure 2.3 A DataSet schema with three tables and a simple type.

You can also create schema elements by dragging a view, a stored procedure, a function, or a set of columns from Server Explorer to the DataSet schema designer.

Manipulating DataSet Relationships As an in-memory representation of a database, the DataSet object retains the notion of relations between tables. As you would expect, this means that a DataSet schema can also store information on keys and relationships in the DataSet it represents.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating . . . . .and . . Manipulating . . . . . . . DataSets . . . . .

Adding Keys to a DataSet Schema The DataSet schema designer allows you to create two types of keys. You can identify a field or a set of fields as the primary key for a table, or you can identify a field or a set of fields as making up a unique key. To create a key in the designer, select the Key tool in the Toolbox. Drag the key from the Toolbox and drop it on an element that represents a column. This will open the Edit Key dialog box. Select the fields you wish to use for the key and type a name for the key. To create a primary key, check the DataSet Primary Key check box. If you don’t check this check box, the result will be a unique key but not a primary key. You can create one primary key and as many unique keys as you like for each table in the DataSet schema designer. The primary key identifies the field (or combination of fields) that uniquely specifies an individual row in the table. Unique keys identify other fields or combinations of fields that cannot be repeated in different records of the same table. To delete a primary key or a unique key in the DataSet schema designer, you must first click in the row containing the key to select the row. Then you can right-click that row and select Delete Key.

One-to-Many Relationships One way to relate two tables in a DataSet schema is to identify common key columns and create a relationship between the tables using those columns. This is similar to the way relational database products handle relationships. To create a relationship in the schema designer, follow these steps: 1. Open a schema that contains the two tables you want to relate. 2. Select the Relation tool in the Toolbox. Use this tool to drag a rela-

tionship from the Toolbox and drop it on the child table. For example, to relate one customer to many orders, you would drop the relation on the Orders table. This will open the Edit Relation dialog box (see Figure 2.4). 3. Name the relationship. Select the parent table (for example,

Customers) as the parent element and then select the child table (for example, Orders) as the child element. Select the key and key fields to use. Leave all other options at their default values.

29

30

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Figure 2.4 Creating a relationship in the schema designer.

4. Click OK to create the relationship. The designer will draw a relation-

ship object and connecting lines between the two tables. You can also specify a number of optional behaviors in the Edit Relation dialog box. You can create a relationship that is only used as a constraint, and you can exercise control over the behavior of child records when a parent record is updated or deleted.

Nested Relationships Although one-to-many relationships are the only kind you’ll find in a typical relational database, the DataSet schema designer also supports nested relationships. In a nested relationship, the child table is stored as a complex data type within the parent table. To create a nested relationship, select a child table in the schema designer. Drag and drop the child table on top of its parent table. This will create a relationship between the two tables. Because there are two different ways to relate tables in a DataSet schema, you’ll have to choose between the two. Here are some points to help you decide whether to use one-to-many or nested relationships in your DataSet schemas: ➤ One-to-many relationships more directly represent the way data is

stored in a relational database. If your data is primarily stored in a database, this provides the most natural mapping.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating . . . . .and . . Manipulating . . . . . . . DataSets . . . . . ➤ Nested relationships are more natural to represent in XML. If your data

is not stored in a relational database, nested relationships provide a cleaner and more succinct XML representation of the connections between tables. ➤ If you require interoperability with other XML applications, nested rela-

tionships are more likely to be correctly interpreted.

Creating and Using Strongly Typed DataSets The best way to understand strongly typed DataSet objects is to see what you can do with one syntactically. Suppose that you have a normal DataSet, and you’ve extracted a DataTable object named dt from this DataSet. Then you can refer to a value in the DataTable with any of these syntaxes: dt.Rows(0).Item(0) dt.Rows(0)(0) dt.Rows(0).Item(“ColumnName”) dt.Rows(0)(“ColumnName”) dt.Rows(0)!ColumnName

All these syntaxes have one thing in common: They’re all late bound. That is, .NET doesn’t know until runtime that “ColumnName” is a valid column name in the DataTable. By contrast, in a strongly typed DataSet, the columns actually become properties of the row. With a strongly typed DataSet, an early-bound version of the data-retrieval code becomes available: dt.Rows(0).ColumnName

In addition to being faster than the late-bound syntax, this syntax also has the benefit that column and table names show up in the applicable IntelliSense lists.

Using the Component Designer to Create a Strongly Typed DataSet One way to create a strongly typed DataSet is to derive it directly from a table or other data-bearing object in a database. Follow these steps to use this technique:

31

32

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1. Expand the Server Explorer tree view to show a data connection to

your database. Drill into the Tables folder within this database. 2. Drag an Employees table from Server Explorer and drop it on a Visual

Basic .NET form. This will add a SqlConnection object named SqlConnection1 and a SqlDataAdapter object named SqlDataAdapter1 to the component tray of the form. 3. Select the SqlDataAdapter object. Click the Generate DataSet hyper-

link at the bottom of the Properties window. This will open the Generate DataSet dialog box. Name the new DataSet object and select the check box to add the DataSet object to the designer. Click OK. 4. You’ll see a new object, with the extension .xsd, appear in the Solution

Explorer. This is a DataSet schema file that describes the new strongly typed DataSet. Click the Show All Files button on the Solution Explorer toolbar. Expand the dsEmployees.xsd node to see the corresponding .vb file. This is a class file that can be instantiated to produce the strongly typed DataSet. In addition to the new objects in Solution Explorer, this example will also add a new component to the component tray underneath the form. This is an instance of the class defined in dsEmployees.vb.

Creating a Strongly Typed DataSet from a DataSet Schema You can also create a strongly typed DataSet from a DataSet schema file— more precisely, if you’ve created a DataSet schema in your Visual Basic .NET project. Visual Basic .NET will automatically create a strongly typed DataSet class that matches the structure defined in the schema. Because you edit the schema, Visual Basic .NET will keep the DataSet class synchronized with your edits. For example, suppose you’ve created a schema named Customers.xsd. If you click the Show All Files toolbar button, you’ll find two files as children of the Customers.xsd DataSet schema file: ➤ Customers.vb—This file is the class definition for a strongly typed

DataSet based on the DataSet schema you’ve been working with. ➤ Customers.xsx—This file contains information on the layout of objects

within the DataSet schema designer window.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating . . . . .and . . Manipulating . . . . . . . DataSets . . . . .

Using a Strongly Typed DataSet Once you’ve built a strongly typed DataSet, you can treat the tables within the DataSet as properties of the DataSet, and you can treat the columns as properties of their tables. For example, if you have built a strongly typed DataSet named dsEmployees and have instantiated an object named dsEmployees1 from this DataSet, you could iterate through all the rows in the DataSet with this code: Private Sub Form1_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim EmpRow As dsEmployees.EmployeesRow SqlDataAdapter1.Fill(DsEmployees1, “Employees”) For Each EmpRow In DsEmployees1.Employees lbEmployees.Items.Add( _ EmpRow.FirstName & “ “ & EmpRow.LastName) Next End Sub

Notice as you type this code that the IntelliSense feature fills in the names of tables and columns for you. A strongly typed DataSet class inherits from the base DataSet class, so it has all the methods and properties of the DataSet. The strong typing gives you the benefits of design-time IntelliSense and type checking. It also makes your code easier to read. Given the ease with which Visual Studio .NET can create strongly typed DataSet classes, you should plan to use them whenever possible.

Accessing and Manipulating SQL Server Data You’ll need to understand Transact-SQL (T-SQL) to pass the exam. T-SQL is Microsoft’s implementation of SQL (Structured Query Language), which is defined by a standard from the American National Standards Institute (ANSI). You can submit T-SQL to a SQL Server database for processing in two ways. First, you can write ad hoc queries, SQL statements that are executed directly. Second, you can write stored procedures, SQL statements that are stored on the server as a named object. The .NET Framework includes facilities for running both ad hoc queries and stored procedures.

33

34

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Using Ad Hoc Queries Ad hoc T-SQL queries provide an extremely flexible way to retrieve data from a SQL Server database or to make changes to that database. You should know the four basic types of T-SQL statements: ➤

SELECT

statements allow you to retrieve data stored in the database.



INSERT

statements allow you to add new data to the database.



UPDATE

statements allow you to modify data already in the database.



DELETE

statements allow you to delete data from the database. You’ll usually see SQL keywords (such as SELECT, INSERT, UPDATE, and DELETE) formatted entirely in uppercase. I follow that convention in this book, but uppercase formatting isn’t required by SQL Server. You might see these same keywords in mixed case or lowercase on an exam. As far as SQL Server is concerned, there’s no difference between SELECT, Select, and select.

Running Queries There are many ways to send queries to SQL Server, including the use of the osql and SQL Query Analyzer utilities that are shipped with SQL Server. But for simple SELECT queries, it’s just as easy to build your own application in Visual Basic .NET. Here’s how: 1. Add a new form to your Visual Basic .NET project. 2. Open Server Explorer. 3. Expand the tree under Data Connections to show a SQL Server data

connection that points to the Northwind sample database. Drag and drop the data connection onto the form to create a SqlConnection1 object on the form. This object represents a connection to SQL Server. 4. Add a TextBox control named

txtQuery, a Button control named and a DataGrid control named dgResults to the form. Set the Multiline property of the TextBox to True. Set the CaptionVisible property of the DataGrid to False. Arrange the controls as shown in Figure 2.5.

btnExecute,

5. Double-click the Button control to open the form’s module. Enter two

statements at the top of the module: Imports System.Data Imports System.Data.SqlClient

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating . . . . .and . . Manipulating . . . . . . . DataSets . . . . . 6. Enter the following code to execute the query when you click the

Button control: Private Sub btnExecute_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnExecute.Click ‘ Create a SqlCommand to represent the query Dim cmd As SqlCommand = _ SqlConnection1.CreateCommand cmd.CommandType = CommandType.Text cmd.CommandText = txtQuery.Text ‘ Create a SqlDataAdapter to talk to the database Dim da As SqlDataAdapter = New SqlDataAdapter() da.SelectCommand = cmd ‘ Create a DataSet to hold the results Dim ds As DataSet = New DataSet() ‘ Fill the DataSet da.Fill(ds, “Results”) ‘ And bind it to the DataGrid dgResults.DataSource = ds dgResults.DataMember = “Results” End Sub

7. Set the form as the startup object for the project. 8. Run the project. Enter a query in the text box, such as the following: SELECT * FROM Employees

9. Click the button to run the code, retrieving the results to the

DataGrid, as shown in Figure 2.5.

Figure 2.5 Running an ad hoc query from a custom form.

You can learn about the ADO.NET objects that this example uses in Appendix A.

The SELECT Statement The basic SQL statement is the SELECT statement.

35

36

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Just reading the descriptions here is no substitute for actually practicing with T-SQL. You’re sure to see some SQL statements on the exam.

The SELECT statement is used to create a resultset. In skeleton form, a SELECT looks like this: SELECT field_list FROM table_list WHERE where_clause GROUP BY group_by_clause HAVING having_clause ORDER BY sort_clause

Each of those lines of code is called a clause. The SELECT and FROM clauses are required, and the rest are optional. Here’s an example of a SQL statement containing only the required clauses: SELECT OrderID, CustomerID FROM Orders

The resultset for this statement contains the values of the OrderID and CustomerID fields from every record in the Orders table. The asterisk (*) character is a shortcut to refer to all columns in the source: SELECT * FROM Orders

You’re also not limited to fields from a single table. For instance, you might try retrieving information from both the Customers and Orders tables with this query: SELECT OrderID, Customers.CustomerID FROM Orders, Customers

Note that Customers.CustomerID is what’s known as a fully qualified name, meaning both the table name and the field name are specified. This is necessary because both the Customers table and the Orders table contain fields named CustomerID, and you need to tell SQL Server which one you want to display. If you try the previous query, though, you’ll get more than 75,000 records back—many more than the number of orders in the database! That’s because the query as written, although it includes all the proper tables, doesn’t tell SQL Server how to relate those tables. This sort of query is called a cross-product query. SQL Server constructs the resultset by including one row in the output for each row in each combination of input table rows. That is, there’s an output row for the first order and

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating . . . . .and . . Manipulating . . . . . . . DataSets . . . . .

the first customer, for the first order and the second customer, and so on. A more useful query, of course, matches each order with the corresponding customer. That’s the job of the INNER JOIN keyword. INNER JOIN tells SQL Server how to match two tables. Here’s how the syntax looks for a fixed version of the original query: SELECT OrderID, Customers.CustomerID FROM Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID

This rewrite tells SQL Server to look at each row in the Orders table and match it with all rows in the Customers table where the CustomerID of the order equals the CustomerID of the customer. Because CustomerIDs are unique in the Customers table, this is tantamount to including only a single row for each order in the resultset. The INNER JOIN keyword can appear more than once in a query for more than two tables to join. For example, here’s a query to show EmployeeIDs along with OrderIDs and CustomerIDs: SELECT Orders.OrderID, Customers.CustomerID, Employees.EmployeeID FROM Employees INNER JOIN (Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID) ON Employees.EmployeeID = Orders.EmployeeID

Note the use of parentheses to specify the order in which the joins should be performed. What if you only want to see some of the rows in the table? That’s where the WHERE clause comes into the picture. You can think of a WHERE clause as making a simple, yes-or-no decision for each row of data in the original table, deciding whether to include that row in the resultset. The simplest form of the WHERE clause checks for the exact contents of a field. For example, SELECT * FROM Orders WHERE ShipCountry = ‘Brazil’

looks at every row in the Orders table and determines whether the ShipCountry field contains the exact value Brazil. If so, the row is included in the results. If not, it’s discarded. However, WHERE clauses need not be exact. This is also a valid SQL statement: SELECT * FROM Orders WHERE Freight > 50

37

38

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

In this case, you’ll get all the rows in which the amount in the Freight field is greater than 50. Note, by the way, that Brazil goes in quotation marks, whereas 50 doesn’t. That’s simply a syntax matter: Text and date data need quotation marks, but numeric columns don’t. You’re free to combine multiple tests in a single WHERE clause. For example, SELECT * FROM Orders WHERE ShipCountry = ‘Brazil’ AND Freight > 50 AND OrderDate 10 GROUP BY ProductID ORDER BY Sum(Quantity) DESC

This has the same effect as the first query, except that it will just ignore any row in the Order Details table that has a quantity of 10 or under. Second, you can limit the results by filtering the totals with a HAVING clause: SELECT ProductID, Sum(Quantity) AS TotalSales FROM [Order Details] GROUP BY ProductID

41

42

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . HAVING Sum(Quantity) > 1000 ORDER BY Sum(Quantity) DESC

A HAVING clause filters the results rather than the input. That is, the last query will sum everything from the Order Details table and then show you rows in which the total is greater than 1,000. You can also combine the two types of filtering, as shown here: SELECT ProductID, Sum(Quantity) AS TotalSales FROM [Order Details] WHERE Quantity > 10 GROUP BY ProductID HAVING Sum(Quantity) > 1000 ORDER BY Sum(Quantity) DESC

This searches the source table for rows in which the quantity is greater than 10 and then only keeps those rows in which the total is more than 1,000. Note that WHERE and HAVING go in two different places in the SQL statement. The order of clauses is fixed, not optional.

The INSERT Statement The purpose of the INSERT statement is to add a row or multiple rows to a table through executing a SQL statement. In its simplest form, the insert query lists a target table and a set of values to insert. For example, this query adds a new row to the Order Details table: INSERT INTO [Order Details] VALUES (10248, 1, 12.00, 5, 0)

This simple form of the statement has two drawbacks. First, knowing which field is getting which piece of data is difficult. The values are inserted into the table fields in the order that the fields show up in Design view, but you must remember (in this example) that the quantity is the fourth field. Second, if you use this format, you must supply a value for every field. This is a problem when you want the default value for a field or when a field can’t have data inserted into it (for example, an identity field whose values are automatically generated by SQL Server). To get around these problems, a second format explicitly lists the fields for the target table: INSERT INTO [Order Details] (OrderID, ProductID, UnitPrice, Quantity, Discount) VALUES (10248, 2, 12.00, 5, 0)

Here, the first set of parentheses holds a column list, and the second set holds the values to insert. If a field has a default value, can be null, or is an identity field, you can leave it out of the field list:

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating . . . . .and . . Manipulating . . . . . . . DataSets . . . . . INSERT INTO Products (ProductName, SupplierID, CategoryID) VALUES (‘Turnips’, 25, 7)

This works even though no value is specified for most of the fields in the Products table. Also, you can rearrange the field list as long as you rearrange the value list to match: INSERT INTO Products (SupplierID, ProductName, CategoryID) VALUES (20, ‘Lettuce’, 7)

The insert query isn’t limited to inserting a single record. A second format inserts the results of a SELECT statement into the target table. For example, this query will insert a product from every supplier into the Products table: INSERT INTO Products (SupplierID, ProductName, CategoryID ) SELECT SupplierID, ‘Trout’, 8 FROM Suppliers

This works by building the results of the SELECT statement and then putting each row returned by SELECT into the target table. Of course, the columns still need to match up properly.

The UPDATE Statement As you can probably guess, the purpose of an update query is to update data. For example, you could update a field in a record in Northwind with this query: UPDATE Customers SET ContactName = ‘Maria Anderson’ WHERE CustomerID = ‘ALFKI’

In this query, the UPDATE keyword introduces an update query. The SET keyword tells SQL Server what to update. Here, it’s setting a field equal to a literal value. The WHERE clause tells SQL Server which row in the table to update. You’re not limited to updating a single record. If the WHERE clause selects multiple records, they’ll all be updated: UPDATE Customers SET Country = ‘United States’ WHERE Country = ‘USA’

You can even update every row in a table by leaving out the WHERE clause: UPDATE Products SET Discontinued = 0

43

44

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

This will update every row in the Products table, even those in which the Discontinued field already has the value False. You can also update more than one field at a time with an update query: UPDATE Customers SET ContactName = ‘Maria Anders’, City = ‘Berlin’ WHERE CustomerID = ‘ALFKI’

And you can update with the result of an expression: UPDATE Products SET UnitPrice = UnitPrice * 1.1

If only it were so simple to raise prices in real life! Finally, you can update based on joined tables: UPDATE Products SET Discontinued = 1 FROM Suppliers INNER JOIN Products ON Suppliers.SupplierID = Products.SupplierID WHERE Suppliers.Country = ‘Italy’

This has the effect of discontinuing all the products imported from Italy.

The DELETE Statement The DELETE statement removes data from a table. The rule for constructing a delete query is simple: Construct a select query to select the records you want to delete and then change the SELECT keyword to DELETE. Remove any * identifier from the SELECT clause as well. That’s it! To avoid destroying existing data, I’ll use another query to set the stage. The SELECT INTO statement is used to create a new table. For example, this statement creates a table named BadCustomers with all the data from the existing Customers table: SELECT * INTO BadCustomers FROM Customers

Here’s a select query to select a single row from the new table: SELECT * FROM BadCustomers WHERE CustomerID = ‘GODOS’

Now change the SELECT

*

clause to DELETE:

DELETE FROM BadCustomers WHERE CustomerID = ‘GODOS’

If you run this query, it will delete the specified row. There’s no need for a WHERE clause if you want to get really extreme: DELETE FROM BadCustomers

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating . . . . .and . . Manipulating . . . . . . . DataSets . . . . .

This statement deletes all the rows from the BadCustomers table.

Using Stored Procedures When you use an ad hoc query to interact with SQL Server, the SQL statements in the query are completely transient. They vanish as soon as you close whatever tool you’ve used to execute the query. By contrast, stored procedures are queries stored permanently on the SQL Server itself. Stored procedures have two main benefits. First, you can save complex SQL statements for future execution so that you don’t have to re-create them from scratch. Second, SQL Server compiles stored procedures so that they run faster than ad hoc queries. You should also know about parameters, which make stored procedures more flexible, and the @@IDENTITY variable, which can supply useful information any time you use a stored procedure to insert data into a table with an identity column.

Creating a Stored Procedure T-SQL includes the CREATE PROCEDURE keyword to create stored procedures. You can run CREATE PROCEDURE statements from any interface that allows you to enter and execute T-SQL. For example, you can execute this statement directly within Visual Studio .NET by following these steps: 1. Open a Visual Basic .NET Windows application in the Visual Studio

.NET IDE. 2. Open Server Explorer. 3. Expand the tree under Data Connections to show a SQL Server data

connection that points to the Northwind sample database and then the Stored Procedures node of the SQL Server. 4. Right-click the Stored Procedures node and select New Stored

Procedure. 5. Replace the boilerplate code in the Stored Procedure designer with

this code: CREATE PROCEDURE procFranceCustomers AS SELECT * FROM Customers WHERE Country = ‘France’

6. Click the Save button to save the stored procedure to the database. 7. Select Database, Run Stored Procedure to run the

CREATE PROCEDURE

statement. This creates the stored procedure in the database.

45

46

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8. Now you can execute the new procFranceCustomers stored procedure

from any tool that allows you to execute SQL statements. For example, Figure 2.6 shows the results of executing this stored procedure in the custom form you built earlier in the chapter.

Figure 2.6 The results of running a stored procedure are the same as the results of running the T-SQL statements contained in the stored procedure.

You can see two separate executing steps in this process. Executing the CREATE PROCEDURE statement (which is itself an ad hoc query) is necessary to create the stored procedure. After that has been done, you can execute the stored procedure itself to return results.

Running Stored Procedures from .NET Executing a stored procedure from .NET is very similar to executing an ad hoc query. The difference is that you supply the name of the stored procedure instead of the actual SQL as the CommandText property of a SqlCommand object. For example, this code will execute the stored procedure you just created: Private Sub StepByStep1_17_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ‘ Create a SqlCommand to represent ‘ the stored procedure Dim cmd As SqlCommand = _ SqlConnection1.CreateCommand cmd.CommandType = CommandType.StoredProcedure cmd.CommandText = “procFranceCustomers” ‘ Create a SqlDataAdapter to talk to the database Dim da As SqlDataAdapter = New SqlDataAdapter() da.SelectCommand = cmd ‘ Create a DataSet to hold the results Dim ds As DataSet = New DataSet() ‘ Fill the DataSet da.Fill(ds, “Customers”) End Sub

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating . . . . .and . . Manipulating . . . . . . . DataSets . . . . .

Stored procedures are not limited to containing SELECT statements. You can place any SQL statement inside of a stored procedure. For example, you might use the following SQL statement to create a stored procedure to update the Customers table: CREATE PROCEDURE procExpandCountry AS UPDATE Customers SET Country = ‘United States’ WHERE Country = ‘USA’

When your stored procedure doesn’t return a resultset, you need to use a slightly different code structure to execute it: Private Sub btnExecute_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnExecute.Click ‘ Create a SqlCommand to represent ‘ the stored procedure Dim cmd As SqlCommand = _ SqlConnection1.CreateCommand cmd.CommandType = CommandType.StoredProcedure cmd.CommandText = “procExpandCountry” ‘ Open the connection and execute ‘ the stored procedure SqlConnection1.Open() cmd.ExecuteNonQuery() ‘ Close the connection SqlConnection1.Close() MessageBox.Show(“SQL statement was executed.”) End Sub

The ExecuteNonQuery method of the SqlCommand object can be used to execute any ad hoc query or stored procedure that doesn’t return any results. When you call the methods of the SqlDataAdapter object, the .NET Framework will automatically open and close the associated SqlConnection object as necessary. For any other operation (such as using the SqlCommand.ExecuteNonQuery method), you must explicitly call the SqlConnection.Open and SqlConnection.Close methods in your code.

Using Parameters in Stored Procedures The examples you’ve seen so far don’t begin to tap the real power of stored procedures. SQL Server supports parameterized stored procedures, which allow you to pass information to the stored procedure at runtime. (You can think of these as the T-SQL analogue of Visual Basic .NET functions.) For example, this SQL statement defines a stored procedure that returns the total sales for a particular customer, with the CustomerID specified at runtime: CREATE PROC procCustomerSales @CustomerID char(5), @TotalSales money OUTPUT

47

48

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AS SELECT @TotalSales = SUM(Quantity * UnitPrice) FROM ((Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID) INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID) WHERE Customers.CustomerID = @CustomerID

In this SQL statement, both @CustomerID and @TotalSales are variables (called parameters in T-SQL). To use the stored procedure, you must supply a value for the @CustomerID parameter. The @TotalSales parameter is marked as an OUTPUT parameter; it returns a value from the stored procedure to the calling code. In the .NET Framework, the SqlCommand object has a collection of parameters to let you manage parameterized stored procedures. You can set parameter values through this collection in code: Private Sub btnGetTotalSales_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnGetTotalSales.Click ‘ Create a SqlCommand to represent ‘ the stored procedure Dim cmd As SqlCommand = _ SqlConnection1.CreateCommand cmd.CommandType = CommandType.StoredProcedure cmd.CommandText = “procCustomerSales” ‘ Add the input parameter and set its value cmd.Parameters.Add(New SqlParameter( _ “@CustomerID”, SqlDbType.Text, 5)) cmd.Parameters(“@CustomerID”).Value = _ txtCustomerID.Text ‘ Add the output parameter and set its direction cmd.Parameters.Add(New SqlParameter( _ “@TotalSales”, SqlDbType.Money)) cmd.Parameters(“@TotalSales”).Direction = _ ParameterDirection.Output ‘ Execute the stored procedure and ‘ display the formatted results SqlConnection1.Open() cmd.ExecuteNonQuery() txtTotalSales.Text = String.Format(“{0:c}”, _ cmd.Parameters(“@TotalSales”).Value) SqlConnection1.Close() End Sub

In ADO.NET, parameters are represented by SqlParameter objects. This code uses two different forms of the constructor for SqlParameters. The first takes the parameter name, the parameter data type, and the size of the parameter; the second omits the parameter size (because the money type has a fixed size). The code works by setting the Value property of the @CustomerID parameter, executing the SqlCommand object, and then retrieving the Value property of the @TotalSales parameter.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating . . . . .and . . Manipulating . . . . . . . DataSets . . . . .

The @@IDENTITY Variable A SQL Server table can have a single identity column. An identity column is a column whose value is assigned by SQL Server itself whenever you add a new row to the table. The purpose of the identity column is to guarantee that each row in the table has a unique primary key. If you’re working with a table that contains an identity column, you’ll often want to add a new row to the table and then immediately retrieve the value of the identity column for the new row. SQL Server provides a variable named @@IDENTITY for just this purpose. The @@IDENTITY variable returns the most recently assigned identity column value. For example, you might create a stored procedure to insert a new row in a table and return the value of the identity column so that your code can continue to work with the new row: CREATE PROC procInsertShipper @CompanyName nvarchar(40), @ShipperID int OUTPUT AS INSERT INTO Shippers (CompanyName) VALUES (@CompanyName) SELECT @ShipperID = @@IDENTITY

This stored procedure contains two SQL statements. The first inserts a row into the Shippers table, and the second retrieves the value of the identity column for the new row. From code, you can retrieve the return value to a variable: Private Sub btnAddShipper_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnAddShipper.Click ‘ Create a SqlCommand to represent ‘ the stored procedure Dim cmd As SqlCommand = _ SqlConnection1.CreateCommand cmd.CommandType = CommandType.StoredProcedure cmd.CommandText = “procInsertShipper” ‘ Add the input parameter and set its value cmd.Parameters.Add(New SqlParameter( _ “@CompanyName”, SqlDbType.VarChar, 40)) cmd.Parameters(“@CompanyName”).Value = _ txtCompanyName.Text ‘ Add the output parameter and set its direction cmd.Parameters.Add(New SqlParameter( _ “@ShipperID”, SqlDbType.Int)) cmd.Parameters(“@ShipperID”).Direction = _ ParameterDirection.Output ‘ Execute the stored procedure and ‘ display the result SqlConnection1.Open() cmd.ExecuteNonQuery() MessageBox.Show(cmd.Parameters( _ “@ShipperID”).Value) SqlConnection1.Close() End Sub

49

50

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Exam Prep Questions Question 1 Your SQL Server database contains a table named Products. This table has columns named ProductID, ProductName, and ProductType. ProductID is the primary key of the table. You want to see a list of each product type, together with the number of products of that type. Which SQL statement should you use? ❍ A. SELECT COUNT(ProductType), COUNT(ProductID) FROM Products GROUP BY ProductType ❍ B. SELECT ProductType, COUNT(ProductID) FROM Products GROUP BY ProductType ❍ C. SELECT COUNT(ProductType), ProductID FROM Products GROUP BY ProductID ❍ D. SELECT ProductType, ProductID, COUNT(ProductID) FROM Products

Answer B is correct. The GROUP BY clause instructs SQL Server to return one row for each product type, and the COUNT() function will count the unique values that go into that row. Answer A is incorrect because it doesn’t return the product type, only the number of product types. Answer C is incorrect because it is grouped by product ID and therefore will return one row for each product. Answer D is incorrect because it does not include a GROUP BY clause.

Question 2 You are using a SQL INSERT statement to insert new records in a table named Customers. The Customers table has the following columns: CustomerID—integer, identity, no default value, cannot be null CustomerName—varchar(50), no default value, cannot be null CompanyContact—varchar(50), no default value, can be null CompanyCountry—varchar(25), default value ‘USA’, cannot be null Which column’s value must you explicitly specify in the SQL statement? ❍ A. CustomerID ❍ B. CustomerName ❍ C. CompanyContact ❍ D. CompanyCountry

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating . . . . .and . . Manipulating . . . . . . . DataSets . . . . .

Answer B is correct. You must specify values for all non-nullable columns that do not have a default value. Answer A is incorrect because the identity property will supply a default value. Answer C is incorrect because the CompanyContact column can be null. Answer D is incorrect because the column has a default value that will be used if you do not specify a different value.

Question 3 Your application contains a DataSet schema file that represents courses and classrooms. Each course is assigned a unique course ID, and each classroom is identified by a unique room number. Each course is taught in precisely one classroom, and each classroom is used for many courses. Courses and Classrooms are two separate XML elements joined by an XML relation. Both the Courses and Classrooms elements contain RoomNumber elements. How should those elements be identified? ❍ A. RoomNumber should be marked as a primary key in the Courses element and as a unique key in the Classrooms element. ❍ B. RoomNumber should be marked as a primary key in the Classrooms element and not marked as a key in the Courses element. ❍ D. RoomNumber should be marked as a primary key in the Classrooms element and as a unique key in the Courses element. ❍ D. RoomNumber should be marked as a primary key in the Classrooms element and as a primary key in the Courses element.

Answer B is correct. Marking the RoomNumber element as a primary key in the Classrooms element ensures that no two classrooms will share the same room number. Because more than one course can use the same classroom, RoomNumber should not be marked as a key at all in the Courses element. Answers A and D are incorrect because marking RoomNumber as a primary key in the Courses element would prevent two courses from sharing the same room. Answer C is incorrect because marking RoomNumber as a unique key in the Courses element would also prevent two courses from sharing the same room.

51

52

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Question 4 You are building an XML schema file for an application that will retrieve data from a Web application that uses XML as its native format. The information you will retrieve includes a list of customers and a list of orders. Each customer has zero or more orders associated with it. You’ve already created a table to represent the customers within the schema file. How should you add the orders to this file? ❍ A. Add orders as an attribute to the Customers table. ❍ B. Add orders as a separate table. Use a nested relationship between the Orders table and the Customers table. ❍ C. Add orders as a separate table. Use a one-to-many relationship between the Orders table and the Customers table. ❍ D. Add orders as a simple type. Add a row using this simple type to the Customers table.

Answer B is correct. Because the native format of the data is XML, a nested relationship is more appropriate than a one-to-many relationship. Answer A is incorrect because an attribute can only represent one piece of information, not a complex type such as orders. Answer C is incorrect because it uses a one-to-many relationship rather than a nested relationship. Answer D is incorrect because a simple type can only represent one piece of information, not a complex type such as orders.

Question 5 You are designing an application that will work with student course registration information stored in a SQL Server database. Which of the following tasks are good candidates for implementation with a stored procedure? [Select all correct answers.] ❑ A. Retrieving a list of all students and student IDs from the database ❑ B. Developing an ad hoc report where the user can select the information to be displayed ❑ C. Inserting a new course registration into the database ❑ D. Allowing the administrator to run one-time queries against the database

Answers A and C are correct. Stored procedures are suitable for tasks that can be expressed as SQL statements that do not change or as SQL statements with parameters that can be specified at runtime. Stored procedures do not work well for ad hoc or interactive applications, where the query to be executed is not known in advance. Therefore, answers B and D are incorrect.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating . . . . .and . . Manipulating . . . . . . . DataSets . . . . .

Question 6 Your SQL Server database contains a table, Products, with the following structure: ProductID—int, identity ProductName—varchar(50) ProductPrice—money You wish to create a stored procedure that accepts as inputs the ProductName and ProductPrice, inserts a new row in the table, and returns the identity value assigned to that row in a parameter. Which SQL statement should you use? ❍ A. CREATE PROCEDURE procInsertProduct @ProductName varchar(50), @ProductPrice money, @ProductID int OUTPUT AS INSERT INTO Products (ProductName, ProductPrice) VALUES (@ProductName, @ProductPrice) SELECT @ProductID = @@IDENTITY

❍ B. CREATE PROCEDURE procInsertProduct @ProductName varchar(50), @ProductPrice money, @ProductID int AS INSERT INTO Products (ProductName, ProductPrice) VALUES (@ProductName, @ProductPrice) SELECT @ProductID = @@IDENTITY

❍ C. CREATE PROCEDURE procInsertProduct @ProductName varchar(50), @ProductPrice money, @ProductID int OUTPUT AS INSERT INTO Products (ProductID, ProductName, ProductPrice) VALUES (@ProductID, @ProductName, @ProductPrice) SELECT @ProductID = @@IDENTITY

❍ D. CREATE PROCEDURE procInsertProduct @ProductName varchar(50), @ProductPrice money, @ProductID int OUTPUT AS INSERT INTO Products (ProductName, ProductPrice) VALUES (@ProductName, @ProductPrice) SELECT @@IDENTITY

53

54

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Answer A is correct. It contains the correct parameters and only inserts values into columns that can accept values. Answer B is incorrect because the @ProductID parameter is not marked as an output parameter. Answer C is incorrect because you cannot insert values into an identity column. Answer D is incorrect because it does not assign the @@IDENTITY value to the output parameter.

Question 7 You are using a table named TempData in your SQL Server database to store intermediate results during a long calculation. At the start of the calculation, you must remove all the data from this table, without removing the table itself. Which SQL statement can you use for this purpose? ❍ A. DELETE FROM TempData WHERE * ❍ B. DELETE * FROM TempData ❍ C. DELETE FROM TempData ❍ D. DELETE TempData

Answer C is correct. To delete all rows from a SQL Server table, you must use the DELETE FROM tablename syntax. Answer B is acceptable syntax for Jet SQL, but not for SQL Server’s T-SQL dialect. Answers A and D are syntactically incorrect and will return an error.

Question 8 You have created a DataSet schema file named Orders.xsd in a Visual Basic .NET Windows application. Which of the following will Visual Studio automatically create for you? ❍ A. A stored procedure named procInsertOrders ❍ B. A SqlDataAdapter class named OrdersAdapter.vb ❍ C. A strongly typed DataSet class named Orders.vb ❍ D. A form named Orders.vb

Answer C is correct. As you work with a DataSet schema file, Visual Studio .NET automatically creates and updates a corresponding strongly typed DataSet class. Answers A, B, and D are incorrect; if you require a stored procedure, a SqlDataAdapter, or a form, you must create them by other means.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating . . . . .and . . Manipulating . . . . . . . DataSets . . . . .

Question 9 You are working with a SQL Server database that contains two tables, Customers and Orders. The Customers table contains columns named CustomerID and CustomerName. CustomerID is the primary key of the Customers table. The Orders table contains columns named OrderID, CustomerID, and OrderDate. OrderID is the primary key of the Orders table, and CustomerID is a foreign key that is related to the CustomerID column in the Customers table. You want to run a query that retrieves all OrderIDs and dates for customers whose CustomerName starts with S. Which of these SQL statements should you use? ❍ A. SELECT Orders.OrderID, Orders.OrderDate FROM Customers, Orders WHERE CustomerName LIKE ‘S%’ ❍ B. SELECT Orders.OrderID, Orders.OrderDate FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE CustomerName LIKE ‘S_’ ❍ C. SELECT * FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE CustomerName LIKE ‘S%’ ❍ D. SELECT Orders.OrderID, Orders.OrderDate FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE CustomerName LIKE ‘S%’

Answer D is correct. It specifies the proper joins and wildcards to retrieve the desired information. Answer A is incorrect because it does not specify how the Customers and Orders tables are related. Answer B is incorrect because the underscore wildcard only matches a single character. Answer C is incorrect because SELECT * cannot be used when there are two columns with the same name (in this case, CustomerID).

55

56

Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Need to Know More? Delaney, Kalen. Inside SQL Server 2000. Microsoft Press, 2000. DeLoveh, David et al. Effective Visual Studio .NET. Wrox, 2002. Gunderloy, Mike. ADO and ADO.NET Programming. Sybex, 2002. SQL Server Books Online, installed as part of SQL Server 2000. World Wide Web Consortium: http://www.w3c.org/.

3 Accessing and Manipulating XML Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Terms you’ll need to understand: ✓ DiffGram ✓ Document Object Model (DOM) ✓ Document Type Definition (DTD) ✓ Valid XML ✓ Well-formed XML ✓ XPath

Techniques you’ll need to master: ✓ Retrieving information from XML files by using the Document Object Model, XmlReader class, XmlDocument class, and XmlNode class ✓ Synchronizing DataSet data with XML via the XmlDataDocument class ✓ Executing XML queries with XPath and the XPathNavigator class ✓ Validating XML against XML Schema Design (XSD) and Document Type Definition (DTD) files ✓ Generating XML from SQL Server databases ✓ Updating SQL Server databases with DiffGrams

58

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

You can’t use the .NET Framework effectively unless you’re familiar with XML. XML is pervasive in .NET, and it’s especially important for the distributed applications covered on the 70-310 exam. The System.Xml namespace contains classes to parse, validate, and manipulate XML. You can read and write XML, use XPath to navigate through an XML document, or check to see whether a particular document is valid XML by using the objects in this namespace. In this chapter, I’ve assumed that you’re already familiar with the basics of XML, such as elements and attributes. If you need a refresher course on XML basics, refer to Appendix B, “XML Standards and Syntax.”

Accessing an XML File In this section, you’ll learn how to extract information from an XML file. I’ll start by showing you how you can use the XmlReader object to move through an XML file, extracting information as you go. Then you’ll see how other objects, including the XmlNode and XmlDocument objects, provide a more structured view of an XML file. I’ll work with a very simple XML file named Books.xml that represents three books a computer bookstore might stock. Here’s the raw XML file:

Gunderloy, Mike Exam 70-306 Training Guide Que

Wildermuth, Shawn Pragmatic ADO.NET Addison-Wesley

Burton, Kevin .NET Common Language Runtime Unleashed Sams

Understanding the DOM The Document Object Model, or DOM, is an Internet standard for representing the information contained in an HTML or XML document as a tree of nodes. Like many other Internet standards, the DOM is an official standard

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . .

of the World Wide Web Consortium, better known as the W3C. You can find it at www.w3.org/DOM. In its simplest form, the DOM defines an XML document as consisting as a tree of nodes. The root element in the XML file becomes the root node of the tree, and other elements become child nodes. The DOM provides the standard for constructing this tree, including a classification for individual nodes and rules for which nodes can have children. In the DOM, attributes are not represented as nodes within the tree. Rather, attributes are considered to be properties of their parent elements. You’ll see later in the chapter that this is reflected in the classes provided by the .NET Framework for reading XML files.

Using an XmlReader Object The XmlReader class is designed to provide forward-only, read-only access to an XML file. This class treats an XML file similar to the way a cursor treats a resultset from a database. At any given time, there is one current node within the XML file, represented by a pointer that you can move around within the file. The class implements a Read method that returns the next XML node to the calling application. The XmlReader class has many other members, as shown in Table 3.1. Table 3.1 Important Members of the XmlReader Class Member

Type

Description

Depth

Property

The depth of the current node in the XML document

EOF

Property

A Boolean property that is True when the current node pointer is at the end of the XML file

GetAttribute

Method

Gets the value of an attribute

HasAttributes

Property

True when the current node contains attributes

HasValue

Property

True when the current node is a type that has a Value property

IsEmptyElement

Property

True when the current node represents an empty XML element

IsStartElement

Method

Determines whether the current node is a start tag

Item

Property

An indexed collection of attributes for the current node (if any) (continued)

59

60

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 3.1 Important Members of the XmlReader Class (continued) Member

Type

Description

MoveToElement

Method

Moves to the element containing the current attribute

MoveToFirstAttribute

Method

Moves to the first attribute of the current element

MoveToNextAttribute

Method

Moves to the next attribute

Name

Property

The qualified name of the current node

NodeType

Property

The type of the current node

Read

Method

Reads the next node from the XML file

Skip

Method

Skips the children of the current element

Value

Property

The value of the current node

The XmlReader class is a purely abstract class. That is, this class is marked with the MustInherit modifier; you cannot create an instance of XmlReader in your own application. Generally, you’ll use the XmlTextReader class instead. The XmlTextReader class implements XmlReader for use with text streams. Here’s how you might use this class to dump the nodes of an XML file to a ListBox control: Private Sub btnReadXml_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnReadXML.Click Dim intI As Integer Dim intJ As Integer Dim strNode As String ‘ Create a new XmlTextReader on the file Dim xtr As XmlTextReader = _ New XmlTextReader(“Books.xml”) ‘ Walk through the entire XML file Do While xtr.Read If (xtr.NodeType = XmlNodeType.Element) Or _ (xtr.NodeType = XmlNodeType.Text) Then strNode = “” For intI = 1 To xtr.Depth strNode &= “ “ Next strNode = strNode & xtr.Name & “ “ strNode &= xtr.NodeType.ToString If xtr.HasValue Then strNode = strNode & “: “ & xtr.Value End If lbNodes.Items.Add(strNode) ‘ Now add the attributes, if any If xtr.HasAttributes Then While xtr.MoveToNextAttribute strNode = “” For intI = 1 To xtr.Depth strNode &= “ “ Next strNode = strNode & xtr.Name & “ “ strNode &= xtr.NodeType.ToString

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . . If xtr.HasValue Then strNode = strNode & “: “ & _ xtr.Value End If lbNodes.Items.Add(strNode) End While End If End If Loop ‘ Clean up xtr.Close() End Sub

Figure 3.1 shows the view of the sample Books.xml file produced by this code.

Figure 3.1 An XML file translated into schematic form by an XmlTextReader object. This and other examples in this chapter assume that the XML file is located in the bin folder of your Visual Basic .NET project.

The DOM includes nodes for everything in the XML file, including the XML declaration and any whitespace (such as the line feeds and carriage returns that separate lines of the files). On the other hand, the node tree doesn’t include XML attributes, though you can retrieve them from the parent elements. However, the DOM and the XmlTextReader are flexible enough that you can customize their work as you like. Note the use of the NodeType property and the MoveToNextAttribute method in this example to display just the elements, text nodes, and attributes from the file.

61

62

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Alternatively, you can retrieve attributes by using the Item property of the XmlTextReader. If the current node represents an element in the XML file, the following code will retrieve the value of the first attribute of the element: xtr.Items(0)

This code will retrieve the value of an attribute named Page: xtr.Item(“Page”)

The XMLNode Class The code you saw in the previous example deals with nodes as part of a stream of information returned by the XmlTextReader object. But the .NET Framework also includes another class, XmlNode, that can be used to represent an individual node from the DOM representation of an XML document. If you instantiate an XmlNode object to represent a particular portion of an XML document, you can alter the properties of the object and then write the changes back to the original file. The DOM provides two-way access to the underlying XML in this case. In addition to XmlNode, the System.Xml namespace also contains a set of classes that represent particular types of nodes: XmlAttribute, XmlComment, XmlElement, and so on. These classes all inherit from the XmlNode class.

The XmlNode class has a rich interface of properties and methods. You can retrieve or set information about the entity represented by an XmlNode object, or you can use its methods to navigate the DOM. Table 3.2 shows the important members of the XmlNode class. Table 3.2 Important Members of the XmlNode Class Member

Type

Description

AppendChild

Method

Adds a new child node to the end of this node’s list of children

Attributes

Property

Returns the attributes of the node as an XmlAttributeCollection

ChildNodes

Property

Returns all child nodes of this node

CloneNode

Method

Creates a duplicate of this node

FirstChild

Property

Returns the first child node of this node

HasChildNodes

Property

True if this node has any children

InnerText

Property

The value of the node and all its children (continued)

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . . Table 3.2 Important Members of the XmlNode Class (continued) Member

Type

Description

InnerXml

Property

The markup representing only the children of this node

InsertAfter

Method

Inserts a new node after this node

InsertBefore

Method

Inserts a new node before this node

LastChild

Property

Returns the last child node of this node

Name

Property

The name of the node

NextSibling

Property

Returns the next child of this node’s parent node

NodeType

Property

The type of this node

OuterXml

Property

The markup representing this node and its children

OwnerDocument

Property

The XmlDocument object that contains this node

ParentNode

Property

Returns the parent of this node

PrependChild

Method

Adds a new child node to the beginning of this node’s list of children

PreviousSibling

Property

Returns the previous child of this node’s parent node

RemoveAll

Method

Removes all children of this node

RemoveChild

Method

Removes a specified child of this node

ReplaceChild

Method

Replaces a child of this node with a new node

SelectNodes

Method

Selects a group of nodes matching an XPath expression

SelectSingleNode

Method

Selects the first node matching an XPath expression

WriteContentTo

Method

Writes all children of this node to an XmlWriter object

WriteTo

Method

Writes this node to an XmlWriter

The XmlDocument Class You can’t directly create an XmlNode object that represents an entity from a particular XML document. Instead, you can retrieve XmlNode objects from an XmlDocument object. The XmlDocument object represents an entire XML document. By combining the XmlNode and XmlDocument objects, you can navigate through the DOM representation of an XML document. For example, you can recursively dump the contents of an XML file to a ListBox control with this code: Private Sub btnReadXML_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnReadXML.Click Dim intI As Integer Dim intJ As Integer Dim strNode As String ‘ Create a new XmlTextReader on the file Dim xtr As XmlTextReader = _ New XmlTextReader(“Books.xml”)

63

64

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ‘ Load the XML file to an XmlDocument xtr.WhitespaceHandling = WhitespaceHandling.None Dim xd As XmlDocument = New XmlDocument() xd.Load(xtr) ‘ Get the document root Dim xnodRoot As XmlNode = xd.DocumentElement ‘ Walk the tree and display it Dim xnodWorking As XmlNode If xnodRoot.HasChildNodes Then xnodWorking = xnodRoot.FirstChild While Not IsNothing(xnodWorking) AddChildren(xnodWorking, 0) xnodWorking = xnodWorking.NextSibling End While End If ‘ Clean up xtr.Close() End Sub Private Sub AddChildren(ByVal xnod As XmlNode, _ ByVal Depth As Integer) ‘ Add this node to the listbox Dim strNode As String Dim intI As Integer Dim intJ As Integer Dim atts As XmlAttributeCollection ‘ Only process Text and Element nodes If (xnod.NodeType = XmlNodeType.Element) Or _ (xnod.NodeType = XmlNodeType.Text) Then strNode = “” For intI = 1 To Depth strNode &= “ “ Next strNode = strNode & xnod.Name & “ “ strNode &= xnod.NodeType.ToString strNode = strNode & “: “ & xnod.Value lbNodes.Items.Add(strNode) ‘ Now add the attributes, if any atts = xnod.Attributes If Not atts Is Nothing Then For intJ = 0 To atts.Count - 1 strNode = “” For intI = 1 To Depth + 1 strNode &= “ “ Next strNode = strNode & _ atts(intJ).Name & “ “ strNode &= atts(intJ).NodeType.ToString strNode = strNode & “: “ & _ atts(intJ).Value lbNodes.Items.Add(strNode) Next End If ‘ And recursively walk ‘ the children of this node Dim xnodworking As XmlNode If xnod.HasChildNodes Then xnodworking = xnod.FirstChild While Not IsNothing(xnodworking) AddChildren(xnodworking, Depth + 1) xnodworking = xnodworking.NextSibling

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . . End While End If End If End Sub

The XmlDocument class includes a number of other useful members. Table 3.3 lists the most important of these. Table 3.3 Important Members of the XmlDocument Class Member

Type

Description

CreateAttribute

Method

Creates an attribute node

CreateElement

Method

Creates an element node

CreateNode

Method

Creates an XmlNode object

DocumentElement

Property

Returns the root XmlNode for this document

DocumentType

Property

Returns the node containing the DTD declaration for this document, if it has one

ImportNode

Method

Imports a node from another XML document

Load

Method

Loads an XML document into the XmlDocument

LoadXml

Method

Loads the XmlDocument from a string of XML data

NodeChanged

Event

Fires after the value of a node has been changed

NodeChanging

Event

Fires when the value of a node is about to be changed

NodeInserted

Event

Fires when a new node has been inserted

NodeInserting

Event

Fires when a new node is about to be inserted

NodeRemoved

Event

Fires when a node has been removed

NodeRemoving

Event

Fires when a node is about to be removed

PreserveWhitespace Property

True if whitespace in the document should be preserved when loading or saving the XML

Save

Method

Saves the XmlDocument as a file or stream

WriteTo

Method

Saves the XmlDocument to an XmlWriter

The XmlDataDocument Class The System.Xml namespace also includes the capability to automatically synchronize a DataSet with an equivalent XML file. The XmlDocument class is useful for working with XML via the DOM, but it’s not a dataenabled class. To bring the DataSet class into the picture, you need to use an XmlDataDocument class, which inherits from the XmlDocument class. Table 3.4 shows the additional members the XmlDataDocument class adds to the XmlDocument class.

65

66

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 3.4 Additional Members of the XmlDataDocument Class Member

Type

Description

DataSet

Property

Retrieves a DataSet representing the data in the XmlDataDocument

GetElementFromRow

Method

Retrieves an XmlElement representing a specified DataRow

GetRowFromElement

Method

Retrieves a DataRow representing a specified XmlElement

Load

Method

Loads the XmlDataDocument and synchronizes it with a DataSet

The XmlDataDocument class allows you to exploit the connections between XML documents and DataSets. You can do this by synchronizing the XmlDataDocument (and hence the XML document that it represents) with a particular DataSet. You can start the synchronization process with any of the following objects: ➤ An XmlDataDocument ➤ A full DataSet ➤ A schema-only DataSet

If you have an XML file in an XmlDataDocument object, you can retrieve a DataSet object from its DataSet property. Here’s how you might load a DataSet using this technique: ‘ Create a new XmlTextReader on a file Dim xtr As XmlTextReader = _ New XmlTextReader(“Books.xml”) ‘ Create an object to synchronize Dim xdd As XmlDataDocument = New XmlDataDocument() ‘ Retrieve the associated DataSet Dim ds As DataSet = xdd.DataSet ‘ Initialize the DataSet by reading the schema ‘ from the XML document ds.ReadXmlSchema(xtr) ‘ Reset the XmlTextReader xtr.Close() xtr = New XmlTextReader(“Books.xml”) ‘ Tell it to ignore whitespace xtr.WhitespaceHandling = WhitespaceHandling.None ‘ Load the synchronized object xdd.Load(xtr)

This code performs some extra setup to make sure the DataSet can hold the data from the XmlDataDocument. Even when you’re creating the DataSet from the XmlDataDocument, you must still explicitly create the schema of the DataSet before it will contain data. That’s because in this technique, you

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . .

can also use a DataSet that represents only a portion of the XmlDataDocument. In this case, the code takes advantage of the ReadXmlSchema method of the DataSet object to automatically construct a schema that matches the XML document. Because the XmlTextReader object is designed for forward-only use, the code closes and reopens this object after reading the schema so that it can also be used to read the data. When you use the ReadXmlSchema method of the DataSet object to construct an XML schema for the DataSet, both elements and attributes within the XML document become DataColumn objects in the DataSet.

A second way to end up with a DataSet synchronized to an XmlDataDocument is to start with a DataSet. To use this technique, you simply pass the DataSet (which you have already filled with data) to the XmlDataDocument object’s constructor: ‘ Fill the DataSet SqlDataAdapter1.Fill(DsCustomers, “Customers”) ‘ Retrieve the associated document Dim xdd As XmlDataDocument = _ New XmlDataDocument(DsCustomers)

The third method to synchronize the two objects is to follow a three-step recipe: 1. Create a new DataSet with the proper schema to match an XML docu-

ment, but no data. 2. Create the XmlDataDocument from the DataSet. 3. Load the XML document into the XmlDataDocument.

One way to manage this is to use an XML schema file. An XML schema file describes the format of an XML file. For example, here’s an XML schema description of Books.xml:







67

68

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .





Given this schema file, with a name such as Books.xsd, you can construct the corresponding DataSet by calling the ReadXmlSchema method of a DataSet object and from there create the corresponding XmlDataDocument: ‘ Create a dataset with the desired schema Dim ds As DataSet = New DataSet() ds.ReadXmlSchema(“Books.xsd”) ‘ Create a matching document Dim xd As XmlDataDocument = _ New XmlDataDocument(ds) ‘ Load the XML xd.Load(“Books.xml”)

The advantage to using this technique is that you don’t have to represent the entire XML document in the DataSet schema; the schema only needs to include the XML elements you want to work with. For example, in this case the DataSet does not contain the Publisher column, even though the XmlDataDocument includes that column (as you can verify by inspecting the information in the ListBox control).

Understanding XPath To pass the exam, you should also have a basic knowledge of XPath. You can think of XPath as being a query language, conceptually similar to SQL. Just as SQL allows you to select a set of information from a table or group of tables, XPath allows you to select a set of nodes from the DOM representation of an XML document. By writing an appropriate XPath expression, you can select particular elements or attributes within an XML document.

The XPath Language XPath starts with the notion of current context. The current context defines the set of nodes that will be inspected by an XPath query. In general, there are four choices to specify the current context for an XPath query: ➤

./—Uses

the current node as the current context

➤ /—Uses the root of the XML document as the current context

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . . ➤

.//—Uses

the entire XML hierarchy starting with the current node as the current context



//—Uses

the entire XML document as the current context

To identify a set of elements using XPath, you use the path down the tree structure to those elements, separating tags by forward slashes. For example, this XPath expression selects all the Author elements in the Books.xml file: /Books/Book/Author

You can also select all the Author elements without worrying about the full path to get to them by using this expression: //Author

You can use an asterisk (*) as a wildcard at any level of the tree. So, for example, the following expression selects all the Author nodes that are grandchildren of the Books node: /Books/*/Author

XPath expressions select a set of elements, not a single element. Of course, the set might only have a single member, or no members at all. In the context of the XmlDocument object, an XPath expression can be used to select a set of XmlNode objects to operate on later. To identify a set of attributes, you trace the path down the tree to the attributes, just as you do with elements. The only difference is that attribute names must be prefixed with the @ character. For example, this XPath expression selects all the Pages attributes from Book elements in the Books.xml file: //Book/@Pages

Of course, in the Books.xml file, only Book elements have a Pages attribute. So in this particular context, the following XPath expression is equivalent to the previous one: //@Pages

You can select multiple attributes with the @* operator. To select all attributes of Book elements anywhere in the XML, use this expression: //Book/@*

XPath also offers a predicate language to allow you to specify smaller groups of nodes or even individual nodes in the XML tree. You might think of this as a filtering capability similar to a SQL WHERE clause. One thing you can do

69

70

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

is specify the exact value of the node you’d like to work with. To find all Publisher nodes with the value “Que,” you could use the following XPath expression: /Books/Book/Publisher[.=”Que”]

Here, the dot operator stands for the current node. Alternatively, you can find all books published by Que: /Books/Book[./Publisher=”Que”]

Note that there is no forward slash between an element and a filtering expression in XPath. Of course, you can filter on attributes as well as elements. You can also use operators and Boolean expressions within filtering specifications. For example, you might want to find books that have 1,000 or more pages: /Books/Book[./@Pages>=1000]

Because the current node is the default context, you can simplify this expression a little bit: /Books/Book[@Pages>=1000]

XPath also supports a selection of filtering functions. For example, to find books whose title starts with A, you could use this XPath expression: /Books/Book[starts-with(Title,”A”)]

Table 3.5 lists some additional XPath functions. Table 3.5 Selected XPath Functions Function

Description

concat

Concatenates strings

contains

Determines whether one string contains another

count

Counts the number of nodes in an expression

last

The last element in a collection

normalize-space

Removes whitespace from a string

not

Negates its argument

number

Converts its argument to a number

position

The ordinal of a node within its parent

starts-with

Determines whether one string starts with another

string-length

Returns the number of characters in a string

substring

Returns a substring from a string

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . .

Square brackets are also used to indicate indexing. Collections are indexed starting at one. To return the first Book node, you’d use this expression: /Books/Book[1]

To return the first author in the XML file (knowing that authors are children of books in this file), regardless of the book, you’d use this expression: (/Books/Book/Author)[1]

The parentheses are necessary because the square brackets have a higher operator precedence than the path operators. Without the brackets, the expression would return the first author of every book in the file. There’s also the last() function, which you can use to return the last element in a collection, without needing to know how many elements are in the collection: /Books/Book[last()]

Another useful operator is the vertical bar, which is used to form the union of two sets of nodes. This expression returns all the authors for books published by Addison-Wesley or Que: /Books/Book[./Publisher=”Addison-Wesley”]/Author| /Books/Book[./Publisher=”Que”]/Author

One way to see XPath in action is to use the SelectNodes method of the XmlDocument object. Here’s how you could load the Books.xml file and select nodes matching a particular XPath expression: ‘ Load the Books.xml file Dim xtr As XmlTextReader = _ New XmlTextReader(“Books.xml”) xtr.WhitespaceHandling = WhitespaceHandling.None Dim xd As XmlDocument = _ New XmlDocument() xd.Load(xtr) ‘ Retrieve nodes to match the expression Dim xnl As XmlNodeList = _ xd.DocumentElement.SelectNodes(“//Books/Book/Title”)

The SelectNodes method of the XmlDocument takes an XPath expression and evaluates that expression over the document. The resulting nodes are returned in an XmlNodeList object, which is just a collection of XML nodes.

Using the XPathNavigator Class You’ve seen how you can use the XmlReader class to move through an XML document. But the XmlReader allows only forward-only, read-only access to the document. The System.Xml.XPath namespace contains another set of

71

72

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

navigation classes. In particular, the XPathNavigator class provides you with read-only, random access to XML documents. You can perform two distinct tasks with an XPathNavigator object: ➤ Selecting a set of nodes with an XPath expression ➤ Navigating the DOM representation of the XML document

Selecting Nodes with XPath To use the XPathNavigator class, you should start with an XmlDocument, XmlDataDocument, or XPathDocument object. In particular, if you’re mainly interested in XPath operations, you should use the XPathDocument class. The XPathDocument class provides a representation of the structure of an XML document that is optimized for query operations. You can construct an XPathDocument object from a URI (including a local filename), a stream, or a reader containing XML. The XPathDocument object has a single method of interest, CreateNavigator (you’ll also find this method on the XmlDocument and XmlDataDocument objects). This method returns an XPathNavigator object that can perform operations with the XML document represented by the XPathDocument object. Table 3.6 lists the important members of the XPathNavigator object. Table 3.6 Important Members of the XPathNavigator Class Member

Type

Description

Clone

Method

Creates a duplicate of this object with the current state

ComparePosition

Method

Compares two XPathNavigator objects to determine whether they have the same current node

Compile

Method

Compiles an XPath expression for faster execution

Evaluate

Method

Evaluates an XPath expression

HasAttributes

Property

Indicates whether the current node has any attributes

HasChildren

Property

Indicates whether the current node has any children

IsEmptyElement

Property

Indicates whether the current node is an empty element

Matches

Method

Determines whether the current node matches an XSLT (Extensible Stylesheet Language Transform) pattern

MoveToFirst

Method

Moves to the first sibling of the current node (continued)

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . . Table 3.6 Important Members of the XPathNavigator Class (continued) Member

Type

MoveToFirstAttribute Method

Description Moves to the first attribute of the current node

MoveToFirstChild

Method

Moves to the first child of the current node

MoveToNext

Method

Moves to the next sibling of the current node

MoveToNextAttribute Method

Moves to the next attribute of the current node

MoveToParent

Moves to the parent of the current node

Method

MoveToPrevious

Method

Moves to the previous sibling of the current node

MoveToRoot

Method

Moves to the root node of the DOM

Name

Property

The qualified name of the current node

Select

Method

Selects a set of nodes using an XPath expression

Value

Property

The value of the current node

Unlike the XmlReader class, the XPathNavigator class implements methods such as MovePrevious and MoveParent that can move backward in the DOM. The XPathNavigator class provides random access to the entire XML document.

Like the XmlReader class, the XPathNavigator class maintains a pointer to a current node in the DOM at all times. But the XPathNavigator brings additional capabilities to working with the DOM. For example, you can use this class to execute an XPath query by calling its Select method: ‘ Load the Books.xml file Dim xpd As XPathDocument = _ New XPathDocument(“Books.xml”) ‘ Get the associated navigator Dim xpn As XPathNavigator = _ xpd.CreateNavigator() ‘ Retrieve nodes to match the expression Dim xpni As XPathNodeIterator = _ xpn.Select(“//Books/Book/Title”) ‘ And dump the results lbNodes.Items.Clear() While xpni.MoveNext lbNodes.Items.Add( _ xpni.Current.NodeType.ToString _ & “: “ & xpni.Current.Name & “ = “ & _ xpni.Current.Value) End While

The Select method of the XPathNavigator class returns an XPathNodeIterator object, which lets you visit each member of the selected set of nodes in turn.

73

74

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Navigating Nodes with XPath You can also use the XPathNavigator object to move around in the DOM. To see how this works, try following these steps: 1. Open a Visual Basic .NET Windows Application project and add a

new form to the project. 2. Add four Button controls (btnParent,

btnPrevious, btnNext, and btnChild) and a ListBox control named lbNodes to the form.

3. Double-click the Button control to open the form’s module. Add this

line of code at the top of the module: Imports System.Xml.XPath

4. Add code to load an XML document when you load the form: Dim xpd As XPathDocument Dim xpn As XPathNavigator Private Sub StepByStep2_9_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ‘ Load the Books.xml file xpd = New XPathDocument(“Books.xml”) ‘ Get the associated navigator xpn = xpd.CreateNavigator() xpn.MoveToRoot() ListNode() End Sub Private Sub ListNode() ‘ Dump the current node to the listbox lbNodes.Items.Add( _ xpn.NodeType.ToString _ & “: “ & xpn.Name & “ = “ & _ xpn.Value) End Sub

5. Add code to handle events from the Button controls: Private Sub btnParent_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnParent.Click ‘ Move to the parent of the current node If xpn.MoveToParent() Then ListNode() Else lbNodes.Items.Add(“No parent node”) End If End Sub Private Sub btnPrevious_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnPrevious.Click

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . . ‘ Move to the previous sibling of the current node If xpn.MoveToPrevious() Then ListNode() Else lbNodes.Items.Add(“No previous node”) End If End Sub Private Sub btnNext_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnNext.Click ‘ Move to the next sibling of the current node If xpn.MoveToNext() Then ListNode() Else lbNodes.Items.Add(“No next node”) End If End Sub Private Sub btnChild_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnChild.Click ‘ Move to the first child of the current node If xpn.MoveToFirstChild() Then ListNode() Else lbNodes.Items.Add(“No child node”) End If End Sub

6. Set the form as the startup form for the project. 7. Run the project and then experiment with the buttons. You’ll find that

you can move around in the DOM, as shown in Figure 3.2.

Figure 3.2 Exploring an XML document with the XPathNavigator.

The XPathNavigator class does not throw an error if you try to move to a nonexistent node. Instead, it returns False from the method call, and the current node remains unchanged.

75

76

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Generating and Using XSD Schemas In Chapter 2, “Creating and Manipulating DataSets,” you learned how to create an XSD schema in the Visual Studio .NET user interface by dragging and dropping XML elements from the Toolbox. This method is useful when you need to create a schema from scratch. But there will be times when you want to create a schema to match an existing object. In this section, you’ll learn about the methods that are available to programmatically generate XSD schemas.

Generating an XSD Schema One obvious source for an XML schema is an XML file. An XML file can contain explicit schema information (in the form of an embedded schema), or it can contain implicit schema information in its structure. Here’s a sample file, Products.xml, that contains embedded schema information:





















. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . .



1 Chai



If the file contains explicit schema information, you can use the DataSet object to read that information and create the corresponding schema as a separate file, as shown here: ‘ Load the XML file with inline schema info Dim xtr As XmlTextReader = _ New XmlTextReader(“Products.xml”) ‘ Read the schema (only) into a DataSet Dim ds As DataSet = New DataSet() ds.ReadXmlSchema(xtr) ‘ Write the schema out as a separate stream Dim sw As StringWriter = New StringWriter() ds.WriteXmlSchema(sw) txtSchema.Text = sw.ToString()

The DataSet object must have the capability to read an XML schema so that it can construct a matching data structure in memory. The .NET Framework designers thoughtfully exposed this capability to you through the ReadXmlSchema and WriteXmlSchema methods of the DataSet object. But what if the file does not contain explicit schema information? It turns out that you can still use the DataSet object because this object also has the capability to infer an XML schema based on the data in an XML file. For example, here’s how to use the DataSet object to infer a schema for the Books.xml file: ‘ Load an XML file with no schema information Dim xtr As XmlTextReader = _ New XmlTextReader(“Books.xml”) ‘ Read the schema (only) into a DataSet Dim ds As DataSet = New DataSet() Dim ns As String() ds.InferXmlSchema(xtr, ns) ‘ Write the schema out as a separate stream Dim sw As StringWriter = New StringWriter() ds.WriteXmlSchema(sw) txtSchema.Text = sw.ToString()

You have at least four ways to obtain XSD files for your applications: ➤ You can use a file generated by an external application such as Microsoft

SQL Server or Microsoft Access.

77

78

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ You can create your own schema files from scratch using the techniques

you learned in Chapter 2. ➤ You can extract inline schema information from an XML file using the

DataSet.ReadXmlSchema method. ➤ You can infer schema information from an XML file using the

DataSet.InferXmlSchema method.

Using an XSD Schema The prime use of a schema file is to validate the corresponding XML file. Although any XML file that conforms to the syntactical rules for XML is well-formed, this does not automatically make the file valid. A valid XML file is one whose structure conforms to a specification. This specification can be in the form of an XML schema or a Document Type Definition (DTD), for example. Any valid XML file is well-formed, but not every well-formed XML file is valid. The .NET Framework provides good support for validating XML files. To validate an XML document, you can use the XmlValidatingReader class. This class provides an additional layer between the XmlReader and the XmlDocument. The extra layer validates the document as it is read in to the XmlDocument object. To use the XmlValidatingReader object to validate an XML document with an inline schema, you should supply a handler for any validation errors, as in this code sample: Private Sub ValidateIt() ‘ Load a document with an inline schema Dim xtr As XmlTextReader = _ New XmlTextReader(“Products.xml”) ‘ Prepare to validate it Dim xvr As XmlValidatingReader = _ New XmlValidatingReader(xtr) xvr.ValidationType = ValidationType.Schema ‘ Tell the validator what to do with errors AddHandler xvr.ValidationEventHandler, _ AddressOf ValidationHandler ‘ Load the document, thus validating Dim xd As XmlDocument = _ New XmlDocument() xd.Load(xvr) End Sub Private Sub ValidationHandler( _ ByVal sender As Object, _ ByVal e As ValidationEventArgs) ‘ Dump any validation errors to the UI MessageBox.Show(e.Message) End Sub

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . .

An inline schema cannot contain an entry for the root element of the document, so even when the document is otherwise valid, you’ll get an error from that node. The XmlValidatingReader class is constructed so that it does not stop on validation errors. Rather, it continues processing the file but raises an event for each error. This enables your code to decide how to handle errors while still filling the XmlDocument object. You can also validate an XML file against an external schema. To do this, you can load the schema and the XML file separately and tell the XmlValidatingReader class to compare one to the other: Private Sub ValidateIt() ‘ Load a document with an external schema Dim xtr As XmlTextReader = _ New XmlTextReader(“Books.xml”) ‘ Prepare to validate it Dim xvr As XmlValidatingReader = _ New XmlValidatingReader(xtr) xvr.ValidationType = ValidationType.Schema ‘ Tell the validator what to do with errors AddHandler xvr.ValidationEventHandler, _ AddressOf ValidationHandler ‘ Load the schema Dim xsc As XmlSchemaCollection = _ New XmlSchemaCollection() xsc.Add(“xsdBooks”, “Books.xsd”) ‘ Tell the validator which schema to use xvr.Schemas.Add(xsc) ‘ Load the document, thus validating Dim xd As XmlDocument = _ New XmlDocument() xd.Load(xvr) End Sub Private Sub ValidationHandler( _ ByVal sender As Object, _ ByVal e As ValidationEventArgs) ‘ Dump any validation errors to the UI MessageBox.Show(e.Message) End Sub

Schema files are not the only way to describe the structure of an XML file. An older standard for specifying structure is the Document Type Definition, or DTD. DTDs are part of the Standard Generalized Markup Language (SGML) standard, from which both HTML and XML derive. A DTD file lists the elements that may appear in an XML file, as in this example (Books.dtd):

Book (Author, Title, Publisher) > Book Pages CDATA #REQUIRED> Author (#PCDATA)> Title (#PCDATA)> Publisher (#PCDATA)>

79

80

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

To use a DTD file as the schema for an XML file, you include a DOCTYPE node in the XML file:



Delaney, Kalen Inside Microsoft SQL Server 2000 Microsoft Press

Gunderloy. Michael ADO and ADO.NET Programming Sybex

Cooper, James W. Visual Basic Design Patterns Addison Wesley

The XmlValidatingReader class can validate an XML document for conformance with a DTD, as in the following sample code: Private Sub ValidateIt() ‘ Load a document with an external schema Dim xtr As XmlTextReader = _ New XmlTextReader(“Books.xml”) ‘ Prepare to validate it Dim xvr As XmlValidatingReader = _ New XmlValidatingReader(xtr) xvr.ValidationType = ValidationType.DTD ‘ Tell the validator what to do with errors AddHandler xvr.ValidationEventHandler, _ AddressOf ValidationHandler ‘ Load the document, thus validating Dim xd As XmlDocument = _ New XmlDocument() xd.Load(xvr) End Sub Private Sub ValidationHandler( _ ByVal sender As Object, _ ByVal e As ValidationEventArgs) ‘ Dump any validation errors to the UI MessageBox.Show(e.Message) End Sub

The only difference between validating against a schema file and validating against a DTD is in the constant chosen for the ValidationType property of the XmlValidatingReader.

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . .

Using XML with SQL Server Over the past several releases, Microsoft SQL Server has become increasingly integrated with XML. In the current release, you can generate XML with SQL statements, using Microsoft T-SQL extensions to the SQL standard query language. You can also update SQL Server tables by sending properly formed XML messages, called DiffGrams, to a SQL Server database. In this section, you learn the basics of interacting with SQL Server via XML.

Generating XML with SQL Statements SQL Server allows you to retrieve the results of any query as XML rather than as a SQL resultset. To do this, you use the Microsoft-specific FOR XML clause. You can use a variety of options in the FOR XML clause to customize the XML that SQL Server generates. The first option is FOR XML RAW. When you use raw mode with FOR XML, SQL Server returns one element (always named row) for each row of the resultset, with the individual columns represented as attributes. For example, consider this query: SELECT Customers.CustomerID, Customers.CompanyName, Orders.OrderID, Orders.OrderDate FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Country = ‘Brazil’ AND OrderDate BETWEEN ‘1997-03-15’ AND ‘1997-04-15’ FOR XML RAW

If you execute this query (for example, using SQL Query Analyzer) in the Northwind sample database, you’ll get back these results:



SQL Query Analyzer returns XML results as one long string. I’ve reformatted these results for easier display on the printed page. If you have trouble seeing all the results in SQL Query Analyzer, select Tools, Options, Results and increase the Maximum Characters Per Column setting.

81

82

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

The second variant of the FOR XML clause is FOR XML AUTO. When you use auto mode with FOR XML, nested tables in the returned data are represented as nested elements in the XML. Columns are still represented as attributes. For example, here’s a query that uses FOR XML AUTO: SELECT Customers.CustomerID, Customers.CompanyName, Orders.OrderID, Orders.OrderDate FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Country = ‘Brazil’ AND OrderDate BETWEEN ‘1997-03-15’ AND ‘1997-04-15’ FOR XML AUTO

Here’s the corresponding returned data:









Note that in this output, the Orders element is nested within the Customers element for each order. If there were multiple orders for a single customer, the Orders element would repeat as many times as necessary. There’s a second variant of FOR XML AUTO. You can include the ELEMENTS option to represent columns as elements rather than as attributes. Here’s a query that uses this option: SELECT Customers.CustomerID, Customers.CompanyName, Orders.OrderID, Orders.OrderDate FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Country = ‘Brazil’ AND OrderDate BETWEEN ‘1997-03-15’ AND ‘1997-04-15’ FOR XML AUTO, ELEMENTS

Here’s the corresponding output:

RICAR Ricardo Adocicados

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . .

10481 1997-03-20T00:00:00

QUEEN Queen Cozinha

10487 1997-03-26T00:00:00

COMMI Comércio Mineiro

10494 1997-04-02T00:00:00

TRADH Tradiçaõ Hipermercados

10496 1997-04-04T00:00:00

The final variant of FOR XML is FOR XML EXPLICIT. In explicit mode, you must construct your query so as to create a resultset with the first column named Tag and the second column named Parent. These columns create a self-join in the results that is used to determine the hierarchy of the created XML file. Here’s a relatively simple query in explicit mode: SELECT 1 AS Tag, NULL AS Parent, Customers.CustomerID AS [Customer!1!CustomerID], Customers.CompanyName AS [Customer!1!CompanyName], NULL AS [Order!2!OrderID], NULL AS [Order!2!OrderDate] FROM Customers WHERE COUNTRY = ‘Brazil’ UNION ALL SELECT 2, 1, Customers.CustomerID, Customers.CompanyName, Orders.OrderID, Orders.OrderDate FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Country = ‘Brazil’ AND OrderDate BETWEEN ‘1997-03-15’ AND ‘1997-04-15’ ORDER BY [Customer!1!CustomerID], [Order!2!OrderID] FOR XML EXPLICIT

The resulting XML from this query is as follows:











Note that in this case, even customers without orders in the specified time period are included because the first half of the query retrieves all customers from Brazil. Explicit mode allows you the finest control over the generated XML, but it’s also the most complex mode to use in practice. You should stick to raw or auto mode whenever possible. Finally, you can generate schema information as part of a SQL Server query by including the XMLDATA option in the query. You can do this in any of the FOR XML modes. For example, here’s a query you saw earlier in this section with the XMLDATA option added: SELECT Customers.CustomerID, Customers.CompanyName, Orders.OrderID, Orders.OrderDate FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Country = ‘Brazil’ AND OrderDate BETWEEN ‘1997-03-15’ AND ‘1997-04-15’ FOR XML AUTO, ELEMENTS, XMLDATA

The resulting XML is as follows:





. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . .





\

RICAR Ricardo Adocicados

10481 1997-03-20T00:00:00

QUEEN Queen Cozinha

10487 1997-03-26T00:00:00

COMMI Comércio Mineiro

10494 1997-04-02T00:00:00

TRADH Tradiçaõ Hipermercados

10496 1997-04-04T00:00:00

Using ExecuteXmlReader ADO.NET provides a means to integrate SQL Server’s XML capabilities with the .NET Framework classes. The ExecuteXmlReader method of the SqlCommand object allows you to retrieve an XmlReader directly from a SQL statement, provided that the SQL statement uses the FOR XML clause. Here’s an example: Dim cmd As SqlCommand = _ SqlConnection1.CreateCommand

85

86

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ‘ Create a command to retrieve XML cmd.CommandType = CommandType.Text cmd.CommandText = _ “SELECT Customers.CustomerID, “ & “Customers.CompanyName,” & _ “Orders.OrderID, Orders.OrderDate “FROM Customers INNER JOIN Orders “ON Customers.CustomerID = “ & _ “Orders.CustomerID “ & _ “WHERE Country = ‘Brazil’ AND “ & “OrderDate BETWEEN ‘1997-03-15’ “ “AND ‘1997-04-15’ “ & _ “FOR XML AUTO, ELEMENTS” SqlConnection1.Open() ‘ Read the XML into an XmlReader Dim xr As XmlReader = _ cmd.ExecuteXmlReader() ‘ Dump the contents of the reader Dim strNode As String Dim intI As Integer Do While xr.Read

_ “ & _ “ & _

_ & _

‘ Do something with the nodes here Loop xr.Close() SqlConnection1.Close()

Updating SQL Server Data by Using XML You can also update SQL Server data by using special XML messages called DiffGrams. You can think of a DiffGram as a before-and-after snapshot of a part of a SQL Server table. The .NET Framework uses DiffGrams internally as a means of serializing changes in a DataSet. For example, if you pass the changes in a DataSet from one tier to another, the .NET Framework will use a DiffGram to send the changes. You can also use DiffGrams yourself to update data in a SQL Server. However, before you can do so, you’ll need to install the SQLXML managed classes, an interface between SQL Server and .NET.

Installing SQLXML Although SQL Server 2000 includes some XML support (for example, the FOR XML syntax is built in to the product), there have been many advances in XML since that version of SQL Server was released. Microsoft has kept SQL Server in tune with these advances by issuing a series of free upgrade packages with the general name of SQLXML. As of this writing, the current release of SQLXML is SQLXML 3.0 SP1. To install SQLXML, you need to download the current release directly from Microsoft’s Web site. You can always find the current release by starting at the SQLXML home page, http://msdn.microsoft.com/sqlxml.

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . .

Using DiffGrams After you’ve installed SQLXML, you can use the SqlXmlCommand object to execute a DiffGram. A DiffGram is an XML file that includes changes to a DataSet. Here’s a small example:



ALFKI Maria Anderson



ALFKI Maria Anders



In this case, the first part of the XML file lists a row in the Customers table and indicates that it has been modified. The second part of the DiffGram contains the original data from the SQL Server table. SQL Server can use this data to find the row to be modified. In addition to the DiffGram, you’ll also need a schema file that maps the element names in the DiffGram back to tables and columns in the SQL Server database. The sql:relation attribute in the schema file indicates the table mapping, whereas the sql:field attributes indicate the field mappings.







87

88

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Given these two pieces, you can use SQLXML to apply the DiffGram to a database with code such as this: Private Sub ApplyDiffGram() ‘ Connect to the SQL Server database Dim sxc As SqlXmlCommand = _ New SqlXmlCommand(“Provider=SQLOLEDB;” & _ “Server=(local);database=Northwind;” & _ “Integrated Security=SSPI”) ‘ Set up the DiffGram sxc.CommandType = SqlXmlCommandType.DiffGram sxc.SchemaPath = “diffgram.xsd” sxc.CommandStream = _ New FileStream(“diffgram.xml”, FileMode.Open) ‘ And execute it sxc.ExecuteNonQuery() MessageBox.Show(“Database was updated!”) End Sub

DiffGrams can insert or delete data as well as modify data. For an insertion, the DiffGram will contain the data for the new row and no old data. For a deletion, the DiffGram will contain the row to be deleted but no new row.

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . .

Exam Prep Questions Question 1 Your SQL Server database contains employee timesheet information. You want to retrieve some of this information into an XML document. You decide to use the FOR XML T-SQL statement to retrieve the information. Your application requires the EmployeeName and EmployeeNumber database columns to be presented as XML elements. Which clause can you use in your SQL statement? ❍ A. FOR XML AUTO ❍ B. FOR XML RAW ❍ C. FOR XML EXPLICIT ❍ D. FOR XML AUTO, XMLDATA

Answer C is correct. FOR XML EXPLICIT maps columns to elements. Answers A and D are incorrect because the AUTO mode of the FOR XML clause maps columns to attributes rather than elements, unless you include the ELEMENTS modifier. Answer B is incorrect because the RAW mode of the FOR XML clause also maps columns to attributes. The EXPLICIT mode can map columns to elements.

Question 2 You have loaded an XML file that represents orders from a trading partner and are using an XPathNavigator class to navigate through the file. The current node of the XPathNavigator is an node that is empty—that is, this node does not contain any child nodes. Your code calls the MoveFirstChild method of the XPathNavigator object. What is the result? ❍ A. No error occurs. The node remains the current node. ❍ B. No error occurs. The root node of the document becomes the current node. ❍ C. A runtime error is thrown. The root node of the document becomes the current node. ❍ D. A runtime error is thrown. The node remains the current node.

Answer A is correct. The XPathNavigator ignores attempts to move to a nonexistent node. Answers B and C are incorrect because the current node remains unchanged when you try to move to a nonexistent node. Answers C and D are incorrect because no error is thrown when you try to move to a nonexistent node.

89

90

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Question 3 Which of the following operations requires you to have an XML schema file? ❍ A. Updating a SQL Server database by sending a DiffGram through the SQLXML managed classes ❍ B. Writing an XML file to disk with the XmlTextWriter class ❍ C. Validating an XML file with the XmlValidatingReader class ❍ D. Performing an XPath query with the XPathNavigator class

Answer A is correct. The SQLXML managed classes require a schema file to match the DiffGram information to columns in the database. Answer B is incorrect because writing an XML file does not require a schema. Answer C is incorrect because you can validate an XML file against non-schema information such as a DTD. Answer D is incorrect because the XPathNavigator class does not use schema information to perform queries.

Question 4 You have an XML file with the following structure:

... ... ...

... ... ... ...

You want to retrieve all the nodes from this file with the best performance. How should you proceed? ❍ A. Read the XML file into an XmlDataDocument object. Retrieve a DataSet object from the DataSet property of the XmlDataDocument object. Create a DataView object within the DataSet object to return the required nodes. ❍ B. Read the XML file into an XPathDocument object. Use the CreateNavigator method of the XPathDocument object to return an XPathNavigator object. Use an XPath expression with the Select method of the XPathNavigator object to return the required nodes.

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . .

❍ C. Read the XML file into an XmlDocument object. Use the CreateNavigator method of the XmlDocument object to return an XPathNavigator object. Use an XPath expression with the Select method of the XPathNavigator object to return the required nodes. ❍ D. Read the XML file into an XPathDocument object. Use the CreateNavigator method of the XPathDocument object to return an XPathNavigator object. Use the Move methods of the XPathNavigator object to move through the document, accumulating the required nodes as you go.

Answer B is correct. The XPathDocument class is optimized to perform XPath operations quickly. Answer A is incorrect because the DataSet object adds unnecessary overhead in this scenario. Answer C is incorrect because the XmlDocument object is not designed to support fast XPath queries. Answer D is incorrect because querying for the required nodes is faster than visiting all the nodes.

Question 5 Your application contains an XML file, Employees.xml, with the following content:

John Farrel

Melanie Runnion

Your application also contains a form with a Button control named btnProcess and a ListBox control named lbNodes. The event handler for the Button control has this code: Private Sub btnProcess_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnProcess.Click Dim xtr As XmlTextReader = _ New XmlTextReader(“Employees.xml”) Do While xtr.Read If (xtr.NodeType = _

91

92

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

XmlNodeType.Attribute) _ Or (xtr.NodeType = _ XmlNodeType.Element) _ Or (xtr.NodeType = _ XmlNodeType.Text) Then If xtr.HasValue Then lbnodes.Items.Add( _ xtr.Value) End If End If Loop xtr.Close() End Sub

What will be the contents of the ListBox control after you click the Button control? ❍ A. 4 7

❍ B. 4 John Farrel 7 Melanie Runnion

❍ C. John Farrel Melanie Runnion

❍ D. Employees Employee 4 EmployeeName John Farrel Employee 7 EmployeeName Melanie Runnion

Answer C is correct. The Value property refers only to the actual data within XML elements. Answers A and B are incorrect because XML attributes are not treated as nodes within the DOM. Answer D is incorrect because it includes element names, which are not treated as values.

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . .

Question 6 Your application loads an XML file selected by the user and then allows him to move through the XML file. You need to allow the user to move up to the parent node, over to the next node, or down to the first child node, by selecting choices on the user interface. Which object can you use to implement this requirement? ❍ A. XPathNavigator ❍ B. XmlReader ❍ C. XPathExpression ❍ D. XmlDataDocument

Answer A is correct. The XPathNavigator class provides random navigation through an XML document. Answer B is incorrect because the XmlReader class provides forward-only access to the XML document. Answer C is incorrect because the XPathExpression class represents a single XPath expression, not an XML document. Answer D is incorrect because the XmlDataDocument class is used to synchronize an XML document and a DataSet but does not provide random access to the XML document.

Question 7 You load an XML file of employee information into an XmlDataDocument object and then retrieve the DataSet from that object. The name of the first employee as stored in the XML file is “James Doe.” In the DataSet, you change the value of the EmployeeName column of the first employee to “John Doe.” After that, in the XmlDataDocument object, you change the value of the corresponding Node to “James Doe Jr.” Finally, you call the AcceptChanges method of the DataSet object. What is the value of the first EmployeeName in the XmlDataDocument after taking these actions? ❍ A. James Doe. ❍ B. John Doe. ❍ C. James Doe Jr. ❍ D. The value is undefined because an error occurs.

Answer C is correct. The XmlDataDocument object and its corresponding DataSet object present two views of the exact same data, so changes to either one affect the other. Answer A is incorrect because the original value has been changed twice. Answer B is incorrect because the DataSet change gets overwritten by the XmlDataDocument change. Answer D is incorrect because you can make as many changes as you like without throwing an error.

93

94

Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Question 8 One of your company’s suppliers has delivered a new parts list to you in the form of an XML file without an inline schema. You’d like to create an XML schema file that corresponds to this XML file. How can you do this with the least effort? ❍ A. Import the XML file to a SQL Server database and then use drag and drop from the Server Explorer to the schema designer within Visual Studio .NET. ❍ B. Use the schema designer within Visual Studio .NET to create the schema file by dragging and dropping elements, attributes, keys, and relations. ❍ C. Use the DataSet.ReadXmlSchema method to create the schema information from the XML file. ❍ D. Use the DataSet.InferXmlSchema method to create the schema information from the XML file.

Answer D is correct. The InferXmlSchema method can create a schema file based on the elements and attributes within an XML file. Answers A and B are incorrect because building a schema for an existing file within Visual Studio .NET is more work than letting the DataSet class do it for you. Answer C is incorrect because the ReadXmlSchema method requires embedded schema information.

Question 9 Which of these operations can you perform by sending a DiffGram to SQL Server? [Select all correct answers.] ❑ A. Add new data to a table ❑ B. Delete existing data from a table ❑ C. Execute a stored procedure ❑ D. Update the index on a table

Answers A and B are correct. The DiffGram format is designed to carry information on data changes. You can add new data, delete existing data, or modify existing data with a DiffGram. Answers C and D are incorrect because the DiffGram format doesn’t carry any information on stored procedures or indexes.

. . . . . . . . . . . . . . . . . . . . . . . . . . . .Accessing . . . . . and . . .Manipulating . . . . . . .XML . . .Data . .

Need to Know More? Griffin, John. XML and SQL Server. New Riders, 2002. Gunderloy, Mike. ADO and ADO.NET Programming. Sybex, 2002. Simpson, John E. XPath and XPointer. O’Reilly, 2002. SQL Server Books Online, installed as part of SQL Server 2000. XML.com: http://www.xml.com/. XMLFiles.com DTD Tutorial: http://www.xmlfiles.com/dtd/.

95

4 .NET Remoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Terms you’ll need to understand: ✓ Application domain ✓ Asynchronous call ✓ Channel ✓ Marshalling ✓ Proxy ✓ Synchronous call ✓ Remoting ✓ Runtime host

Techniques you’ll need to master: ✓ Creating a .NET Remoting object ✓ Consuming a .NET Remoting object ✓ Choosing between client-activated and server-activated components ✓ Selecting appropriate channel protocols and formatters ✓ Configuring IIS as an activation agent ✓ Configuring remoting on the client and the server

98

Chapter . . . . .4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

The .NET Framework allows you to create distributed applications in various ways. Two approaches for distributed applications are .NET Remoting and ASP.NET Web services. I’ll discuss .NET Remoting in this chapter and cover ASP.NET Web services in the next two chapters. Remoting gives you a way to invoke an object on another computer via a local proxy object, and it’s well supported in .NET.

Developing Distributed Applications Using the .NET Framework The .NET Framework supplies three namespaces for distributed applications: ➤ The System.Net Namespace—Provides low-level classes that you can use to

“roll your own” distributed protocols ➤ The System.Runtime.Remoting Namespace—Enables communication

between objects in different application domains, whether they are on the same computer or not ➤ The System.Web.Services Namespace—Enables objects in different applica-

tion domains to exchange messages using standard protocols such as HTTP (Hypertext Transfer Protocol) and SOAP (Simple Object Access Protocol) The functionalities offered by .NET Remoting and ASP.NET Web services appear very similar to each other. In fact, ASP.NET Web services are actually built on the .NET Remoting infrastructure. Keep the following in mind when choosing between the two: ➤ You should choose .NET Remoting when both the endpoints (client and

server) of a distributed application are under your control. ➤ You should choose ASP.NET Web services when one of the endpoints

of a distributed application is not under your control.

.NET Remoting Architecture Remoting takes an indirect approach to application domain communication by creating proxy objects, as shown in Figure 4.1. The client and server communicate using the following steps:

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NET . . .Remoting . . . . .

Client Object

Server Object

Proxy

Remoting System

Client Application Domain

Channel

Remoting System

Server Application Domain

Figure 4.1 In this simplified view of .NET Remoting, note that the client and server communicate indirectly through a proxy object.

1. When a client object wants to create an instance of the server object,

the remoting system at the client side instead creates a proxy of the server object. The proxy object lives at the client but behaves just like the remote object; this leaves the client with the impression that the server object is in the client’s process. 2. When the client object calls a method on the server object, the proxy

passes the call information to the remoting system on the client. This remoting system in turn sends the call over the channel to the remoting system on the server. 3. The remoting system on the server receives the call information and,

on the basis of it, invokes the method on the actual object on the server (creating the object if necessary). 4. The remoting system on the server collects all the results of the

method invocation and passes them through the channel to the remoting system on the client. 5. The remoting system at the client receives the response of the server

and returns the results to the client object through the proxy.

99

100 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Object Marshalling There are two types of remotable objects: ➤ Marshal-by-value (MBV) objects—These objects are copied and passed out

of the server application domain to the client application domain. ➤ Marshal-by-reference (MBR) objects—These objects are accessed on the

client side using a proxy. The client just holds a reference to these objects.

Marshal-by-Value Objects MBV objects reside on the server. However, when the client invokes a method on the MBV object, the MBV object is serialized, transferred over the network, and restored on the client as an exact copy of the server-side object. The method is then invoked directly on the client. When this happens, the MBV object is no longer a remote object. Any method calls to the object do not require any proxy object or marshalling because the object is locally available. An MBV object can be created by declaring a class with the Serializable attribute. Here’s an example: ‘ Define an MBV remoting object _ Public Class MyMBVObject ‘ Implementation details End Class

Marshal-by-Reference Objects MBR objects are remote objects. They always reside on the server, and all methods invoked on these objects are executed at the server side. The client communicates with the MBR object on the server using a local proxy object that holds the reference to the MBR object. An MBR object can be created by deriving System.MarshalByRefObject class. Here’s an example: ‘ Define an MBR remoting object Public Class MyMBRObject Inherits MarshalByRefObject ‘ Implementation details End Class

from

the

101 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NET . . .Remoting . . . . .

Channels When a client calls a method on a remote object, the details of the method call are transported to the remote object through a channel. The channel object at the receiving end of a channel (the server) listens to a particular protocol using the specified port number, whereas the channel object at the sending end of the channel (the client) sends information to the receiving end using the protocol and port number specified by the channel object on the receiving end. The .NET Framework provides implementations for HTTP and TCP (Transmission Control Protocol) channels. If you want to use a different protocol, you can define your own channel by implementing the IChannelReceiver and IChannelSender interfaces.

Formatters Formatters are the objects used to encode and serialize data into messages before they are transmitted over a channel. The .NET Framework packages two formatter classes for common scenarios—the BinaryFormatter class and the SoapFormatter class. If you want to use a different formatter, you can define your own formatter class by implementing the IFormatter interface. SOAP (Simple Object Access Protocol) is a relatively straightforward, XMLbased protocol for exchanging types and messages between applications. SOAP formatting is an ideal way of communicating between applications that use incompatible architectures. However, SOAP is very verbose. SOAP messages require more bytes to represent data than the equivalent binary messages. Unlike SOAP, the binary format used by the .NET Framework is proprietary and can be understood only within .NET applications. However, as compared to SOAP, the binary format of representing messages is very compact and efficient.

The Relationship Between Channels and Formatters The HTTP channel uses the SOAP formatter as its default formatter. The TCP channel uses the binary formatter as its default formatter.

102 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

However, channels are configurable. You can configure the HTTP channel to use the binary formatter or a custom formatter instead of the SOAP formatter. Similarly, the TCP channel can be configured to use the SOAP formatter or a custom formatter instead of the binary formatter. Figure 4.2 compares the various combinations of channels and formatters on a scale of efficiency and compatibility. Channel

Formatter

TCP

Binary

TCP

SOAP

HTTP

Binary

HTTP

SOAP

Efficiency

Interoperability

Figure 4.2 A TCP channel with a binary formatter provides maximum efficiency, whereas an HTTP channel with a SOAP formatter provides maximum interoperability.

Remote Object Activation Only MBR objects can be activated remotely. No remote activation is needed in the case of MBV objects because the MBV object itself is transferred to the client side. There are two types of MBR objects: server-activated objects (SAOs) and client-activated objects (CAOs). Server-activated objects are those remote objects whose lifetime is directly controlled by the server. The remote object is only instantiated (or activated) on the server when the client calls a method on the proxy object. SAOs can be used in SingleCall activation mode or Singleton activation mode. In the SingleCall activation mode, an object is instantiated for the sole purpose of responding to just one client request. After the request is fulfilled, the .NET Remoting framework deletes the object and reclaims its memory. SingleCall objects are inherently stateless. They are a good solution when the overhead of creating the object is not significant, state is not required, and the server needs to support a large number of requests for the object. Because SingleCall objects are stateless, it does not matter which server processes requests for such objects. For this reason, SingleCall activation is ideally suited for load-balanced environments.

103 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NET . . .Remoting . . . . .

In the Singleton activation mode, at most there will be one instance of the remote object, regardless of the number of clients accessing it. Singleton objects are stateful, but the state is globally shared by all its clients. Singleton objects are a good solution when the overhead of creating the object is substantial, state is required, or clients need to share state. Client-activated objects are those remote objects whose lifetime is directly controlled by the client. Client-activated objects are instantiated on the server as soon as the client requests the object to be created. Unlike an SAO, a CAO does not delay the object creation until the first method is called on the object. An instance of a CAO serves only the client responsible for its creation, and the CAO doesn’t get discarded with each request. For this reason, a CAO can maintain state with each client that it is serving, but unlike the Singleton SAO, different CAOs cannot share a common state. CAOs are a good solution when clients need to maintain private state or want complete control over the object. For example, you might implement a remote object that represents a shopping cart on a Web site as a CAO so that each instance of the object has its own private state. Figure 4.3 shows some of the tradeoffs in choosing an activation type. Activation Type

Flexibility

Scalability

SingleCall Server Activation Singleton Server Activation Client Activation

Figure 4.3 SingleCall server activation offers maximum scalability, whereas client activation offers maximum flexibility.

Lifetime Leases A lifetime lease is the period of time that a particular object can be active in memory before the .NET Framework deletes it and reclaims its memory. Both Singleton SAO and CAO use lifetime leases to determine how long they should continue to exist. A lifetime lease is represented using an object that implements the ILease interface defined in the System.Runtime.Remoting.Lifetime namespace.

104 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Simply speaking, the lease works as follows: ➤ When an object is created, its lifetime lease (CurrentLeaseTime) is set

using the value of the InitialLeaseTime property (which is 5 minutes by default). ➤ Whenever the object receives a call, its CurrentLeaseTime is reset to

the time specified by the value of the RenewOnCallTime property (which is 2 minutes by default). ➤ The client can also renew a lease for a remote object by directly calling

the ILease.Renew() method. ➤ When the value of CurrentLeaseTime reaches 0, the .NET Framework

contacts any sponsors registered with the lease to check whether they are ready to sponsor renewing the object’s lease. ➤ If the sponsor does not renew the object or the server cannot contact the

sponsor within the duration specified by the SponsorshipTimeout property, the object is marked for garbage collection.

Applying .NET Remoting Although you won’t have to write code for the exam, you should be familiar with the basic code architecture for various remoting tasks. In particular, you should know how to create a remotable class and how to create both serveractivated and client-activated objects from the class.

Creating a Remotable Class Creating a remotable class is simple. All you need to do is to inherit a class from the MarshalByRefObject class. A simple remotable class in a class library might look like this: Public Class RandomNumber Inherits MarshalByRefObject Private r As System.Random Public Sub New() r = New System.Random() End Sub Public Function NextRandom(ByVal Max As Integer) As Integer NextRandom = r.Next(Max) End Function End Class

105 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NET . . .Remoting . . . . .

If you’d like to follow along with the examples, create this class in a class library named RemotableClass and compile it.

Creating a Server-Activated Object A remotable class is usually connected with the remoting framework through a separate server program. The server program needs to take these steps: 1. Create a server channel that listens on a particular port to the incom-

ing object-activation requests from other application domains. 2. Register the channel with the remoting framework. This tells the

framework which requests should be directed to this particular server. 3. Register the remotable class with the remoting framework. This tells

the framework which classes this particular server can create for remote clients. Normally, you’ll use an existing Windows service, such as Internet Information Services (IIS), or a new Windows service to host remoting objects. But you can also use a simple Windows Forms or console application for this purpose.

Registering a Remotable Class As a Server-Activated Object Using the SingleCall Activation Mode Follow these steps to create a server that exposes the RandomNumber class as a SingleCall SAO: 1. Add a new Visual Basic .NET Console application named

RandomSingleCall to the solution. 2. Add references to the RemotableClass class library and to

System.Runtime.Remoting. 3. Replace the code in the default module of the new project: Imports Imports Imports Imports

RemotableClass System.Runtime.Remoting System.Runtime.Remoting.Channels System.Runtime.Remoting.Channels.Tcp

Module SingleCallServer Public Sub Main() ‘ Create and Register a TCP server channel ‘ that listens on port 50001 Dim channel As TcpServerChannel = _ New TcpServerChannel(50001) ChannelServices.RegisterChannel(channel)

106 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ‘ Register the service that publishes ‘ RandomNumber for remote access in SingleCall mode RemotingConfiguration. _ RegisterWellKnownServiceType( _ GetType(RemotableClass.RandomNumber), “RandomNumber”, _ WellKnownObjectMode.SingleCall) ‘ Keep the server loaded Console.WriteLine(“Started server in the “ & _ “SingleCall mode”) Console.WriteLine(“Press to terminate “ & _ “server...”) Console.ReadLine() End Sub End Module

4. Right-click the project in the Solution Explorer and select Properties.

Change the Startup object to SingleCallServer. 5. Build the project. If a remoting application will run entirely on your company’s network, you can safely use a port in the private port range of 49152 through 65535—provided, of course, that the port number you choose is not used by any other internal application. In case you are distributing the application, you should get a port number registered with the Internet Assigned Numbers Authority (IANA). You can see a list of already assigned port numbers at www.iana.org/assignments/port-numbers.

Instantiating and Invoking a Server-Activated Object At this stage, you have a remotable object as well as a remoting server ready. Now it’s time for a remoting client. In overview, a remoting client must take these steps: 1. Create and register a client channel that is used by the remoting

framework to send messages to the remoting server. 2. Register the remotable class as a valid type in the client’s application

domain. 3. Instantiate the SAO on the server. You can only instantiate an SAO at the client side using its default constructor.

Here’s a remoting client that works with the simple SingleClass server you just created:

107 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NET . . .Remoting . . . . . 1. Add a new Visual Basic .NET Windows Application named

ClientSingleCall to the solution. 2. Add references to the RemotableClass class library and to

System.Runtime.Remoting. 3. Add a TextBox control named

txtMax, a Button control named and a Label control named lblRandom to the default form in the project.

btnGetRandom,

4. Add the following directives to the form’s module: Imports Imports Imports Imports

System.Runtime.Remoting System.Runtime.Remoting.Channels System.Runtime.Remoting.Channels.Tcp RemotableClass

5. Enter this code to handle events on the form: Dim r As RandomNumber Private Sub Form1_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ‘ Register a TCP client channel Dim channel As TcpClientChannel = _ New TcpClientChannel() ChannelServices.RegisterChannel(channel) ‘ Register the remote class as a valid ‘ type in the client’s application domain RemotingConfiguration. _ RegisterWellKnownClientType( _ GetType(RandomNumber), _ “tcp://localhost:50001/RandomNumber”) ‘ Instantiate the remote class r = New RandomNumber() End Sub Private Sub btnGetRandom_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnGetRandom.Click ‘ Call a method on the remote class lblRandom.Text = _ r.NextRandom(Convert.ToInt32(txtMax.Text)) End Sub

6. Right-click the name of the solution in the Solution Explorer window

and select Properties. This opens the Solution Property Pages dialog box. In the dialog box, select the Multiple Startup Projects radio button, select the action Start for RandomSingleCall and ClientSingleCall, and set the action to None for any other projects in the solution. Make sure that RandomSingleCall is placed above

108 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ClientSingleCall. If it isn’t already there, click the Move Up and Move Down buttons to get the right order. 7. Build the project. Select Debug, Start to run the project. You should

see a command window displaying a message that the server is started in the SingleCall mode. 8. Shortly afterward, you’ll see a Windows Form for the client program.

Enter a number in the text box and click the Get Random button. The client invokes a method on the remote object and displays the results.

Registering a Remotable Class As a Server-Activated Object Using the Singleton Activation Mode The same remotable object can be activated in different modes without making any changes to the remotable object itself. In the case of SAO, the choice of activation mode is totally with the server. In fact, you only need to change one line of code in the server to register the remotable object as a Singleton object rather than a SingleCall object. The affected line is shown here in bold: Public Sub Main() ‘ Create and Register a TCP server channel ‘ that listens on port 50001 Dim channel As TcpServerChannel = _ New TcpServerChannel(50001) ChannelServices.RegisterChannel(channel) ‘ Register the service that publishes ‘ RandomNumber for remote access in Singleton mode RemotingConfiguration. _ RegisterWellKnownServiceType( _ GetType(RemotableClass.RandomNumber), “RandomNumber”, _ WellKnownObjectMode.Singleton) ‘ Keep the server loaded Console.WriteLine(“Started server in the “ & _ “Singleton mode”) Console.WriteLine(“Press to terminate “ & _ “server...”) Console.ReadLine() End Sub

Creating a Client-Activated Object When exposing a remotable class as a CAO, no changes are required to be made on the remotable class. Instead, you modify the client and the server, changing their interactions with the remoting system.

109 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NET . . .Remoting . . . . .

You’ll have to take the following steps to register a remotable class as a CAO on the server: 1. Create a server channel that listens on a particular port to the incom-

ing object-activation requests from other application domains. 2. Register the channel with the remoting framework. 3. Register the remotable class with the remoting framework. For a

client-activated object, this registration is performed using the RegisterActivatedServiceType() method of the RemotingConfiguration class. Putting the pieces together, here’s how to register the RandomNumber class as a CAO: Public Sub Main() ‘ Create and Register a TCP server channel ‘ that listens on port 50001 Dim channel As TcpServerChannel = _ New TcpServerChannel(50001) ChannelServices.RegisterChannel(channel) ‘ Register the service that publishes ‘ RandomNumber for remote access as a CAO RemotingConfiguration. _ RegisterActivatedServiceType( _ GetType(RandomNumber)) ‘ Keep the server loaded Console.WriteLine(“Started server in the “ & _ “Client activation mode”) Console.WriteLine(“Press to terminate “ & _ “server...”) Console.ReadLine() End Sub

To instantiate and invoke a client-activated object, the remoting client needs to take the following steps: 1. Create and register a client channel used by the remoting framework

to send messages to the remoting server. 2. Register the remotable class as a valid type in the client’s application

domain. This registration is performed using the RegisterActivatedClientType() method of the RemotingConfiguration class. 3. Instantiate the CAO on the server using the desired constructor.

110 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . You can instantiate a CAO at the client side using any of its available constructors.

The client code for using the CAO version of the RandomNumber object looks like this: Dim r As RandomNumber Private Sub Form1_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ‘ Register a TCP client channel Dim channel As TcpClientChannel = _ New TcpClientChannel() ChannelServices.RegisterChannel(channel) ‘ Register the remote class as a valid ‘ type in the client’s application domain RemotingConfiguration. _ RegisterActivatedClientType( _ GetType(RandomNumber), “tcp://localhost:50001”) ‘ Instantiate the remote class r = New RandomNumber() End Sub Private Sub btnGetRandom_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnGetRandom.Click ‘ Call a method on the remote class lblRandom.Text = _ r.NextRandom(Convert.ToInt32(txtMax.Text)) End Sub

Using Configuration Files to Configure the Remoting Framework In all the examples so far, I have written code to register the channel and remote object with the remoting framework. This approach to specifying settings is also known as programmatic configuration. Alternatively, you can store the remoting settings in an XML-based configuration file instead of in the code file. Any changes made to the configuration file can be automatically picked up by the program when it executes the next time. The general format of a remoting configuration file is as follows:

111 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NET . . .Remoting . . . . .















A particular configuration file for the RandomNumber object might look like this:







112 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

With this file saved as RandomServer.exe.config to the same folder as the executable file for the server (normally the bin folder underneath the server project), the server code could be simplified as follows: Sub Main() ‘ Load remoting configuration RemotingConfiguration.Configure( _ “RandomServer.exe.config”) Console.WriteLine(“Started server”) Console.WriteLine(“Press to terminate “ & _ “server...”) Console.ReadLine() End Sub

The configuration of a remoting client is quite similar to that of a remoting server. However, you’d configure the element of the configuration file instead of the element.

Using IIS As an Activation Agent Rather than run a separate console application to host a remotable object, you may want to use IIS as an activation agent. Using IIS as an activation agent offers the following advantages: ➤ You need not write a separate server program to register the remotable

classes. ➤ You need not worry about finding an available port for your server

application. You can just host the remotable object, and IIS automatically uses the port 80. ➤ IIS can provide other functionality, such as authentication and Secure

Sockets Layer (SSL). The following list specifies what you need to do in order to host a remotable class in IIS: ➤ Place the assembly containing the remotable objects into the \bin direc-

tory of an IIS Web application or place the assembly in the Global Assembly Cache (GAC) on the IIS computer. ➤ Configure the remoting settings by placing the

configuration section into the Web.config file for the Web application. ➤ You should not specify a channel. IIS already listens on port 80.

Specifying a port for a channel causes exceptions to be thrown when new IIS worker processes are started.

113 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NET . . .Remoting . . . . . ➤ The well-known object URI (Uniform Resource Indicator) must end

with the extension .rem or .soap because these are the two extensions registered with both IIS (via the aspnet_isapi.dll) and the remoting system (in machine.config). When creating IIS-hosted remote objects, you cannot specify constructor parameters. Therefore, activating CAO is not possible using IIS.

IIS Activation only supports the HTTP channel. The default formatting is SOAP, but IIS also supports binary and other custom formatting.

Here’s how you can use IIS as an activation agent for the RandomNumber class: 1. Add a new Empty Web Project named RandomWeb to the solution. 2. Add a reference to the RemotableClass project. 3. Add a Web Configuration File to the project. Open the Web.config

file and add the following element inside the element:





Lambert Tractor Works

Millbank WA



Doppel OR

XML Declaration The first thing you find in an XML file is the XML declaration:

The declaration tells you three things about this document: ➤ It’s an XML document. ➤ It conforms to the XML 1.0 specification of the W3C. ➤ It uses the UTF-8 character set (a standard set of characters for the

Western alphabet). The XML declaration is optional. However, the W3C XML recommendation suggests that you include the XML declaration. The XML declaration can help identify the XML version and the character encoding used in an XML document. Lines that begin with a string are called processing instructions (PIs). Processing instructions are used to provide information to the application processing an XML document on how to process it.

XML Comments An XML document can contain comments. Comments are set off by the opening string

445 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .XML . . Standards . . . . . . and . . Syntax . . . .

XML Elements XML consists of tags (that is, markup), which are contained within angle brackets, and character data. The character data is the information stored in the XML files, and the tags (markup) record the structure of the XML file. XML tags usually describe the data contained by them rather than describing format or layout information. Tags appear in pairs, with each opening tag matched by a closing tag. The closing tag has the same text as the opening tag, prefixed with a forward slash. For example, if is the opening tag, is the closing tag. An opening tag together with a closing tag and the content between them define an element. Tags in an XML document contain the name of the element. For example, here’s a single element from the sample document: OR

This defines an element whose name is CustomerState and whose data is OR. Elements can sometime contain no content. Such elements are called empty elements. For example, here’s an element with no content:

This defines an element whose name is Citizen. Empty elements can also be defined using a shorter syntax. Here’s an example:

In this case, you do not provide the closing tag, but you end the opening tag with />. Elements can be nested, but they cannot overlap. Nested elements have a logical parent-child relationship. A parent element can contain any number of child elements, but a child element belongs to only one parent element. Every element in an XML document is a child element except one element. This is the root element in the XML document that contains all other child elements. The root element in the sample document is named Customers. The Customer elements in that document are nested within the Customers element.

XML Attributes Elements can contain attributes. An attribute is a piece of data that further describes an element. Attributes appear in a name-value pair in the opening

446 Appendix B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

tag of an element. For example, the sample document includes this opening tag for an element:

This declares an element named Customer. The Customer element includes an attribute whose name is CustomerNumber and whose value is 1. The value of the attribute must always be enclosed in either single or double quotation marks.

XML Naming Convention If you’re familiar with HTML, you know that in HTML, some elements have names dictated by the HTML specification. For example, the tag specifies a first-level heading. XML takes a different approach. You can make up any name you like for an XML element or attribute, subject to some simple naming rules: ➤ A name can contain any alphanumeric character. ➤ A name can contain underscores, hyphens, and periods. ➤ A name must not contain any whitespace. ➤ A name must start with a letter or an underscore.

The names of the XML elements and attributes can be in uppercase, lowercase, or both, but they are case sensitive. For example, the following is not well-formed XML because the opening and closing tags of the element do not match: OR

Handling Special Characters in XML Data Some characters have special meaning for the programs that process XML. For example, the opening angle bracket indicates the beginning of a tag. Quotation marks enclose the attributes, and so on. But sometime you might also like to use these characters as part of the XML data. XML offers two ways to deal with special characters in data. First, for individual characters, you can use entity references. Five entity references are defined in the XML standard: ➤

—Translates

to > (closing angle bracket)

447 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .XML . . Standards . . . . . . and . . Syntax . . . . ➤

&—Translates

to & (ampersand)



'—Translates

to ‘ (apostrophe)



"—Translates

to “ (quotation mark)

You can also use a CDATA section to hold any arbitrary data, whether the data contains special characters or not. The sample document uses this approach to store a customer name containing an apostrophe, as shown here:

sections are generally used for large amounts of text that may or may not contain special characters. Individual special characters are normally represented by an entity reference. CDATA

XML Namespaces An XML document can contain one or more namespace declarations. A namespace is a device for uniquely identifying elements. Although the sample document at the beginning of this chapter does not declare a namespace, here’s an example of how to declare one:

The namespace is declared as part of the root tag for the document. In this particular case, the namespace (introduced with the special xmlns characters) defines the prefix tr for tags within the namespace. The urn (uniform resource name) is an arbitrary string whose purpose is to distinguish this namespace from other namespaces. XML namespaces serve the same purpose as .NET namespaces: They help cut down on naming collisions. After declaring the tr namespace, an XML document could use a tag such as this: OR

This example indicates that the CustomerState tag is from the and should not be confused with any other CustomerState tag.

tr

namespace

448 Appendix B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Need to Know More? Elliotte, Rusty Harold and W. Scott Means. XML in a Nutshell. O’Reilly, 2001. W3C XML Home Page: www.w3.org/XML.

C What’s on the CD-ROM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

This appendix is a brief rundown of what you’ll find on the CD-ROM that comes with this book. For a more detailed description of the PrepLogic Practice Tests, Preview Edition exam simulation software, see Appendix D, “Using the PrepLogic Practice Tests, Preview Edition Software.” In addition to the PrepLogic Practice Tests, Preview Edition, the CD-ROM includes the electronic version of the book in Portable Document Format (PDF), and a set of sample applications demonstrating code concepts from the book.

PrepLogic Practice Tests, Preview Edition PrepLogic is a leading provider of certification training tools. Trusted by certification students worldwide, PrepLogic is, we believe, the best practice exam software available. In addition to providing a means of evaluating your knowledge of the Exam Cram 2 material, PrepLogic Practice Tests, Preview Edition features several innovations that help you to improve your mastery of the subject matter. For example, the practice tests allow you to check your score by exam area or domain to determine which topics you need to study more. Another feature allows you to obtain immediate feedback on your responses in the form of explanations for the correct and incorrect answers. PrepLogic Practice Tests, Preview Edition exhibits most of the full functionality of the Premium Edition but offers only a fraction of the total questions. To get the complete set of practice questions and exam functionality, visit PrepLogic.com and order the Premium Edition for this and other challenging exam titles.

450 Appendix C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Again, for a more detailed description of the PrepLogic Practice Tests, Preview Edition features, see Appendix D.

D Using PrepLogic Practice Tests, Preview Edition Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

This Exam Cram 2 includes a special version of PrepLogic Practice Tests—a revolutionary test engine designed to give you the best in certification exam preparation. PrepLogic offers sample and practice exams for many of today’s most in-demand and challenging technical certifications. This special Preview Edition is included with this book as a tool to use in assessing your knowledge of the Exam Cram 2 material while also providing you with the experience of taking an electronic exam. This appendix describes in detail what PrepLogic Practice Tests, Preview Edition is, how it works, and what it can do to help you prepare for the exam. Note that although the Preview Edition includes all the test-simulation functions of the complete, retail version, it contains only a single practice test. The Premium Edition, available at PrepLogic.com, contains the complete set of challenging practice exams designed to optimize your learning experience.

Exam Simulation One of the main functions of PrepLogic Practice Tests, Preview Edition is exam simulation. To prepare you to take the actual vendor certification exam, PrepLogic Practice Tests, Preview Edition is designed to offer the most effective exam simulation available.

452 Appendix D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Question Quality The questions provided in the PrepLogic Practice Tests, Preview Edition are written to the highest standards of technical accuracy. The questions tap the content of the Exam Cram 2 chapters and help you review and assess your knowledge before you take the actual exam.

Interface Design The PrepLogic Practice Tests, Preview Edition exam-simulation interface provides you with the experience of taking an electronic exam. This enables you to effectively prepare for taking the actual exam by making the test experience a familiar one. Using this test simulation can help eliminate the sense of surprise or anxiety you might experience in the testing center because you will already be acquainted with computerized testing.

Effective Learning Environment The PrepLogic Practice Tests, Preview Edition interface provides a learning environment that not only tests you through the computer but also teaches the material you need to know to pass the certification exam. Each question comes with a detailed explanation of the correct answer and often provides reasons the other options are incorrect. This information helps to reinforce the knowledge you already have and also provides practical information you can use on the job.

Software Requirements PrepLogic Practice Tests requires a computer with the following: ➤ Microsoft Windows 98, Windows Me, Windows NT 4.0, Windows

2000, or Windows XP. ➤ A 166MHz or faster processor is recommended. ➤ A minimum of 32MB of RAM. (As with any Windows application, the

more memory, the better your performance.) ➤ 10MB of hard drive space.

453 . . . . . . . . . . . . . . . . . .Using . . . PrepLogic . . . . . .Practice . . . . Tests, . . . .Preview . . . . Edition . . . . Software . . . . .

Installing PrepLogic Practice Tests, Preview Edition Install PrepLogic Practice Tests, Preview Edition by running the setup program on the PrepLogic Practice Tests, Preview Edition CD-ROM. Follow these instructions to install the software on your computer. 1. Insert the CD-ROM into your CD-ROM drive. The Autorun feature

of Windows should launch the software. If you have Autorun disabled, click Start and select Run. Go to the root directory of the CD and select setup.exe. Click Open and then click OK. 2. The Installation Wizard copies the PrepLogic Practice Tests, Preview

Edition files to your hard drive; adds PrepLogic Practice Tests, Preview Edition to your Desktop and Program menu; and installs test engine components to the appropriate system folders.

Removing PrepLogic Practice Tests, Preview Edition from Your Computer If you elect to remove the PrepLogic Practice Tests, Preview Edition product from your computer, an uninstall process has been included to ensure that it is removed safely and completely. Follow these instructions to remove PrepLogic Practice Tests, Preview Edition from your computer: 1. Select Start, Settings, Control Panel. 2. Double-click the Add/Remove Programs icon. 3. You are presented with a list of software installed on your computer.

Select the appropriate PrepLogic Practice Tests, Preview Edition title you want to remove. Click the Add/Remove button. The software is then removed from your computer.

Using PrepLogic Practice Tests, Preview Edition PrepLogic Practice Tests, Preview Edition is designed to be user friendly and intuitive. Because the software has a smooth learning curve, your time is maximized because you start practicing almost immediately. PrepLogic

454 Appendix D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Practice Tests, Preview Edition has two major modes of study: Practice Test and Flash Review. Using Practice Test mode, you can develop your test-taking abilities as well as your knowledge through the use of the Show Answer option. While you are taking the test, you can expose the answers along with a detailed explanation of why the given answers are right or wrong. This gives you the ability to better understand the material presented. Flash Review is designed to reinforce exam topics rather than quiz you. In this mode, you will be shown a series of questions but no answer choices. Instead, you will be given a button that reveals the correct answer to the question and a full explanation for that answer.

Starting a Practice Test Mode Session Practice Test mode enables you to control the exam experience in ways that actual certification exams do not allow: ➤ Enable Show Answer Button—Activates the Show Answer button, allowing

you to view the correct answer(s) and full explanation(s) for each question during the exam. When this feature is not enabled, you must wait until after your exam has been graded to view the correct answer(s) and explanation(s). ➤ Enable Item Review Button—Activates the Item Review button, allowing

you to view your answer choices and marked questions and facilitating navigation between questions. ➤ Randomize Choices—Randomizes answer choices from one exam session

to the next and makes memorizing question choices more difficult, thereby keeping questions fresh and challenging longer. To begin studying in Practice Test mode, click the Practice Test radio button from the main exam-customization screen. This enables the options detailed in the preceding list. To your left, you are presented with the option of selecting the preconfigured Practice Test or creating your own custom test. The preconfigured test has a fixed time limit and number of questions. Custom Tests allow you to configure the time limit and the number of questions in your exam. The Preview Edition included with this book provides a single, preconfigured Practice Test. Get the compete set of challenging PrepLogic Practice Tests at PrepLogic.com and make certain you’re ready for the big exam. Click the Begin Exam button to begin your exam.

455 . . . . . . . . . . . . . . . . . .Using . . . PrepLogic . . . . . .Practice . . . . Tests, . . . .Preview . . . . Edition . . . . Software . . . . .

Starting a Flash Review Mode Session Flash Review mode provides you with an easy way to reinforce topics covered in the practice questions. To begin studying in Flash Review mode, click the Flash Review radio button from the main exam-customization screen. Select either the preconfigured Practice Test or create your own Custom Test. Click the Best Exam button to begin your Flash Review of the exam questions.

Standard PrepLogic Practice Tests, Preview Edition Options The following list describes the function of each of the buttons you see. Depending on the options, some of the buttons will be grayed out and inaccessible or missing completely. Buttons that are appropriate are active. The buttons are as follows: ➤ Exhibit—This button is visible if an exhibit is provided to support the

question. An exhibit is an image that provides supplemental information necessary to answer the question. ➤ Item Review—This button takes you from the question window to the

Item Review screen. From this screen you will see all the questions, your answers, and your marked items. You will also see correct answers listed here when appropriate. ➤ Show Answer—This option displays the correct answer with an explana-

tion of why it is correct. If you select this option, the current question is not scored. ➤ Mark Item—Check this box to tag a question you need to review further.

You can view and navigate your marked items by clicking the Item Review button (if enabled). When grading your exam, you will be notified if you have marked items remaining. ➤ Previous Item—Used to view the previous question. ➤ Next Item—Used to view the next question. ➤ Grade Exam—When you have completed your exam, click this button to

end your exam and view your detailed score report. If you have unanswered or marked items remaining, you will be asked whether you would like to continue taking your exam or view your exam report.

456 Appendix D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Time Remaining If the test is timed, the time remaining is displayed in the upper-right corner of the application screen. It counts down the minutes and seconds remaining to complete the test. If you run out of time, you will be asked whether you want to continue taking the test or end your exam.

Your Examination Score Report The Examination Score Report screen appears when the Practice Test mode ends—as the result of time expiration, the completion of all questions, or your decision to terminate early. This screen provides you with a graphical display of your test score, with a breakdown of scores by topic domain. The graphical display at the top of the screen compares your overall score with the PrepLogic Exam Competency Score. The PrepLogic Exam Competency Score reflects the level of subject competency required to pass this vendor’s exam. Although this score does not directly translate to a passing score, consistently matching or exceeding this score does suggest you possess the knowledge to pass the actual vendor exam.

Reviewing Your Exam From Your Score Report screen, you can review the exam you just completed by clicking the View Items button. Navigate through the items, viewing the questions, your answers, the correct answers, and the explanations for those answers. You can return to your score report by clicking the View Items button.

Get More Exams The PrepLogic Practice Tests, Preview Edition that accompanies your book contains a single PrepLogic Practice Test. Certification students worldwide trust PrepLogic Practice Tests to help them pass their IT certification exams the first time. Purchase the Premium Edition of PrepLogic Practice Tests and get the entire set of the new, challenging Practice Tests for this exam. PrepLogic Practice Tests—Because You Want to Pass the First Time.

457 . . . . . . . . . . . . . . . . . .Using . . . PrepLogic . . . . . .Practice . . . . Tests, . . . .Preview . . . . Edition . . . . Software . . . . .

Contacting PrepLogic If you would like to contact PrepLogic for any reason, including information about our extensive line of certification practice tests, we invite you to do so. Please contact us online at www.preplogic.com.

Customer Service If you have a damaged product and need a replacement or refund, please call the following phone number: 800-858-7674

Product Suggestions and Comments We value your input! Please email your suggestions and comments to the following address: [email protected]

License Agreement YOU MUST AGREE TO THE TERMS AND CONDITIONS OUTLINED IN THE END USER LICENSE AGREEMENT (“EULA”) PRESENTED TO YOU DURING THE INSTALLATION PROCESS. IF YOU DO NOT AGREE TO THESE TERMS, DO NOT INSTALL THE SOFTWARE.

Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ACID (Atomic, Consistent, Isolated, and Durable) The key properties of a transaction. A transaction executes as a single thing (atomic), always leaves the data in a sensible state (consistent), is not affected by other transactions (isolated), and makes a permanent change (durable).

activation type An activation category for a serviced component application that indicates whether the application runs in or out of its client’s process space (a library or a server application).

ad hoc query

assembly A logical unit of functionality that can contain one or more files. Every type loaded in the Common Language Runtime (CLR) belongs to precisely one assembly.

assembly manifest Stores the assembly’s metadata. The metadata provides selfdescribing information, such as the name and version of the assembly, the files that are part of the assembly and their hash values, the files’ dependencies on other assemblies, and so on. This subset of information in the manifest makes assemblies self-sufficient.

A set of SQL statements that are executed immediately.

attribute

application domain

authentication

A secure unit of processing that the Common Language Runtime (CLR) uses to provide isolation between applications.

The process of determining the identity of a user from his or her credentials.

A property of an XML object.

460 authorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

authorization

COM+ catalog

The process of allowing a user to use specific resources based on his or her authenticated identity.

A COM+ repository that maintains the configuration information for COM+ components.

binding policy

COM interface

A set of rules that specifies which version of an assembly the Common Language Runtime (CLR) will load.

A collection of related public functions that provide access to a COM object. The set of interfaces on a COM object specifies how programs and other objects can interact with the COM object.

CDATA section Raw data within an XML file.

channel In remoting, a channel has the responsibility of transmitting all messages between the client and object across a process boundary.

CLR (Common Language Runtime) The program that executes all managed code and provides code with various services at runtime, such as automatic memory management, cross-language integration, code access security, and debugging and profiling support.

code access security Security based on the identity of the running code.

COM+ application A primary unit of administration and security for the COM+ Component Services. A COM+ application is a group of components that, generally, perform related functions. These components further consist of interfaces and methods.

conditional compilation A process for determining at compile time whether particular sections of code should be included in a project.

context A set of runtime properties that defines the environment for the objects that reside within it.

DataSet class A server-independent store that can hold multiple tables and their relations. You can think of a DataSet as a memory-resident relational database.

DataSet schema An XML file that describes the structure of a DataSet.

debugging The process of locating logical or runtime errors in an application. It involves finding the cause of the errors and fixing them.

461 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . key . .

delayed signing

DTD (Document Type Definition)

A process that allows an assembly to be given a strong name while withholding the signing keys until after the assembly is compiled. This allows you to guard your private key closely while still securing the assembly.

A reference in an XML file that specifies which nodes are valid in the file.

deployment

FCL (Framework Class Library)

A process by which a Windows application or component is distributed in the form of installation package files to be installed on the other computers.

deserialization The process of converting an XML representation of an object back to the object.

element An XML tag together with its contents. A library of classes, interfaces, and value types that are included in the Microsoft .NET Framework. This library provides access to the system functionality and is the foundation on which the .NET Framework applications, components, and controls are built.

GAC (Global Assembly Cache)

An XML file containing changes to be applied to a DataSet.

The Global Assembly Cache is an area for the storage of assemblies that can be shared by many applications on the computer.

Disco

identity

A Microsoft standard for Web service discovery.

An identity column in a database is one with a value that is automatically assigned by the server when a new row is entered.

DiffGram

DOM (Document Object Model) An Internet standard for representing the information contained in an HTML or XML document as a tree of nodes.

DTC (Distributed Transaction Coordinator) A Windows service that manages transactions and transaction-related communications that are distributed across two or more resource managers on one or more systems to ensure ACID properties.

just-in-time activation The capability for a COM+ object to be activated only as needed for executing requests from its client.

key A key column in a database stores keys that uniquely identify a row (primary key) or that refer to a row in another table (foreign key).

462 managed code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

managed code

object pooling

Code that runs under the Common Language Runtime (CLR).

A performance optimization based on using collections of already created objects. Pooling results in more efficient resource allocation.

marshaling Packaging and sending interface method calls across thread or process boundaries via serialization and deserialization.

Merge Module A Merge Module allows you to create reusable components that help in deploying shared components. Merge Modules cannot be directly installed. They need to be merged with installers of applications that use the component packed into a Merge Module.

metadata Data that describes other data.

namespace A naming scheme that provides a way to logically group related types. Namespaces have two benefits: They are used to avoid naming conflicts, and they make it easier to browse and locate classes.

native compilation The process of precompiling assemblies in the processor-specific machine code.

.NET Framework A platform for building, deploying, and running XML Web services and applications. The .NET Framework consists of three main parts: the Common Language Runtime (CLR), the Framework Class Library (FCL), and a set of language compilers.

parameter A piece of information that is passed to a stored procedure at runtime or that is returned by the stored procedure to the calling code.

PInvoke (Platform Invoke) The feature of the .NET Framework that allows you to call Windows API and other DLL procedures from managed code.

private assembly An assembly available only to clients in the same directory tree as the assembly.

proxy An interface-specific object that packages parameters for that interface in preparation for a remote method call. A proxy runs in the address space of the sender and communicates with a corresponding stub in the receiver’s address space.

queued components A COM+ service that provides an easy way to invoke and execute components asynchronously. Message processing can occur without regard to the availability of either the sender or the receiver.

463 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SQL-92 . . . .

RCW (runtime callable wrapper)

shared assembly

A proxy that allows .NET code to make use of COM classes and members.

An assembly that can be referenced by more than one application. An assembly must be explicitly built to be shared by giving it a cryptographically strong name. Shared assemblies are stored in the machinewide Global Assembly Cache.

remoting The .NET Remoting system is an architecture designed to simplify communication between objects running in different application domains, whether they’re on the same computer.

role-based security Security based on the authenticated identity of the user running the code.

runtime host The environment in which the Common Language Runtime (CLR) is started and managed. When you install the .NET Framework, you get three runtime hosts already configured: the Windows shell, ASP.NET, and Internet Explorer. The runtime hosts create application domains, which run the managed code on behalf of the user.

schema The structure of a database or XML file.

SCM (Service Control Manager) The part of the Windows operating system that manages Windows services.

serialization The process of converting one or more objects to their XML representation.

side-by-side execution The ability of .NET to load more than one version of an assembly simultaneously.

signing The process of assigning a cryptographically strong name to an assembly.

SOAP (Simple Object Access Protocol) A standard for transmitting objects as XML over HTTP.

SOAP extension A class that is invoked during the serialization or deserialization of SOAP messages.

SOAP request A SOAP message sent from client to server to invoke a Web method.

SOAP response A SOAP message sent from server to client with the results of a Web method.

SQL-92 The official ANSI specification for the Structured Query Language.

464 stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

stored procedure

transaction

A set of SQL statements stored on the server for later execution.

A unit of work that is done as an atomic operation—that is, the operation succeeds or fails as a whole.

strong name The combination of a simple text name, a version number, and culture information (if provided) that is signed by a digital signature and contains a public key of the assembly. Strong names provide security for assemblies by making it very difficult to forge the identity of an assembly.

strongly typed DataSet A DataSet class that allows you to use early binding for table and column names.

testing The process of executing programs and determining whether they worked as expected.

trace listener A class that can receive trace messages from the Trace or Debug classes.

trace switch A class that dictates whether trace messages from the Trace or Debug classes should be emitted by an application being executed.

tracing The process of displaying informative messages in an application at the time of execution. Tracing is a noninteractive process, unlike interactive debugging.

T-SQL (Transact-SQL) The SQL-92 dialect used in Microsoft SQL Server.

UDDI (Universal Description, Discovery, and Integration) A standard for discovering details of Web services and other business services available via the Internet.

unmanaged code Code written in a non-.NET environment that does not benefit from the services of the Common Language Runtime (CLR).

Web method A method of a Web service that can be invoked by client applications.

Web reference Information in a Visual Studio .NET project that allows you to use objects supplied by a Web service.

Web service A Web service is an application that makes one or more objects available to clients over the Internet. Web services communicate with clients using standard protocols such as SOAP and WSDL.

465 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .XPath . . .

Windows service A Windows process that runs in the background, usually without any user interaction. A Windows service must conform to the interface provided by the Windows Service Control Manager. Windows services may run for the entire time the operating system is loaded or can be started and stopped by the Service Control Manager.

WSDL (Web Services Description Language) An XML language that describes the interface of a Web service.

XML Extensible Markup Language. XML is a general language consisting of metadata tags that can contain data.

XML declaration The line in an XML file that identifies the file as XML.

XML namespace An XML namespace defines a set of XML tags that are uniquely identified so that they cannot be confused with XML tags in another namespace.

XML wire format The structure of the actual XML messages passed between Web services servers and clients.

XPath A query language for XML documents.

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

* (asterisk) wild card SELECT statements, 36 XPath queries, 69 ^ (caret) wild card, 39 % (percent) wild card, 38 _ (underscore) wild card, 38-39 —! XML closing string, 444 !— XML opening string, 444

A abort bits, 206-207 AcceptChanges method (DataSet class), 428 access code access security, 290-292 code groups, 292-293 computing permissions, 295-297 granting/denying permissions, 293-294 imperative security, 295 permission sets, 293 requesting permissions, 292, 297 Simple Access Object Protocol. See SOAP XML files, 58 DOM (Document Object Model), 58-59 XmlDocument class, 63-65 XmlNode class, 62-63

XmlReader class, 59-62 XPathNavigator class, 71-75 Account property (ServiceProcessInstaller class), 174 Activate method (ServicedComponent class), 191 activating remote objects, 102-103 serviced components, 194-195 ActiveX components, packaging, 276 ad hoc T-SQL queries, 34 cross-product queries, 36 DELETE statement, 44-45 INSERT statement, 42-43 running, 34-35 SELECT statement, 35-42 GROUP BY clause, 40-41 HAVING clause, 41-42 INNER JOIN clause, 37 ORDER BY clause, 39-40 querying multiple tables, 36-37 required clauses, 36 WHERE clause, 37-39 UPDATE statement, 43-44 adaptive certification exams, 13-15, 18 Add Web Reference dialog box, 125-126 ADO.NET, 423-424 data providers, 424-427 SqlCommand class, 426 SqlConnection class, 426

468 ADO.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SqlDataAdapter class, 427 SqlDataReader class, 426 SqlParameter class, 426 DataSet objects, 427-428 adding data, 438-439 deleting data, 439-440 DataColumn, 429 DataRelation, 428 DataRow, 428-429 DataTable, 428 DataView, 429, 436-437 finding data, 433-436 moving through, 431-432 with multiple tables, 432-433 populating, 430-431 sorting data, 436-437 updating data, 437-438 aggregate functions, T-SQL, 40-41 anonymous authentication (IIS), 300 AppendChild method (XmlNode class), 62 Application logs, 256 ApplicationAccessControl attribute, 308 ApplicationQueuing attribute, 208 applications COM+ applications, 193 deploying, 265-266 .NET Remoting objects, 281-282 packaging .NET applications, 274-276 private assemblies, 266-269 serviced components, 280-281 shared assemblies, 270-274 Web services, 279-280 Windows services, 280 distributed applications, 98 testing, 236 ASP.NET authentication, 298-299 tracing, 242-246 assemblies, deploying, 266 private assemblies, 266-269 adding probing locations, 269 binding policy, 266-267 locating privately deployed assemblies, 267-269

shared assemblies, 270-274 adding assemblies to GAC, 272-273 assigning strong names, 270-271 binding policy, 273-274 delay signing, 272 Assembly Binding Log Viewer, 269 Assembly Registration (regasm.exe) tool assembly-registration process, 189 exporting .NET components as COM libraries, 190 assembly-registration process, 189-190 assembly signing, 190 Assert method Debug class, 237 Trace class, 237 assertions, 238 associating file extensions, 278 asynchronous Web service calls, 126-127, 149-151 callback functions, 127, 150 WaitHandle object, 150-151 attributes DataSet schema attributes, 26-27 DOM attributes, 59 XML attributes, 445-446 Attributes property (XmlNode class), 62 authentication, 297-298 ASP.NET authentication, 298-299 forms authentication, 301 IIS authentication, 298-300 no authentication, 298 passport authentication, 300-301 providers, 299 serviced components, 308-309 Authenticode signatures, 272 authorization, 301 element, Web.config, 305 serviced components, 308-309 auto mode, FOR XML clause, 82 AutoFlush property Debug class, 237 Trace class, 237 AutoLog property, ServiceBase class, 170 Autos window, debugging code, 249 AVG() function, T-SQL, 40

469 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .CLR . .

B bare parameters, 158 basic authentication (IIS), 300 BeginEdit method (DataRow class), 429 binary formatters, 101-102 BinaryFormatter class, 101 binding policies, 266 private assemblies, 266-269 shared assemblies, 273-274 BooleanSwitch class, 239-240 breakpoints, 248 BufferResponse property (WebMethod attribute), 129

C CAB Project template, 276 CacheDuration property (WebMethod attribute), 129 Call Stack window, debugging code, 249 callback functions, 127, 150 CanBePooled method (ServicedComponent class), 191 CancelEdit method (DataRow class), 429 CanPauseAndContinue property ServiceBase class, 170 ServiceController class, 179 CanShutdown property ServiceBase class, 170 ServiceController class, 179 CanStop property ServiceBase class, 170 ServiceController class, 179 CAOs (client-activated objects), 103 creating, 108-110 instantiating, 109-110 case studies, 4, 13, 15 exhibits, 4 strategies for, 15-16 CategoryName property (PerformanceCounter class), 257 CCW (COM-callable wrapper), 190 CDATA sections, 447

certification exams, 1-2 adaptive tests, 13-15 strategies for, 18 assessing readiness for, 2 case studies, 4, 13-15 exhibits, 4 strategies for, 15-16 fixed-length tests, 13 number of questions, 15 strategies for, 16-17 PrepLogic Practice Tests, Preview Edition, 449-457 questions, 4-5 build-list-and-reorder, 6-8 case studies, 4 create-a-tree, 8-9 drag-and-connect, 10-11 hot-area questions, 12 multiple choice, 5-6 select-and-place, 11 strategies for, 19-20 resources, 20-22 short-form tests, 14-15 strategies for, 16-17 testing centers, 3-4 channels, 101-102 ChildNodes property (XmlNode class), 62 Clear method (DataSet class), 428 client-activated objects (CAOs), 103 creating, 108-110 instantiating, 109-110 client-side scripts, debugging, 252-253 Clone method (XPathNavigator class), 72 CloneNode method (XmlNode class), 62 Close method Debug class, 238 PerformanceCounter class, 257 ServiceController class, 179 Trace class, 238 closing tags, XML, 445 CLR (Common Language Runtime) private assembly binding policies, 266-269 shared assembly binding policies, 273-274

How can we make this index more useful? Email us at [email protected]

470 code access security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . code access security, 290-292 code groups, 292-293 computing permissions, 295-297 granting/denying permissions, 293-294 imperative security, 295 permission sets, 293 requesting permissions, 292, 297 code groups, 292-293 columns, identity, 49 COM components, 218 direct references, 222 registering COM DLLs, 220 runtime callable wrappers, 219 Type Library Importer tool, 220-222 COM libraries, exporting .NET components as, 190 COM+ applications, 193 COM+ catalogs, 194 COM+ components authentication, 308-309 authorization, 308-309 just-in-time activation, 188, 203-205 object pooling, 188, 201-203 queued components, 188, 208-209 role-based security, 188 transaction processing, 188, 205-207 COM-callable wrapper (CCW), 190 Command class, 426 comments, XML, 444 ComparePosition method (XPathNavigator class), 72 Compile method (XPathNavigator class), 72 Component Services (regsvcs.exe) tool, 280-281 ComponentAccessControl attribute, 309 components COM components, 218 direct references, 222 registering COM DLLs, 220 runtime callable wrappers, 219 Type Library Importer tool, 220-222 COM+ components authentication, 308-309 authorization, 308-309

just-in-time activation, 188, 203-205 object pooling, 188, 201-203 queued components, 188, 208-209 role-based security, 188 transaction processing, 188, 205-207 .NET components assembly-registration process, 189-190 exporting as COM type libraries, 190 serviced components, 191 activating, 194-195 consuming, 198, 200-201 context, 194-195 creating, 196-199 declarative programming model, 191-193 deploying, 280-281 runtime requirements, 194 security, 308-309 concat function (XPath), 70 Conditional attribute, 242 ConditionalAttribute class, 242 configuration files .NET Remoting, 110-112 Web.config file tag, 305 tag, 112 tag, 245-246 configuring authentication, 297-298 ASP.NET authentication, 298-299 forms authentication, 301 IIS authentication, 298-300 no authentication, 298 passport authentication, 300-301 providers, 299 authorization, 301 remoting framework, 110-112 Connection class, 426 consistent bits, 206-207 #Const directive, 242 Construct method (ServicedComponent class), 191 consuming serviced components, 198-201

471 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deactivate . . . . . . method . . . . contains function (XPath), 70 context, 194-195 ContextUtil class, 195 Continue method (ServiceController class), 179 ConvertAssemblyToTypeLib method (TypeLibConverter class), 190 count function (XPath), 70 COUNT() function, T-SQL, 40 CounterHelp property (PerformanceCounter class), 257 CounterName property (PerformanceCounter class), 257 CounterType property (PerformanceCounter class), 257 CREATE PROCEDURE statement (T-SQL), 45-46 CreateAttribute method (XmlDocument class), 65 CreateElement method (XmlDocument class), 65 CreateEventSource method (EventLog class), 256 CreateNavigator method (XPathDocument class), 72 CreateNode method (XmlDocument class), 65 CreationTimeout property (ObjectPooling class), 202 cross-product queries, 36 current context (XPath), 68-69 Custom Actions Editor, 279 customizing setup and deployment projects, 278-279 Web services, 129

D data providers, 423-427 SqlCommand class, 426 SqlConnection class, 426 SqlDataAdapter class, 427 SqlDataReader class, 426 SqlParameter class, 426 DataAdapter class, 423, 427

databases adding data, 42-43 deleting data, 44-45 retrieving data, 35-42 updating data, 43-44 Windows services database, 168, 173 DataColumn class, 429 DataReader class, 426 DataRelation class, 428 DataRow class, 428-429 DataSet property (XmlDataDocument class), 66 DataSet schema, 23-24 attributes, adding, 26-27 creating from scratch, 24 with Server Explorer, 27-28 elements, adding, 25-27 relationships, 28-31 adding keys, 29 deleting keys, 29 nested relationships, 30-31 one-to-many relationships, 29-30 DataSets, 423-424, 427 adding data, 438-439 DataColumn, 429 DataRelation, 428 DataRow, 428-429 DataTable, 428 DataView, 429, 436-437 deleting data, 439-440 finding data, 433-436 members, 428 moving through, 431-432 with multiple tables, 432-433 populating, 430-431 sorting data, 436-437 strongly typed DataSets, 31-33 synchronizing with XML files, 65-68 updating data, 437-438 DataTable class, 428 DataView class, 429, 436-437 Deactivate method (ServicedComponent class), 191

How can we make this index more useful? Email us at [email protected]

472 DeactivateOnReturn property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . DeactivateOnReturn property (ContextUtil class), 195 Debug class, 237-238 Debug project configuration, 237 debugging, 247 analyzing program state, 248-249 breakpoints, setting, 248 client-side scripts, 252-253 DLL files, 252 on exceptions, 249-250 .NET Remoting objects, 254-255 remote processes, 251-252 running processes, 250-251 serviced components, 253-254 stepping through programs, 247-248 Web service projects, 128 Web services, 255 Windows services, 253 declarative programming model, 191-193 security, 295 Decrement method (PerformanceCounter class), 257 delay signing assemblies, 272 Delete method DataRow class, 429, 439-440 EventLog class, 256 DELETE statement (T-SQL), 44-45 DeleteEventSource method (EventLog class), 256 deleting DataSet data, 439-440 denying permissions, 293-294 deployment, 265-266 .NET Remoting objects, 281-282 packaging applications, 274-276, 279 private assemblies, 266-269 adding probing locations, 269 binding policy, 266-267 locating privately deployed assemblies, 267-269 serviced components, 280-281 shared assemblies, 270-274 adding assemblies to GAC, 272-273 assigning strong names, 270-271

binding policy, 273-274 delay signing, 272 Web services, 279-280 Windows services, 280 Depth property (XmlReader class), 59 Description property TraceSwitch class, 240 WebMethod attribute, 129 deserialization, 142. See also SOAP, extensions DiffGrams, 86-88 digest authentication (IIS), 300 DisableCommit method (ContextUtil class), 195 Disco, 125, 130-131 disco.exe (Web Service Discovery Tool), 130-131 discovering Web services, 125, 130-131 DisplayName property ServiceController class, 179 ServiceInstaller class, 174 TraceSwitch class, 240 DisposeObject method (ServicedComponent class), 191 distributed applications, 98 DLL files debugging, 252 registering COM DLLs, 220 DllImport attribute, 223-225 Document Object Model (DOM), 58-59 Document Type Definitions (DTDs), 79-80 DocumentElement property (XmlDocument class), 65 DocumentType property (XmlDocument class), 65 DOM (Document Object Model), 58-59 done bits, 206-207 DTDs (Document Type Definitions), 79-80

E elements, 445 DataSet schema elements, 25-27 empty elements, 445 namespaces, 447

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . FOR . . .XML . . .clause . . . naming conventions, 446 nested elements, 445 #Else directive, 242 #ElseIf directive, 242 empty XML elements, 445 EnableCommit method (ContextUtil class), 195 Enabled property (ObjectPooling class), 202 EnableRaisingEvents property (EventLog class), 256 EnableSession property (WebMethod attribute), 129 encoded parameter formatting, 155-156 #End ExternalSource directive, 242 #End If directive, 242 #End Region directive, 242 EndEdit method (DataRow class), 429 enterprise services, 201 declarative programming model, 191-193 just-in-time activation, 188, 203-205 object pooling, 188, 201-203 queued components, 188, 208-209 role-based security, 188 security, 308-309 transaction processing, 188, 205-207 entity references, 446-447 Entries property (EventLog class), 256 EntryWritten event (EventLog class), 256 EOF property (XmlReader class), 59 Evaluate method (XPathNavigator class), 72 event logs, 255-257 EventClass class, 192 EventLog class, 256-257 EventLog property (ServiceBase class), 170 EventTrackingEnabled class, 192 exams, certification, 1-2 adaptive tests, 13-15, 18 assessing readiness for, 2 case studies, 4, 13-16 fixed-length tests, 13, 15-17 PrepLogic Practice Tests, Preview Edition, 449-457

questions, 4-5 build-list-and-reorder, 6-8 case studies, 4 create-a-tree, 8-9 drag-and-connect, 10-11 hot-area questions, 12 multiple choice, 5-6 select-and-place, 11 strategies for, 19-20 resources, 20-22 short-form tests, 14-17 testing centers, 3-4 exceptions, debugging on, 249-250 ExecuteCommand method (ServiceController class), 179 ExecuteNonQuery method (SqlCommand class), 47 ExecuteXmlReader method (SqlCommand class), 85-86 Exists method (EventLog class), 256 explicit mode, FOR XML clause, 83-84 exporting .NET components as COM type libraries, 190 #ExternalSource directive, 242

F Fail method Debug class, 238 Trace class, 238 file extensions, associating, 278 File Signing (signcode.exe) tool, 272 File System Editor, 278 File Types Editor, 278 filtering DataSet data, 436-437 T-SQL query results, 41-42 finding data in DataSets, 433-436 FirstChild property (XmlNode class), 62 Flush method Debug class, 238 Trace class, 238 FOR XML clause auto mode, 82 explicit mode, 83-84

How can we make this index more useful? Email us at [email protected]

473

474 FOR XML clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . raw mode, 81 XMLDATA option, 84-85 formatters, 101-102 forms authentication, 301 Forms authentication provider, 299 fully qualified names, 36 functions callback functions, 127, 150 calling functions with PInvoke, 223-226 T-SQL aggregate functions, 40-41 XPath functions, 70 fuslogvw.exe (Binding Log Viewer), 269

G GAC (Global Assembly Cache), 270 adding assemblies, 272-273 gacutil.exe, 273 GetAttribute method (XmlReader class), 59 GetChanges method (DataSet class), 428 GetElementFromRow method (XmlDataDocument class), 66 GetEventLogs method (EventLog class), 256 GetRowFromElement method (XmlDataDocument class), 66 GetServices method (ServiceController class), 179 GetXml method (DataSet class), 428 GetXmlSchema method (DataSet class), 428 Global Assembly Cache. See GAC granting permissions, 293-294 GROUP BY clause, SELECT SQL statement, 40-41

H HasAttributes property XmlReader class, 59 XPathNavigator class, 72 HasChildNodes property (XmlNode class), 62 HasChildren property (XPathNavigator class), 72 HasValue property (XmlReader class), 59 HAVING clause, SELECT SQL statement, 41-42

HTML DOM (Document Object Model), 58-59 HTTP channel objects, 101-102

I IChannelReceiver interface, 101 IChannelSender interface, 101 identity columns, 49 @@IDENTITY variable, 49 #If directive, 242 IFormatter interface, 101 IIS (Internet Information Services) authentication, 298-300 as .NET Remoting activation agent, 112-114 ILease interface, 103 Immediate window, debugging code, 249 imperative security, 295 impersonation, 302 ImportNode method (XmlDocument class), 65 Increment method (PerformanceCounter class), 257 IncrementBy method (PerformanceCounter class), 257 Indent method Debug class, 238 Trace class, 238 IndentLevel property Debug class, 238 Trace class, 238 IndentSize property Debug class, 238 Trace class, 238 indexing XPath collections, 71 INNER JOIN clause, SELECT SQL statement, 37 InnerText property (XmlNode class), 62 InnerXml property (XmlNode class), 63 INSERT statement (T-SQL), 42-43 InsertAfter method (XmlNode class), 63 InsertBefore method (XmlNode class), 63 InsertCommand property (SqlDataAdapter class), 438-439

475 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . LogNameFromSourceName . . . . . . . . . . . . . . . method . . . . installation. See also deployment PrepLogic Practice Tests, Preview Edition, 453 SQLXML, 86 Windows service applications, 173 adding installer classes, 175 customizing installation, 175 Installer class, 173, 175 installutil.exe, 175 ServiceInstaller class, 169, 173-174 ServiceProcessInstaller class, 169, 173-174 zero-impact installations, 275 Installer class, 173, 175 installutil.exe, 175 InstanceName property (PerformanceCounter class), 257 instantiating CAOs (client-activated objects), 109-110 remote objects, 102-103 SAOs (server-activated objects), 106-108 serviced components, 198, 200-201 integration testing, 236 InterfaceQueuing attribute, 208 InterfaceQueuing class, 192 interfaces IChannelReceiver, 101 IChannelSender, 101 IFormatter, 101 ILease, 103 Internet Information Services (IIS) authentication, 298-300 as .NET Remoting activation agent, 112-114 IsCallerInRole method (ContextUtil class), 195 IsEmptyElement property XmlReader class, 59 XPathNavigator class, 72 IsEnabled property (TraceContext class), 243 IsInTransaction property (ContextUtil class), 195 IsNull method (DataRow class), 429

IsSecurityEnabled property (ContextUtil class), 195 IsStartElement method (XmlReader class), 59 Item property DataRow class, 429 XmlReader class, 59

J-K JIT (just-in-time) activation, 188, 203-205 JustInTimeActivation class, 192, 204 keys adding to DataSet schema, 29 deleting from DataSet schema, 29 key pairs, 270-271

L last function (XPath), 70 LastChild property (XmlNode class), 63 Launch Conditions Editor, 279 lazy registration, 280 Level property (TraceSwitch class), 240 library applications, running COM+ applications as, 193 lifetime leases, 103-104 listeners, 238-239 Listeners property Debug class, 238 Trace class, 238 literal parameter formatting, 153-155 Load method XmlDataDocument class, 66 XmlDocument class, 65 LoadXml method (XmlDocument class), 65 Locals window, debugging code, 249 Log property (EventLog class), 256 LogDisplayName property (EventLog class), 256 LogNameFromSourceName method (EventLog class), 256

How can we make this index more useful? Email us at [email protected]

476 logs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . logs application logs, 256 Assembly Binding Log Viewer, 269 event logs, 255-257

M MachineName property EventLog class, 256 PerformanceCounter class, 257 ServiceController class, 179 managed code, 219 MarshalByRefObject class, 100 Matches method (XPathNavigator class), 72 MAX() function, T-SQL, 41 MaxPoolSize property (ObjectPooling class), 202-203 MBR (marshal-by-reference) objects, 100 CAOs, 103 creating, 108-110 instantiating, 109-110 SAOs, 102 activation modes, 102-103 creating, 105-108 MBV (marshal-by-value) objects, 100 remote object activation, 102 Me window, debugging code, 249 Merge method (DataSet class), 428 merge modules, 282 Merge Module Project template, 276 MessageName property (WebMethod attribute), 129 methods asynchronous Web methods, creating, 149-151 callback functions, 127, 150 WaitHandle object, 150-151 channel objects, 101 marking as conditional, 242 translating in XML, 124 Microsoft certification exams, 1-2 adaptive tests, 13-15, 18 assessing readiness for, 2 case studies, 4, 13, 15-16 fixed-length tests, 13, 15-17

PrepLogic Practice Tests, Preview Edition, 449-457 questions, 4-5 build-list-and-reorder, 6-8 case studies, 4 create-a-tree, 8-9 drag-and-connect, 10-11 hot-area questions, 12 multiple-choice, 5-6 select-and-place, 11 strategies for, 19-20 resources, 20-22 short-form tests, 14-17 testing centers, 3-4 Microsoft Message Queuing (MSMQ), 208 Microsoft SQL Server. See SQL Server Microsoft Windows Installer, 275-276 MIN() function, T-SQL, 41 MinPoolSize property (ObjectPooling class), 202-203 MoveToElement method (XmlReader class), 60 MoveToFirst method (XPathNavigator class), 72 MoveToFirstAttribute method XPathNavigator class, 73 XmlReader class, 60 MoveToFirstChild method (XPathNavigator class), 73 MoveToNext method (XPathNavigator class), 73 MoveToNextAttribute method XPathNavigator class, 73 XmlReader class, 60 MoveToParent method, 73 MoveToPrevious method (XPathNavigator class), 73 MoveToRoot method (XPathNavigator class), 73 MSMQ (Microsoft Message Queuing), 208 MustRunInClientContext class, 192 MyTransactionVote property (ContextUtil class), 195

477 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .ObjectPooling . . . . . . . class . . .

N Name property XmlNode class, 63 XmlReader class, 60 XPathNavigator class, 73 Namespace property (WebService attribute), 128 namespaces for distributed applications, 98 System.Data, 427-429, 436-437 System.Data.Common, 425 System.Data.OleDb, 425 System.Data.SqlClient, 425-427 System.Diagnostics, 238-239 System.EnterpriseService, 192-193, 195 System.MarshalByRefObject, 100 System.Net, 98 System.Runtime.InteropService, 189190 System.Runtime.Remoting, 98 System.Runtime.Remoting.Lifetime, 103 System.Web.Services, 98 System.Xml, 62-68, 78-80 System.Xml.XPath, 71-75 XML namespaces, 447 nested relationships, 30-31 XML elements, 445 .NET components assembly-registration process, 189-190 exporting as COM type libraries, 190 .NET Remoting, 97-98 application domain communication, 98-99 CAOs (client-activated objects) creating, 108-110 instantiating, 109-110 channels, 101-102 configuring remoting framework, 110-112 debugging remoting objects, 254-255 deploying remoting objects, 281-282 formatters, 101-102

IIS as activation agent, 112-114 lifetime leases, 103-104 MBR (marshal-by-reference) objects, 100 MBV (marshal-by-value) objects, 100 remotable classes, creating, 104-105 remote object activation, 102 SAOs (server-activated objects) activation modes, 102-103 creating, 105-108 security, 307-308 net.exe, 177-178 NextSample method (PerformanceCounter class), 257 NextSibling property (XmlNode class), 63 NextValue method (PerformanceCounter class), 258 NodeChanged event (XmlDocument class), 65 NodeChanging event (XmlDocument class), 65 NodeInserted event (XmlDocument class), 65 NodeInserting event (XmlDocument class), 65 NodeRemoved event (XmlDocument class), 65 NodeRemoving event (XmlDocument class), 65 NodeType property XmlNode class, 63 XmlReader class, 60 normalize-space function (XPath), 70 not function (XPath), 70 NT services. See Windows services number function (XPath), 70

O object marshalling MBR (marshal-by-reference) objects, 100-103, 105-110 MBV (marshal-by-value) objects, 100-102 object pooling (COM+), 188, 201-203 ObjectPooling class, 192, 201-202

How can we make this index more useful? Email us at [email protected]

478 objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . objects activating remote objects, 102-103 deploying .NET Remoting objects, 281-282 CAOs (client-activated objects), 103, 108-110 DOM (Document Object Model), 58-59 HTML DOM (Document Object Model), 58-59 HTTP channel objects, 101-102 proxy objects, 98-99, 131-132 SAOs (server-activated objects), 102-103, 105 translating objects in XML, 124 OnContinue method (ServiceBase class), 170-171 one-to-many relationships, 29-30 OnPause method (ServiceBase class), 170-171 OnStart method (ServiceBase class), 170 OnStop method (ServiceBase class), 170-171 opening tags, XML, 445 ORDER BY clause, SELECT SQL statement, 39-40 OuterXml property (XmlNode class), 63 OwnerDocument property (XmlNode class), 63

P packaging applications, 274-276, 279 Parameter class, 426 parameterized stored procedures, 47-48 ParentNode property (XmlNode class), 63 Passport authentication provider, 299 Passport authentication service, 300-301 Passport Software Development Kit, 300 Password property (ServiceProcessInstaller class), 174 Pause method (ServiceController class), 179 pausing Windows services, 169 percent (%) wild card, 38 perfmon.exe, 258 Performance Counter Builder Wizard, 258 performance counters, 257-258

Performance Monitoring (perfmon.exe) tool, 258 PerformanceCounter class, 257-258 permissions, 290-292 code groups, 292-293 computing, 295-297 granting/denying, 293-294 imperative security, 295 permission sets, 293 requesting, 292, 297 PIAs (Primary Interop Assemblies), 222 PIs (processing instructions), 444 Platform Invoke (PInvoke), 223-226 Pooling Manager, 202-203 position function (XPath), 70 PrependChild method (XmlNode class), 63 PrepLogic Practice Tests, Preview Edition, 449-457 contacting PrepLogic, 457 Flash Review mode, 455 installation, 453 license agreement, 457 obtaining additional exams, 456 option buttons, 455 Practice Test mode, 454 removing, 453 reviewing exams, 456 score reports, 456 software requirements, 452 time remaining, 456 preprocessing directives, 241-242 PreserveWhitespace property (XmlDocument class), 65 PreviousSibling property (XmlNode class), 63 Primary Interop Assemblies (PIAs), 222 primary keys, 29 private assemblies, deploying, 266-269 adding probing locations, 269 binding policy, 266-267 locating privately deployed assemblies, 267-269 private UDDI registries, 130 PrivateComponent class, 192

479 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .ReplaceChild . . . . . . . method . . . . processing instructions (PIs), 444 programmatic configuration, 110 properties. See also specific properties translating in XML, 124 proxy objects creating with wsdl.exe, 131-132 .NET Remoting and, 98-99 public UDDI registries, 130 publisher policy, 273

Q queries ad hoc T-SQL queries, 34 cross-product queries, 36 DELETE statement, 44-45 INSERT statement, 42-43 running, 34-35 SELECT statement, 35-42 UPDATE statement, 43-44 stored procedures, 45 creating, 45-46 executing from .NET, 46-47 parameterized procedures, 47-48 queued components, 188, 208-209

R raw mode, FOR XML clause, 81 RawValue property (PerformanceCounter class), 258 RCWs (runtime callable wrappers), 219-222 Read method (XmlReader class), 60 ReadOnly property (PerformanceCounter class), 258 ReadXml method (DataSet class), 428 ReadXmlSchema method (DataSet class), 428 Recordsets, 431 Refresh method (ServiceController class), 179 regasm.exe (Assembly Registration) tool assembly-registration process, 189 exporting .NET components as COM libraries, 190

#Region directive, 242 registering COM DLLs, 220 remotable classes as SAOs SingleCall Activation mode, 105-106 SingleTon activation mode, 108 serviced components, 280-281 RegistrationHelper class, 280-281 RegistrationServices class, 189 Registry Editor, 278 regsvcs.exe (Component Services tool), 280-281 Relations property (DataSet class), 428 Release project configuration, 237 remote processes, debugging, 251-252 Remoting (.NET), 97-98 application domain communication, 98-99 channels, 101-102 CAOs (client-activated objects) creating, 108-110 instantiating, 109-110 configuring remoting framework, 110-112 debugging .NET Remoting objects, 254-255 deploying .NET Remoting objects, 281-282 formatters, 101-102 IIS as activation agent, 112-114 lifetime leases, 103-104 MBR (marshal-by-reference) objects, 100 MBV (marshal-by-value) objects, 100 remotable classes, creating, 104-105 remote object activation, 102 security, 307-308 SAOs (server-activated objects) activation modes, 102-103 creating, 105-108 RemoveAll method (XmlNode class), 63 RemoveChild method (XmlNode class), 63 RemoveInstance method (PerformanceCounter class), 258 ReplaceChild method (XmlNode class), 63

How can we make this index more useful? Email us at [email protected]

480 repression testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . repression testing, 236 role-based security, 188, 290 authentication, 297-301 authorization, 301 impersonation, 302 rows deleting, 44-45 inserting, 42-43 updating, 43-44 RowState property (DataRow class), 429 RPC-style body formatting, 156-157 Run method (ServiceBase class), 170 runtime callable wrappers (RCWs), 219-222

S SAOs (server-activated objects), 102-103 activation modes, 102-103 creating, 105 Save method (XmlDocument class), 65 sc.exe (Service Control utility), 178 schema DataSet schema, 23-24 attributes, adding, 26-27 creating from scratch, 24 creating with Server Explorer, 27-28 elements, adding, 25-27 keys, adding, 29 nested relationships, 30-31 one-to-many relationships, 29-30 XSD schema creating, 76-78 validating XML files, 78-80 SCM (Service Control Manager), 168-171 SecureMethod attribute, 309 security, 290 authentication, 297-298 ASP.NET authentication, 298-299 forms authentication, 301 IIS authentication, 298-300 no authentication, 298 passport authentication, 300-301 providers, 299 authorization, 301

code access security, 290-292 code groups, 292-293 computing permissions, 295-297 granting/denying permissions, 293294 imperative security, 295 permission sets, 293 requesting permissions, 292, 297 impersonation, 302 .NET Remoting, 307-308 serviced components, 308-309 Web services, 304-306 Windows services, 302-303 Security logs, 256 SecurityRole attribute, 308-309 Select method DataTable class, 433-436 XPathNavigator class, 73 SELECT statement (T-SQL), 35-42 FOR XML clause, 81-85 GROUP BY clause, 40-41 HAVING clause, 41-42 INNER JOIN clause, 37 ORDER BY clause, 39-40 querying multiple tables, 36-37 required clauses, 36 WHERE clause, 37-39 SelectNodes method XmlDocument object, 71 XmlNode class, 63 SelectSingleNode method (XmlNode class), 63 Self-Assessment, 2 Serializable attribute, MBV objects, 100 serialization, 142. See also SOAP, extensions server applications, running COM+ applications as, 193 Server Explorer DataSet schema, creating, 27-28 Windows services, controlling, 177 server-activated objects (SAOs), 102-103 activation modes, 102-103 creating, 105 Service Control (sc.exe) utility, 178

481 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SQL . . Server . . . . Service Control Manager (SCM), 168-171 ServiceBase class, 169-170 ServiceController class, 169, 178-180 serviced components, 191 activating, 194-195 COM+ applications, 193 COM+ catalogs, 194 consuming, 198, 200-201 context, 194-195 creating, 196-199 debugging, 253-254 declarative programming model, 191193 deploying, 280-281 queued components, 188, 208-209 registering with COM+ catalog, 280-281 runtime requirements, 194 security, 308-309 ServicedComponent class, 191 ServiceInstaller class, 169 properties, 173-174 ServiceName property ServiceBase class, 170 ServiceController class, 179 ServiceInstaller class, 174 ServiceProcessInstaller class, 169 properties, 173-174 Services MMC snap-in, 176-177 ServicesDependedOn property ServiceController class, 179 ServiceInstaller class, 174 ServiceType property (ServiceController class), 179 session state, using in Web services, 129 SET clause, UPDATE SQL statement, 43 SetAbort method (ContextUtil class), 195 SetComplete method (ContextUtil class), 195 setup and deployment projects. See also deployment Cab Project template, 276 customizing, 278-279 Merge Module Project template, 276 Setup Project template, 276-278 Web Setup Project template, 276

Setup Project template, 276-278 shared assemblies, deploying, 270-274 adding assemblies to GAC, 272-273 assigning strong names, 270-271 binding policy, 273-274 delay signing, 272 short-form certification exams, 14-17 signcode.exe (File Signing tool), 272 signing assemblies, 190 Simple Object Access Protocol. See SOAP SingleCall activation mode, 102 registering remotable classes, 105-106 Singleton activation mode, 103 registering remotable classes, 108 Skip method (XmlReader class), 60 sn.exe (Strong Name) tool, 190, 270-272 SOAP (Simple Object Access Protocol), 98, 101, 124 authentication, 304-305 extensions, 142-143 creating, 143-148 examples of use, 143 priority, 142 required tasks, 143-144 testing, 148-149 formatting messages, 152-153 bare parameter formatting, 158 encoded parameter formatting, 155-156 literal parameter formatting, 153-155 RPC-style body formatting, 156-157 wrapped parameter formatting, 158 XmlElement attribute, 159 SoapDisplayExtension class, 148 SoapFormatter class, 101 sorting DataSet data, 436-437 Source property (EventLog class), 256 SourceExists method (EventLog class), 256 SQL Server ad hoc queries, 34 cross-product queries, 36 DELETE statement, 44-45 INSERT statement, 42-43 running, 34-35

How can we make this index more useful? Email us at [email protected]

482 SQL Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SELECT statement, 35-42 UPDATE statement, 43-44 data providers, 425 SqlCommand class, 426 SqlConnection class, 426 SqlDataAdapter class, 427 SqlDataReader class, 426 SqlParameter class, 426 generating XML with, 81-86 stored procedures, 45 creating, 45-46 executing from .NET, 46-47 @@IDENTITY variable, 49 parameterized stored procedures, 47-48 updating data with DiffGrams, 86-88 SqlCommand class, 426 ExecuteNonQuery method, 47 ExecuteXmlReader method, 85-86 SqlConnection class, 426 SqlDataAdapter class, 427 SqlDataReader class, 426 SqlParameter class, 48, 426 SQLXML, installation, 86 stack walks, 296 Start method (ServiceController class), 179 starting Windows services, 169-171 starts-with function (XPath), 70 StartType property (ServiceInstaller class), 174 static discovery, 130 Status property (ServiceController class), 179 stepping through programs, 247-248 Stop method (ServiceController class), 180 stopping Windows services, 169 stored procedures, 45 creating, 45-46 executing from .NET, 46-47 @@IDENTITY variable, 49 parameterized stored procedures, 47-48 string-length function (XPath), 70 Strong Name (sn.exe) tool, 190, 270-272 strong names, assigning to assemblies, 270-272

strongly typed DataSets, 31-33 creating, 31-32 using, 33 StructLayout attribute, 225-226 substring function (XPath), 70 SUM() function, T-SQL, 40 Synchronization class, 193 System logs, 256 System.Data namespace, 427 DataColumn class, 429 DataRelation class, 428 DataRow class, 428-429 DataSet class, 427-428. See also DataSets DataTable class, 428 DataView class, 429, 436-437 System.Data.Common namespace, 425 System.Data.OleDb namespace, 425 System.Data.SqlClient namespace, 425 SqlCommand class, 426 SqlConnection class, 426 SqlDataAdapter class, 427 SqlDataReader class, 426 SqlParameter class, 426 System.Diagnostics namespace, 238-239 System.EnterpriseServices namespace attributes, 192-193 ContextUtil class, 195 ServicedComponent class, 191 System.MarshalByRefObject namespace, 100 System.Net namespace, 98 System.Runtime.InteropService namespace RegistrationServices class, 189 TypeLibConverter class, 190 System.Runtime.Remoting namespace, 98 System.Runtime.Remoting.Lifetime namespace, 103 System.Web.Services namespace, 98 System.Xml namespace XmlDataDocument class, 65-68 XmlDocument class, 63-65 XmlNode class, 62-63 XmlReader class, 59-62 XmlValidatingReader class, 78-80 System.Xml.XPath namespace, 71-75

483 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . unmanaged . . . . . . code . . .

T T-SQL, 33 ad hoc queries, 34 cross-product queries, 36 running, 34-35 aggregate functions, 40-41 CREATE PROCEDURE statement, 45-46 DELETE statement, 44-45 INSERT statement, 42-43 SELECT statement, 35-42 FOR XML clause, 81-85 GROUP BY clause, 40-41 HAVING clause, 41-42 INNER JOIN clause, 37 ORDER BY clause, 39-40 querying multiple tables, 36-37 required clauses, 36 WHERE clause, 37-39 stored procedures, 45 creating, 45-46 executing from .NET, 46-47 @@IDENTITY variable, 49 parameterized procedures, 47-48 UPDATE statement, 43-44 tables identity columns, 49 rows deleting, 44-45 inserting, 42-43 updating, 43-44 Tables property (DataSet class), 428 tags, XML, 445 TCP (Transmission Control Protocol), channel objects, 101-102 testing applications, 236 SOAP extensions, 148-149 testing centers, 3-4 tlbexp.exe (Type Library Exporter), 190 tlbimp.exe (Type Library Importer), 220-222 Trace class, 237-238

TraceContext class, 242-243 element, Web.config file, 245-246 TraceError property (TraceSwitch class), 240 TraceInfo property (TraceSwitch class), 240 TraceListener class, 238-239 TraceMode property (TraceContext class), 243 TraceSwitch class, 239-241 TraceVerbose property (TraceSwitch class), 240 TraceWarning property (TraceSwitch class), 240 tracing ASP.NET tracing, 242-246 Debug class, 237-238 preprocessing directives, 241-242 Trace class, 237-238 trace listeners, 238-239 trace switches, 239-241 Transact-SQL. See T-SQL Transaction class, 193 transaction processing, 188, 205-207 Transaction property (ContextUtil class), 195 TransactionOption property (WebMethod attribute), 129 translating objects in XML, 124 type libraries, 220-222 Type Library Exporter (tlbexp.exe), 190 Type Library Importer (tlbimp.exe), 220-222

U-V UDDI (Universal Description, Discovery, and Integration), 125, 130 Unindent method Debug class, 238 Trace class, 238 unique keys, 29 unit testing, 236 unmanaged code, 217-226 COM components, 218 direct references, 222 registering COM DLLs, 220

How can we make this index more useful? Email us at [email protected]

484 unmanaged code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . runtime callable wrappers, 219 Type Library Importer tool, 220-222 Platform Invoke (PInvoke), 223-226 Update method (SqlDataAdapter class), 437-438 UPDATE statement (T-SQL), 43-44 URL authorization, 305 User Interface Editor, 278-279 user interfaces, customizing, 278-279 Username property (ServiceProcessInstaller class), 174 validating XML files, 78-80 Value property XmlReader class, 60 XPathNavigator class, 73

W W3C (World Wide Web Consortium), 58 WaitForStatus method (ServiceController class), 180 WaitHandle class, 150-151 Warn method (TraceContext class), 243 Watch window, debugging code, 249 Web methods, asynchronous calls, 149-151 callback functions, 127, 150 WaitHandle object, 150-151 Web references, 132-133 Web Service Discovery Tool (disco.exe), 130-131 Web services, 123-124 asynchronous calls, 126-127, 149-151 callback functions, 127, 150 WaitHandle object, 150-151 creating, 127-128 customizing, 129 debugging, 255 deploying, 279-280 discovering, 125, 130-131 invoking, 125-126 protocols, 124. See also specific protocols Disco, 125, 130 SOAP, 124 UDDI, 125, 130 WSDL, 125, 131-132

security, 304-306 session state use in, 129 SOAP extensions, 142-143 creating, 143-148 testing, 148-149 testing projects, 128 Web references, 132-133 XML wire format, 152-153 bare parameter formatting, 158 encoded parameter formatting, 155-156 literal parameter formatting, 153-155 RPC-style body formatting, 156-157 wrapped parameter formatting, 158 XmlElement attribute, 159 Web Services Description Language Tool (wsdl.exe), 131-132 Web Services Description Language (WSDL), 125 Web Setup Project template, 276 Web.config file tag, 305 tag, 112 tag, 245-246 WebMethod attribute, 129 well-formed XML documents, 443 WHERE clause (SQL) DELETE statement, 44 SELECT statement, 37-39 UPDATE statement, 43-44 Windows API, calling unmanaged functions, 223-226 Windows authentication provider, 299 Windows Installer, 275-276 Windows integrated authentication (IIS), 300 Windows services, 167-168 architecture, 168-169 controlling Windows service applications using net.exe, 177-178 using Server Explorer window, 177 using Service Control utility, 178 using ServiceController class, 178-180 using Services MMC snap-in, 176-177

485 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . XmlNode . . . . . class . . . creating Window service applications, 169-173 database, 168, 173 debugging, 253 deploying, 280 installing applications, 173 adding installer classes, 175 customizing installation, 175 Installer class, 173, 175 installutil.exe, 175 ServiceInstaller class, 169, 173-174 ServiceProcessInstaller class, 169, 173-174 .NET Framework support for, 169 pausing, 169 security, 302-303 starting, 169-171 stopping, 169 World Wide Web Consortium (W3C), 58 wrapped parameters, 158 Write method Debug class, 238 Trace class, 238 TraceContext class, 243 WriteContentTo method (XmlNode class), 63 WriteEntry method (EventLog class), 256 WriteIf method Debug class, 238 Trace class, 238 WriteLine method Debug class, 238 Trace class, 238 WriteLineIf method Debug class, 238 Trace class, 238 WriteTo method XmlDocument class, 65 XmlNode class, 63 WriteXml method (DataSet class), 428 WriteXmlSchema method (DataSet class), 428 WSDL (Web Services Description Language), 125 wsdl.exe, 131-132

X-Z XCOPY command, 275 XML, 443 accessing XML files, 58 DOM (Document Object Model), 58-59 XmlDocument class, 63-65 XmlNode class, 62-63 XmlReader class, 59-62 XPathNavigator class, 71-75 DiffGrams, 86-88 generating with SQL Server, 81-86 processing instructions (PIs), 444 synchronizing DataSets, 65-68 syntax, 443-447 attributes, 445-446 comments, 444 declarations, 444 elements, 445 namespaces, 447 naming conventions, 446 special characters, 446-447 tags, 445 translating objects into, 124 validating XML files, 78-80 Web services. See Web services well-formed XML documents, 443 wire format, controlling, 152-159 bare parameter formatting, 158 encoded parameter formatting, 155-156 literal parameter formatting, 153-155 RPC-style body formatting, 156-157 wrapped parameter formatting, 158 XmlElement attribute, 159 XPath queries. See XPath XSD schemas creating programmatically, 76-78 validating XML files, 78-80 XmlDataDocument class, 65-68 XmlDocument class, 63-65 XmlElement attribute, 159 XmlNode class, 62-63

How can we make this index more useful? Email us at [email protected]

486 XmlReader class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . XmlReader class, 59-62 XmlValidatingReader class, 78-80 XPath, 68-71 current context, 68-69 filtering capability, 69-70 indexing collections, 71 XPathDocument class, 72 XPathNavigator class, 71-75 navigating nodes, 74-75 selecting nodes, 72-73 XPathNodeIterator class, 73 XSD schemas creating, 76-78 validating XML files, 78-80 zero-impact installations, 275