Need to Know More? - Shaheen Education Family
Transcription
Need to Know More? - Shaheen Education Family
Developing and Implementing WindowsBased Applications with Visual C# .NET and Visual Studio .NET Kalani Kirk Hausman Amit Kalani Priti Kalani Developing and Implementing Windows-Based Applications with Visual C# .NET and Visual Studio .NET Exam Cram 2 (Exam 70-316) Publisher Paul Boger Copyright 2003 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-2902-4 Library of Congress Catalog Card Number: 2003100978 Printed in the United States of America Executive Editor Jeff Riley Development Editor Ginny Bess Munroe Managing Editor Charlotte Clapp Project Editor Tricia Liebig First Printing: May 2003 05 04 03 02 4 3 2 1 Indexer Mandie Frank 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. Windows is a registered trademark of Microsoft Corporation. Visual C# and Visual Studio are registered trademarks of Microsoft Corporation 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. Proofreader Juli Cook Team Coordinator Pamalee Nelson Technical Editors Steve Heckler Greg Guntle Multimedia Developer Dan Scherf Page Layout Michelle Mitchell 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!! Developing and Implementing Windows-based Applications with Visual C# .NET and Visual Studio .NET Training Guide (Exam 70-316) Amit Kalani ISBN 0-7897-2823-0 $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 Contents at a Glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introduction xxiii Self-Assessment xxxiii Chapter 1 Introducing Windows Forms 1 Chapter 2 Controls on Forms Chapter 3 Handling Exceptions Chapter 4 Components and .NET Assemblies Chapter 5 Data Binding Chapter 6 Consuming and Manipulating Data Chapter 7 Web Services Chapter 8 Globalization Chapter 9 Working with Legacy Code 33 71 93 119 141 173 191 213 Chapter 10 User Assistance and Accessibility 233 Chapter 11 Printing Chapter 12 Testing and Debugging Chapter 13 Deploying a Windows Application Chapter 14 Maintaining and Supporting a Windows Application 307 Chapter 15 Configuring a Windows Application Chapter 16 Sample Test #1 Chapter 17 Answer Key for Sample Test #1 251 269 287 347 387 325 Chapter 18 Sample Test #2 401 Chapter 19 Answer Key for Sample Test #2 437 Appendix A: Microsoft Certification Exams Appendix B: What’s on the CD Appendix C: Using the PrepLogic Practice Tests, Preview Edition Software 475 Glossary Index 483 497 451 471 Table of Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introduction ...................................................................xxiii Self-Assessment ............................................................xxxiii Chapter 1 Introducing Windows Forms ...................................................1 Introduction to the .NET Framework and Visual Studio .NET 2 Objects and Classes 2 Class Inheritance 3 Namespace 4 Using the Windows Forms Designer 5 Creating a Blank Form 6 Modifying a Form’s Properties 6 Displaying a Form 6 Exploring Code View 7 Compiling the Form 8 Using Classes 9 The Application Class 9 The Form Class 10 Custom Properties 11 Visual Inheritance 13 Event Handling 13 Attaching a Delegate 14 Overriding a Protected Method of the Base Class 16 Building Graphical Interface Elements by Using the System.Drawing Namespace 17 Understanding the Graphics Object 18 The System.Drawing Namespace 18 Drawing Text on a Form 19 Drawing Shapes Using the Draw Method 21 Creating Filled Shapes Using the Fill Method 23 Practice Questions 25 Need to Know More? 31 viii Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Chapter 2 Controls on Forms .............................................................33 Common Properties of Controls 34 Anchor 35 Dock 35 Enabled 35 Font 36 Location 37 Name 37 Size, Height, and Width 37 TabIndex and TabStop 37 Text 37 Visible 38 Common Windows Forms Controls 38 GroupBox and Panel 38 Label and LinkLabel 40 TextBox and RichTextBox 41 PictureBox 43 Button, RadioButton, and CheckBox 43 ListBox and CheckedListBox 44 ComboBox 46 DomainUpDown and NumericUpDown 47 MonthCalendar and DateTimePicker 49 TreeView and ListView 50 Timer, TrackBar, and ProgressBar 53 HScrollBar and VScrollBar 54 TabControl 55 ToolTip 56 Dialog Boxes 56 Common Dialog Boxes 56 Modal and Modeless Dialog Boxes 57 Menus 57 Creating Menus and Menu Items 57 StatusBar 58 ToolBar 59 Single- and Multiple-Document Interface Applications 60 Adding Controls to Forms 61 Adding Controls with the Windows Forms Designer 61 Adding Controls Programmatically 63 Practice Questions 65 Need to Know More? 70 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Contents . . . . . Chapter 3 Handling Exceptions ..........................................................71 Understanding Exceptions 72 Handling Exceptions 73 try Block 73 catch Blocks 74 finally Block 76 The throw Statement 77 Creating Custom Exceptions 78 Managing Unhandled Exceptions 79 Validating User Input 80 Control-Based Validation 80 Control-Access Restriction 81 Keystroke-Level Validation 81 Field-Level Validation 82 Practice Questions 86 Need to Know More? 92 Chapter 4 Components and .NET Assemblies .........................................93 Creating .NET Components 94 Creating Components Derived from the Component Class 95 Creating Components Derived from the Control Class 98 Components Derived from the UserControl Class 99 Creating .NET Assemblies 105 Single-File and Multifile Assemblies 107 Static and Dynamic Assemblies 107 Private and Shared Assemblies 107 Satellite and Resource-Only Assemblies 109 Practice Questions 111 Need to Know More? 117 Chapter 5 Data Binding ..................................................................119 Binding Data to the User Interface 120 Simple Data Binding 120 Complex Data Binding 124 One-Way and Two-Way Data Binding The Data Form Wizard 129 129 ix x Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Transforming and Filtering Data 129 The Server Explorer 130 Filtering and Transforming Data 131 Practice Questions 133 Need to Know More? 139 Chapter 6 Consuming and Manipulating Data .......................................141 Transact-SQL 142 The SELECT Statement 142 The INSERT Statement 145 The UPDATE Statement 145 The DELETE Statement 146 Querying SQL Server 146 Ad-Hoc Queries 146 Stored Procedures 148 Data Access 150 Disk Files 150 The ADO.NET Object Model 153 XML Data 162 Handling Database Errors 165 Practice Questions 167 Need to Know More? 172 Chapter 7 Web Services .................................................................173 Understanding Web Services 174 Simple Object Access Protocol (SOAP) 174 Disco and Universal Description, Discovery, and Integration (UDDI) 175 Web Services Description Language (WSDL) 175 Using Web Services 176 Adding a Web Reference 176 The Web Services Discovery Tool (disco.exe) 178 The Web Services Description Language Tool (wsdl.exe) 178 Creating Web Services 180 Testing the New Web Service 181 Practice Questions 183 Need to Know More? 189 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Contents . . . . . Chapter 8 Globalization ..................................................................191 Introduction to Localization 192 The Localization Process 192 Localization Considerations 193 User Interface Localization 193 Cultures 194 Resource Files 198 Character Encodings 201 Unicode 201 Converting Encodings 201 User Interface Mirroring 202 Mirroring in .NET 203 Managing User Input 203 String Indexing 203 Comparing and Sorting Data 205 Practice Questions 206 Need to Know More? 212 Chapter 9 Working with Legacy Code ................................................213 Using ActiveX Controls 214 The Windows Forms ActiveX Control Importer (aximp.exe) 215 Importing Controls Using the Visual Studio .NET Toolbox 217 Using ActiveX Controls 219 Using COM Components 219 Runtime Callable Wrappers 219 The Type Library Importer Tool (tlbimp.exe) 220 Using COM Components Directly 222 Using COM+ Components 222 Using Platform Invoke 223 Practice Questions 225 Need to Know More? 231 Chapter 10 User Assistance and Accessibility ........................................233 HTML Help 234 Inside HTML Help 1.3 235 Creating a Help Project 236 Creating Topic Files 236 xi xii Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Linking Topic Files 237 Creating a Table of Contents 237 Creating an Index 238 Compiling and Testing an HTML Help File Implementing User Assistance 239 The Help Class 240 The HelpProvider Component 240 Pop-Up Help 241 The ToopTip Component 241 Accessibility 242 Control Properties for Accessibility 243 Supporting High Contrast Mode 244 Practice Questions 245 Need to Know More? 250 239 Chapter 11 Printing ........................................................................251 The PrintDocument Component 252 Printing Text 253 The PrintPageEventArgs Class 255 Printing Graphics 256 Using the Printing Controls 257 The PageSetupDialog Component 258 The PrintPreviewDialog Component 259 The PrintPreviewControl Control 260 The PrintDialog Component 261 Practice Questions 263 Need to Know More? 268 Chapter 12 Testing and Debugging ......................................................269 Application Testing 270 Unit Testing 271 Integration Testing 271 Regression Testing 272 Tracing 272 Trace Listeners 273 Trace Switches 274 Conditional Compilation 275 Debugging 276 Stepping Through Code During Execution Using Breakpoints 277 Debugging When an Exception Is Thrown 276 278 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Contents . . . . . Debugging a Running Process 278 Analyzing Program State 279 Practice Questions 281 Need to Know More? 286 Chapter 13 Deploying a Windows Application ........................................287 Deployment Tools 288 Deploying Your Application 288 Setup Projects 289 Customizing Setup Projects 292 Shared Assemblies 293 Signing the Assembly 294 Adding an Assembly to the GAC 295 Creating and Deploying the Installation Components URL Remoting 297 Deployment Considerations 298 Windows Logo Program Requirements 299 Practice Questions 300 Need to Know More? 305 296 Chapter 14 Maintaining and Supporting a Windows Application ...................307 Introduction 308 The Process Class 308 Starting and Stopping Processes 308 Getting Process Information 312 Windows Event Logs 313 Accessing Event Logs 314 Monitoring Performance 315 Reading Performance Data 315 Publishing Performance Data 316 Practice Questions 318 Need to Know More? 324 Chapter 15 Configuring a Windows Application .......................................325 Dynamic Application Configuration 326 Using Dynamic Properties 326 Using the .NET Framework Configuration Tool Configuring Security 329 Permissions 330 Requesting Minimum Permissions 332 328 xiii xiv Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Code Groups 333 Permission Sets 334 Granting Permissions 334 Computing Final Permissions 336 Configuring Authorization 337 Identity and Principal Objects 337 The PrincipalPermission Class 339 Practice Questions 340 Need to Know More? 345 Chapter 16 Sample Test #1 ...............................................................347 How to Take the Sample Exams Exam-Taking Tips 348 Sample Exam 1 350 348 Chapter 17 Answer Key for Sample Test #1 ............................................387 Answer Key 388 Detailed Answers 388 Chapter 18 Sample Test #2 ...............................................................401 Practice Test 402 Chapter 19 Answer Key for Sample Test #2 ............................................437 Answer Key 438 Detailed Answers 438 Appendix A Microsoft Certification Exams ..............................................451 Assessing Exam-Readiness 451 What to Expect at the Testing Center 452 Exam Layout and Design: New Case Study Format 453 Multiple-Choice Question Format 454 Build-List-and-Reorder Question Format 455 Create-a-Tree Question Format 457 Drag-and-Connect Question Format 458 Select-and-Place Question Format 460 Microsoft’s Testing Formats 461 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Contents . . . . . Strategies for Different Testing Formats 463 Case Study Exam Strategy 463 Fixed-Length and Short-Form Exam Strategy Adaptive Exam Strategy 465 Question-Handling Strategies 466 Mastering the Inner Game 467 464 Appendix B What’s on the CD-ROM ......................................................471 PrepLogic Practice Tests, Preview Edition 472 Exclusive Electronic Version of Text 472 Easy Access to Online Pointers and References 473 Appendix C Using the PrepLogic Practice Tests, Preview Edition Software ...................................................475 Exam Simulation 476 Question Quality 476 Interface Design 476 Effective Learning Environment 476 Software Requirements 477 Installing PrepLogic Practice Tests, Preview Edition 477 Removing PrepLogic Practice Tests, Preview Edition from Your Computer 477 Using PrepLogic Practice Tests, Preview Edition 478 Starting a Practice Test Mode Session 478 Starting a Flash Review Mode Session 479 Standard PrepLogic Practice Tests, Preview Edition Options 479 Time Remaining 480 Your Examination Score Report 480 Review Your Exam 481 Get More Exams 481 Contacting PrepLogic 481 Customer Service 481 Product Suggestions and Comments 481 License Agreement 482 Glossary .......................................................................483 Index ............................................................................497 xv About the Authors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Kalani Kirk Hausman (MCSE+I, MCSD, MCDBA, MCSA, MCT, CCNA, CIW-A, Security+, A+, Network+, I-Net+) has been an IT professional for more than 25 years in the roles of director, consultant, trainer, programmer, security administrator, database administrator, manager, and network administrator. He is currently working as a Lead Security Analyst and Computer Systems Manager for Texas A&M University. Mr. Hausman’s studies include security, computer science, electronics technology, electrical engineering, mechanical engineering, and philosophy. His hobbies include designs in high-speed transportation, submersible propulsion, cosmology, interactive telepresence, technology in education, and virtual reality for use by those with disabling conditions. His current independent projects include development of a shared interactive telepresence system designed to allow remote experience of widely varying environments by students regardless of geographic location or disabling condition. He is also working on implementing a zoological wireless telepresence system that is capable of allowing remote observation of animals in both natural and human-created environments and is involved with grants relating to the leveraging of emerging technologies towards the development of improved bilingual distance education programs, along with many other ongoing projects. Kirk can be reached by email at [email protected]. Amit Kalani is a Microsoft Certified Application Developer (MCAD) and Microsoft Certified Solution Developer (MCSD) for the Microsoft .NET platform. He is the author of MCAD/MCSD Training Guide: Developing and Implementing Web Applications with Visual C# .NET and Visual Studio .NET (Exam 70-315), MCAD/MCSD Training Guide: Developing and Implementing Windows-based Applications with Visual C# .NET and Visual Studio .NET (Exam 70-316), and MCAD/MCSD Training Guide: Developing XML Web Services and Server Components with Microsoft Visual C# .NET and Microsoft .NET Framework (Exam 70-320). Amit has been long associated with Microsoft certifications exams. In an earlier job, he also managed a Microsoft Certified Technical Education Center (CTEC), where he closely worked with students to understand their requirements, and he guided them towards passing the certification exams. You can reach Amit at [email protected]. Priti Kalani is a Microsoft Certified Application Developer (MCAD) and Microsoft Certified Solution Developer (MCSD) for Microsoft .NET. Priti has been programming with Visual Studio .NET and the .NET Framework since their early beta versions. She is a co-author of the MCAD/MCSD Training Guide (Exam 70-320): Developing XML Web Services and Server Components with Microsoft Visual C# .NET and Microsoft .NET Framework. She has also been a technical reviewer for several popular books about the .NET Framework and related technologies. Priti welcomes your comments about the book at her email address, [email protected]. About the Technical Editors 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. Greg Guntle is a twenty-one year veteran of developing PC applications using languages, including C, C++, VB, VB .NET, and C# .NET. He has been technical editing computer programming books for the past 18 years. He has also co-authored several books, including Teach Yourself Advanced C and Borland C++ Builder. Dedication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . To our parents. Amit and Priti Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . We would like to acknowledge following people, who in diverse ways helped to create this book: Ginny Bess, Tricia Liebig, Krista Hansing, Steve Heckler, Greg Guntle, Ken Cox, and the design and production team. A special thanks to Jeff Riley for giving us the opportunity to work on this project. Thanks also to Kalani Kirk Hausman and Mike Gunderloy for their allaround contributions towards this book. —Amit Kalani —Priti Kalani 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 Certification 201 West 103rd Street Indianapolis, IN 46290 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-316 Exam Cram 2! Whether this is your first or your fifteenth Exam Cram 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 developer certification exams for Microsoft .NET. Chapters 1 through 15 are designed to remind you of everything you’ll need to know in order to take—and pass—the 70-316 Microsoft certification exam. Two sample tests at the end of the book should give you a reasonably accurate assessment of your knowledge, and yes, we’ve provided the answers and their explanations to the tests. Read the book, and you’ll stand a very good chance of passing the test. The appendix includes a description of the testing environment, and a discussion of test-taking strategies. 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, we present and dissect the questions and problems you’re likely to encounter on a test. We’ve worked to bring together as much information as possible about Microsoft certification exams. Nevertheless, to completely prepare yourself for any Microsoft test, we recommend that you begin by taking the Self-Assessment that is 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) for Microsoft .NET. Based on what you learn from the Self-Assessment, you might decide to begin your studies with some classroom training or some background reading. On the other hand, you might decide to pick up and read one of the many study guides such as the award-winning MCAD/MCSD Training Guide series from Que Publishing. We also recommend that you supplement your study program with visits to www.examcram2.com to receive additional practice xxii Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . questions, get advice, and track the MCAD and MCSD for Microsoft .NET program. We also strongly recommend that you install, configure, and play around with the software that 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! Taking a Certification Exam After you’ve prepared for your exam, you need to register with a testing center. In the United States and Canada, tests are administered by Prometric and 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 1-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 a check has cleared can you actually register for a test. 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 (or 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 testing ID. (If you are sitting for an Microsoft exam for the first time, you will be assigned a testing ID when you register for the exam.) ➤ 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.) xxiii . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introduction . . . . . . . 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—to be admitted into the testing room. All 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 few blank sheets of paper and a pen or, in some cases, an erasable plastic sheet and a marker. We 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. We 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 whether you’ve passed or failed. If you need to retake an exam, you have to schedule a new test with Prometric or VUE. The first time you fail a test, you can retake the test 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. 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 (www.microsoft.com/traincert/mcp/mcpsecure.asp) 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. Microsoft sends you a Welcome Kit in about six to eight weeks. The kit contains a certificate that is suitable for framing, along with a wallet card and a lapel pin. In addition you get a number of other benefits such as these: ➤ A license to use the MCP/MCAD/MCSD logo, which means that you can use the logo on your letterhead and business cards. (Refer to the Microsoft Web site for the logo usage guidelines and terms and conditions.) xxiv Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ Access to the MCP Secure Web site, for the latest technical and product information, and exclusive discount offers on products and services from select companies. ➤ Invitations to Microsoft conferences, technical training sessions, and spe- cial events. ➤ A free subscription to Microsoft Certified Professional Magazine Online, which provides ongoing data about testing and certification activities, requirements, and changes to the program. Many people believe that the industry recognition of the MCP/MCAD/MCSD credentials 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, MCSD, and other certifications, and many individuals who complete Microsoft certification programs can qualify for increases in pay 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 Exam 70-316 requires that you obtain and study materials designed to provide comprehensive information about the .NET Framework and Visual Studio .NET, and their capabilities for Windows-based application development. The following list of materials can help you study and prepare: ➤ The Visual Studio .NET product CD—Although you can develop Windows-based applications using the freely available .NET Framework SDK (www.microsoft.com/net/), I also recommend that you use Microsoft Visual Studio .NET. Several questions on the exam will test your skills on Visual Studio .NET. If do not have access to Visual Studio .NET, consider getting a trial version from Microsoft. ➤ MSDN (Microsoft Developer Network) online (msdn.microsoft.com)— This Web site provides access to the most up-to-date product documentation, articles, product support knowledge base, and seminars. ➤ The .NET Framework community sites—Sites such as www. and www.windowsforms.net provide the latest news and announcements related to the Windows-based application development using the .NET Framework. In addition to accessing this information, you can discuss your topics of interests with other developers. gotdotnet.com . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introduction . . . . . . . ➤ The Exam Cram 2 Web site—The official Exam Cram 2 Web site (www.examcram2.com) provides various exam-preparation tools, including advice, practice tests, questions of the day, and discussion groups. ➤ Search engines—Search engines such as www.google.com make it easy for you to find the information that you are looking for. You can search for Microsoft-specific information using Google’s Microsoft search Web site, www.google.com/microsoft. The Google Groups Web site (groups.google.com) requires special mention because it not only allows you to post questions in the subject-related newsgroups such as microsoft.public.cert.exam.mcad and microsoft. public.cert.exam.mcsd, but it also allows you to search the Usenet archive. You can use the Usenet archive to see whether other developers have already posted solutions for the problems that you are facing. In addition, you might find any or all of the following materials useful in your exam preparations: ➤ Self-study MCAD/MCSD training guides—Que Certification offers a comprehensive self-study training guide for the MCAD and the MCSD for Microsoft .NET exams. The training guides cover the subject in much greater level of detail than the Exam Cram2 books, and are designed to teach you everything you need to know about the subject covered by the exam. For the 70-316 exam, refer to the MCAD/MCSD Training Guide: Developing and Implementing Windows-Based Applications with Visual C# .NET and Visual Studio .NET (Exam 70-316), by Amit Kalani. ➤ Classroom training—Although classroom training is an expensive solu- tion, many novice developers find it useful. Many companies, including the Microsoft Certified Technical Education Centers (CTECs), and third-party training companies (such as Wintellect and DevelopMentor) offer classroom training on subjects related to the 70-316 exams. ➤ Other publications—There’s no shortage of materials available about the .NET Framework and Visual Studio .NET. You can select the topics in which you are having difficulty and then find a book related to that topic for an in-depth study. You can find several books and sample chapters online at the InformIT Web site (www.informit.com). What This Book Will Not Do This book will not teach you everything you need to know about the .NET Framework, or even about a given topic. Nor is this book an introduction to xxv xxvi Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . computer programming. If you’re new to applications development and are looking for an initial preparation guide, check out www.quepublishing.com, where you will find whole sections dedicated to the books about the MCSD/MCAD certifications and computer programming. This book reviews what you need to know before you take the test, with the fundamental purpose dedicated to reviewing the information needed on the Microsoft 70-316 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 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 might want to read the book one time, 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-based application development using the Microsoft .NET Framework in as few pages as possible. We think you can use this book to get a sense of the underlying context of any topic in the chapters, or to skim-read for Study Alerts, bullet points, summaries, and topic headings. We’ve drawn on material from Microsoft’s own listing of knowledge requirements, from other preparation guides, and from the exams themselves. We’ve also drawn from a battery of third-party test-preparation tools, technical Web sites, and from our own experience with application development. Our aim is to walk you through your knowledge you will need, looking over your shoulder, so to speak, and pointing out those things that are important for the exam (study alerts, practice questions, and so on). The 70-316 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. We’ve tried to demystify the jargon, acronyms, terms, and concepts, and wherever we think you’re likely to blur past an important concept, we’ve defined the assumptions and premises behind that concept. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introduction . . . . . . . About This Book If you’re preparing for the 70-316 certification exam for the first time, we’ve structured the topics in this book to build upon one another. Therefore, the topics covered in later chapters often refer to previous discussions in earlier chapters. In our opinion, many computer manuals and reference books are essentially a list of facts. Rather than simply listing raw facts about each topic on the exam, we’ve tried to paint an integrated landscape, where each exam fact becomes an obvious conclusion to the problems evolving out of earlier technology. We suggest you read this book from front to back. You won’t be wasting your time: Nothing we’ve written is a guess about an unknown exam. What might appear to be a detour into rambling discussions is based upon our many years of working with less experienced computer users. We’ve had to explain certain underlying information on such a regular basis that we’ve included those explanations here. Time and again, we’ve found that by understanding the conceptual underpinnings of a topic, our audience members were much better able to recall the resulting details. After you’ve read the book, you can brush up on a topic by using the index or the table of contents to go straight to the topics and questions you want to re-examine. We’ve tried to use the headings and subheadings to provide outline information about each given topic. After you’ve been certified, we think you’ll find this book useful as a tightly focused reference and an essential foundation of Windows application development. Chapter Formats Each Exam Cram 2 chapter follows a regular structure, along with graphical cues about especially important or useful material. The structure of a typical chapter includes: ➤ 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. We 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 at least three topics related to the chapter’s subject. ➤ Exam Alerts—Throughout the topical coverage section, we highlight material most likely to appear on the exam by using a special Exam Alert layout that looks like this: Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . This is what an Alert looks like. An Alert stresses concepts, terms, software, or activities that will most likely appear in one or more certification exam questions. For that reason, we think any information found offset in Alert format is worthy of unusual attentiveness on your part. Even if material isn’t flagged as an 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, we dip into nearly every aspect of Windows application development. Where a body of knowledge is deeper than the scope of the book, we 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. While you can memorize just the facts you need, 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—We 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 are a helpful way to remind you of the context surrounding a particular area of a topic under discussion. You should also read Appendix A, “Microsoft Certification Exams,” for helpful strategies used in taking a test. The introduction to the sample tests at the end of the book contains additional tips on how to figure out the correct response to a question, or what to do if you draw a complete blank. ➤ Practice 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 we found to be most important on the exam. ➤ Need to know more?—Every chapter ends with a section entitled “Need to Know More?” This section provides pointers to resources that we 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. We use this section to recommend resources that we have used on a regular basis, so none of the recommendations will be a waste of your time or money. These resources might go out of print or be taken down (in the case of Web sites), so we’ve tried to reference widely accepted resources. xxix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introduction . . . . . . . The bulk of the book follows this chapter structure, but we would like to point out a few other elements: ➤ Sample tests—The sample tests, which appear in Chapters 16 and 18 are very close approximations of the types of questions you are likely to see on the current 70-316 exam. ➤ Answer keys—Here you’ll find the answers to the sample tests, with a following explanation of both the correct response 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 we 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 we’ve found require bruteforce memorization. You need to remember this information only 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 the parking lot or in the lobby of the testing center just before you walk into the testing center. The Cram Sheet is separated into headings, so you can review the appropriate parts just before each test. ➤ CD-ROM—The CD-ROM that comes with this book contains the com- plete code listing from the Que Certification’s MCAD/MCSD Training Guide: Developing and Implementing Windows-Based Application With Visual C# .NET and Visual Studio .NET (Exam 70-316). This code listing provides you an opportunity to read, understand, and extend a lot of additional code that demonstrates various concepts related to the 70-316 exam objectives. The CD 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 only questions sufficient for one practice exam. To get the complete set of practice questions and exam functionality, visit www.preplogic.com. Code Lines Limitations of printed pages many times will introduce false line breaks in programming code, character strings, pathnames, and other related text. We make every effort to ensure that a line break or line wrap generated by the page margins does not change the meaning of the information. Contacting the Authors We’ve tried to create a real-world tool that you can use to prepare for and pass the 70-316 MCAD/MCSD certification exam. We are interested in any feedback you care to share about the book, especially if you have ideas about how we can improve it for future test-takers. We will consider everything you say carefully and will respond to all reasonable suggestions and comments. You can reach us via email at [email protected]. Let us know if you found this book to be helpful in your preparation efforts. We’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, we’d love to hear that you passed the exam, and even if you just want to share your triumph, we’d be happy to hear from you. Thanks for choosing us as your personal trainers, and enjoy the book. We would wish you luck on the exam, but we know that if you read through all the chapters, you won’t need luck—you’ll pass the test on the strength of real knowledge! Self-Assessment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . This self-assessment helps 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-316, “Developing and Implementing Windows-Based Applications with Microsoft Visual C# .NET and Microsoft Visual Studio .NET.” But before you tackle this selfassessment, let’s talk about the developer certifications offered by Microsoft for Microsoft .NET. Microsoft Developer Certifications for Microsoft .NET Microsoft currently offers two levels of developer certification for Microsoft .NET—MCAD and MCSD for Microsoft .NET. In fact, the MCAD certification is a subset of the MCSD certification. In this section, you will learn how the two certifications are structured and what you can expect from an ideal MCAD or MCSD candidate. The MCAD Certification The MCAD is a certification for the developers who develop, deploy, and maintain applications and components using the Microsoft .NET Framework and Microsoft Visual Studio .NET. To obtain the MCAD certificate, you are required to pass three exams that include two core exams and one elective exam, as listed in the following sections. MCAD Core Exams You must pass two of the following core exams to earn credit toward the MCAD certification: ➤ 70-305, “Developing and Implementing Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio .NET” or xxxii Self-Assessment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ 70-306, “Developing and Implementing Windows-Based Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio .NET” or 70-315, “Developing and Implementing Web Applications with Microsoft Visual C# .NET and Microsoft Visual Studio .NET” or 70-316, “Developing and Implementing Windows-Based Applications with Microsoft Visual C# .NET and Microsoft Visual Studio .NET” ➤ 70-310, “Designing XML Web Services and Server Components with Microsoft Visual Basic .NET and the Microsoft .NET Framework” or 70-320, “Designing XML Web Services and Server Components with Microsoft Visual C# .NET and the Microsoft .NET Framework” MCAD Elective Exams You must pass one of the following elective exams to earn credit toward the MCAD certification: ➤ 70-229, “Designing and Implementing Databases with Microsoft SQL Server 2000 Enterprise Edition” ➤ 70-230, “Designing and Implementing Solutions with Microsoft BizTalk Server 2000 Enterprise Edition” ➤ 70-234, “Designing and Implementing Solutions with Microsoft Commerce Server 2000” You also can count as an elective one of the four core exams 70-305, 70-306, 70-315, and 70-316. The one that you can count as an elective is the exam from the opposite technology from the exam that you count as a core exam. For example, if you take the exam “Developing and Implementing Windows-Based Applications with Microsoft Visual C# .NET and Microsoft Visual Studio .NET (70-316)” as a core exam, you can take either exam 70315 or exam 70-305 as an elective, but you cannot take exam 70-306 as an elective. An Ideal MCAD Candidate An ideal MCAD candidate is someone who has one to two years of experience in developing and maintaining department-level applications, Web or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Self-Assessment . . . . . . . . . desktop clients, XML Web services, and back-end data services using the Microsoft .NET Framework and Microsoft Visual Studio .NET. The ideal MCAD candidate also might be someone who works in teams that use Microsoft .NET Framework and other Microsoft technologies to develop enterprise-level applications. Typical job titles for an ideal MCAD candidate include programmer, programmer/analyst, and software developer. The MCSD for Microsoft .NET Certification The MCSD for Microsoft .NET certification is for those developers who design and develop enterprise-level solutions using the Microsoft .NET Framework and other Microsoft development tools and technologies. For the MCSD for Microsoft .NET certification, you must pass four core exams and one elective exam, as listed in the following sections. MCSD for Microsoft .NET Track Core Exams You must pass four of the following core exams to earn credit toward the MCSD for Microsoft .NET certification: ➤ 70-305, “Developing and Implementing Web Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio .NET” or 70-315, “Developing and Implementing Web Applications with Microsoft Visual C# .NET and Microsoft Visual Studio .NET” ➤ 70-306, “Developing and Implementing Windows-Based Applications with Microsoft Visual Basic .NET and Microsoft Visual Studio .NET” or 70-316, “Developing and Implementing Windows-Based Applications with Microsoft Visual C# .NET and Microsoft Visual Studio .NET” ➤ 70-310, “Designing XML Web Services and Server Components with Microsoft Visual Basic .NET and the Microsoft .NET Framework” or 70-320, “Designing XML Web Services and Server Components with Microsoft Visual C# .NET and the Microsoft .NET Framework” ➤ 70-300, “Analyzing Requirements and Defining .NET Solution Architectures” xxxiv Self-Assessment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MCSD for Microsoft .NET Track Elective Exams You must pass one of the following elective exams to earn credit toward the MCSD for Microsoft .NET certification: ➤ 70-229, “Designing and Implementing Databases with Microsoft SQL Server 2000 Enterprise Edition” ➤ 70-230, “Designing and Implementing Solutions with Microsoft BizTalk Server 2000 Enterprise Edition” ➤ 70-234, “Designing and Implementing Solutions with Microsoft Commerce Server 2000” Exam 70-316 also qualifies as an elective toward a different certification, the Microsoft Certified Database Administrator (MCDBA) on Microsoft SQL Server 2000 certification. An Ideal MCSD for Microsoft .NET Candidate An ideal MCSD for Microsoft .NET candidate is someone who has at least two years of experience in designing and developing enterprise-level solutions with the Microsoft .NET Framework and other Microsoft technologies. An ideal MCSD for Microsoft .NET candidate should be able to work as a lead developer, performing tasks such as analyzing business and technical requirements and defining solution architecture. In addition, an MCSD for Microsoft .NET candidate should be able to perform tasks typical to the MCAD certification, such as building, deploying, and maintaining the applications. Typical job titles for an ideal MCSD for Microsoft .NET candidate include software engineer, application analyst, application developer, and technical consultant. 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 might consult on your quest. 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 certification success. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Self-Assessment . . . . . . . . . 1. Do you have experience with computer programming or with the C# programming language? Experience with a programming language, even if with a different language, will really help in passing Exam 70-316. However, If you do not have much experience with programming—or, in particular, with the C# programming language—we recommend that you read the following book: C# How to Program, by Harvey M. Deitel et al. Prentice Hall, 2001. 2. Do you have a general understanding of what the .NET Framework is and what it has to offer to you as a developer? The .NET Framework has a lot to offer. Even if you have been developing applications in the .NET Framework for the past few months, you might not have had the opportunity to experiment with all the features of the .NET Framework. In that case, I recommend that you read the following book: Understanding .NET: A Tutorial and Analysis, by David Chappell. Addison Wesley Professional, 2002. This book gives you a bird’s-eye view of Microsoft .NET and how it affects you as a developer. Many questions in the 70-316 exam require you to have a high-level view of the .NET Framework and related technologies. 3. Have you installed, configured, or used Visual Studio .NET and the .NET Framework Software Development Kit (SDK)? Experience is necessary for passing Exam 70-316. If you haven’t worked much with the .NET Framework SDK and with Visual Studio .NET, now is the time to do so. Before you sit for the exam, make sure you spend enough time in programming using both the Microsoft .NET Framework SDK and Visual Studio .NET. The Microsoft .NET Framework is available as a free download from http://msdn.microsoft.com/netframework/downloads/howtoget.asp. Unlike the .NET Framework, you’ll have to buy a license for using Visual Studio .NET; if you do not plan to do so, you should at least consider ordering a trial version of Visual Studio .NET, at http://msdn.microsoft.com/vstudio/productinfo/trial. 4. Have you reviewed the exam objectives? If you have not reviewed the exam objectives lately, look at them now when you are assessing your exam readiness. The up-to-date exam xxxv xxxvi Self-Assessment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . objectives for the 70-316 exam are available at www.microsoft.com/ traincert/exams/70-316.asp. You should review each objective and then ask yourself if you have used Visual C# .NET and Visual Studio .NET enough to answer questions related to that particular exam objective. If you are not confident, consider looking at the related topics in the following resources: ➤ http://msdn.microsoft.com ➤ http://support.microsoft.com ➤ MCAD/MCSD Training Guide (70-316): Developing and Implementing Windows-Based Applications with Visual C# and Visual Studio.NET, by Amit Kalani. Que Certifications, 2002. 5. Have you taken a few practice exams for Exam 70-316? This book has two sample exams in Chapter 16 and Chapter 18. You should attempt these exams to access how ready you are. If you require additional practice, you might also take practice exams from other test providers. Onward, Through the Fog! 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 our assessment regime, you’ll know not only what you need to study, but also when you’re ready to set a test date at Prometric (www.2test.com) or VUE (www.vue.com). Good luck! 1 Introducing Windows Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ .NET Framework ✓ Common Language Runtime (CLR) ✓ Framework Class Library (FCL) ✓ Integrated development environment (IDE) ✓ Class ✓ Inheritance ✓ Namespace ✓ Application and Form class ✓ Event handling ✓ Delegate ✓ System.Drawing namespace ✓ Draw and Fill method Techniques you’ll need to master: ✓ Create a form and edit its properties at design time using the Properties window and at run time within the form’s code. ✓ Understand how to handle events in a Windows Forms application. ✓ Experiment with the classes in the System.Drawing namespace. ✓ Understand the use of the Draw and Fill methods of the Graphics class. 2 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A user interface enables you to input and modify information for use by an application. Many types of controls can be added to the user interface to allow information input, manipulation, and selection in different ways. A Windows form can be used to integrate these controls and provide a structure for the deployed interface. This chapter examines the basic creation of Windows forms and simple event handling using the Visual Studio .NET development environment. Introduction to the .NET Framework and Visual Studio .NET The Microsoft .NET initiative brings about a change in the fundamental structure of development and deployment. The .NET development platform integrates support for multiple development languages such as Visual Basic .NET and C# (pronounced see-sharp) with a Common Language Runtime (CLR) and a shared Framework class library (FCL). These enable programmers to develop in whatever language they are most comfortable with. To prepare a machine to support .NET applications, the Common Language Runtime (CLR) must be present. This is accomplished by loading the .NET Framework, available through the Windows Update site or included within the Microsoft .NET Framework Software Development Kit (SDK) from the Microsoft MSDN downloads site. Code development for the .NET environment can be performed using a text editor and the command-line compilers within the Microsoft .NET Framework SDK, but a more robust solution exists in the form of Microsoft’s Visual Studio .NET product. This product includes an integrated development environment (IDE) and advanced editing tools that make it possible to rapidly develop code and other .NET structures, use integrated debugging and automation tools, and simplify application distribution and update by using the Windows Installer technology. You are expected to be able to use the Visual Studio .NET product, and to understand code written using the C# language. Objects and Classes C# is an object-oriented language in which every construct is considered an object that has associated attributes and methods and that, in turn, can . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . contain other objects. The abstract concept of a group of objects with common qualities is a class. The class is a fundamental concept that you will encounter throughout this book. You should be very familiar with the idea of classes. A class is a blueprint for an object rather than an object itself. A class encapsulates both data (such as constants and fields) and behavior (including methods, properties, constructors, and events) into a single concept. To the programs using a class, a property looks like a field—that is, a storage location. Properties and fields have the same usage syntax, but their implementations differ. In a class, a property is not a storage location; instead, it defines accessors that contain code to be executed when the property value is being read or written. This piece of code allows properties to preprocess the data before it is read or written, to ensure integrity of a class. Using properties is the preferred way of exposing attributes or characteristics of a class. A class can have static members (fields, properties, methods, and so on). Static members belong to the class itself instead of to a particular instance of that class. Class Inheritance Inheritance enables you to create new classes that are based on classes that already exist. The newly created classes are called derived classes, and the classes from which they inherit are called base classes. However, a class can inherit from only one base class at a time; that base class can be inherited from another base class. Therefore, the chain of inheritance provides a hierarchy on which the classes are based. Figure 1.1 provides an example of the chain of inheritance from a Windows form through its parent and, in turn, back to the most fundamental class: the Object class. The properties, or members, of a class that can be inherited can be limited by including an access modifier in their declaration. The default modifier for the properties, or members, of a class is private. Visual C# .NET provides four access modifiers: ➤ public—This member is globally accessible. ➤ private—This member is accessible only to its containing type. 3 4 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ protected—This member is accessible to the containing type and all classes derived from the containing type. ➤ internal—This member is accessible to all classes within the current project. System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.Control System.Windows.Forms.ScrollableControl System.Windows.Forms.ContainerControl System.Windows.Forms.Form Figure 1.1 This is an example of class inheritance by the form class from its parent classes. Namespace The .NET Framework FCL includes hundreds of classes, and you will develop many more for each project. To provide organization and structure to what could rapidly become an unmanageable number of classes, the .NET Framework makes use of the concept of a namespace. This is a hierarchical naming system in which classes can be grouped as required. The standard naming convention for creation of a namespace is shown here: CompanyName.ApplicationName An example of this is the creation of a namespace for this book as ExamCram2.70316. Here, 70316 is the child namespace of the parent ExamCram2 namespace. If you created a class named ExamItems within the 70316 namespace, the class would be designated as ExamCram2.70316. ExamItems. A separate ExamItems class could exist within a different namespace, as in ExamCram2.70306.ExamItems. These are unrelated classes sharing only the common class name, separated by the namespace groupings of 70316 and 70306 within the parent ExamCram2 namespace. In FCL, the root namespace that includes all other classes and namespaces is the System namespace. This contains the Object class (System.Object), which is the parent for all other classes in the .NET Framework. System also includes other namespaces that you will deal with, such as the . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . System.Drawing namespace that includes classes used to create graphical elements, and the System.Windows namespace that includes the System.Windows.Forms child namespace, which, in turn, includes the classes used to create Windows forms objects. The namespace hierarchy is simply used to organize classes and is separate from the hierarchy in a chain of class inheritance. A class can inherit from another class located in any namespace. Now that you are familiar with the basics of the conceptual side of the .NET development environment, let’s examine the creation of a form within the Windows Forms Designer. Using the Windows Forms Designer Because the .NET Framework supports development across multiple languages, it provides a common development interface for the creation of objects such as a Windows form. As seen in Figure 1.2, the Windows Forms Designer displays a form in Design view. Figure 1.2 The Windows Forms Designer showing the default creation of Form1. 5 6 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a Blank Form To create a new Windows form, first launch Visual Studio .NET and then perform the following steps: 1. Click the New Project button in the Start page or select File, New, Project from the Visual Studio .NET menu. 2. Select Visual C# Projects as the project types and Windows Application for the template. Provide a meaningful name for the project and a location for the project’s files. 3. As shown in Figure 1.2, you will see the new blank form in Design view along with the project’s Solution Explorer and Properties windows. If the Solution Explorer is not displayed by default, you can find it within the View options. 4. To change the name of the form, right-click the form in the Solution Explorer and select Rename. Then provide the desired name. Modifying a Form’s Properties The Properties window within the design environment provides access to the properties of a selected form in the current project. Values can be edited here by clicking on the desired property, such as the Text property, which specifies the text that will be displayed in a form’s title bar. Displaying a Form To see the results of your changes, select Start from the Debug menu or press the F5 key. This displays the form. Clicking the Close button on the form returns you to Design view. You can switch to Code view of the form by right-clicking the form and selecting View Code. This opens a new window displaying the code that corresponds to the Windows form (see Figure 1.3). When a new Windows application is created, it automatically includes a blank Windows form. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . Figure 1.3 The Windows Forms Designer showing the Code view of Form1. Exploring Code View Within the Code view of a form, you can expand the code blocks by clicking the (+), and you can collapse the block by clicking the (–). As in Figure 1.3, hovering the cursor over the code block displays the first lines of the collapsed code. A code block can be specified by bracketing the code with #region and #endregion. In Code view, you can directly edit the code that creates the form. Changes here are reflected on your form automatically. One item to note is the inheritance from the System.Windows.Forms.Form class so that the new form instance automatically includes the inherited members necessary to allow it to contain other controls and inherit form-related methods. This is accomplished by the automatic code shown here: public class Form1 : System.Windows.Forms.Form { //Form code goes here } You will also notice the constructor for the class, which allows for the creation of a new instance of a class. The constructor is recognizable by the name of the class, as shown here: 7 8 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . public Form1() { // Required for Windows Forms Designer support InitializeComponent(); // TODO: Add any constructor code after InitializeComponent call } The Windows Forms Designer uses the InitializeComponent() method for storing the customizations done to the form through Design view. Additional initialization of the new instance of the Form class, including programmatic assignment of property values, can be performed within the InitializeComponent() method of the class. To set the same Text value previously edited in the Solution Explorer, use the following code: private void InitializeComponent() { // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 266); this.Name = “Form1”; this.Text = “My First Form”; } Here, the keyword this indicates that the code is acting on the currently selected object and is assigning the value of My First Form to the Text property of the new instance of the Form object. The Main method within the code is automatically generated by Visual Studio .NET and receives focus when the code first runs. The code for a Single Threaded Apartment (STA) designated application would look like this: [STAThread] static void Main() { Application.Run(new Form1()); } When you edit code, you will find that the Visual Studio .NET interface offers access to any methods and properties available to an object of a class. This feature, called IntelliSense, will help in rapid development of your application. Compiling the Form When you run the form by selecting Start from the Debug menu or using the F5 key, Visual Studio .NET attempts to compile the form’s code using a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . suitable language compiler. Errors are displayed so that you can correct them and compile again, if necessary. If no errors are encountered, Visual Studio .NET creates an executable (.exe) file with the project’s name, located in the \bin\debug folder in the location selected to contain the project’s files. Using Classes Many classes included in the Framework class library (FCL) can be used within your application. Many of these classes provide methods, properties, and events that are used to perform specific tasks in your application. The Application Class An Application class provides properties that the code can use to obtain information about the current application (see Table 1.1), as well as provide methods to start and close an application, and to process windows messages (see Table 1.2). Table 1.1 Important Static Properties of the Application Class Property Description CompanyName Company name associated with the application CurrentCulture Culture information for the current thread CurrentInputLanguage Input language for the current thread ExecutablePath Path to the EXE file that started the application ProductName Product name for the current application ProductVersion Product version for the current application Table 1.2 Important Static Methods of the Application Class Method Description DoEvents Processes Windows messages currently in the queue Exit Closes and exits the application ExitThread Exits the message loop on the current thread and closes all windows on the current thread Run Begins a standard application message loop on the current thread 9 10 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Form Class Whenever you create an instance of the System.Windows.Forms.Form class, the instance inherits many useful properties that can be configured programmatically or through the properties window, as described earlier in this chapter. Table 1.3 lists important properties of the Form class. Table 1.3 Important Properties of the Form Class Property Description BackColor Specifies the background color of the form BackgroundImage Specifies the background image for the form ClientSize Specifies the size of the client area of the form ControlBox Indicates whether a control box needs to be displayed in the caption bar of the form DesktopLocation Determines the location of the form on the Windows desktop Enabled Indicates whether a control can respond to user interaction FormBorderStyle Specifies the border style of the form Handle Gets the window handle (hWnd) of the form HelpButton Indicates whether a Help button is to be displayed on the caption bar of the form Icon Specifies the icon for the form MaximizeBox Indicates whether a Maximize button is to be displayed on the caption bar of the form MaximumSize Determines the maximum size to which this form can be resized MinimizeBox Indicates whether a Minimize button is to be displayed in the caption bar of the form MinimumSize Determines the minimum size to which this form can be resized Modal Indicates whether the form will be displayed modally Name Gives the name of the form Opacity Specifies the opacity level of the form, measured as a decimal percentage from 0 (transparent) to 1 (fully opaque) ShowInTaskbar Indicates whether this form is displayed in the Windows taskbar Size Determines the size of the form StartPosition Specifies the starting position of the form at runtime TopMost Indicates whether this form is displayed as the topmost form of the application Forms also include many methods that can be used to act upon an instance of the Form class. These include the Show() method, which displays an . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . instance of the class; the Hide() method, which temporarily stops displaying the form without closing it; and the Close() method, which terminates an instance of a form. To provide the final result, some of the methods take into account other properties set on a form at the time the Show() method is invoked, such as the specification of the Opacity property. If this property is set at a value between 0 (transparent) and 1 (opaque), the resultant form will be partially transparent when the Show() method is called. To place a form on top of others already present, you would set the form’s TopMost property to true before invoking the Show() method. Custom Properties In addition to using the existing properties, you can add custom properties to a Windows Form. You can use a custom property to store applicationspecific data. For example, you can add the following code in the class definition to declare a property named FormState that stores the value of the custom-defined State enumeration: //define constant values for State public enum State{Idle, Connecting, Processing} //use this field as storage location for FormState property private State formState; //set attributes for FormState property [Browsable(true), EditorBrowsable(EditorBrowsableState.Never), Description(“Sets the custom Form state”), Category(“Custom”)] //Creating FormState property public State FormState { get { return formState; } set { formState = value; switch (formState) { case State.Idle: this.BackColor = Color.Red; this.Text = “Idle”; break; case State.Connecting: this.BackColor = Color.Orange; this.Text = “Connecting...”; break; case State.Processing: 11 12 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . this.BackColor = Color.Green; this.Text = “Processing”; break; } } } The preceding code first defines the memory variable formState to hold the value of the FormState property, which is a custom-defined State enumeration member. Therefore, custom properties can hold any type of data. You can set the value for custom properties through code as follows: //set the FormState property of this form this.FormState = State.Processing; When you create a new property, you can control its behavior by configuring its attributes. You can customize the custom property to appear in the Properties window (for the derived forms) or in IntelliSense by applying attributes to the property. The attributes you should be aware of are listed in Table 1.4. Table 1.4 Attributes That Control the Behavior of a Custom Property Attribute Description Browsable Indicates whether the property will be displayed in the Properties window. Its default value is true. EditorBrowsable Indicates whether the property should appear in the IntelliSense list of an object in Code view. Its value is set to a member of the EditorBrowsableState enumeration, with three possible values: Advanced, Always, or Never. Its default value is Always. Description Provides a description of the property. When specified, it is displayed in the description area when the property is selected. Category Specifies the category of the property. This is used in the Properties window to categorize the property list. When you create a new property, you must specify its accessors (get and set). These are access methods that apply to the new property. Without a defined get accessor, the property becomes write-only; a property lacking a set accessor definition is read-only. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . Visual Inheritance Visual inheritance is a process by which a visual element such as a form or a control inherits from an existing element. Visual inheritance helps reuse existing code and maintains consistency among visual elements. You can inherit a form from an existing form by using visual inheritance. You can add an inherited form using the Visual Studio .NET IDE: In the Solution Explorer, right-click the project name and select Add, Add Inherited Form. This opens the Add New Item dialog box. In the dialog box, name the new form and click the Open button. This opens the Inheritance Picker dialog box (see Figure 1.4). Figure 1.4 The Inheritance Picker shows components that can be selected for inheritance. When a form inherits from another form, the derived form inherits all the members of the base class, but the private members of the base class are not accessible in the derived class. This is because the variables with a private access modifier are not accessible beyond the class definition. You can also add extra functionality to the inherited form. The new functionality does not affect any of the base classes; it is available only in the inherited form and the other classes you derive from it. Event Handling Event handling is the process of reacting to events and is an important part of programming a user interface. An event is generated as the result of user actions, such as resizing a form, clicking the form, or moving the mouse over the form. An event also can be generated by changes in the environment, such as when a change in time occurs or when another application performs some action that affects the current application. 13 14 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Two basic methods of event handling exist: ➤ Attaching a delegate ➤ Overriding a protected method of the base class Attaching a Delegate When a form is loaded, a Load event is raised. When you click the left or right buttons of a mouse, a MouseDown event is raised. Therefore, events enable a class to provide notifications to other objects that something of interest to them has happened. If you want to perform some actions when events occur, you can define an appropriate event handler. An event handler is a method that is executed as a response to an event. The event handler should be registered with the event source so that when the event occurs, the handler is invoked (this is also referred to as event wiring). The event handler is a method with a specific signature specified by the event delegate. An event handler normally has a void return type and accepts two arguments: the object on which the event occurred and an argument of type EventArgs (or a type derived from it, such as MouseEventArgs). The following code shows the way the delegate for the MouseDown event is defined: public delegate void MouseEventHandler(object sender, MouseEventArgs e); The preceeding definition means that the MouseEventHandler, the delegate for the MouseDown event, is capable of storing references to any method whose return type is void and which accepts two arguments: the first one of type System.Object and the other one of type MouseEventArgs. The following code shows how to define the event handler so that it can be registered with the help of the MouseEventHandler delegate: private void MouseClicker_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { MessageBox.Show(String.Format(“X ={0}, Y={1}”, e.X, e.Y), String.Format(“The {0} mouse button hit me at:”, e.Button.ToString())); } Now, after creating the event handler with the desired signature, you need to attach this event handler with the event. For this, you need to create a new instance of the delegate (in this case, MouseEventHandler) and then attach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . the delegate object to the event. The following code shows how to attach a delegate: [STAThread] static void Main() { MouseClicker MyForm= new MouseClicker(); MyForm.MouseDown += new MouseEventHandler(MyForm.MouseEventHandler); Application.Run(MyForm); } In the preceeding code, MyForm represents the current form, MouseDown is the name of the event, MouseEventHandler is the delegate, and MouseClicker_MouseDown() is the event handler to attach. When you are attaching a delegate object to the event, you should usually use the += syntax instead of the = syntax. This is because = attaches the current delegate but loses the other previously attached delegates. Using += ensures that the list of previously attached delegates is preserved. You can detach an event handler from an event by using the -= syntax. After the delegate containing the event handler definition is attached, in this example, whenever the MouseDown event triggers, the MouseClicker_ MouseDown() event handler is executed. This displays the current position of the mouse over the form in a message box, as shown in Figure 1.5. Figure 1.5 A message box displaying the results of the MouseDown event. The properties window in Visual Studio .NET provides an easy-to-use interface for attaching an event handler to the event. Using this method, you select the Events icon of the properties window and then select an event such as the MouseDown event from the list of events. After you select the MouseDown event, you specify the name of the event handler that should be executed when the event occurs. This simple step attaches the event handler to the event. Behind the scenes, Visual Studio .NET generates code to actually attach the event handler to the event. Using a delegate is the preferred way of attaching event handlers in Visual Studio .NET. It is possible to have a single event handler respond to multiple events if the delegates of the event require event handlers to be of the same signature. It is also possible to have multiple event handlers interested in responding to an event. 15 16 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . If you designate multiple event handlers to respond to the same event, they execute sequentially in the order they are registered. The MouseEventArgs Type The second argument of the event handler is an object of type EventArgs, or one derived from EventArgs that contains event-related data. In the previous example, the MouseDown event handler had defined the second argument of MouseEventArgs type, which consisted of MouseDown event-related data. This class is derived from the System.Windows.EventArgs type. Table 1.5 lists some of the properties of the MouseEventArgs type. Table 1.5 MouseEventArgs Properties Member Description Button Returns a value of type MouseButtons that specifies which mouse button was pressed. Clicks Returns the number of times the mouse button was pressed and released. Delta Gives a signed count of the number of detents the mouse wheel has rotated. A detent is one notch of the mouse wheel. X The x-coordinate of a mouse click. Y The y-coordinate of a mouse click. Overriding a Protected Method of the Base Class When you create a Windows Form, it inherits from the Form class. By virtue of this inheritance, it can access a set of public and protected methods, as well as properties available to it from one of its base classes. Some of the classes provide sets of protected methods that raise events. You can easily identify these methods because their naming convention is the word On followed by the name of the event. For example, OnMouseDown() is a protected method that raises the MouseDown event. The Form class gets this protected method from the Control class. You can perform event handling by just overriding the base class method. The following code provides an example by overriding the OnMouseDown method of the Control class in the form: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . protected override void OnMouseDown( System.Windows.Forms.MouseEventArgs e) { // Calling the base class version of the method base.OnMouseDown(e); MessageBox.Show(String.Format(“X ={0}, Y={1}”, e.X, e.Y), String.Format(“The {0} mouse button hit me at:”, e.Button.ToString())); } When you override the protected method of the base class, you should always call the base-class version of the method. This way, the derived class will always have the minimum level of functionality offered by the base class. On the other hand, if you don’t call the base-class version of the method, you will not be able to access all the functionality provided by the base class in the derived class. In the case of event handling, calling the base-class version of the method is all the more important because the protected method of the base class takes care of invoking the attached delegates: public event MouseEventHandler MouseDown; protected virtual void OnMouseDown(MouseEventArgs e) { if (MouseDown != null) { //Invokes the delegates. MouseDown(this, e); } } } Therefore, it is always a good practice to call the base-class version of the method when overriding. Building Graphical Interface Elements by Using the System.Drawing Namespace The .NET FCL provides an advanced implementation of the Windows Graphics Device Interface (GDI) known as GDI+. GDI+ includes the following four namespaces in System.Drawing.dll: ➤ System.Drawing ➤ System.Drawing.Drawing2D 17 18 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ System.Drawing.Imaging ➤ System.Drawing.Text The GDI+ classes in these preceeding namespaces can be used to build graphical interface elements such as drawing text, fonts, lines, shapes, and images. GDI+ enables you to develop device-independent applications; you just need to work with the Graphics object instead of worrying about the specific details of the underlying platform. The Graphics object is discussed in the following section. Understanding the Graphics Object The Graphics object represents a drawing surface that can be used to draw graphical elements without worrying about the underlying devices. The Graphics object is an instance of the Graphics class, which resides in the System.Drawing namespace. It is a sealed class and, therefore, cannot be further inherited like the Form class. The Graphics class does not contain any constructors, so it cannot be instantiated. You can retrieve a Graphics object through one of the following methods: ➤ Through the Graphics property of the PaintEventArgs argument passed to the Paint event handler of a control or a form. The resultant Graphics object represents the drawing surface of the object that called the event. ➤ By calling the CreateGraphics() method of a control or form. ➤ By calling the Graphics.FromHwnd() method and passing to it the han- dle of the current form. ➤ By calling the Graphics.FromImage() method. This method takes an image object and returns a Graphics object corresponding to that image. You can use the resultant Graphics object to manipulate the image. The Graphics class provides properties and methods that can be used to draw graphical elements on a form. These properties and methods are discussed later in the chapter. The System.Drawing Namespace Within the System.Drawing namespace, you can use several structures to manipulate a Graphics object. Table 1.8 lists those you should be familiar with. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . Table 1.8 System.Drawing Namespace Structures Structure Description CharacterRange A range of character positions within a string. Color A structure with 140 static properties, each representing the name of a color and four properties—A, R, G, and B, specifying the alpha, red, green, and blue portions of the color. A Color value can be created using the static methods FromArgb(), FromKnownColor(), and FromName(). Point An ordered pair of integer x and y that defines a point in a twodimensional plane. It includes a set of methods and operators to work with points. PointF A float version of the Point structure. Rectangle Stores the integer location and size of a rectangular region. You can create a Rectangle structure by using a Point structure and a Size structure. Point represents the top-left corner, while Size specifies its width and length from the given point. RectangleF A float version of the Rectangle structure. Size The integer size of a rectangular region (width, height). SizeF A float version of the Size structure. The size of a form is measured from its top-left corner, which serves as its origin (0,0). The client area of a form is the portion excluding the title bar, borders, and a menu, if present. The value of x increases as you measure to the right, while the value of y increases as you measure downward. Drawing Text on a Form To draw text on a Windows form, use the DrawString() method of the Graphics class. The following code gives an example: private void PaintExample_Paint( object sender, System.Windows.Forms.PaintEventArgs e) { Graphics grfx = e.Graphics; String str = String.Format( “Form Size is: Width={0}, Height={1}”, Width, Height); grfx.DrawString(str, Font, Brushes.Black, 0, 0); } [STAThread] static void Main() { Application.Run(new PaintExample()); } 19 20 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The preceding code uses the Paint event handler of the form to retrieve a Graphics object and draw text. The Paint event is selected because it is generated each time the form is redrawn, including when the Show() method is called to initially create or restore a hidden form. The DrawString method displays the height and width of the form. The arguments passed to the DrawString method in the preceeding example are as follows: GDI+ and the Windows forms library include full support for the Unicode character set, making it possible to draw text in any language supported by the system. ➤ The first argument is the string to be displayed. ➤ The second argument is the font of the string. Here, the default font is used. ➤ The third argument is the type of brush. The Brushes enumeration pro- vides you with a variety of Brush objects, each with a distinct color. Here, the Brushes.Black value was selected to draw text in the color black. ➤ The fourth and fifth arguments are used to specify the x and y locations for the point that marks the start of a string on the form. Both of these values are required to be of float data type. Here, the 0 value implicitly is converted to a Float value. Using the Invalidate Method The Paint event is generated whenever the form is redrawn. To draw text during other events, such as during a form Resize event, you can call the Invalidate() method. The following code invokes the Invalidate() method when the Resize event of the form occurs: private void PaintExample_Resize(object sender, System.EventArgs e) { // Call the Invalidate method Invalidate(); } The Invalidate() method is called without any arguments in this example, to cause a Paint event to occur for the entire form. You also can provide a Rectangle parameter to restrict a specific portion of a form to be redrawn when the Invalidate() method is called. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . Using the ResizeRedraw Property You also can set the ResizeRedraw property of the form to true so that the form can redraw itself when it is resized. When you set this property to true, and when the form is resized, the code in the Paint event handler is executed. Drawing Shapes Using the Draw Method It is often desirable to draw shapes and graphics on a form. The Graphics class enables you to draw many shapes. Table 1.9 lists the drawing methods of the Graphics class and the shapes you can create with them. Table 1.9 Drawing Methods from the Graphics Class Method Description DrawArc An arc that represents a portion of an ellipse DrawBezier A Bézier curve defined by four points DrawBeziers A series of Bézier curves DrawClosedCurve A closed curve defined by an array of points DrawCurve A curve defined by an array of points DrawEllipse An ellipse defined by a bounding rectangle specified by a pair of coordinates, a height, and a width DrawIcon The image represented by the specified Icon object located at the given coordinates DrawImage An Image object at the specified location, preserving its original size DrawLine A line connecting two points DrawLines A series of line segments that connect an array of points DrawPath A GraphicsPath object DrawPie A pie shape defined by an ellipse and two radial lines DrawPolygon A polygon defined by an array of points DrawRectangle A rectangle specified by a point, a width, and a height DrawRectangles A series of rectangles DrawString Draws the given text string at the specified location with the specified Brush and Font objects The Draw methods make use of the Pen object to draw the graphic elements. You can retrieve a Pen object with the help of different Pen-related classes in the System.Drawing namespace. 21 22 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 1.10 lists the Pen-related classes within the System.Drawing namespace. Table 1.11 lists some of the properties of the Pen class you should be familiar with. Table 1.10 Classes Related to Pen in the System.Drawing Namespace Class Description Pen Represents an object used to draw lines and curves. Pens Provides 140 static properties, each representing a Pen object of a standard color. SystemPens Provides a set of static properties named after a Windows display element. Each of these properties returns a Pen object of width 1. Table 1.11 Properties of the Pen Class Property Description Alignment Alignment for the Pen object Brush Brush object that determines attributes of the Pen object Color Color of the Pen object DashCap Cap style used at the end of the dashes in dashed lines DashPattern An array of custom dashes and spaces DashStyle The style used for dashed lines EndCap Cap style used at the end of lines LineJoin Join style for the ends of two consecutive lines PenType Style of lines StartCap Cap style used at the beginning of lines Width Width of the Pen object When you draw graphical shapes using the methods of the Graphics class, you can set the rendering quality of these elements with the help of the SmoothingMode property. The SmoothingMode property can be set to one of the values of the SmoothingMode enumeration. Table 1.12 details these enumerated values. Antialiasing is the process in which semitransparent pixels are included at the boundaries of two colors to create a smootherappearing boundary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . Table 1.12 SmoothingMode Enumeration Members Member Name Description AntiAlias Antialiased rendering. Default Same as None. HighQuality High-quality, low-performance rendering. Same as AntiAlias. HighSpeed High-performance, low-quality rendering. Same as None. Invalid Invalid mode. Raises an exception. None Does not use antialiasing. Creating Filled Shapes Using the Fill Method An additional option for the creation of graphical objects on a form includes using the Fill method to create filled objects with colors or patterns. Table 1.13 details the Fill methods of the Graphics class. Table 1.13 Fill Methods of the Graphics Class Method Description FillClosedCurve Fills the interior of a closed curve defined by an array of points FillEllipse Fills the interior of an ellipse defined by a bounding rectangle FillPath Fills the interior of a GraphicsPath object FillPie Fills the interior of a pie section defined by an ellipse and two radial lines FillPolygon Fills the interior of a polygon defined by an array of points FillRectangle Fills the interior of a rectangle specified by a point, a width, and a height FillRectangles Fills the interiors of a series of rectangles FillRegion Fills the interior of a Region object The Fill methods use Brush objects to determine the type of fill that will occur. You can retrieve a Brush object with the help of different Brushrelated classes in the System.Drawing and System.Drawing.Drawing2D namespaces. Table 1.14 details the types of Brush-related classes that can be used. 23 24 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 1.14 Brush Classes in System.Drawing and System.Drawing.Drawing2D Namespaces Class Description Brush An abstract base class. Used to create brushes such as SolidBrush, TextureBrush, and LinearGradientBrush. These are used to fill the interiors of graphical shapes such as rectangles, pies, polygons, and paths. Brushes Has 140 static properties, one for the name of each standard color. HatchBrush Used to fill a region using one of a large number of patterns available in HatchStyle. LinearGradientBrush Used to create two-color gradients and multicolor gradients. The default is a linear gradient from one color to another along a specified line. SolidBrush Defines a brush of a single color. Brushes are used to fill graphics shapes, such as rectangles, pies, polygons, and paths. SystemBrushes A set of properties named after a Windows display element. Each of these properties returns a SolidBrush object representing the color of the display element. TextureBrush A Brush object that uses an image to fill the interior of a shape. This section discussed how to use the Graphics class to draw deviceindependent graphical elements such as text, lines, and shapes. It also discussed how to work with other key graphics elements, such as brushes, colors, and pens. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . Practice Questions Question 1 The Framework class library (FCL) enables you to access which of the following? ❍ A. Custom classes created by a particular developer ❍ B. Custom classes shared by a particular project ❍ C. Public classes common to the .NET Framework ❍ D. Private classes common to the .NET Framework Answer C is correct. The FCL includes hundreds of public classes that can be used in an application developed within the .NET Framework. Answers A and B are incorrect because the FCL contains classes common to the .NET Framework rather than custom user-created classes. Answer D is incorrect because the private classes within the FCL are inaccessible. Question 2 You want to change the font setting of a form so that all text placed on it will appear in bold. Which of the following statements would you use to set the font programmatically? ❍ A. this.Font.Bold = true; ❍ B. this.Font = new Font(this.Font, FontStyle.Bold); ❍ C. this.Font.FontStyle = FontStyle.Bold; ❍ D. this.Font = new Font(this.Font, this.Font.Bold); Answer B is correct. You cannot directly set the Bold property of a Font object because it’s a read-only property (the set accessor is not available). Therefore, the only way to set the Font object’s Bold property is by calling its constructor to create a new Font object with the desired settings. 25 26 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 3 You need to define a property named ModuleNumber. This property should be accessible only inside the same project. Which of the following access modifiers will you use to define this property? (Choose all correct answers.) ❑ A. public ❑ B. private ❑ C. protected ❑ D. internal Answer D is correct. Members defined with the internal access modifier are accessible only within the same project. Answer A is not correct because members defined with the public access modifier are globally accessible. Answer B is not correct because members defined with the private access modifier are not accessible outside their own class. Answer C is not correct because members defined with the protected access modifier are accessible by the derived classes, which can be defined within the same or different project. Question 4 You have configured a redraw handler using the Invalidate() method without providing any input parameters. What will be the result of this? ❍ A. The application will terminate at the instance of the Invalidate() method. ❍ B. The application will continue but will fail to redraw the graphic elements. ❍ C. The entire form will be redrawn. ❍ D. Only the area under the cursor will be redrawn. Answer C is correct. A call to the Invalidate() method without specifying any parameters causes the entire form to be redrawn. Answers A and B are incorrect because the Invalidate() call does not cause the application to terminate. Answer D is incorrect because the cursor location is not used by the Invalidate() method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . Question 5 Which method of the Form class must you call to remove a form and be able to open it later with the same information present? ❍ A. Exit ❍ B. Hide ❍ C. Close ❍ D. Show Answer B is correct. The Hide method allows a form to be temporarily hidden and later accessed with the information intact. Answer A is incorrect because the Form class does not contain an Exit method. Answer C is incorrect because the Close method closes a form completely, losing its current settings if it is later reopened. Answer D is incorrect because the Show method is used to reveal a form rather than to conceal it. Question 6 You are creating a drawing board application. After clicking a button that enables drawing, you are required to draw on the form as the mouse moves over the form. You have already written an event handler to handle drawing. You now want to attach the event handler to the event. Which of the following statements will you place in the Main method? ❍ A. MyForm.MouseDown += new System.Windows.Forms MouseEventHandler( DrawingForm_MouseDown); ❍ B. MyForm.MouseMove += new System.Windows.Forms. MouseEventHandler( DrawingForm_MouseMove); ❍ C. MyForm.MouseDown += DrawingForm_MouseDown; ❍ D. MyForm.MouseMove += DrawingForm_MouseMove; Answer B is correct. To attach an event handler, you should create a delegate object that stores a reference to the event handler and attach the delegate object to the event. Here, you need to attach an event handler that gets executed whenever the mouse moves; you need to attach the event handler to the MouseMove event. Answers A and C are incorrect because these statements use the MouseDown event instead of the MouseMove event. Answer 27 28 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . D is incorrect because you should create a delegate object and then attach it to the event rather than attaching the event handler directly. Question 7 Which of the following is true if your form, Form1, has been configured with an Opacity of .3, while Form2 has been configured with an Opacity of 1? ❍ A. Form1 will be displayed on top of Form2. ❍ B. Form2 will be displayed on top of Form1. ❍ C. Form1 is 30% transparent. ❍ D. Form1 is 70% transparent. ❍ E. Form2 is transparent. Answer D is correct. The opacity value is set on a form to determine how much of a covered form it will occlude. A setting of .3 opacity means that 30% of the background will be occluded, so the form is 70% transparent. Answers A and B are incorrect because the Opacity property does not dictate which form will be on top; the TopMost property provides this information. Answer C is incorrect because a 30% transparency would require an opacity of .7, while Answer E is incorrect because neither form is transparent. Form2 is completely opaque with an opacity of 1, which means that it is 100% opaque. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . Question 8 You need to draw graphical shapes such as circles, ellipses, rectangles, and pies on a Windows Form. You need to draw these shapes filled with a hatch style selected by the user. You have discovered that you have to use the HatchBrush class for a Brush object and call Fill methods of the Graphics class to draw filled shapes with a hatch style. You want to refer to these classes in your programs directly. Which of the following using directives will you include in your program to enable this? ❍ A. using System.Drawing; ❍ B. using System.Drawing.Drawing2D; ❍ C. using System.Drawing.Imaging; ❍ D. using System.Drawing.Text; Answers A and B are correct. The Graphics class resides in the System.Drawing namespace. Therefore, you need to include a using directive for this namespace to access it directly. The HatchBrush class and HatchStyle enumeration reside in System.Drawing.Drawing2D namespace. Therefore, you need to include a using directive for this namespace to access them directly. Question 9 You need to measure the size of a form. You know that the corner opposite the origin (0,0) is at location (128,164). The form has a 3-pixel-wide border and a 20-pixel-high title bar. What is the width and height of the form? ❍ A. Width: 122, height: 138 ❍ B. Width: 138, height: 122 ❍ C. Width: 128, height: 144 ❍ D. Width: 128, height: 164 29 30 Chapter . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer D is correct. The Size property specifies the overall size of the form, measured from its origin. Answer A is incorrect because it specifies only the user area of the form, excluding the borders and title bar. Answer B is incorrect because it is the measure of the user area reversed in width and height measure. Answer C is incorrect because it specifies the proper measures for the user area if the borders were 0 pixels wide. Question 10 Which of the following methods can be used to get a Graphics object for a Windows Form? ❍ A. Graphics.FromHWnd ❍ B. Graphics.FromForm ❍ C. Graphics.FromImage ❍ D. Graphics.CreateObject Answer A is correct. Graphics.Hwnd method gets a Graphics object for a Windows Form. Answer C is not correct because Graphics.FromImage method can get only the Graphics object for an image file. Answers B and D are not correct because these methods do not exist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing . . . . . . Windows . . . . . .Forms . . . Need to Know More? Albahari, Ben, Peter Drayton, and Brad Merrill. C# Essentials. O’Reilly, 2002. Petzold, Charles. Programming Windows with C#. Microsoft Press, 2001. Chappell, David. Understanding .NET. Addison-Wesley, 2001. Windows Forms Community Site: www.windowsforms.net/. Windows Forms FAQ: www.syncfusion.com/FAQ/winforms. 31 2 Controls on Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ Control ✓ Container ✓ TabIndex property ✓ TabStop property ✓ ToolTip ✓ Dialog box ✓ Menu ✓ Status bar ✓ Toolbar Techniques you’ll need to master: ✓ Experiment with the common Windows controls that are available in the Windows Forms Designer toolbox. Know their important properties, methods, and events. ✓ Know how to add controls to container objects using the Windows Forms Designer and programmatic code. ✓ Utilize the Z-order to properly sort overlapping controls. ✓ Configure the TabIndex and TabStop properties of the controls to determine the order in which controls will gain focus. ✓ Know how to handle events for Windows Forms controls. ✓ Experiment creating main menus and context menus and implement them in single-document and multidocument applications. 34 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The purpose of a user interface is to allow the user to input, view, and act upon data presented by an application. C# includes a wide variety of standard controls that can be added to a form to allow this functionality. Users can create their own custom controls and include these in their applications as well. In this chapter, we discuss the properties, methods, and events of the control types you should be familiar with before appearing for the exam. Finally, we discuss the methods of adding controls to forms, and we contrast singledocument and multidocument applications. Common Properties of Controls The Windows form inherits from the ContainerControl class. As a result, it is capable of containing other controls. The controls in the Windows form design the user interface of an application. The Windows form controls inherit from the Control class either directly or indirectly through their chain of inheritance. As a result, these controls derive some common properties, methods, and events from the Control class. As you already know from Chapter 1, “Introducing Windows Forms,” you can easily modify the properties of controls using the Properties window within the Visual Studio .NET IDE. Simply click the control to select it and then modify the values within the Properties window. The Properties window provides a rich interface that enables you to modify simple properties as well as properties that return structures and objects. You can also modify the properties of a control using code by assigning the desired value to the control’s property using the format ControlObject.Property, where ControlObject is the name of the target control and Property is the name of the property to which the new value should be assigned. The Z-order specifies the order in which controls are evaluated when layered atop one another. The control with the lowest z-axis value is considered to be on top of others with higher z-axis values. You can rapidly move a control’s z-axis location within its container by right-clicking the control and selecting Bring to Front or Send to Back from the shortcut menu. The following sections review common properties of the controls that you should know for the exam. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . Anchor When a form is resized, you might want the controls to remain anchored to a particular location on the form so that the result remains in a standard layout. The default anchor for controls is the top left of the form; as the form is resized larger, controls remain in position at the top left of the expanded form. You can change this within the Properties window, as seen in Figure 2.1. Figure 2.1 The Properties window for a control, showing the Anchor value selected with an assigned anchor at the bottom-left corner of the form. Dock The Dock property enables a control to span an entire edge (left, right, top, or bottom) of its parent control. Docking is often used with toolbars and status bars to maintain their position even as a form is resized. You can adjust this value within the Properties window, as shown in Figure 2.2. Its default value is None, meaning that a control is not docked to an edge. Enabled A control has a Boolean (true/false) value assigned to its Enabled property. This value is generally true by default, though some controls such as Timer have an Enabled value of false by default. If a control is not enabled, it appears grayed out and cannot generate events or receive focus. 35 36 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Figure 2.2 The Properties window for a control showing the Dock property selected for bottomedge docking. Font Font describes the format for presenting textual information within the control. Figure 2.3 displays the Font dialog box used to set this property. The Font dialog box can be accessed by clicking the ellipsis button (…) when you select the Font property in the Properties window. The Font property returns a Font object that contains different properties to set the desired font. You cannot programmatically change one of the properties of this Font object because Font objects cannot be modified after they are created. You must create a new Font object with the desired property settings and assign it to the Font property. Figure 2.3 The Font dialog box shows the Microsoft Sans Serif font selected in Italic mode at 12-point size. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . Location This property specifies the absolute location of the top-left corner of the control, measured in pixels from the top-left corner of the form. This value is automatically set when you place the control from the toolbox into the Windows form within Visual Studio .NET. Name The name of a control is used to manipulate the control programmatically. The default value of the Name property is an automatically generated value based on the type of control and the order in which it is placed on the form. For example, the names Label1, Label2, and Label3 refer to the first three Label controls added to a form. It is good coding practice to rename a control using a meaningful name and the three-character Hungarian naming scheme prefix to display what type of control it is. An example of this is a Label box that holds a description for the Sales form, named lblSalesDesc. Size, Height, and Width The Size property refers to a structure that contains Height and Width properties. The Size property for a new control is assigned based on the control’s DefaultSize value. It can be altered as desired to fit on the application’s form. TabIndex and TabStop The Tab key can be used to allow a user to rapidly change focus from one control to the next. The TabStop property is a Boolean (true/false) value, set to true by default that indicates whether a control receives the focus when a user is tabbing between controls. If this value is set to false, the control is skipped when the Tab key is pressed. If TabStop is set to true, the control receives focus based on its order within the other controls, established by the TabIndex value. Text The Text property is used in different ways by many types of controls. As you saw in Chapter 1, the Text property of a form is displayed in its title bar, 37 38 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . while the Text value of a label is displayed on its face. Controls such as TextBox display the Text property as an input value that can be changed. The Text property can be used to provide keyboard shortcuts using the ampersand character (&) in front of a text character, to use it as the access key for that control. For example, a button with a Text value of &Save displays the S in Save As Underlined and accepts Alt+S to cause the Click event of the control to be executed. Some controls, such as a Label control, cannot receive the focus. If an access key is assigned to a control such as this, the focus is received by the control with the next-highest TabIndex value. To display an ampersand within the Text value, as in “Texas A&M University,” you would include a double ampersand (&&), which tells the control to display the ampersand value itself. Visible The Visible property is a Boolean (true/false) value that determines whether the control is visible to the user. Set to true by default, this value affects only the visibility of the control to the user and does not prevent the control from being manipulated programmatically. If this value is set to false, the control remains visible within the Windows Forms Designer but is not visible to the end user at runtime. Common Windows Forms Controls Many controls are available for use in your Windows forms application. Most of these are derived from the System.Windows.Forms.Control class, as detailed in Figure 2.4. This section reviews properties, methods, and events of some of the common controls. If you are very familiar with the Visual Studio .NET IDE, many of these might be familiar to you already. GroupBox and Panel Like the Form control itself, some controls are meant to contain other controls to arrange or group controls together. The GroupBox and Panel controls can contain other controls. They are mostly used to arrange controls and group similar controls. The GroupBox control does not include scrollbars, but it enables you to specify a caption for the group box. The Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . control adds scrollbars to allow you to present more controls within the same panel. The Panel control does not include a caption. Table 2.1 details the important members of the GroupBox class, while Table 2.2 details those of the Panel class. Control ButtonBase ListView ScrollBar Button MonthCalendar HScrollBar CheckBox PictureBox VScrollBar RadioButton PrintPreviewControl Splitter DataGrid ProgressBar StatusBar DateTimePicker ScrollableControl TabControl GroupBox Label LinkLabel ListControl ContainerControl TextBoxBase Form RichTextBox PropertyGrid TextBox UpDownBase ToolBar ComboBox DomainUpDown TrackBar ListBox NumericUpDown TreeView CheckedListBox Panel Figure 2.4 The Controls hierarchy showing many common Windows Forms controls. Table 2.1 Important Members of the GroupBox Class Member Type Description Controls Property Collection of controls contained in the group box Text Property Caption of the group box Table 2.2 Important Members of the Panel Class Member Type Description AutoScroll Property Indicates whether scrollbars should be displayed when the display of all controls exceeds the panel’s area Controls Property Collection of controls contained in the panel GroupBox and Panel controls can be used on the same form to group other controls as desired or to allow the use of scrollbars to access a larger control 39 40 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . within a smaller area. Figure 2.5 shows the use of a Panel control to provide a scrollable area containing a larger PictureBox control displaying an image; a GroupBox control also is used here to show the file statistics for the image file by grouping several Label controls. Figure 2.5 Panel and GroupBox controls are used here in combination to display an image file and its statistics. Label and LinkLabel The Label control displays read-only data to the user, including both text and image information. The LinkLabel control extends this to include a clickable hyperlink capability that can open a Web page, an application, or a folder. Table 2.3 details the important members of the Label class, while Table 2.4 details those of the LinkLabel class. Table 2.3 Important Members of the Label Class Member Type Description Image Property Image displayed on the Label Font Property Font for the displayed text Text Property The displayed text TextAlign Property Alignment of the text on the Label (Center, Left, or Right; Bottom, Middle, or Top) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . Table 2.4 Important Members of the LinkLabel Class Member Type Description ActiveLinkColor Property Specifies the color used to display an active link. DisabledLinkColor Property Specifies the color used to display a disabled link. Links Property Gets the collection of Link objects in the LinkLabel. The Link class contains information about the hyperlink. Its LinkData property allows you to associate a URL with the hyperlink. LinkArea Property Specifies which portion of text in the LinkLabel is treated as part of the link. LinkBehavior Property Specifies how the link will appear when the mouse pointer is placed over it. LinkClicked Event The default event. It is generated when the link is clicked. Inside its event handler, the LinkLabelLinkClickedEventArgs parameter provides you with data for the event. LinkColor Property Specifies the color used to display a link. VisitedLinkColor Property Specifies the color used to display a previously visited link. TextBox and RichTextBox The TextBox and RichTextBox classes both derive from the TextBoxBase class. They allow single or multiline user input, including masked input such as that used in a password input field, where each input character is displayed simply as the masking character—typically the asterisk (*). The RichTextBox includes the capability to display formatted text using the Rich Text Format (RTF). Table 2.5 details the important members of the TextBox class, while Table 2.6 details those of the RichTextBox class. Table 2.5 Important Members of the TextBox Class Member Type Description AcceptsReturn Property Consists of a Boolean value (true/false), where true indicates that pressing the Enter key in a multiline textbox inserts a new line. CharacterCasing Property Controls the case of characters as they are entered (Lower, Normal, or Upper). The default value is Normal, which does not modify the case of entered characters. (continued) 41 42 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 2.5 Important Members of the TextBox Class (continued) Member Type Description MultiLine Property Specifies whether the TextBox can accept multiple lines of input. The default value is false. PasswordChar Property Used to display input characters with the specified mask character. Typically used to protect the display of sensitive information such as a password. The setting is null by default; if this value is not set, characters are displayed normally. ReadOnly Property Determines whether the displayed text is read-only. The control’s text cannot be edited. The default value is false. ScrollBars Property Specifies which scrollbars (none, horizontal, vertical, or both) should appear in a multiline textbox. Text Property Specifies the text contained in the textbox. TextChanged Event The default event. Occurs when the value of the control’s Text property changes. WordWrap Property Specifies whether text in a multiline control can automatically wrap words to the next line. The default value is true. Table 2.6 Important Members of the RichTextBox Class Member Type Description DetectUrls Property Specifies whether the control automatically detects and formats URLs. Rtf Property Specifies the text of the RichTextBox control, including all RTF codes. SelectionColor Property Sets the color of the currently selected text. SelectionFont Property Sets the font of the currently selected text. SelectedRtf Property Specifies the currently selected RTF text. TextChanged Event The default event. Occurs when the value of the control’s Text property changes. WordWrap Property Specifies whether the control can automatically wrap words to the next line, if required. ZoomFactor Property Gives the current zoom level. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . PictureBox The PictureBox control can display graphical images from many sources, including icon (.ICO), bitmap (.BMP), metafile (.WMF), JPEG/JPG, PNG, and GIF files. Table 2.7 details the important members of the PictureBox class. Table 2.7 Important Members of the PictureBox Class Member Type Description Click Event The default event. Occurs when the control is clicked. Image Property Is the displayed image. SizeMode Property Specifies how the image is displayed. Holds one of the PictureBoxSizeMode enumeration values—AutoSize (autosized to the image size), CenterImage (displayed in the center of the control), Normal (placed in the upper-left corner of the control), or StretchImage (stretched or reduced to fill the control). Button, RadioButton, and CheckBox When you need to obtain selection information from users, the Button, RadioButton, and CheckBox controls can be used. These derive from the ButtonBase control. The Button control is used to initiate actions when clicked, while the RadioButton and CheckBox controls are used to select an on or off state (that is, selected or not selected, and checked or unchecked). A CheckBox control can be two-state (on/off) or three-state (on/off/indeterminate), depending on the value of the ThreeState property. A group of CheckBox controls can be used to allow selection of several states, while a group of RadioButtons can be used to allow selection of one of the options listed. If you want to place two groups of RadioButton controls on a form and have each group allow one selection, you need to place them in different container controls, such as GroupBox or Panel controls, rather than placing them directly on the form. Table 2.8 details the important members of the Button class. Table 2.9 details those of the RadioButton class, and Table 2.10 details those of the CheckBox class. 43 44 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 2.8 Important Members of the Button Class Member Type Description Image Property Image displayed on the button. Text Property Text displayed on the button. Click Event The default event. Fires when the Button control is clicked. Table 2.9 Important Members of the RadioButton Class Member Type Description Checked Property Indicates whether the RadioButton is checked (true if checked, false otherwise). CheckedChanged Event Default event of RadioButton. Fires every time this control is checked or unchecked. Text Shows text displayed along with the RadioButton. Property Table 2.10 Important Members of the CheckBox Class Member Member Description Checked Property Is true if the CheckBox is checked; otherwise, is false. CheckedChanged Event Default event for the CheckBox control. Fires every time a CheckBox is checked or unchecked. CheckState Property Gives the state of the CheckBox: Checked, Unchecked, or Indeterminate. ThreeState Property Determines whether the CheckBox allows three states. If set to false, the CheckState can be set only to Indeterminate state through code but not through the user interface. Text Property Shows text displayed adjacent to the CheckBox control. AutoCheck Property—When this value is set to true (the default) on a CheckBox or RadioButton control, the control will change its Checked and CheckState values as well as the appearance of the control automatically. You can set the AutoCheck property to false and then write code in the Click event handler to have these controls behave in a different manner. ListBox and CheckedListBox The ListBox and CheckedListBox controls both derive from the ListControl class and allow selection of values from a predetermined list of options. The . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . ListBox can be configured to allow only a single selection or multiple selections from the displayed values, while the CheckedListBox control includes integrated CheckBox controls for each item and cannot be restricted to allow only a single value. Table 2.11 details the important members of the ListBox class, while Table 2.12 details those of the CheckedListBox class. Table 2.11 Important Members of the ListBox Class Member Type Description ColumnWidth Property Specifies column width in a multicolumn ListBox. ItemHeight Property Specifies the height of an item in the ListBox. Items Property Specifies a collection of objects representing the list of items in the ListBox. FindString Method Finds the first item in the ListBox that starts with the specified string. FindStringExact Method Finds the first item in the ListBox that exactly matches the specified string. MultiColumn Property Determines whether the ListBox supports multiple columns. SelectedIndex Property Gives the index of the currently selected item. SelectedIndexChanged Event The default event. Occurs when the SelectedIndex property changes. SelectedIndices Property Specifies a collection of indices of currently selected items. SelectedItem Property Shows the currently selected item. SelectedItems Property Specifies a collection of currently selected items. SelectionMode Property Specifies the number of items that can be selected. The values are specified by the SelectionMode enumeration. They can be MultiSimple (allows multiple selections), MultiExtended (allows multiple selections with the help of the Ctrl, Shift, and arrow keys), None (allows no selections—can be used to just display data), and One (allows single selection). Sorted Property Specifies whether the items are sorted alphabetically. 45 46 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 2.12 Important Members of the CheckedListBox Class Member Type Description CheckedIndices Property Is a collection of indices of currently checked items. CheckedItems Property Is a collection of currently checked items. ItemCheck Event Occurs when an item is checked or unchecked. SelectionMode Property Indicates the number of items that can be checked. The values are specified by the SelectionMode enumeration. They can be only None (no selections) or One (allows multiple selections). Figure 2.6 shows the use of a CheckBox control and a ListBox control to provide selectable lists of values. Figure 2.6 CheckBox and ListBox controls are used on the same form to display list-selection options. The SelectedIndex property in the ListBox, CheckedListBox, and ComboBox controls returns a zero-based index of the currently selected item, but if no item is selected in these controls, it returns –1. ComboBox The ComboBox control is also derived from the ListControl class and is used to allow selection of one value from a specified list or allow you to enter a new value. It combines a scrollable list of values with a text entry area that can be used to modify the selected value or to input a new value not already in the list if the control has been configured to allow this. Table 2.13 details the important members of the ComboBox class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . Table 2.13 Important Members of the ComboBox Class Member Type Description DrawMode Property Specifies how the ComboBox items are drawn. The value Normal specifies that the list of items is drawn by the system. The other two values specify that elements are drawn by your own program (preferably using the DrawItem event handler). OwnerDrawFixed specifies that elements will all be of the same size, while OwnerDrawVariable specifies a variable size. DropDownStyle Property Specifies the style of the combo box. The style can be set to one of the values of the ComboBoxStyle enumeration: DropDown (default style—you click the arrow button to display items, and the text portion is editable), DropDownList (you click the arrow button to display items, but the text portion is not editable), and Simple (no arrow button—the list and text portions are always visible and text is editable). DropDownWidth Property Specifies the width of the drop-down list portion of the combo box. Items Property Is a collection of items in the control. MaxDropDownItems Property Specifies the maximum number of items the drop-down list portion can display at a time. If the number of items is more than specified by this property, a scrollbar appears. MaxLength Property Specifies the maximum length of text allowed in the editable portion. SelectedIndex Property Gives the index of the currently selected item. SelectedIndexChanged Event The default event. Occurs when the selected index property changes. SelectedItem Property Shows the currently selected item. SelectedText Property Shows the currently selected text in the editable portion. Sorted Property Specifies whether the items are sorted alphabetically. DomainUpDown and NumericUpDown The DomainUpDown and NumericUpDown controls inherit from the System.Windows.Forms.UpDownBase class and allow selection of values 47 48 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . from an ordered list of values using the up and down buttons of the controls. If the ReadOnly value is false (the default value), values can be directly entered in the controls as well. The DomainUpDown control allows selection from a list of objects, with the result being returned as a string to the control; the NumericUpDown control contains a numeric value that can be adjusted between the Minimum and Maximum values by an amount specified by the Increment property. Table 2.14 details the important members of the DomainUpDown class, while Table 2.15 details those of the NumericUpDown class. Table 2.14 Important Members of the DomainUpDown Class Member Type Description Items Property Is the collection of objects assigned to the control. ReadOnly Property Specifies whether you can enter a value directly in the control. SelectedIndex Property Gives the index value of the currently selected item. SelectedItem Property Gives the selected value based on the selected index. SelectedItemChanged Event The default event. Occurs when the SelectedIndex property is changed. Sorted Property Determines whether the Items collection is sorted. Wrap Property Specifies whether the SelectedIndex property wraps to the first or the last item if the user continues past the end of the list. Table 2.15 Important Members of the NumericUpDown Class Member Type Description Increment Property Value of the increment used to decrease or increase the value when a button is clicked. Maximum Property Maximum allowed value. Minimum Property Minimum allowed value. ReadOnly Property Specifies whether you can change the value directly. ThousandsSeparator Property Specifies whether a thousands separator should be used when appropriate. Value Property Value assigned to the control. ValueChanged Event The default event. This event occurs when the Value property is changed. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . MonthCalendar and DateTimePicker The MonthCalendar and DateTimePicker controls allow the selection of date and time values. The MonthCalendar control includes an easily navigable user interface to select a date or a range of dates, while the DateTimePicker control allows the selection of date and time values using different formats. Figure 2.7 provides an example of the use of the MonthCalendar and DateTimePicker controls. Figure 2.7 MonthCalendar and DateTimePicker controls displaying selected values. Table 2.16 details the important members of the MonthCalendar class, while Table 2.17 details those of the DateTimePicker class. Table 2.16 Important Members of the MonthCalendar Class Member Type Description CalendarDimensions Property Number of columns and rows of months displayed. DateChanged Event The default event. This event occurs when the date selected in the control changes. DateSelected Event Event that occurs when a date is selected in the control. FirstDayOfWeek Property The first day of week displayed by the calendar. MaxDate Property Maximum allowable date to be selected. MaxSelectionCount Property Maximum number of days that can be selected. MinDate Property Minimum allowable date to be selected. SelectionEnd Property End date of the selected range. SelectionRange Property Selected range of dates. SelectionStart Property Start date of the selected range. (continued) 49 50 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 2.16 Important Members of the MonthCalendar Class (continued) Member Type Description ShowToday Property Whether today’s date should be displayed at the bottom of the control. ShowTodayCircle Property Whether today’s date should be circled. ShowWeekNumbers Property Whether the week numbers (1–52) should be displayed at the beginning of each row of days. TodayDate Property Represents today’s date. Table 2.17 Important Members of the DateTimePicker Class Member Type Description CustomFormat Property Represents a custom date and time format string. Format Property Specifies the format of the date and time displayed in the control. The values are specified by the DateTimePickerFormat enumeration—Custom, Long (the default), Short, and Time. Long, Short, and Time display the date in the value formats set by the operating system. Custom lets you specify your own custom format. FormatChanged Event Occurs when the Format property changes. MaxDate Property Gives the maximum allowable date and time to be selected. MinDate Property Gives the minimum allowable date and time to be selected. ShowCheckBox Property Specifies whether a check box should be displayed at the left of the selected date. ShowUpDown Property Specifies whether an up-down control should be displayed to allow user selections rather than the default calendar control. Value Property Gives the value of the date and time selected. ValueChanged Event The default event. Occurs when the value changes. TreeView and ListView The TreeView and ListView controls allow the display of hierarchical collections of nodes. Within the TreeView control, nodes are represented by TreeNode objects, each of which has its own collection of child nodes. The ListView control includes a list of items, each of which can have a name, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . icon, and additional columns of associated text. Figure 2.8 provides an example of the use of the TreeView and ListView controls. Figure 2.8 TreeView and ListView controls used to display a simple folder hierarchy and objects contained within the selected folder. Table 2.18 details the important members of the TreeView class, and Table 2.19 details those of the ListView class. Table 2.18 Important Members of the TreeView Class Member Type Description AfterCheck Event Occurs after a tree node is checked. AfterCollapse Event Occurs after a tree node is collapsed. AfterExpand Event Occurs after a tree node is expanded. AfterSelect Event The default event. Occurs after a tree node is selected. CheckBoxes Property Specifies whether a check box should appear along with each item in the control. ImageList Property Represents the ImageList that contains node icons. Nodes Property Specifies a collection of TreeNodes in the control. Scrollable Property Specifies whether scrollbars should be displayed when needed. The default value is true. SelectedNode Property Shows the currently selected node. Sorted Property Specifies whether the tree nodes are sorted. Table 2.19 Important Members of the ListView Class Member Type Description Activation Property Indicates how an item can be activated— OneClick (single click), Standard (double click), and TwoClick (double click and item color change when the mouse hovers over it). These values are defined in the ItemActivation enumeration. (continued) 51 52 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 2.19 Important Members of the ListView Class (continued) Member Type Description CheckBoxes Property Specifies whether a check box should appear along with each item in the control. CheckedIndices Property Specifies a collection of indices of the currently checked items. CheckedItems Property Specifies a collection of currently checked items. ItemActivate Event Occurs when an item is activated. ItemCheck Event Occurs when an item’s check state changes. Items Property Specifies a collection of items displayed by the ListView control. LargeImageList Property Represents the ImageList to be used to display large icons. MultiSelect Property Specifies whether multiple items can be selected. Scrollable Property Specifies whether scrollbars need to be added when the list of items exceeds the size of the client area. Default value is true. SelectedIndexChanged Event The default event. Occurs when the selected index changes. SelectedIndices Property Specifies a collection of indices of the currently selected items. SelectedItems Property Specifies a collection of currently selected items. SmallImageList Property Represents the ImageList to be used to display small icons. Sorting Property Specifies the sort order of items in the control, from SortOrder enumeration—Ascending, Descending, or None (default). View Property Represents the way items are displayed. The values are specified by the View enumeration— Details (items are displayed with multicolumn information about the item), LargeIcon (default value—the item appears with a large icon and a label below it in multicolumns), List (a singlecolumn list with small icons displayed with a label to the right), and SmallIcon (a small icon with a label on the right displayed in multicolumns). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . Timer, TrackBar, and ProgressBar Several progress-related controls are important to know well. The Timer control is used when an event needs to occur after a particular interval. This method is preferred for handling timer requirements within a form, rather than using the System.Timers.Timer, which fires from another thread and can cause unpredictable results. Table 2.20 details the important members of the Timer class. Table 2.20 Important Members of the Timer Class Member Type Description Enabled Property Indicates whether the timer is currently running Interval Property Gives the time in milliseconds between Tick events of the timer Start Method Starts the Timer control Stop Method Stops the Timer control Tick Event Occurs when the timer interval elapses and the timer is enabled The TrackBar control is used to allow a user to select a value from a range by sliding the scrollbar along the displayed scale, while the ProgressBar control is used to display progress during a lengthy operation. Figure 2.9 provides an example of the use of the TrackBar and ProgressBar controls. Figure 2.9 TrackBar and ProgressBar controls display progress and slide-bar selection. Table 2.21 details the important members of the TrackBar class, while Table 2.22 details those of the ProgressBar class. 53 54 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 2.21 Important Members of TrackBar Class Member Type Description LargeChange Property Specifies the number of units the Value property changes when the scroll box is moved a large distance. Maximum Property Specifies the upper bound of the TrackBar control’s range. Minimum Property Specifies the lower bound of the TrackBar control’s range. Orientation Property Specifies the orientation of the control (Horizontal or Vertical). Scroll Event The default event. Occurs when the scroll box is moved by a keyboard or mouse action. SmallChange Property Specifies the number of units the Value property changes when the scroll box is moved a small distance. TickFrequency Property Specifies the frequency within which scale ticks are drawn in the control. TickStyle Property Specifies the way in which the control appears. The values are specified by the TickStyle enumeration—Both, BottomRight, None, or TopLeft. Value Property The scroll box’s current position in the control. ValueChanged Property Occurs when the Value property changes. Table 2.22 Important Members of the ProgressBar Class Member Type Description Maximum Property Upper limit of the Value property Minimum Property Lower limit of the Value property Value Property The current position of the control HScrollBar and VScrollBar The HScrollBar and VScrollBar controls are members of the ScrollBar class and are used in combination with other controls, such as the PictureBox control, to provide basic scrolling capability. Table 2.23 details the important members of the ScrollBar class from which the HScrollBar and VScrollBar controls inherit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . Table 2.23 Important Members of ScrollBar Class Member Type Description LargeChange Property Specifies the amount the Value property changes when the scroll box is moved a large distance. Maximum Property Specifies the upper bound of the Value property. Minimum Property Specifies the lower bound of the Value property. Scroll Event The default event. Occurs when the scroll box is moved by a keyboard or mouse action. SmallChange Property Specifies the amount the Value property changes when the scroll box is moved a small distance. Value Property Specifies the current position of the control. ValueChanged Event Occurs when the Value property changes. TabControl The TabControl can contain other controls, arranged on tabbed pages. This control is useful in organizing large numbers of controls within a manageable format. Visual Studio itself relies on a tabbed display format. Table 2.24 details the important members of the TabControl class. Table 2.24 Important Members of the TabControl Class Member Type Description Alignment Property The area where the tabs will be aligned: Bottom, Left, Right, or Top (default). ImageList Property The ImageList from which images are displayed on tabs. MultiLine Property Whether tabs can be displayed in multiple rows. SelectedIndex Property The index of the selected tab page. SelectedIndexChanged Event Default event. This event occurs when the selected index changes. SelectedTab Property The selected tab page. TabCount Property Count of tabs in the control. TabPages Property Collection of tab pages in the control. 55 56 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ToolTip A ToolTip is a feature that allows an application to provide useful information about a control when the user hovers the cursor over the control. Some controls, such as StatusBarPanel, ToolBarButton, and TabPage, have a ToolTipText property. For other controls, you must add a ToolTip component in the container object. For each control, you will find a new property named ToolTip on ComponentName, where ComponentName is the name of the ToolTip component that you added to the container previously. Entering the ToolTip message into this property’s value provides the ToolTip functionality needed for each control. Dialog Boxes When an application needs to prompt a user for input, a dialog box is often used. Several dialog box components are provided within the Windows Forms library, or you can create a custom dialog box, if necessary. Common Dialog Boxes The Windows Forms library provides several ready-made dialog boxes for Windows applications, including the following: ➤ ColorDialog—Displays a list of colors and returns a property contain- ing the selected color ➤ FontDialog—Enables the user to select a font and set its properties, such as size, style, and special effects ➤ OpenFileDialog—Enables the user to browse files and folders on the computer and select one or more files ➤ PageSetupDialog—Enables the user to select various page-layout settings ➤ PrintDialog—Enables the user to select various print options and sends the specified document to the selected printer ➤ PrintPreviewDialog—Enables the user to preview a file before printing ➤ SaveFileDialog—Enables the user to browse the files and folders on the computer and select a name for a file to be saved . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . These classes are also referred to as Windows Forms dialog components. You will recognize many of these from your experience with the Windows operating system and Microsoft products such as the Office suite. The dialog classes are derived from the CommonDialog class, which provides the basic functionality for displaying a dialog box. The dialog classes each provide a method named ShowDialog that presents the dialog box. Each of the dialog classes has a set of properties that stores the data relevant to its particular type. Modal and Modeless Dialog Boxes When a modal dialog box is open, the application can only receive input for the modal dialog box, and the code that called the box remains suspended. If a user wants to work with other windows in the application, the modal dialog box first must be closed. By contrast, a modeless dialog box allows the application to receive input for other windows while the dialog box remains open. When using the ShowDialog method of the Form class, a modal dialog box is displayed. If you would like to display a modeless dialog box, use the Show method instead. Menus To provide functionality within your application that spans a broader scope than a single control within the form, Visual Studio .NET includes the capability to specify several types of menu and display status bars and toolbars. Creating Menus and Menu Items Menus are used to group commonly available and less used functions into a user-friendly format. The MainMenu, ContextMenu, and MenuItem classes are all derived from the Menu class. There can be only a single MainMenu for a Windows form. A ContextMenu can be associated with each control, if desired, to provide commands or information related to the control. Table 2.25 details the important members of the MenuItem class. 57 58 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 2.25 Important Members of the MenuItem Class Member Type Description Checked Property Specifies whether a checkmark or radio button should appear near the MenuItem. Click Event Fired when the user clicks on the MenuItem. DrawItem Event Occurs when a request is made to draw an owner-drawn menu item. DrawItem occurs only when the OwnerDraw property is true. Enabled Property Specifies whether the MenuItem is enabled. MenuItems Property Gives the collection of MenuItem objects associated with a menu. This property can be used to create hierarchical submenus. OwnerDraw Property Specifies whether you can provide custom code to draw a MenuItem instead of allowing Windows to handle it in a standard way. Parent Property The parent menu with which the menu item is associated. You must specify a parent for a MenuItem object; otherwise, it is not displayed. PerformClick Method Fires the Click event for the MenuItem as if the user clicked it. Popup Event Occurs just before displaying a submenu corresponding to this MenuItem. This event handler is generally used to add, remove, enable, disable, check, or uncheck menu items depending on the state of an application when they are displayed. RadioCheck Property Specifies whether the MenuItem should display a radio button instead of a check mark when its Checked property is set to true. Select Event Fired when the user selects a MenuItem by navigating to it. Shortcut Property Represents the shortcut key combination associated with this MenuItem. Text Property Specifies the caption of the MenuItem. StatusBar The StatusBar control is typically used to display information such as a message to the user or application status messages. You might be familiar with the Windows taskbar, which is similar to a StatusBar for your operating system. By convention, StatusBar controls are typically docked along the bottom edge of a form and are used to provide information and feedback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . useful to the user. If you set the Z-order of the StatusBar control to Send to Back, the control will not overlap other controls at the bottom of the form. One of the most important properties of a StatusBar is the Panels property, which is a collection of StatusBarPanel objects that can be used to divide the StatusBar into multiple functional areas. For example, one might display the current editing status while another displays the date and time. Table 2.26 details the important members of the StatusBarPanel class. Table 2.26 Important Members of the StatusBarPanel Class Member Type Description Alignment Property Specifies the alignment of the text and icon within the panel: Center, Left, or Right. AutoSize Property Specifies how the panel will size itself. Values are None, Contents, and Spring from the StatusBarPanelAutosize enumeration. BorderStyle Property Specifies the border style to be used: None, Raised, or Sunken. Icon Property Displayed in the StatusBar, always to the left of the text. Style Property Specifies whether the StatusBarPanel object is OwnerDraw or Text (System-drawn). The OwnerDraw style can be used to give custom rendering to a StatusBarPanel object. ToolTipText Property Specifies the ToolTip. ToolBar The ToolBar control is usually docked at the top of a form just below its menu bar. Each ToolBar control is typically used to group tools of a similar function together, such as text-editing and formatting tools or image-editing tools. If you use Microsoft’s Office suite of products, you are likely very familiar with ToolBar controls. If you set the Z-order of the ToolBar control to Send to Back, the control will not block other controls at the top of the form. Table 2.27 details the important members of the StatusBarPanel class. Table 2.27 Important Members of the ToolBar Class Member Type Description Buttons Property Is a collection of ToolBarButton objects. Each ToolbarButton represents a button on the ToolBar object. ButtonClick Event Fires when a ToolBarButton is clicked. (continued) 59 60 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 2.27 Important Members of the ToolBar Class (continued) Member Type Description ImageList Property Stores icons that will be displayed on ToolBarButton objects. SendToBack Method Sends the toolbar to the back of the Z-order. ShowToolTips Property Specifies whether the toolbar should show ToolTips. Single- and Multiple-Document Interface Applications Small applications might well reside within a single window, but as applications become larger and more robust, you might find it necessary to create a Multiple-Document Interface (MDI) application capable of opening several windows at once. The main application window of an MDI application is referred to as the parent window; it is able to open several child windows. Windows Forms in an MDI application are created using the System.Windows.Forms.Form class. You need to know the following main points about an MDI application: ➤ The child windows are limited to their parent window. You cannot move child windows outside the main application window. ➤ The parent window can open several types of child windows. ➤ Child windows can be opened, closed, maximized, or minimized inde- pendently of each other. When the parent window is closed, the child windows are automatically closed. ➤ The MDI frame should have a menu. One common menu in an MDI application is the Window menu, which allows a user to manipulate windows opened in the MDI container (parent) form. To create an MDI parent form, create a Windows Form and change its IsMdiContainer property to true. To create an MDI parent form, you create a regular Windows form and change its IsMdiContainer property to true. To create an MDI child form, you create a regular Windows form and programmatically assign the name of the parent MDI object to the MdiParent property. Table 2.28 summarizes the important members of the Form class related to the MDI forms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . Table 2.28 Important Members of the Form Class Related to MDI Applications Member Type Description ActiveMdiChild Property The currently active MDI child window IsMdiContainer Property Specifies whether the form is a container for MDI child forms MdiChildActivate Event Fires when an MDI child form is activated or closed within an MDI application MdiChildren Property An array of forms representing the MDI child form of the parent form MdiParent Property Specifies the MDI parent form for the current form LayoutMdi Method Arranges the MDI child forms within an MDI parent Adding Controls to Forms Within the Visual Studio .NET Forms Designer, controls can be placed on the surface of any container object, such as Windows Forms, or controls such as Panel, GroupBox, or TabControl. You also can add controls to a form programmatically. When creating controls programmatically, you must remember to associate them with a parent container control. If you don’t do this, controls will be created but not displayed. Adding Controls with the Windows Forms Designer Within the Forms Designer interface, you can drag and drop controls from the toolbox or using the View menu. Figure 2.10 shows this toolbox. From the toolbox, there are three different ways to add controls to a container object: ➤ Adding controls to forms: method 1—In the first method, you can select a control from the toolbox and draw it on the container surface by following these steps: 1. Select a control by clicking the control’s icon in the Toolbox win- dow (see Figure 2.10). 61 62 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Figure 2.10 Controls toolbox. 2. Release the mouse button and move the mouse pointer to the posi- tion on the container where you want to draw the control. 3. Hold down the mouse button and draw a rectangle on the contain- er surface to indicate the size and position for the control instance. ➤ Adding controls to forms: method 2—With the second method, you drag the control directly from the toolbox to the desired location on the form. Follow these steps: 1. Select a form or other container control in which you want to add a control. 2. Drag the control’s icon from the toolbox and drop it at the desired location on the container control. The control is added with its default size. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . ➤ Adding controls to forms: method 3—With the third method, you can add the control to the form by double-clicking in the Toolbox. Follow these steps: 1. Select a form or other container control in which you want to add a control. 2. Double-click the control’s icon in the toolbox. This adds the con- trol to the top-left corner of the form or other container control in its default size. You can later use the mouse or properties of the control to modify its position and size. Adding Controls Programmatically You can add controls to a container object programmatically. When doing so, you should remember to add code to take care of three things: 1. Create a private variable to represent each of the controls you want to place on form. 2. In the form’s constructor, place code to instantiate each control and to customize each by using its properties, methods, or events. 3. Add each control to the form’s control collection. When creating controls programmatically, you should also specify the location and size of the controls numerically. You can add a control to a Windows Form programmatically by following these steps: 1. Add a new Windows Form to your C# project. 2. Switch to Code view and add the following variables just above the form’s constructor code: //create variables to hold controls private Label lblName, lblPassword; private TextBox txtName, txtPassword; private Button btnLogin; 3. Add the following code to the form’s constructor: //specify the form’s size this.ClientSize = new System.Drawing.Size(272, 182); //set up the label for prompting Name lblName = new Label(); lblName.Text = “Name: “; //Specify the location for proper placement 63 64 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . //the default location will be (0, 0) otherwise lblName.Location = new Point(16, 16); //set up label for prompting Password lblPassword = new Label(); lblPassword.Text = “Password: “; lblPassword.Location = new Point(16, 80); //setup a text box that allows user to enter Name txtName = new TextBox(); txtName.Location = new Point(152, 16); //setup text box for entering password txtPassword = new TextBox(); txtPassword.Location = new Point(152, 80); txtPassword.PasswordChar = ‘*’; //set up a command button btnLogin = new Button(); btnLogin.Text = “Login”; btnLogin.Location = new Point(96, 128); //Add control to the form //Method 1: Specify the current form as parent container for a control lblName.Parent = this; //Method 2: Add a control to form’s control collection this.Controls.Add(txtName); //Method 3: Add an array of controls to form’s control collection this.Controls.AddRange(new Control[] {lblPassword, txtPassword, btnLogin}); 4. Insert the Main method to launch this form and set the form as the startup object for the project. 5. Run the project. The form is displayed as shown in Figure 2.11. Figure 2.11 A form with controls loaded programmatically. The examples in this section add controls to a Windows Form, but the same concepts will work with any of the container controls. A container control has a property named Controls, which is a collection of Control objects that the container control contains. When you add or remove a control to a container, it is added to or removed from the container’s Controls collection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . Practice Questions Question 1 Which of the following are container controls? (Choose all correct answers.) ❑ A. Windows Form ❑ B. Label ❑ C. Panel ❑ D. RadioButton ❑ E. GroupBox Answers A, C, and E are correct. The Windows Form is itself both a container and a control, as are the Panel and GroupBox controls. Answer B is incorrect because the Label control is a read-only control used to display text. Answer D is incorrect because a RadioButton control is a check box–like control used to allow a user to select only one of several items. Question 2 You want to prevent a TextBox control from receiving the focus through user tabbing and to not accept changes to its stored value if a user clicks it. What action or actions should you take to complete this task using the least amount of effort? (Choose all correct answers.) ❑ A. Change the TextBox’s Z-order using Send to Back. ❑ B. Set the TextBox’s Enabled value to false. ❑ C. Set the TextBox’s TabIndex value to 1. ❑ D. Set the TextBox’s TabStop value to false. ❑ E. Set the TextBox’s Visible value to false. Answer B is correct. By setting the control’s Enabled value to false, it will be grayed out, will not receive the focus, and cannot be changed by the user. This single action is the simplest solution to the requirement. Answer A is incorrect because the Z-order will not affect its ability to be selected through tabbing or direct clicking. Answer C is incorrect because setting the TabIndex to any value simply affects the order in which it receives the focus. Answers D and E are potentially correct because setting the TabStop to false prevents it receiving focus through tabbing; if the Visible value is set to false, it will not be directly accessible to the user. However, this solution is not the simplest and thus is incorrect. 65 66 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 3 You are using a CheckedListBox control in one of the Windows forms of an application. You want to allow the user to select multiple items from the CheckedListBox control. What value of the SelectionMode property would you choose? ❍ A. SelectionMode.None ❍ B. SelectionMode.One ❍ C. SelectionMode.MultiSimple ❍ D. SelectionMode.MultiExtended Answer B is correct. The CheckedListBox control supports only two values for the SelectionMode property: SelectionMode.None, which does not allow any selection, and SelectionMode.One, which allows multiple selections. If the other two selection modes are set through the Properties window, the IDE generates an error message; if the modes are set programmatically, an ArgumentException error is raised. Question 4 You want to use a container control that allows scrolling around a large area. Which of the following controls is best suited to this? (Select one from the following.) ❍ A. StatusBar ❍ B. Label ❍ C. Panel ❍ D. RadioButton ❍ E. GroupBox Answer C is correct. The Panel control is a container control used for grouping other controls, which includes scrollable bars to allow navigation over a large control area. Answers A, B, and D are incorrect because they are not container controls. Answer E is incorrect because the GroupBox control has a caption but is not scrollable to navigate a larger control area. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . Question 5 Which of the following image types are supported by the PictureBox control? (Choose all correct answers.) ❑ A. ICO ❑ B. BMP ❑ C. WMF ❑ D. JPEG ❑ E. PNG ❑ F. GIF Answers A, B, C, D, E, and F are all correct. The PictureBox control can be used to display graphic images of the icon (ICO), bitmap (BMP), metafile (WMF), JPEG, PNG, and GIF image formats. Question 6 You want to create a form that will display the objects located within a folder when a button is clicked to populate the listing control. Which control is best suited to this type of display? (Select one of the following.) ❍ A. GroupBox ❍ B. ListBox ❍ C. ComboBox ❍ D. TreeView ❍ E. ListView Answer E is correct. The ListView control is best suited to the display of a list of objects such as the contents of a folder. Answer A is incorrect because the GroupBox is better suited as a container object holding other controls. Answers B and C are more suited to displaying a list of values than displaying a folder’s contents. Answer D is incorrect because the hierarchical capability of the TreeView control is unnecessary here. 67 68 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 7 You are designing a menu that has some mutually exclusive options. You have set the RadioCheck properties of all the menu items to true and their OwnerDraw properties to false. Still, you are able to check multiple items from the menu when you run the program. Which of the following events would you program to set mutual exclusion among menu items? ❍ A. Click ❍ B. Select ❍ C. Popup ❍ D. DrawItem Answer C is correct. The Popup event occurs just before a menu’s list of items is displayed. You can use this event to check or uncheck menu items. Remember that setting the RadioCheck property to true does not implicitly set mutual exclusion for menu items; you still can check several of them together. So, the Popup event is the right place to check the appropriate item and uncheck all others. Question 8 You have decided to utilize a Dialog Box to allow a user to view print settings. Which of the following types of Dialog Box is best suited to this? (Select one of the following.) ❍ A. ColorDialog ❍ B. PageSetupDialog ❍ C. PrintDialog ❍ D. PrintPreviewDialog ❍ E. PrintSettingsDialog Answer C is correct. The PrintDialog box is used to select various print options and send a document to a printer. Answer A is incorrect because the ColorDialog box is used to select and return a particular color value. Answer B is incorrect because the PageSetupDialog box is used to select page layout settings. Answer D is incorrect because the specification is for viewing the print settings rather than a print preview of the document. Answer E is incorrect because there is no standard dialog box of the PrintSettingsDialog type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controls . . . . . on . .Forms . . . Question 9 Which of the following overlapping controls would be shown on top of the others? (Select one of the following.) ❍ A. Control1, z-index 25 ❍ B. Control2, z-index 5 ❍ C. Control3, z-index 15 ❍ D. Control4, z-index 50 ❍ E. Control5, z-index 99 Answer B is correct. The lowest z-index value specifies the control that will be on top when multiple controls overlap. Answers A, C, D, and E are incorrect because they all specify z-axis values that are higher and thus will be layered below Control2. Question 10 Which of the following control types can support a tristate value? (Choose all correct answers.) ❑ A. Button ❑ B. RadioButton ❑ C. CheckBox ❑ D. ListBox ❑ E. CheckedListBox ❑ F. ComboBox Answer C is correct. Only the CheckBox control is intended to include a three-state value (checked, unchecked, or indeterminate). Answer A is incorrect because the Button control is used to enact an action when selected. Answer B is incorrect because a RadioButton control is used to select only one of several values, but it is not limited to only three. Answers D and E are incorrect because the ListBox and CheckedListBox controls are used to select multiple values from a list. Answer F is incorrect because the ComboBox control is used to select one value from a list of options or to input a new value. 69 70 Chapter . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Need to Know More? Amit Kalani. MCAD/MCSD Training Guide: Developing and Implementing Windows-Based Applications with Microsoft Visual C# .NET and Microsoft Visual Studio .NET, Exam 70-316. Que Certification, 2003. Charles Petzold. Programming Windows with C#. Microsoft Press, 2001. Windows Forms Community site: www.windowsforms.net. 3 Handling Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ Exception ✓ try block ✓ catch block ✓ finally block ✓ throw statement ✓ Validation ✓ Validating event ✓ ErrorProvider component Techniques you’ll need to master: ✓ Know the default application behavior that occurs when an unhandled exception is encountered. ✓ Understand the use of try, catch, and finally code blocks. ✓ Understand the different techniques of user input validation. 72 Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . This chapter discusses exceptions, which appear as an outcome of unexpected problems during the normal execution of a program. The chapter focuses on how to handle such exceptional situations with the help of try, catch, and finally blocks. You will also learn how to handle unhandled exceptions at the level of application domain. We also discuss the different user input validation techniques and cover how to use the ErrorProvider component to display error messages. Understanding Exceptions When an application encounters an unexpected situation such as a missing file or input parameter, or a logical error such as performing a division by zero, the application generates exceptions. By default, when an exception is generated, the application terminates and generates an error display such as the one shown in Figure 3.1. Figure 3.1 This is an example error message, caused when an application commits a logical error, such as attempting to divide by zero. Unhandled exceptions in an application can result in unexpected termination and lost data, and potentially even can create security holes if input values are not properly restricted. Visual C# .NET helps you fire and handle exceptions with the help of try, catch, finally, and throw statements. The Framework Class Library (FCL) includes a large set of exception classes for dealing with various unforeseen conditions in the normal execution environment. The .NET Framework provides two exception classes that derive from the common Exception class: ➤ ApplicationException—Exceptions thrown by the application ➤ SystemException—Exceptions thrown by the CLR Both of these child exception classes enjoy the same properties and are differentiated only in the source of the exception they represent. Table 3.1 details some of the important properties of the Exception class, inherited by the exception classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Handling . . . . . Exceptions . . . . . . Table 3.1 Important Properties of the Exception Class Property Description HelpLink The URL for a help file associated with the current exception. InnerException An exception associated with the current exception. This is helpful when a series of exceptions are involved. Each new exception can preserve the information about the previous exception by storing it in this property. Message A message explaining the error and possibly offering ways to resolve it. Source The name of the application that caused the error. StackTrace Retrieves the current stack trace information. You can use this information to locate where an error has occurred. If debugging information is available, the stack trace includes the source file and program line number. TargetSite The method that threw the exception. Handling Exceptions One of the most fundamental and often most complex tasks of a developer is to design exception-handling procedures to allow an application to recover gracefully from an unexpected or disallowed condition. The .NET Framework allows exception handling to be performed across languages, across multiple computers, and even across the Component Object Model (COM) and other legacy solutions. Within C#, the most common methods of exception handling involve the try, catch, and finally blocks, in addition to the throw statement. try, catch, and finally blocks must be consecutive within code. You cannot have any intervening code separating these blocks when configuring event-handling solutions within your code. try Block When processing code that might generate an exception, the code can be placed within a try block, which, in turn, must be followed by one or more catch blocks or a finally block. Exceptions raised cause the CLR to search for the nearest try block (which can be nested within one another) and then pass control to the following catch block, or on to the finally block if no catch block is present in the code. 73 74 Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A try block in its most basic form looks like this: try { //code that may cause exception } Any normal code can be placed within the try block, including another try block or calls to methods that include try blocks of their own. When an exception occurs, the CLR finds the nearest try block and passes control to the following associated exception-handling blocks. A try block must be followed by one or more catch blocks or by a finally block. catch Blocks After an exception is encountered within a try block, control is passed to the following catch blocks or to the finally block. catch blocks are evaluated in order until a match to the exception type is made. The catch blocks should be arranged in order from specific to more general types of the exception. For example, a DivideByZeroException might match a DivideByZeroException, ArithmeticException, SystemException, or Exception catch block. In the case of multiple catch blocks, only the first matching catch block is executed. All other catch blocks are ignored. If no matching catch block can be found, the exception is passed back to the code that raised the exception and is considered an unhandled exception. This is discussed in greater detail later in this chapter. The default behavior for an unhandled exception is to cause the program to terminate with an error message. Listing 3.1 shows an example of a try-catch block in use. Listing 3.1 try-catch Block in Use private void btnCalculate_Click(object sender, System.EventArgs e) { //put all the code that may require graceful error recovery //in a try block try { . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Handling . . . . . Exceptions . . . . . . Listing 3.1 try-catch Block in Use (continued) decimal decMiles = Convert.ToDecimal(txtMiles.Text); decimal decGallons = Convert.ToDecimal(txtGallons.Text); decimal decEfficiency = decMiles/decGallons; txtEfficiency.Text = String.Format(“{0:n}”, decEfficiency); } // try block should at least have one catch or a finally block // catch block should be in arranged in order of specific to // the generalized exceptions; // otherwise, compiler generates an error catch (FormatException fe) { string msg = String.Format( “Message: {0}\n Stack Trace:\n {1}”, fe.Message, fe.StackTrace); MessageBox.Show(msg, fe.GetType().ToString()); } catch (DivideByZeroException dbze) { string msg = String.Format(“Message: {0}\n Stack Trace:\n {1}”, dbze.Message, dbze.StackTrace); MessageBox.Show(msg, dbze.GetType().ToString()); } //catches all CLS-compliant exceptions catch(Exception ex) { string msg = String.Format(“Message: {0}\n Stack Trace:\n {1}”, ex.Message, ex.StackTrace); MessageBox.Show(msg, ex.GetType().ToString()); } //catches all other exception including the //NON-CLS compliant exceptions catch { //just rethrow the exception to the caller throw; } } Here, an exception raised within the code is thrown to the catch blocks to see if a match is made. When this code is compiled and run, an input zero value will be caught by the second catch block that catches exceptions of type DivideByZeroException, a non-numeric value will be caught by the first catch block that catches exceptions of type FormatException, or a very large numeric value will be caught by the third catch block that catches exceptions of type Exception from which the OverflowException derives. All languages that follow the Common Language Specification (CLS) generate an exception type that derives from System.Exception. Therefore, the catch block that catches exceptions of type Exception will be capable of catching all the exceptions generated by CLS-compliant languages. The final catch block in the code example is included to handle exceptions generated by non–CLS-compliant languages. An unspecified catch block is the most general form of catch possible and should always be the last catch 75 76 Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . block if multiple catch blocks are present. The inclusion of the most general catch block prevents an unhandled exception. When the exceptions are caught, they will not cause the program to terminate. Visual C# .NET provides you with checked and unchecked keywords that can be used to enclose a block of statements—for example, checked {a = c/d};—or as an operator when you supply it parameters enclosed in parentheses—for example, unchecked(c/d). The checked keyword enforces checking of an arithmetic operation for overflow exceptions. If constant values are involved, they are checked for overflow at compile time. The unchecked keyword suppresses overflow checking and does not raise any OverflowException. If any operation results in an overflow while using unchecked, its value is truncated and the result is returned. finally Block The finally block includes code that will run whether or not an exception is raised. This is a good location for cleanup code that closes open files or disconnects database connections to release held resources. The following is an example of code that includes a finally block: private void btnSave_Click(object sender, System.EventArgs e) { //a StreamWriter writes characters to a stream StreamWriter sw = null; try { sw = new StreamWriter(txtFileName.Text); //Attempt to write the textbox contents in a file foreach(string line in txtText.Lines) sw.WriteLine(line); //This line only executes if there were no exceptions so far MessageBox.Show(“Contents written, without any exceptions”); } //catches all CLS-compliant exceptions catch(Exception ex) { string msg = String.Format(“Message: {0}\n Stack Trace:\n {1}”, ex.Message, ex.StackTrace); MessageBox.Show(msg, ex.GetType().ToString()); goto end; } // finally block is always executed to make sure that the // resources get closed whether or not the exception occurs. // Even if there is any goto statement in a catch or try block the // finally block is first executed before the control // goes to the goto label finally { if (sw != null) sw.Close(); MessageBox.Show( “finally block always executes whether or not exception occurs”); } end: MessageBox.Show(“Control is at label: end”); } . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Handling . . . . . Exceptions . . . . . . The finally block can also be used in conjunction with a try block, without any catch blocks. Exceptions raised are returned as unhandled exceptions in this case. An example of the simplest form of this follows: try { //Write code to allocate some resources } finally { //Write code to Dispose all allocated resources } This usage ensures that allocated resources are properly disposed whether the exception occurs. In fact, C# provides a using statement that does the same job, but with less code. A typical use of the using statement is as follows: // Write code to allocate some resource. // List the allocate resources in a comma-separated list // inside the parentheses, with the following using block using(...) { // use the allocated resource } // Here, the Dispose method is called for all the objects referenced // in the parentheses of the using statement. // There is no need to write any additional code It is possible to programmatically throw exceptions within the finally block using the throw statement, but this is a bad practice because there might already be unhandled exceptions waiting to be handled. try, catch, and finally blocks must be consecutive within code. You cannot have any intervening code separating these blocks when configuring event-handling solutions within your code. The throw Statement The throw statement can be used to explicitly throw an exception within your code. This can be used to rethrow a caught exception after performing a task such as generating an event log entry or sending an email notification of the exception. Or, it can be used to raise a custom exception explicitly defined within your code. Throwing an exception is a costly operation and, if carelessly used, can potentially slow down your application. You should throw exceptions with caution and only when essential. You should avoid throwing exceptions for regular control transfer. 77 78 Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . An example of the throw statement being used to rethrow a caught exception looks like this in its simplest form: catch(Exception e) { //TODO: Add code to create an entry in event log throw; } You can also use the throw statement to throw explicitly created exceptions (that contain a custom error message), as shown here: string strMessage = “EndDate should be greater than the StartDate”; ArgumentOutOfRangeException newException = new ArgumentOutOfRangeException(strMessage); throw newException; Creating Custom Exceptions The .NET Framework CLR includes many standard exception types, but occasionally it is necessary or desirable to create a custom exception to address a specific need within your code. This should be done only if there is not already an existing exception class that satisfies your requirements. While creating a new custom exception class, Microsoft recommends that you consider the following guidelines: ➤ Derive all programmer-defined custom exception classes from the System.ApplicationException class. ➤ End the name of your custom exception class with the word Exception (for example, MyOwnCustomException). ➤ Implement three constructors with the signatures shown in the follow- ing code: public class MyOwnCustomException : ApplicationException { // Default constructor public MyOwnCustomException () { } // Constructor accepting a single string message public MyOwnCustomException (string message) : base(message) { } // Constructor accepting a string message and an inner exception // that will be wrapped by this custom exception class public MyOwnCustomException(string message, Exception inner) : base(message, inner) { } } . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Handling . . . . . Exceptions . . . . . . Managing Unhandled Exceptions The AppDomain class represents the application domain, which is an isolated environment where the CLR-managed applications execute. This class generates an event named UnhandledException whenever an unhandled exception occurs in an application. Unhandled exception can occur if there are no try-catch-finally blocks in the code, or if the existing catch blocks in the code cannot catch the thrown exception. The UnhandledException event handler receives unhandled exception details through its argument, an object of type UnhandledExceptionEventArgs. Table 3.2 details the most UnhandledExceptionEventArgs class. important properties of the Table 3.2 Important Properties of the UnhandledExceptionEventArgs Class Property Description ExceptionObject Receives the unhandled exception object corresponding to the current domain IsTerminating Is a Boolean value that indicates whether the CLR is terminating An event handler can be attached to the UnhandledException event to take custom actions such as logging the exception-related information. A log maintained over a period can help you to analyze and identify patterns providing useful debugging information. Several techniques can be used to log event-related information: ➤ By using the Windows event log ➤ By using the custom log files ➤ By using the databases such as SQL Server 2000 ➤ By sending email notifications The Windows event log provides the most dependable method of logging because other forms of logging can suffer from loss of network connectivity or file access. You can use the EventLog class to write data to the Windows event logs available in Windows 2000 and later versions of the operating system. 79 80 Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The option to use the EventLog class is not available in older versions of the Windows operating system, such as Windows 98. It should not be used if the application will be deployed on legacy platforms. Validating User Input To make your application as robust as possible, the best solution to invalid or incorrect user input is to prevent the entry of “bad” data as often as possible. Validating user input before hand provides a better solution than very complex error-handling code that might add a great deal of resource overhead to your program. Four basic techniques are used to validate user input: ➤ Restricting the available values by using the proper type of control, con- figured with a specific list of allowed values. Controls such as RadioButton, ListBox, ComboBox, and CheckBox are often used for this type of validation. Configuring properties of the controls allows additional restriction of user input, such as controlling the case or length of TextBox input. ➤ Restricting data entry through controls by enabling or disabling them based on the state of other controls. As an example of this technique, a set of controls allowing the entry of address information might remain disabled until a valid CustomerID has been selected in another control. ➤ Capturing and evaluating user keystrokes and allowing only acceptable values to be recognized. This might be used to prevent the entry of symbol or alphabetic characters within a control that should hold only numeric characters. ➤ Evaluating a control’s data as a whole and warning the user of incorrect or unacceptable values. This is often used to warn a user when attempting to change focus from the control or save the form. Control-Based Validation Restriction of allowable values within a control was discussed at greater length in Chapter 2, “Controls on Forms.” In addition to simply restricting input to a selection from a list of values, control properties can be configured to further limit possible input values. Of note are the CharacterCasing and MaxLength properties used in text input controls such as the TextBox. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Handling . . . . . Exceptions . . . . . . CharacterCasing The CharacterCasing property of a TextBox control can be used to change all input alphabetic characters to a particular case. The options for the CharacterCasing property are Normal (the default, which does not change the case of input characters), Upper (changes all the characters to uppercase), and Lower (changes all the characters to lowercase). MaxLength The MaxLength property of a TextBox or ComboBox is used to restrict the maximum number of characters the user can input into the control. A value of 0 (the default) specifies no specific limit for the number of characters that can be entered by the user. This property does not restrict the length of values that can be set programmatically. Control-Access Restriction Manipulating access properties such as the Enabled or ReadOnly properties can restrict data entry access within a control. When a control’s Enabled value is set to false, it cannot receive focus. If the ReadOnly property of a TextBox control is set to true, it can still receive focus, allowing users to scroll through its contents while preventing changes. Keystroke-Level Validation When a user presses a key, three events are fired in order: 1. KeyDown 2. KeyPress 3. KeyUp The KeyPress event can be used to intercept input keyboard characters and perform validation tasks through the use of the KeyPressEventArgs class before the KeyUp event is handled. Table 3.4 details some important properties of the KeyPressEventArgs class. Table 3.4 Important Properties of the KeyPressEventArgs Class Property Description Handled Whether the event has been handled. KeyChar The character value corresponding to the pressed key. 81 82 Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The KeyPress event fires only for keys that generate character values, excluding function, control, and cursor-movement keys. To respond to the excluded keys, you must use the KeyDown and KeyUp events instead. These use the properties of the KeyEventArgs class, detailed in Table 3.5. Table 3.5 Important Properties of the KeyEventArgs Class Property Description Alt Is true if the Alt key is pressed; otherwise, is false. Control Is true if the Ctrl key is pressed; otherwise, is false. Handled Indicates whether the event has been handled. KeyCode The keyboard code for the event. Its value is one of the values specified in the Keys enumeration. KeyData The key code for the pressed key, along with modifier flags that indicate the combination of Ctrl, Shift, and Alt keys that were pressed at the same time. KeyValue An integer representation of the KeyData property. Modifiers Modifier flags that indicate which combination of modifier keys (Ctrl, Shift, and Alt) was pressed. Shift Is true if the Shift key was pressed; otherwise, is false. By default, only the control, which currently has the focus, responds to the KeyDown, KeyPress, and KeyUp events. However, if you set the KeyPreview property of a form to true, the form can also handle the same three events before the control with the current focus handles them, allowing two tiers of keystroke-level validation—at the form level and at the control level. Field-Level Validation Validation also can be performed to include the entire value entered within a control by configuring validation code to run before focus is lost or the form is closed. When a user enters or leaves a field, the following events occur in order: 1. Enter—Occurs when a control is entered 2. GotFocus—Occurs when a control receives focus 3. Leave—Occurs when focus leaves a control 4. Validating—Occurs when a control is validating 5. Validated—Occurs when a control is finished validating 6. LostFocus—Occurs when a control loses focus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Handling . . . . . Exceptions . . . . . . The Validating event is the ideal place to store the validating logic for a field; we discuss the Validating event in the next section. The Validating Event The Validating event is ideal for input value validation. You can write code to check the values presented and display an error message to the user or prevent the loss of focus from the current control until the value has been corrected. The Focus method of the control can be used to redirect focus to the same control programmatically. Alternatively, the Cancel property of the CancelEventArgs object can be set to true, to prevent the transfer of focus from the current control. Closing a form fires a Validating event. Therefore, if you want to use the Cancel property of the CancelEventArgs to prevent loss of focus, this will also prevent the user from closing the form. To avoid this, you need to code the event handling to reset the Cancel value only when the mouse is inside the form’s client area. This allows the mouse to close the form using the Close button in the title bar. The Validated event occurs after validation has occurred. It can be used to perform actions based on the validated values, such as enabling or disabling other controls, as discussed previously in this section. The CausesValidation Property When using the Validating event to retain the focus in a control until you receive a valid input value, you can prevent the user from being able to obtain help on what constituted a valid input value by clicking another control such as the Help button in the toolbar. This is a result of the default setting (true) of the CausesValidation property of the Button control. If you set the CausesValidation property of the Help button control to false, the control can act without triggering the Validating event in the control with current focus. The ErrorProvider Component The ErrorProvider component provided within the Visual Studio .NET toolbox allows the display of error validation messages. A small icon includes a message that appears as a ToolTip when the user hovers the cursor over the displayed icon. Table 3.6 details the most important members of the ErrorProvider class. 83 84 Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 3.6 Important Members of the ErrorProvider Class Member Type Description BlinkRate Property Specifies the rate at which the error icon flashes. BlinkStyle Property Specifies a value indicating when the error icon flashes. ContainerControl Property Specifies the parent control of the ErrorProvider control. GetError Method Returns the error description string for the specified control. Icon Property Specifies an icon to display next to the parent control. The icon is displayed only when an error-description string (SetError) has been set for the parent control. SetError Method Sets the error-description string for the specified control. SetIconAlignment Method Specifies the location at which to place an error icon in relation to the control. SetIconPadding Method Specifies the amount of extra space to leave between the specified control and its error icon. This component offers many advantages over opening separate message boxes for each possible error, which can confuse users and complicate the desktop. The ErrorProvider component provides a simple user-friendly display that rapidly draws a user’s attention to the control failing input validation. Figure 3.2 shows a form that includes an ErrorProvider component. Figure 3.2 A form displaying an example of the ErrorProvider component. The following code shows how the ErrorProvider component can be used together with the Validating event to display errors during validation: private void txtGallons_Validating(object sender, System.ComponentModel.CancelEventArgs e) { . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Handling . . . . . Exceptions . . . . . . try { decimal decGallons = Convert.ToDecimal(txtGallons.Text); if (decGallons > 0) errorProvider1.SetError(txtGallons, “”); else errorProvider1.SetError( txtGallons, “Please enter value > 0”); } catch(Exception ex) { errorProvider1.SetError(txtGallons, ex.Message); } } In this section, we discussed various techniques that can be used for user input validation. You also learned how the ErrorProvider component can be used to point to errors when the user enters input data on a Windows Form. 85 86 Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Questions Question 1 You have created the following code segment: try { //Write code to allocate some resources } finally { //Write code to Dispose all allocated resources } Which of the following will result from compiling this code, assuming that all other code for your form works properly? ❍ A. The code will generate an error because it lacks a catch block. ❍ B. The code will generate an error because it lacks a throw statement. ❍ C. The code will generate an error because the finally block is placed immediately after the try block. ❍ D. The code will compile without an error. Answer D is correct. The code will compile properly because a try block should be followed by either a catch block or a finally block. The code here includes both a try block followed by a finally block. Answer A is incorrect because a try block can be followed by either one or more catch blocks or a finally block (or both). Answer B is incorrect because the throw statement is used to explicitly raise an error and is not required. Answer C is incorrect because a finally block can be placed after a try block. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Handling . . . . . Exceptions . . . . . . Question 2 What will be the output of the following code? try { int num = 100; int den = 0; try { MessageBox.Show(“Message1”); int res = num/den; MessageBox.Show(“Message2”); } catch(ArithmeticException ae) { MessageBox.Show(“Message3”); } MessageBox.Show(“Message4”); } ❍ A. Message1 Message4 ❍ B. Message1 Message2 Message3 Message4 ❍ C. Message1 Message3 Message4 ❍ D. Message1 Message3 Message2 Message4 Answer C is correct. This code first displays Message1 and executes the next line to perform the division. Because the denominator is 0, a DivideByZeroException is raised. Because the code that raises the exception is enclosed in a try block, the program searches for a matching catch block associated with that try block. The code finds a matching catch block with ArithmeticException (that is a base class for the DivideByZeroException exception), which can handle the exception. Therefore, it executes the catch block and displays Message3. After executing the catch block, control comes to the next line after the catch block, and the program displays Message4. Answer A is not correct because the program is capable of locating a catch 87 88 Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . block that can catch DivideByZeroException. Answer B is not correct because when an exception is raised, the code first searches for the catch block that can handle the exception. Answer D is not correct because after the code in the catch block is executed, control is transferred to the next line after the catch block. Question 3 How should you arrange catch blocks? ❍ A. Only one catch block for each try block. ❍ B. Several catch blocks for a try block, arranged in order starting with Exception and ending with the most specific exception. ❍ C. Several catch blocks within one try block, arranged starting with the most specific exception and ending with Exception. ❍ D. The catch blocks should be used only when a finally block is not used. Answer C is correct. One or more catch blocks can be used with a try block, arranged in order from the most specific exception to the most general; the first matching catch block catches the exception. Answer A is incorrect because you can associate more than one catch block with a try block. Answer B is incorrect because it specifies a reversed order, starting with Exception class. The compiler generates an error if the catch blocks are not arranged from specific to generic types. Answer D is incorrect because catch and finally blocks can both be used together, if desired. Question 4 You have designed a logon form with two TextBox controls named txtUserName and txtpassword. You want to ensure that the user can enter only lowercase characters in the controls. Which of the following solutions will fulfill this requirement using the simplest method? ❍ A. Program the KeyPress event of the TextBox controls to convert uppercase letters to lowercase letters. ❍ B. Create a single event handler that is attached to the KeyPress event of the form. Program this event handler to convert the uppercase letters to lowercase ones. ❍ C. Set the CharacterCasing property of the Textbox controls to Lower. ❍ D. Use the CharacterCasing method of the controls to convert the letters to lowercase letters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Handling . . . . . Exceptions . . . . . . Answer C is correct. The simplest method to accomplish this requirement is to set the CharacterCasing property of the two TextBox controls to Lower so that all input characters will be forced to lowercase. Answers A and B could be used to accomplish this task, but this would not be the simplest solution available. Answer D is incorrect because there is no CharacterCasing method for TextBox controls. CharacterCasing is a property that accepts values of Normal, Lower, or Upper. Question 5 You are creating an order-tracking application using a Visual C# .NET Windows application. When you are unable to track a particular order number entered by the user, you need to raise an exception. Which of the following options will help you to raise an exception? ❍ A. try block ❍ B. catch block ❍ C. finally block ❍ D. throw statement Answer D is correct. The throw statement is used to raise an exception. Answer A is not correct because the try block is used to place code that can raise exceptions. Answer B is not correct because the catch block is used to catch and handle exceptions. Answer C is not correct because the finally block is used to insert code that always needs to be executed, such as resource-cleanup code. Question 6 Which of the following events will fire when the Insert key is pressed? (Choose all correct answers.) ❑ A. KeyDown ❑ B. KeyPress ❑ C. KeyUp ❑ D. Move Answers A and C are correct. When control and cursor-navigation keys are pressed, only the KeyDown and KeyUp events are fired. Answer B is incorrect because the KeyPress event occurs only when a keyboard key generates a character. 89 90 Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 7 You have a TextBox control and a Help button that the user can press to get help on allowable values. You validate the data entered by the user in the TextBox control. If the user enters an invalid value, you set the focus back in the control using the Cancel property of the CancelEventArgs. A user reports that once he enters invalid data in the text box, he cannot click the Help button. What should you do to correct the problem? ❍ A. Set the CausesValidation property of the text box to false. ❍ B. Set the CausesValidation property of the text box to true. ❍ C. Set the CausesValidation property of the Help button to false. ❍ D. Set the CausesValidation property of the Help button to true. Answer C is correct. By setting the CausesValidation property of the Help button to false, you allow it to act without first firing the Validating event in the TextBox, which would return the focus to the TextBox. Answers A and B are incorrect because changing the CausesValidation property of the textbox will not affect the capability of the Help button to be selected. Answer D is incorrect because setting the CausesValidation property of the help button to true (the default value) would result in the same problem experienced by the user. Question 8 You are designing a Windows Form that enables you to add a new product to the product catalog of your company. You need to validate the controls as the user enters the data. If incorrect data is entered in the field, you should set the focus back to the control and ask the user to enter the correct data. Which of the following events will you use to validate user input? ❍ A. LostFocus ❍ B. Validating ❍ C. Leave ❍ D. Validated Answer B is correct. The Validating event is the ideal place to store the validating logic for a field. Answers A and C are not correct because these events are not intended for validation. Properties such as CausesValidation and Cancel, which provide important roles in control validation, affect only the Validating and Validated events. Answer D is not correct because the Validated event is fired after the validation is performed. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Handling . . . . . Exceptions . . . . . . Question 9 You have an order entry form. When an exception occurs, you want to get information about the sequence of method calls and the line number in the method where the exception occurs. Which property of your custom exception class that derives from the ApplicationException class should be used? ❍ A. HelpLink ❍ B. InnerException ❍ C. Message ❍ D. StackTrace Answer D is correct. The StackTrace method of the Exception class provides information about the method call sequence and line number where the exception occurred. Answer A is incorrect because the HelpLink property specifies the URL for an associated help file. Answer B is incorrect because the InnerException property details an exception associated with the raised exception. Answer C is incorrect because the Message property is used to explain the error or offer possible corrective actions. Question 10 You want to log events generated by exception-handling code within your application, which will run on standalone systems running Windows 98 and Windows 2000. Which of the four methods of logging is the best single solution able to fulfill this requirement? ❍ A. Windows event log ❍ B. Custom log files ❍ C. Databases such as SQL Server 2000 ❍ D. Email notifications Answer B is correct. The best solution in this scenario is to use a local custom log file. Answer A is incorrect because some of the systems are running Windows 98, which does not support logging using the event log. Answers C and D are incorrect because standalone systems will not have network access to allow connection to databases or transmission of SMTP messages. 91 92 Chapter . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Need to Know More? Dietel, Harvey M., et al. C#: How to Program. Prentice Hall, 2001. Richter, Jeffrey. Applied Microsoft .NET Framework Programming. Microsoft Press, 2001. Windows Forms Community Site: www.windowsforms.net/. 4 Components and .NET Assemblies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ Component ✓ Control ✓ UserControl ✓ Event handling ✓ Assemblies ✓ Assembly Manifest ✓ Global Assembly Cache ✓ Satellite assembly Techniques you’ll need to master: ✓ Understand how to create a component by extending the Component, Control, and UserControl classes. ✓ Know how to extend the functionality of existing controls through visual inheritance. ✓ Understand the difference between the private and shared assemblies. 94 Chapter . . . . .4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . In Chapter 2, “Controls on Forms,” we looked at several common controls that can be placed within a container object, such as a Windows Form. However, the .NET Framework also includes the capability to create more complex and customized components. In this chapter, we discuss the creation of custom components by inheriting from the Component, Control, and UserControl classes. We also examine the use of the .NET Assembly for security, versioning, and deployment of custom components. Creating .NET Components In programming, the term component is generally used for an object that is reusable and can interact with other objects. The .NET Framework enables you to create components in several different ways: ➤ By deriving from the Component class, which belongs to the System.ComponentModel namespace. This technique is used to create those components that are used to control external resources such as an event log, or to provide a design-time interface such as the one supplied by the System.Windows.Forms.Timer component. These objects generally don’t have any runtime user interface. ➤ By deriving from the Control class of the System.Windows.Forms namespace. This technique is used to create the control that provides user interface capabilities. These objects are generally placed on a container control such as a Windows form to create the client-side user interface. ➤ By deriving from the UserControl class or any of its derived classes. The UserControl class derives from the ContainerControl class, making its derived components capable of serving as containers for other controls. This allows the rapid creation and deployment of custom modular components based on existing controls that work together. When you create your own controls by deriving from the Control class, you must override the Paint method with your own rendering logic. On the other hand, when you create a control by deriving from the UserControl class, you need not override the Paint method because the control renders the user interface of its child controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Components . . . . . . .and . . .NET . . . Assemblies . . . . . . The templates mentioned in the following sections are not available in Visual Studio .NET Standard edition. You must have Visual Studio .NET Professional or higher to utilize these templates. Creating Components Derived from the Component Class Some components provide functionality without requiring a visual representation. One example of this is the Timer component, which provides useful properties and events to its container without a displayed user interface. You can create a component derived from the Component class by performing the following tasks: 1. Open an instance of Visual Studio .NET and create a new project based on the Class Library template. Name the project RandomNumberGenerator. 2. Remove the automatically created Class1.cs by right-clicking it and selecting Delete. 3. Right-click the project name (RandomNumberGenerator) in the Solution Explorer and select Add, Add New Item to open the Add New Item dialog box. Select Component Class as the template of the item, and name the component RandomNumberGenerator.cs (see Figure 4.1). Figure 4.1 The Add New Item dialog box showing the Component Class option selected. 95 96 Chapter . . . . .4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4. In Code view, add the following code just after the Component Designer–generated code: //stores minValue and maxValue private int minValue=1, maxValue=100; 5. Add the following code to create two properties, MinValue and MaxValue, of type int: public int MinValue { get { return minValue; } set { minValue = value; } } public int MaxValue { get { return maxValue; } set { maxValue = value; } } 6. Add a method named GetRandomNumber(), as shown in the following code: public int GetRandomNumber() { Random r = new Random(); return r.Next(minValue, maxValue); } 7. In the Solution Explorer, navigate to the project RandomNumberGenerator and right-click its Reference node. Select Add Reference from the context menu. In the Add Reference dialog box, select the .NET tab and double-click the component named System.Drawing.dll. Then click OK. A reference to System.Drawing.dll is added to this project. 8. Insert the following line at the top of the code, along with other directives: // Required for ToolboxBitmap attribute using System.Drawing; using . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Components . . . . . . .and . . .NET . . . Assemblies . . . . . . 9. Select any 16 × 16–pixel .bmp file (if you have a 16 × 16 ICO file, just rename it with a .bmp extension). Change its name to RandomNumberGenerator.bmp and add it to the project. After the .bmp file appears in the Solution Explorer, right-click it and select Properties from the context menu. In the Properties window, set Build Action to Embedded Resources. 10. Add the following attribute just before the class declaration: // Set the Toolbox icon [ToolboxBitmap(typeof(RandomNumberGenerator))] 11. Select the project RandomNumberGenerator in the Solution Explorer and select Build, Build RandomNumberGenerator. This generates a RandomNumberGenerator.dll file that contains the code for the RandomNumberGenerator component. You can also place the RandomNumberGenerator component on the Visual Studio .NET toolbar; this enables you to use drag-and-drop to include the component on Windows forms applications. To add the component to the toolbox, right-click an empty area on the toolbox and select Customize Toolbox from the shortcut menu. You can use the new component in your form by including a reference to the project’s .dll file in the toolbox. To do this, right-click the .NET Framework Components tab and select Browse to navigate to the new .dll. These steps automatically add the control to the Toolbox window (see Figure 4.2). Figure 4.2 The toolbox showing several custom controls. Adding this component to your form as RandomNumberGenerator1 and configuring its MinValue and MaxValue properties enables you to use its results in other visual controls using code similar to the following: 97 98 Chapter . . . . .4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . private void btnGenerate_Click(object sender, System.EventArgs e) { lblResult.Text = String.Format(“The next random number is: {0}”, randomNumberGenerator1.GetRandomNumber()); } Creating Components Derived from the Control Class When you need a control that cannot easily be created using existing user interface controls, you can create a custom control derived directly from the Control class. No template is provided for this purpose, so you first must create a new control derived from the UserControl class and then modify it to extend from the Control class. You create a component derived from the Control class by performing the following steps: 1. Open an instance of Visual Studio .NET and create Control Library project based on the User Control template. 2. Switch to Code view for the new control and change the class declara- tion so that its base class is Control rather than Systems.Windows.Forms.UserContol, like this: public class DigitalClock : Control When you change back to Design view after changing the class declaration to Control, you will notice that the gray borderless box used for creating controls is gone. 3. Add any required event handlers to the control, including code needed to support rendering the control on a Paint event and a call to the Paint event during a Resize event: private void timer1_Tick(object sender, System.EventArgs e) { Invalidate(); } private void DigitalClock_SizeChanged(object sender, System.EventArgs e) { Invalidate(); } private void DigitalClock_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Components . . . . . . .and . . .NET . . . Assemblies . . . . . . Graphics g = e.Graphics; string strTime = DateTime.Now.ToString(“T”); //Get the current string size SizeF sizef = g.MeasureString(strTime, Font); //get the scaling factor float scale = Math.Min(ClientSize.Width/ sizef.Width, ➥ClientSize.Height/ sizef.Height) ; //scale the font as per new control size Font font = new Font(Font.FontFamily, scale*Font.SizeInPoints); //get the string size for scaled font size sizef = g.MeasureString(strTime, font); //Find the position to draw the string PointF pos = new PointF((ClientSize.Width - sizef.Width)/2, ➥(ClientSize.Height - sizef.Height)/2); //Draw the time string g.DrawString(strTime, font, new SolidBrush(ForeColor), pos); } After you build this project, the project’s .dll will include code for the new control to be added to your toolbox, as detailed in the previous section. Including this visual control on your form will redraw itself as you resize the control, as seen in Figure 4.3. Figure 4.3 A form displaying the custom DigitalClock control. Components Derived from the UserControl Class Existing user interface controls can be combined to create a custom control derived from the UserControl class. When creating a control such as this, you also might want to create custom event delegates that allow your form to trigger events that occur within your new control. The following sections explain how to create a control derived from the UserControl class and how to add event responses to the newly created control. 99 100 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a Control Derived from the UserControl Class You can create a component derived from the UserControl class by performing the following tasks: 1. Open an instance of Visual Studio .NET and create a Windows Control Library project based on the Windows Control Library template. Rename UserControl1.cs to ColorMixer.cs, and change the class name to ColorMixer within Code view. 2. Within Design view, add three TrackBar controls, naming them tbRed, tbGreen, and tbBlue. Change their Maximum property to 255, their Orientation to Vertical, their TickFrequency to 15, and their TickStyle to both. Figure 4.4 shows the layout of this control. Figure 4.4 Three TrackBar controls arranged for the ColorMixer control. 3. Select View, Class View from the header and navigate to the ColorMixer class. Then right-click the class and select Add, Add Property from the options provided. In the C# Property Wizard, add three properties—Red, Green, and Blue (see Figure 4.5). Figure 4.5 Creating the Red property using the C# Property Wizard. 101 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Components . . . . . . .and . . .NET . . . Assemblies . . . . . . 4. Add code to create properties for the custom control: [Category(“Color”), Description(“Value of Red Color”)] public int Red { get { return tbRed.Value; } set { tbRed.Value = value; } } [Category(“Color”), Description(“Value of Green Color”)] public int Green { get { return tbGreen.Value; } set { tbGreen.Value = value; } } [Category(“Color”), Description(“Value of Blue Color”)] public int Blue { get { return tbBlue.Value; } set { tbBlue.Value = value; } } After you build this project, the project’s .dll will include code for the new control that can be added to your toolbox as detailed previously. After you add a reference to the project’s .dll including the new control and after you include this control on your form as ColorMixer1, you can access its value, as shown here: private void btnSetColor_Click(object sender, System.EventArgs e) { lblColorSample.BackColor = Color.FromArgb(colorMixer1.Red, colorMixer1.Green, colorMixer1.Blue); } Adding Event Responses to Custom Controls You might want to allow the manipulation of your custom control to trigger events external to the control itself. In the previous example, the resulting 102 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ColorMixer control class could be used to generate a color value based on the current settings of the contained TrackBar controls. However, a change to these settings could not automatically be reflected without the calling form requerying the value of the ColorMixer control. Events in Visual C# .NET use the publisher-subscriber model, in which the class that implements an event is called the publisher and other classes registering appropriate event handlers are called the subscribers. The publisher announces that other classes can subscribe to this event by attaching appropriate event handlers to the event. The publishing class registers all event handlers with itself and takes responsibility for invoking them all when the event occurs. An event handler is a method with a specific signature that the publisher class is capable of registering. By convention, most event handlers take two arguments. The first specifies the object on which the event occurred, and the second contains information related to the event; the second argument is an object of type EventArgs or of a class derived from EventArgs. You can modify the ColorMixer control that you created to accommodate event delegation by performing the following steps: 1. Create a new blank project and copy the ColorMixer.cs from your pre- vious project (hold down the Ctrl key while dragging and dropping the control to copy it easily). Rename this copy and change all instances of ColorMixer within Code view to ColorMixerEventArgs. 2. Within Code view, add the code to create a delegate and handle the event: public class ColorMixerEventArgs : EventArgs { public readonly int red, green, blue; public ColorMixerEventArgs(int red, int green, int blue) { this.red = red; this.green = green; this.blue = blue; } } //define the prototype of the callback method public delegate void ChangedEventHandler(object sender, ColorMixerEventArgs args); //define the event public event ChangedEventHandler Changed; //notify the registered objects of event protected virtual void OnChanged(ColorMixerEventArgs e) { 103 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Components . . . . . . .and . . .NET . . . Assemblies . . . . . . //if any object registered with the event if (Changed != null) { //notify that object Changed(this, e); } } 3. Add an event handler to each of the TrackBar controls: //Fire Change event when there is any change to the trackbar controls private void TrackBar_ValueChanged(object sender, System.EventArgs e) { ColorMixerEventArgs args = new ColorMixerEventArgs(tbRed.Value, tbGreen.Value, tbBlue.Value); OnChanged(args); } 4. Build the code, add its reference to a form, and then add an instance of the new control and accept the default name of ColorMixerEventArgs1. 5. Add a GroupBox control to your form and place a Label control within it, named lblColorSample. 6. Add code to handle the Changed event of the ColorMixerWithEvents1 control: private void colorMixerWithEvents1_Changed(object sender, StepByStep4_3.ColorMixerWithEvents.ColorMixerEventArgs args) { lblColorSample.BackColor = Color.FromArgb(args.red, args.green, args.blue); } 7. Set this form as the startup object for your project, and run the project to see the results. Manipulating the TrackBars of the custom control causes the Label control’s background color to change automatically. Extending a Control Through Visual Inheritance A new component can be created that inherits all the qualities from an existing component, adding additional functionality as required. With regard to a form or other type of user interface component, this process is referred to as visual inheritance. You can create a new control that extends the ColorMixerEventArgs control created previously in this section to include a color sampler displaying the color and its Red, Green, and Blue values by performing the following: 104 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1. Create a new project based on the Windows Control Library template, and name the project ColorMixerX. Delete the automatically created file, UserControl1.cs. 2. Right-click the project and select Add, Add Inherited Control from the options. Name the new control ColorMixerX.cs and click the Open button to open the Inheritance Picker dialog box, as shown in Figure 4.6. Figure 4.6 The Inheritance Picker dialog box showing the ColorMixerWithEvents component selected. 3. Select the desired parent component and click OK to return to Design view of the derived control, which displays all the features of the parent component. 4. Add a GroupBox control that contains four Label controls: lblSampler, lblRed, lblGreen, and lblBlue. Change the Text property of the GroupBox control to Sampler, and change the Text property of the Label controls to an empty string. 5. In Code view, add code to the control’s constructor after the call to the InitializeComponent method: //set the initial display of control lblSampler.BackColor = Color.FromArgb(this.Red, this.Green, this.Blue); lblRed.Text = String.Format(“R: {0}”, this.Red); lblGreen.Text = String.Format(“G: {0}”, this.Green); lblBlue.Text = String.Format(“B: {0}”, this.Blue); 6. Add code to handle the Changed event of the control: private void ColorMixerX_Changed(object sender, StepByStep4_3.ColorMixerWithEvents.ColorMixerEventArgs args) { lblSampler.BackColor = Color.FromArgb(args.red, args.green, args.blue); lblRed.Text = String.Format(“R: {0}”, args.red); lblGreen.Text = String.Format(“G: {0}”, args.green); lblBlue.Text = String.Format(“B: {0}”, args.blue); } 105 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Components . . . . . . .and . . .NET . . . Assemblies . . . . . . After building this project, the project’s .dll will include code for the new control that can be added to your toolbox as detailed previously. The new control includes all the functionality of its parent as well as the new features. Creating .NET Assemblies Beyond practice sessions, Windows applications generally consist of more than a single file. These can include application code files with DLL and EXE extensions; graphics files with extensions such as GIF and BMP; or other data files used by the application that store utility information or strings for multilingual support. The .NET Framework groups all the files from an application into a single logical group called an assembly. The files are not physically altered to designate them as part of an assembly, but instead they are detailed within the Assembly Manifest, which includes the metadata for an assembly. Each assembly has a version number. All types and resources within an assembly share the same version number, to make it possible for applications to refer to the correct version of files. When the Common Language Runtime (CLR) prepares to load an assembly, it reads the Manifest to get the following information: ➤ The name and version of the assembly ➤ The files that make up the assembly, including their name and hash values ➤ The compile-time dependency of this assembly on other assemblies ➤ The culture or language that an assembly supports ➤ The set of permissions required for the assembly to run properly You can view the Assembly Manifest using the Microsoft Intermediate Language (MSIL) Disassembler, which is a separate utility program that can be used from within the Visual Studio interface by the following process: 1. Within the Solution Explorer window of Visual Studio .NET, click the Show All Files button in its toolbar. Then navigate to the folder that holds your project’s assembly. 2. Right-click the DLL or EXE file generated by your project. Select Open With from the options listed in order to access the Open With dialog box. 106 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3. Select ildasm.exe from the options to open the MSIL Disassembler, as shown in Figure 4.7. If you do not see ildasm in the options, you can add it by clicking the Add button. The ildasm can be located in the bin subdirectory of .NET Framework SDK installation directory, which is typically \Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Bin. Expand the nodes to see the methods and constructors of the assembly. 4. Double-clicking the MANIFEST node displays the metadata for the assembly, as shown in Figure 4.8. Figure 4.7 The MSIL Dissassembler displaying metadata from an assembly. Figure 4.8 Metadata displayed from within the MANIFEST node. One method used to identify assemblies is based on the manner of their use. We examine the following categories based on this method of identification: 107 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Components . . . . . . .and . . .NET . . . Assemblies . . . . . . ➤ Single-file and multifile assemblies ➤ Static and dynamic assemblies ➤ Private and shared assemblies ➤ Satellite and resource-only assemblies Single-File and Multifile Assemblies Most examples that you will encounter generate a single-file assembly, which is a single EXE or DLL file encapsulating all code, embedded resources, and the Assembly Manifest within the same file. Visual Studio .NET does not support the creation of multifile assemblies, but you can create them using the .NET Framework SDK’s command-line Assembly Generation tool (al.exe). In a multifile assembly that includes several DLL and EXE files, the Assembly Manifest can be attached to any of these or can exist within its own separate file. Although Visual Studio .NET does not allow the creation of multifile assemblies, it can make use of multifile assemblies in other projects. Static and Dynamic Assemblies Static assemblies are created when you explicitly compile a program using either Visual Studio .NET or the command-line compilers. Static assemblies are physically stored on a disk. Dynamic assemblies are implicitly created on the fly by programs such as ASP.NET. You can use the classes in the System.Reflection.Emit namespace to create dynamic assemblies in your own programs. Dynamic assemblies are not persisted on the disk. Private and Shared Assemblies Assemblies can be deployed using two different approaches: ➤ When an assembly is deployed for use within a single application, it is called a private assembly. Private assemblies are located within the same folder where the application is installed and do not require detailed name and versioning information. They can be copied to the Global Assembly Cache (GAC) if this is necessary for later usage or for several applications; this is covered in greater detail in Chapter 13, “Deploying a Windows Application.” ➤ When an assembly is deployed for use by many applications, it is stored within the Global Assembly Cache and is called a shared assembly. Shared assemblies have several common characteristics, including the following: 108 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ Assemblies stored in the GAC cannot be deployed simply by copy- ing the appropriate files to the destination system—they must instead be deployed to the GAC of the target system using tools such as gacutil.exe or through Windows Installer 2.0. You’ll learn more about installing files to the GAC in Chapter 13. ➤ Assemblies installed within the GAC must have a strong name, to ensure the assembly’s identity. A strong name consists of an assembly’s name, version number, and culture, along with a public key and a digital signature. The CLR checks an assembly’s identity before installing it to the GAC and then ensures that it has not been tampered with later by checking its strong name. ➤ Unlike a folder containing a static assembly, the GAC can contain multiple copies of an assembly with the same name but different versions. The runtime of an application can determine which version of an assembly to load based on its configuration file. This is covered in greater detail in Chapter 15, “Configuring a Windows Application.” You can view the contents of the GAC using the following process: 1. Within the Windows Explorer, navigate to the system folder of your computer (such as c:\Windows or c:\WINNT) and open the subfolder named Assembly, as shown in Figure 4.9. Figure 4.9 Windows Explorer showing the contents of a system’s GAC. Native Assembly Versus JIT-Compiled Assembly Assemblies store code in the Microsoft Intermediate Language (MSIL) format. When a method is invoked for the first time, the CLR will Just-In-Time (JIT) compile that method into native machine code. The native code is stored in memory and is directly used for any subsequent 109 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Components . . . . . . .and . . .NET . . . Assemblies . . . . . . calls to this method. In this mode, a method is slower when called for the first time because compilation is involved, but any subsequent calls to that method will run as fast as native code itself. When you view the GAC, you will note that some assemblies have their type marked as native images. These assemblies have been compiled in native code before being installed in the GAC. The advantage of using a native image is that even the first call of a method will be as fast as its subsequent calls. You, too, can create a native image for your assembly by using the Native Image Generator Tool (NGEN.EXE), which is installed as part of the .NET Framework SDK. 2. Right-click an assembly and select Properties to display the assembly’s information details, including its version (see Figure 4.10). Figure 4.10 Displayed properties of the System.Security assembly. Satellite and Resource-Only Assemblies Many applications require additional resources, such as files containing graphics, culture, and language settings, to function properly. In the RandomNumberGenerator.cs example shown earlier in this chapter, you included a bitmap (BMP) file with your assembly. Resource files can be included in an assembly in two ways: ➤ Select the option Build Type of a Project’s Properties as Content. This generates an assembly containing only code, metadata, and links to external resource files. The resources files must be distributed with the application to remain available at runtime. ➤ Select the option Build Type to Embedded Resources, as in the RandomNumberGenerator example. This causes the compiler to include the resources embedded within the application’s assembly itself. Visual Studio .NET performs this process in the following steps: 110 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1. An XML resource file is created with an extension of resx. This file stores the resources as key-value pairs—for example, the name of a resource file and its location. 2. During compilation, all resources listed in the resx file are embed- ded into a binary file with the extension of resources. 3. The resultant binary resource file is embedded into the code assembly. You can use the Assembly Generation tool (al.exe) to create an assembly by linking various compiled modules. This feature is especially useful if you are using multiple .NET languages in your programming environment. You can first compile the various programs, by using their corresponding language compilers, into module files and then use al.exe to link the module files into an assembly. Another option is to create an assembly that contains only resources. Although Visual Studio .NET does not directly support this method, it is possible using command-line utilities from the SDK. You can use the Resource File Generator tool (resgen.exe) to convert .txt files and .resx (XML-based resource format) files to CLR binary .resources files. When you have the .resources file, you can compile it into a resource-only assembly using the Assembly Generation tool (al.exe). Table 4.1 details a few important classes from the System.Resources namespace that you might find useful in your programs. Table 4.1 Some Important Classes That Deal with Resources Class Explanation ResourceManager Provides access to resources at runtime. This class can be used to read information from resource-only assemblies. ResourceReader Enables you to read resources from a binary resource file. ResourceWriter Enables you to write resources to a binary resource file. ResXResourceReader Enables you to read resource information from an XML-based .resx file. ResXResourceWriter Enables you to write resource information to an XML-based .resx file. Visual Studio .NET includes support for the creation of one type of resource-only assembly—the satellite assembly. A satellite assembly is used to store culture-specific information to support globalization. Globalization is a process of creating world-ready applications; it involves changing the applications interface based on the user’s currently selected language and culture (we cover globalization in greater detail in Chapter 8, “Globalization”). 111 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Components . . . . . . .and . . .NET . . . Assemblies . . . . . . Practice Questions Question 1 You need to create several forms capable of accepting and validating addresses, accepting information such as the name, street name, state, country, and ZIP code using TextBox and ComboBox controls. You want to package your input and validation code in a standard component so that you can reuse the control. Which of the following classes should be the base class of your component? ❍ A. System.Windows.Forms.Control ❍ B. System.Windows.Forms.UserControl ❍ C. System.Windows.Forms.Form ❍ D. System.ComponentModel.Component Answer B is correct. The System.Windows.Forms.UserControl class provides the capability to quickly create a reusable component by combining existing Windows controls. Answer A is incorrect because extending the base Control class provides a means of creating your own controls from scratch rather than simply reusing existing Windows controls. Answer C is incorrect because you would not use a form within another form as a control. Answer D is incorrect because the base Component class is extended to create nonvisual components. Question 2 You have defined a custom user-authentication component that raises an Authenticated event whenever a user is successfully authenticated. When this event fires, you want to make the username and SID (security identifier) available to the control container. How should you accomplish this requirement? ❍ A. Place the username and SID in properties of the component for the container to retrieve. ❍ B. Pass the username and SID as parameters of the Authenticated event. ❍ C. Define global variables in a separate module and place the values in those variables. ❍ D. Define a custom AuthenticatedEventArgs class that inherits from the EventArgs class, and pass it as a parameter of the Authenticated event. Answer D is correct. Using a class derived from EventArgs to pass event parameters is preferable to using individual arguments because it is easier to extend to include more parameters later. Answers A, B, and C are incorrect 112 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . because they all involve placing the variables in other locations, making them harder to manipulate and update. Answer C also involves the use of a separate module, where the code from your control might be incapable of effecting changes. Question 3 A friend attempts to host a control in Internet Explorer. He creates the control and tests it successfully on a Windows Form, but he can’t get it to display in IE. The name of the control is SolidControls.ColorMixer, within a DLL named SolidControlsLib.dll. He has placed both the HTML page and the DLL in the same virtual directory on the Web server. He shows you the HTML file that hosts this control. Part of his HTML code is listed here (line numbers are for reference purpose only): 01: <html> 02: <body> 03: <object id=”colorMixerX1” 04: classid=”http://localhost/WebDir/ ➥SolidControlsLib.dll” 05: height=”300” width=”300”> 06: </object> 07: </body> 08: </html> What change is needed to display this control in IE? ❍ A. Change the code in line 4 to: classid=”http://localhost/WebDir/SolidControlsLib. ➥dll#SolidControls.ColorMixer” ❍ B. Change the code in line 4 to: classid=”http://localhost/WebDir/SolidControlsLib. ➥dll?SolidControls.ColorMixer” ❍ C. Change the code in line 4 to: classid=”SolidControls.ColorMixer” ❍ D. Change the code in line 4 to: classid=”http://localhost/WebDir/SolidControlsLib. ➥dll?classid=SolidControls.ColorMixer” Answer A is correct. The correct usage is to give the classid a string with the virtual path to the control and the namespace-qualified name of the control class, separated by the # sign. Answer B is incorrect because the separating character is specified as the ? symbol. Answer C is incorrect because it is missing the virtual path assignment. Answer D is incorrect because it includes a second classid assignment as a divider. 113 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Components . . . . . . .and . . .NET . . . Assemblies . . . . . . Question 4 You develop a Windows application that allows the users to view the global product sales in a graphical format. Your application uses a shared assembly for creating the graphs. Where should you copy the shared assembly so that other applications can access it? ❍ A. In the bin directory of the application ❍ B. In the Global Assembly Cache ❍ C. In the Windows installation directory ❍ D. In the application’s root directory Answer B is correct. Shared assemblies must be deployed in the Global Assembly Cache. Answers A and D are not correct because only private assemblies should be copied to the application’s root directory or a subdirectory. Answer C is not correct because it is not recommended to deploy private and shared assemblies to the Windows installation directory. Question 5 You are creating an application that will be used company-wide. Several forms show a clock to the user. You have decided to code the custom analog clock as a reusable component. Which of the following classes should be the base class for creating this control? ❍ A. System.Windows.Forms.Control ❍ B. System.Windows.Forms.UserControl ❍ C. System.Windows.Forms.Form ❍ D. System.ComponentModel.Component Answer A is correct. You should inherit from the Control class if you want to provide a custom graphical representation of your control or functionality that is not available through standard controls. Answer B is incorrect because the UserControl class provides the capability to quickly create a reusable component by combining existing Windows controls. Answer C is incorrect because you would not use a form within another form as a control. Answer D is incorrect because the base Component class is extended to create nonvisual components. 114 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 6 You have designed a custom UserControl combining five TextBox controls and two Button controls. You want only derived controls to be able to access the contained objects within your control. You want your project classes to have access to this control. Which modifiers should you use to achieve this requirement? (Select all correct answers.) ❑ A. private ❑ B. internal ❑ C. protected ❑ D. public Answers B and C are correct. When you configure the contained objects within a control as internal or protected, they are not accessible only within the current project and derived classes. Answer B is incorrect because the protected setting only limits access to the same project. Answer D is incorrect because the public modifier allows access from any application. Question 7 You are designing a component that interacts with the computers in a network. The component has no visual representation but should provide you with a design time interface that will help client application designers to set its properties and behavior. Which of the following should you chose as the base class for this control? ❍ A. System.Windows.Forms.Control ❍ B. System.Windows.Forms.UserControl ❍ C. System.Windows.Forms.Form ❍ D. System.ComponentModel.Component Answer D is correct. Components that provide no visual interface should derive directly from the System.ComponentModel.Component class. Answers A and B are incorrect because the Control and UserControl classes are used for components that need a visual representation. Answer C is incorrect because a Form class is used as a container for other controls and includes a visual representation. 115 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Components . . . . . . .and . . .NET . . . Assemblies . . . . . . Question 8 Your Windows application utilizes several graphics files. You don’t want to have to distribute additional files with your application. What should you do? ❍ A. Create a satellite assembly for storing graphics. ❍ B. Set the BuildAction property of the graphics files to Content. ❍ C. Set the BuildAction property of the graphics files to Compile. ❍ D. Set the BuildAction property of the graphics files to Embedded Resources. Answer D is correct. When you set the Build Action property of a graphics file to Embedded Resources, the file is embedded with the main assembly file (DLL or EXE). Answer A is incorrect because a satellite assembly is used to include culture-specific information. Answer B is incorrect because the Content setting causes the compilation to result in a main file that includes only code, metadata, and references to external resource files that must be distributed with the main file. Answer C is incorrect because compilation is the process by which the assembly EXE or DLL is created. Question 9 You have developed, tested, and deployed a Windows form application in your company. The users use this application to create labels and bar code for various products that your company distributes. Users of the application complain that it is slow when it is loaded for the first time, but it works fast after that. Which of the following actions should you take to resolve this problem? ❍ A. Use gacutil.exe to install the assemblies in the Global Assembly Cache. ❍ B. Use ngen.exe to create native images from the managed assemblies and store them in the native image cache. ❍ C. Use tlbexp.exe to generate type libraries from the application’s assemblies. ❍ D. Use regasm.exe to read the metadata within an assembly and add the necessary entries to the Registry. Answer B is correct. If the application is performing slowly when it is loaded but performs well later, the most likely reason is that managed code needs to be compiled into the native code. If you use the ngen.exe tool to precompile all the assemblies to native assemblies, it will significantly improve the application’s startup performance. 116 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 10 Which of the following statements is true for a multifile assembly? ❍ A. Each file must contain an Assembly Manifest. ❍ B. Only one of the files can contain the Assembly Manifest. ❍ C. You can find the assembly to which a file belongs by opening that file with the MSIL Disassembler (ildasm.exe). ❍ D. You can have files with the same name but different versions in a multifile assembly without conflicts. Answer B is correct. Only one of the files in a multifile assembly can contain the Assembly Manifest. Answer A is incorrect because only one Assembly Manifest exists for each assembly. Answer C is incorrect because you cannot find the name of the assembly to which a file belongs to by viewing it in ILDASM. Only the Assembly Manifest contains this information. Answer D is incorrect because it is not possible to have two files with same name in an assembly; the most elementary unit of versioning is the assembly itself, so the files contained in it cannot have different versions. 117 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Components . . . . . . .and . . .NET . . . Assemblies . . . . . . Need to Know More? Jeffrey Richter. Applied Microsoft .NET Framework Programming. Microsoft Press, 2002. Amit Kalani. MCAD/MCSD Training Guide (70-316): Developing and Implementing Windows-Based Applications with Visual C# and Visual Studio .NET. Que Certification, 2002. Visual C# Support Center: http://support.microsoft.com ?scid=fh;en-us;vcsnet. Visual Studio .NET Support Center: http://support. microsoft.com?scid=fh;en-us;vsnet. 5 Data Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ Data binding ✓ Simple data binding ✓ Complex data binding ✓ One-way data binding ✓ Two-way data binding ✓ Relational database ✓ Data Form Wizard ✓ Filtering ✓ Transforming ✓ View ✓ Lookup Techniques you’ll need to master: ✓ Understand the difference between simple and complex data binding. ✓ Know the more common members of the CurrencyManager class. ✓ Understand how to filter data within the client application and at the server. 120 Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Few applications will be completely monolithic or will operate without communicating with other files. Most applications will interact with some type of data, whether in the form of a database, an array of values, or some other form of data storage. In this chapter, we review the process of linking data to the user interface and accessing only the data that the user needs. Chapter 6, “Consuming and Manipulating Data,” covers consuming and manipulating this data. One of the most important programming tasks that you might face will be to connect data to the user interface, a process referred to as data binding. An application’s data model includes many data sources, such as databases, arrays of values, XML files, or data values stored using objects within the System.Collections namespace. It is often not desirable to provide all possible records to the user at one time, requiring data filtering to extract only the target data. At other times, data might not be stored in a user-friendly form, requiring transformation to a more useful format before it is presented within the user interface. Binding Data to the User Interface The process of data binding involves creating a link between the data model and the user interface. Depending on your application’s requirement, you may use different techniques for databinding: ➤ Simple data binding ➤ Complex data binding ➤ One-way and Two-way data binding ➤ The Data Form Wizard Simple Data Binding Simple data binding involves connecting a single value from the data model to a single property of a control. By default, a new control is unbound. To bind a control, you can add a new Binding object to its ControlDataBindings collection, which is accessed through its DataBinding property. Using the Add method for the Binding class requires the following information: ➤ The name of the bound property ➤ The data source to bind ➤ The navigation path to the data (empty if there is only a single property of an object to bind) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data . . . Binding . . . . Now that you’ve seen the basics of simple databinding, I’ll start by looking at which entities can be bound to the user interface and which properties you can bind to those entities. I’ll also explain the architecture that the .NET Framework uses to manage simple data binding. You’ll see that you can work directly with the objects that handle the databinding connections if you need to interact with the databinding process from your code. Bindable Entities and Properties The Binding class can accept many data sources, including these: ➤ An instance of a class that implements the IBindingList or ITypedList interface, including DataSet, DataTable, DataView, and DataViewManager ➤ A class that implements the IList interface on an indexed collection of objects, such as classes that inherit from System.Array ➤ An IList of strongly typed objects, such as an array of objects A strongly typed object is explicitly declared to represent only one type. Unlike a weakly typed object, it cannot be used to represent a different type during the course of execution. You perform a simple data-binding operation by completing the following steps: 1. Launch Visual Studio .NET and add a new Visual C# .NET Windows Application project. 2. Add a TextBox control named txtVendorName to your form. 3. Add a new class named Vendor.cs, and provide this code for the class: public class Vendor { private string vendorName; public string VendorName { get { return vendorName; } set { vendorName = value; } } public Vendor(string strVendorName) { this.VendorName = strVendorName; 121 122 Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . } } 4. Add the following code to the form’s code module: private void Form1_Load(object sender, System.EventArgs e) { // Create an array of vendor objects Vendor[] aVendors = new Vendor[3]; aVendors[0] = new Vendor(“Microsoft”); aVendors[1] = new Vendor(“Rational”); aVendors[2] = new Vendor(“Premia”); // Bind the array to the textbox txtVendorName.DataBindings.Add(“Text”, aVendors, “VendorName”); } 5. Add a Main method to launch the form. Set the form as the startup object for the project and run the project. The TextBox control is now bound to the array, displaying its first value. It is possible to bind data to any control that has a DataBindings property. This includes all controls derived from the System.Windows.Forms.Control class. Data Binding Architecture When a control is bound to a data source, the .NET Framework creates a pair of objects to manage this link: ➤ CurrencyManager object—An instance of the CurrencyManager class, the CurrencyManager object, keeps track of which element from a data source is currently bound to a control. All controls on a form that are bound to the same data source can share the same CurrencyManager object. ➤ BindingContext object—An instance of the BindingContext class, the BindingContext object, keeps track of the CurrencyManager objects on a form, allowing navigation through the elements within the data source. Container controls (such as GroupBox, Panel, or TabControl) can have their own BindingContext object, allowing separate views of the same data on a form. The BindingManagerBase class is the abstract base class of both the CurrencyManager and the BindingContext class and is used to manipulate the current value of an individual property rather than the property of the current object in a list. Table 5.1 details some of the most important members of this class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data . . . Binding . . . . Table 5.1 Important Members of the BindingManagerBase Class Member Type Description AddNew Method Adds a new object to the underlying list Bindings Property Gives the collection of bindings being managed by this class CancelCurrentEdit Method Cancels any edit in progress Count Property Gives the number of rows managed by the class Current Property Gets the current object CurrentChanged Event Fires when the bound value changes EndCurrentEdit Method Commits any edit in process GetItemProperties Method Lists item properties for the current object in the list Position Property Gets or sets the position in the underlying list that is bound with this class PositionChanged Event Fires when the Position property changes RemoveAt Method Removes the object at the specified position from the underlying list ResumeBinding Method Resumes data binding SuspendBinding Method Suspends data binding The CurrencyManager class extends the BindingManagerBase class to include some additional members, detailed in Table 5.2. Table 5.2 Additional Members of the CurrencyManager Class Member Type Description ItemChanged Event Occurs when the current item has been altered List Property Gets the IList interface from the data source Refresh Method Repopulates the bound controls Remember that the ItemChanged event fires when the data itself is changed by some external action, the CurrentChanged event fires when the data is changed within the user interface, and the PositionChanged event fires when the Position property is changed (which also fires the CurrentChanged event). The BindingContext class provides a means of retrieving the CurrencyManager objects on a form. Table 5.3 details some of the most important members of this class. 123 124 Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 5.3 Important Members of the BindingContext Class Member Type Description Contains Method Indicates whether the BindingContext contains a specific BindingManagerBase object. Items Property Retrives a BindingManagerBase object. This property is an indexer for the BindingContext class. Complex Data Binding Complex data binding involves binding a control to an entire collection of data rather than to a single data item. Figure 5.1 shows an example of complex binding between a DataGrid control and the Suppliers table within the Northwind database. Figure 5.1 A DataGrid control displaying the Suppliers table of the Northwind database. Binding to a Control The ComboBox and ListBox controls are used to allow selection of a value from a listing of values, which might be bound to the control through a complex binding. You perform a complex data binding operation using a ListBox control by completing the following steps: 1. Launch Visual Studio .NET and add a new Visual C# .NET Windows Application project. 2. Add a ListBox control named lbExams to your form. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data . . . Binding . . . . 3. Add a new class named Exam.cs, and provide this code for the class: public class Exam { private String examNumber; private String examName; public String ExamNumber { get { return examNumber; } } public String ExamName { get { return examName; } } public Exam(String strExamNumber, String strExamName) { examNumber = strExamNumber; examName = strExamName; } } 4. Add the following code to the form’s code module: private void Form1_Load(object sender, System.EventArgs e) { Exam[] aExams = {new Exam(“305”, “Web Applications With VB.NET”), new Exam(“306”, “Windows Applications With VB.NET”), new Exam(“310”, “XML With VB.NET”), new Exam(“315”, “Web Applications With Visual C# .NET”), new Exam(“316”, “Windows Applications With Visual C# .NET”), new Exam(“320”, “XML With Visual C# .NET”)}; lbExams.DataSource = aExams; lbExams.DisplayMember = “ExamName”; } 5. Set the form as the startup object for the project, add a Main method that launches the form, and run the project. The ListBox control displays the ExamName property of all objects in the array. It is also possible to bind multiple data sources to the same control, using the properties of the control to provide a link between the data bindings. You can modify the ListBox example to do this by following these steps: 1. Open your project, add a second class named Candidate.cs, and pro- vide this code for the new class: public class Candidate { private string examNumber; 125 126 Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . private string candidateName; public string ExamNumber { get { return examNumber; } set { examNumber = value; } } public string CandidateName { get { return candidateName; } set { candidateName = value; } } public Candidate(String strCandidateName, String strExamNumber) { this.CandidateName = strCandidateName; this.ExamNumber = strExamNumber; } } 2. Add two Label controls, two Button controls (btnPrevious and btnNext), and two TextBox controls (txtCandidateName and txtExamNumber) to your form. 3. Modify the form’s code module to this: private Candidate[] aCandidates = { new Candidate(“Bill Gates”, “305”), new Candidate(“Steve Ballmer”, “320”)}; private void Form1_Load(object sender, System.EventArgs e) { Exam[] aExams ={ new Exam(“305”, “Web Applications With VB.NET”), new Exam(“306”, “Windows Applications With VB.NET”), new Exam(“310”, “XML With VB.NET”), new Exam(“315”, “Web Applications With Visual C# .NET”), new Exam(“316”, “Windows Applications With Visual C# .NET”), new Exam(“320”, “XML With Visual C# .NET”)}; lbExams.DataSource = aExams; lbExams.DisplayMember = “ExamName”; lbExams.ValueMember = “ExamNumber”; txtCandidateName.DataBindings.Add( “Text”, aCandidates, “CandidateName”); txtExamNumber.DataBindings.Add( “Text”, aCandidates, “ExamNumber”); . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data . . . Binding . . . . lbExams.DataBindings.Add( “SelectedValue”, aCandidates, “ExamNumber”); } private void btnPrevious_Click(object sender, System.EventArgs e) { this.BindingContext[aCandidates].Position -= 1; } private void btnNext_Click(object sender, System.EventArgs e) { this.BindingContext[aCandidates].Position += 1; } 4. Set the form as the startup object for the project, include the Main method to launch the form, and run the project. The ListBox control displays the ExamName property of all objects in the array, as before. However, if you change the selected value within the ListBox or txtExamNumber controls, the change is reflected in the other as soon as the change is committed by tabbing to another control. When using the Position method of the BindingContext property, incrementing one element forward is accomplished by += 1, while decrementing is accomplished by -= 1. Using the DataGrid Control The DataGrid control is also a popular control used to present complex bound data. Its AutoFormat capability allows for the selection of many different formats, as shown in Figure 5.2. Figure 5.2 Three DataGrid controls formatted using different AutoFormat selections. If you want to set the formatting options of a DataGrid control more directly, many useful settings are available. Table 5.4 details some of the most useful display properties of the DataGrid control. 127 128 Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 5.4 DataGrid Control Display Properties Property Explanation AlternatingBackColor Background color to use for even-numbered rows in the grid BackColor Background color to use for odd-numbered rows in the grid BackgroundColor Color to use for any portion of the control that is not filled with data BorderStyle Select from None, FixedSingle, or Fixed3D for the border style CaptionBackColor Background color for the caption portion of the control CaptionFont Font for the caption portion of the control CaptionText Display text for the caption portion of the control CaptionVisible Boolean property that controls whether a caption will be displayed ColumnHeadersVisible Boolean property that controls whether each column will have a header FlatMode Boolean property that controls whether the grid will have a 3D or a flat appearance Font Font for text in the control ForeColor Foreground color for text in the control GridlineColor Color for the lines of the grid GridlineStyle Either None or Solid HeaderBackColor Background color for column and row headers HeaderFont Font for column and row headers HeaderForeColor Foreground color for column and row headers LinkColor Color to use for hyperlinks between sections of the control ParentRowsBackColor Background color to use for the parent row’s area ParentRowsForeColor Text color to use for the parent row’s area ParentRowsLabelStyle Either None, TableName, ColumnName, or Both ParentRowsVisible Boolean property that controls whether the parent row’s area is visible PreferredColumnWidth Default width for columns (pixels) PreferredRowHeight Default height for rows (pixels) RowHeadersVisible Boolean property that controls whether each row will have a header RowHeaderWidth Default width of row headers (pixels) SelectionBackColor Background color for selected cells SelectionForeColor Text color for selected cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data . . . Binding . . . . One-Way and Two-Way Data Binding Data binding can be either one-way or two-way. In one-way data binding, changes to the underlying data model are reflected in the bound property of the control, but changes to the bound property are not propagated back to the data model. In two-way data binding, changes to the bound property value of the control also are reflected in the underlying data model, and vice versa. This is typically accomplished through the Update method of the DataAdapter object, which is covered in Chapter 6. In some cases, such as with the DataSet class, the data model and the actual original source of the data are not the same. This requires additional code to change values in the original data source to reflect changed values within the data model. The Data Form Wizard Visual Studio .NET includes a utility named the Data Form Wizard that automates much of the configuration necessary when creating data-bound forms. This utility can be used to create single-table forms as well as multitable forms. Multitable forms rely on key field relationships between tables to associate records in one table with those in another. A database is a collection of tables. Tables contain rows of data called records, and records are made up of elements (also called fields) that are arranged in columnar layout. Relational databases use a key column to link related data between tables. A foreign key value in one table relates records in that table to a record in another table that has a matching primary key value. Transforming and Filtering Data You usually want to present less than the total number of records available to your users, to make your application more user-friendly. If you have a table named Invoices that has a few hundred thousand entries and you need a listing of open invoices only for a particular customer, it would not be good design planning to require users to find the few necessary records. Restricting data returned to the user interface is a process known as filtering. Your database might also record the clientID field for each invoice, and you want to provide the data to your users with a more useful name value. Manipulating output data is a process referred to as transformation. 129 130 Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Server Explorer Before we address filtering and data transformation, you should be familiar with the Server Explorer, which is available in the Visual Studio .NET IDE. The Server Explorer provides ready access to available data connections and other services, some of which are listed in Table 5.5. Table 5.5 Manageable Resources Available Through the Server Explorer Resource Type Represents Data connection A connection to a particular database Crystal Services Options for Crystal Reports Event Logs Windows event logs Message Queues Windows message queues Performance Counters Windows performance counters Services Windows services SQL Servers Microsoft SQL Servers When creating data-bound applications, you add a data connection by completing the following steps: 1. Open a Visual C# .NET Windows Application project. 2. Expand the Server Explorer, right-click the Data Connections node, and select Add Connection from the options provided. 3. Provide the connection information necessary for your data source. The default is the Microsoft OLE DB Provider for SQL Server, but others are available, including Oracle and Jet (Access) database support. 4. Click OK to create the new data connection. This new connection remains across all of your projects unless you right-click the connection and select Delete. 5. Left-click on an element within the Data Connections node and drag it to a form within your project. This automatically creates the necessary code for the relevant data source used within your application. When working with Microsoft SQL Server 7 and above, dragging and dropping a database onto a form creates a new SqlConnection object. Tables, views, or columns create a new SqlDataAdapter object. Stored procedures and table-valued functions create a new SqlCommand object. All of these are members of the System.Data.SqlClient namespace and are covered in more detail in Chapter 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data . . . Binding . . . . Filtering and Transforming Data Filtering data involves selecting a subset of available data. Filtering can be performed in the application client using a DataView object or on the server using an SQL view. The DataView object or the SQL view can also be used to transform data into a more user-friendly format, such as translating a CustomerID field for a series of invoices into a human-readable CustomerName value before presenting the information to the user interface for display. A DataView object represents a bindable, filterable view of a DataTable. A DataSet contains a collection of DataTable objects, such as the Tables collection and the Relations collection, that is made up of DataRelation objects. The following example assumes that you have the default Northwind database available on an SQL Server. It is also possible to create a Data Connection to the Jet (Access) version of the Northwind database to perform this example. You can create a DataSet and filter the resulting data using a DataGrid control by following these steps: 1. Open a Visual C# .NET Windows Form project, and expand the Server Explorer. 2. Expand the Data Connections node to show the SQL Server connec- tion for the Northwind database. 3. Expand the Tables node of this datbase. Drag the Customers table and drop it on your form, creating two new data objects (SqlConnection1 and SqlDataAdapter1). 4. Select the SqlDataAdapter1 object and click the Generate Dataset link in the Properties window. Name the DataSet as dsCustomers1 and click OK. 5. Add a DataGrid control (dgCustomers) on your form and set its CaptionText property to Customers. 6. Open the form’s code module and add the following: private void Form1_Load(object sender, System.EventArgs e) { sqlDataAdapter1.Fill(dsCustomers1, “Customers”); System.Data.DataView dvCustomers = new System.Data.DataView(dsCustomers1.Tables[“Customers”]); dvCustomers.Sort = “ContactName”; 131 132 Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dvCustomers.RowFilter = “Country = ‘France’”; dgCustomers.DataSource = dvCustomers; } 7. Set the form as the startup object for the project, add a Main to launch the form, and run the project. The DataGrid displays the filtered data, showing only Customers from France, sorted by the ContactName field. Client-side filtering using the DataView is useful but can be very inefficient when dealing with large sets of data. Instead of sending everything over the network and then selecting the needed data, it is more efficient to create a SQL view on the server, which is a derived set of data that acts much like a table. The SQL view can be configured to present only the desired subset of data, minimizing the amount of data that must be transferred over the network to your client application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data . . . Binding . . . . Practice Questions Question 1 Your application includes a form that displays employee names in a simplebound TextBox control. You’d like to add a tooltip to the TextBox control, with the tooltip displaying the title of the employee. The employee names and employee titles are both supplied by the same IList. How can you do this? ❍ A. Bind the employee title to the Tag property of the TextBox control. In the event handler for the PositionChanged event of the CurrencyManager object, call the ToolTip’s SetToolTip method to copy the value from the Tag property to the Tooltip. ❍ B. Bind the employee title to the Name property of the ToolTip control. ❍ C. Bind the employee title to the Tag property of the TextBox control. In the event handler for the CurrentChanged event of the CurrencyManager object, call the ToolTip’s SetToolTip method to copy the value from the Tag property to the Tooltip. ❍ D. Bind the employee title to the Tag property of the TextBox control. In the event handler for the ItemChanged event of the CurrencyManager object, call the ToolTip’s SetToolTip method to copy the value from the Tag property to the Tooltip. Answer A is correct. You should bind the employee title to the Tag property of the TextBox control and then in the event handler for the PositionChanged event of the CurrencyManager object, call the ToolTip’s SetToolTip method to copy the value from the Tag property to the Tooltip. Answer B is not correct because the value displayed by the Tooltip can only be set with the SetToolTip method. Answers C and D are not correct because the appropriate event for renewing the Tooltip is the PositionChanged event, which fires whenever a record becomes current. Question 2 Which form of data binding must be used when populating a DataGrid component? (Select the best answer.) ❍ A. Simple data binding ❍ B. One-way data binding ❍ C. Two-way data binding ❍ D. Complex data binding 133 134 Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer D is correct. Complex data binding involves binding an entire group of data to a control, such as when populating a DataGrid control. Answer A is incorrect because simple data binding involves the association of a single element or value to the bound control. Answers B and C are incorrect because they involve whether changes are made to data within the component, and the proposed scenario could be of either type. Question 3 You have an XML file containing information on customers. You plan to make this information available to your users by using simple databinding to controls on the user interface. What must you do? ❑ A. Transfer the data from the XML file to a data structure that implements the IList, IBindingList, or ITypedList interfaces. ❑ B. Create an XML Web Service to retrieve information from the file. ❑ C. Store the XML file in a SQL Server database. ❑ D. Set the Tag property of each control that you will use for databinding to “XML”. Answer A is correct. Only this answer will produce data that can be bound. Answers B, C and D are not correct because the data in these solutions cannot be bound to the controls. Question 4 Your application includes a SqlDataAdapter object named sqlDataAdapter1 that was created by dragging and dropping the Physicians table from a database to your form. Your application also includes a Dataset named dsPhysicians1, based on this SqlDataAdapter. What line of code should you use to load the data from the database into the Dataset? ❍ A. dsPhysicians = sqlDataAdapter1.Fill(“Physicians”); ❍ B. sqlDataAdapter1.Fill(“dsPhysicians1”, “Physicians”); ❍ C. sqlDataAdapter1.Fill(dsPhysicians1); ❍ D. sqlDataAdapter1.Fill(dsPhysicians1, “Physicians”); . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data . . . Binding . . . . Answer D is correct. In a call to the Fill method of a SqlDataAdapter object, you must specify the Dataset to fill as an object and the table to fill as a string. Answer A is not correct because the return type of the Fill method is an int value instead of DataSet. Answer B is not correct because the first argument to the Fill method should be type DataSet instead of String. Answer C is not correct because if you do not specify the name of the data table in the second parameter, the Fill method adds or refreshes data into a table named “Table”. Question 5 Which data binding class forms the parent for the others? (Select the best answer.) ❍ A. CurrencyManager ❍ B. BindingContext ❍ C. BindingManagerBase ❍ D. BaseCollection ❍ E. BindingsCollection Answer C is correct. The BindingManagerBase class is an abstract class that is implemented in both the CurrencyManger and the BindingContext classes, making answers A and B incorrect. Answer D is not correct because the BaseCollection class provides the base functionality for creating data-related collections. Answer E is not correct because the BindingsCollection class represents a collection of Binding objects for a control. Question 6 Which of the following events would be triggered by incrementing the Position property of a CurrencyManager object by one? (Select all that apply.) ❑ A. CurrentChanged ❑ B. ItemChanged ❑ C. ValueChanged ❑ D. PositionChanged Answers A and D are correct. When the Position value is changed, the PositionChanged and CurrentChanged events fire. Answer B is incorrect because the ItemChanged value fires when the underlying data is changed by an external action. Answer C is incorrect because no ValueChanged event is defined within the CurrencyManager class. 135 136 Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 7 Your application is connected to a SQL Server database that contains customer and order information. You have a form in your application that fills a Dataset with information from the Orders table that includes the CustomerID. The Dataset is displayed on the form by using complex data binding to a DataGrid. Now you’ve been asked to display the CustomerName column from the Customers table in the DataGrid, instead of the CustomerID column. How should you proceed? ❍ A. Create a view in the SQL Server database that combines the Customers and Orders tables. Replace the Dataset on the form with a new Dataset based on this new view. Bind the new Dataset to the DataGrid. ❍ B. Add a second Dataset to the form. Base the second Dataset on the Customers table from the database. Use each Dataset to fill the appropriate columns of the DataGrid. ❍ C. Create a DataView in code from the existing Dataset. Filter the DataView to remove the CustomerID column. ❍ D. Add an array of Customer objects to your application and initialize it in code with customer names and IDs. Use a view to join this array to the existing Dataset. Answer A is correct. Only answer A lets you set up the DataGrid so that it’s automatically kept up to date. Answers B and C are unworkable. Answer D requires you to maintain the code to synchronize the array with the actual data in the database. Question 8 Which of the following DataGrid control properties specifies the color to use on odd-numbered rows in the grid? ❍ A. BackColor ❍ B. BackgroundColor ❍ C. AlternatingBackColor ❍ D. ParentRowsBackColor ❍ E. SelectionBackColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data . . . Binding . . . . Answer A is correct. The BackColor property specifies the color to be used for odd-numbered rows on the grid; the AlernatingBackColor property specifies the color to be used for even-numbered rows, making answer C incorrect. Answer B is incorrect because the BackgroundColor property specifies the color to be used to fill any area without data. Answer D is incorrect because the ParentRowBackColor property specifies the color to be used for the background of the parent row’s area. The SelectionBackColor property specifies the color to be used to highlight currently selected cells, making answer E incorrect as well. Question 9 You have a large database made up of customer and order records, linked by a CustomerID field. You want to provide access to all open orders from customers located in Texas, sorted by customer. What is the best solution to fulfill this requirement in the most efficient manner? (Select the best answer.) ❍ A. Create a lookup view on the server to translate each Order.CustomerID value into its State value and sort by state for Texas. ❍ B. Create a view on the server that limits the result set to records with a related address State value of Texas. ❍ C. Bind the table to a DataView component and restrict the records to those with a State value of Texas. ❍ D. Create a view on the server to translate each Order.CustomerID value into its State value, and filter the records to include only those from Texas. Answer B is correct. The best solution is to create a server-side multitable view that filters for open records in the Orders table that are related to customers with a Customers.State value of Texas. Answers A and D are incorrect because both involve the translation of an order’s CustomerID into its related State value, which would prevent sorting by customer without adding another field. The requirement mandates the most efficient method, making answer C incorrect because a client-side filtering solution requires all data to be first sent to the client and then filtered. 137 138 Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 10 You are working with a complex form that uses Panel controls to organize a large amount of data. The form displays information from six different data sources. Some of the panels contain data from more than one data source. You have added navigation buttons to scroll through the data in one particular data source. The navigation buttons increment and decrement the Position property of a CurrencyManager object. You test the form, and the buttons do not appear to scroll the data in that data source. What could be the problem? (Choose two.) ❑ A. There are too many controls on the form, so your code is not being executed. ❑ B. You retrieved the CurrencyManager through the Form’s BindingContext object, but the Panel control has its own BindingContext object. ❑ C. This particular CurrencyManager object does not support a Position property. ❑ D. The BindingContext object that you’re using has more than one CurrencyManager object, and you’re working with the wrong one. Answer B and D are correct. You are working with the wrong CurrencyManager object because you retrieved the CurrencyManager through the Form’s BindingContext object, but the Panel control has its own BindingContext object. Answer A is not correct because it would take a truly astronomical number of controls to cause problems with .NET’s code execution. Answer C is not correct because all CurrencyManager objects support a Position property. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data . . . Binding . . . . Need to Know More? Kalani, Amit. MCAD/MCSD Training Guide (Exam 70-316): Developing and Implementing Windows-based Applications with Visual C# .NET and Visual Studio .NET, Que Certification, 2003. Moore, Thomas. MCSE/MCSD Training Guide: SQL Server 2000 Database Design and Implementation (Exam 70-229), Que Certification, 2002. Microsoft ADO.NET Support Center: http://support. microsoft.com? id=fh;en-us;adonet. Microsoft SQL Server Site: www.microsoft.com/sql. 139 6 Consuming and Manipulating Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ System.IO and System.Xml namespaces ✓ ADO.NET ✓ Transact-Structured Query Language (T-SQL) ✓ FileStream and DataAdapter objects ✓ DataView object ✓ Extensible Markup Language (XML) ✓ XmlDocument and XmlDataDocument objects Techniques you’ll need to master: ✓ Understand ad-hoc queries and stored procedures. ✓ Know how to construct basic T-SQL statements, including SELECT, INSERT, UPDATE, and DELETE, as well as SQL Server stored procedures. ✓ Know which objects are part of the System.Data namespace shared by all data providers and which are part of specific data provider namespaces, such as System.Data.SqlClient and System.Data.OleDb. ✓ Understand how to use the DataSet object to make data available within your application. ✓ Know how to read and write XML data and synchronize an XML document. 142 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Now that you know how to bind controls to the data model, you should develop an understanding of the basics involved in manipulating and consuming (using) data from a variety of sources. The .NET Framework includes support for data in various forms, including the following: ➤ System.IO namespace to access file-based data storage ➤ System.Data, System.Data.SqlClient, and System.Data.OleDb, System.Data.Common and System.Data.SqlTypes namespaces (which are collectively known as ADO.NET) used to access relational databases ➤ System.Xml and its other child namespaces to manipulate XML data files This chapter focuses on accessing data located in external disk files, relational databases, and XML files, along with a brief review of SQL Server operation and the handling of data errors. Transact-SQL Microsoft’s implementation of the Structured Query Language (SQL) standard is named Transact-SQL (T-SQL). T-SQL queries provide a flexible way of retrieving data from a SQL Server database or making changes to that database. The four main T-SQL statements that help you manipulate SQL Server data are as follows: ➤ SELECT statement—Used to retrieve stored data ➤ INSERT statement—Used to add new data ➤ UPDATE statement—Used to modify existing data ➤ DELETE statement—Used to remove existing data T-SQL is derived from the American National Standards Institute (ANSI) SQL-92 standard. The SELECT Statement The SELECT statement is used to retrieve data from one or more tables in a database. A SELECT statement looks like this: 143 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . SELECT field_list FROM table_list WHERE where_clause GROUP BY group_by_clause HAVING having_clause ORDER BY sort_clause The order of these clauses is fixed, although only the SELECT and FROM clauses are required. The rest are optional, as in this example: SELECT CustomerID as CustID, CustomerName as CustName FROM Customers This would return the CustomerID and CustomerName fields for all records in the Customers table, naming the resulting fields CustID and CustName, respectively. It is also possible to select all fields in a table using the asterisk (*) character, as shown here: SELECT * FROM Customers In addition, it is possible to select data from multiple tables at once, as in this example: SELECT Customers.CustomerID as CustID, O.OrderID as OrdID FROM Customers INNER JOIN Orders as O ON Customers.CustomerID = O.CustomerID Note the use of the <table1> INNER JOIN <table2>...ON <relationship> syntax. This causes the result to include only those records in each table that have a matching value in the other table. Without this, the query could result in a cross-product result set, in which the result set includes one row in the output for each row in each combination of input table rows. This can rapidly bloom into a huge result set. A cross-product of two tables, each with only 100 records, results in 100 × 100 = 10,000 records returned. You can filter the result set generated by a SELECT query by including a WHERE clause, as in this example: SELECT TOP 50 * FROM Customers WHERE State = ‘Washington’ AND CustomerName LIKE ‘B%’ AND CurrentCredit < 5000 ORDER BY CurrentCredit DESC, CustomerName This example selects the first 50 matching records from the Customers database where the State field holds the value of Washington, the CustomerName begins with the letter B, and the customer’s CurrentCredit value is less than 5,000. When selecting the first 50, the order is determined by sorting in descending order on the CurrentCredit value first, and then in 144 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ascending order on the CustomerName field when the CurrentCredit values match. Wildcard values can be used in SQL language queries by using the LIKE keyword instead of the equals sign (=) and by placing the wildcard symbol (%) (for zero or more characters and _ for one character) in the desired location within the test string. It is also possible to search for a single-replacement character within a set of values using square brackets ([]). In this way, ...WHERE ProductID LIKE ‘PANT[ABC]’... would return all records whose ProductID matches PANT-A, PANT-B, or PANT-C. You can use the GROUP BY clause in a query to retrieve a result set with summarized information. You can make use of aggregate functions within an SQL query statement along with the GROUP BY clause to retrieve summarized information, as shown here: SELECT Count(CustomerID) as CustCount, State FROM [Customer Data] GROUP BY State ORDER BY CustCount DESC This generates a result set that counts the number of customers for each State from the Customer Data table; it is ordered by the customer count per state in descending order. Note the use of square brackets ([ ]) to enclose the Customer Data table name. This is required because the table name includes a space. Some of the more common aggregate functions used with the GROUP BY clause include these: ➤ Count function—Counts the number of returned records ➤ Sum function—Adds the values of all returned records ➤ Avg function—Returns the average value for all returned records ➤ Min function—Returns the smallest value within all returned records ➤ Max function—Returns the largest value within all returned records When working with aggregate functions, it is important to identify whether a restricting filter is applied in the proper manner. The WHERE clause allows filtering of values that will be handed to the aggregating function. The HAVING clause can be used to filter based on the final aggregated value, as 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 145 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . In this example, the WHERE clause causes the query to exclude records with a Quantity value greater than 10 for aggregation. The HAVING clause causes the record set to return only TotalSales values for Products whose Quantity (ignoring the already excluded records) exceeds 1000. SELECT INTO is a special case of the SELECT statement that can be used to create a new table from the result set, as shown here: SELECT * INTO BadCustomers FROM Customers WHERE CurrentCredit < 5000 The INSERT Statement The INSERT statement is used to add new records to a table, and it can be used to insert a single record or multiple records in one statement. An example of a single record insertion is as follows: INSERT INTO [Order Details] (OrderID, ProductID, UnitPrice, Quantity, Discount) VALUES (10248, 2, 12.00, 5, 0) Here, the values of the new record are inserted in the order of the defined field list. If the list of values exactly matches the order of the fields in the table, you can omit the field list, as shown here: INSERT INTO [Order Details] VALUES (10248, 1, 12.00, 5, 0) This method has several drawbacks, including the need to rewrite your queries if the underlying table organization should be changed or when a field has values that are automatically generated by the SQL server. It is also possible to insert multiple records using a single INSERT statement, as shown in this example: INSERT INTO Products (SupplierID, ProductName, CategoryID ) SELECT SupplierID, ‘Trout’, 8 FROM Suppliers Note that a SELECT statement is used to provide the record set that will be inserted into the table. The UPDATE Statement The UPDATE statement allows modification of existing values stored within the database. It is possible to update a single record or multiple records in a single statement, even allowing multiple fields to be updated using a single UPDATE statement, as shown here: 146 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UPDATE Customers SET ContactName = ‘Maria Anders’, Discount = Discount * 2 WHERE CustomerID LIKE ‘AL%’ In this example, all records within the Customers table with a CustomerID starting with AL are updated with a ContactName of Maria Anders and a Discount that is twice the current Discount value. Updating values in one table based on those in another related table is also possible, as shown here: UPDATE Products INNER JOIN ON Suppliers.SupplierID = SET Products.Discontinued WHERE Suppliers.Country = Suppliers Products.SupplierID = 1 ‘Italy’ The DELETE Statement The DELETE statement uses an identical format as the SELECT statement to specify records that will be deleted. However, the DELETE statement does not specify any column list like the SELECT statement does because it removes the specified row(s) from the table: DELETE FROM Customers WHERE CustomerID = ‘GODOS’ Querying SQL Server T-SQL statements are used to manipulate the data present within an SQL Server database. These commands can be passed in an ad-hoc manner to the server or can be compiled as stored procedures on the server itself. The advantage of using stored procedures is that they are faster than ad-hoc queries. The disadvantage of stored procedures is that they are not as flexible as ad-hoc queries, which can be created within your application at runtime. Ad-Hoc Queries Microsoft provides several methods to allow you to execute ad-hoc queries: ➤ Visual Studio .NET IDE—Using the Server Explorer, you can create a new view within the Views folder of a Data Connection object. When you run this query, the results are displayed. ➤ OSQL—This command-line utility ships with SQL Server and can be used to execute ad-hoc queries. 147 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . ➤ SQL Query Analyzer—This full-featured GUI utility provided with SQL Server includes templates for common queries, integrated performance analysis, and an object browser that enables you to see the structure of SQL Server objects. ➤ .NET application—You can use a .NET application to submit an ad-hoc query and then display the returned result set. You can create an application that will submit an ad-hoc SQL query and display its returned result set as follows: 1. Open a Visual C# .NET Windows application and expand the Server Explorer. 2. Expand the Data Connections node to show the SQL Server connec- tion for the Northwind database, created in Chapter 5, “Data Binding.” 3. Drag the data connection and drop it on your form, creating a new sqlConnection1 object. 4. Add a TextBox control (txtQuery), a Button control (btnExecute), and a DataGrid control (dgResults) on your form. Set the Multiline property of the TextBox to true, and set the CaptionVisible property of the DataGrid to false. Refer to Figure 6.1 for the design of this form. 5. Switch to Code view and add the following using directives: using System.Data; using System.Data.SqlClient; 6. Double-click the Button control and add the following code to the Click event handler for the btnExecute control: private void btnExecute_Click(object sender, System.EventArgs e) { SqlCommand cmd = sqlConnection1.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = txtQuery.Text; SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = cmd; DataSet ds = new DataSet(); da.Fill(ds, “Results”); dgResults.DataSource = ds; dgResults.DataMember = “Results”; } 7. Set the form as the startup object for the project, add a Main method, and run the project. 8. Enter a query in the TextBox, such as: SELECT * from Employees 148 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9. Click the botton to execute your ad-hoc statement and display the result set using the DataGrid, as shown in Figure 6.1. Figure 6.1 An ad-hoc query run within the example form. Stored Procedures Stored procedures are precompiled SQL queries that are stored on the server, allowing them to run much more quickly than ad-hoc queries that must first be translated into machine code before execution. Stored procedures can make use of input and output parameters, designated using the @ symbol (example: @TotalSales), as well as special variables such as the @@IDENTITY variable that returns the most recently assigned identity column value. You also can make use of parameters within your application code to prompt the user for an input value. A column with the IDENTITY constraint is given a unique initial value by SQL Server; however, unless other constraints are placed on the column, this value can later be changed. To ensure that a primary key value remains unique, you should use the PRIMARY KEY constraint. Stored procedures can be created using any of the same methods used to execute ad-hoc queries, through the use of the CREATE PROCEDURE (CREATE PROC) statement, as shown here: CREATE PROCEDURE procGermanCustomers AS SELECT * FROM Customers WHERE Country = ‘Germany’ 149 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . After creating the stored procedure, you must save it and then run it to cause the database server to compile the SQL statement and store a copy of the compiled stored procedure. The ExecuteNonQuery method of the SqlCommand object can be used to execute an ad-hoc query or stored procedure that does not return any results to the user. You also can specify variable parameters that provide input and output values for use with your stored procedure, as in the following example, which accepts the input parameter @CustomerID and returns an output parameter value through @TotalSales: CREATE PROC procCustomerSales @CustomerID char(5), @TotalSales money OUTPUT 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 After creating this stored procedure using whichever means you prefer, you can create a sample form that uses the procedure through the following: 1. Open a Visual C# .NET Windows application and expand the Server Explorer. 2. Expand the Data Connections node to show the SQL Server connec- tion for the Northwind database. 3. Drag the data connection and drop it on your form, creating a new sqlConnection1 object. 4. Add two Label controls, two TextBox controls (txtCustomerID and txtTotalSales), and a Button control (btnGetTotalSales) on your form. 5. Switch to Code view and add the following using directives: using System.Data.SqlClient; using System.Data.SqlTypes; 6. Double-click the Button control and add the following code for the Click event handler of the btnGetTotalSales control: private void btnGetTotalSales_Click(object sender, System.EventArgs e) { SqlCommand cmd = sqlConnection1.CreateCommand(); 150 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = “procCustomerSales”; cmd.Parameters.Add(new SqlParameter(“@CustomerID”,SqlDbType.Text,5)); cmd.Parameters[“@CustomerID”].Value = txtCustomerID.Text; cmd.Parameters.Add(new SqlParameter(“@TotalSales”, SqlDbType.Money)); cmd.Parameters[“@TotalSales”].Direction = ParameterDirection.Output; sqlConnection1.Open(); cmd.ExecuteNonQuery(); txtTotalSales.Text = String.Format(“{0:c}”, cmd.Parameters[“@TotalSales”].Value); sqlConnection1.Close(); } 7. Set the form as the startup object for the project, add a Main method, and run the project. Enter a CustomerID from the Customers table in the first TextBox. The form executes your stored procedure and returns the TotalSales value in the second TextBox. Data Access Within the .NET Framework, data access primarily falls within three general categories: ➤ File-based data storage, handled by the System.IO namespace ➤ Relational database storage, handled by the System.Data, System.Data.SqlClient, System.Data.OleDb, System.Data.Common, and System.Data.SqlTypes namespaces that make up ADO.NET ➤ XML data files, handled by the System.Xml namespace Disk Files One of the oldest forms of storage still in common use involves the storage of data within simple disk files, often referred to as flat files to distinguish them from the more structured relational database and hierarchical XML storage models. Browsing When your application needs to include external file data, it is often useful to allow users to browse to the desired file’s location. This is accomplished by invoking an instance of the System.Windows.Forms.OpenFileDialog class, as shown here: 1. Open a Visual C# .NET Windows application. 151 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . 2. Place a Button control (btnBrowse) and a TextBox control (txtFilename) on the form. 3. Attach a Click event handler to the Button control and add the follow- ing code: private void btnBrowse_Click(object sender, System.EventArgs e) { OpenFileDialog dlgOpen = new OpenFileDialog(); dlgOpen.Title = “Select a File”; dlgOpen.Filter = “Text files (*.txt)|*.txt|All Files(*.*)|*.*”; if(dlgOpen.ShowDialog() == DialogResult.OK) { txtFilename.Text = dlgOpen.FileName; } } 4. Set the form as the startup object for the project, add a Main method, and run the project. When you click the button, the File Open dialog box opens. After you select a file and click Open, the name of the file is displayed in the TextBox. Streams and Backing Classes File-based data access involves two primary concepts: ➤ Stream—A flow of raw data ➤ Backing store—A place to put data, such as a file, a network connection, an Internet address, or even a section of memory The System.IO namespace includes several classes suitable for accessing and manipulating streams and backing stores: ➤ FileStream class—Treats a file simply as a stream of bytes ➤ StreamReader class—Reads data as characters from a stream ➤ StreamWriter class—Writes characters to a stream ➤ BinaryReader class—Reads primitive data types as binary values from a stream ➤ BinaryWriter class—Writes primitive data types as binary values to a stream The FileStream class treats a file as a stream of bytes. The FileStream class is your best option when you don’t know (or don’t care) about the internal structure of the files with which you’re working. For files with known internal structures, you can use specific objects such as BinaryReader, 152 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BinaryWriter, StreamReader and StreamWriter; in this case, the FileStream object handles opening a particular disk file and serves as a parameter to the constructor of these objects. You can think of these other objects as forming an additional layer of functionality on top of the FileStream class. Table 6.1 includes some of the important members of the FileStream object. Table 6.1 Important Members of the FileStream Object Member Type Description CanRead Property Returns true if you can read from the FileStream CanSeek Property Returns true if you can seek to a particular location in this FileStream CanWrite Property Returns true if you can write to the FileStream Close Method Closes the FileStream and releases associated resources Flush Method Writes any buffered data to the backing store Length Property Gives the length of the FileStream in bytes Position Property Returns the position within the FileStream Read Method Reads a sequence of bytes ReadByte Method Reads a single byte Seek Method Sets the FileStream to a specified position Write Method Writes a sequence of bytes WriteByte Method Writes a single byte The following example shows how to write and read data as binary values using the BinaryWriter and BinaryReader classes. The BinaryReader and BinaryWriter classes offer streaming functionality oriented toward particular data types. 1. Open a Visual C# .NET Windows application. 2. Place a Button control (btnCreateFile) and a ListBox control (lbData) on the form. 3. Switch to Code view and add the following using directive: using System.IO; 4. Double-click the Button control and enter this code to handle the Click event of the Button control: private void btnCreateFile_Click(object sender, System.EventArgs e) { // Create a new file to work with FileStream fsOut = File.Create(@”c:\temp\test.dat”); 153 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . // Create a BinaryWriter to handle writing BinaryWriter bw = new BinaryWriter(fsOut); // And write some data Int32 intData1 = 7; Decimal dblData2 = 3.14159M; String strData3 = “Pi in the Sky”; bw.Write(intData1); bw.Write(dblData2); bw.Write(strData3); bw.Flush(); bw.Close(); fsOut.Close(); // Now open the file for reading FileStream fsIn = File.OpenRead(@”c:\temp\test.dat”); // Create a BinaryReader to handle reading BinaryReader br = new BinaryReader(fsIn); // And read the data lbData.Items.Add(“Int32: “ + br.ReadInt32()); lbData.Items.Add(“Decimal: “ + br.ReadDecimal()); lbData.Items.Add(“String: “ + br.ReadString()); br.Close(); fsIn.Close(); } 5. Set the form as the startup object for the project, and add a Main method. 6. Run the project and click the button. The file is created on your hard drive, and the list box shows the contents of the file. c:\temp\test.dat The ADO.NET Object Model ADO.NET refers to the collection of classes that the .NET Framework provides for working with data in relational databases. The ADO.NET object model is separated into two primary types of objects: ➤ Data provider objects—Used to access and manage the data stored within the DataSet objects ➤ DataSet objects—Used to store data within the data model Data Provider Objects Visual Studio .NET ships with several data providers, including the SQL Server data provider (System.Data.SqlClient) and the OLEDB data provider (System.Data.OleDb). Each of these namespaces provides access to variations of the standard data provider objects: Connection, Command, Parameter, DataReader, and DataAdapter. 154 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Although this section examines the objects provided by the SQL Server data provider (SqlConnection, SqlCommand, SqlParameter, SqlDataReader, and SqlDataAdapter), there are implementations of the same objects within the OLE DB data provider as well (OleDbConnection, OleDbCommand, OleDbParameter, OleDbDataReader, and OleDbDataAdapter). The Connection Object The Connection object represents a single persistent connection to a data source. The SQL Server implementation of this object is the SqlConnection object. Table 6.2 details some of the most important members of this object. Table 6.2 Important Members of the SqlConnection Object Member Type Description BeginTransaction Method Starts a new transaction Close Method Returns the connection to the pool ConnectionString Property The server used by this connection CreateCommand Method A new SqlCommand object executing through this connection Open Method Opens the connection When a connection is closed, it is simply returned to a pool of available connections to later be reused. The Command and Parameter Objects A Command object represents an executable action, while a Parameter object represents a single value passed to a stored procedure. These objects are implemented within the SQL Server data provider as the SqlCommand and SqlParameter objects. Table 6.3 details some of the most important members of the SqlCommand object. Table 6.3 Important Members of the SqlCommand Object Member Type Description CommandText Property Represents the statement to be executed by the command CommandType Property Specifies the type of the command, such as Text, StoredProcedure, or TableDirect (continued) 155 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . Table 6.3 Important Members of the SqlCommand Object (continued) Member Type Description Connection Property Represents the connection through which the command executes CreateParameter Method Creates a new parameter ExecuteNonQuery Method Executes a command that does not return a result set ExecuteReader Method Executes a command and returns the results in a DataReader object ExecuteScalar Method Executes a command and returns the first column of the first row of the result set ExecuteXmlReader Method Executes a command and returns the results in an XmlReader object Parameters Property Collection of parameter objects for this command The DataReader Object When the ExecuteReader method of the Command object is called, the result set is returned in a DataReader object. This read-only object can be accessed only sequentially from first to last, but it results in high-speed data retrieval. The DataReader object is implemented within the SQL Server data provider as the SqlDataReader object. The methods of the DataReader class return values from a single record at a time or a single element at a time from a specified column. It is very important to call the DataReader.Close method when you are done, to release the Connection object for other uses. The DataAdapter Object The DataAdapter object provides a two-way data-transfer conduit between data provider and DataSet objects. Within the SQL Server data provider, this object is implemented as the SqlDataAdapter object. Some of the most important members of this object are detailed in Table 6.4. Table 6.4 Important Members of the SqlDataAdapter Object Member Type Description DeleteCommand Property Specifies the Command object used to delete rows from the data source Fill Method Copies data from the data source to a DataSet object (continued) 156 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 6.4 Important Members of the SqlDataAdapter Object (continued) Member Type Description InsertCommand Property Specifies the Command object used to insert new rows in the data source SelectCommand Property Specifies the Command object used to select rows from the data source Update Method Copies data from a DataSet back to the data source UpdateCommand Property Specifies the Command object used to update rows in the data source DataSet Objects When manipulating data derived from a relational database, it is often useful to create a memory-resident copy of the target relational data, with changes posted back to the data source through an update operation. The DataSet object provides access to a disconnect relational database that includes its own tables, views, and relationships, without requiring a persistent connection to the original data source. Table 6.5 details some of the most important members of the DataSet object. Table 6.5 Important Members of the DataSet Object Member Type Description AcceptChanges Method Accepts all changes in the DataSet Clear Method Removes all data from the DataSet GetChanges Method Returns a DataSet containing only the changed data in the DataSet GetXml Method Returns the DataSet in XML format GetXmlSchema Method Returns an XML Schema Definition (XSD) representation of the DataSet Merge Method Combines two DataSets ReadXml Method Inputs data from an XML file to the DataSet ReadXmlSchema Method Inputs the schema from an XSD file Relations Property Represents a collection of DataRelation objects Tables Property Represents a collection of DataTable objects WriteXml Method Outputs the DataSet to an XML file WriteXmlSchema Method Outputs the DataSet’s schema to an XSD file 157 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . The DataTable Object Each table within a DataSet is represented by a DataTable object, which can be manipulated by row or by column as desired. Table 6.6 details some of the most important members of the DataTable object. You might recognize many of the members as being very similar to structures within a relational database. Table 6.6 Important Members of the DataTable Object Member Type Description ChildRelations Property Represents a collection of child DataRelation objects Clear Method Removes all data from the DataTable ColumnChanged Event Fires after a change to data in any row of the specified column ColumnChanging Event Fires just before a change to data in any row of the specified column Columns Property Represents a collection of DataColumn objects Constraints Property Represents a collection of Constraint objects NewRow Method Adds a new blank row ParentRelations Property Represents a collection of parent DataRelation objects PrimaryKey Property Represents an array of DataColumn objects that form the DataTable’s primary key RowChanged Event Fires just after a change to data in the specified DataRow RowChanging Event Fires just before a change to data in the specified DataRow RowDeleted Event Fires just after a row deletion RowDeleting Event Fires just before a row deletion Rows Property Represents a collection of DataRow objects Select Method Returns an array of DataRow objects filtered by the specified criteria TableName Property Specifies the DataTable’s name When using the Select method of a DataTable, the filter expression is an SQL WHERE clause that follows these rules: ➤ Column names containing special characters or whitespace are enclosed in square brackets ([ ]). ➤ String constants are enclosed in single quotes (‘). 158 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ Date constants are enclosed in pound signs (#). ➤ Expressions can be created using the AND, OR, NOT, IN, and LIKE keywords; using parenthetical ordering; and using comparison and arithmetic operators. ➤ String values are concatenated (combined) using the plus sign (+). ➤ Wildcard values (* and %) can be used only at the beginning or end of test string values. ➤ Child table columns can be referenced using Child.Column, or you can use Child(RelationName).Column to choose a particular child table, if there are several. ➤ You can use the Sum, Avg, Min, Max, Count, StDev, and Var aggregate functions with child tables. ➤ You can use the CONVERT, LEN, ISNULL, IIF, and SUBSTRING functions. It is also possible to order the resulting result set by providing a sort order expression, and to restrict the returned rows in the result set by specifying one of the DataViewRowState enumerated values, as detailed in Table 6.7. Table 6.7 DataViewRowState Enumerated Values Value Meaning Added Returns only new rows not yet committed CurrentRows Returns all current rows Deleted Returns only deleted rows ModifiedCurrent Returns only modified rows ModifiedOriginal Returns the original data from the modified rows None Returns an empty result set OriginalRows Returns all original data, including modified values and deleted rows Unchanged Returns only unmodified rows The DataRelation Object A DataRelation object represents each relationship between tables within a DataSet. Table 6.8 details some of the most important members of the DataRelation object. 159 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . Table 6.8 Important Members of the DataRelation Object Member Type Description ChildColumns Property Collection of DataColumn objects defining the foreign key ChildKeyConstraint Property A ForeignKeyConstraint object for the relation ChildTable Property DataTable linked by the foreign key (child DataTable) ParentColumns Property Collection of DataColumn objects defining the primary key ParentKeyConstraint Property A PrimaryKeyConstraint object for the relation ParentTable Property DataTable linked by the primary key (parent DataTable) RelationName Property The DataRelation name The DataView Object The DataView object represents a view of the data contained in a DataTable object. A DataView object might contain every DataRow object from the DataTable object, or it might be filtered to contain only specific rows. That filtering can be done by SQL expressions (returning, for example, only rows for customers in France) or by row state (returning, for example, only rows that have been modified). Table 6.9 details some of the most important members of this object. Table 6.9 Important Members of the DataView Object Member Type Description AddNew Method Adds a new row AllowDelete Property Returns true if the DataView allows deletions AllowEdit Property Returns true if the DataView allows updates AllowNew Property Returns true if the DataView allows insertion of new rows Count Property Gives the number of rows in the DataView Delete Method Deletes an existing row Find Method Searches for a particular row FindRows Method Returns an array of rows filtered by the provided expression Item Property Returns a particular row as a DataRowView object Sort Property Sorts the rows in a DataView 160 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The DataRow Object DataTable objects represent a collection of DataRow objects, which serve the same role as records within a relational database. Each row can have one or more elements arranged within a columnar format in the table. Table 6.10 details some of the most important members of the DataRow object. Table 6.10 Important Members of the DataRow Object Member Type Description BeginEdit Method Initiates editing of the DataRow CancelEdit Method Discards a pending edit Delete Method Deletes a row EndEdit Method Saves a pending edit’s changes IsNull Method Returns true if the specified column contains a null value RowState Property Returns the current state of a DataRow, which can be tested against the DataViewRowState enumerated values The DataColumn Object DataTable objects also include a collection of DataColumn objects, which serve the same role as individual elements within a relational database. Each column can be independently configured with a length, a specific data type, and constraints on allowable values. Table 6.11 details some of the most important members of the DataColumn object. Table 6.11 Important Members of the DataColumn Object Member Type Description AllowDbNull* Property Returns true if the column allows null values AutoIncrement Property Returns true if the column has the identity constraint ColumnName Property Specifies the DataColumn’s name DataType Property Specifies the data type stored in the column DefaultValue Property Specifies the default value assigned to this column when a new row is inserted MaxLength Property Specifies the maximum length of the value stored in the column Unique Property Returns true if values in the column must be unique across all rows * A Null value is not the same thing as a numeric zero or zero-length string value. Null is a special condition that reflects a completely unknown value, and it cannot be used in some types of comparative evaluation without additional testing. 161 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . Using a DataSet You create a form capable of displaying a multitable DataSet by performing these steps: 1. Open a Visual C# .NET Windows application. 2. Place a Button control (btnLoadData) and a DataGrid control (dgMain) on the form. 3. Switch to Code view and add the following using directives: using System.Data; using System.Data.SqlClient; 4. Attach a Click event handler to the Button control and add the follow- ing code: private void btnLoadData_Click(object sender, System.EventArgs e) { SqlConnection cnn = new SqlConnection(“Data Source=(local);” + “Initial Catalog=Northwind;Integrated Security=SSPI”); DataSet ds = new DataSet(); SqlCommand cmdCustomers= cnn.CreateCommand(); cmdCustomers.CommandType = CommandType.Text; cmdCustomers.CommandText = “SELECT * FROM Customers”; SqlDataAdapter daCustomers = new SqlDataAdapter(); daCustomers.SelectCommand = cmdCustomers; daCustomers.Fill(ds, “Customers”); SqlCommand cmdOrders = cnn.CreateCommand(); cmdOrders.CommandType = CommandType.Text; cmdOrders.CommandText = “SELECT * FROM Orders”; SqlDataAdapter daOrders = new SqlDataAdapter(); daOrders.SelectCommand = cmdOrders; daOrders.Fill(ds, “Orders”); SqlCommand cmdOrderDetails = cnn.CreateCommand(); cmdOrderDetails.CommandType = CommandType.Text; cmdOrderDetails.CommandText = “SELECT * FROM [Order Details]”; SqlDataAdapter daOrderDetails = new SqlDataAdapter(); daOrderDetails.SelectCommand = cmdOrderDetails; daOrderDetails.Fill(ds, “OrderDetails”); DataRelation relCustOrder = ds.Relations.Add(“CustOrder”, ds.Tables[“Customers”].Columns[“CustomerID”], ds.Tables[“Orders”].Columns[“CustomerID”]); DataRelation relOrderOrderDetails= ds.Relations.Add(“OrderOrderDetails”, ds.Tables[“Orders”].Columns[“OrderID”], ds.Tables[“OrderDetails”].Columns[“OrderID”]); dgMain.DataSource = ds; dgMain.DataMember = “Customers”; } 5. Set the form as the startup object for the project, add a Main method, and run the project. When you click the button, the application accesses the Northwind database on an SQL Server running on the local system using integrated Windows authentication, and it displays customer data within the DataGrid, as shown in Figure 6.2. 162 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Figure 6.2 Customer data from a multitable DataSet. In the previous example, the data fetched from the data source is stored in a separate DataTable object in a DataSet object. The code then adds DataRelation objects to specify the relationships between these DataTable objects. The Add method of the DataSet.Relations collection takes three parameters: ➤ A name for the DataRelation object to be created ➤ A DataColumn object that represents the primary key side of the rela- tionship ➤ A DataColumn object that represents the foreign key side of the rela- tionship The DataGrid control contains built-in logic to help navigate between related DataTable objects in a DataSet object. XML Data XML data files make up the third common source of data that your applications can use. XML stands for the Extensible Markup Language, which uses human-readable, highly structured files that include both data and a description of the data (referred to as metadata). XML Example The following is an example XML document: <?xml version=”1.0” encoding=”UTF-8”?> <!-- Customer list for Speedy Auto --> <Customers> <Customer CustNumber=”1”> <CustName>Performance Wheels</CustName> <CustCity>Dallas</CustCity> 163 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . <CustState>TX</CustState> </Customer> <Customer CustNumber=”2”> <CustName><![CDATA[Larry’s Grille]]></CustName> <CustCity>Austin</CustCity> <CustState>TX</CustState> </Customer> </Customers> The first line of the example file is the XML declaration, which details the version of the XML specification and encoding used. The second line is a formatted comment, which is ignored during data manipulation. The third line defines the opening tag of the root element of the XML document. Data within the file is organized by nested elements; each level is bracketed by a pair of tags, as shown here: <Tag>element data</Tag> Tag names can be anything you like, provided that the name starts with a letter character or an underscore and contains only alphanumeric characters, underscores, hyphens, or periods. Tag names cannot include whitespace and are case sensitive. Elements can contain other elements and also can have attributes containing values. The example code includes an attribute named CustNumber for each of the Customer elements. The CustName element in the second Customer record includes a [CDATA()] section, which allows the customer name to include the apostrophe (‘) special character. XML files also can use entity references denoted by the ampersand (&) in the place of the special characters: ➤ < (<) ➤ > (>) ➤ & (&) ➤ ' (‘) ➤ " (“) The XmlDocument Class The .NET Framework includes support for XML files through the System.Xml namespace. An XmlNode object represents each node in an XML document, such as an attribute, a comment, an element, and so on. An XmlDocument provides an in-memory representation of an XML 164 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . document. The XmlDocument class implements the W3C Document Object Model (DOM) Level 1 Core and the Core DOM Level 2 standards. The DOM provides a standard programming model for working with XML. Table 6.12 details some of the most important classes of the XmlDocument object. Table 6.12 XmlDocument Object Members Member Type Description CreateAttribute Method Creates an attribute node CreateElement Method Creates an element node CreateNode Method Creates an XmlNode object DocumentElement Property Returns an XmlNode object for the root node GetElementsByTagName Method Lists all elements with the specified tag name Load Method Inputs an XML document LoadXml Method Inputs an XML string Save Method Outputs the XmlDocument to a file or stream WriteTo Method Outputs the XmlDocument to an XmlWriter object The XmlDataDocument Class The XmlDataDocument class extends the XmlDocument class to support DataSet synchronization. You can practice using an XML file as a relational data source by completing the following steps: 1. Open a Visual C# .NET project Windows application. 2. Place two Button controls (btnBrowse and btnSave) and a DataGrid control (dgXml) on the form. 3. Switch to Code view and add the following using directives: using System.Xml; using System.Data; 4. Add the following code in the class definition: XmlDataDocument xdd; String strFileName; 5. Attach a Click event handler for the Button controls and add the fol- lowing code: private void btnBrowse_Click(object sender, System.EventArgs e) { OpenFileDialog dlgOpen = new OpenFileDialog(); dlgOpen.Title = “Select a File”; dlgOpen.Filter = “XML files (*.xml)|*.xml|All Files(*.*)|*.*”; 165 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . if (dlgOpen.ShowDialog() == DialogResult.OK) { strFileName = dlgOpen.FileName; // Create a DataSet object // Read the XML document’s schema DataSet ds = new DataSet(); ds.ReadXmlSchema(dlgOpen.FileName); // Create an XmlDataDocument object with the DataSet // Load the file into the XmlDataDocument xdd = new XmlDataDocument(ds); xdd.Load(strFileName); // And display it on the DataGrid dgXml.DataSource = ds; } } private void button1_Click(object sender, System.EventArgs e) { xdd.Save(strFileName); } 6. Set the form as the startup object for the project, add a Main method, and run the project. When you click the button, the File Open dialog box opens. After you select an XML file and click OK, the contents of the file are displayed in the DataGrid. Modify the contents in the DataGrid, and click Save to write the changes back to the XML document. Handling Database Errors The .NET Framework includes two classes within the System.Data.SqlClient namespace that are useful in handling SQL Server errors. The SqlException class can be used to catch SQL Server–related errors and warnings. The SqlException object exposes an Errors property, which is a collection of SqlError objects. The SqlError object contains information related to errors and warnings generated by the SQL server. In addition to encountering operational errors, when multiple users make changes to data within separate DataSets and then attempt to update the values in the data source, the question arises over which one of the conflicting changes will “win.” You can control the resolution of this situation through the UpdateCommand property of an SqlDataAdapter object, which can be configured in one of two ways: ➤ Last one wins concurrency control—All updates are applied regardless of whether changes have occurred because the rows were loaded into the DataSet. When you use a regular UPDATE statement to update the database, you use the last one wins concurrency control—for example: 166 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UPDATE Customers SET ContactName = @ContactName WHERE CustomerID = @CustomerID ➤ Optimistic concurrency control—The change is applied only if the source row has not changed since the DataSet was loaded. To use the optimistic concurrency control, you need to ensure that the original value of a field in the database is not changed after you have loaded the data. You can use the WHERE clause in the UPDATE statement to ensure this requirement—for example: UPDATE Customers SET ContactName = @ContactName WHERE CustomerID = @CustomerID AND ContactName = @ContactNameOrig Here, the new WHERE clause finds a row to update only if both the CustomerID and ContactName fields are unchanged from when the row was originally loaded. 167 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . Practice Questions Question 1 You need to modify the data present in the Customers table to increase the Discount rate by 5%. Which type of SQL statement should you use for this purpose? ❍ A. DELETE ❍ B. INSERT ❍ C. SELECT ❍ D. UPDATE Answer D is correct. SQL UPDATE statements are used to modify existing data. Answer A is incorrect because DELETE statements are used to remove existing data rather than change it. Answer B is incorrect because the INSERT statement is used to add new records. The SELECT statement is used to return existing data records, not to change them, making answer C incorrect as well. Question 2 Given the following code, what order will the final record set be in? SELECT Count(CustomerID) as CustCount, State FROM [Customer Data] GROUP BY State ORDER BY 2+3 DESC ❍ A. The results will be in ascending order, based on the values stored in the State column. ❍ B. The results will be in descending order, based on the values stored in the State column. ❍ C. The results will be in ascending order, based on the values stored in the Count value. ❍ D. The results will be in descending order, based on the values stored in the Count value. ❍ E. The results will be ordered, based on what the database engine decides. Answer E is correct. Although the records in the result set will be grouped by the value in the State field, the use of a constant (in this case, the addition 168 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . of two constant values) in the ORDER BY clause causes the result set to be ordered, based on what the database engine decides. Answers A and B are incorrect because the State field is being used to determine the aggregate grouping rather than ordering the result set. Answers C and D are incorrect because the Count value is only one of the data elements returned and is not used in the ordering of the result set. Question 3 Which of the following objects would be used with an Access database? (Select all that apply.) ❑ A. SqlConnection ❑ B. SqlDataAdapter ❑ C. OleDbCommand ❑ D. OleDbDataReader ❑ E. SqlCommand Answers C and D are correct. When accessing Jet databases such as Microsoft Access files, the OLE DB data provider is used, making both the OleDbCommand and OleDbDataReader objects available. Answers A, B, and E are incorrect because the SqlConnection, SqlDataAdapter, and SqlCommand objects are included with the SQL Server data provider rather than the OLE DB data provider. Question 4 What happens when you invoke the Close method of an SqlConnection object? ❍ A. The connection is maintained until the application invokes the Open method again. ❍ B. The connection is returned to the pool. ❍ C. The connection is terminated and its resources are cleared. ❍ D. Nothing—it is no longer necessary in .NET to explicitly invoke the Close method. Answer B is correct. The connection is returned to an available pool for later connections. Answer A is incorrect because the Close method is invoked to end an existing connection, not to keep it open. Answer C is incorrect because the server’s connection resources are not immediately cleared. Answer D is incorrect because the Close method is still required to terminate an existing connection. 169 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . Question 5 Which method of the SqlDataAdapter class would be used to copy data from a SQL Server View to a DataSet named dsText? ❍ A. Fill ❍ B. InsertCommand ❍ C. SelectCommand ❍ D. Update ❍ E. UpdateCommand Answer A is correct. The Fill method copies information from a database to a DataSet. Answers B, C, and E are incorrect because InsertCommand, SelectCommand, and UpdateCommand are properties used to specify Command objects rather than methods used to copy information. Answer D is incorrect because the Update method copies information from a DataSet back to the data source, not the other way around. Question 6 You want to load an XML file data into a DataSet object. The DataGrid object is then bound to the DataSet object. The DataGrid control provides the capability to modify the data in the DataSet object. You want the changes to be synchronized with the XML file. Which of the following objects should you use to load the XML document? ❍ A. XmlDataDocument ❍ B. XmlDocument ❍ C. XmlReader ❍ D. XmlValidatingReader Answer A is correct. The key feature of the XmlDataDocument class is that it can be synchronized with a DataSet object. Therefore, the XmlDataDocument object should be used to load the XML document. Answers B, C, and D are not correct because they cannot be synchronized with the DataSet object. 170 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 7 Your application needs to retrieve a list of student marks from a SQL Server database. The application should move through the list sequentially once, processing each student’s marks in turn. Which object should you use to hold the list to achieve maximum performance? ❍ A. DataSet ❍ B. DataTable ❍ C. DataView ❍ D. SqlDataReader Answer D is correct. The SqlDataReader object provides a fast, forwardonly, read-only view of the data. It loads one row of data at a time in the memory without any extra overhead. Answers A, B, and C are incorrect because they load a complete result set in memory, causing extra overhead because the data is read sequentially only once. Question 8 Which of the following members of the XmlDocument class create or return an XmlNode object? (Select all that apply.) ❑ A. CreateAttribute ❑ B. CreateElement ❑ C. CreateNode ❑ D. DocumentElement ❑ E. Load Answers C and D are correct. The CreateNode method creates a new XmlNode, while the DocumentElement property returns an XmlNode object representing the root node of the XML file. Answers A and B are incorrect because the CreateAttribute and CreateElement methods are used to create attribute and element nodes, respectively. Answer E is incorrect because the Load method is used to import an XML document. 171 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Consuming . . . . . . and . . Manipulating . . . . . . . .Data . . Question 9 You have created an application that uses optimistic concurrency control to manage data access by multiple users. Users Bob, Mary, and Sal synchronized their local DataSets with the data source at 10:30, and all three post updates to the same record within a local DataSet. Mary submits her update at 11:00, Sal submits his at 10:55, and Bob submits his at 11:05. Which value will be present at 11:10, assuming that no one else attempts to change the data? ❍ A. Mary’s will remain. ❍ B. Sal’s will remain. ❍ C. Bob’s will remain. ❍ D. The database does not reflect any changes. Answer B is correct. Because your solution uses optimistic concurrency control, only the first changed value (Sal’s) will be updated. Mary and Bob will encounter an error when they attempt to post changes to the same record because the underlying data will have changed since the DataSet was last updated, making answers A and C incorrect. Question 10 Which class within the System.IO namespace would be used to extract records from a flat file that have a 10-digit integer key, followed by a 20-character customer name string, followed by two timedate fields? (Select the best answer.) ❍ A. FileStream ❍ B. StreamReader ❍ C. BinaryReader ❍ D. DataReader Answer C is correct. The BinaryReader class reads binary data from primitive data types. Answer A is incorrect because the FileStream class treats any file simply as a stream of bytes and would not be the best choice here. Similarly, answer B is incorrect because the StreamReader class is used to read data as characters, which would be less efficient than directly reading each data type available in a known format. Answer D is incorrect because the DataReader object is created by the ExecuteReader method of an ADO.NET Command object rather than as a class within the System.IO namespace. 172 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Need to Know More? Carlos Eduardo Rojas and Fernando G. Guerrero. SQL Server 2000 Programming by Example. Que Publishing, 2001. Microsoft ADO.NET Support Center: http://support. microsoft.com?scid=fh;en-us;adonet. Data and ADO HOWTO articles: com/quickstart/howto. http://samples.gotdotnet. 7 Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ Simple Object Access Protocol (SOAP) ✓ Universal Description, Discovery, and Integration (UDDI) ✓ Web Services Description Language (WSDL) ✓ Web Services Discovery tool (disco.exe) ✓ Web Services Description Language tool (wsdl.exe) ✓ WebService attribute ([WebService()]) ✓ WebMethod attribute ([WebMethod()]) Techniques you’ll need to master: ✓ Understand the purpose of SOAP when connecting to a Web Service. ✓ Understand how to make use of Web references and the command-line utilities disco.exe and wsdl.exe. ✓ Understand how to instantiate and invoke a Web Service. 174 Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The .NET Framework has been described by Microsoft as “an XML Web Services platform that will enable developers to create programs that transcend device boundaries and fully harness the connectivity of the Internet.” In essence, a Web Service allows interaction between objects across the Internet. Object-oriented languages allow two objects within the same application to interact, while protocols such as the Component Object Model (COM) extend this to allow two objects on the same system but in different applications to interact. Distributed Component Object Model (DCOM) components extend this even more, to allow two objects located on different systems within the same local network to interact. Web Services extend this progression to allow objects to interact even when located on systems in widely separated networks, sharing only Internet connectivity. In this chapter, we discuss the creation and use of Web Services and the primary protocols involved in their use. Understanding Web Services Web Services provide interactivity through a number of protocols, including the following: ➤ Simple Object Access Protocol (SOAP) ➤ Disco and Universal Description, Discovery, and Integration (UDDI) ➤ Web Services Description Language (WSDL) By default, communications between Web Services and their clients is accomplished using XML messages over HTTP connectivity. This allows access to Web Services through most firewall configurations, although it is possible to configure a firewall to prevent HTTP access. Simple Object Access Protocol (SOAP) The Simple Object Access Protocol (SOAP) provides a method of translating objects, along with their methods and properties, into XML that can be sent via HTTP connectivity. Because SOAP is XML-based, Web Services can be used by many different vendors and clients. 175 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Web . . Services . . . . . You are expected to know that you can transmit SOAP messages over protocols other than the Hypertext Transfer Protocol (HTTP)). SOAP messages also can be sent via asynchronous methods such as the File Transfer Protocol (FTP) or email using the Simple Mail Transfer Protocol (SMTP). A SOAP message is an XML message that has an envelope and a body; a SOAP message optionally can contain a header. The SOAP envelope is the topmost element of the XML document that contains the body and the header of the message. The body of the SOAP message contains information meaningful to the recipient of the message. For example, when you make a call to a Web Service method, the body of a SOAP message includes the name of the method and the arguments needed to invoke that method. Disco and Universal Description, Discovery, and Integration (UDDI) Disco is a Microsoft standard for the creation of Web Service discovery documents. Disco documents are kept on a Web Services server and contain paths and other information, including the path to the Web Services Description Language (WSDL) file that describes the service. Universal Description, Discovery, and Integration (UDDI) describes a method for finding Web Services, URLs for information, or other details of Web Services such as documentation of the Web Service available on a particular server. UDDI relies on a central directory that can be searched for details of available services. Public UDDI registries provide information to any client requesting the data; private UDDI registries provide information only to authorized clients or within a restricted intranet. The UDDI standard is being developed by a joint group of industry partners, including Microsoft and IBM. For more information, visit www.uddi.org and uddi.microsoft.com. Web Services Description Language (WSDL) The Web Services Description Language (WSDL) file is an XML file maintained on the Web Services server that details the data types, methods, and URLs that can be used to interact with each Web Service. 176 Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . It is not necessary for a Web Service to have a UDDI registration or WSDL file. These are necessary only to allow clients to automatically discover the message formats and locations used with the Web Service. Clients can be configured to use the proper format without exposing the Web Service to discovery. Using Web Services The first step is Web Service discovery, in which you discover and locate the documents that provide documentation and a WSDL description of the Web Service. After you retrieve the information about its interface through the description document (WSDL), you generate a proxy class that locally represents the Web Service. The client application then needs to simply create an object of the proxy class and call its methods to invoke the Web methods of the Web Service remotely. In this section, we discuss how to discover and generate a proxy class for a Web Service: ➤ By adding a Web reference using Visual Studio .NET ➤ By using command-line tools: the Web Services Discovery tool (disco.exe) to discover Web Service–related information and the Web Services Description Language tool (wsdl.exe) to generate proxy classes for the Web Service Adding a Web Reference Visual Studio .NET enables you to discover Web Service details and generate a proxy class for a Web Service from its IDE with the help of Web References. Within a project, you can add a Web reference by right-clicking the References folder within the Solution Explorer and selecting Add Web Reference from the options provided. The Add Web Reference dialog box appears, as shown in Figure 7.1. In the Address text box, specify the proper URL of the Web Service and press Enter (see Figure 7.1). Click the Add Reference button to add a Web reference to the Web Service in your project. Visual Studio .NET discovers the methods of the Web Service and generates a proxy class, as shown in Figure 7.2 (you need to click the Show All Files icon in the Solution Explorer to view the proxy classes). 177 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Web . . Services . . . . . Figure 7.1 The Add Web Reference dialog box shows exposed methods of the Web Service http://terraservice.net/TerraService.asmx. Figure 7.2 When you add a Web Reference, the proxy class is automatically generated. Web references are preferred over the command-line creation of proxy classes because it is possible to rapidly update a Web reference to reflect Web Service changes. This is done by right-clicking the Web reference and selecting Update Web Reference. After generating the proxy class, you can instantiate and invoke Web methods on the Web Service through the generated proxy class: net.terraservice.TerraService ts = new net.terraservice.TerraService(); net.terraservice.PlaceFacts[] pf = ts.GetPlaceList(“Grand Canyon”, 1, false); 178 Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . In the preceding code, the autogenerated proxy file uses a namespace that is based on the name of the Web reference. The TerraService and PlaceFacts objects are proxy objects that pass calls to the Web Service and return results from the Web Service. The Web Services Discovery Tool (disco.exe) When you create a Web reference, Visual Studio .NET performs all the steps necessary to discover and make available the target Web Service. It is also possible to do this explicitly by using the command-line tool disco.exe. The disco.exe utility can be used within the Visual Studio .NET command prompt; the command prompt is accessible through Start, Programs, Microsoft Visual Studio, .NET, Visual Studio .NET Tools, Visual Studio .NET Command Prompt. To retrieve discovery information of the TerraService Web Service using this utility, you can input the following: disco http://terraservice.net/TerraService.asmx The tool contacts the Web Service and creates the following files: ➤ The WSDL description file is an XML file that contains the contract of the Web methods exposed by the Web Service. You can use the WSDL file to generate a proxy class for a Web Service. ➤ If the Web Service includes a static discovery document (.disco file), the tool will also retrieve this document. This XML file contains URL information such as the URL for the WSDL file, the URL for the Web Service documentation, and so on. ➤ The results.discomap file, an XML file, contains the name of the other files created by the disco.exe tool and the URL from which their contents were retrieved. The Web Services Description Language Tool (wsdl.exe) The .NET Framework Software Development Kit (SDK) includes a command-line utility, wsdl.exe that can use a WSDL file and create a proxy class that can be used to invoke the Web Service. Using the Visual Studio .NET command prompt, simply navigate to the folder containing the WSDL file 179 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Web . . Services . . . . . generated by the disco.exe tool, and execute the wsdl.exe with the desired options: wsdl /language:CS /out:TS.cs TerraService.wsdl You can then add the resultant proxy file, TS.cs, to your application project by selecting File, Add Existing Item and then navigating to the proper file. After generating the proxy class, you can instantiate and invoke Web methods on the Web Service just as you did when you used the Add Web Reference feature of Visual Studio .NET IDE. However, the proxy file generated by using the Web Services Description Language tool uses a namespace specified by the /namespace option. Because you did not specify a /namespace option in the wsdl command mentioned previously, you can refer to the proxy objects directly as shown here: TerraService ts = new TerraService(); PlaceFacts[] pf = ts.GetPlaceList(“Grand Canyon”, 1, false); Table 7.1 details some of the more common options used with the wsdl.exe utility. Table 7.1 Command-line Options for the wsdl.exe Utility Option Meaning /domain:DomainName Gives the domain name for connecting to a server that requires authentication. /language:LanguageCode Specifies the language of the generated class. The LanguageCode parameter can be CS (for C#), VB (for Visual Basic .NET), or JS (for JScript). /namespace:Namespace Specifies a namespace for the new class. /out:Filename Gives the filename for the output. By default, the filename is derived from the Web Service name. /password:Password Gives the password for connecting to a server that requires authentication. /server Generates a class to create a server object. By default, the tool generates a client proxy object. /username:Username Gives the username for connecting to a server that requires authentication. /? Displays the utility’s help file. 180 Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating Web Services You can create an ASP.NET Web Service using the Visual Studio .NET interface by selecting the option to create a Web Service and specifying the name of the Web server, as show in Figure 7.3 (here, the server being used is the localhost). Figure 7.3 Specification of a new Web Service within Visual Studio .NET. To create a Web Service, you create a file with an .asmx extension. You then need to perform the following steps: 1. Mark the class that should be available via the Web Service by using the WebService attribute. For example: [WebService(Namespace=”http://NetExam.org/StringProc”)] public class Strings : System.Web.Services.WebService {} 2. Mark the public methods in the Web Service class that should be exposed via the Web Service by using the WebMethod attribute. For example: [WebMethod()] public String ToUpper(String inputString) { return inputString.ToUpper(); } [WebMethod()] public String ToLower(String inputString) { return inputString.ToLower(); } The methods marked with the WebMethod attribute are known as Web methods. They expose the functionality of the ASP.NET Web Service to the outside world. 181 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Web . . Services . . . . . Now you just need to build the Web Service project to create the Web Service on the server. Testing the New Web Service Visual Studio .NET includes built-in tools for testing a Web Service project from your browser without building any client applications for the Web Service. You can test the project by selecting Run, which opens a browser window showing the test page for any exposed methods of the Web Service, as shown in Figure 7.4. Figure 7.4 Exposed methods of the Strings Web Service. You can test any of the methods by clicking the method link. This opens the Web method test page, shown in Figure 7.5. Figure 7.5 Test page for the ToUpper method. 182 Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Here, you can test the method by entering appropriate values for each parameter and clicking the Invoke button. This opens another browser window displaying the XML response (see Figure 7.6). Figure 7.6 XML response from testing the ToUpper method. 183 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Web . . Services . . . . . Practice Questions Question 1 Which of the following is the best description of the general purpose of SOAP? ❍ A. SOAP is used to automatically discover the properties and methods of a Web Service. ❍ B. SOAP is used to create a proxy class for a Web Service. ❍ C. SOAP is used to encapsulate objects as XML messages. ❍ D. SOAP is used to clean data before it is consumed by a Web Service. Answer C is correct. SOAP is used to encapsulate objects as XML messages so that their properties and methods can be transferred over a network using protocols such as HTTP, FTP, or SMTP. Answer A is incorrect because SOAP is used to translate the properties and methods of an object into XML, and it cannot directly perform discovery of Web Services and their properties. Answer B is incorrect because SOAP is a method of data interchange and does not create a Web Service or a proxy class for one. Answer D is incorrect because SOAP does not provide error checking of user data; it serves only to provide basic XML transfer of data. Question 2 You have created the file NewService.asmx, containing code for a new Web Service named MyService. The code contains exposed methods FirstService and SecondService. To expose the FirstService method, which of the following must be done to the method? ❍ A. Configure NewService.asmx for anonymous access. ❍ B. Configure MyService using the [WebClass()] attribute. ❍ C. Configure FirstService using the [WebMethod()] attribute. ❍ D. Configure FirstService using the [WebService()] attribute. Answer C is correct. The FirstService Web method must be marked using the [WebMethod()] attribute to expose it from the Web Service. Answer A is incorrect because the exposure of Web methods is not performed at the file or class levels. Answers B and D are incorrect because there is no [WebClass()] attribute, and the [WebService()] attribute is used to mark a Web Service, not a Web method. 184 Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 3 You are developing a Web Service that provides stock-related data to the users. The Web Service exposes various methods. One of the methods, StockPrice(), provides the current price for a stock symbol. You have defined the method as follows: [WebMethod] decimal StockPrice(string symbol) { decimal price; // Fetch the current price return price; } Your clients complain that they cannot access the StockPrice() Web method, although they can call other Web methods in the Web Service. What could be the problem? ❍ A. You need to apply a WebService attribute to the method. ❍ B. Web methods cannot return a decimal value; you must change the return type to int. ❍ C. Web methods cannot contain any arguments. ❍ D. Web methods should be defined as public methods. Answer D is correct. For Web methods to be accessible via the Web Service, they should be defined as public methods with the WebMethod attribute. Answer A is not correct because the WebService attribute is applied to the Web Service class rather than the Web method. Answers B and C are not correct because Web methods can return decimal values and can contain any number of arguments. Question 4 Which of the following are valid transport protocols for translating XML messages? (Select all that apply.) ❑ A. FTP ❑ B. HTTP ❑ C. SOAP ❑ D. SMTP Answers A, B, and D are correct. SOAP-translated XML messages can be transported using the SMTP, FTP, or HTTP protocols. Answer C is incorrect because SOAP is used to encapsulate objects into XML format, but it does not provide a transport mechanism. 185 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Web . . Services . . . . . Question 5 You have created an application used by the accounting office that includes a Web reference to the QuarterlyBalance Web Service. Changes to this service have been made, and you need to reflect those changes in the proper proxy classes. What must you do? ❍ A. Create a new application and add a new Web reference to the Web Service. ❍ B. Delete the existing Web reference and re-create it. ❍ C. Update the Web reference in the existing application. ❍ D. Explicitly re-create the reference using the wsdl.exe utility. Answer C is correct. All you need to do is update the Web reference within the existing application. Answers A and B are incorrect because it is not necessary to delete or create anything new simply to update an existing Web reference. Answer D is incorrect because the original Web reference was created in Visual Studio .NET and, therefore, should be updated in that environment rather than at the command line. Question 6 What must a developer do to make a Web Service available asynchronously? ❍ A. Nothing. ❍ B. Use a separate Thread object for each invocation of the Web Service. ❍ C. Provide callback methods to invoke the Web Service. ❍ D. Host the Web Service on an Internet Information Server 6.0 server. Answer A is correct. There is no need to modify the Web Service. Answers B, C, and D are not correct because the client can always call a Web Service asynchronously. 186 Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 7 You want to create a Visual C# .NET proxy class named MyService.cs from the WSDL file named NewService.wsdl. After navigating to the proper folder using the Visual Studio .NET command-line utility, what should you do? ❍ A. Enter the following code: disco /language:CS /out:MyService.cs NewService.wsdl ❍ B. Enter the following code: disco /language:VB /out:MyService.vb NewService.wsdl ❍ C. Enter the following code: wsdl /language:VB /out:MyService.vb NewService.wsdl ❍ D. Enter the following code: wsdl /language:CS /out:MyService.cs NewService.wsdl ❍ E. Enter the following code: wsdl /language:CS /out:NewService.wsdl MyService.cs Answer D is correct. You should execute the wsdl.exe utility using both the /language specification of CS for a Visual C# .NET result and the /out specification of the MyService.cs target file. Answers A and B are incorrect because they both specify the use of the disco.exe utility, which is not used to create proxy classes directly. Answers B and C are incorrect because they both specify the /language option of VB, which would generate a Visual Basic .NET code file. Answer E is incorrect because the target file is the proxy class and should be used with the /out switch. Question 8 You are modifying an application to include references to the Employees class of a Web Service available within the organization’s intranet. The application already includes an Employees class. Using the wsdl.exe utility, which switch should you use to allow these two classes to coexist? ❍ A. /domain ❍ B. /namespace ❍ C. /out ❍ D. /server 187 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Web . . Services . . . . . Answer B is correct. The /namespace switch allows the specification of the namespace for the Employees proxy class, which can be used to set a different namespace from the existing Employees class, so that they can be specified uniquely. Answer A is incorrect because the /domain switch is used to specify the domain used for authentication on the Web server. Answer C is incorrect because the /out switch specifies the name of the output file. Answer D is incorrect because the /server switch specifies that the resultant class should be a server object rather than a client object. Question 9 You are invoking a Web Service within your client application. This Web Service returns the DataSet object, which is included in the System.Data namespace. Where should you place a reference to the namespace? ❍ A. In the client application project only. ❍ B. In the Web Service project only. ❍ C. In both the client application and Web Service projects. ❍ D. You do not need to specify the namespace reference in either project. Answer C is correct. You must place a reference to the proper namespace in both projects to generate and access a DataSet object between the server and client applications. Answers A and B are both incorrect because they specify only one of the two requirements, while answer C fails to include either. Question 10 You are creating an application that will require credit card verification when the customers register. You decide to use a Web Service that will provide credit card authentication facilities. You do not want to write this service yourself; instead, you want to use one that is already available. What should you use to find such a Web Service? ❍ A. Use the Web Services Discovery tool. ❍ B. Use the Web Services Description Language tool. ❍ C. Use the Soapsuds tool. ❍ D. Use the UDDI Registry. Answer D is correct. With the UDDI Registry, you can find Web Services by browsing or searching for your particular interest. Answer A is not correct because the Web Services Discovery tool requires the base address of the 188 Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Web Service to discover the details about the Web Service. Answer B is not correct because the Web Services Description Language tool generates proxy classes to interface with the Web Service and does not discover Web Services. Answer C is not correct because the Soapsuds tool is used not for discovering Web Services, but for compiling client applications by downloading schema information and generating reference assemblies. 189 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Web . . Services . . . . . Need to Know More? Newcomer, Eric. Understanding Web Services: XML, WSDL, SOAP, and UDDI. Addison-Wesley, 2002. Short, Scott. Building XML Web Services for the Microsoft .NET Platform. Microsoft Press, 2002. The UDDI Project: www.uddi.org/. The Microsoft UDDI Business Registry: uddi.microsoft.com. 8 Globalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ Globalization ✓ Localizability ✓ Localization ✓ Culture ✓ Resource files ✓ CultureInfo class ✓ CurrentUICulture property ✓ CurrentCulture property ✓ Invariant Culture ✓ Character encodings ✓ Mirroring ✓ String indexing Techniques you’ll need to master: ✓ Understand the purpose of cultures within the .NET Framework. ✓ Understand how to obtain a listing of available cultures from an application. ✓ Understand how to perform application localization at runtime. 192 Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Modern global network applications might require the ability to support different languages and information-presentation formats based on the local settings appropriate to the current user. Microsoft’s .NET Framework includes support for culture and globalization changes, including form layouts, currency and numerical display, and locally appropriate maps and other forms of image data. Introduction to Localization Applications created to support multiple localized configurations can be managed by creating a separate version for each locale, or a single application can be created with integrated support for multiple local settings. Planning for a globally deployed application includes many focus topics: ➤ Translating user interface (UI) text ➤ Translating between character encodings ➤ Controlling the direction of text display through the mirroring of char- acter data ➤ Formatting currency and date values ➤ Managing data sorts to include different alphabets Although it is possible to build multiple versions of an application, each designed to support a particular locale, it is considered a better method to create a single application that supports localized automatic configuration. The former approach is not a good solution because it is expensive. By building multiple versions of source code, you will have to employ lots of resources. Furthermore, you will need to implement bug fixes in all the versions of an application. Therefore, creating a single localizationaware application is easier to manage and is cost-efficient. The following section discusses how to implement localization in an application. The Localization Process Microsoft divides the process of localization into three primary phases: ➤ Globalization—During globalization, you identify all localizable resources and separate these resources from the fixed-code portions of the application. You perform this step during the design phase of an application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Globalization . . . . . . . ➤ Localizability—This process involves ensuring that translating an applica- tion from one localization to another does not require design changes. ➤ Localization—This process customizes an application to include new locales and localizable resources, as identified during the globalization phase. The terms globalization, localization, and localizability are often used interchangeably. Watch for questions involving these, and be sure to identify their function rather than the term specified. Localization Considerations An application’s user interface (UI) provides many areas that require localization consideration: ➤ Menu item text. ➤ Form layouts. Different languages might represent the same data in dif- ferent length of characters; for example, German text requires nearly twice as much as space required by English text. Therefore, you need to arrange form layouts accordingly. ➤ Time and date display format. ➤ Currency display format. ➤ Number display format, such as whether commas are used as the thou- sands separator. ➤ Data input fields, such as the use of postal codes in countries that do not use the U.S. ZIP code standard. ➤ Maps, road signs, photos, and other graphics displaying local content. ➤ Shortcut keys, including non–English-based keyboard support. ➤ Calendars, such as support for countries that do not use a Gregorian- based calendar. ➤ Alphabetical order. User Interface Localization The System.Globalization namespace provides most of the .NET support for localization in your applications. The two key features in development are listed here: 193 194 Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ Cultures—An identifier for a specific locale ➤ Resource files—A storage location for culture-dependent resources such as strings and bitmaps A culture does not simply define the language to be used; many locales might share the same language and yet have very different localization requirements. As an example, the United Kingdom and the United States both use English as the primary language, but they also use very different formats for currency and dates. Cultures Cultures are identified by abbreviations called culture codes. A full culture code is made up of a neutral culture code, with one or more possible subculture codes. A neutral culture code specifies only a language and cannot be used for localization. A subculture code specifies the location and other information for localization. The following list shows a few examples of culture codes: ➤ de—The German culture. This is a neutral culture code, without a speci- fied subculture code. Neutral cultures generally do not provide sufficient information to localize an application. ➤ en-GB—The English (U.K.) culture. This is a specific culture that includes enough information to localize an application—in this case, for English speakers in Great Britain. ➤ az-AZ-Cyrl—A specific culture with two subculture codes. Here, the culture refers to Azeri language in Azerbaijan, written using the Cyrillic alphabet. The CultureInfo Class The System.Globalization.CultureInfo class provides various items of information about a particular culture. You can retrieve culture information using CultureInfo class by performing the following steps: 1. Open Visual Studio .NET and create a new Visual C# .NET Windows application. 2. Place a Button control named btnGetInfo, a TextBox control named txtCulture, and a ListBox control named lbInfo on the form. 3. Add a reference to the System.Globalization namespace at the top of the form’s code: using System.Globalization; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Globalization . . . . . . . 4. Enter code to handle the button’s Click event: private void btnGetInfo_Click(object sender, System.EventArgs e) { // Create a CultureInfo object for the specified culture CultureInfo ci = new CultureInfo(txtCulture.Text); // Dump information about the culture lbInfo.Items.Clear(); lbInfo.Items.Add(“Display Name: “ + ci.DisplayName); lbInfo.Items.Add(“English Name: “ + ci.EnglishName); lbInfo.Items.Add(“Native Name: “ + ci.NativeName); // Get day names lbInfo.Items.Add(“Day Names:”); String[] strDayNames = ci.DateTimeFormat.DayNames; foreach(String strDay in strDayNames) { lbInfo.Items.Add(“ “ + strDay); } // Get the current year lbInfo.Items.Add(“Current year: “ + ➥ci.Calendar.GetYear(DateTime.Today)); // And the currency symbol lbInfo.Items.Add(“Currency symbol: “ + ➥ci.NumberFormat.CurrencySymbol); } 5. Insert the Main method and set the form as the startup object for the project. Then run the project. Enter the name of a culture in the text box, and click the button to display some of the information of that culture (see Figure 8.1). Figure 8.1 The sample form displaying information on the fi-Fi (Finnish) culture. You can use the CultureInfo.GetCultures method to retrieve an array of all supported CultureInfo objects. This method helps you enumerate all supported cultures. 195 196 Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The CurrentCulture and CurrentUICulture Properties The .NET framework allows localization on a thread-by-thread basis. In a normal Windows application, only a single thread of execution is used, represented by the Thread.CurrentThread object within the System.Threading namespace. Each thread has two properties that are used for determining the culture to use: ➤ CurrentUICulture—Tells the Common Language Runtime (CLR) which culture to use when selecting resources for the user interface. (Resource files are covered in the next section of this chapter.) ➤ CurrentCulture—Dictates the format used for dates, times, currency, numbers, and string comparison and casing rules. Although localization settings can change currency display settings, the code does not perform any type of currency conversion process. This affects only the manner in which the data is displayed in the user interface. The Invariant Culture A special culture can be used to interact directly with system services or components that will not display data directly to the user interface. This cultureindependent setting is managed by using the Invariant culture, which can be instantiated in two ways: ➤ Instantiate a new CultureInfo object with a empty input string: CultureInfo ciInv = new CultureInfo(“”); ➤ Instantiate a new object using CultureInfo.InvariantCulture: CultureInfo ciInv = CultureInfo.InvariantCulture; Displaying Localized Information You can display localized information by performing the following steps: 1. Open Visual Studio .NET and create a new Visual C# .NET Windows application. 2. Place a Label control, a ComboBox control named cboSelectCulture, and four TextBox controls named txtCulture, txtDate, txtCurrency, and txtNumber on the form. Refer to Figure 8.2 for the design of this form. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Globalization . . . . . . . 3. Add the following using directives in Code view: using System.Globalization; using System.Threading; 4. Enter code to handle events within the form’s class definition: private void SampleForm_Load(object sender, System.EventArgs e) { // Stock the combo box foreach (CultureInfo ci in CultureInfo.GetCultures( CultureTypes.SpecificCultures)) { cboSelectCulture.Items.Add(ci.Name); } // Display the name of the default culture txtCulture.Text = Thread.CurrentThread.CurrentCulture.EnglishName; // Display some data DisplayData(); } private void cboSelectCulture_SelectedIndexChanged( object sender, System.EventArgs e) { // Create an appropriate CultureInfo object for the thread Thread.CurrentThread.CurrentCulture = new CultureInfo(cboSelectCulture.Text); // Display the name of the culture txtCulture.Text = Thread.CurrentThread.CurrentCulture.EnglishName; // Refresh the display of the data DisplayData(); } private void DisplayData() { DateTime dtNow = DateTime.Now; Double dblcurrency = 13472.85; Double dblnumber = 1409872.3502; txtDate.Text = dtNow.ToLongDateString(); txtCurrency.Text = dblcurrency.ToString(“c”); txtNumber.Text = dblnumber.ToString(“n”); } 5. Insert the Main method and set the form as the startup object for the project. Run the project. Select the name of a culture in the combo box to display localized information using that culture (see Figure 8.2). Note that no special code is required to format the data provided by the ToLongDateString and ToString methods. This example shows how to programmatically select a culture other than the current culture of the operating system, which is the default culture. 197 198 Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Figure 8.2 The sample form displaying localized information using the Uzbekistan (Latin) culture. Resource Files Localizing the text displayed on the user interface is an important aspect of multicultural application development. As discussed in Chapter 4, “Components and .NET Assemblies,” localized data for user interfaces can be configured as external resource files, satellite assemblies, or assembly resource files. Assembly resource files are often the easiest to work with because they are simply XML files that contain formatted text. The following sections discuss how to localize the user interface using the Visual Studio .NET IDE and using assembly resource files. Localizing the User Interface in the Visual Studio .NET IDE You can create a form that provides a localized user interface by first creating the user interface form. Follow these steps: 1. Open Visual Studio .NET and create a new Visual C# .NET Windows application. Name the form SampleForm1.cs. 2. Place a label control, three radio button controls, and a button control on the form, as shown in Figure 8.3. Figure 8.3 A sample form displaying the placed controls. 3. Set the Localizable property of the form to true and set the Language property to French (France). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Globalization . . . . . . . 4. Change the text of each of the controls to the French translations, and expand the button to accommodate the French translation, as shown in Figure 8.4. Figure 8.4 The sample form now displaying French (France) localized settings. After you have created the user interface form, you can add the localization control form to your project: 1. Add a new form to your project and name it SampleForm2.cs. 2. Place a combo box control named cboCulture and a button control named btnOpenForm on the form. 3. Add the references at the top of the form’s class definition: using System.Globalization; using System.Threading; 4. Add code to handle events within the form’s class definition: private void SampleForm2_Load(object sender, System.EventArgs e) { // Put language choices in the combo box cboCulture.Items.Add(“English”); cboCulture.Items.Add(“French”); } private void btnOpenForm_Click(object sender, System.EventArgs e) { SampleForm1 f = new SampleForm1(); f.Show(); } private void cboCulture_SelectedIndexChanged( object sender, System.EventArgs e) { // When the user selects a language, change the UI culture switch (cboCulture.Text) { case “English”: Thread.CurrentThread.CurrentUICulture = new CultureInfo(“en-US”); break; case “French”: 199 200 Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Thread.CurrentThread.CurrentUICulture = new CultureInfo(“fr-FR”); break; } } 5. Insert the Main method and set the SampleForm2.cs form as the start- up object for the project. Then run the project. Select a culture from the combo box and open the form using the button to display that culture’s settings, as shown in Figure 8.5. Note that all settings, including the button-width change, are maintained. Figure 8.5 Two examples of the same form created by selecting English or French culture localization for the form to be opened. In the previous example, the localized settings for each culture are stored in a resource file (.resx) and a satellite assembly (.dll), created automatically by the Visual Studio .NET interface. Localizing Resources at Runtime Runtime user interface resources are loaded by an instance of the System.Resources.ResourceManager class. After you have initialized a ResourceManager object by calling one of the class’s constructors, you can use two methods to retrieve localized settings: ➤ Use the GetObject method to return an object from the resource file. ➤ Use the GetString method to return a string from the resource file. If you plan to move or resize controls, the satellite assembly approach like that in the previous example is more convenient. In the satellite assembly approach, you can move and resize controls directly within the Windows Forms Designer. If you attempted this using assembly resource files, you would also have to store position and size data, and then apply this information to your controls at runtime. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Globalization . . . . . . . Assembly resource files might be preferable when performing localization of information that is not directly displayed on the user interface, such as text that the application uses to display information in a message box. It is also possible to create hybrid solutions using both satellite assemblies and assembly resource files within the same project. In such cases, you can use satellite assemblies to localize controls, and you can use resource files to localize other information presented by the application. Character Encodings Because many different character sets can be used in an application, the .NET Framework provides support for encodings through the System.Text.Encoding class. Encoding is a set of characters and their associated numerical values, such as the ASCII character set, which associates common Latin characters with numerical values between 0 and 127. Unicode The .NET Framework utilizes the Unicode 2-byte (16-bit) character set by default. The Unicode character set includes roughly 65,000 common characters from most of the world’s languages, with additional support possible for approximately 1 million special characters. Older versions of Windows and Microsoft development platforms made use of separate code pages, each of which specified a 256-character encoding specific to a particular language or locale. Converting Encodings Although the native mode of the .NET Framework uses the Unicode character set, the Framework includes support for the older encodings, to provide backward compatibility with legacy applications. The System.Text namespace contains classes that can be used to convert characters from the Unicode (UTF-16) encoding to other encodings, and vice versa. Table 8.1 lists some of the more common subclasses of the System.Text.Encoding class that can be used to convert between character encodings. 201 202 Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 8.1 Encoding Subclasses Within the System.Text Namespace Class Use ASCIIEncoding Converts between Unicode and ASCII Encoding A general-purpose class using the Encoding.GetEncoding static method to return encodings that can be used for legacy code page compatibility UnicodeEncoding Converts to or from Unicode encoded as consecutive bytes UTF7Encoding Converts to and from 7-bit Unicode UTF8Encoding Converts to and from 8-bit Unicode User Interface Mirroring Because some cultures present information in different orientations, it is sometimes necessary to include planning for a reversal of the left-to-right order that is common in English- and German-speaking countries. In Hebrew and Arabic, the language is written right to left on a page; user controls must be similarly reversed so that their functionality remains constant based on the cultural access patterns of the user (see Figure 8.6). Figure 8.6 An Arabic Windows user interface displaying the mirroring of controls, tab location, and text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Globalization . . . . . . . Mirroring in .NET To reverse text input to be right to left, to change the location of text on the title bar, to relocate menus to the right side of the menu bar, and to reverse the appearance of combo box, radio box, and check box controls, you simply need to set a form’s RightToLeft property to Yes. Figure 8.7 shows an example of a form with its RightToLeft property set to Yes. Figure 8.7 An example of mirrored controls. This can also be done at the control level instead of the form level, to limit the area being mirrored by setting the control’s RightToLeft property to RightToLeft.Yes. True mirroring of the entire form, like that shown in Figure 8.6, requires a call to the SetProcessDefaultLayout Windows API. Managing User Input Global applications require several special considerations when planning for manipulation and validation of user input. When attempting to validate nonLatin character user input, it might be necessary to extract single characters in sequence through string indexing. The comparison and sort order of a simple alphabetic sort routine might produce different results, depending on the culture used. String Indexing The Unicode standard supports 32-bit extended characters (surrogate characters) and 32-bit characters that are formed by combining two 16-bit Unicode characters (combined characters), such as an accent mark and the base character to which it applies. To evaluate these characters amid other normal input characters, it is sometimes necessary to parse an input string 203 204 Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . character by character for validation, taking into account the fact that some characters might be 16-bit and others might be 32-bit. The .NET Framework provides support for this type of string manipulation through the System.Globalization.StringInfo class. This class can be used to iterate through the elements in a string by calling the static GetTextElementEnumerator() method of the StringInfo class. Given any Unicode string, this method returns an iterator that you can use to move through the string one character at a time, properly handling surrogate pairs and combining characters. The iterator has a MoveNext() method that returns false when it has exhausted the characters in the string. The Current property of the iterator returns a single character from the current position of the iterator. The following example shows how to iterate characters using the StringInfo class: 1. Open Visual Studio .NET and create a new Visual C# Windows .NET application. 2. Place a text box control named txtTest, a button control named btnIterate, and a list box control named lbIterate on the form. 3. Add the references at the top of the form’s class definition: using System.Globalization; 4. Add code to the Click events of the form’s button: private void btnIterate_Click(object sender, System.EventArgs e) { lbIterate.Items.Clear(); // Get an iterator for the entered text TextElementEnumerator iter = StringInfo.GetTextElementEnumerator(txtTest.Text); // The iterator starts before the string, have to move // it forward once to reach the first element iter.MoveNext(); do lbIterate.Items.Add(“Element “ + iter.ElementIndex + “: “ + iter.Current); while(iter.MoveNext()); } 5. Insert the Main method and set the form as the startup object for the project. Then run the project. Paste or enter text in the text box, and click the button control to display the string one character at a time, as shown in Figure 8.8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Globalization . . . . . . . Figure 8.8 An example of indexed string output. Comparing and Sorting Data Some cultures sort alphabetical lists in different ways. For example, some cultures place numeric characters before or after alphabetic characters. To support culture-aware sorting, the .NET Framework includes several features: ➤ String.Compare method—Compares strings according to the rules of CultureInfo, referenced by the CurrentCulture property ➤ CultureInfo.CompareInfo object—Supports substring searching according to the rules referenced by the CurrentCulture property ➤ Array.Sort method—Orders the members of an array by the alphabetiza- tion rules referenced by the CurrentCulture property ➤ SortKey.Compare method—Compares strings according to the rules refer- enced by the CurrentCulture property 205 206 Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Questions Question 1 Which of the following should be used if you want to store culture-specific error messages for an application? ❍ A. Embedded resource file ❍ B. External resource file ❍ C. Satellite assembly ❍ D. Assembly resource file Answer D is correct. An assembly resource file is often the best solution when you need to store localized data that is not directly displayed within the user interface. Answer A is incorrect because an embedded resource is integrated into the application and is difficult to update without redeploying a new version of the application. Answer B is incorrect because an external resource file is typically used to allow integration of resources provided by third-party vendors, rather than the XML-based assembly resource file that is preferred. Answer C is incorrect because satellite assemblies are preferred for data that is displayed within the user interface itself. Question 2 Which phase of the localization process involves ensuring that culture-specific translations do not require design changes? ❍ A. Globalization ❍ B. Globalizability ❍ C. Localizability ❍ D. Localization Answer C is correct. The localizability phase involves planning to ensure that changes in localization do not require application design changes between versions. Answer A is incorrect because the globalization phase is used to identify and separate localizable resources from application code. Answer B is incorrect because there is no globalizability phase. Answer D is incorrect because the localization phase involves implementing culture-based customized details identified in the globalization phase. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Globalization . . . . . . . Question 3 You are designing a Visual C# .NET Windows application that will be deployed to your customers in Japan, France, and Germany. You provide a combo box that allows the user to select the desired culture to display the application’s interface. After the user selects the culture, you want all the forms in the application to use the selected culture. Which of the following actions should you take? ❍ A. Set the Thread.CurrentCulture property to the CultureInfo object that represents the selected culture. ❍ B. Set the Thread.CurrentUICulture property to the CultureInfo object that represents the selected culture. ❍ C. Set the Thread.CurrentThread.CurrentCulture property to the CultureInfo object that represents the selected culture. ❍ D. Set the Thread.CurrentThread.CurrentUICulture property to the CultureInfo object that represents the selected culture. Answer D is correct. The CurrentUICulture property specifies which culture to use when choosing resources for the user interface. Therefore, to set the UI culture for the current thread, you should set the Thread.CurrentThread.CurrentUICulture property. Answers A and C are not correct because they set the CurrentCulture property, which is not used for displaying the user interface. Answer B is not correct because it does not set the culture for the currently executing thread. Question 4 Which one of the following statements about cultures is the most correct? ❍ A. Cultures identify local settings such as date and numerical formatting. ❍ B. Cultures identify the user’s locale and associated values. ❍ C. Cultures identify local settings such as alphabetic order. ❍ D. Cultures identify the user’s language and text-based formatting details. Answer B is correct. A culture is used to identify a user’s locale and any associated settings. Answers A, C, and D are all incorrect because they specify only a portion of the possible settings managed by culture-aware applications. 207 208 Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 5 You are responsible for the planning of a new globally deployed application. Which of the following are requirements that can be handled through culturespecific localization alone? (Select all that apply.) ❑ A. Translating user interface text labels to reflect the user’s culture setting ❑ B. Translating currency into local equivalent values based on the user’s culture setting ❑ C. Translating date values into a format suitable to the user’s culture setting ❑ D. Controlling the direction of the entire user interface through the mirroring process ❑ E. Controlling the order of data sorting based on the user’s culture setting Answers A, C, and E are correct. Culture-aware applications can configure the user interface text labels, date value formats, and alphabetic sort order based on the user’s CurrentCulture setting. Answer B is incorrect because the localization process does not directly perform translation between equivalent currency values. Answer D is incorrect because mirroring of the entire user interface requires a call to the SetProcessDefaultLayout Windows API. Question 6 Users of your application need to display dates and currencies in German, but you want the user interface in English. How can you accomplish this? ❍ A. Set the Thread.CurrentThread.CurrentCulture property to a CultureInfo object that represents the de-DE culture, and set the Thread.CurrentThread.CurrentUICulture property to a CultureInfo object that represents the en-US culture. ❍ B. Set the Thread.CurrentThread.CurrentCulture property to a CultureInfo object that represents the en-US culture, and set the Thread.CurrentThread.CurrentUICulture property to a CultureInfo object that represents the de-DE culture. ❍ C. Set the Thread.CurrentThread.CurrentCulture property to a CultureInfo object that represents the de-DE culture, and set the Thread.CurrentThread.CurrentUICulture property to a CultureInfo object that represents the de-DE culture. ❍ D. Set the Thread.CurrentThread.CurrentCulture property to a CultureInfo object that represents the en-US culture, and set the Thread.CurrentThread.CurrentUICulture property to a CultureInfo object that represents the en-US culture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Globalization . . . . . . . Answer A is correct. The CurrentCulture property specifies which culture to use for formatting dates, times, currencies, numbers, and so on. The CurrentUICulture property control specifies which culture to use when choosing resources for the user interface. Therefore, the CurrentCulture property should be set to de-DE to display dates and currencies in German, and the CurrentUICulture property should be set to en-US to display the user interface in English. Question 7 Which culture designation would be best for an English (U.K.)–based application responsible for communicating with two additional system processes running on the same server? ❍ A. en ❍ B. en-GB ❍ C. en-Invariant ❍ D. en-GB-Invariant ❍ E. Invariant Answer E is correct. The Invariant culture is a culture-independent culture setting used to allow communication with components that are not part of the user interface, such as system processes. Answers A and B are incorrect because en defines the English class itself, while en-GB defines the British version of English, both of which would be proper for a user interface, but not for culture-independent communications with other processes. Answers C and D are incorrect because the Invariant culture is specified without additional culture details. Question 8 Which of the following is most often used when a form must include cultureaware configuration settings to mirror data presentation order within its controls? ❍ A. Embedded resource file ❍ B. External resource file ❍ C. Satellite assembly ❍ D. Assembly resource file 209 210 Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer C is correct. A satellite assembly is used to store user interface configuration settings that vary between cultures, such as formatting and layout. Answer A is incorrect because an embedded resource is compiled within the code and is suitable for including common graphical icons and other standard components in an application. Answer B is incorrect because an external resource file is most often used to include resources provided by third-party vendors. Answer D is incorrect because an assembly resource file is preferred for use with localized data that is not tied directly to the user interface, such as message box text. Question 9 Your application contains Unicode strings encoded in the default .NET Framework encoding format. You want to copy these strings into a file in ASCII encoding format so that your legacy ERP system can read the file and update its system. How can you convert the data into ASCII encoding? ❍ A. Call the UnicodeEncoding.GetChars() method to perform the conversion. ❍ B. Call the ASCIIEncoding.GetChars() method to perform the conversion. ❍ C. Call the UnicodeEncoding.GetBytes() method to perform the conversion. ❍ D. Call the ASCIIEncoding.GetBytes() method to perform the conversion. Answer D is correct. The GetBytes() method of any encoding object translates from Unicode characters to bytes that are represented by the encoding object. Therefore, calling the ASCIIEncoding.GetBytes() method converts the UTF-16 characters to ASCII format. Answers A and B are not correct because the GetChars() method of any encoding object translates the bytes represented by the ecoding object into Unicode characters. Answer C is not correct because it would fetch the result in a Unicode byte array. Question 10 How should you configure a form for mirroring in Visual Studio .NET applications? ❍ A. Set the LeftToRight property to No ❍ B. Set the RightToLeft property to Yes ❍ C. Set the Mirrored property to True ❍ D. Call the SetProcessDefaultLayout API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Globalization . . . . . . . Answer B is correct. You should set the RightToLeft property to Yes to configure a form for mirrored presentation. Answers A and C are incorrect because they specify nonexistent properties LeftToRight and Mirrored. Answer D is incorrect because SetProcessDefaultLayout is a Windows API used to mirror an entire application’s interface, and it is not part of the .NET Framework’s basic settings available within Visual Studio .NET. 211 212 Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Need to Know More? Symmonds, Nick. Internationalization and Localization Using Microsoft .NET. Apress, 2001. Unicode home page: www.unicode.org/. Microsoft Global Software Development Archives: www.microsoft. com/globaldev/articles/articles.asp. 9 Working with Legacy Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ ActiveX controls ✓ COM/COM+ components ✓ Windows API ✓ Wrapper ✓ aximp.exe ✓ tlbimp.exe ✓ Platform Invoke Techniques you’ll need to master: ✓ Understand the function of a proxy wrapper when integrating legacy components within .NET applications. ✓ Know how to convert ActiveX controls to use within .NET applications. ✓ Understand how to use Platform Invoke to invoke common Windows API calls. 214 Chapter 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Although the .NET Framework can handle almost any possible application development need, most organizations implement new .NET applications within a collection of existing legacy code written using earlier technologies. The ActiveX, COM, and COM+ functionality can be integrated into .NET application development. You can also make calls to the Windows application programming interface (API) through .NET applications. This makes migration to the .NET Framework much easier than writing everything from the ground up. The interoperability features of .NET can handle legacy code in many ways: ➤ ActiveX—ActiveX controls can be placed on Windows forms. ➤ COM/COM+—These components can be instantiated and invoked by .NET code. ➤ Windows API—The Windows API can be invoked using the Platform Invoke capability (PInvoke) within .NET applications. In this chapter, we discuss the integration of legacy code objects within .NET application development. It should be noted that the interoperability of .NET code is two-way. It is possible for .NET code to call COM components, and vice versa. Using ActiveX Controls The .NET Framework utilizes an object-oriented development style, while ActiveX components deliver encapsulated functionality through standard interfaces that communicate with the form on which they are placed. To make a legacy ActiveX control accessible as a .NET class, it is necessary to encapsulate the ActiveX control within a wrapper, which serves as a proxy between the .NET and ActiveX development technologies. A wrapper is a software layer that acts as a control container for an ActiveX component. It allows .NET code to treat the contained component as a normal Windows Forms control. 215 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Working . . . . .with . . Legacy . . . . Code . . . The Windows Forms ActiveX Control Importer (aximp.exe) The System.Windows.Forms namespace includes a wrapper class, AxHost, which is used to encapsulate ActiveX components. An instance of the AxHost class must be customized for the contained ActiveX control. This is accomplished using the Windows Forms ActiveX Control Importer (aximp.exe), as in the following example: 1. Create a folder to house the imported control. 2. Open the Visual Studio .NET command prompt, accessed through Start, Programs, Microsoft Visual Studio .NET, Visual Studio .NET Tools, Visual Studio .NET Command Prompt. 3. Navigate to the folder created in Step 1, and then enter the following command (here, we are importing the SysInfo control included with Visual Basic 6.0 on a system running Windows 2000): aximp c:\winnt\system32\sysinfo.ocx In Windows XP, replace c:\Winnt in the previous command with c:\Windows. The Importer lists the names of the files that were created by the import process: SysInfoLib.dll AxSysInfoLib.dll 4. Open Visual Studio .NET and create a new Visual C# .NET Windows application. 5. Right-click the References node of the Solution Explorer, and select Add Reference to open the Add Reference dialog box. 6. Select the COM tab and browse to the folder created in Step 1. 7. Add references to both files created in Step 3. 8. Modify the form’s class definition as follows: public class SampleControl : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private AxSysInfoLib.AxSysInfo sysInfo1; public SampleControl() { // Required for Windows Form Designer support 216 Chapter 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . InitializeComponent(); // TODO: Add any constructor code after // InitializeComponent call } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(Type.GetType( “MyProject.SampleControl”)); this.sysInfo1 = new AxSysInfoLib.AxSysInfo(); ((System.ComponentModel.ISupportInitialize)this.sysInfo1). BeginInit(); this.SuspendLayout(); // //SysInfo1 // this.sysInfo1.Enabled = true; this.sysInfo1.Name = “sysInfo1”; this.sysInfo1.OcxState = (System.Windows.Forms.AxHost.State) resources.GetObject(“SysInfo1.OcxState”); this.sysInfo1.Size = new System.Drawing.Size(38, 38); this.sysInfo1.TabIndex = 0; // // SampleControl // this.AutoScaleBaseSize = new System.Drawing.Size(5, ➥13); this.ClientSize = new System.Drawing.Size(292, 273); this.Controls.AddRange(new System.Windows.Forms.Control[] {this.sysInfo1}); this.Name = “SampleControl”; this.Text = “SampleControl”; this.Load += new System.EventHandler(this.SampleControl_Load); ((System.ComponentModel.ISupportInitialize)this.sysInfo1). EndInit(); this.ResumeLayout(false); } #endregion [STAThread] static void Main() 217 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Working . . . . .with . . Legacy . . . . Code . . . { Application.Run(new SampleControl()); } private void SampleControl_Load(object sender, System.EventArgs e) { MessageBox.Show(sysInfo1.OSVersion.ToString()); } } 9. Switch back to Design view of the form to see the included instance of the SysInfo control (see Figure 9.1). Figure 9.1 Sample form displaying an instance of the imported SysInfo ActiveX component. Importing Controls Using the Visual Studio .NET Toolbox Although the Windows Forms ActiveX Control Importer tool can be used to create the necessary files to import an ActiveX component, you can also perform this task using the Visual Studio .NET toolbox. This is considered an easier method because most of the setup work is done for you when importing the desired ActiveX component. The following example displays this capability: 1. Open Visual Studio .NET and create a new Visual C# .NET Windows application. 2. Right-click the toolbox and select Customize Toolbox to open the Customize Toolbox dialog box. 3. Select the COM components tab in the Customize Toolbox dialog box. Scroll down the list of registered controls on the system, and click the checkbox for any controls to import, as shown in Figure 9.2. 218 Chapter 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Figure 9.2 The Customize Toolbox dialog box showing the Masked Edit Control selected for import. 4. Click OK to add the imported control to the toolbox, as shown in Figure 9.3. Figure 9.3 The Visual Studio .NET toolbox showing the newly imported Masked Edit control. 5. Drag and drop the imported control onto a form, as with any other Windows Forms control. The properties of an imported ActiveX control can be accessed using the properties window. You also can click the ActiveX Properties hyperlink at the bottom of the sheet to open the ActiveX control’s property sheet directly. 219 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Working . . . . .with . . Legacy . . . . Code . . . Using ActiveX Controls Imported ActiveX controls can be used like any other type of Windows Forms control. However, there are a few drawbacks to consider: ➤ Performance—Calls to the wrapper providing support to ActiveX compo- nents will generate additional delay, resulting in decreased performance compared to pure .NET controls. ➤ Property names—Some property names might change when importing an ActiveX component into the .NET Framework, to avoid conflicts with existing properties. The most commonly encountered property name change is the State property, which is renamed to CtlState during the conversion process. ➤ Errors—Because ActiveX components are not managed code, errors and memory-access issues can cause abnormal operation or undesired application termination. ➤ Deployment—Including ActiveX controls can add to the complexity of application deployment because each workstation must have the ActiveX control properly installed and registered. Using COM Components Beyond simply including ActiveX components within Windows Forms, you will encounter situations that involve the instantiation and invocation of other types of legacy COM components, including controls and class libraries. During the process of migration to the .NET Framework, it is possible that other developers within an organization might continue producing new COM-based functionality, while vendors might continue to make use of this technology for some time beyond your organization’s migration. It is critical to know how to use COM components within your .NET applications. Runtime Callable Wrappers The .NET Framework makes use of a Common Language Runtime (CLR), which provides support for managed code, including garbage collection, member management, security, and versioning. Legacy code, which is not designed to operate within the CLR, does not gain this support and thus is termed unmanaged code. 220 Chapter 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A proxy class must wrap unmanaged code, such as COM components, to allow the CLR to call the encapsulated component. This proxy is termed a runtime-callable wrapper. If you have Visual Basic 6.0, you can follow the next steps to create a suitable COM component to test the inclusion of an unmanaged COM component within a .NET application: 1. Open Visual Basic 6.0 and create a new ActiveX DLL project. 2. Rename the Project1 node to MyCustomer, and the Class1 node to Balances in the Project Explorer. 3. Add code to the Balances class: Option Explicit Private mintCustomerCount As Integer Private macurBalances(1 To 10) As Currency ‘ Create a read-only CustomerCount property Public Property Get CustomerCount() As Integer CustomerCount = mintCustomerCount End Property ‘ Create a GetBalance method Public Function GetBalance(CustomerNumber As Integer) As Currency GetBalance = macurBalances(CustomerNumber) End Function ‘ Initialize the data Private Sub Class_Initialize() Dim intI As Integer mintCustomerCount = 10 For intI = 1 To 10 macurBalances(intI) = Int(Rnd(1) * 100000) / 100 Next intI End Sub 4. Save the project and then build the MyCustomer.dll to create the COM component. The Type Library Importer Tool (tlbimp.exe) It is possible to import the metadata of a COM component using the Type Library Importer (tlbimp.exe) tool to import the component’s type library. You can create a runtime-callable wrapper for the COM component created in the last example using the following steps: 1. Open the Visual Studio .NET command prompt, accessed through Start, Programs, Microsoft Visual Studio .NET, Visual Studio .NET Tools, Visual Studio .NET Command Prompt. 221 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Working . . . . .with . . Legacy . . . . Code . . . 2. Navigate to the folder containing the MyCustomers.dll and enter the following code: tlbimp MyCustomer.dll /out:NETMyCustomer.dll 3. After creating a Visual C# .NET Windows application, right-click the References node in the Solution Explorer and select Add Reference. 4. Navigate to the NETMyCustomer.dll file and then click OK to add the new reference to the project. 5. Switch to Code view of the form and add the following using directive: using NETMyCustomer; 6. Use the component within your code as you would any .NET managed code component. The wrapper will serve as a proxy between the .NET and COM technologies. Table 9.1 displays a number of important options for the Type Library Importer tool (tblimp.exe). Table 9.1 Options for the Type Library Importer Tool Option Meaning /asmversion:versionNumber Specifies the assembly’s version number /delaysign Prepares the assembly for delay signing /help Displays help on these options /keycontainer:containerName Signs the assembly with the strong name from the specified key container /keyfile:filename Signs the assembly with the strong name from the specified key file /namespace:namespace Specifies the namespace for the assembly /nologo Suppresses the startup banner display /out:filename Specifies the name of the created assembly /primary Produces a primary interop assembly /publickey:filename Contains a public key used to sign the resulting file /reference:filename Specifies a file used to resolve references from the imported file /silent Suppresses information that would be displayed during conversion /strictref Refuses to create the assembly if any references cannot be resolved (continued) 222 Chapter 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 9.1 Options for the Type Library Importer Tool (continued) Option Meaning /sysarray Imports COM safe arrays as instances of the System.Array class /unsafe Creates interfaces without .NET Framework security checks /verbose Displays additional information during conversion /? Displays help on these options Using COM Components Directly The Visual Studio .NET interface supports directly adding a reference to COM components. To do so, follow these steps: 1. After creating a new Visual C# .NET Windows application, right-click the References node in the Solution Explorer and select Add Reference. 2. Select the COM tab in the Add Reference dialog box and navigate the list of registered COM components until you locate the MyCustomer library. 3. Click OK to add the reference to the COM component. 4. Add the following code to the top of your form’s class definition: using MyCustomer; 5. Use the component within your code as you would any .NET managed code component. The wrapper will serve as a proxy between the .NET and COM technologies. When deciding between the Type Library Importer tool and directly referencing a COM component, you should use the direct reference only if you do not need to be able to sign the resultant assembly and place it in the Global Assembly Cache (GAC) for distribution. If you need to distribute the application or manage its name, namespace, or version, you must use the Type Library Importer tool. Using COM+ Components COM+ extended the COM standard to allow several new features when running under Windows 2000 and later: ➤ Role-based security ➤ Object pooling and reusability 223 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Working . . . . .with . . Legacy . . . . Code . . . ➤ Queued components for asynchronous calls ➤ Transactional processing ➤ Publisher/subscriber events model References to COM+ components can be created using the same techniques as used for COM components. Using wrapped COM and COM+ components within .NET applications involves the same basic problems detailed earlier in this section. Using Platform Invoke In addition to COM and COM+ components, the .NET Framework can access other types of unmanaged code libraries. .NET can call functions from unmanaged Windows API libraries through the use of Platform Invoke (PInvoke), described in the following steps: 1. After creating a new Visual C# .NET application, place a Label control named lblComputerName on the form. Add the following code at the top of the form’s class definition: using System.Text; using System.Runtime.InteropServices; 2. Add the following lines of code in the class definition, which indicates that the GetComputerName method is implemented in kernel32.dll: [DllImport(“kernel32.dll”, CharSet=CharSet.Auto)] public static extern int GetComputerName( StringBuilder buffer, ref uint size); 3. Add the following code to handle the Load event of the form: private void SampleForm_Load(object sender, System.EventArgs e) { StringBuilder sbBuf = new StringBuilder(128); UInt32 intLen = (uint) sbBuf.Capacity; Int32 intRet=0; // Call the Win API method intRet = GetComputerName(sbBuf, ref intLen); lblComputerName.Text = “This computer is named “ + sbBuf.ToString(); } In Viusal C# .NET, you should use a StringBuilder object for a Windows API call that expects a string buffer. 224 Chapter 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . PInvoke also can use API calls that require structures as parameters. The .NET Framework and Visual Studio .NET include a variety of features to make it easy to use legacy components. In this chapter, you learned about three of those features: ➤ The capability to use ActiveX controls on a Windows form ➤ The capability to instantiate and invoke objects from a COM compo- nent ➤ The capability to call functions from an unmanaged DLL 225 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Troubleshooting . . . . . . . . . Practice Questions Question 1 After importing your favorite ActiveX control using the .NET toolbox, you insert an instance of it as MyControl and need to manipulate a property named State. Which of the following will result in the desired manipulation? ❍ A. Include this line of code: MyControl.CtlState = 1; ❍ B. Include this line of code: MyControl.AxState = 1; ❍ C. Include this line of code: MyControl.State = 1; ❍ D. Include this line of code: CtlState.MyControl = 1; Answer A is correct. The State property is renamed during the import process to CtlState, to avoid conflicting with the existing .NET State property. Answer B is incorrect because the normal renaming method results in a property named CtlState. Answer C is incorrect because the State property is a standard .NET property that requires the renaming of the imported property to CtlState. Answer D is incorrect because the property specification must follow the name of the control, which is reversed here. Question 2 Which of the following are reasons for using legacy code within .NET applications? (Select all that apply.) ❑ A. Other developers might be continuing to develop COM and ActiveX elements. ❑ B. Third-party components might use older technologies. ❑ C. COM+ components might be faster than their .NET equivalent. ❑ D. It is possible to migrate in stages. Answers A, B, and D are correct. Using legacy components in your .NET application enables you to begin a staged migration while other developers continue using technologies they are more familiar with; this also enables 226 Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . you to support third-party provided components. Answer C is incorrect because the use of a proxy wrapper between .NET code and encapsulated COM or COM+ components generally causes legacy components to suffer a performance penalty compared to .NET components running within the CLR. Question 3 You want to use the Microsoft Masked Edit ActiveX control in your Visual C# .NET application. How can you make this control available for your Windows forms? (Select two.) ❑ A. Add the control directly to the Visual C# .NET toolbox ❑ B. Add a direct reference to the COM component ❑ C. Use the aximp.exe utility ❑ D. Use the tlbimp.exe utility Answers A and C are correct. To use an ActiveX control in Windows forms, you can either use the Windows forms ActiveX Control Importer tool (aximp.exe) or you can add the ActiveX control directly to the Visual Studio .NET toolbox. The latter technique automatically creates the necessary wrapper for the ActiveX control. Answers B and D are not correct because you cannot add an ActiveX control by using these methods. These methods enable you to use COM components in .NET applications. Question 4 Which of the following methods can be used to create a runtime-callable wrapper for a COM component? (Select all that apply.) ❑ A. Placing the COM component directly on your form ❑ B. Using the aximp.exe utility ❑ C. Adding a direct reference to the COM component ❑ D. Using the tlbimp.exe utility Answers C and D are correct. You can create the necessary wrapper for a COM component by adding a reference to the COM component directly or by using the Type Library Importer utility (tlbimp.exe). Answer A is incorrect because ActiveX components predate the CLR and cannot be placed directly on a .NET Windows form; this question also specifies a more general COM component than an ActiveX component. Answer B is incorrect 227 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Troubleshooting . . . . . . . . . because the Windows Forms ActiveX Control Importer (aximp.exe) can be used only with ActiveX controls. Question 5 Which one of the following statements is most true regarding the inclusion of legacy components in your .NET application? ❍ A. COM components cannot take advantage of the enhanced support provided by the CLR, whereas COM+ components can. ❍ B. Legacy components cannot be used when their property names conflict with existing .NET properties. ❍ C. Legacy components suffer a performance loss due to the presence of the wrapper class. ❍ D. Legacy component use is transparent to users within .NET applications. Answer C is correct. The proxy wrapper adds an extra processing step during calls to legacy components, creating a decrease in performance over .NET components. Answer A is incorrect because both COM and COM+ components are unmanaged code and thus cannot use the CLR’s support capabilities. Answer B is incorrect because conflicting property names automatically are renamed during conversion. Answer D is incorrect because legacy component use is slower and might require extra steps to properly deploy the additional components to user workstations. Question 6 You have set a direct reference to a COM component named MortgageCalculator. This component is heavily used by the mortgage application developed in Visual C# .NET. Users report that the performance of the application is poor; it takes a lot of time when they perform mortgage calculations. Which of the following options should you take to solve the problem? ❍ A. Rewrite the MortgageCalculator component as a .NET component. ❍ B. Use the Type Library Importer tool to generate wrapper assembly. ❍ C. Use the Platform Invoke to make calls to the BarGraph component. ❍ D. Store the MortgageCalculator component in the GAC. Answer A is correct. Using COM components in .NET applications incurs an overhead that can decrease the performance of your application. The best option to remove the overhead is to rewrite the COM component as a .NET 228 Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . component. Answer B is not correct because it does not matter how you generate wrapper assembly. Answer C is not correct because platform invoke is used to call methods from unmanaged libraries, such as Windows API, not from the COM component. Answer D is not correct because the MortgageCalculator component is used by just one application and need not be placed in the GAC. Question 7 Which one of the following statements is most true regarding the usage of PInvoke in .NET applications? ❍ A. PInvoke can be used to include legacy interoperability support for ActiveX components. ❍ B. PInvoke can be used to include legacy interoperability support for COM components. ❍ C. PInvoke can be used to include legacy interoperability support for COM and COM+ components. ❍ D. PInvoke can be used to include legacy interoperability support for Windows API calls. Answer D is correct. Platform Invoke (PInvoke) is used to provide access to Windows API calls. Answers A, B, and C are incorrect because PInvoke does not provide support for COM, COM+, or ActiveX components, all of which require a proxy wrapper class. Question 8 Which of the following legacy items can be directly added using the Visual Studio .NET interface? (Select all that apply.) ❑ A. ActiveX controls ❑ B. COM components ❑ C. COM+ components ❑ D. Windows API calls Answers A, B, and C are correct. An ActiveX component can be directly imported using the Visual Studio .NET toolbox, while COM and COM+ components can be directly added to the References node of the Solution Explorer. Answer D is incorrect because PInvoke calls to the Windows API require code within your application. 229 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Troubleshooting . . . . . . . . . Question 9 You are planning to use a COM component in your .NET application. You want to place the COM component in the LegacyComponents namespace. Which of the following options should you choose? ❍ A. Set a direct reference to the COM component. Change the namespace in the wrapper class created to LegacyComponents. ❍ B. Use the Type Library Importer tool to create the wrapper class with the /keycontainer option to specify the container namespace. ❍ C. Use the Type Library Importer tool to create the wrapper class with the /namespace option to specify the desired namespace. ❍ D. Use the Type Library Importer tool to create the wrapper class with the /out option to specify the output namespace. Answer C is correct. When you want to manage the name, namespace, version, and other details while creating the wrapper assembly, you should choose to create the wrapper using the Type Library Importer tool rather than add a direct reference to the COM component. The /namespace option is used to specify the namespace for the wrapper class. Answer A is not correct because you should not add a reference to the COM assembly if you want to specify a namespace explicitly. Answer B is not correct because the /keycontainer option signs the assembly with the strong name from the specified key container. Answer D is not correct because the /out option specifies the name of the created wrapper assembly. Question 10 Your application needs to use the GetUserName API function from advapi32.dll. You declare the method using DllImport attribute, as follows: [DllImport(“advapi32.dll”)] public static extern bool GetUserName (String buffer, ref int size); When you call this method, you notice that the string buffer is empty, even though there is a username specified. What should you do to solve the problem? ❍ A. Use the ref keyword along with the buffer declaration. ❍ B. Use the out keyword along with the buffer declaration. ❍ C. Replace the String object with StringBuilder object. ❍ D. Set the size of the string to a large number. 230 Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer C is correct. In Platform Invoke calls, you should use the StringBuilder object for a Windows API call that expects a string buffer to hold the return value. Therefore, you should replace the String object with the StringBuilder object. Answers A, B, and D are simply incorrect. 231 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Troubleshooting . . . . . . . . . Need to Know More? Kalani, Amit. MCAD/MCSD Training Guide: Developing and Implementing Windows-Based Applications with Microsoft Visual C# .NET and Microsoft Visual Studio .NET, Exam 70-316. Que Certifications, 2003. Nathan, Adam. .NET and COM: The Complete Interoperability Guide. Sams, 2002. Troelsen, Andrew. COM and .NET Interoperability. Apress, 2002. Windows Forms Community Site: www.windowsforms.net/. 10 User Assistance and Accessibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ User assistance ✓ Accessibility ✓ HTML Help ✓ Topic files ✓ Table of contents ✓ Index ✓ HelpProvider component ✓ Pop-up help ✓ Tool Tip ✓ High Contrast mode Techniques you’ll need to master: ✓ Understand the purpose of user assistance and accessibility planning within your application. ✓ Know how to create and consume an HTML Help file project. ✓ Understand how to plan for application accessibility. 234 Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Complex applications should include assistive coding to help users during operation. This might include traditional help files or ToolTips that provide specific help for individual components. Accessibility planning might include details such as high contrast monochromatic (black-and-white) display or alternate methods for data output such as Braille text readers. ➤ User assistance is the process of providing help within an application. ➤ Accessibility refers to making your application usable by those with dis- abling conditions. This chapter covers several ways in which your application can take advantage of the user assistance and accessibility options available within the .NET Framework. HTML Help Multipaned HTML Help files are often the most familiar form of userassistive programming (see Figure 10.1). These files support typical help descriptions that can be cross-linked using HTML hyperlinks, enabling a user to navigate among related topics. Context-sensitive applications allow access to HTML Help files that relate to the currently selected control. Figure 10.1 An example of an HTML Help file. At the time of this writing, HTML Help version 1.3 is the current standard. Version 2.0 is currently in beta and has not yet released the application programming interface (API) that is necessary to call it from a Visual C# .NET form through context-sensitive help. 235 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . User . . . Assistance . . . . . . and . . Accessibility . . . . . . . Inside HTML Help 1.3 Many utilities can be used to create HTML Help files, including shareware and commercial applications such as Robohelp. When you install Visual Studio .NET, the HTML Help Software Development Kit (SDK) is installed, along with a utility intended to make the creation of HTML Help files less arduous: the HTML Help Workshop utility. The HTML Help SDK includes the following components: ➤ HTML Help Workshop—An Integrated Development Environment (IDE) for developing HTML Help files ➤ HTML Help ActiveX Control and HTML Help Java Applet—Components that can be used for navigation within HTML Help files ➤ HTML Help Viewer—A host application used to display HTML Help files ➤ HTML Help Image Editor—An application that can capture screenshots and perform graphics-editing tasks ➤ HTML Help—An application that can execute HTML Help files outside the browser ➤ HTML Help Compiler—An application that converts HTML Help Workshop files into actual HTML Help files ➤ HTML Help Authoring Guide—Documentation for HTML Help file developers An HTML Help solution involves several files: ➤ Help project file—Determines the overall structure of the HTML help file ➤ Topic files—Contain individual sections of help documentation written as HTML files ➤ Graphics, sound, animation, and multimedia files—Can be embedded within HTML Help files ➤ Contents files—Contain table of contents information ➤ Index files—Contain index information 236 Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a Help Project The first step toward creating an HTML Help 1.3 solution is to create a Help project. This can be done by completing the following steps: 1. Launch the HTML Help Workshop by choosing Start, Programs, HTML Help Workshop, HTML Help Workshop. 2. Select File, New, and choose Project as the new file type. Click OK to launch the New Project Wizard, and click Next to bypass the introduction. 3. Select an appropriate location and name for the new HTML Help Project (.hpp) file and click Next. In the Existing Files page, click Next because you do not need to include any existing files. 4. Click Finish to create the new project file, as shown in Figure 10.2. Figure 10.2 New Help project in HTML Help Workshop. Creating Topic Files When you have created your HTML Help project, you must then create topic files designed to assist the user in a particular situation. You first need to know how your application will operate before you can create an appropriate help file for each situation. You can create a topic file by following these steps: 1. In the HTML Help Workstop, select File, New. 2. Select HTML File from the available options, and click OK to open the new HTML file. 3. Provide a meaningful title for the new file, and click OK to open the file in the HTML Help Workshop workspace. 237 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . User . . . Assistance . . . . . . and . . Accessibility . . . . . . . 4. Modify the HTML file to include specific details for the desired topic, such as these: <!DOCTYPE HTML PUBLIC “-//IETF//DTD HTML//EN”> <HTML> <HEAD> <meta name=”GENERATOR” content=”Microsoft® HTML Help Workshop 4.1”> <Title>Topic-Specific Title</Title> </HEAD> <BODY> <h1>Topic Heading</h1> <p><img src=”SomeImage.jpg”></p> <p>This is the topic help text that will be displayed following the image file noted above.</p> </BODY> </HTML> 5. Select File, Save File and provide a meaningful name for the topic file to save. You are not required to edit the raw HTML code here. You can also use any common HTML-editing utility, such as Microsoft’s FrontPage. Linking Topic Files Using HTML files for online help allows the cross-linking of individual topic files through the use of a hyperlink. Hyperlinks should be familiar to anyone who browses the Web. Clicking a hyperlink redirects the browser’s focus to another page. This functionality allows users to navigate between related topics. A hyperlink can be placed anywhere in the body of the HTML file (between the <BODY> and </BODY> tags), and it can be either a file reference for a local file or a remote URL referencing an external file: <p><a href=”somepage.htm”>Some Page</a></p> <p><a href=”http://www.mycorp.com/someotherpage.htm”> Some Other Page</a></p> Creating a Table of Contents To make your HTML Help files useful to users looking for a particular item, you should create a table of contents. After you have created your topic files, you can accomplish this within the HTML Help Workshop as follows: 1. In the HTML Help Workshop, select File, New. Select Table of Contents and click OK. 238 Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2. Provide a meaningful name for the new table of contents (.hhc) file, and save the file. 3. Click the Options button on the Projects tab. Set the default file to the proper HTML (.htm) file, and set the contents file to your newly created table of contents file (.hhc). 4. Select Edit, Insert Topic to add your topic files (.htm). When you select existing items within the interface, your new additions become subordinate items within the table of contents listing, as shown in Figure 10.3. Figure 10.3 Topic files listed within a table of contents in the HTML Help Workshop. 5. Continue adding topics until the table of contents is completed. Creating an Index One additional measure of assistance for users is a searchable index. You can create this in the HTML Help Workshop by completing the following steps: 1. In the HTML Help Workshop, select File, New. Select Index and click OK. 2. Provide a meaningful name for the new index (.hhk) file and save the file. 3. Select Edit, Insert Keyword to open the Keyword dialog box. Select the target HTML Help file (.hhp) project. 4. Provide a keyword and select Browse to navigate to the target topic file (.htm) for the keyword. Then click OK. 239 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . User . . . Assistance . . . . . . and . . Accessibility . . . . . . . 5. Continue adding keywords until completed. Then click the Options button on the Project tab of the HTML Help Workshop. 6. On the Files tab, set the index file to your newly created index file (.hhk) and click OK. Remember that a table of contents provides a structured way for users to find topics of interest. The index allows users to rapidly search for keywords. Compiling and Testing an HTML Help File After you have completed all topic files, the table of contents, and an index, you can compile the HTML Help project and test it by following these steps: 1. In the HTML Help Workshop, save and close all files. Select File, Compile to open the Create a Compiled File dialog box. 2. Select options if you want to display or save the compiled files. Provide a meaningful name for the completed file and then click Compile. 3. After the compilation has been completed, click the View Compiled File button, browse to the newly created file, and click View to open the file in the Help browser. Implementing User Assistance After you have created your help files, you must make this information available in your application. User assistance has many elements, including the following: ➤ Readme files and other introductory material for the user to refer to even before installing the application ➤ Printed, online, or electronic documentation ➤ Email, telephone, or on-site support by product specialists ➤ Wizards, builders, and other user interface components designed to guide the user through a process ➤ Help files, pop-up help, and ToolTip details for individual controls Within your .NET application, you can provide integrated user assistance in three main ways: 240 Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ Help files—You can use the HelpProvider component to show a tradi- tional help file. ➤ Pop-up help—You can use the HelpProvider component to provide pop- up help for a dialog box. ➤ ToolTips—The ToolTip component can provide quick help for individual controls. The Help Class The Help class can be used to display help from compiled Help files (.chm) or HTML files in the HTML Help format. It consists of two static methods—ShowHelp and ShowHelpIndex—that enable you to display a help file to its default topic instead of any specific topic. The ShowHelp method displays the contents of a specified help file, and the ShowHelpIndex method displays the index of a specified help file. The HelpProvider Component The HelpProvider component can link your application and an associated help file. By placing a HelpProvider component on your form, it extends other objects on the form to include help-related properties. The extended properties automatically appear in the Properties list for the form and its controls. The HelpNamespace property of the HelpProvider component specifies the help file or target URL to use, while the HelpNavigator and HelpKeyword properties specify the information to show from the help file. Table 10.1 displays the possible values for the HelpNavigator property. Table 10.1 Values of the HelpProvider.HelpNavigator Property Value Meaning AssociateIndex Displays the first topic listed in the index for the specified HelpKeyword property Find Displays the search page of the specified help file Index Displays the index for the specified help file KeywordIndex Displays the index for the specified HelpKeyword property TableOfContents Displays the table of contents for the specified help file Topic Displays the topic identified by the specified HelpKeyword property 241 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . User . . . Assistance . . . . . . and . . Accessibility . . . . . . . Pop-Up Help Implementing the HelpProvider component to open a normal HTML Help browser window might not always be desired. Dialog boxes are intended to keep users focused on a simple task until it has been completed, and switching to another window might not be desirable in such a scenario. Pop-up help can be used to allow the display of focused help information, without including the additional navigability of a separate Help browser window or to focus redirection. After placing a HelpProvider component on your form, you can provide pop-up help by entering text within the HelpString property for each control. Clicking the Help button on the form’s toolbar and then clicking a control displays the HelpString text for that control. To display a form’s Help button, set the HelpButton property to true, the MinimizeBox property to false, and the MaximizeBox property to false. The ToopTip Component Another useful component that extends the properties of the controls on your form is the ToolTip component. By placing a ToolTip component on your form, you can provide a short text string for each control that will be displayed when the user hovers the cursor over the control. You can configure four properties to control the timing (in milliseconds) of ToolTip displays: ➤ InitialDisplay—The delay before the initial ToolTip is displayed. ➤ AutoPopDelay—The time that the ToolTip remains visible. ➤ ReshowDelay—The delay before subsequent ToolTips are displayed as the cursor moves across controls. ➤ AutomaticDelay—A single value used to set all three of the other proper- ties. InitialDelay is set equal to AutomaticDelay, AutoPopDelay is set to 10 times AutomaticDelay, and ReshowDelay is set to one-fifth of AutoDelay. 242 Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Accessibility When planning your application, you should take the time to consider the various accessibility requirements of your users. Accessibility design planning includes five basic principles: ➤ Flexibility—The user interface should be flexibile and customizable, allowing users to adjust it to their individual needs and preferences. ➤ Input methods—All operations in your application should be accessible by the keyboard alone, and basic operations should be available via the mouse as well. In the future, voice, directed-visual cues, and other types of input might also be considered here. ➤ Output methods—Output should not depend on a single method (such as sound, color, or text) for important information. ➤ Consistency—The application should be consistent with the Windows operating system and other applications, to reduce the learning curve required of new users. ➤ Compatibility with accessibility aids—Microsoft Windows includes a num- ber of accessibility aids, such as the Magnifier and the On-Screen Keyboard. Your application should support these. Table 10.2 details some of the accessibility guidelines you should use to support these principles. Table 10.2 Accessibility Guidelines for Application Design Area Guidelines Color Use color to highlight information, but not as the sole means of conveying important information. Remember that not all users can distinguish among all colors. Disks Do not make the user insert or swap removable media during the normal operation of the application. General User Interface Provide a user interface that is flexible enough to accommodate the varying needs and preferences of different users, such as providing keyboard navigation in addition to mouse navigation. Keyboard focus Many accessibility aids need to identify the location of the keyboard focus to function properly. The .NET Framework normally takes care of this for you. (continued) 243 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . User . . . Assistance . . . . . . and . . Accessibility . . . . . . . Table 10.2 Accessibility Guidelines for Application Design (continued) Area Guidelines Keyboard input Applications should be accessible via keyboard input. Alternative input devices often emulate the keyboard, so if your application is fully available via the keyboard, it will generally be available to these devices as well. Layout Every item onscreen should be identified by a label, to assist users who cannot see the entire screen at one time. Mouse input Some users might use a mouse (or a device whose interface emulates a mouse) more easily than a keyboard. Your application should also be available via the mouse. Multitasking Excessive consumption of processor power can interfere with accessibility aids. Your application should be as efficient as possible. Size Allow users to resize items onscreen to accommodate their own preferences. Sound Use sound to enhance information, but do not rely on it as the sole means of conveying important information. Users with hearing impairments or those working in noisy environments might be unable to make use of sound cues. Timing Timed events should be adjustable by the user to accommodate varying reaction times based on user preferences. Control Properties for Accessibility The .NET Framework provides a number of accessibility-related properties for controls, including these: ➤ AccessibleDescripton property—This is a description of the control that will be reported to accessibility aids. ➤ AccessibleName property—This is the control’s name that will be reported to accessibility aids. ➤ AccessibleRole property—This is the control’s role that will be reported to accessibility aids. ➤ BackColor property and ForeColor property—Use the default value to use the user’s selected screen colors. ➤ BackgroundImage property—Leave this property empty to help users read text on your forms. ➤ Font-Size property—If the font size on your form is fixed, it should be set to at least 10 points (10pt). 244 Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ TabIndex property—Set the TabIndex for each control to ensure a sensible navigation path and to make sure that shortcut keys work to access controls. ➤ Text property—Use the ampersand character (&) to create shortcut keys and ensure keyboard access to controls. Supporting High Contrast Mode Many users use the High Contrast property to make information more clearly recognizable. Your application can adjust its functionality based on the value of the Boolean SystemInformation.HighContrast property. An event handler for the SystemEvents.UserPrefernceChanged event can allow your application to change its operation when the HighContrast property changes. To make effective use of the High Contrast mode, your application should do the following: ➤ Use only system colors to display controls ➤ Add visual cues, such as a bold font face or special icons, to enhance information instead of using color ➤ Remove background images or patterns 245 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . User . . . Assistance . . . . . . and . . Accessibility . . . . . . . Practice Questions Question 1 You have created an HTML Help file for an application. You have placed a HelpProvider component on the form. You have set the HelpProvider component’s HelpNamespace property to HTML help file, to link the help file with the application. You now want to display a specific help topic from the help file for this form. Which of the following properties should you choose? (Select two.) ❑ A. HelpKeyword ❑ B. HelpString ❑ C. HelpNavigator ❑ D. ShowHelp Answers A and C are correct. The HelpKeyword and HelpNavigator properties specify the exact information to show from the help file. The HelpKeyword property specifies the information to display. The HelpNavigator property specifies which element of the help file to display. Answer B is not correct because the HelpString property specifies the help to be displayed for the pop-up help. Answer D is not correct because the ShowHelp property indicates whether the help for the form should be displayed. Question 2 Which of the following are components of the HTML Help system? (Select all that apply.) ❑ A. Project file ❑ B. Topic files ❑ C. Contents file ❑ D. Index file ❑ E. Keyword file Answers A, B, C, and D are correct. An HTML Help project includes the project file, several topic files, a contents file, and an index file. Keywords are associated with help destinations within the index file rather than in a separate keywords file, making answer E incorrect. 246 Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 3 Where should you place a hyperlink reference within a topic file? (Select the best answer.) ❍ A. Between the <HEAD> and </HEAD> tags ❍ B. Between the <BODY> and </BODY> tags ❍ C. Between the <HTML> and </HTML> tags ❍ D. Between the <LINK> and </LINK> tags Answer B is correct. A hyperlink reference should be placed within the body of the HTML file, between the <BODY> and </BODY> tags. Answer A is incorrect because the <HEAD> and </HEAD> tags define the header portion of the HTML file. The <HTML> and </HTML> tags enclose both the header and body portions of the HTML file, making answer C incorrect because it is not the best option available. Answer D is incorrect because a hyperlink uses <a href=“...”> and </a> tags rather than <LINK> and </LINK> tags. Question 4 Your application contains a modal dialog box form. You need to provide user assistance in the form of pop-up help for the dialog box form. How should you set the properties of the form? (Select all that apply.) ❑ A. Set the HelpButton property to true. ❑ B. Set the HelpButton property to false. ❑ C. Set the MaximizeBox property to true. ❑ D. Set the MaximizeBox property to false. ❑ E. Set the MinimizeBox to true. ❑ F. Set the MinimizeBox to false. Answers A, D, and F are correct. To display pop-up help, the form should have the HelpButton set to true and the MaximizeBox and MininmizeBox properties set to false. 247 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . User . . . Assistance . . . . . . and . . Accessibility . . . . . . . Question 5 One of your users makes use of an electromyogram mouse emulator that moves the cursor based on muscular tension. Which of the accessibility design principles would include planning for this device? (Select the best answer.) ❍ A. Flexibility ❍ B. Input methods ❍ C. Output methods ❍ D. Consistency ❍ E. Compatibility with accessibility aids Answer B is correct. Input method planning includes making sure that your application supports mouse and keyboard access. Alternate input-emulation devices that use keyboard and mouse functionality should then work with your application. Answer A is incorrect because flexibility addresses the need to allow users to select their own preferences. Answer C is incorrect because a mouse emulator is an input device rather than an output device. Answer D is incorrect because consistency involves making your application compatible with the standard Windows interface, to make it more easily navigable to users familiar with the Microsoft platform. Answer E is incorrect because the Windows accessibility aids are software rather than hardware. Question 6 You are creating an installation wizard for your new application and want to provide help for each stage of the installation. It is important that no new processes are instantiated during the installation. Which form of help should you implement to meet this requirement? ❍ A. HTML Help ❍ B. Pop-up help ❍ C. ToolTips ❍ D. Readme files Answer B is correct. Pop-up help provides assistance to users within an application without requiring a secondary help browser window. Answer A is incorrect because HTML Help makes use of the help file browser. Answer C is incorrect because a ToolTip is used to provide brief by-control assistance when a user passes the cursor over a control, and it would not be the best solution for user help for each section of the installation process. Answer D is not correct because opening Readme files would require a different process to start. 248 Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 7 Your application needs to be accessible by accessibility aids such as screen readers. Which properties should you explicitly set for every control? (Select two.) ❑ A. ForeColor property ❑ B. BackColor property ❑ C. AccessibleName property ❑ D. AccessibleDescription property ❑ E. AccessibleRole property Answers C and D are correct. The AccessibleDescription and AccessibleName properties provide important information for accessibility aids. The AccessibleRole property needs to be set only in special situations, thus making answer E incorrect. Answers A and B are not correct because the ForeColor and BackColor properties need not be set; if they are left at their default values, the user can adjust colors through the Control Panel. Question 8 Which ToolTip properties can be used to set the delay before a ToolTip is displayed? (Select all that apply.) ❑ A. AutomaticDisplay property ❑ B. AutoPopDelay property ❑ C. InitialDisplay property ❑ D. ReshowDelay property Answers A, C, and D are correct. The InitialDisplay property specifies the delay before the initial ToolTip is displayed, and the ReshowDelay property specifies the delay before another ToolTip is displayed when a user passes the cursor over several controls. The AutomaticDisplay property can be used to set all three of the other values. Answer B is incorrect because the AutoPopDelay specifies the length of time that a ToolTip will be displayed after the cursor moves over the control. 249 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . User . . . Assistance . . . . . . and . . Accessibility . . . . . . . Question 9 Which utility within the HTML Help SDK provides the integrated development environment for developing HTML Help projects? ❍ A. HTML Help Viewer ❍ B. HTML Help ❍ C. HTML Help Workshop ❍ D. HTML Help Compiler Answer C is correct. The HTML Help Workshop provides the IDE for developing HTML Help projects. Answers A and B are incorrect because the HTML Help Viewer and HTML Help are applications that can be used to view or execute HTML Help files outside the help browser. Answer D is incorrect because the HTML Help Compiler is used to convert HTML Help project files into actual HTML Help files. Question 10 Your application uses the system default colors and fonts throughout. When the user makes a data entry mistake, the computer beeps and the cursor remains in place. When the user saves a record, the data in the controls is cleared and the cursor is returned to the first control on the form. What should you do to make this form more accessible? ❍ A. Provide audio notification of saves. ❍ B. Provide an additional, nonaudio means of notification for data entry errors. ❍ C. Prompt the user before clearing the form. ❍ D. Set the form’s BackColor property to White instead of depending on the system properties. Answer B is correct. Your application should provide an additional nonaudio means for notifying data entry errors. Answer A is not correct because an accessible application should not depend on sound as the sole means of feedback. Answer C is not correct because this requires the user to respond to a dialog box every time the form is cleared. Answer D is not correct because an application should mostly use the system properties to set the form’s properties, such as BackColor. 250 Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Need to Know More? Kalani, Amit. MCAD/MCSD Training Guide: Developing and Implementing Windows-Based Applications with Microsoft Visual C# .NET and Microsoft Visual Studio .NET, Exam 70-316. Que Certification, 2003. Windows Forms Community Site: www.windowsforms.net/. Microsoft Accessibility Site: www.microsoft.com/enable/dev/. 11 Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ PrintDocument component ✓ Print method ✓ BeginPrint event ✓ QueryPageSettings event ✓ PrintPage event ✓ EndPrint event ✓ PrintPageEventArgs class ✓ PageSettings class ✓ PrinterSettings class ✓ PageSetupDialog component ✓ PrintPreviewDialog component ✓ PrintPreviewControl control ✓ PrintDialog component Techniques you’ll need to master: ✓ Understand the order of events generated during a print job. ✓ Understand how to configure the common PageSettings and PrinterSettings properties. ✓ Understand how to use the four standard Windows printing controls. 252 Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Many applications require the capability to produce permanent, printed output. This chapter reviews sending output to a printer from within your .NET application. Although the Visual Studio .NET package includes an integrated version of Crystal Reports, this is not a focus of the exam and thus it is not covered in detail here. The PrintDocument Component The .NET Framework makes use of the System.Drawing. Printing.PrintDocument class for printing output. You can print anything you can draw using the PrintDocument class. Printing in .NET applications is very similar to drawing text and graphics using the classes in the System.Drawing and its child namespaces. You learned about drawing graphical interface elements in Chapter 1, “Introducing Windows Forms.” To implement printing, you need to create a new instance of the PrintDocument class, set its properties and then call its Print method, which fires the PrintDocument.PrintPage event. You can retrieve a Graphics object from the PrintPage event and treat it as the page from which data can be printed. Using methods of the Graphics class, such as the Font and Brush objects, you can paint text and graphics on each page. To implement printing, the order of operations is as follows: 1. Instantiate a copy of the PrintDocument component in the Windows form. 2. Write code in the component’s PrintPage event handler that will dic- tate what is to be printed. At the end of this event, set the HasMorePages property to indicate whether there are more pages to print. 3. Call the Print method of the PrintDocument object to generate output to the printer. 4. The BeginPrint event fires once, before the first page of the job prints. 5. The QueryPageSettings event fires immediately before each PrintPage event, allowing manipulation of the page settings through QueryPageSettingsEventArgs.PageSettings property before the page is printed. 6. The PrintPage event fires once for each page to be printed. 7. The EndPrint event fires once, after the last page of the job has printed. 253 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Printing . . . . Printing Text The DrawString method of the Graphics class allows you to print text. In the following steps, you learn how to use the DrawString method to create a sample form capable of printing multiple pages. The number of pages is calculated based on the number of lines and the height of the selected font: 1. Open Visual Studio .NET create a new Visual C# .NET Windows application with a form. 2. Place a TextBox control named txtText, a Label control, a NumericUpDown control named nudCopies, a FontDialog component, two button controls named btnSetFont and btnPrint, and a PrintDocument component from the toolbox on your form. Figure 11.1 shows the design for this form. Figure 11.1 You can print multiple lines of text by using the font height to calculate the vertical position where the text should be printed. 3. Add this using directive in Code view: using System.Drawing.Printing; 4. Add this code to the class definition: // Create a default font to print with Font fnt = new Font(“Arial”, 10, FontStyle.Regular, GraphicsUnit.Point); // Number of lines printed so far Int32 intLines = 0; 5. Add this code to handle the events: private void btnPrint_Click(object sender, System.EventArgs e) { intLines=0; printDocument1.Print(); } private void btnSetFont_Click(object sender, System.EventArgs e) { 254 Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // Start with the current font fontDialog1.Font = fnt; // If the user clicks OK, set a new font if(fontDialog1.ShowDialog() == DialogResult.OK) { fnt = fontDialog1.Font; } } private void printDocument1_PrintPage(object sender, ➥System.Drawing.Printing.PrintPageEventArgs e) { // Determine the height of the font float fltFontHeight = fnt.GetHeight(e.Graphics); // Vertical position for the next line of text float fltCurrentY = 0; bool pageDone = false; while (!pageDone) { // Check to see whether there’s more space on the page if(fltCurrentY <= e.MarginBounds.Height) { // Increment the line number intLines += 1; if(intLines <= nudCopies.Value) { // Print the text, using the selected font e.Graphics.DrawString(txtText.Text, fnt, Brushes.Black, ➥0, fltCurrentY); // And increment the vertical location on the page fltCurrentY += fltFontHeight; } else { // We’ve printed all the copies we need to print. In // this case, set the flags to indicate that this page // is done, but there are no more pages pageDone = true; e.HasMorePages = false; } } else { // We want to print another line, but there’s no space pageDone = true; e.HasMorePages = true; } } } 6. Insert the Main method to launch this form, set the form as the startup object, and then run the application. After entering some text and manipulating the controls, you can print the result by clicking the Print button. The results automatically are formatted to fit on separate pages if required by the font and the number of copies specified for printing. 255 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Printing . . . . The PrintPageEventArgs Class The System.Drawing.Printing.PrintPageEventArgs class is used to provide properties of the printed page, such as the margins and page size that define the printable area. Table 11.1 presents many of the more common properties of the PrintPageEventArgs class. Table 11.1 Properties of the PrintPageEventArgs Class Property Meaning Cancel Gets or sets a value indicating whether the print job should be cancelled. Graphics Graphics object representing the page to be printed. HasMorePages Boolean value indicating whether more pages are left. MarginBounds Rectangle representing the printable area of the page. PageBounds Rectangle representing the entire page. PageSettings Object that gets or sets page settings such as orientation. The PageSettings property represents a PageSettings object that stores page settings. The PageSettings object contains the PrinterSettings property that exposes the PrinterSettings object. You should be familiar with some of the more common properties of the PageSettings and PrinterSettings subclasses, as presented in Tables 11.2 and 11.3. Table 11.2 Properties of the PageSettings Class Property Meaning Bounds Size of the page based on orientation. Color Gets or sets a value indicating whether to print in color. Landscape Is true if the page is in landscape (sideways) orientation. Margins Gets or sets the margins. PaperSize Gets or sets the paper size. PaperSource Gets or sets the paper source. PrinterResolution Gets or sets the resolution. PrinterSettings Returns the current PrinterSettings object. 256 Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 11.3 Properties of the PrinterSettings Class Property Meaning CanDuplex Is true if the printer supports duplex (two-sided) printing. Collate Is true if the printer output is collated. Copies Gets or sets the number of copies to print. DefaultPageSettings Returns a PageSettings object for this printer. Duplex Gets or sets the duplex setting. FromPage Gets or sets the first page number. InstalledPrinters Gets the names of all printers on the system. IsDefaultPrinter Indicates whether this is the default printer. IsPlotter Indicates whether this is a plotter. IsValid Indicates whether the PrinterName property designates a valid printer. LandscapeAngle Number of degrees of rotation between portrait and landscape output. MaximumCopies Maximum number of copies that you can print at once. MaximumPage Maximum number of pages allowed in the Print dialog box selection. MinimumPage Minimum number of pages allowed in a Print dialog box selection. PaperSizes Paper sizes supported by this printer. PaperSources Paper sources supported by this printer. PrinterName Gets or sets the name of the printer to use. Changing this property changes the target printer. PrinterResolutions Resolutions supported by this printer. PrintRange Page numbers specified for printing. PrintToFile Is true if output will be sent to a file. SupportsColor Is true if this printer supports color. ToPage Gets or sets the last page number to print. Printing Graphics It is also possible to print graphic images using the PrintDocument class, as in the following example: 1. Open Visual Studio .NET and create a new Visual C# .NET Windows application with a form. 257 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Printing . . . . 2. Place a button control named btnPrintGraphics and a PrintDocument component from the toolbox on your form. 3. Add these using directives in Code view: using System.Drawing; using System.Drawing.Printing; using System.Drawing.Drawing2D; 4. Add this code to handle the events: private void btnPrintGraphics_Click(object sender, System.EventArgs e) { printDocument1.Print(); } private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { Graphics grfx = e.Graphics; // Set the Smoothing mode to SmoothingMode.AntiAlias grfx.SmoothingMode = SmoothingMode.AntiAlias; // Create Pen objects Pen penYellow = new Pen(Color.Blue, 20); Pen penRed = new Pen(Color.Red, 10); // Call Draw methods grfx.DrawLine(Pens.Black, 20, 130, 250, 130); grfx.DrawEllipse(penYellow, 20, 10, 200, 100); grfx.DrawRectangle(penRed, 150, 10, 100, 100); // No more pages to print e.HasMorePages = false; } 5. Insert the Main method to launch this form, set the form as the startup object, and then run the application. When you click the button, the form prints a rectangle, an ellipse, and a line on the output page. Using the Printing Controls Although it is possible to design forms that can be used to set all the PageSettings and PrinterSettings property values, it is easier to use the provided Windows components to set Page settings and Printer settings: ➤ PageSetupDialog component ➤ PrintPreviewDialog component ➤ PrintPreviewControl control ➤ PrintDialog component Each of these is discussed in the following sections. 258 Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The PageSetupDialog Component The PageSetupDialog component is the standard Windows Page Setup dialog box used in most Windows applications, as shown in Figure 11.2. Figure 11.2 The Page Setup dialog box showing a portrait-oriented page. You can experiment with this component by modifying the first form created in this chapter to include a button control named btnPageSetup and a PageSetupDialog component named pageSetupDialog1. Add the following code to handle the Click event of the btnPageSetup control: private void btnPageSetup_Click(object sender, System.EventArgs e) { // Create a PageSettings object and send it to the dialog pageSetupDialog1.PageSettings = new PageSettings(); if(pageSetupDialog1.ShowDialog() == DialogResult.OK) { printDocument1.DefaultPageSettings = ➥pageSetupDialog1.PageSettings; } } When you click the Page Setup button, an instance of the Page Setup dialog box is displayed. This component has four properties that can be used to enable or disable different portions of the dialog box: ➤ AllowMargins—If false, disables margin settings. ➤ AllowOrientation—If false, disables orientation (print direction) settings. 259 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Printing . . . . ➤ AllowPaper—If false, disables paper size and source settings. ➤ AllowPrinter—If false, disables the Printer Selection button. The PrintPreviewDialog Component Another standard Windows component is the PrintPreviewDialog component, which enables a user to preview printed output before it is sent to the printer. You can experiment with this component by modifying the form used in the previous section to include another button control named btnPreview and a PrintPreviewDialog component named printPreviewDialog1. Add the following code to handle the Click event of the btnPreview control: private void btnPreview_Click(object sender, System.EventArgs e) { printPreviewDialog1.ShowDialog(); } When you click the Preview button, an instance of the PrintPreview dialog box is displayed, as shown in Figure 11.3. Figure 11.3 The PrintPreviewDialog component displaying two pages of formatted output. The PrintPreviewDialog component provides access to several encapsulated features: ➤ Capability to print from the preview interface (the printer icon) ➤ Adjustable Zoom settings (the magnifying glass icon) ➤ Multipage display modes allowing 1, 2, 3, 4, or 6 pages to be displayed at once ➤ The capability to scroll through all pages of the document that is being printed 260 Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The PrintDocument object’s events are fired in both the preview and print mode. The PrintPreviewControl Control It is also possible to embed a print preview control directly within your form so that a separate preview dialog interface is not required. You can include this functionality within the form you have been experimenting with by adding a PrintPreviewControl control to the form and by modifying the code fired by the Click event of the Preview button, as follows: private void btnPreview_Click(object sender, System.EventArgs e) { intLines=0; // Set the Document property of the control to printDocument1 printPreviewControl1.Document=printDocument1; } When you click the Preview button, an instance of the PrintPreviewControl control is displayed within the expanded form, as shown in Figure 11.4. Figure 11.4 Sample form showing an included instance of the PrintPreviewControl. The PrintPreviewControl will not function properly if you drop an instance onto a form and set its properties. It must be instantiated during runtime. 261 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Printing . . . . Unlike the PrintPreviewDialog component, the PrintPreviewControl control lacks the integrated feature buttons for presentation and scrolling. However, the control includes several features that can be manipulated by your code to produce the same results, as detailed in Table 11.4. Table 11.4 Selected Properties of the PrintPreviewControl Control Property Meaning AutoZoom If true, automatically changes the zoom factor when the control is resized. Columns Number of columns of pages to display. Rows Number of rows of pages to display. StartPage Page number of the first page to display. UseAntiAlias If true, allows antialiasing when displaying the print preview. This provides higher-quality text but takes longer to render. Zoom Zoom factor to use. The PrintDialog Component One more Windows component is the PrintDialog component, which enables a user to control a printer and its properties. You can experiment with this component by modifying the same form to include another Button control named btnPrinter and a PrintDialog component named printDialog1. Add the following code to handle the Click event of the btnPrinter control:: private void btnPrinter_Click(object sender, System.EventArgs e) { // Create a PrinterSettings object and send it to the dialog printDialog1.PrinterSettings = new PrinterSettings(); if(printDialog1.ShowDialog() == DialogResult.OK) { printDocument1.PrinterSettings = printDialog1.PrinterSettings; } } When you click the Printer button, an instance of the PrintDialog component is displayed, as shown in Figure 11.5. The PrintDialog component allows a user to set printer-related settings encapsulated in a PrinterSettings object. The settings are then retrieved and applied to the PrintDocument object through its PrinterSettings property. 262 Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Figure 11.5 The PrintDialog component displaying current printer settings. 263 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Printing . . . . Practice Questions Question 1 You are printing the first page of a two-page document and want to fire the PrintPage event for the second page. How can you do this with the least amount of effort? ❍ A. Set the HasMorePages property to false. ❍ B. Set the HasMorePages property to true. ❍ C. Perform a simple loop, instantiating the PagePrint method for each page in order. ❍ D. Place two PrintDocument components within the application, and link each to the appropriate page. Answer B is correct. By setting the HasMorePages property to true, the PrintDocument component will generate the next page’s output. Answer A is incorrect because setting the HasMorePages property to false would tell the component there are no more pages to print. Answers C and D are incorrect because they involve far more effort and might limit later application expansion to include reports with more than two pages. Question 2 Which events fire once for each page to be printed? (Select all that apply.) ❑ A. BeginPrint ❑ B. QueryPageSettings ❑ C. PrintPage ❑ D. EndPrint Answers B and C are correct. The QueryPageSettings and PrintPage events both fire once for each printed page. Answer A is incorrect because the BeginPrint event fires once before the entire print job. Answer D is incorrect because the EndPrint event fires once after the entire job is done. 264 Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 3 You want to display a list of installed printers on a user’s computer. Which of the following classes would you use to accomplish this? ❍ A. PrintController ❍ B. PrinterSettings ❍ C. PrinterResolution ❍ D. StandardPrintController Answer B is correct. The PrinterSettings class is used to get information about how a document is printed, including the printer that prints the document. The InstalledPrinters static method of this class retrieves the list of all the installed printers. Answers A, C, and D are incorrect because they provide no mechanism of determining the list of installed printers on a machine. Question 4 You need to configure printed output based on data you will acquire from a single SQL query, but based on business rules, you need to group the data into separate pages. In which event should you place the SQL call? ❍ A. BeginPrint ❍ B. QueryPageSettings ❍ C. PrintPage ❍ D. EndPrint Answer A is correct. You should use the BeginPrint event to perform preloading tasks that will be used for the entire print job. Answers B and C are incorrect because the QueryPageSettings and PrintPage events fire once for each page and would generate multiple hits against your SQL server, increasing the network and system load. Answer D is incorrect because the EndPrint event fires only after all pages have been printed. 265 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Printing . . . . Question 5 You want to make sure that a report is always generated in Portrait mode. Which of the following fulfills this requirement? ❍ A. Set the Bounds property of the PageSettings class to true. ❍ B. Set the Portrait property of the PageSettings class to true. ❍ C. Set the Landscape property of the PageSettings class to false. ❍ D. Set the Orientation property of the PageSettings class to Landscape. Answer C is correct. By setting the Landscape property of the PageSettings class to false, the output is forced to Portrait mode. Answer A is incorrect because the Bounds property defines the available space based on the paper orientation rather than the orientation itself. Answers B and D are incorrect because they do not specify valid properties of the PageSettings class. Question 6 Users report that their printouts are not properly formatted because of the mix of fonts used. Which of the following options should you choose to ensure proper formatting of the reports? You decide to calculate the page spacing required for each font using the GetHeight method. Will this allow you to properly determine the number of lines that can fit on a page? ❍ A. Use the Font.GetHeight method. ❍ B. Use the PrintPageEventArgs.MarginBounds property. ❍ C. Use the PrintDocument.PrinterSetting property. ❍ D. Write an event handler for the PrintDocument.QueryPageSettings event. Answer A is correct. By summing by-line values calculated using the GetHeight method to measure font size, it is possible to determine whether a new page is required or whether the line of text will fit in the remaining space. Answers B, C, and D are incorrect because they apply either to a page as a whole or to the printer, but they do not provide any resolution to the problem caused by using different fonts. 266 Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 7 You need to create an event log entry for each print job that details the number of pages in a print job, along with a code that indicates whether any errors occurred during page formatting for any of the pages. Where should you place the code for this requirement? ❍ A. BeginPrint ❍ B. QueryPageSettings ❍ C. PrintPage ❍ D. EndPrint Answer D is correct. An event log entry that includes details spanning an entire print job should be generated within the EndPrint event, which fires after the job is completed. You must add code necessary to handle any errors, setting some type of flag to allow later specification of the error condition in the event log entry. Answer A is incorrect because the BeginPrint event fires before any pages have been printed. Answers B and C are incorrect because the QueryPageSettings and PrintPage events fire once for every page that is generated and would result in multiple event log entries. Question 8 You want to allow your users to check the way the printed output will look before they waste paper printing lengthy reports. They need to be able to vary the zoom for close detail inspection of graphic images. Which elements can be used to support this requirement? (Select all that apply.) ❑ A. PageSetupDialog ❑ B. PrintPreviewDialog ❑ C. PrintPreviewControl ❑ D. PrintDialog Answers B and C are correct. Both the PrintPreviewDialog and PrintPreviewControl elements can be used to support print preview, although the PrintPreviewControl element requires additional code to manage the need for a variable zoom. Answer A is incorrect because the PageSetupDialog component is used to control page settings. Answer D is incorrect because the PrintDialog component is used to control printer settings. 267 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Printing . . . . Question 9 You need to print a document in which each page has different print settings. Which of the following event handlers should you use to ensure that the correct print settings are applied? ❍ A. BeginPrint ❍ B. EndPrint ❍ C. PrintPage ❍ D. QueryPageSettings Answer D is correct. To print each page of a document using different page settings, you handle the QueryPageSettings event of the PrintDocument class. Answers A and B are incorrect because these events apply to the print operation as a whole, not to individual pages. Answer C is incorrect because you need to find the print settings before the PrintPage event is fired. Question 10 You have been tasked with saving paper when executing the many lengthy print jobs that are routinely generated. Which property of the PrinterSettings class should you use to directly support this requirement, assuming that the printer supports all properties? ❍ A. CanDuplex ❍ B. Collate ❍ C. Copies ❍ D. Duplex Answer D is correct. The Duplex property can be used to force printouts on both sides of each page, reducing the number of pages by half. Answer A is incorrect because the CanDuplex property returns a value based on whether the printer supports duplex printing. Answer B is incorrect because collating the output simply involves the manner in which the resulting pages are ordered. Answer C is incorrect because there is no requirement that the number of copies of each report should be modified, so this is not the best answer of those provided. 268 Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Need to Know More? Charles Petzold. Programming Microsoft Windows with C#. Microsoft Press, 2001. Windows Forms Community Site: www.windowsforms.net. Printing with Windows Forms: http://samples.gotdotnet.com/ quickstart/winforms/doc/WinFormsPrinting.aspx. 12 Testing and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ Testing ✓ Bottom-up testing ✓ Top-down testing ✓ Trace class ✓ Debug class ✓ TraceListener class ✓ TraceSwitch class ✓ Tracing ✓ Debugging ✓ Step-by-step execution ✓ Breakpoint Techniques you’ll need to master: ✓ Know different kinds of testing: unit, integration, and regression ✓ Know how to implement tracing in Windows applications using the Trace and Debug classes of System.Diagnostics namespace ✓ Know how to implement trace switches and conditional compilation for your application ✓ Know how to perform step-by-step debugging using the debugging features provided by Visual Studio .NET 270 Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Before an application is deployed to users, it is critical to test the application for errors or unexpected behaviors. This chapter examines the methods used to plan a thorough testing of your application, as well as the classes provided by the .NET Framework for use in testing and debugging an application during its runtime. Application Testing Application testing must be performed to ensure that an application is capable of functioning properly, even if presented with invalid or conflicting data. In addition, it is important to do a simple measure of base functionality within the expected operational environment. Automated alpha-phase testing can be done using code-based agents based on classes within the System.Diagnostics namespace of the .NET Framework. Test users often perform additional human-interaction testing during the beta-testing phase. Remember that testing can prove only that specific bugs exist. Testing cannot prove that an application is entirely free of errors—it can determine only that no known bugs remain. Testing may be performed during different stages of application development, such as when a module is developed, and when several modules are integrated together to create a system. Testing is also crucial after performing a correction or update, to ensure that the changes have not introduced new errors or caused unexpected results. Stubs are often used during unit-level testing of individual modules and classes. A stub is a replacement code segment that automatically returns the correct response when called by the module being tested, avoiding extensive processing and data access overhead generated by calling the actual code (assuming that the code even exists). When multiple developers are working on separate portions of an application, stubs might be mandated during the independent development of various portions of the application. When planning for a test, it is important to determine which software segment or functionality will be tested, what approach will be used during testing, what constitutes a pass or failure within the testing boundaries, and who the responsible individuals will be during testing. Reporting and documentation of testing, including both successful and failed results, are an important part of the complete documentation for your application. 271 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Testing . . . . and . . Debugging . . . . . . Testing should include a measure of three key elements of operation: ➤ Correctness—When given a known set of valid data, the application should produce the expected result. This element tests whether an application is functioning correctly. ➤ Reliability—When provided valid data repeatedly, the application should produce the expected result for each iteration. This element tests whether an application can function in repeated use, ensuring that values are not held over from one iteration to the next. ➤ Robustness—When provided with invalid data, the application should be capable of preventing invalid input or raising an error during improper operation. This element ensures that the application can cope with invalid data. The following sections discuss three forms of testing: unit testing, integration testing, and regression testing. Unit Testing Unit testing involves testing a single code module or class. This level of testing ensures that each module can perform properly alone, allowing testing to be conducted before other code segments have been created. This approach also limits the scope of testing to a smaller segment of code and makes it possible to test modules of very resource-intensive applications without heavily loading the development server. Integration Testing Integration testing ensures that all modules work with one another within an application. Integration testing is performed in several ways, including these: ➤ Bottom-up—This approach begins at the unit level and progresses to increasingly more complex levels of integration. Bottom-up testing is more useful when the development team is well-experienced with the technology; the product specifications are well-defined and only limited risk is involved. ➤ Top-down—This approach involves testing the full functionality of the application, using stubs for modules still under development. Focused testing can then be performed on smaller subsystems and code modules to eliminate any identified errors. Top-down testing is more useful when the development team is inexperienced with the technology; product specifications are not well-defined and high risks are involved. 272 Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ Umbrella—This approach involves testing of the user-interface element of the application, such as reports, screen, and so on, prior to testing the program components. This approach is more useful when your application involves extensive user interaction. Regression Testing Regression testing is performed each time a change is made to the application, to ensure that the modification has not introduced new errors into an application and to ensure that the change provides the desired result. When testing international applications, make sure that you are using either Unicode or the proper code page for each language, and that you test the application using a set of localization settings. Tracing Tracing refers to instrumenting your application by writing debugging statements in your code. These debugging statements are not removed from your application when it is deployed to production servers; instead, the debugging statement remains functional allowing you to trace unexpected paths of execution in your program. The .NET Framework includes two classes for tracing within the System.Diagnostics namespace: Trace and Debug. These classes derive from the same abstract class and share the same Listeners collection, differing only in the symbol set used for each. These classes are used to diagnose conditions within an application while it is running. When you compile an application in the default (Debug) configuration, both the DEBUG and TRACE symbol sets are included. When compiling an application in Release mode, only the TRACE symbol is included. Table 12.1 details some of the most useful members of the Trace and Debug classes. Table 12.1 Important Members of the Trace and Debug Classes Member Type Description Assert Method Displays a message if the specified condition is not met AutoFlush Property Returns true if the Flush method should be called on listener objects after each write Close Method Flushes the output buffer and closes the listener objects (continued) 273 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Testing . . . . and . . Debugging . . . . . . Table 12.1 Important Members of the Trace and Debug Classes (continued) Member Type Description Fail Method Returns an error message Flush Method Flushes the output buffer’s data to the listener objects Indent Method Increments the current IndentLevel by one IndentLevel Property Gives the current indent level IndentSize Property Gives the number of spaces used in an indent Listeners Property Specifies the collection of objects monitoring trace output, shared by both Trace and Debug Unindent Method Decrements the current IndentLevel by one Write Method Writes the specified data to the listeners WriteIf Method Writes the specified data to the listeners if the specified condition is true WriteLine Method Is identical to the Write method, but adds a newline character WriteLineIf Method Is identical to the WriteIf method, but adds a newline character Trace Listeners Trace listeners are classes derived from the TraceListener class that handle the reporting of data provided by the Trace and Debug classes. One or more listener objects can be placed within the Listeners collection shared by the Trace and Debug classes. Several types of listener objects are available within the .NET Framework, including these: ➤ DefaultTraceListener class—This is the default listener object automatical- ly added to the Listeners collection. Objects of this class send their output to the Output window. ➤ TextWriterTraceListener class—This listener class can be used to output messages to any object deriving from the Stream class, including external files and the console. ➤ EventLogTraceListener class—This listener class is used to output mes- sages to the Windows Event Log. You can define custom listeners by inheriting from the TraceListener base class and overriding its methods with your customized methods. When you do so, at a minimum, you must implement the Write and WriteLine methods. Additionally, you can implement the Fail, Close, and Flush methods. 274 Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Trace Switches When your application is deployed, you might want to include the capability to turn application tracing off and on when necessary. This can be accomplished by including a TraceSwitch object or a BooleanSwitch object. These classes derive from the Switch class and can be adjusted by including an XML element to set the proper value for the switch object within an application’s XML configuration file. The BooleanSwitch value is used for a simple trace-on/trace-off selection, where any nonzero value represents a trace-on condition. If you want greater control over tracing, you can use the TraceSwitch class to adjust the level of tracing based on the enumerated values of the TraceLevel class, as detailed in Table 12.2. Table 12.2 The TraceLevel Enumeration Value Integer Type of Trace Messaging Off 0 None Error 1 Adds error messages Warning 2 Adds warning and error messages Info 3 Adds informational, warning, and error messages Verbose 4 Adds verbose, informational, warning, and error messages Table 12.3 details some of the most important properties of the TraceSwitch class. Table 12.3 Important Properties of the TraceSwitch Class Property Description Description Description of the switch object. DisplayName The name of the switch class instance. This is used in the XML config file to identify the object. Level The level of tracing, using one of the enumerated TraceLevel values detailed previously. TraceError Returns true if Level is set to 1, 2, 3, or 4 (Error, Warning, Info, or Verbose). TraceInfo Returns true if Level is set to 3 or 4 (Info or Verbose). TraceVerbose Returns true if Level is set to 4 (Verbose). TraceWarning Returns true if Level is set to 2, 3, or 4 (Warning, Info, or Verbose). 275 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Testing . . . . and . . Debugging . . . . . . Conditional Compilation During compilation, you might want to vary the elements that are compiled using one of the preprocessing directives. These directives enable you to skip or replace segments of code during compilation, report warnings, or mark regions of the code. These directives are evaluated before compilation of the underlying application code. Table 12.4 details the preprocessing directives available in Visual C# .NET. Table 12.4 Visual C# .NET Preprocessing Directives Directives Description #if, #else, #elif, and #endif Used to evaluate a condition and then vary which code elements are compiled based on that evaluation. #define and #undef Used to define or undefine symbols in the code. #warning and #error Used to explicitly generate error or warning messages. #line Used to alter the line numbers and source file filenames reported by the compiler in warning and error messages. #region and #endregion Used to mark sections of code that can be easily expanded or collapsed to make code easier to read within the Visual Studio .NET Integrated Development Environment (IDE). You can also mark methods to enable them to be conditionally compiled if a symbol (DEBUG, TRACE, or a custom symbol) is specified in their Conditional attribute. Only void methods (that do not return any value) can make use of the Conditional attribute. The following method includes a Conditional attribute that defines the DEBUG symbol: [Conditional(“DEBUG”)] public void InitDebugMode() { lblDebug.Text = “Debug Mode”; lblDebug.Visible = true; } If the application is compiled in Debug mode (where the DEBUG symbol is defined), the Label control displays the message “Debug Mode” when the InitDebugMode method is invoked. 276 Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Debugging When compiling code in the default Debug mode, the compiler includes several options that can assist during the process of debugging an application, including stepping through the code, using code breakpoints, doing conditional debugging when an exception is thrown, performing process monitoring, and analyzing program state using the .NET debugging tools. The .NET Framework supports transparent debugging of applications that use multiple languages. If some modules of your application are written in Visual C# .NET while others are written in Visual Basic .NET, the debugger can step between languages transparently. Stepping Through Code During Execution One method used in debugging an application is the step-by-step execution of its code within the debugger. If the application terminates unexpectedly, you will have a good idea of where the code caused problems in the application. You might also check for variable values and other ongoing changes the code is making during its execution so that you can determine the effect of each step. Visual Studio .NET provides three options for step-by-step execution of an application. These modes are selectable using keyboard shortcuts, as detailed in Table 12.5. Table 12.5 Options for Step-by-Step Application Execution Debug Menu Keyboard Shortcut Function Step Into F11 This option allows step-by-step execution of program code. If a method is called, the debugger enters the code of the method and steps through each line one at a time as well. Step Over F10 This option also allows step-by-step execution of program code. If a method is called, it is executed completely in one step and then the step-by-step process continues on the next line after the method call. Step Out Shift+F11 This option is used inside a method call to execute the rest of the method without stepping. You resume step execution mode when control returns to the calling method. 277 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Testing . . . . and . . Debugging . . . . . . Using Breakpoints A breakpoint causes code execution to pause when encountered. If you place a breakpoint in your code, the application will pause when it reaches the breakpoint, enabling you to do the following: ➤ Examine the current program state of the application ➤ Enter step-by-step mode ➤ Allow program execution to continue Within the Visual Studio .NET IDE, you can add a breakpoint by rightclicking the beginning of a line of code and selecting New Breakpoint from the options provided. The New Breakpoint dialog box includes options to create a breakpoint within a file, function, and address within the code, or when a specific condition is met. The New Breakpoint dialog box contains Condition and Hit Count buttons that enable you to create conditional breakpoints. The Breakpoint Condition dialog box allows you to break the program execution based on the runtime value of an expression. The Breakpoint Hit Count dialog box enables you to break the program execution only if the specified breakpoint has been hit a given number of times. These dialog boxes can be especially helpful if you have a breakpoint and want to step execute the program during specific circumstances. You can right-click an existing breakpoint to remove or disable the breakpoint’s operation. Removing a breakpoint also removes any information that you have associated with the breakpoint using the Breakpoints window. Disabling a breakpoint simply causes the debugger to ignore a breakpoint and continue normally. You can open the Breakpoints window (shown in Figure 12.1) by selecting Debug, Windows, Breakpoints from the header. Figure 12.1 The Breakpoints window showing a breakpoint set on the 32nd line of code within the Calculator application. 278 Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Debugging When an Exception Is Thrown It is possible to configure the debugger to respond when a particular exception is thrown, using the Exceptions dialog box shown in Figure 12.2. Here, you can configure the debugger to continue or to break execution when an exception is thrown or when an unhandled exception occurs, alerting you to the presence of an unhandled exception within your code. Figure 12.2 The Exceptions dialog box, which enables the developer to decide whether to break into the debugger when the exception is thrown or when it is not handled. Debugging a Running Process Visual Studio .NET also allows you to debug processes that are running outside the Visual Studio .NET debugging environment. You can access external processes from Visual Studio .NET by running both on a local or remote computer through the Processes dialog box (by selecting Tools, Debug Processes), as shown in Figure 12.3. By selecting the target system and the running process within the Processes dialog box and clicking the Attach button, you can attach the process to the Visual Studio .NET Debugger. Note that, to debug a running process on the remote machine, you should ensure that the remote system is running the Machine Debug Manager (mdm.exe) service. This service can be installed using Visual Studio .NET or through the Remote Components Setup. Mdm.exe provides remote debugging support. You should also ensure that you are a member of the Debugger Users group on the remote computer. 279 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Testing . . . . and . . Debugging . . . . . . Figure 12.3 The Processes dialog box allows you to attach a debugger to a process that is under execution. The local computer and the remote computer must be members of a trusted domain to perform remote debugging. If you want to debug a DLL file rather than an EXE file under execution, you must create a simple application that invokes the DLL and then attach the debugger to the executing application’s process. Analyzing Program State During the debugging process, you will want to be able to evaluate many conditions and values that changed while the program was under execution. The Visual Studio .NET development environment provides several debugging windows that display valuable information on the state of the program (which can be selected using the Debug, Windows menu option): ➤ Autos window—This window includes information on the variables with- in the current and previous statements. ➤ Call Stack window—This window displays the path through which pro- gram execution reached the current point within the code. ➤ Immediate window—This window can be used to invoke real-time evalua- tion of variables and functions within the Command window. ➤ Locals window—This window shows variables that have their scope local to the current method being executed. 280 Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ This window—This window shows all of the members associated with the current object. ➤ Watch window—Each Watch window can be used to monitor the value of a particular variable or an expression. 281 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Testing . . . . and . . Debugging . . . . . . Practice Questions Question 1 You are developing an application using Visual Studio .NET on a team of 15 developers. Your team has performed extensive testing of the application and eliminated all known errors. You have also configured your application to break on any unhandled exceptions. Which of the following statements correctly defines the state of your application? ❍ A. The application is bug free. ❍ B. The application has no known errors and is very reliable. ❍ C. The application has no known errors and is very robust. ❍ D. The application has no known errors and will stop on an unhandled exception. Answer D is correct. You have ensured that all known errors have been corrected. Answer A is incorrect because you cannot prove through testing that there are no other errors: Your testing process might not have encompassed all possible types of error that a user can create. Answers B and C are not the most correct answers in this case. If your application repeatedly functions as expected, it might be considered to have fulfilled the reliability requirement for testing, and its capability to handle invalid data or incorrect actions would define its robustness. Because you do not know anything about the specific testing methods used, you cannot be certain of the reliability or robustness of the application. Question 2 Which of the following options defines the TRACE symbol? ❍ A. Default Release configuration. ❍ B. Default Debug configuration. ❍ C. Default Release configuration and the Default Debug configuration. ❍ D. Neither the default Release configuration nor the default Debug configuration. Answers C is correct. The TRACE symbol is defined in both the default Debug and default Release configurations. Answer A and B are incorrect because they both are incomplete answers. Answer D is simply incorrect. 282 Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 3 You have the following segment of code in your program: EventLogTraceListener traceListener = new EventLogTraceListener(“TraceLog”); Trace.Listeners.Add(traceListener); Trace.WriteLine(“Sample Message”); Debug.WriteLine(“Sample Message”); When you debug the program through Visual Studio .NET, how many times would the message “Sample Message” be written to the trace log? ❍ A. 1 ❍ B. 2 ❍ C. 3 ❍ D. 4 Answer B is correct. When you add a listener object to the Trace.Listeners collection, you also add a listener object to the Debug.Listeners collection because Trace and Debug classes share their Listeners collection. Since the message is written twice and one listener object is attached to the Listeners collection, the message will be written twice. Question 4 You want to control the tracing and debug output of a Windows application without needing to recompile your code. Which of the following classes would enable you to do this? (Select all that apply.) ❑ A. Debug ❑ B. Trace ❑ C. TraceListener ❑ D. TraceSwitch ❑ E. BooleanSwitch Answers D and E are correct. TraceSwitch and BooleanSwitch classes can be used to control the tracing and debugging output without needing to recompile the code. You can store the level of tracing required in XML application configuration files, which can later be edited to reflect new tracing requirements without needing to recompile code. Answers A and B are incorrect because Trace and Debug classes are used to write tracing output. Answer C 283 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Testing . . . . and . . Debugging . . . . . . is incorrect because the TraceListener object is used to listen to the messages generated by the Trace and Debug classes. Question 5 Which member of the Trace and Debug classes displays message when a specified condition is not met? ❍ A. Assert ❍ B. Write ❍ C. Fail ❍ D. WriteIf Answer A is correct. The Assert method displays the message, if the specified condition is not met. Answer B is incorrect because the Write method is used to display the message without checking for any condition. Answer C is incorrect because the Fail method is used to display the error message without checking for any condition. Answer D is incorrect because the WriteIf method displays the message, if the specified condition is met. Question 6 Which object type should be used to write an output message to a flat file? ❍ A. DefaultTraceListener class ❍ B. TextWriterTraceListener class ❍ C. EventLogTraceListener class ❍ D. TraceSwitch class ❍ E. BooleanSwitch class Answers B is correct. The TextWriterTraceListener class is used to output messages to objects deriving from the Stream class, including external flat files. Answer A is incorrect because the DefaultTraceListener class is used to write messages to the Output window. The EventLogTraceListener class is used to write output to the Windows Event Log, making answer C incorrect as well. Answer D and E are incorrect because TraceSwitch and BooleanSwitch classes are used to control the level of tracing to be enabled; they do not listen to the messages generated by the Trace and Debug classes. 284 Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 7 If you selected a trace level of 3, which types of trace messages will be returned? (Select all that apply.) ❑ A. Error ❑ B. Informational ❑ C. Verbose ❑ D. Warning Answers A, B, and D are correct. Trace level 3 (Info) returns informational, warning, and error messages. To return verbose messages, the trace level must be set to level 4 (Verbose), making answer C incorrect here. Question 8 Which property of the TraceSwitch class will return a true value if the trace level is set to 1? (Select the best answer.) ❍ A. TraceError property ❍ B. TraceInfo property ❍ C. TraceVerbose property ❍ D. TraceWarning property Answer A is correct. The TraceError property returns true if the Level property is anything other than 0. Answers B and C are incorrect because the TraceInfo property returns true only if the trace level is 3 or 4; the TraceVerbose property returns a true value for a level of 4 only. The TraceWarning property returns a true value only when the Level property is greater than 1, making answer D incorrect as well. 285 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Testing . . . . and . . Debugging . . . . . . Question 9 You are trying to debug a Windows application running on a remote machine using Visual Studio .NET installed on your local machine. The local machine and remote machine have a two-way trust relationship between their domains. When you attempt to debug the application, you get a DCOM configuration error. Which one of the following steps should you take to resolve this problem? ❍ A. Add your account to the Powered Users group on the local computer. ❍ B. Add your account to the Powered Users group on the remote computer. ❍ C. Add your account to the Debugger Users group on the local computer. ❍ D. Add your account to the Debugger Users group on the remote computer. Answer D is correct. You should be a member of the Debugger Users group on the remote computer in order to remotely debug a process running on that computer. Answers A and C are incorrect because being a member of any group in the local computer does not provide any privileges to debug a process on a remote computer. Answer B is not correct because you should be a member of the Debugger Users group rather than the Powered Users group. Question 10 Which of the following windows provides the easiest display of the variables used in the previous and current statement? ❍ A. Autos ❍ B. Call Stack ❍ C. Immediate ❍ D. Locals ❍ E. Watch Answer A is correct. The Autos window provides an automated display of the variables in the current and previous statements. Answer B is incorrect because the Call Stack window is used to display the path of execution used to get to the current location in the application’s execution. Answer C is incorrect because the Immediate window requires you to specify variables and expressions at every stage of execution to monitor their values. Answer D is incorrect because the Locals window shows all the variables that are local to the current execution context. Answer E is incorrect because the Watch window requires you to specify the variables and expressions in order to evaluate them. 286 Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Need to Know More? Kalani, Amit. MCAD/MCSD Training Guide: Developing and Implementing Windows-Based Applications with Microsoft Visual C# .NET and Microsoft Visual Studio .NET, Exam 70-316. Que Certification, 2003. Richard Grimes. Developing Applications with Visual Studio .NET. Addison-Wesley, 2002. Production Debugging for .NET Framework Applications: http://msdn.microsoft.com/library/en-us/dnbda/html/DBGrm.asp. Visual Studio .NET, Debugging .NET Applications, and More: http://msdn.microsoft.com/msdnmag/issues/02/04/Basics. The .NET Show: Debugging with Visual Studio .NET: http://msdn.microsoft.com/theshow/Episode022. 13 Deploying a Windows Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ XCOPY ✓ Cabinet (.cab) files ✓ Merge Module ✓ Bootstrapper ✓ Custom actions ✓ Delay signing ✓ Authenticode signature ✓ URL remoting ✓ Logo programs Techniques you’ll need to master: ✓ Experiment with using setup projects and merge module projects to deploy Windows-based applications. Understand when you should choose to create a setup project versus a merge module project. ✓ Work with the different editors that are available in setup and merge module projects, and thoroughly understand the purpose of each of these editors. ✓ Understand how digital signing is used when creating a strong name for an assembly. ✓ Experiment with placing assemblies in the Global Assembly Cache. 288 Chapter 13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . After creating and testing your application, you must provide the completed product to its users. This chapter focuses on the process involved in deploying simple and complex applications using XCOPY, the Windows Installer, and zero-touch Web-based deployment methods. We also briefly examine the use of shared assemblies and the application requirements for certification in the Microsoft Windows Logo program. Deployment Tools The Visual Studio .NET development platform has the new Setup and Deployment projects category, which includes useful templates for creating installation packages for many types of applications. These packages are based on the Microsoft Windows Installer technology, which handles many of the setup and configuration details automatically. When you decide to deploy a package, its complexity and installation requirements will determine the best tool for deployment. You might be able to deploy a simple .NET application that uses managed code and private assemblies by using nothing more than the XCOPY utility to duplicate the application’s files to the desired destination. This type of installation is insufficient when an application involves key management, user registration, feature selection, relative path selection, the Global Assembly Cache (GAC) manipulation, or the creation of shortcuts, databases, or a branded interface. To support more complex installation requirements, you can use the Windows Installer technology. Installer packages (.msi) can create shortcuts, set Registry entries, add Start menu items, execute custom scripts, and allow by-feature and on-demand installations. In addition, the Windows Installer provides the capability to roll back an installation process, uninstall an application, and repair a component or an application. Visual Studio .NET ships with version 2.0 of the Installer, which is compatible with Windows NT 4 (Service Pack 6), Windows ME, Windows 2000, and Windows XP, Windows 2003 Server. Microsoft provides a downloadable earlier version that can be used on Windows NT 4.0, Windows 95, and Windows 98. Deploying Your Application Visual Studio .NET includes templates and setup wizards for several forms of application deployment, including these: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deploying . . . . . .a .Windows . . . . . Application . . . . . . ➤ Cab Projects—Used to package ActiveX components into redistributable cabinet (.cab) files for Internet download ➤ Merge Module Projects—Used to create redistributable packages, includ- ing shared components and assemblies ➤ Setup Projects—Used to create installation packages for Windows appli- cations to be installed on client computer systems ➤ Web Setup Projects—Used to create installation packages for Web applica- tions to be installed on a Web server Visual Studio .NET also has a Setup Wizard that helps you interactively create these deployment projects. This chapter mainly discusses the Setup Project, which is used to deploy Windows-based applications. Setup Projects After you have created an application and compiled it using the Release option, you can wrap your application into a setup project using Visual Studio .NET. You might want to include additional files, such as a license agreement or a ReadMe file, to provide installation instructions or information on the purpose and use of the application. When all of these files have been created, you can create a new Setup project by following these steps: 1. Open a Visual Studio .NET and open the Windows application for which you want to create a setup project. 2. Add a project to the solution, select Setup and Deployment projects from the Project Types tree, and then select Setup Wizard from the list of templates on the right. Enter a name and location for the project, and then click OK. 3. The Setup Wizard appears. The first page of the wizard is the welcome screen. Click Next. 4. The second page of the wizard is the Choose a Project Type screen. Choose Create a Setup for a Windows Application from the first group of options to create a setup project for Windows applications, as shown in Figure 13.1. Click Next. 5. The third page of the wizard is the Choose Project Outputs to Include screen. Select Primary Output from the Windows application (in this example, the name of the application is MyProject), as shown in Figure 13.2. Click Next. 289 290 Chapter 13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Figure 13.1 The Choose a Project Type screen in the Setup Wizard prompts the user to select the project type. Figure 13.2 The Choose Project Outputs to Include screen in the Setup Wizard prompts the user to select the project output that will be deployed by the installer. 6. The fourth page of the wizard is the Choose Files to Include screen. You can use this screen to include any additional files in the setup project. Click Next. 7. The final page of the wizard is the Project Summary screen. Click Finish to create the project. 8. Select the project in the Solution Explorer and provide meaningful information for Manufacturer, ProductName, Title, and other information as desired using the Properties window for the project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deploying . . . . . .a .Windows . . . . . Application . . . . . . 9. Build the setup project to create the setup package. When you are done, open Windows Explorer and navigate to the Release folder inside the project folder. You will find the Setup.exe file, along with the installer package (.msi), initialization files (.ini), and any additional executables (.exe) needed. On a machine with the .NET Framework installed, you can install your new application by double-clicking the Setup.exe file. This enables you to specify the destination location during installation.If you later want to uninstall this application, you can do so through Start, Control Panel, Add/Remove Programs; simply select the application from the list of installed packages and select Remove. Easy removability or reinstallation to replace damaged component files is one of the many benefits of using the Windows Installer to deploy your package. Deployment of your application requires the .NET Framework, which you can install from a source such as the Windows Update site. If you want to include a bootstrapper program that will automatically install the .NET Framework if it is not already present, you can download a sample from http://msdn.microsoft.com/downloads/ sample.asp?url=/msdn-files/027/001/830/msdncompositedoc.xml. Include the bootstrap information within your initialization (.ini) file to direct the setup file to the .NET Framework setup files. Before deployment, you can modify the configuration settings for your package using the Property Pages dialog box for your project within the Solution Explorer, as shown in Figure 13.3. Figure 13.3 The configuration settings page for a setup project. 291 292 Chapter 13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Five primary configuration properties are presented here: ➤ Output filename—Used to specify the name of the generated installer (.msi) package. ➤ Package files—Used to specify whether the files should be packaged as loose, uncompressed files, within the setup file or as one or more cabinet (.cab) files. If multiple cabinet files are allowed, you can specify the maximum size for each, to reduce the size of each file that must be downloaded by a user installing the package. ➤ Bootstrapper—Used to specify whether the installation package should include the capability to install the Windows Installer utility on the client system if it is not already present, to allow installation of your application. ➤ Compression—Used to specify whether your files should be compressed for either size or speed of installation. ➤ Authenticode signature—Used to specify the file containing an Authenticode digital signature and private key file that will be used during installation. Customizing Setup Projects You can also customize your setup project using the Visual Studio .NET IDE editors. Visual Studio .NET provides different types of editors to customize various aspects of the installation process: ➤ File System Editor—Used to specify the file system configuration that will be used during installation. Within this editor, placeholders such as the user’s Startup folder are provided to reflect a mapping to the appropriate location for the user performing the installation. Some of the available special folders include the Application folder, the Common Files folder, the Program Files folder, the user’s desktop, and the System folder. This editor can be used to configure shortcuts to your application that automatically are installed along with the application. ➤ Registry Editor—Used to specify Registry keys, subkeys, and values that will be added to the Registry of the user’s system during installation. ➤ File Types Editor—Used to specify file type associations, allowing your application to automatically open a file if its type (based on the file extension) matches the associated value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deploying . . . . . .a .Windows . . . . . Application . . . . . . ➤ User Interface Editor—Used to customize the installation interface to include dialog boxes within the start, progress, and end stages of installation. This editor can be used to include rich-text (.rtf) files such as your license agreement and readme files mentioned earlier, so the installation will continue only after the user acknowledges reading the details provided. ➤ Custom Actions Editor—Used to allow the specification of compiled .dll or .exe files to be executed during the install, commit, rollback, or uninstall phases of installation. These might be used to configure a database for your application or any other type of executable action that is not directly a part of the installation itself. If a custom action fails, the entire installation is rolled back, leaving the target machine to its original state. ➤ Launch Conditions Editor—Used to set conditions that must be met before an installation can begin, such as whether the .NET Framework is already installed or whether a particular Registry key is present. If the condition is not met, installation terminates. You can view editors by right-clicking the project in the Solution Explorer and then selecting View and the desired editor. The Condition property is present on Editor elements such as folders, files, Registry keys, custom actions, and launch conditions. The Condition property consists of a valid conditional statement in the form of a string that evaluates to either true or false. If this property does not evaluates to true, the action is not enacted. Shared Assemblies Chapter 4, “Components and .NET Assemblies,” covered the creation of assemblies, noting that a shared assembly is stored in the Global Assembly Cache (GAC) so that it can be shared by several applications. Because the GAC allows multiple versions of the same assembly to be present at once, the assembly must be designated using a strong name; this includes the assembly’s text name (the name of the file without its extension), the version number (major, minor, build, and revision), culture information (neutral or localized), and a unique digital signature. The following sections discuss how to digitally sign an assembly and how to add shared assemblies to the GAC. 293 294 Chapter 13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Signing the Assembly The digital signature is created using a public key encryption process that involves first creating a public key/private key pair using the Strong Name utility (sn.exe), calculating a hash of the assembly, and then encrypting the hash using the private key. The encrypted hash value and the public key are accessed within the assembly’s manifest by the CLR and are used to verify that the assembly remains uncorrupted and unique. When signing multifile assemblies, you need to sign only the assembly manifest because it contains hash values for the included files. When the signed manifest is verified as unchanged, it is easy to then evaluate the included files to ensure that they are also correct. Immediate Signing You can create a public key/private key pair using the Strong Name command-line utility provided within the .NET Framework Software Development Kit (SDK) using this format: sn –k MyKeys.snk You should then add this file to your component project and use the AssemblyVersion and AssemblyKeyFile attributes in the AssemblyInfo.cs file to specify the version number and keyfile (.snk) to be used when signing this assembly. The settings will look something like this: [assembly: AssemblyVersion(“1.0.*.*”)] [assembly: AssemblyKeyFile(@”<Path to Keyfile>\MyKeys.snk”)] When you rebuild the component, its digital signature is created to provide a unique strong name. Using asterisks (*) for the build and revision number allows the compiler to update those values automatically each time you rebuild the component. Delay Signing It is also possible to sign an assembly using only its public key so that it can later be uniquely signed using a more secure private key. This eliminates the need to provide both public and private keys to all developers. You can extract just the public key from your keyfile using this line: sn.exe –p MyKeys.snk MyPubKey.snk When using this file to sign your assembly, you must specify the use of a delay sign, as shown here: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deploying . . . . . .a .Windows . . . . . Application . . . . . . [assembly: AssemblyVersion(“1.0.*.*”)] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyKeyFile(@”<Path to Keyfile>\MyPubKey.snk”)] After development has been completed, you can re-sign the final component using the following private key: sn.exe –R MyComponent.dll MyKeys.snk Authenticode Signing An assembly signed with a strong name does not automatically assert a company’s identity, such as its name. For that purpose, you can use an Authenticode signature, in which case the company’s identity is asserted by a third-party certification authority (such as Verisign or Thawte). You can use the File Signing tool (signcode.exe) to attach an Authenticode signature to the assembly. An important thing to know is the order of commands when signing an assembly using both sn.exe and signcode.exe. You must sign your assembly with the Strong Name tool (sn.exe) before you sign it with the File Signing tool (signcode.exe). Adding an Assembly to the GAC When you have associated a strong name with your new assembly, you can add it to the GAC in several ways: ➤ Windows Installer—You can create a Merge Module (.msm) project with- in Visual Studio .NET, which then is added to your Setup project for the application that will consume the shared assembly. The Windows Installer then adds the shared assembly to the installation host’s GAC during installation. ➤ Windows Explorer—During installation of the .NET Framework, the Assembly Cache Viewer Shell Extension (shfusion.dll) is installed. This component allows the addition of new assemblies into the GAC by simply navigating to the assembly cache (%systemroot%\WINNT\ assembly or %systemroot%\Windows\assembly) and then dragging and dropping the component (.dll) file into this folder. ➤ Microsoft .NET Framework Configuration tool—You can use the Add an Assembly option within the .NET Framework Configuration tool to add your component to the GAC. This utility is found in the Administrative Tools section of the Windows Control Panel. 295 296 Chapter 13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ Global Assembly Cache Tool (GacUtil.exe)—This command-line utility can be used to add or remove an assembly from the GAC. The utility accepts switches to install (/i), list (/l), or uninstall (/u) assemblies within the GAC. Creating and Deploying the Installation Components Many of your components will make use of additional resources, such as performance counters, event logs, or databases. When you deploy your application, it is important that these additional resources are included in the final installation component. This is accomplished by including an instance of the Installer class in your setup project. The Installer class derives from the System.Configuration.Install.Installer class and includes the following methods: ➤ Commit method—Use this method to write the code that needs to be exe- cuted after successful installation. ➤ Install method—Use this method to write the code that needs to be exe- cuted during the application’s installation. ➤ Rollback method—Use this method to write the code that needs to be exe- cuted when the Install method fails to complete. This method is used to undo any changes enacted by the Install method before its failure. ➤ Uninstall method—Use this method to write the code that needs to be executed when an installed application is selected for uninstallation using the Add/Remove Programs Wizard. When you choose Add Installer within the properties of a class, a new instance of the ProjectInstaller class is added to your project. This object maintains a collection of Installer objects required for the instance to install the component within its Installers property. You can also create a custom class that inherits from the base Installer class to implement your own code and overload the methods of the base class. Within the Setup project, you can use the Custom Actions Editor to add the primary output from the Installer component. This action adds the necessary installation code to the Installer methods of the project. When you install . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deploying . . . . . .a .Windows . . . . . Application . . . . . . this component, the necessary setup configuration is enacted on the installation host, provided that you added the following to your class before compilation: [RunInstaller(true)] You can also use the Installer tool (InstallUtil.exe) command-line utility to install an assembly that includes additional component resources, as shown here: InstallUtil.exe MyComponent.dll InstallUtil.exe MyComponent.dll AnotherComponent.dll This utility can also be used to uninstall a component as well, as shown here: InstallUtil.exe /u MyComponent.dll If you are installing components from multiple assemblies by using the installutil.exe command and any assembly fails to install, installutil.exe rolls back the installations of all other assemblies. However, the process of uninstallation is not transactional. URL Remoting The .NET Framework includes a zero-touch deployment model that allows the installation of an application simply by navigating to the proper URL for the application’s executable (.exe) file within Internet Explorer. The Web server does not need to have the .NET Framework for this to function—in fact, it does not even need to be a Microsoft Web server. The local system’s .NET Framework handles the installation and execution of the application using a zone-based security model. Downloaded assemblies are maintained in a download cache, which is unique for each user and for each download location from which the user has remoted an application. The security model used is based on the zone from which the application is executed, which can be one of the following: ➤ My_Computer_Zone—This zone includes local file and URL paths on the same system. By default, this zone has the FullTrust permission. ➤ LocalIntranet_Zone—This zone includes URLs accessing systems located on the same network. By default, this zone has the LocalIntranet permission. ➤ Internet_Zone—This zone includes all addresses outside the local net- work. By default, this zone has its permissions set to None if the .NET Framework Service Pack 1 (SP-1) has been installed; otherwise, it has the Internet permission. 297 298 Chapter 13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ Trusted Sites Zone—This zone includes Web sites that you trust to not damage your computer or data. By default, this zone has the lowest security permission, and most of the code originating from this zone will be capable of executing. ➤ Restricted Sites Zone—This zone includes Web sites that could potentially damage your computer or data. By default, this zone has the highest security permission and disallows the code originating from this zone to execute. You can modify the security zone settings using the Microsoft .NET Framework Configuration tool located in the Administrative Tools section of the Windows Control Panel. In the Microsoft .NET Framework Configuration tool, select the Runtime Security Policy, Machine, Code Groups, All_Code, My_Computer_Zone nodes to modify or view the security settings at the machine level. You can also adjust the runtime security policy for a particular assembly within the Runtime Security Policy folder. When you configure the Runtime Security settings for an assembly, you have the option to configure access for only the logged-in user or for all users on the machine. Remember that if you relax the security for a zone, such as providing FullTrust to the Internet_Zone, you might allow undesired components to run on your system. Deployment Considerations Many different methods exist for deployment of your application, including these: ➤ Removable media—This deployment form makes use of removable stor- age such as floppy disks, CD-ROMs, ZIP disks, or even small solid-state storage devices. This is suitable when a user does not have an Internet connection, when the deployable application is so large that file transfers would not be reasonable, or when the tightest security is required for data contained within the application. By configuring the Setup project to use cabinet (.cab) files, you can specify a maximum size for each to allow the application to fit within the capacity of the media type used. The Setup.exe and Installer package (.msi) should be placed on the first disk in a series. ➤ Network download—This deployment makes use of file shares to allow remote users to access and download an application, generally from a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deploying . . . . . .a .Windows . . . . . Application . . . . . . read-only file share with access security limited by group membership. In this scenario, you can configure the Setup project to create a single setup file for the application, to simplify download for your users. ➤ Administrative installation—This deployment method involves installing the Windows Installer package to a network file share using the MSIEXEC command with the /a switch (example: MSIEXEC /a MyApp.msi). Users with access to this image within their workgroup can then install and run the application, accessing source files over the network. ➤ Web-based distribution—It is possible to use the Web to distribute an application’s setup files. This method does not require a reproduction and distribution method, as with removable media. In this deployment method, you can allow the Setup project to generate the Installer package and multiple cabinet files so that the application can download its files as needed during installation. Windows Logo Program Requirements To reflect the degree to which a new application conforms to the guidelines for Windows development, Microsoft makes available several forms of logo certification. Products branded with a logo must meet at least the basic requirements of each program to be certified. Users thus know to what degree the application is considered compatible with their operating system. Currently, you should be aware of three types of logo programs: ➤ Certified for Windows—This logo program ensures that an application meets the technical requirements for the Application Specifications for Windows 2000, detailed at www.microsoft.com/windowsserver2003/ partners/isvscfw.mspx. This site also includes prerelease guidelines for Windows Server 2003 program requirements. ➤ Designed for Microsoft Windows XP—This logo program ensures that an application meets the technical requirements for Designed for Microsoft Windows XP Application Specifications, detailed at www.microsoft.com/winlogo. ➤ .NET Connected—This logo program ensures that applications conform to varying levels of application specifications within the .NET and XML Web Service Application Specifications. Details of this program can be found at www.microsoft.com/net/logo. 299 300 Chapter 13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Questions Question 1 If you want to package a shared assembly for distribution, which of the following templates would be best for this requirement? ❍ A. Cab project ❍ B. Merge Module project ❍ C. Setup project ❍ D. Web Setup project Answer B is correct. A Merge Module project is used to create a redistributable package that includes shared components or assemblies. Answers A and D are incorrect because Cab and Web Setup projects are used to package ActiveX controls and Web applications for deployment to a Web server. Answer C is incorrect because Setup projects are used to create Windows Installer packages for application distribution. Question 2 After building a Setup project, which files will be present in the Release folder of the setup project? (Select all that apply.) ❑ A. .exe ❑ B. .ini ❑ C. .msi ❑ D. .txt Answers A, B, and C are correct. The Setup project produces the installer package (.msi), initialization files (.ini), and any additional executable files (.exe) needed. Text (.txt) files are not produced directly by this process, making answer D incorrect. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deploying . . . . . .a .Windows . . . . . Application . . . . . . Question 3 When deploying an application packaged as an .msi file to a user accessing the package through a network file share, what components must be loaded first? (Select all that apply.) ❑ A. .NET Framework on the server ❑ B. .NET Framework on the workstation ❑ C. Windows Installer on the server ❑ D. Windows Installer on the workstation Answers B and D are correct. Both the .NET Framework and Windows Installer components must be installed on the user’s workstation before installing an installer package (.msi). Because all installation processing is performed on the workstation, neither component is specifically required on the server, making answers A and C incorrect. Question 4 Which Setup project configuration option would be used to specify the creation of .cab files no larger than 1.4MB to fit your application on multiple floppy disks? ❍ A. Bootstrapper ❍ B. Compression ❍ C. Package files ❍ D. Output filename Answer C is correct. The package files option allows specification of the type of file to be generated, including the capability to specify the maximum size for generated cabinet (.cab) files. The Bootstrapper option is used to specify whether the distributable application should carry a copy of the Windows Installer package with it for installation first if the destination system lacks the utility, making answer A incorrect. Answer B is incorrect because the Compression option is used to specify whether the installer package should be compressed to make the file smaller or to speed up its installation. The Output filename is used to specify the name for the generated installer package, making answer D incorrect as well. 301 302 Chapter 13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 5 Which editor should be used to enable the automatic creation of a shortcut icon for your application during the installation in the user’s desktop? ❍ A. Custom Actions Editor ❍ B. Launch Conditions Editor ❍ C. File Types Editor ❍ D. File System Editor ❍ E. User Interface Editor Answer D is correct. The File System Editor allows you to specify shortcuts and icons mapped to user-relative paths such as the user’s desktop. Answer A is incorrect because the Custom Actions Editor is used to configure additional installation actions to be taken that are not directly a part of the installation itself. The Launch Conditions Editor is used to specify conditions that must be met before installation can occur, making answer B incorrect. Answer C is incorrect because the File Types Editor is used for file type association between the application and files of the type it should handle. The User Interface Editor is used to configure dialog boxes that will be presented to the user during the installation process, making answer E incorrect. Question 6 You want to execute custom code when the installation of a component is successful. Which of the following methods of the Installer should you choose to write your custom code? ❍ A. Install ❍ B. Rollback ❍ C. Commit ❍ D. Uninstall Answers C is correct. The Commit method executes when the installation is successful. Answer A is not correct because the Install method executes when the installation is performed; the installation might or might not be successful. Answer B is not correct because the Rollback method is executed when the installation fails. Answer D is not correct because the Uninstall method executes to remove an installation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deploying . . . . . .a .Windows . . . . . Application . . . . . . Question 7 A strong name must include which of the following elements? (Select all that apply.) ❑ A. Authenticode signature ❑ B. Culture ❑ C. Digital signature ❑ D. Version ❑ E. Text name Answers C, D, and E are correct. An assembly’s strong name must include a text name, a version number, culture information (if specified), and a unique digital signature created from the hashed value of the application. Answer A is not correct because an Authenticode signature can be added to allow thirdparty verification of an assembly’s source, but it is not required for its strong name. Answer B is not correct because although culture information may be included, it is not necessary. Question 8 When using delay signing, which key(s) are used to sign the assembly initially? ❍ A. Public key ❍ B. Private key ❍ C. Both keys ❍ D. Hashed key Answer A is correct. In delay signing, the public key is used to sign the assembly during development. The private key is used later to sign the assembly for deployment, making answers B and C incorrect. Answer D is incorrect because the hashed value is used along with the signing key to create the final digital signature. 303 304 Chapter 13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 9 Which methods can be used to register a shared assembly within the GAC? (Select all that apply.) ❑ A. Global Assembly Cache tool ❑ B. Internet Explorer ❑ C. Microsoft .NET Framework Configuration tool ❑ D. Windows Explorer ❑ E. Windows Installer Answers A, C, D, and E are correct. An assembly can be registered in the Global Assembly Cache through the Global Assembly Cache tool (GacUtil.exe), the Microsoft .NET Framework Configuration tool, Windows Explorer, and Windows Installer. Answer B is incorrect because Internet Explorer cannot register a shared assembly in the GAC. Question 10 Which zone should you edit to allow the execution of an assembly identified by a URL within the same subnet as the client? ❍ A. My_Computer_Zone ❍ B. My_Network_Zone ❍ C. LocalIntranet_Zone ❍ D. Internet_Zone Answer C is correct. The LocalIntranet_Zone is used for URLs within the same network. Answer A is incorrect because My_Computer_Zone is used only for paths local to the user’s system. There is no My_Network_Zone, making answer B incorrect. Internet_Zone is used for URLs outside the local network, making answer D incorrect. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deploying . . . . . .a .Windows . . . . . Application . . . . . . Need to Know More? Jeffery Ritcher. Applied Microsoft .NET Framework Programming. Microsoft Press, 2002. Microsoft Developer Network: http://msdn.microsoft.com. Microsoft Windows Update Site: http://windowsupdate. microsoft.com. Certified for Microsoft Windows logo program Web site: msdn.microsoft.com/certification. Designed for Microsoft Windows XP logo program Web site: www.microsoft.com/winlogo. Microsoft .NET Connected logo Web site: www.microsoft.com/ net/logo. 305 14 Maintaining and Supporting a Windows Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ Process class ✓ EventLog class ✓ PerformanceCounter class ✓ Start method ✓ CloseMainWindow method ✓ Kill method ✓ CreateEventSource method ✓ WriteEntry method ✓ Sampling ✓ Publishing Techniques you’ll need to master: ✓ Understand the use of the Start, Kill, and CloseMainWindow methods to start and stop processes. ✓ Know how to use event logs within your applications. ✓ Understand the purpose and use of performance counters. 308 Chapter 14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . After you have created your Visual C# .NET application and deployed it to your users, you will need to monitor its operation and make adjustments to improve performance. In this chapter, we examine some of the methods that can be used to fulfill this requirement, including the management of Windows processes and event logs, and the monitoring of performance data for running processes. Using these tools, you also can allow an application to alter its behavior based on available system resources within a dynamic setting. Introduction Within the .NET environment, the Systems.Diagnostics namespace includes many classes that can be used to manage or monitor a Windows application, including the following: ➤ Process class—This class provides information about processes running on a system, local or remote, and also grants control over starting and stopping processes on the local system. ➤ EventLog class—This class provides the capability to read from or write to a Windows event log. ➤ PerformanceCounter class—This class provides access to performance data about running processes, as well as the publication of performance data over a network. The Process Class When an application is executed, it creates a process. Each process consumes memory and other system resources, and is uniquely identified by a process identifier (PID). The System.Diagnostics namespace includes a Process class. The methods of the Process class can be used to start and stop running processes, and its properties can be used to obtain information about running processes. Starting and Stopping Processes The Start method of the Process class can be used to start an instance of the target process, using startup information specified in the StartInfo property to allow runtime configuration of the application’s environment. The Process class also includes two methods that can be used to terminate a running process: CloseMainWindow and Kill. 309 . . . . . . . . . . . . . . . . . . . . .Maintaining . . . . . . and . . .Supporting . . . . . .a .Windows . . . . . Application . . . . . . The Process class can be used only to start and stop processes on the local system. However, it is possible to access process information on both local and remote systems using this class. CloseMainWindow is equivalent to clicking the Close icon of an application, and it can be used only with applications that have a user interface and that participate in the Windows message loop. The Kill method must be used for applications that lack a user interface or that do not participate in the Windows message loop, such as MS-DOS–based executables. The Kill method terminates an application immediately without saving data or performing resource cleanup. Table 14.1 details several members of the Process class that are useful for starting or stopping processes. Table 14.1 Members of the Process Class Useful for Starting or Stopping Processes Member Type Description CloseMainWindow Method Closes a process with a user interface by sending a close message to its main window EnableRaisingEvents Property Specifies whether an Exited event is raised when the process terminates ExitCode Property Is an exit value specified by a process on termination Exited Event Fires on process termination ExitTime Property Gives the time when the process ended GetProcessById Method Is a Process object representing a running process with the specified PID GetProcesses Method Returns an array of Process objects in which each element represents a running process GetProcessesByName Method Returns an array of Process objects in which each element represents a running process with the specified name HasExited Property Indicates whether a process has been terminated Id Property Gives the PID of a process Kill Method Immediately terminates a running process StartInfo Property Specifies the properties to pass to the Start method (continued) 310 Chapter 14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 14.1 Members of the Process Class Useful for Starting or Stopping Processes (continued) Member Type Description WaitForExit Method Specifies the period to wait for process termination, blocking the current thread of execution until the time has expired or the process has terminated WaitForInputIdle Method Causes a Process object to wait for the system to enter an idle state You can create a sample form that can start and stop instances of a calculator application by performing the following: 1. Open an instance of Visual Studio .NET and create a new Visual C# .NET Windows application. 2. Place two GroupBox controls, three Button controls (btnLaunchCalculator, btnCloseRecentCalculator, and btnCloseAllCalculators), and two Label controls on your form. Name one of the Label controls lblLiveCalculators and set its Text property to 0. Figure 14.1 shows the design for the form. Figure 14.1 Design of a form that uses the Process class to start and stop processes. 3. Switch to the form’s Code view and add the following statement at the top of the form’s class definition: using System.Diagnostics; 4. Add the following code to your form: ArrayList arrCalculators = new ArrayList(); private void Calculator_Exited(object sender, System.EventArgs e) { 311 . . . . . . . . . . . . . . . . . . . . .Maintaining . . . . . . and . . .Supporting . . . . . .a .Windows . . . . . Application . . . . . . Process p = (Process) sender; arrCalculators.RemoveAt(arrCalculators.IndexOf(p.Id)); lblLiveCalculators.Text = (Int32.Parse(lblLiveCalculators.Text) - 1).ToString(); } private void btnLaunchCalculator_Click( object sender, System.EventArgs e) { Process prcCalculator = new Process(); prcCalculator.StartInfo.FileName = “calc.exe “; prcCalculator.EnableRaisingEvents = true; prcCalculator.Exited += new EventHandler(Calculator_Exited); prcCalculator.Start(); prcCalculator.WaitForInputIdle(); arrCalculators.Add(prcCalculator.Id); lblLiveCalculators.Text = (Int32.Parse(lblLiveCalculators.Text) + 1).ToString(); } private void btnCloseRecentCalculator_Click( object sender, System.EventArgs e) { if(arrCalculators.Count > 0) { int intId = (int) arrCalculators[arrCalculators.Count - 1]; try { Process p = Process.GetProcessById(intId); p.CloseMainWindow(); } catch(Exception ex) { Trace.WriteLine(ex.Message); } } } private void btnCloseAllCalculators_Click( object sender, System.EventArgs e) { Process[] arrCalculators = Process.GetProcessesByName(“calc”); foreach(Process prcCalculator in arrCalculators) { prcCalculator.CloseMainWindow(); } } 5. Insert the Main method, set the form as the startup object, and run your project. When you click the Launch button, a new instance of the Calculator process is launched. Clicking the Close Most Recent button terminates the most recent instance of the Calculator process started by this application. The Close All Calculators button stops all running instances of the Calculator process. 312 Chapter 14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . You can also use the Process component from the toolbox instead of creating a Process object in the code. You can configure the Process component’s StartInfo property to include the filename of the target process and its startup parameters. Getting Process Information Process information can be programmatically accessed using the properties of an instance of the Process class created for a process running on a local or remote system. Table 14.2 details some of the useful properties exposed by this class. Table 14.2 Useful Properties of the Process Class Property Description MachineName Gives the name of the machine on which the process is running MainModule Gives the main module of the process MainWindowTitle Is the caption in the main window of a process Modules Are modules loaded by the associated process PriorityClass Gives the priority class for the process ProcessName Gives the name of the process ProcessorAffinity Specifies the processors on which the threads in this process can be scheduled to run Responding Indicates whether the user interface is responding StandardError Provides access to a StreamReader object, allowing you to read error output StandardInput Provides access to a StreamWriter object, allowing you to write input to the process StandardOutput Provides access to a StreamReader object, allowing you to read output from the process StartTime Gives the process start time Threads Are threads running in the associated process TotalProcessorTime Gives the total processor time used by a process UserProcessorTime Gives the total user processor time used by a process VirtualMemorySize Gives the size of virtual memory used by a process WorkingSet Gives the physical memory used by a process 313 . . . . . . . . . . . . . . . . . . . . .Maintaining . . . . . . and . . .Supporting . . . . . .a .Windows . . . . . Application . . . . . . Windows Event Logs Events logs provide a standard location where events and other messages can be recorded and later reviewed using applications such as the Event Viewer. The .NET Framework Class Library also includes several classes that can be used to create event logs, read from or write events to the logs, and delete event logs. Three default event logs (the Application, Security, and System logs) cannot be deleted. (The security log is read-only and cannot be written to directly.) Additional resources or applications also can create their own event logs, such as the Domain Name System (DNS) and the Active Directory. It is important to be cautious while using the Delete method on any of these logs: Deleting a log also removes all event sources registered with the deleted event log. Table 14.3 details some useful members of the EventLog class within the System.Diagnostics namespace. Table 14.3 Useful Members of the EventLog Class Member Type Description CreateEventSource Method Opens an event source for an application Delete Method Removes a log resource DeleteEventSource Method Removes an application’s event source from a log EnableRaisingEvents Property Specifies whether the EventLog object is notified on the EntryWritten event Entries Property Gives the contents of a log EntryWritten Event Fires when an entry is written to an event log on the local computer Exists Method Indicates whether the specified log exists GetEventLogs Method Returns an array of all event logs on the local or the specified computer Log Property Gives the name of the log to read from or write to LogDisplayName Property Gives an event log’s user-friendly name LogNameFromSourceName Method Shows the name of the log to which a specified source is registered MachineName Property Shows the name of the computer on which to read or write events (continued) 314 Chapter 14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 14.3 Useful Members of the EventLog Class (continued) Member Type Description Source Property Specifies the event source to register and use when writing to the event log SourceExists Method Determines whether a given event source exists WriteEntry Method Writes an entry to the log Each application must register an event source before it can interact with an event log. Registration of the source is stored in the Registry. The CreateEventSource method can be used to register the application with an event log, creating the log if it does not yet exist. Accessing Event Logs The WriteEntry method of the EventLog class is used to write messages into the event log specified by the event source. If the event source has not already been created using the CreateEventSource method, it is created automatically by the WriteEntry method. The type of event written is determined by its EventLogEntryType enumerated value (Error, FailureAudit, Information, SuccessAudit, or Warning). The following code shows you how to create a new event log and write an entry to it: EventLog el = new EventLog(); el.Log = “MyCustomLog”; el.Source = “MyCustomLogSource”; el.WriteEntry(“Created new event log”, EventLogEntryType.Information); You can then view the newly created event log in the Event Viewer, as shown in Figure 14.2. To access the contents of an event log, you use the Entries property of the EventLog object to return an EventLogEntryCollection object. The elements of this object are the individual event log entries. It is possible to view events on the local system, as well as those from remote systems. Although you can read event logs on remote systems, the EntryWritten event can be used to fire only when event log entries are written on the local system. 315 . . . . . . . . . . . . . . . . . . . . .Maintaining . . . . . . and . . .Supporting . . . . . .a .Windows . . . . . Application . . . . . . Figure 14.2 You can use the Event Viewer to view the contents of the event logs. Monitoring Performance Microsoft Windows includes several hundred performance counters, each monitoring a particular service parameter. Other applications, such as Exchange and SQL Server, also provide a wide variety of performance counters that can be used to obtain current operational parameters. Microsoft Windows organizes performance counters into categories, such as Memory, Processor, or PhysicalDisk, while categories can be further divided into instances. Each instance of the Process class, for example, has its own associated performance counters. Reading Performance Data The PerformanceCounter class is provided to allow your .NET applications to read performance data from processes running on a local or remote system and to publish their own performance counters. Table 14.4 details some important members of the PerformanceCounter class. Table 14.4 Some Important Members of the PerformanceCounter Class Member Type Description CategoryName Property Gives the performance counter category name Close Method Closes the performance counter and releases its resources CounterHelp Property Describes the performance counter CounterName Property Gives the performance counter name CounterType Property Gives the performance counter type Decrement Method Decrements the performance counter value by 1 Increment Method Increments the performance counter value by 1 (continued) 316 Chapter 14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 14.4 Some Important Members of the PerformanceCounter Class (continued) Member Type Description IncrementBy Method Increments or decrements the performance counter value by the specified amount InstanceName Property Gives the instance name MachineName Property Gives the computer name NextSample Method Returns the raw, uncalculated value newly sampled for a performance counter NextValue Method Returns the calculated value newly sampled from a performance counter RawValue Property Returns a sampled raw value from a performance counter ReadOnly Property Indicates whether a PerformanceCounter is in read-only mode RemoveInstance Method Removes an instance from a PerformanceCounter object Sampling is the process of reading the value of a performance counter. You can sample existing performance counters on local and remote systems. You can view sampled performance data using the Performance Monitor (perfmon.exe) utility and also within your .NET application. A listing of available performance counters can be easily accessed within the Server Explorer of Visual Studio .NET, where you can drag and drop the desired counter into your application (see Figure 14.3). Figure 14.3 Selection of the Available Bytes performance counter within the Server Explorer. Publishing Performance Data The .NET Framework enables you to create your own custom performance counters, which you then can access from other applications in addition to using the Performance Monitor utility. You can use the Create method of the PerformanceCounterCategory to programmatically add a new category, or 317 . . . . . . . . . . . . . . . . . . . . .Maintaining . . . . . . and . . .Supporting . . . . . .a .Windows . . . . . Application . . . . . . you can right-click the Performance Counters node of the Server Explorer and select Create New Category from the options provided. When you create a new performance counter, it must be placed within a new category. It is not possible to place a custom counter within an existing category, although it is possible to add multiple new performance counters within the newly created category. 318 Chapter 14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Questions Question 1 Which of the following are valid message type values that can be written in the event log? (Select all that apply.) ❑ A. Error ❑ B. FailureAudit ❑ C. Information ❑ D. Kill ❑ E. Warning Answers A, B, C, and E are correct. The type of an event log message must be one of the EventLogEntryType enumerated values: Error, FailureAudit, Information, SuccessAudit, and Warning. Answer D is incorrect because the Kill method of the Process class is not a member of the EventLogEntryType enumeration. Question 2 You want to determine whether a given event log exists on a machine. Which of the following methods can you call to determine this? ❍ A. Exists ❍ B. SourceExists ❍ C. GetEventLogs ❍ D. LogNameFromSourceName Answer A is correct. The Exists method determines whether a log exists on a machine. Answer B is not correct because the SourceExists method determines whether a particular source exists. Answer C is not correct because the GetEventLogs method creates an array of the event logs available on a local or specified machine. Answer D is not correct because the LogNameFromSourceName method determines the log name for a specified source. 319 . . . . . . . . . . . . . . . . . . . . .Maintaining . . . . . . and . . .Supporting . . . . . .a .Windows . . . . . Application . . . . . . Question 3 You have written an application that presents an opening standalone form that can be used to select which external module to access. If no user input is provided after 15 minutes, you want to close the process. Which of the following methods of the Process class would best fulfill this requirement? ❍ A. Close ❍ B. CloseMainWindow ❍ C. Dispose ❍ D. Kill Answer B is correct. The CloseMainWindow method should be used to terminate a process with a user interface. Answers A and C are incorrect because the Process class does not include the Close or Dispose methods. Answer D is incorrect because the Kill method terminates a process without performing resource cleanup, so it would not be the best solution here. Question 4 You have written an application that monitors an event log so that it can trigger a regular low-priority data update process only when the primary application process has completed. Although the primary process is writing to the event log and your application is capable of reading events from the log, your program fails to automatically trigger the desired event. What should you do within the code to configure the EventLog object so that it can trigger your process? ❍ A. Set its Enabled property to true ❍ B. Set its Enabled property to false ❍ C. Set its EnableRaisingEvents property to true ❍ D. Set its EnableRaisingEvents property to false Answer C is correct. You must set the EnableRaisingEvents property of an EventLog object to true to allow it to raise events on the local system. Answers A and B are incorrect because an Enabled property is not used for this purpose. Answer D is incorrect because setting the EnableRaisingEvents property to false prevents the handler from raising events. 320 Chapter 14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 5 You develop a Windows forms application that needs to display the message from a custom event log on the user’s computer. You choose the event log object to accomplish this. Which of the following properties should you choose for retrieving the event log messages? ❍ A. Log ❍ B. Entries ❍ C. Source ❍ D. LogDisplayName Answer B is correct. You should use the Entries property to retrieve the contents of a specified log. Answer A is not correct because the Log property gets the name of the event log instead of the entries. Answer C is not correct because the Source property is the name registered with the event log as a source of entries. Answer D is not correct because the LogDisplayName property is used to obtain a friendly name of the specified event log. Question 6 Which of the following statements are true regarding performance counters? (Select all that apply.) ❑ A. Performance counters are grouped into performance counter categories. ❑ B. Each performance counter category has its own set of associated values. ❑ C. Each performance counter instance has its own set of associated values. ❑ D. Performance counter categories must include one or more performance counter instances. ❑ E. You can add performance counters only to an existing performance counter category. Answers A and C are correct. Performance counters are grouped into performance counter categories, and each performance counter instance has its own set of published values. Answer B is incorrect because performance counter values are published for each instance rather than for an entire performance category. Answer D is incorrect because a performance category might contain zero instances, while Answer E is incorrect because you cannot add performance counters to existing categories. You must create a new category, which can contain none, one, or many new performance counters. 321 . . . . . . . . . . . . . . . . . . . . .Maintaining . . . . . . and . . .Supporting . . . . . .a .Windows . . . . . Application . . . . . . Question 7 Which of the following default event logs can be written to on a local system? (Select all that apply.) ❑ A. Application ❑ B. Event ❑ C. Security ❑ D. System Answers A and D are correct. The Application and System default event logs can be written to on a local system. Answer B is incorrect because there is no default event log named Event; Answer C is incorrect because the security event log is read-only. Question 8 Your colleague is experimenting with the classes in the System.Diagnostics namespace of the .NET Framework class libraries. She has requested that you review her code. A part of the code that is designed to list events from an event log is as follows (line numbers are for reference purposes only): 01: 02: 03: 04: 05: 06: 07: EventLog log = new EventLog(); log.Log = “Security”; //log.MachineName = “.”; foreach(EventLogEntry entry in log.Entries) { MessageBox.Show(“Entry: “ + entry.Message); } Which of the following statements is true of the previous code segment? ❍ A. The code correctly displays all the events from the security event log on the local computer. ❍ B. The code throws an exception because you cannot read from the security event log. ❍ C. Your colleague must uncomment Line 3 to read the events from the local computer. ❍ D. Your colleague must use the Source property of the EventLog class to specify the source of the event. Answer A is correct. The code segment correctly displays the events from the security event log on the local computer. Answer B is not correct because the security event log is read-only. Answer C is not correct because if the MachineName is not specified, the local machine is assumed. Answer D is 322 Chapter 14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . not correct because it is necessary to specify the Source property only when writing to an event log. Question 9 You have written an application that includes several initialization procedures that occur when the form is first loaded. Some users complain that the form often generates an error because the initialization procedures are not completing before user access is allowed. You want to fire an event to enable user access only after the initialization routine is completed. Which member of the Process class should you monitor to meet this requirement? ❍ A. Exited ❍ B. ExitTime ❍ C. HasExited ❍ D. StartInfo ❍ E. WaitForExit ❍ F. WaitForInputIdle Answer F is correct. The WaitForInputIdle method causes a Process object to wait for an idle state, which occurs only after the initialization procedures have been completed. Answers A, B, C, and E are incorrect because they involve the termination of an application and would not be suitable for taking action when the process must continue running. Answer D is incorrect because the StartInfo property is used to pass parameters and operating environment settings to the process during instantiation. Question 10 You have created a custom performance counter that publishes a value representing how many records remain unprocessed. This value is decreased by 10 as each cycle processes a record batch, until it reaches 0. What method of the PerformanceCounter class would best suit this requirement? ❍ A. Decrement ❍ B. DecrementBy ❍ C. Increment ❍ D. IncrementBy ❍ E. NextValue 323 . . . . . . . . . . . . . . . . . . . . .Maintaining . . . . . . and . . .Supporting . . . . . .a .Windows . . . . . Application . . . . . . Answer D is correct. The IncrementBy method is used to increment and decrement a published performance counter by an arbitrary value. Answers A and C are incorrect because the Decrement and Increment methods adjust the published value only by 1. Answer B is incorrect because the PerformanceCounter class does not have a separate DecrementBy method. Answer E is incorrect because the NextValue method is used to return a newly sampled value rather than to publish a value. 324 Chapter 14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Need to Know More? Kalani, Amit. MCAD/MCSD Training Guide: Developing and Implementing Windows-Based Applications with Microsoft Visual C# .NET and Microsoft Visual Studio .NET, Exam 70-316. Que Certifications, 2003 Burton, Kevin. .NET Common Language Runtime Unleashed. Sams, 2002. Performance tips and tricks in .NET applications: http://msdn. microsoft.com/library/default.asp?url=/library/en-us/ dndotnet/html/dotnetperftips.asp. 15 Configuring a Windows Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms you’ll need to understand: ✓ Dynamic properties ✓ Code-access security ✓ Role-based security ✓ Permissions ✓ Code groups ✓ Permission sets ✓ WindowsIdentity object ✓ WindowsPrincipal object ✓ IsInRole method ✓ PrincipalPermission class Techniques you’ll need to master: ✓ Understand how to use dynamic properties to manage runtime configuration. ✓ Know how to use code groups to manage user permissions. ✓ Understand the use of the WindowsIdentity and WindowsPrincipal objects. 326 Chapter 15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Many values used within an application must allow for dynamic configuration. An example of this is the need for a data-aware application to provide a mechanism for changing the target database source. Without this flexibility, applications cannot adjust as changes are made to the distributed network environment. The .NET platform allows for dynamic configuration changes to be readily integrated into your application through the use of XML configuration files. It is also important to plan for access control, restricting who may use your application, and for limitations on available capabilities within your application. Role-based access control allows the application to alter its behavior based on the permissions provided to the current logon account or to the application itself. This chapter focuses on dynamic configuration at runtime, code access security, and role-based security integration. You will rarely need to configure detailed access control over Windows controls. The .NET Framework uses a LicenseProvider object that can be configured by the control’s developer. If the license requirements stored in this object are met, the control can be added to your application. Everything else is automatically handled by the .NET Framework. Dynamic Application Configuration Applications might require dynamic runtime configuration to allow contact with a service provider, such as an e-mail or database server, determination of available system and network resources, or changes to the user environment to meet with deployment requirements or user preference. The .NET Framework includes support for dynamic properties that can be configured at runtime without requiring a recompilation of the base application. Using Dynamic Properties Dynamic properties are managed at runtime by the System. Configuration.AppSettingsReader class. The Visual Studio .NET IDE enables you to define dynamic properties for your application. You can use dynamic properties only within applications that create an executable (.exe) file. Applications that create .dll files cannot use dynamic properties. 327 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring . . . . . . .a .Windows . . . . . Application . . . . . . You configure a dynamic property for a form by performing the following steps: 1. Open an instance of Visual Studio .NET and create a new Visual C# .NET Windows application. 2. In the form’s properties window, click the plus (+) sign next to the (DynamicProperties) entry. 3. Click in the (Advanced) section and click the ellipsis (…) button to open the Dynamic Properties dialog box (see Figure 15.1). In the Properties list, select the check boxes for the ShowInTaskbar and Text properties. Figure 15.1 The Dynamic Properties dialog box enables you to configure dynamic properties by selecting the desired properties and their key mappings. 4. Select the properties that will be configured for dynamic runtime eval- uation. Then click OK to close the dialog box. After you save the form and run the application within the IDE, the app.config file is created and displayed in the Solution Explorer window. Editing this XML file allows manipulation of the dynamic properties used each time the application is run. After you compile the application, the <appname>.exe.config file is created in the application’s bin\Debug directory. This XML file can be edited to alter the configuration settings used at runtime. You can set any simple property (that is, any property whose value is not an instance of a class or a structure) to be a dynamic property. Some .NET components include dynamic properties already. If you drag an Access database from the Server Explorer to a Windows Form, .NET 328 Chapter 15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . automatically includes a dynamic property entry for the OleDbConnection component. If you later remove a property from the dynamic properties list, the key and last value for that property remain in the configuration file. It is important to remember to remove any password or development-only values from the file before deploying your application. All of the dynamic properties on forms, controls, and components in a project use the same configuration file, named <appname>.exe.config. Application configuration files generally override settings in the machine configuration file (machine.config), unless the machine configuration file specifies that the application configuration file not be used. Using the .NET Framework Configuration Tool When you load the .NET Framework on a server, the .NET Framework Configuration tool is included (see Figure 15.2). You can locate this Microsoft Management Console (MMC) utility by selecting Start, Programs, Administrative Tools, Microsoft .NET Framework Configuration. Figure 15.2 The .NET Framework Configuration tool. Using the .NET Framework Configuration tool, it is possible to do the following: 329 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring . . . . . . .a .Windows . . . . . Application . . . . . . ➤ Manage the contents of the Global Assembly Cache (GAC) ➤ Manage machine-wide configured assemblies, which map from one assembly version to another, as shown in Figure 15.3 Figure 15.3 A configured assembly, mapping version 1.0.3300.0 to the new 2.0.0.0 version. ➤ Manage remoting channels, which allow communication with objects on remote systems ➤ Manage security policy settings ➤ Manage application settings, which allow each application to have its own remoting and configured assembly rules The .NET Framework Configuration tool does not perform validation when specifying a new configured assembly mapping. If you attempt to load a nonexistent assembly, you will get a Just In Time (JIT) debugging error. Configuring Security The security model in .NET development breaks down into two primary areas: ➤ Code access security—This manages the security of the code itself, enabling the .NET Framework to verify permissions before allowing code to run or ensuring that all necessary permissions are availble to access required resources on the system before execution. 330 Chapter 15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ Role-based security—This manages the logon account’s access rather than the application code itself, allowing control of application access based on user or group membership. The .NET Framework also includes security features such as public-key and privatekey encryption, but these are not focus topics on the exam. Code access security involves controlling access to resources. Within the .NET Framework, this involves the following: ➤ Permissions ➤ Code groups ➤ Permission sets Permissions Permissions specify whether access to a resource is granted or denied. These permissions can include the capability to read or write information into the Windows Registry specified through the RegistryPermission setting. Application code can request permissions in four ways: ➤ By requesting the minimum permissions required to run ➤ By requesting optional permissions desired but not required ➤ By refusing permissions to ensure that the code cannot access a particu- lar set of resources ➤ By demanding permissions on behalf of calling code The machine determines the maximum permissions possible, but application code can be configured to request or receive lesser permissions than the maximum. The .NET Framework groups permissions into three types: ➤ Code access—These represent access to a protected resource or operation. ➤ Identity—These represent access based on credentials provided by the code. ➤ Role-based—These represent access based on the logon account executing the code. 331 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring . . . . . . .a .Windows . . . . . Application . . . . . . Permissions within the .NET Framework are derived from the System.Security.CodeAccessPermission class. Table 15.1 details some of the more useful permissions derived from this class. Table 15.1 Permissions in the .NET Framework Permission Type Explanation DirectoryServicesPermission Code access Controls access to the System.DirectoryServices namespace. DnsPermission Code access Controls access to Domain Name System (DNS) services. EnvironmentPermission Code access Controls access to environment variables. EventLogPermission Code access Controls access to the Windows event log. FileDialogPermission Code access Controls access to files selected from the Open dialog box. FileIOPermission Code access Controls access to reading and writing files and directories. IsolatedStorageFilePermission Code access Controls access to private virtual file systems. IsolatedStoragePermission Code access Controls access to isolated storage. MessageQueuePermission Code access Controls access to message queuing via Microsoft Message Queue (MSMQ). OleDbPermission Code access Controls access to data via the System.Data.OleDb namespace. PerformanceCounterPermission Code access Controls access to performance counters. PrintingPermission Code access Controls access to printers. ReflectionPermission Code access Controls access to the .NET reflection features. RegistryPermission Code access Controls access to the Windows Registry. SecurityPermission Code access Controls access to unmanaged code. ServiceControllerPermission Code access Controls access to starting and stopping services. SocketPermission Code access Controls access to Windows sockets. (continued) 332 Chapter 15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table 15.1 Permissions in the .NET Framework (continued) Permission Type Explanation SqlClientPermission Code access Controls access to data via the System.Data.SqlClient namespace. UIPermission Code access Controls access to the user interface. WebPermission Code access Controls access to making Web connections. PublisherIdentityPermission Identity Represents the identity of the publisher, as determined by the code’s digital signature. SiteIdentityPermission Identity Represents the identity of the Web site from which the code originated. StrongNameIdentityPermission Identity Represents the identity for the strong name of the assembly. URLIdentityPermission Identity Represents the identity of the uniform resource locator (URL) where the code originated. ZoneIdentityPermission Identity Represents the identity for the security zone where the code originated. This is viewed on the Security tab of Internet Explorer Options. PrincipalPermission Role-based Represents the user’s credentials. Allows checks against the active principal. If the available listing of permissions is inadequate for your needs, it is also possible to create custom permissions by deriving from the System.Security.CodeAccessPermission class. Requesting Minimum Permissions Application code should request the least permissions required to operate. You can follow an example of this with these steps: 1. Open an instance of Visual Studio .NET and create a new Visual C# .NET Windows application. 2. Place a Label control, a TextBox control (txtFileName), a Button con- trol (btnGetFile), and an OpenFileDialog component (dlgOpen) on your form. 333 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring . . . . . . .a .Windows . . . . . Application . . . . . . 3. Switch to Code view and add the following code before the class decla- ration: using System.Security.Permissions; [assembly:FileDialogPermissionAttribute( SecurityAction.RequestMinimum, Unrestricted=true)] private void btnGetFile_Click( object sender, System.EventArgs e) { try { if(dlgOpen.ShowDialog() == DialogResult.OK) txtFileName.Text = dlgOpen.FileName; } catch (Exception ex) { MessageBox.Show(“Exception: “ + ex.Message); } } 4. After saving and compiling this project, you can launch the executable and ensure that access of the FileDialogPermission is accomplished through the FileDialogPermissionAttribute request. In this example, the SecurityAction.RequestMinimum flag establishes that you are determining whether the application code has been granted at least the minimum necessary permissions to operate. The SecurityAction enumeration consists of four values that you should be familiar with: ➤ RequestMinimum—Determines whether the application code has at least the minimum permissions needed to run. ➤ RequestOptional—Requests additional desired permissions that are not strictly required to run the application. This requires a try-catch block to handle the exception if a permission is not available. ➤ RequestRefuse—Limits the permissions granted to the application code, to restrict the harm application code can cause. ➤ Demand—Requires all code that calls this application to have a particular permission. Code Groups A code group is a set of assemblies that share a security context. Every assembly in a code group shares the same permissions, but an assembly also can belong to more than one code group at the same time. The .NET Framework supports seven code-group membership conditions: 334 Chapter 15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ Application directory—All code in the installation directory of the running application. ➤ Cryptographic hash—All code matching a specific cryptographic hash, creating a single-assembly code group. ➤ Software publisher—All code from a specific publisher, verified by Authenticode digital signing. The Authenticode digital signing identifies the publisher of the software and verifies that the software has not been tampered with. ➤ Site—All code from a particular Internet domain. ➤ Strong name—All code with the specified assembly strong name. ➤ URL—All code from a specified URL. ➤ Zone—All code from a specified security zone (Internet, Local Intranet, Trusted Sites, My Computer, or Untrusted Sites). Permission Sets It is not possible to assign permissions directly within the .NET Framework. You must construct permission sets, which contain one or more permissions that are assigned as a unit. The .NET Framework includes seven default permission sets: ➤ Nothing—Grants no permissions ➤ Execution—Grants permission to run but not to access protected resources ➤ Internet—Grants limited permissions for code of unknown origin ➤ LocalIntranet—Grants high permissions for code within an enterprise ➤ Everything—Grants all permissions except the permission to skip security checks ➤ SkipVerification—Grants the permission to skip security checks ➤ FullTrust—Grants all permissions over all resources Granting Permissions The easiest way to grant permissions is to use the .NET Framework Configuration tool (shown in Figure 15.2). To configure a specific set of 335 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring . . . . . . .a .Windows . . . . . Application . . . . . . permissions for the application created in the previous section of this chapter, follow these steps within this tool: 1. Expand the Runtime Security Policy node, then the User node, and then the Permission Sets node. You should see the built-in .NET permission sets. Right-click the Everything permission set and select Duplicate. A new permission set named Copy of Everything is created. Rename the permission set No FileDialog. 2. Select the No FileDialog permission and click the Change Permissions link in the right panel of the .NET Framework Configuration tool. In the Create Permission Set dialog box, select File Dialog and click Remove. Click Finish to save your changes. 3. Expand the Code Groups node under the User node, and click the default All Code code group. Click the Add a Child Code Group link in the right panel of the configuration tool. This opens the Create Code Group dialog box. Name the new group Chapter15. Enter a description and click Next. Choose the Hash condition. Click the Import button and browse to the application’s executable file created in the previous example. Select the No FileDialog permission set, and click Next. Click Finish to create the new code group. Right-click the newly created code group, and select Properties to view the code group’s Properties dialog box, as shown in Figure 15.4. Check the first check box to make this code group exclusive. Figure 15.4 Configuring a group named Chapter15. 4. Run the application’s executable file created in the previous example by double-clicking it in Windows Explorer. A policy exception error box appears, indicating that the code cannot be run. 336 Chapter 15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . To evaluate the final permissions available to a piece of code, right-click the Runtime Security node and select Evaluate Assembly from the options provided. Requesting permissions through the use of attributes is known as declarative security. Imperative security involves creating objects to represent the permissions your code requires. Imperative security is generally used only when security must be configured based on runtime conditions. Computing Final Permissions Determination of the final permissions available to your code involves determining the permissions at each level (Enterprise, Machine, User, and Application Domain) and then evaluating all of the permissions assigned at each level within the hierarchical code group structure. The final set of permissions is the intersection of all of these evaluations. If there is no assignment of a particular permission at any point in the path discovered by the Common Language Runtime (CLR) code walk through all layers and all code groups, the permission is not available to your application. Evaluation occurs at the Enterprise level first and then the Machine, User, and the Application Domain levels. If the CLR encounters a code group with the LevelFinal property, evaluation stops at that level. Code group evaluation is performed in order of the organized hierarchy set using the Microsoft .NET Framework Configuration tool. If a code group is marked as an Exclusive group, the CLR stops evaluating code group membership for a piece of application code. After determining the code group membership of an application, the CLR calculates all of the permissions for each code group and takes the intersection of these for the final permissions granted by the code group. Then the CLR determines all of the code groups that the code has membership in and takes the union of these permission sets, to create the final set of permissions granted to the code at a particular level. The final evaluation involves calculating the intersection of the permissions granted at each level, to yield the final set of permissions for a code module. If your code has multiple modules, the ultimate set of permissions for the entire application will be the intersection of the final permissions assigned to each module. 337 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring . . . . . . .a .Windows . . . . . Application . . . . . . Configuring Authorization Role-based security involves authentication and authorization. Authentication involves verifying the identity of the requesting account, and authorization refers to granting rights based on that identity. In Windows applications, authentication is mainly based on the user’s Windows login credentials. The user is authenticated as soon as he logs on to Windows, and this identity then is used by .NET applications to implement security. The .NET Framework provides various other forms of authentication, mainly used by ASP.NET applications. But you need to know about them because they are specified in the exam objectives. The following list summarizes the various forms of authentication provided by the .NET Framework: ➤ None—No authentication is attempted, and access is granted to all requests. ➤ Forms-based—Credentials are requested from the user via an HTML form. The application sends back an identity key if acceptable. ➤ Windows—ASP.NET applications can use the built-in Windows authen- tication available within IIS. ➤ Passport—Microsoft Passport provides a centralized authentication and profile service for member sites. ➤ Custom—It is possible to develop a custom authentication scheme, although this is not recommended due to potential security risks. Identity and Principal Objects Role-based authorization within the .NET Framework involves two interfaces: IIdentity and IPrincipal. Applications that use Windows accounts use these interfaces through the WindowsIdentity and WindowsPrincipal objects, although it is possible to create your own custom authorization scheme using the IIdentity and IPrincipal classes directly. The WindowsIdentity object represents the current user running the code and includes information such as the username and authentication method. The WindowsPrincipal object adds functionality to the WindowsIdentity object, representing the entire security context of the user running the code, including the roles to which the user belongs. 338 Chapter 15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . You can obtain the WindowsIdentity of the current user through the static GetCurrent method of that class, as shown in the following example: 1. Open an instance of Visual Studio .NET and create a new Visual C# .NET Windows application. 2. Place a ListBox control (lbProperties) and a Button control (btnGetProperties) on the form. 3. Switch to Code view and add the following using directive: using System.Security.Principal; private void btnGetProperties_Click(object sender, System.EventArgs e) { AppDomain.CurrentDomain.SetPrincipalPolicy( PrincipalPolicy.WindowsPrincipal); lbProperties.Items.Clear(); WindowsIdentity wi = WindowsIdentity.GetCurrent(); // Dump its properties to the listbox lbProperties.Items.Add(“WindowsIdentity:”); lbProperties.Items.Add(“ Authentication type: “ + wi.AuthenticationType); lbProperties.Items.Add(“ Is Anonymous: “ + wi.IsAnonymous); lbProperties.Items.Add(“ Is Authenticated: “ + wi.IsAuthenticated); lbProperties.Items.Add(“ Is Guest: “ + wi.IsGuest); lbProperties.Items.Add(“ Is System: “ + wi.IsSystem); lbProperties.Items.Add(“ Name: “ + wi.Name); lbProperties.Items.Add(“ Token: “ + wi.Token.ToString()); WindowsPrincipal prin = new WindowsPrincipal(wi); lbProperties.Items.Add(“WindowsPrincipal:”); lbProperties.Items.Add(“ Authentication Type: “ + prin.Identity.AuthenticationType); lbProperties.Items.Add(“ Is Authenticated: “ + prin.Identity.IsAuthenticated); lbProperties.Items.Add(“ Name: “ + prin.Identity.Name); lbProperties.Items.Add(“ Member of Users: “ + prin.IsInRole(@”MYDOMAIN\Users”)); } 4. When you run the project, the code returns the current values of the WindowsIdentity and WindowsPrincipal classes. Note that you need to replace MYDOMAIN in the previous code with your domain name. The IsInRole method enables you to test the role membership of the current user against the specified DOMAIN\Group name. This method accepts three forms of arguments: ➤ IsInRole(WindowsBuiltInRole)—Uses one of the WindowsBuiltInRole constants to check group membership ➤ IsInRole(String)—Checks for membership in the specified group 339 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring . . . . . . .a .Windows . . . . . Application . . . . . . ➤ IsInRole(Integer)—Checks for membership in a group with the specified role identifier (RID) The PrincipalPermission Class Another way to identify group membership involves using the PrincipalPermission class or the PrincipalPermissionAttribute attribute, as in the following example: 1. Open an instance of Visual Studio .NET and create a new Visual C# .NET Windows application. 2. Switch to code view and add the following using directive: using System.Security.Permissions; using System.Security.Principal; 3. Add the following code to handle the Load event of the form: private void Form1_Load(object sender, System.EventArgs e) { // Tell the CLR to use Windows security AppDomain.CurrentDomain.SetPrincipalPolicy( PrincipalPolicy.WindowsPrincipal); // Create a new PrincipalPermission object // This object matches any user in a group named Administrators PrincipalPermission pp = new PrincipalPermission( null, “Administrators”); // See if the user is in the group try { pp.Demand(); MessageBox.Show(“You are in the Administrators group”); } catch (Exception ex) { MessageBox.Show(“Exception: “ + ex.Message); } } 4. When you run the project, the code either notifies you if you are a member of the Administrators group or displays the security exception message. 340 Chapter 15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Questions Question 1 After compiling your application into an executable named MyApp.exe, what will be the name of the file that contains the values assigned to dynamic properties in your application? ❍ A. app.config ❍ B. MyApp.config ❍ C. machine.config ❍ D. MyApp.exe.config ❍ E. MyApp.exe Answer D is correct. The configuration file for an executable application derives its name from <application name>.exe.config. Answer A is incorrect because app.config is used only by an application within the IDE. Answer B is incorrect because it lacks the executable designation (exe) linking it to the primary MyApp.exe executable. Answer C is incorrect because the machine.config file details machine configuration details rather than application-level settings. Answer E is incorrect because MyApp.exe is the name of the compiled executable rather than its associated configuration file. Question 2 You want to develop an application that can be easily customized by users through an application configuration file. You have decided that a few properties of the form need to be customized. Which of these form properties can be set in a configuration file through dynamic property support? ❑ A. Text ❑ B. Font ❑ C. BackColor ❑ D. ForeColor ❑ E. Opacity ❑ F. ShowInTaskBar 341 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring . . . . . . .a .Windows . . . . . Application . . . . . . Answers A, E, and F are correct. You can set any simple property (that is, any property whose value is not an instance of a class or a structure) to be a dynamic property. Therefore Text, Opacity and ShowInTaskBar can be set up as dynamic properties which can be configured through an configuration file. Answers B, C, and D are not correct because the Font property is an instance of the Font class and the BackColor and ForeColor properties are of type Color Structure. Question 3 Which of the following actions can be performed using the Microsoft .NET Framework Configuration tool? (Select all that apply.) ❑ A. Manage configured assemblies ❑ B. Manage remoting channels ❑ C. Manage application settings ❑ D. Manage security policy settings ❑ E. Manage the contents of the GAC Answers A, B, C, D, and E are all correct. The Microsoft .NET Framework Configuration tool can be used to manage configured assemblies, remoting channels, application settings, security policy settings, and the contents of the Global Assembly Cache (GAC). Question 4 How many configuration files can an application have? ❍ A. One ❍ B. Two ❍ C. Three ❍ D. As many as needed Answer A is correct. An application can have only one configuration file. Answers B, C, and D are incorrect because they specify an incorrect number of configuration files. However, it is possible for an application to have its settings affected by a machine.config file. 342 Chapter 15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 5 You have an assembly named PieChart, which is a member of code groups in the Enterprise, Machine, and User levels. PieChart is a member of the All Code group in the Enterprise level that has the FullTrust permission set. In the Machine level, it is a member of the Low Risk code group that has the LocalIntranet permission set. In the User level, it is a member of the High Risk code group that has the Internet permission set. What permission set will the CLR assign to the PieChart assembly? ❍ A. FullTrust ❍ B. LocalIntranet ❍ C. Internet ❍ D. Nothing Answer C is correct. The PieChart assembly is a member of code groups that belong to different levels. Across levels, the permission set granted to an assembly is the intersection of all the permission sets of the levels. Therefore, the intersection of the FullTrust, LocalIntranet, and Internet permission sets is the Internet permission set. Question 6 Which of the following are valid permission object types? (Select all that apply.) ❑ A. Code-based ❑ B. Group-based ❑ C. Role-based ❑ D. User-based ❑ E. Identity Answers A, C, and E are correct. The .NET Framework groups permissions into three object types: code-based, role-based, and identity. Answer B is incorrect because there is not a defined group-based security object type— group-based access control is referred to as role-based security. Answer D is incorrect because there is no defined user-based security object type. 343 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring . . . . . . .a .Windows . . . . . Application . . . . . . Question 7 You have created an application that might be exposed to anonymous access, and you want to ensure that only other code modules that have a specific set of permissions can use your application. Which of the following SecurityAction values would be most appropriate? ❑ A. RequestMinimum ❑ B. RequestOptional ❑ C. RequestRefuse ❑ D. Demand Answer D is correct. The Demand security action specifies that only code modules that have the specified permissions can call your application. Answer A is incorrect because the RequestMinimum security action is used to verify that the calling code has at least the minimum permissions specified. Answer B is incorrect because the RequestOptional security action is used to check whether the calling code has some optional, but not strictly required, permissions. Answer C is incorrect because the RequestRefuse security action is used to restrict the possible permissions that your application will have. It is a good idea to configure a RequestRefuse in an anonymous-access application, but it is not the best answer for the proposed requirement. Question 8 Which of the following statements is not correct with respect to the security permissions in the Microsoft .NET Framework? ❍ A. Code access security permissions specify whether a user has the access to execute given code. ❍ B. Identity security permissions specify that the given code has credentials that support a particular kind of identity. ❍ C. Role-based security permissions specify whether a user has a particular identity that is required to access the given code. ❍ D. If you place a demand on a particular security permission on your code, all code that uses your code must have that security permission to run. Answer A is correct. Code access security permissions specify whether a particular code can access a protected resource or can perform a protected operation. Answers B, C, and D are true for the security permissions in the .NET Framework. 344 Chapter 15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 9 Which of the following default permissions sets should be used to grant all permissions except the permission to skip security checks? ❍ A. Execution ❍ B. Internet ❍ C. LocalIntranet ❍ D. FullTrust ❍ E. Everything Answer E is correct. The Everything permission set includes all permissions except the permission to skip security checks. Answers A, B, and C are incorrect because the Execution, Internet, and LocalIntranet permission sets do not have sufficient permissions to meet the requirement. Answer D is incorrect because the FullTrust permission grants all permissions, including the permission to skip security checks. Question 10 Your application includes several ASP.NET components. Which type of authorization should you use to allow these components to use Windows authentication? ❍ A. Forms-based ❍ B. Windows ❍ C. Microsoft Passport ❍ D. Custom Answer B is correct. The Windows method of authorization allows ASP.NET applications to use the built-in Windows authentication available within IIS. Answer A is incorrect because a forms-based authorization method can be used to prompt a user for credentials but would not function automatically with the user’s Windows account. Answer C is incorrect because the Passport service is used for authorization through a centralized service rather than through integrated Windows authentication. Answer D is incorrect because it is not necessary to create a custom authorization method; the Windows authorization method will suffice. 345 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring . . . . . . .a .Windows . . . . . Application . . . . . . Need to Know More? Kalani, Amit. MCAD/MCSD Training Guide: Developing and Implementing Windows-Based Applications with Microsoft Visual C# .NET and Microsoft Visual Studio .NET, Exam 70-316. Que Certification, 2003. LaMacchia, Brian A. et al. .NET Framework Security. AddisonWesley, 2002. Visual Studio .NET how-to resources: http://msdn.microsoft. com/howto/visualstudio.asp. 16 Sample Test #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Do not read Chapters 16–19 until you have learned and practiced all the material presented in the earlier chapters of this book. These chapters serve a special purpose: They are designed to test whether you are ready to take Exam 70-316. In these chapters, you will find two sample exams. Each sample exam is followed by an answer key and a brief explanation of correct answers, along with explanation as to why the other answers are not correct. Reading these chapters before other chapters is like reading the climax of a story and then going back to find out how the story arrived at that ending. Of course, you don’t want to spoil the excitement, do you? How to Take the Sample Exams Each sample exam in this book consists of 60 questions; you should complete an exam within 150 minutes. The number of questions and the time duration in the actual exam might vary but should be close to this number. After you have studied the material presented in the earlier chapters of this book, you should take Sample Test #1 to check how prepared you are. After you have completed the sample exam, evaluate yourself using the answer key in Chapter 17, “Answer Key for Sample Test #1.” When you evaluate yourself, note the questions that you answered wrong, identify their corresponding chapters in the book, and then read and understand that material before taking Sample Test #2. After you take Sample Test #2, evaluate yourself again, and reread the material corresponding to any wrong answers. Finally, repeat both the sample exams until you can correctly answer all the questions. Information in the following sections helps you in taking the sample exam and then evaluating yourself. Exam-Taking Tips You take these sample exams on your own, but I strongly suggest that when you take this practice exam, you treat it just as you would the actual exam at the test center. Use the following tips to get the maximum benefit from the sample exams. ➤ Before you start, create a quiet, secluded environment where you are not disturbed for the duration of the exam. ➤ Provide yourself a few empty sheets of paper before you start. Use some of these sheets to write your answers, and use the others to organize your thoughts. At the end of the exam, use your answer sheet to evaluate your exam with the help of the answer key that follows the sample exam. 349 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. ➤ Don’t use any reference material during the exam. ➤ Some of the questions are vague and require you to make deductions to come up with the best possible answer from the possibilities given. Others are verbose, requiring you to read and process a lot of information before you reach the actual question. ➤ As you progress, keep track of the elapsed time and make sure that you’ll be able to answer all the questions in the given time limit. 350 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Sample Exam 1 Question 1 You have created a DataSet that contains a single DataTable object named Customers. The Customers DataTable has all of the rows and columns from the Customers table in your database. You would like to bind only selected columns from the Customers table to a DataGrid control. You want a solution that requires minimum programming, and you want to have minimum impact on the performance of SQL Server. How should you proceed? ❍ A. Create a second DataTable in the DataSet. Copy the desired data to the second DataTable. Bind the second DataTable to the DataGrid. ❍ B. Create a Command object to retrieve the desired columns from the DataTable. Bind the Command object to the DataGrid. ❍ C. Bind the DataGrid to the entire DataTable. Use the Width property of the columns in the DataGrid to hide the undesired columns by setting them to 0 width. ❍ D. Create a DataView that retrieves only the desired rows from the DataTable. Bind the DataGrid to the DataView. Question 2 Your application includes a SqlDataAdapter object named sqlDataAdapter1 that was created by dragging and dropping the Customers table from a database to your form. Your application also includes a DataSet named dsCustomers1, based on this SqlDataAdapter. What line of code should you use to load the data from the database into the DataSet? ❍ A. dsCustomers1= sqlDataAdapter1.Fill(“Customers”); ❍ B. sqlDataAdapter1.Fill(“dsCustomers1”, “Customers”); ❍ C. sqlDataAdapter1.Fill(dsCustomers1, “Customers”); ❍ D. sqlDataAdapter1.Fill(dsCustomers1); 351 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 3 You have recently deployed an expense-reporting system in your company. The application relies heavily on its SQL Server database. All employees in the company have identical access permissions to the database. You have created the application in such a way that it uses each employee’s logon name and password in the connection string to connect to SQL Server. Users of the application consistently report slow performance of the application. Your task is to optimize the performance of this application. You noted that another application, which uses the same SQL Server database, is having good performance. Which one of the following steps will you take? ❍ A. Compile the application to native code using ngen.exe. ❍ B. Run the SQL Server Index Tuning Wizard. ❍ C. Increase the maximum size of the connection pool. ❍ D. Use same connection strings for all users. Question 4 You are developing a Windows-based application named VerifyOrders. The VerifyOrders application receives data from the Orders application in XML format. The VerifyOrders application enables its users to review the orders and make any required changes. When the users are finished reviewing the orders, the VerifyOrders application must create an output XML file, which is returned to the Orders application. The output XML file must contain the original as well as the changed values. Which of the following options will you choose to create such an output XML file? ❍ A. Call the DataSet.WriteXmlSchema() method and pass an XmlWriter object as a parameter. ❍ B. Call the DataSet.WriteXml() method and set the value for the XmlWriteMode parameter to IgnoreSchema. ❍ C. Call the DataSet.WriteXml() method and set the value for the XmlWriteMode parameter to WriteSchema. ❍ D. Call the DataSet.WriteXml() method and set the value for the XmlWriteMode parameter to DiffGram. 352 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 5 You are writing a Visual C# .NET Windows application that executes several stored procedures to update a SQL Server database. You use database transactions to ensure that either all updates to the database succeed or the changes are rolled back in case of an error. You used the following code segment to create the database connection and the transaction object in your program: SqlConnection sqlConnection1 = new SqlConnection (strConnString); sqlConnection1.Open(); SqlCommand sqlCommand1 = new SqlCommand(); SqlTransaction sqlTrans; You need to prevent other users from updating or inserting rows into the database until the transaction is complete. Which of the following statements enables you to fulfill this requirement? ❍ A. sqlTrans = sqlConnection1.BeginTransaction(IsolationLevel. ➥ReadCommitted); ❍ B. sqlTrans = sqlConnection1.BeginTransaction(IsolationLevel. ➥Serializable); ❍ C. sqlTrans = sqlCommand1.BeginTransaction(IsolationLevel. ➥ReadCommitted); ❍ D. sqlTrans = sqlCommand1.BeginTransaction(IsolationLevel. ➥Serializable); 353 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 6 You need to develop a Windows application that exports the content of the Customers table to an XML file. The exported XML file will be used by a marketing company for various customer-relation programs. The marketing company requires that customer data be exported to the XML file in the following format: <Customers CustomerID=”ALFKI” ContactName= ”Maria Anders” Phone=”030-0074321” /> <Customers CustomerID=”ANATR” ContactName= ”Ana Trujillo” Phone=”(5) 555-4729” /> Which of the following code segments would you use to export the Customers table to the XML format in the specified format? ❍ A. foreach(DataColumn c in dataSet1.Tables[“Customers”]. ➥Columns) { c.ColumnMapping = MappingType.Attribute; } dataSet1.WriteXml(“Customers.xml”); ❍ B. foreach(DataColumn c in dataSet1.Tables[“Customers”]. ➥Columns) { c.ColumnMapping = MappingType.Element; } dataSet1.WriteXml(“Customers.xml”); ❍ C. foreach(DataColumn c in dataSet1.Tables[“Customers”]. ➥Columns) { c.ColumnMapping = MappingType.Attribute; } dataSet1.WriteXml(“Customers.xml”, XmlWriteMode. ➥WriteSchema); ❍ D. foreach(DataColumn c in dataSet1.Tables[“Customers”]. ➥Columns) { c.ColumnMapping = MappingType.Element; } dataSet1.WriteXml(“Customers.xml”, XmlWriteMode. ➥WriteSchema); 354 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 7 You are developing a Windows form application that processes data from a SQL Server 7.0 database. The application reads the data from the database in a forward-only way and does not perform any update operation. You use the System.Data.SqlClient.SqlConnection object to connect to the SQL Server database. You then use a System.Data.SqlClient.SqlCommand object to run a stored procedure and retrieve the results into a System.Data.SqlClient.SqlDataReader object. The application reads two fields from each row of data, and concatenates their values into a string variable. What can you do to optimize this application? ❍ A. Replace the SqlConnection object with an OleDbConnection object. ❍ B. Replace the stored procedure with a SQL statement. ❍ C. Replace the SqlDataReader object with a DataSet object. ❍ D. Replace the String variable with a StringBuilder object. Question 8 Your application uses a SqlDataReader object to retrieve patient information from a medical records database. When you find a patient who is currently hospitalized, you want to read the names of the patient’s caregivers from the same database. You have created a second SqlDataReader object, based on a second SqlCommand object, to retrieve the caregiver information. When you call the ExecuteReader() method of the SqlCommand object, you get an error. What is the most likely cause of this error? ❍ A. You are using the same SqlConnection object for both SqlDataReader objects, and the first SqlDataReader is still open when you try to execute the SqlCommand. ❍ B. You must use a SqlDataAdapter object to retrieve the caregiver information. ❍ C. You must use the OleDbDataReader object to retrieve information instead of the SqlDataReader object. ❍ D. You are using the ExecuteReader() method of the SqlCommand object, but you should be using the ExecuteScalar() method instead. 355 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 9 Your application retrieves data from the Customers and Orders tables in a database by using a view named vwCustOrders. This view is used as the CommandText for the SelectCommand of a DataAdapter object. The application uses the Fill() method of this DataAdapter to fill a DataSet. The DataSet is bound to a DataGrid control. Users report that changes they make to data displayed on the DataGrid are not saved to the database. What could be the problem? ❍ A. The DataGrid control does not support editing data from a database. ❍ B. You cannot update a DataSet that’s based on a view. ❍ C. The DataGrid control does not support two-way data binding. ❍ D. Your application does not call the Update() method of the DataAdapter object. Question 10 You use Visual C# .NET to develop a Windows application that will be used by the customer service department. Your application receives data from the Orders application. Users of your application get calls from the customers to make changes to their orders. You write the code that enables them to make the changes to the data, but now you want to write code that sends the changed records back to the Orders application. Which of the following methods should you use to accomplish this requirement? ❍ A. DataSet.Clone() ❍ B. DataSet.Copy() ❍ C. DataSet.GetChanges() ❍ D. DataSet.Merge() 356 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 11 You develop a Windows application that enables users to add new regions in the SQL Server Sales database. You use the following Visual C# .NET code segment to add regions: SqlCommand command = new SqlCommand(null, sConn); command.CommandText = “INSERT INTO Region (RegionID, “ + “RegionDescription) VALUES (@rid, @rdesc)”; command.Parameters.Add ( “@rid”, rid); command.Parameters.Add ( “@rdesc”, rdesc); command.ExecuteNonQuery(); Each time the users use this application, they can add several regions. Which of the following options will you use to ensure optimum performance of the application? ❍ A. Use the SqlCommand.ExecuteReader() method instead of the SqlCommand.ExecuteNonQuery() method. ❍ B. Call the SqlCommand.Prepare() method before each call to the SqlCommand.ExecuteNonQuery() method. ❍ C. Call the SqlCommand.Prepare() method before the first call to the SqlCommand.ExecuteNonQuery() method. ❍ D. Call the SqlCommand.ResetCommandTimeout() method before each call to the SqlCommand.ExecuteNonQuery() method. 357 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 12 You develop a Windows application named ProcessOrder using Visual C# .NET. Your application receives orders from customers in an XML file named Orders.xml. The Orders.xml file does not include any schema. Which of the following methods should you use to load the data from Orders.xml into a DataSet object? (Select two.) ❑ A. DataSet ds = new DataSet(“Orders”); ds.ReadXml(“Orders.xml”, XmlReadMode.Auto); ❑ B. DataSet ds = new DataSet(“Orders”); ds.ReadXml(“Orders.xml”, XmlReadMode.DiffGram); ❑ C. DataSet ds = new DataSet(“Orders”); ds.ReadXml(“Orders.xml”, XmlReadMode.Fragment); ❑ D. DataSet ds = new DataSet(“Orders”); ds.ReadXml(“Orders.xml”, XmlReadMode.InferSchema); ❑ E. DataSet ds = new DataSet(“Orders”); ds.ReadXml(“Orders.xml”, XmlReadMode.ReadSchema); 358 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 13 You are a Microsoft .NET developer for a large warehousing company. You need to develop an application that helps users manage the inventory. Inventory data is stored in a SQL Server 2000 named Warehouse2 in a database named Inventory. You use a SqlConnection object and Windows Integrated authentication to connect with the Inventory database. Which of the following connection strings should you choose in your Visual C# .NET program? ❍ A. “Provider=SQLOLEDB;Data Source=WareHouse2; ➥Initial Catalog=Inventory; ➥Integrated Security=SSPI;” ❍ B. “Provider=SQLOLEDB;Data Source=WareHouse2; ➥Initial Catalog=Inventory; ➥user id=sa;password=Ti7uGf1;” ❍ C. “data source=WareHouse2; ➥initial catalog=inventory; ➥Trusted_Connection=true;” ❍ D. “data source=WareHouse2;user id=sa; ➥password=Ti7uikGf1; ➥initial catalog=inventory;” 359 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 14 The application that you’re designing should display employee information on a DataGrid control by using complex data binding. Your database contains a table of departments and a table of employees. The Employees table has a foreign key that points back to the Departments table. The application should communicate with the database via a slow WAN link. The list of departments changes approximately once every two months. The form should display all the employees from a single department. Although users will view only one department at a time, they will frequently need to view several departments during the course of a session with the application. You want to write minimum code. How should you design the filtering for this form? ❍ A. Build one view on the server for each department. At runtime, have the program use the appropriate view to retrieve the requested department. ❍ B. Each time the user requests a department, retrieve all the data into a DataSet object. Then delete all rows from the DataSet object that do not apply to this department. ❍ C. Retrieve all the data into a DataSet object. Use a DataView object, with its RowFilter property set at runtime, to retrieve individual departments as needed. ❍ D. Build one form for each department. Each form should be based on a view that returns only the employees for that department. At runtime, open the appropriate form. Hide the form when the user is done so that it can be opened more quickly if it’s needed a second time. 360 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 15 You are working with a complex form that uses Panel controls to organize a large amount of data. The form displays information from six different data sources. Some of the panels contain data from more than one data source. You have added navigation buttons to scroll through the data in one particular data source. The navigation buttons increment and decrement the Position property of a CurrencyManager object. You test the form, and the buttons do not appear to scroll the data in that data source. What could be the problem? (Choose the best two answers.) ❑ A. There are too many controls on the form, so your code is not being executed. ❑ B. You retrieved the CurrencyManager object through the form’s BindingContext object, but the Panel control has its own BindingContext object. ❑ C. This particular CurrencyManager object does not support a Position property. ❑ D. The BindingContext object that you’re using has more than one CurrencyManager object, and you’re working with the wrong one. 361 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 16 You have to develop a Windows application that will be used by the Ordertracking system of your company. The application contains a form that displays a list of orders placed by the customers for the past year. When the employee selects an order from the list box, you need to display the order status and other information of the selected order in a set of text boxes. You have retrieved the order details in a DataSet object named dsOrders. The dsOrders object contains a table named Order that contains the order status and other information. You are required to bind the text box controls with the information from the DataSet. Which line of code would you use to bind the text box control to the field named OrderStatus in the Order table? ❍ A. txtStatus.DataBindings.Add(“Text”, dsOrders, “Order. ➥OrderStatus”); ❍ B. txtStatus.DataBindings.Add(“Text”, dsOrders, “”); ❍ C. txtStatus.DataBindings.Add(“Text”, dsOrders, “OrderStatus”); ❍ D. txtStatus.DataBindings.Add(“Tag”, dsOrders, “Order. ➥OrderStatus”); ❍ E. txtStatus.DataBindings.Add(“Tag”, dsOrders, “”); ❍ F. txtStatus.DataBindings.Add(“Tag”, dsOrders, “OrderStatus”); 362 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 17 You develop a Windows-based application that displays supplier data in a DataGrid control. The supplier data is stored in a table named Suppliers within the dsSuppliers DataSet object. The primary key for the Suppliers table is the SupplierID column. You need to display the supplier data in the DataGrid control in ascending order of the field named State. Which of the following code segments can you use? (Select two.) ❑ A. DataView dvSuppliers = new DataView(dsSuppliers.Tables[“Suppliers”]); dvSuppliers.Sort = “State ASC”; dataGrid1.DataSource = dvSuppliers; ❑ B. DataView dvSuppliers = new DataView(dsSuppliers.Tables[“Suppliers”]); dvSuppliers.Sort = “ASC”; dataGrid1.DataSource = dvSuppliers; ❑ C. DataView dvSuppliers = new DataView(dsSuppliers.Tables[“Suppliers”]); dvSuppliers.ApplyDefaultSort = true; dataGrid1.DataSource = dvSuppliers; ❑ D. DataView dvSuppliers = new DataView(dsSuppliers.Tables[“Suppliers”]); dvSuppliers.Sort = “State”; dataGrid1.DataSource = dvSuppliers; 363 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 18 You need to develop a database application that interacts with the Oracle database. You need to write code to return the total number of customers from the database as quickly as possible. Which of the following actions should you take? ❍ A. Write an ad-hoc SQL query to return the total number of customers. Use the OleDbCommand.ExecuteScalar() method to execute the SQL statement. ❍ B. Write an ad-hoc SQL query to return the total number of customers. Use the OleDbCommand.ExecuteReader() method to execute the SQL statement. ❍ C. Write an ad-hoc SQL query to return the total number of customers. Use the OleDbDataAdapter.Fill() method to execute the SQL statement. ❍ D. Create a stored procedure to return the total number of customers. Use the OleDbCommand.ExecuteScalar() method to execute the stored procedure. ❍ E. Create a stored procedure to return the total number of customers. Use the OleDbCommand.ExecuteReader() method to execute the stored procedure. ❍ F. Create a stored procedure to return the total number of customers. Use the OleDbDataAdapter.Fill() method to execute the stored procedure. 364 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 19 You are developing a Windows form using Visual C# .NET. You name the form as form1 and place a TextBox control named textBox1 on the form. The KeyPreview property of form1 is set to true. You write the following event handlers for form1: private void form1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if(e.KeyChar == ‘a’) { Debug.WriteLine(“Handled by form”); e.Handled = true; } } private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if(e.KeyChar == ‘a’) { Debug.WriteLine(“Handled by textbox”); } } private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if(e.KeyCode == Keys.A) { Debug.WriteLine(“Handled by textbox”); } } When testing this form, the user presses the A key with the focus in textBox1. What is the output generated from the event handlers? ❍ A. Handled by form ❍ B. Handled by textbox Handled by form Handled by textbox ❍ C. Handled by textbox Handled by form ❍ D. Handled by textbox 365 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 20 Your form requires a control that behaves exactly like a TextBox control, except that you want to display the text in red. You want to write minimum code. From which of the following classes should you derive this control? ❍ A. UserControl ❍ B. TextBox ❍ C. Control ❍ D. Component Question 21 You want to give end users the capability to customize your application so that it fits better with their corporate look and feel. In particular, you want to specify the text that appears in the title bar of the main menu form. You want to write minimum code to do this. How would you add this capability to your application? ❍ A. Supply full source code with your application and tell users that they can edit the text and rebuild the application. ❍ B. Let the user edit the text in the Registry and use the Microsoft.Win32.Registry class to retrieve the value that they save. ❍ C. Make the Text property of the form a dynamic property, and provide an XML file that the user can edit to set the value of the property. ❍ D. Run code in the form’s Load event to retrieve the form’s title from a text file by using a FileStream object. Question 22 Your department is responsible for maintaining a variety of accounting applications. You’ve been assigned the task of creating a standard control to represent credit and debit accounts. The control will be made up of a collection of TextBox and ComboBox controls. You want to write minimum code. On which class should you base this control? ❍ A. Control ❍ B. UserControl ❍ C. Form ❍ D. Component 366 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 23 Your form enables the user to enter a telephone number into a TextBox control named txtPhone. You use the Validating event of this control to check that the phone number is in the correct format. If the phone number is not in the correct format, you do not allow the focus to leave the txtPhone TextBox control. The form also includes a Button control and a btnCancel, to cancel the data entry action. The user should be able to click this button at any time, even when there is invalid data in the textbox. What should you do to ensure this? ❍ A. Set the CausesValidation property of the TextBox control to true. ❍ B. Set the CausesValidation property of the Button control to true. ❍ C. Set the CausesValidation property of the TextBox control to false. ❍ D. Set the CausesValidation property of the Button control to false. Question 24 Your application includes a CheckBox control with its ThreeState property set to true. Your form displays this control in the indeterminate state. You want to take an action only if the user checks the CheckBox. Which code snippet should you use? ❍ A. if (chkTriState.CheckState == CheckState.Checked) { // Take action } ❍ B. if (chkTriState.Checked) { // Take action } ❍ C. if (chkTriState.CheckState == CheckState.Indeterminate) { // Take action } ❍ D. if (chkTriState.CheckState == CheckState.Unchecked) { // Take action } 367 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 25 The main menu form of your application uses the System.Drawing objects to draw your company’s logo on the background of the form. You want to redraw the logo whenever the form is resized so that it always fills the entire form. You want a responsive interface, but you want to write minimum code to get it. Which of the following options should you choose? ❍ A. Use a Timer control to call the Invalidate() method periodically. ❍ B. Call the Invalidate() method within an event handler for the form’s Resize event. ❍ C. Call the Invalidate() method within an event handler for the form’s Paint event. ❍ D. Set the form’s ResizeRedraw property to true. Question 26 You are designing a Windows application with a variety of controls on its user interface. Some controls will be infrequently used. For these controls, you do not want the user to be able to tab into the control, but the user should still be able to activate the control by clicking in it. Which of the following options should you use? ❍ A. Set the TabIndex property of the control to 0. ❍ B. Set the TabIndex property of the control to –1. ❍ C. Set the TabStop property of the control to false. ❍ D. Set the Enabled property of the control to false. 368 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 27 Your form uses Label controls to convey information. When the text in the Label control represents a higher than average value, you want to display it in bold; when the text in the Label control represents a value that requires the user’s attention, you want to display it in italics. If both conditions are true, you want to display the text in bold italics. How should you set the Italic FontStyle for the control when the value requires attention so that it adds italics whether or not the font is already bold? ❍ A. lblSampleText.Font.Style & FontStyle.Italic ❍ B. lblSampleText.Font.Style ^ FontStyle.Italic ❍ C. lblSampleText.Font.Style | FontStyle.Italic ❍ D. lblSampleText.Font.Style | (FontStyle.Underline & ➥FontStyle.Bold) Question 28 Your application’s main form contains two different Button controls named btnA and btnB. When the user clicks either of these controls, or when the user moves the mouse over these controls, you want to run code to display a message on the form. The message is identical in all cases. You want to write minimum code. How should you structure your code to fulfill this requirement? ❍ A. Write four separate event handlers, one each for the Click event of btnA, the MouseMove event of btnA, the Click event of btnB, and the MouseMove event of btnB. ❍ B. Write two event handlers. The first will handle both Click events, and the second will handle both MouseMove events. ❍ C. Write two event handlers. The first will handle the Click and MouseMove events for btnA, and the second will handle the Click and MouseMove events for btnB. ❍ D. Write a single event handler to handle the Click and MouseMove events of both controls. 369 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 29 You use Visual Studio .NET to develop an accounting application for your company. You need to develop a set of classes that contains classes and methods for accounting-related business rules. Several applications in the company will use these classes. Other developers should be able to instantiate these classes, but you do not want those developers to create derived classes based on these classes. Which of the following options should you choose to create such a class? (Select two.) ❑ A. Create a Windows Control Library project to package your classes. ❑ B. Create a Windows Service project to package your classes. ❑ C. Create a Class Library project to package your classes. ❑ D. Use the following class-declaration template to define your classes: public abstract class Class1 ❑ E. Use the following class-declaration template to define your classes: public sealed class Class1 ❑ F. Use the following class-declaration template to define your classes: private abstract class Class1 ❑ G. Use the following class-declaration template to define your classes: private sealed class Class1 Question 30 You are developing an accounting application that includes a class named Transaction. The Transaction class is inherited by subclasses such as DepositTransaction and PaymentTransaction. The Transaction class includes a method named VerifyChecksum(). The VerifyChecksum() method should be available to the Transaction class and to all classes derived from the Transaction class, but not to any other classes in the application. Which access modifier should you use in the declaration of the VerifyChecksum() method? ❍ A. protected ❍ B. public ❍ C. private ❍ D. internal 370 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 31 You develop a Windows application that helps manage production schedules for a manufacturing company. This application uses a library named Production.dll. You anticipate that, in the future, some other applications might use classes from the Production.dll library. You might also need to maintain multiple versions of Production.dll. Which of the following options should you choose to deploy Production.dll? (Select two.) ❑ A. Sign Production.dll with sn.exe. ❑ B. Sign Production.dll with signcode.exe. ❑ C. Install Production.dll in the Windows system directory. ❑ D. Install Production.dll in the Global Assembly Cache. Question 32 You are designing a custom control for use in industrial automation. This control will monitor a serial port and raise events based on data sent in through the serial port. This control will be hosted on forms, but it does not require any visual representation at runtime. From which class should you derive this control? ❍ A. Control ❍ B. UserControl ❍ C. Form ❍ D. Component 371 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 33 You are developing a Visual C# .NET application. Your application has two classes, named Person and Employee. The Employee class is derived from the Person class, as shown in the following code: 01: public class Person 02: { 03: public virtual void GetInfo() 04: { 05: //Code to print person information 06: } 07: } 08: class Employee: Person 09: { 10: public override void GetInfo() 11: { 12: // Calling the base class GetInfo method: 13: 14: } 15: } In the Employee class, you need to write code to call the GetInfo() method of the Person class and then do some additional processing. To accomplish this, which of the following lines of code should you insert at Line 13? ❍ A. Person.GetInfo(); ❍ B. this.GetInfo(); ❍ C. base.GetInfo(); ❍ D. Person:GetInfo(); 372 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 34 Your colleague is writing Visual C# .NET code to understand how exception handling works. She has written the following code, which handles the Click event of a Button control that is placed on a Windows form: private void button1_Click(object sender, _ System.EventArgs e) { Int32 i, j; try { i = 0; j = 5 / i; Debug.WriteLine(“Result = “ + j.ToString()); } catch (ArithmeticException aex) { Debug.WriteLine(“Arithmetic Exception”); goto EndIt; } catch (Exception ex) { Debug.WriteLine(“Unknown Exception”); goto EndIt; } finally { Debug.WriteLine(“Cleaning up”); i = 0; j = 0; } EndIt: } Which of the following output should you expect when the button is clicked? ❍ A. Arithmetic Exception Unknown Exception ❍ B. Arithmetic Exception ❍ C. Result = Arithmetic Exception Cleaning Up ❍ D. Arithmetic Exception CleaningUp 373 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 35 You develop a Windows-based application that retrieves data from a SQL Server database named Customers. You use the System.Data.SqlClient data provider to connect with the database. You need to log the severity level of the error returned from the SQL Server .NET data provider. Which of the following options should you choose? ❍ A. Catch the SqlException, which is thrown by the SQL Server .NET data provider. Examine the Class property of the SqlException object. ❍ B. Catch the SqlException, which is thrown by the SQL Server .NET data provider. Examine the Source property of the SqlException object. ❍ C. Catch the SqlException, which is thrown by the SQL Server .NET data provider. Examine the Server property of the SqlException object. ❍ D. Catch the SqlException, which is thrown by the SQL Server .NET data provider. Examine the State property of the SqlException object. Question 36 You need to develop a Windows application that accesses the Orders XML Web Service provided by your company’s business partner. You know the URL of the Web Service. How can you generate client-side proxy classes for a Web Service? (Select two.) ❑ A. Use a proxy tool such as the .NET WebService Studio tool. ❑ B. Use the Web Services Description Language tool. ❑ C. Use the Web Services Discovery Tool. ❑ D. Set a Web reference to point to the Web Service. Question 37 You are asked to write a program that alerts users about the latest traffic and weather conditions in their area. You use Visual Studio .NET to write such a program. To gather the traffic and weather data, your application calls a few Web Services. Users of your application complain that the user interface of the application is unresponsive while the traffic and weather information is being retrieved. Which of the following steps should you take to fix this problem? ❍ A. Move the application to a faster computer. ❍ B. Install a faster link to the Internet. ❍ C. Install more memory in the computer. ❍ D. Use asynchronous calls to invoke the Web Service. 374 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 38 You work as a Visual C# .NET programmer for a multinational marketing company. You have been given a task to create a localized version of a Windows form for use in countries where the text is read from right to left. You need to make sure that all the controls in the form are aligned properly for the ease of local users. You need to make minimum changes in the code. Which of the following options should you choose to accomplish this task? ❍ A. Set the RightToLeft property of each control on the Windows form to true. ❍ B. Set the RightToLeft property of each control on the Windows form to RightToLeft.Yes. ❍ C. Set the RightToLeft property of the Windows form to true. ❍ D. Set the RightToLeft property of the Windows form to RightToLeft.Yes. Question 39 You are responsible for maintaining a COM component that is used by numerous applications throughout your company. You are not yet ready to migrate this COM component to .NET–managed code, but you need to make it available to an increasing number of other projects that are being developed under the .NET Framework. What should you do? ❍ A. Set a direct reference to the existing COM component from each .NET project. ❍ B. Use the Type Library Importer tool to create and sign an assembly that will use the COM component. Place the generated assembly in the Global Assembly Cache. ❍ C. Obtain a Primary Interop Assembly for the COM component. ❍ D. Set a direct reference from a single .NET project to the COM component. Include this project in each solution that must make use of the component. 375 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 40 You use Visual C# .NET to develop a Windows form that allows users to enter readings from laboratory test results. You want to display help to the user in a pop-up window when the user presses the F1 key. The help should be contextsensitive--that is, the help text displayed should correspond to the form element that currently has the focus. You have decided that the help text will be associated with each control on the form. You choose to use the HelpProvider component to display help. Which of the following methods of the HelpProvider component should you invoke to set the associated help text? ❍ A. SetHelpKeyWord() ❍ B. SetHelpNavigator() ❍ C. SetHelpString() ❍ D. SetShowHelp() Question 41 Your corporate guidelines insist that the documents generated by programs should be printed on legal-size paper. Unfortunately, users sometimes use the Printer Setup dialog box to switch to letter-size paper for their own convenience. Which event of the PrintDocument class can you use to check and (if necessary) change the paper tray? ❍ A. BeginPrint ❍ B. EndPrint ❍ C. PrintPage ❍ D. QueryPageSettings 376 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 42 You use Visual Studio .NET to create an application that interacts with a Microsoft SQL Server database. You create a stored procedure to calculate the monthly wireless Internet access charges for the customers. You name the stored procedure as CalculateAccessCharges. When you run the program, you observe that the results from the stored procedure are not as expected. You want to debug the CalculateAccessCharges stored procedure to find the error. You want to minimize the time and efforts involved in debugging. Which of the following actions should you take? ❍ A. Use the Tools, Debug Processes menu to attach a debugger to the SQL Server and then step into the CalculateAccessAcharges stored procedure. ❍ B. Place a breakpoint in the CalculateAccessCharges stored procedure and then use the Debug, Step Into menu to step into the Visual C# program that calls the stored procedure. ❍ C. Use the SQL Server Print command to print the calculated values in the stored procedure. ❍ D. Use the Debug.WriteLine() method to print the calculated values in the stored procedure. Question 43 You develop a Visual Studio .NET application that helps the shipping department create mix-and-match pallets. Users of the application complain that the numbers of cases in the pallet is not displayed correctly. To find the location of the error, you place a breakpoint on the GetCasesInPallet() method. However, when you execute the program by selecting Debug, Execute, the execution does not break at the breakpoint. Which of the following actions should you take to resolve this problem? ❍ A. Select Exceptions from the Debug menu. ❍ B. Select Enable All Breakpoints from the Debug menu. ❍ C. Select Build, Configuration Manager and set the project’s configuration to Debug. ❍ D. Select Build, Configuration Manager and set the project’s configuration to Release. 377 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 44 Your application is failing when a particular variable equals 117. Unfortunately, you cannot predict when this will happen. You want to write minimal code. Which debugging tool should you use to investigate the problem? ❍ A. Locals window ❍ B. Output window ❍ C. Immediate window ❍ D. Conditional breakpoint Question 45 You need to develop an application that performs regression analysis on sales data. You start working on a code sample that you borrowed from your colleague. You encounter several compile-time errors when you customize the code sample according to your requirements. You want to easily locate each error and correct it as quickly as possible. Which of the following actions should you take? (Select the best answer.) ❍ A. Locate each error using the Task List window, and fix them all before recompiling the program. ❍ B. Locate each error using the Output window, and fix them all before recompiling the program. ❍ C. Locate each error using the Find Results window, and fix them all before recompiling the program. ❍ D. Locate each error using the Immediate window, and fix them all before recompiling the program. 378 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 46 The Visual C# .NET project that you are developing contains the following API declaration: [DllImport(“kernel32.dll”, CharSet=CharSet.Auto)] public static extern int GetComputerName(String buffer, ref uint size); The project also contains code to use this API to display the computer name: public static void ShowName() { String buf = “”; UInt32 intLen=128; Int32 intRet; // Call the Win API method intRet = GetComputerName(buf, ref intLen); Console.WriteLine(“This computer is named “ + buf.ToString()); } You deploy this project and ask users to test it. Users report that no computer name is displayed. What should you do to resolve this problem? ❍ A. Use the ref keyword with the variable buf in the call to GetComputerName() API. ❍ B. Tell the users that their computers have no name set in their network properties. ❍ C. Replace the String object with the StringBuilder object in the code. ❍ D. Use the out keyword with the variable buf in the call to GetComputerName() API. 379 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 47 You use Visual C# .NET to create an assembly named Tracker.dll. Tracker.dll contains classes for tracking a shipment. You need to deploy the assembly on the target computer in such a way that it can be accessed by multiple .NET applications. Which of the following actions should you take? (Select all that apply.) ❑ A. Create a strong name for the assembly by using the Strong Name tool (sn.exe). ❑ B. Register the assembly using the Assembly Registration tool (regasm.exe). ❑ C. Use XCOPY to deploy the assembly to the Global Assembly Cache. ❑ D. Use XCOPY to deploy the assembly to the Windows system directory. ❑ E. Use a Setup and Deployment project to deploy the assembly to the Global Assembly Cache. ❑ F. Use a Setup and Deployment project to deploy the assembly to the Windows system directory. Question 48 You have deployed your .NET application to several computers in the PRODUCTION domain that are not used for development. Your own computer is in the DEVELOPMENT domain. There is a two-way trust relationship established between the PRODUCTION domain and the DEVELOPMENT domain. Users report problems with the running application. You want to attach to the remote process for debugging, but you are unable to do so. What could be the problem? ❍ A. The Machine Debug Manager (mdm.exe) is not installed on the computers in the PRODUCTION domain. ❍ B. Visual Studio .NET does not support cross-domain debugging. ❍ C. You cannot attach to a remote process that was compiled in the default Release configuration. ❍ D. You must add a switch to the application’s configuration file to enable remote debugging. 380 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 49 You use Visual C# .NET to develop an assembly that enables developers in your company to create pie charts in their applications. You name the assembly as PieChart.dll and package it as version 1.0.0, which is deployed into the GAC. After two months, you discover that there is a bug in the assembly. You fix the bug by releasing a new Version 1.0.1 of the assembly. You place the newly created assembly in the GAC. What will happen to the application written by other developers that use PieChart.dll? ❍ A. The applications using the PieChart.dll assembly will break because the applications will notice two versions of the assembly in the GAC and won’t know which one to execute. ❍ B. The applications using the PieChart.dll assembly will notice a new version of the assembly and will load the new version of the assembly and cause no problems. ❍ C. The applications using the PieChart.dll assembly will ignore the new version of the assembly in the GAC and will continue to use the older, buggy version of the assembly. ❍ D. The applications using the PieChart.dll assembly will be requested to select the desired assembly version to run for their application. Question 50 You use Visual C# .NET to develop a component that enables developers to create bar graphs in their applications. You name the component as BarGraph. The developers need to deploy the BarGraph component with each application that uses the component. How should you package the BarGraph component for deployment? ❍ A. Use a Cab project to package the BarGraph component. ❍ B. Use a Setup project to package the BarGraph component. ❍ C. Use a Web Setup project to package the BarGraph component. ❍ D. Use a Merge Module project to package the BarGraph component. 381 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 51 Your company uses Visual Studio .NET to create a Windows-based application that helps students learn geography. The application uses several graphics and media files to make the presentation interesting and informative for the students. You have been assigned to create a setup program for this application. Your installation program needs to target Windows XP computers with a full installation of Windows XP Service Pack 1. For ease in distribution and use, you need to package the setup program on a single CD-ROM. When you create the setup program, you note that the size of the resulting package is more than what you can fit on a CD. Which of the following steps should you take to accommodate the setup program on a single CD? (Select all that apply.) ❑ A. Select the Detected Dependencies folder of the Installer project. In the Properties window, select the Exclude property for the .NET Framework dependency and set it to true. ❑ B. Select the Detected Dependencies folder of the Installer project. In the Properties window, select the Exclude property for the .NET Framework dependency and set it to false. ❑ C. In the Deployment Project Properties dialog box, set the Package files property to In Cabinet File(s). ❑ D. In the Deployment Project Properties dialog box, set the Compression property to Optimized for Size. Question 52 You develop a Windows-based application using Visual Studio .NET. The application needs to be distributed to users via the Internet. You use Visual Studio .NET Setup and Deployment projects to package the application. When you test the software on a Windows XP machine, you observe that your name is being shown as the software publisher in the program support information in the Add or Remove Programs section of the Windows Controls Panel. You need to change the name so that your company’s name, instead of yours, is displayed in the support information. Which of the following properties of the deployment project should you change? ❍ A. Author ❍ B. Description ❍ C. SupportPhone ❍ D. SupportUrl 382 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 53 You have created a database-driven Windows application. Using Microsoft SQL Server, you have also generated an installation script for your database. This script is stored in a file named InstData.sql. You create a Setup project using Visual Studio .NET to deploy this application on your client’s computer. Which of the following actions should you take to create the database when deploying your application on the client’s machine? ❍ A. Create a component that derives from the Installer class. Override its Install() method to create the database. Add the component to the Install node of the Custom Actions Editor in the Setup project. ❍ B. Create a component that derives from the Installer class. Override its Install() method to create the database. Add the component to the Commit node of the Custom Actions editor in the Setup project. ❍ C. Copy the InstData.sql file to the Application folder on the file system on the target machine using the File System Editor. Add InstaData.sql to the Install node of the Custom Actions Editor in the Setup project. ❍ D. Create a component that derives from the Installer class. Override its Install() method to create the database. Add the component to the Launch Conditions Editor in the Setup project. Question 54 You work as a Visual Studio .NET developer for a big finance company on Wall Street. The chief information officer of the company has decided to take steps to increase the security in the organization so that malicious code cannot be executed. You have been asked to implement a security policy that enables users to execute applications locally and from the company’s intranet but that prevents them from executing code originating from the Internet. You want to complete this task with minimum efforts. Which of the following actions should you take? ❍ A. Modify the enterprise security policy. ❍ B. Modify the machine security policy. ❍ C. Modify the user security policy. ❍ D. Modify the application-domain security policy. 383 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 55 You develop a Windows-based application using Visual C# .NET. The name of the main executable file of your application is OrderHistory.exe. You use an XML-based application configuration file to configure the behavior of OrderHistory.exe. What should you name the application configuration file, and where should you deploy it for the application to function correctly? ❍ A. Name the application configuration file as OrderHistory.xml, and deploy it in the Windows\System32 directory. ❍ B. Name the application configuration file as OrderHistory.xml, and deploy it in the same directory as OrderHistory.exe. ❍ C. Name the application configuration file as OrderHistory.exe.config, and deploy it in the Windows\System32 directory. ❍ D. Name the application configuration file as OrderHistory.exe.config, and deploy it in the same directory as OrderHistory.exe. Question 56 You develop a Windows-based application using Visual C# .NET. Your code would like File I/O permission, but it can run without this permission. You plan to request the permission and trap the error if it is not granted. Which SecurityAction action should you use with the FileIOPermission object? ❍ A. SecurityAction.RequestMinimum ❍ B. SecurityAction.RequestOptional ❍ C. SecurityAction.Demand ❍ D. SecurityAction.RequestRefuse Question 57 You have used Visual C# .NET to develop a process-monitoring application. Your application can identify any process on the system that has a user interface and enable you to collect information about the process. Now you want to add code that can shut down the identified process as well. Which method should you use to shut down these processes? ❍ A. Process.Kill() ❍ B. Process.WaitForExit() ❍ C. Process.CloseMainWindow() ❍ D. Process.WaitForInputIdle() 384 Chapter 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 58 The configuration file of a Windows application has the following contents: <system.diagnostics> <switches> <add name=”BooleanSwitch” value=”-1” /> <add name=”TraceLevelSwitch” value=”33” /> </switches> </system.diagnostics> You are using the following statements to create switch objects in your code: BooleanSwitch booleanSwitch = new BooleanSwitch(“BooleanSwitch”, “Boolean Switch”); TraceSwitch traceSwitch = new TraceSwitch(“TraceLevelSwitch”, “Trace Switch”); Which of the following options is correct regarding the values of these switch objects? ❍ A. The booleanSwitch.Enabled property is set to false, and traceSwitch.Level is set to TraceLevel.Verbose. ❍ B. The booleanSwitch.Enabled property is set to true, and traceSwitch.Level is set to TraceLevel.Verbose. ❍ C. The booleanSwitch.Enabled property is set to false, and traceSwitch.Level is set to TraceLevel.Error. ❍ D. The booleanSwitch.Enabled property is set to false, and traceSwitch.Level is set to TraceLevel.Info. Question 59 You have added the following statement to the Load event handler of a singleform Windows application: Trace.Listeners.Add(new TextWriterTraceListener ➥(“TraceLog.txt”)); Which of the following statements are true with respect to program execution? (Select all that apply.) ❑ A. TextWriterTraceListener will listen to all messages generated by the methods of the Debug and Trace classes. ❑ B. TextWriterTraceListener will listen only to the messages generated by the methods of the Trace class. ❑ C. All the trace messages will be stored in a file named TraceLog.txt. ❑ D. The trace messages will be displayed in the output window while the program is run in either the Debug or the Release configurations. 385 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#1. Question 60 You want to control the tracing and debug output of a Windows-based application without recompiling your code. Which of the following classes will enable you to do this? ❍ A. TraceListener ❍ B. TraceSwitch ❍ C. Trace ❍ D. Debug 17 Answer Key for Sample Test #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388 Chapter 17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19. C 40. C 20. B 41. D 21. C 42. B 1. D 22. B 43. C 2. C 23. D 44. D 3. D 24. A 45. A 4. D 25. D 46. C 5. B 26. C 47. A and E 6. A 27. C 48. A 7. D 28. B 49. C 8. A 29. C and E 50. D 9. D 30. A 51. A and D 10. C 31. A and D 52. A 11. C 32. D 53. A 12. A and D 33. C 54. A 13. C 34. D 55. D 14. C 35. A 56. B 15. B and D 36. B and D 57. C 16. A 37. D 58. B 17. A and D 38. D 59. A, C, and D 18. D 39. B 60. B Answer Key Detailed Answers 1. The correct answer is D. The DataView class represents a data- bindable, customized view of a data table that is optimized for sorting, filtering, searching, editing, and navigating. Answers A and B are not correct because these actions will impact SQL Server with additional hits, thereby decreasing performance. Answer C is not correct because it is complicated and requires additional programming, and you were asked to present a solution that requires little programming. 389 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer . . . . .Key . . for . .Sample . . . . Test . . .#1. 2. The correct answer is C. Although answers C and D both use correct syntax of the Fill method, the question clearly states the name of the table; therefore, it is recommended to use the name of the table when filling the DataSet. Answer A is not correct because there is not an overload of the Fill method that accepts a single string parameter. Answer B is not correct because there is not an overload of the Fill method that accepts two string parameters. 3. The correct answer is D. Using the same connection string enables ADO.NET to reuse existing pooled database connections instead of creating new ones. This improves performance because creating new database connections is a costly operation. Answer B is not correct because another application that uses the same database is already performing well. Answer C is not correct because if different connection strings are used, each request for the connection will create a new connection pool; therefore, increasing the maximum size of the pool will not increase performance of the application. Answer A is not correct because users are facing slow performance consistently, not just during the first execution. 4. The correct answer is D because when you set the XmlWriteMode parameter of the DataSet.WriteXml method to DiffGram, the output contains both original and current values. Answer A is not correct because the DataSet.WriteXmlSchema method writes the DataSet structure as an XML Schema instead of writing XML data. Answers B and C are not correct because, although the DataSet.WriteXml method writes the DataSet as an XML file by setting the XmlWriteMode parameter to IgnoreSchema or WriteSchema, it writes only the current value of the data to the XML file. 5. The correct answer is B because IsolationLevel.Serializable places a range lock on the database, preventing other users from updating or inserting rows into the database until the transaction is complete. Answer A is not correct because IsolationLevel.ReadCommitted holds the lock while the data is being read, but data can be changed before the transaction is complete. Answers C and D are not correct because the BeginTransaction method is available for objects of the SqlConnection type but is not available for objects of the SqlCommand type. 6. The correct answer is A. The ColumnMapping property determines how a column’s values will be written when the WriteXml method is called on a DataSet to write output to an XML document. When you set the ColumnMapping property of a column to 390 Chapter 17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MappingType.Attribute, that column of the table is mapped to an XML attribute. Answer B is not correct because setting the ColumnMapping property of the column to MappingType.Element maps that column of the table to an XML element. Answers C and D are not correct because XmlWriteMode.WriteSchema specifies the WriteXml method to write the current contents of the DataSet as XML data, along with the relational structure as inline XSD schema. Writing an additional schema is not required in the question. 7. The correct answer is D. Strings in Visual C# .NET are immutable, so concatenating multiple values into a string requires deleting and recreating the string many times. The StringBuilder object is optimized for changing textual data. Answer A is not correct because the SqlConnection object is more optimized than OleDbConnection for accessing a SQL Server 7.0 database. Answer B is not correct because stored procedures have much higher performance than SQL statements. Answer C is not correct because, for a forward-only, read-only operation, the SqlDataReader object provides the best performance. 8. The correct answer is A. You can have only a single SqlDataReader object open on a single SqlConnection object. If you need a second SqlDataReader object, you must open a second SqlConnection object. Answers B and C are not correct because the question asks for the likely cause for the error, not just an alternative approach. Answer D is not correct because you want to retrieve multiple values from the database, and the ExecuteScalar method retrieves only the first column of the first row in the result set. 9. The correct answer is D. Changes made to a DataGrid bound to a DataSet are automatically saved to the DataSet. However, they are not persisted to the underlying data source until you call the Update method of the DataAdapter object that was used to fill the DataSet. Answers A and C are not correct because the DataGrid control does support editing the data from a database and two-way databinding. Answer B is not correct because a DataSet, which is based on a view, can be updated. 10. The correct answer is C. Calling the GetChanges method of a DataSet returns a new DataSet that contains only records that have been changed. Answer A is not correct because the DataSet.Clone method copies the structure of the DataSet but does not copy any data. Answer B is not correct because the DataSet.Copy method copies all the data instead of only the changed data. Answer D is not correct because you do not want to merge two DataSet objects. 391 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer . . . . .Key . . for . .Sample . . . . Test . . .#1. 11. The correct answer is C. The SqlCommand.Prepare method creates a prepared version of the command on an instance of SQL Server. After the command has been prepared, further execution of that command will be comparatively faster. Answer A is not correct because the SqlCommand.ExecuteReader method is generally used to execute query statements such as the SELECT statement rather than nonquery statements such as the INSERT statement. Answer B is not correct because if SQL Server needs to prepare the command with each execution, performance will decrease instead of increase. Answer D is not correct because the SqlCommand.ResetCommandTimeout method just resets the CommandTimeout property to its default value and does not play a role in optimizing the performance in the given scenario. 12. The correct answers are A and D. In the current scenario, the XmlReadMode.Auto and XmlReadMode.InferSchema options will infer schema from the data. Answer B is not correct because the data in Orders.xml file is not a DiffGram. Answer C is not correct because when XmlReadMode is set to Fragment, the default namespace is read as the inline schema. 13. The correct answer is C. To create a connection string for a SqlConnection object that uses Windows Integrated authentication, you need to specify the data source and the initial catalog, and indicate that it is a secure connection. You can indicate that it is a secure connection by setting the Trusted_Connection or Integrated Security parameters to true or sspi. Answers A and B are not correct because you do not specify the provider in the connection string when connecting through the SqlConnection object. Answer D is not correct because you need to use Windows authentication instead of SQL Server authentication. 14. The correct answer is C. Using DataView.RowFilter property provides an easy mechanism to retrieve a selected row from the databse. Answers A and D are not correct because these answers require maintenance programming every time the list of departments changes. Answer B is not correct because it will retrieve more data than necessary over the slow WAN line. 15. The correct answers are B and D. If you use a container control, such as a GroupBox, Panel, or TabControl, to contain the data-bound controls, you can create a BindingContext for just that container control and its controls. This allows each part of your form to be managed by its own BindingManagerBase object. For things to work correctly, you need to make sure that you are using the CurrencyManager from the 392 Chapter 17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . correct BindingContext object. Answer A is not correct because Windows forms can easily contain more controls on a form than specified in the given scenario. Answer C is not correct because all CurrencyManager objects support a Position property. 16. The correct answer is A. The three parameters of the ControlBindingsCollection.Add method are the name of the control property to bind to, the data source to bind, and the navigation path to the particular data to bind. So, in this case, the Text property of the TextBox control should be data-bound to the OrderStatus field of the Order table in the dsOrders data source. Answer B is wrong because an empty string is passed to the last parameter only if the data source contains one property or data to bind. Answer C is wrong because the last parameter of the Add method should specify the complete navigation path of the property or data to which the control wants to bind. Answers D, E, and F are wrong because to display the status in the text box, you need to bind to the Text property instead of the Tag property of the TextBox. 17. The correct answers are A and D. The Sort property of a DataView object is a string containing the column name followed by ASC (ascending) or DESC (descending). Columns are sorted ascending by default. Answer B is not correct because you must specify the name of a column in the Sort property, along with ASC or DESC. Answer C is not correct because the ApplyDefaultSort property is used to automatically create a sort order, in ascending order, based on the primary key of the table. The ApplyDefaultSort property applies only when the table has a primary key defined and the Sort property is a null reference or an empty string. 18. The correct answer is D. To return a single value from the database, you should use the ExecuteScalar method of the OleDbCommand object. The ExecuteScalar method executes the query and retrieves the first column of the first row of the result set. You should always use stored procedures rather than the ad-hoc SQL statements for speedy delivery. Answers A, B, and C are wrong because they use SQL queries rather than stored procedures. Answers E and F are wrong because they involve extra overhead if only a single value is to be returned from the database. 19. The correct answer is C. The KeyDown event occurs before the KeyPress events. Setting the Handled property to true in the form’s KeyPress event prevents the control’s KeyPress event from firing. As a result, the first message is displayed from the textBox1_KeyDown 393 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer . . . . .Key . . for . .Sample . . . . Test . . .#1. event handler and the next message is displayed by the form_KeyPress event handler. Answer A is not correct because the KeyDown event occurs before KeyPress. Answer B is not correct because the textBox1_KeyPress event handler is not executed. Answer D is not correct because the KeyPreview property of form1 is set to true, which causes the form1_KeyPress event handler to be invoked. 20. The correct answer is B. The easiest way to get a control to behave precisely like a TextBox is to derive from the TextBox class. Answers A, C, and D are not correct because they require additional code to be written. 21. The correct answer is C. Dynamic properties provide a built-in mecha- nism to set properties at runtime without needing to write any code. Answers A and B are not correct because asking the user to modify the program source code or Windows Registry could have undesirable effects. Answer D is not correct because this option requires writing additional code to retrieve a form’s text from a file. 22. The correct answer is B. The UserControl class provides you with a design surface on which you can assemble constituent controls to create a custom control. Answer A is not correct because it requires you to write additional code. Answer C is not correct because deriving from the Form class is not a standard way of creating reusable controls. Answer D is not correct because using the Component class to create reusable visual components requires additional programming and is therefore better suited for creating nonvisual components. 23. The correct answer is D. You should set the CausesValidation property of the Button control to false because setting the CausesValidation property of a control to false causes the Validating event of other controls to be ignored when the focus is shifted to the specified control. Answers A and C are not correct because setting the CausesValidation property of a TextBox control will not have any effect on the Button control. Answer B is not correct because setting the CausesValidation property of the Button control to true will not allow you to click the Button control when there is invalid data in the textbox. 24. The correct answer is A. If a CheckBox control has its ThreeState property set to true, its Checked property will return true even if the check box is in the indeterminate state. Answer B is not correct because you must evaluate the CheckState property to determine whether the check box is actually checked. Answers C and D are not correct because you want to take an action only when the user checks the CheckBox control. 394 Chapter 17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25. The correct answer is D. Using the ResizeRedraw property requires less code and causes the form to refresh instantly. Answer A is not correct because calling the Invalidate method periodically will not refresh the form instantly. Answer B is not correct because this approach requires you to write more code. Answer C is not correct because the Invalidate method triggers the Paint event, so calling it within the Paint event leads to an infinite regress. 26. The correct answer is C. Setting the TabStop property of the control to false removes the control from the tab order. Answers A and B are not correct because they just change the order of a control instead of removing the control from the tab order. Answer D is not correct because if you set the Enabled property of the control to false, it cannot get the focus under any circumstances. 27. The correct answer is C. Using the Or (|) operator sets the proper bit to represent the Italic FontStyle without altering any other bits that might already be set. Answers A, B, and D are not correct because these options cause additional bits to be set, resulting in an undesired font style. 28. The correct answer is B. You should avoid duplicating code if you don’t have to. However, the Click and MouseMove event handlers of the Button control have different signatures. Therefore, you need to write two event handlers. The first will handle both Click events, and the second will handle both MouseMove events. Answer A is not correct because this approach requires a lot of code to be written. Answers C and D are not correct because the Click and the MouseMove event handlers have different signatures and must be written separately. 29. The correct answers are C and E. The Class Library project is the best way to package a set of standard classes. If you do not want a class to be inherited, it must be declared as sealed. Answers A and B are not correct because these are not the appropriate project types for the given scenario. Answer D is not correct because you are writing classes with the implementation logic. Answers F and G are not correct because if the classes are defined as private, other developers will not be able to instantiate them. 30. The correct answer is A. The protected modifier limits member access to the class containing the member and to subclasses of that class. Answer B is not correct because the public modifier allows any class to call the member. Answer C is not correct because the private modifier limits access to the defining class only. Answer D is not correct because 395 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer . . . . .Key . . for . .Sample . . . . Test . . .#1. the internal modifier limits access to classes within the same project, whether or not they are derived from the defining class. 31. The correct answers are A and D. You need to sign a shared assembly with the strong name and then install the assembly in the Global Assembly Cache. Answer B is not correct because you use sn.exe instead of signcode.exe to sign an assembly with a strong name. Answer C is not correct because the Windows system directory does not allow multiple versions of an assembly to be maintained. 32. The correct answer is D. When a custom control does not require a runtime user interface, the Component class provides the lowest overhead. Answers A, B, and C are not correct because they are more suitable for designing controls with a user interface. 33. The correct answer is C. The base keyword is used to access members of the base class from within a derived class. Answer A is not correct because the given syntax is for invoking static members of a class. Answer B is not correct because the given syntax is for accessing the method of the current class. Answer D is not correct because of its invalid syntax. 34. The correct answer is D. An exception will be handled by the most specific applicable catch block and the finally block will always be executed. Answers A and B are not correct because the finally block always executes. Answer C is not correct because a division by 0 arithmetic exception is thrown before the Debug.WriteLine method is executed in the try block. 35. The correct answer is A. The SqlException.Class property gets a value from 1 to 25 that indicates the severity level of the error. Answer B is not correct because the SqlException.Source property gets the name of the provider that generated the error. Answer C is not correct because the SqlException.Server property gets the name of the computer running an instance of SQL Server that generated the error. Answer D is not correct because the SqlException.State property gets a numeric error code from SQL Server that represents an error, warning, or “no data found” message. 36. The correct answers are B and D. Either of these options can generate proxy classes for use in a client application. Answer A is not correct because the .NET WebService Studio tool is used to invoke a Web Service for testing. Answer C is not correct because the Web Services Discovery Tool can locate files related to a Web Service, but it does not generate any proxy classes. 396 Chapter 17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37. The correct answer is D. Answers A, B, and C are not correct because calls to a Web Service will block other processing unless you use asynchronous calls to invoke the Web Service. 38. The correct answer is D. When the RightToLeft property value is set to RightToLeft.Yes, the horizontal alignment of the control’s elements is reversed. Answers A and C are not correct because the RightToLeft property is of the type System.Windows.Form.RightToLeft, which specifies a value indicating whether the text appears from right to left, such as when using Hebrew or Arabic fonts. Answer B is not correct because you need to make minimum changes. 39. The correct answer is B. The Type Library Importer tool enables you to place the RCW assembly in the GAC so that it can be shared by all projects on the computer. Answers A and D are not correct because you need to use the component in more than one project. Answer C is not correct because a Primary Interop Assembly is for code from other vendors, not for your own code. 40. The correct answer is C. The SetHelpString method specifies the help string associated with the specified control. Answer A is not correct because the SetHelpKeyWord method specifies only the keyword used to retrieve the help text associated with a control. Answer B is not correct because the SetHelpNavigator method specifies the help command to use while retrieving the text from the help file. Answer D is not correct because the SetShowHelp method specifies only whether help is displayed for the specified control. 41. The correct answer is D. The QueryPageSettings event fires before each page is printed and enables you to check and change page settings. Answers A and B are not correct because you do not have access to the PageSettings objects in the event arguments of the BeginPrint and EndPrint events. Answer C is not correct because the event arguments of the PrintPage event provide read-only access to the PageSettings objects. 42. The correct answer is B. You can step into a stored procedure execu- tion directly from within Visual Studio .NET. Answer A is not correct because the Tools, Debug Processes menu item is useful for debugging running processes, not stored procedures. Answer C is not correct because this option takes more time and effort. Answer D is not correct because the Debug.WriteLine method cannot directly access the stored procedure values. 43. The correct answer is C. Breakpoints are invoked only when the pro- ject’s configuration is in Debug mode. Answer A is not correct because 397 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer . . . . .Key . . for . .Sample . . . . Test . . .#1. the Exceptions dialog box is used to configure the breakpoint only in case of an exception. Answer B is not correct because when you place a breakpoint, it is enabled by default. Answer D is not correct because the project’s configuration should be Debug instead of Release for debugging to occur (breakpoints to be executed). 44. The correct answer is D. A conditional breakpoint lets you pause your code only when a particular condition is true. In this case, you can use that capability to break into the code when the variable has the value of 117. Answers A, B, and C are not correct because they do not work conditionally. 45. The correct answer is A. The Task List window helps you identify and locate problems, which are detected automatically as you edit or compile code. Answer B is not correct because it mixes other messages along with the error messages generated by the compiler. Answer C is not correct because the Find Results window displays matches for text searches that were performed in the Find in Files dialog box. Answer D is not correct because the Immediate window is used for debugging purposes, such as evaluating expressions, executing statements, printing variable values, and so forth. 46. The correct answer is C. In the PInvoke calls, you should use the StringBuilder object instead of the String object to hold the return value. Answer B is not correct because all identified with some name in the network. Answers A and D are wrong because the GetComputerName API expects a string buffer rather than sending reference parameters. 47. The correct answers are A and E. If you want multiple applications to use an assembly, you need to sign the assembly with a strong name and place the assembly in the Global Assembly Cache. Answer B is not correct because the COM application is not using the assembly. Answer C is not correct because assemblies cannot be deployed in the Global Assembly Cache with the XCOPY command. Answers D and F are not correct because shared assemblies must be installed in the Global Assembly Cache instead of the Windows system directory. 48. The correct answer is A. To enable remote debugging on a computer, the Machine Debug Manager (mdm.exe) must be installed. You can install this software by installing Visual Studio .NET on the remote machine or by installing Remote Components Setup on the remote machine. Answer B is not correct because Visual Studio .NET does support cross-domain debugging, provided that there is a two-way trust relationship between the domains. Answer C is not correct 398 Chapter 17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . because how the remote process was compiled does not matter for debugging. Answer D is not correct because no switch needs to be added in the application’s configuration file for remote debugging. 49. The correct answer is C. The applications always bind to the assem- blies with which they are compiled. If you want to execute a new version of the assembly, the applications should be recompiled with the new version of the assembly or you should modify the application configuration file to redirect an application to a new version of the assembly. Therefore answers A, B, and D are not correct. 50. The correct answer is D. Merge Module projects enable you to create reusable setup components by packaging all the required files, resources, Registry entries, and setup logic necessary to install a component. Answer A is not correct because the Cab project creates a cabinet file for downloading from a Web browser. Answer B is not correct because the Setup project creates an installer for a standalone Windows-based application. Answer C is not correct because the Web Setup project creates an installer for a standalone Web application. 51. The correct answers are A and D. Full installation of Windows XP Service Pack 1 includes the installation of the .NET Framework; therefore, you can safely choose to exclude the deployment of the .NET Framework from the setup package. This will reduce the size of the setup package to a good extent. To further reduce the size, you can choose to optimize the setup package for size. Answer B is not correct because setting the Exclude property to false will include the .NET Framework and increase the size of the setup package. Answer C is not correct because changing the packaging to cabinet files will not reduce the size of the setup package. 52. The correct answer is A. You need to change the Author property of the deployment project because the Author property specifies the name of the author of an application. Answer B is not correct because the Description property is usually used to describe the application instead of specifying the name of the publisher. Answers C and D are not correct because they are intended to specify the phone number and the URL of the manufacturer instead of the name. 53. The correct answer is A. You can use the Custom Actions Editor to take custom actions such as install a database during application setup. If you have an installer class or a program that needs to create a database, you must override the Install method of the base class and add the installer program to the Install node of the Custom Actions editor. Answer B is not correct because you need to add the component to the 399 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer . . . . .Key . . for . .Sample . . . . Test . . .#1. Install node instead of the Commit node. Answer C is not correct because copying the InstData.sql file will not help; you also need to execute this file on SQL Server and create a custom installation component for the same. Answer D is not correct because the Launch Conditions Editor is used to specify the prerequisite conditions that must be met to successfully run an installation; it cannot be used to execute custom actions. 54. The correct answer is A. The enterprise security policy affects every computer and user on the network. Answer B is not correct because this option requires modifying the machine security policy for each machine in the company. Answer C is not correct because the user security policy applies to only a single logon account. Answer D is not correct because security policy at the application domain level cannot be administered. 55. The correct answer is D. The name of the application configuration file is X.config, where X is the name of the application (including file extension). An application will read the settings from the application configuration file only if both the files are present in the same directory. Answers A and B are not correct because the name of the configuration file is not correct. Answer C is not correct because the deployment directory of the application configuration file is not correct. 56. The correct answer is B. SecurityAction.RequestOptional is used to request additional permissions that are optional. Answer A is not correct because SecurityAction.RequestMinimum requests the minimum permissions required for code to run. Answer C is not correct because SecurityAction.Demand requires all callers higher in the call stack to have been granted the permission specified by the current permission object. Answer D is not correct because SecurityAction.RequestRefuse is used to refuse those requests that might be misused. 57. The correct answer is C. You should use the Process.CloseMainWindow method to shut down applications that have a user interface. This method gives the application a chance to clean up resources. Answer A is not correct because although the Process.Kill method also shuts down the application, it does not perform any normal cleanup processing. Answer B is not correct because instead of killing the process, the Process.WaitForExit method waits indefinitely for the associated process to exit. Answer D is not correct because instead of killing the process, the Process.WaitForInputIdle method waits for the associated process to enter an idle state. 400 Chapter 17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58. The correct answer is B. For BooleanSwitch, a value of 0 corresponds to Off (false), and any nonzero value corresponds to On (true). For TraceSwitch any number greater than 4 is treated as Verbose. From the given values in the configuration file, the booleanSwitch object will have its Enabled property set to true, and the traceSwitch object will have its Level property set to TraceLevel.Verbose. Answers A, C, and D are not correct because the booleanSwitch.Enabled property should be true instead of false. 59. The correct answers are A, C, and D. When you add a listener to the Trace.Listeners collection, it listens to the messages generated by both the Trace and Debug classes. When the new listener is added, it is added to the Listeners collection. It already has a DefaultTraceListener object that sends messages to the output window, and it is still active and listening to the messages. Therefore, you have messages in TraceLog.txt as well as in the output window. Answer B is not correct because listener objects listen to messages generated by both Debug and Trace classes. 60. The correct answer is B. The TraceSwitch class provides a multilevel switch that enables you to control tracing and debug output of a Windows application without recompiling the code. The changes in behavior can be instrumented by just changing the application’s configuration file. Answer A is not correct because TraceListener is used to redirect the output of the trace messages. Answers C and D are not correct because Trace and Debug classes can print messages but cannot provide any control mechanism for which messages will be printed and which messages will not be printed. 18 Sample Test #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Practice Test Question 1 You develop a customer contact-management application using Visual Studio .NET. You use the methods of the Trace and Debug classes to log serious error messages encountered during program execution. You want to record all such errors in the Windows event log. You do not want any duplicate entries for error messages in the event log. In what two ways can you add a listener to the Windows event log? ❍ A. EventLogTraceListener traceListener = new EventLogTraceListener(“CustomEventLog”); Trace.Listeners.Add(traceListener); ❍ B. EventLogTraceListener traceListener = new EventLogTraceListener(“CustomEventLog”); Trace.Listeners.Add(traceListener); Debug.Listeners.Add(traceListener); ❍ C. EventLogTraceListener traceListener = new EventLogTraceListener(“CustomEventLog”); D. ❍ EventLogTraceListener traceListener = new EventLogTraceListener(“CustomEventLog”); Debug.Listeners.Add(traceListener); 403 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 2 You develop a supplier-evaluation system using Visual Studio .NET. While testing the program, you notice that the value of TotalShipments variable sometimes becomes 0 and causes an exception in the CalculateAvgShipDelay method. You want your program to check the value of the TotalShipments variable and display an error message when the value of TotalShipments is 0. You want the program to display this error message regardless of how you compile the program. Which of the following code segments should you write before making a call to the CalculateAvgShipDelay method? ❍ A. Trace.Assert(TotalShipment == 0, “TotalShipments is zero”); ❍ B. Trace.Assert(TotalShipment != 0, “TotalShipments is zero”); ❍ C. Debug.Assert(TotalShipment == 0, “TotalShipments is zero”); ❍ D. Debug.Assert(TotalShipment != 0, “TotalShipments is zero”); Question 3 Your application includes a DataSet object that contains a DataTable object named Suppliers. This DataTable object contains all rows from the Suppliers table in your database. You want to bind an object to a DataGrid control on a form so that the DataGrid control displays only the suppliers from Michigan. You want a quick solution. What should you do? ❍ A. Create a filtered array by calling the DataTable.Select method on the Suppliers data table and bind the array to the DataGrid control. ❍ B. Create a new SqlCommand object to retrieve only suppliers from Michigan. Use a new SqlDataAdapter object to fill a new DataSet object with these suppliers. Bind the new DataSet object to the DataGrid control. ❍ C. Use a foreach loop to move through the entire Suppliers data table. Each time you find a DataRow object that represents a supplier from Michigan, bind that DataRow object to the DataGrid control. ❍ D. Create a filtered DataView object from the Suppliers data table and bind the DataView object to the DataGrid control. 404 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 4 You develop a Windows-based application that displays supplier data in a DataGrid control. The supplier data is stored in a table named Suppliers within the dsSuppliers DataSet object. The primary key for the Suppliers table is the SupplierID column. You need to display the supplier data in the DataGrid control in ascending order of the primary key. You write the following code segment to accomplish this task: DataView dvSuppliers = new DataView(dsSuppliers.Tables[“Suppliers”]); dvSuppliers.Sort = “ASC”; dvSuppliers.ApplyDefaultSort = true; dataGrid1.DataSource = dvSuppliers; However, when you run the program, the results are not as expected. How should you change the code segment to get the intended results? ❍ A. Set the Sort property of the DataView object to an empty string. ❍ B. Set the ApplyDefaultSort property of the DataView object to false. ❍ C. Set the RowFilter property of the DataView object to SupplierID. ❍ D. The code segment is correct. You need to ensure that the data in the Suppliers table is already sorted on the primary key. 405 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 5 You are developing a Windows-based application using Visual C# .NET. Your application’s configuration files have the following code: <system.diagnostics> <switches> <add name=”TraceLevelSwitch” value=”3” /> </switches> </system.diagnostics> You have written the following tracing code in your program: static TraceSwitch traceSwitch = new TraceSwitch( “TraceLevelSwitch”, “Trace the application”); [Conditional(“DEBUG”)] private void Method1() { Trace.WriteLineIf( traceSwitch.TraceError, “Message 1”, “Message 2”); } [Conditional(“TRACE”)] private void Method2() { Trace.WriteLine(“Message 3”); } private void btnCalculate_Click(object sender, System. ➥EventArgs e) { if(traceSwitch.TraceWarning){ Trace.WriteLine(“Message 10”); Method1(); } else{ Trace.WriteLineIf(traceSwitch.TraceInfo, ➥“Message 20”); Method2(); } if (traceSwitch.TraceError) Trace.WriteLineIf(traceSwitch.TraceInfo, ➥“Message 30”); Trace.WriteLineIf(traceSwitch.TraceVerbose, ➥“Message 40”); } Which tracing output will be generated when you run your program in Debug mode and click the btnCalculate button? ❍ A. Message Message Message Message 10 1 2 30 406 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B. Message 10 Message 2: Message 1 Message 30 C. Message Message Message Message 10 2 30 40 D. Message Message Message Message 20 3 30 40 Question 6 You use Visual C# .NET to create an assembly named Tracker.dll. Tracker.dll contains classes for tracking a shipment and is used by several applications, including both managed applications and unmanaged COM applications. The COM applications are already compiled and use late binding to invoke methods from the assembly. What actions should you take to ensure that the assembly is properly deployed on the target machine? (Select all that apply.) ❑ A. Create a strong name for the assembly by using the Strong Name tool (sn.exe). ❑ B. Register the assembly using the Assembly Registration tool (regasm.exe). ❑ C. Create a type library for the application using the Type Library Exporter tool (tlbexp.exe). ❑ D. Import the COM type library definition into an assembly by using the Type Library Importer tool (tlbimp.exe). ❑ E. Deploy the assembly to the Global Assembly Cache (GAC). ❑ F. Deploy the assembly to the application’s installation directory. ❑ G. Deploy the assembly to the Windows system directory. 407 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 7 You use Visual C# .NET to develop an assembly that enables developers to create pie charts in their applications. You name an assembly as PieChart.dll and package it as Version 1.0.0 for distribution over the Internet. After two months, you discover that there is a bug in the assembly. You fix the bug by releasing a new Version 1.0.1 of the assembly. You do not want other developers to recompile the applications that they built using Version 1.0.0 of PieChart.dll. You want to make sure that when Version 1.0.1 of PieChart.dll is deployed, all existing applications that use Version 1.0.0 start making use of Version 1.0.1 of the assembly. You want to minimize efforts in deploying the new version of the assembly. Which of the following steps should you take to deploy Version 1.0.1 of PieChart.dll? ❍ A. Modify the application configuration files of all the applications that use Version 1.0.0 of the PieChart.dll assembly to now use Version 1.0.1 of the PieChart.dll assembly. ❍ B. Modify the machine configuration files to redirect the references for Version 1.0.0 of the PieChart.dll assembly to Version 1.0.1 of the PieChart.dll assembly. ❍ C. Deploy a publisher policy file to redirect the references for Version 1.0.0 of the PieChart.dll assembly to Version 1.0.1 of the PieChart.dll assembly. ❍ D. Remove Version 1.0.0 of the PieChart.dll assembly and then deploy Version 1.0.1 of the PieChart.dll assembly. Question 8 You develop desktop applications for a large university. Your new project is to write a Visual C# .NET application that enables professors to maintain the test scores of students. You place a DataGrid control on the Windows form and bind the data grid to a DataView object. You allow professors to make changes in the data grid by adding new rows, by modifying existing rows, and by deleting existing rows. You now want to place a command button that allows professors to view the deleted rows from the original data. How should you program the Click event of the command button? ❍ A. In the event handler for the Click event, set the RowFilter property of the DataView object to DataViewRowState.Deleted. ❍ B. In the event handler for the Click event, set the RowFilter property of the DataView object to DataViewRowState.OriginalRows. ❍ C. In the event handler for the Click event, set the RowStateFilter property of the DataView object to DataViewRowState.Deleted. ❍ D. In the event handler for the Click event, set the RowStateFilter property of the DataView object to DataViewRowState.OriginalRows. 408 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 9 You need to debug a Windows application by using Visual Studio .NET installed on your local machine. The Windows application is deployed on a remote server. When you attempt to debug the application, you get a DCOM configuration error. Which of the following steps should you take to resolve this problem? ❍ A. Add your account to the Power Users group on the local computer. ❍ B. Add your account to the Power Users group on the remote computer. ❍ C. Add your account to the Debugger Users group on the local computer. ❍ D. Add your account to the Debugger Users group on the remote computer. Question 10 You develop a Windows forms application that displays a background image in a form. Your application needs to comply with the Windows logo program. To do so, you want your application to monitor for changes to the HighContrast setting at runtime so that it can remove a background image from a form, if necessary. Which event must you trap? ❍ A. SystemEvents.UserPreferenceChanged ❍ B. Form.Paint ❍ C. SystemEvents.PaletteChanged ❍ D. Form.Load Question 11 You develop a Windows form application using Visual C# .NET. A TextBox control on your Windows form should accept no more than three characters from the user. However, your code might need to place the value Invalid in the TextBox control. What value should you use for the MaxLength property of this control? ❍ A. 3 ❍ B. 4 ❍ C. 7 ❍ D. 8 409 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 12 You have created an array of Project objects named aProjects. Each Project object has a Name property and a Number property. You want to display all of the Name values in a ListBox control named lbProjects. Which code snippet should you use for this purpose? ❍ A. lbProjects.DataSource = aProjects; lbProjects.ValueMember = Name; ❍ B. lbProjects.DataSource = aProjects; lbProjects.DisplayMember = Name; ❍ C. lbProjects.DataSource = aProjects; lbProjects.ValueMember = “Name”; ❍ D. lbProjects.DataSource = aProjects; lbProjects.DisplayMember = “Name”; Question 13 You have created a custom component for your application that monitors a bidirectional parallel port for error messages. This component raises an event named PortError whenever an error message is detected. At that point, you must make the error code available to the control container. You want to use the best coding practices. Which of the following options should you choose to make the error code available to the container? ❍ A. Place the error code in a property of the component for the container to retrieve it. ❍ B. Pass the error code as a parameter to the PortError event handler. ❍ C. Define a global variable in a separate class and place the value in that variable. ❍ D. Define a custom PortErrorEventArgs class that inherits from the EventArgs class to contain the error code, and pass an instance of the class as a parameter of the PortError event. 410 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 14 You are developing a Windows form application that enables users to create network diagrams. You plan to use objects from the System.Drawing namespace to draw shapes on a form at runtime. You have already determined that you will draw these shapes during the form’s Paint event. You want to write minimum code; how should you create the Graphics object required by the classes of the System.Drawing namespace? ❍ A. Call the CreateGraphics method of the form. ❍ B. Retrieve the Graphics property of the PaintEventArgs object that is passed to the event. ❍ C. Pass the handle of the form to the Graphics.FromHwnd method. ❍ D. Call the CreateGraphics method of the control that has the focus. Question 15 You use Visual C# .NET to create a Windows forms application. You create a form, Form1, and set its BackColor property to Red. You add a new form, Form2, to the application by using visual inheritance to derive the new form from Form1. You set Form2 to be the startup object for the application, and you set its BackColor to Blue. After this, you change the BackColor of Form1 to Yellow. When you run the application, what is the BackColor of Form2? ❍ A. Blue ❍ B. Red ❍ C. Yellow ❍ D. Control 411 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 16 You are creating a graphic application that will manipulate a variety of image formats. You have created an OpenFileDialog object in your program and have set its Filter property as follows: ofdPicture.Filter=”Image Files (BMP, GIF, JPEG, etc.)|”+ “*.bmp;*.gif;*.jpg;*.jpeg;*.png;*.tif;*.tiff|”+ “BMP Files (*.bmp)|*.bmp|”+ “GIF Files (*.gif)|*.gif|”+ “JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg|”+ “PNG Files (*.png)|*.png|”+ “TIF Files (*.tif;*.tiff)|*.tif;*.tiff|”+ “All Files (*.*)|*.*”; You have created a Button with its text property set to “Open Image”. When you click this button, you’ll display the OpenFileDialog to allow a selection. You want BMP files to be the default choice in the dialog box. Which of the following values for FilterIndex property must you choose to achieve this in the event handler of Button control’s Click event? ❍ A. 0 ❍ B. 1 ❍ C. 2 ❍ D. 3 412 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 17 Your Visual C# .NET application contains a Windows form that enables users to delete multiple records from a database. You do not want the users to unintentionally delete the records. You develop a form named frmConfirm to get confirmation from the user. This form includes two Button controls, btnOK and btnCancel. The DialogResult property of btnOK is set to OK, and the DialogResult property of btnCancel is set to Cancel. Which code snippet should you use to display frmConfirm and process the user’s choice? ❍ A. frmConfirm frm = new frmConfirm(); frm.ShowDialog(); if(frm.DialogResult == DialogResult.OK) { // Delete the records } ❍ B. frmConfirm frm = new frmConfirm(); frm.Show(); if(frm.DialogResult == DialogResult.OK) { // Delete the records } ❍ C. frmConfirm frm = new frmConfirm(); frm.ShowDialog(); if(frm.btnOK.DialogResult == DialogResult.OK) { // Delete the records } ❍ D. frmConfirm frm = new frmConfirm(); frm.Show(); if(frm.btnOK.DialogResult == DialogResult.OK) { // Delete the records } 413 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 18 You develop a Windows form application that enables users to generate shipping labels. The program needs to generate thousands of shipping labels each day. You use the Trace object to monitor the application and log the results in the Windows event log. You need to monitor errors, warnings, and other informational messages generated by the Trace object. You should have flexibility of controlling the amount of information logged for your application, and you want to do this with minimum administrative efforts. What should you do? ❍ A. Start the application using the /d:TRACE switch. ❍ B. Define an environment variable named TRACE and set its value to true or false. In the program, check the value of the environment variable to indicate the amount of information that you want for your application to be logged. ❍ C. Declare a compilation constant named TRACE and set its value to Error, Warning, or Info. In your program, use #if, #else, and #endif directives to check the level of tracing that you want. ❍ D. Use the TraceSwitch class in your program, and use the TraceSwitch.Level property to check whether you need to log the performance. Set the level of the TraceSwitch by using the application’s configuration file. Question 19 While you are debugging in Visual Studio .NET, you want to watch the value of only those variables that are used in the current executing method. Which of the following debugger windows is the easiest window to use to watch these variables? ❍ A. This ❍ B. Autos ❍ C. Locals ❍ D. Watch 414 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 20 You are performing final acceptance testing on your application before shipping it. You have set a breakpoint inside the SelectedIndexChanged event handler for a combo box. However, when you select a new value in this combo box, the code in the event handler gets executed but does not stop at the breakpoint. What could be the most likely problem? ❍ A. Selecting a value in a combo box does not fire the SelectedIndexChanged event. ❍ B. You are executing the project using the default Release configuration. ❍ C. You have neglected to add the [Conditional(“DEBUG”)] attribute to the event handler. ❍ D. You have neglected to add #const int DEBUGGING = 1 to the code. Question 21 You are debugging a Windows form application that you wrote using Visual Studio .NET. Your code uses the Trace class to produce the debugging output. In which configuration(s) will this output be enabled? ❍ A. In the default Release configuration only. ❍ B. In the default Debug configuration only. ❍ C. In both the default Release configuration and the default Debug configuration. ❍ D. In neither the default Release configuration nor the default Debug configuration. 415 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 22 You need to develop a custom toolbar control that will be used by several Windows applications to display application-specific tool buttons. You want this control to be of same width as the form in which the control is hosted, and the control should be displayed at the top of form. When the parent form is resized or repositioned, the custom toolbar control should also be resized and repositioned accordingly. Which of the following answers should you choose to accomplish this requirement? ❍ A. Create a property that enables the developers to set the Anchor property of the custom toolbar control and then set the default value of this property to AnchorStyle.Top. ❍ B. Create a property that enables the developers to set the Dock property of the custom toolbar control and then set the default value of this property to DockStyle.Top. ❍ C. In UserControl_Load event handler, add the following code: this.Anchor = AnchorStyle.Top; ❍ D. In UserControl_Load event handler, add the following code: this.Dock = DockStyle.Top; Question 23 You develop a Windows-based application using Visual C# .NET. The application needs to display weather information for the ZIP code entered by the user. You do not know how to determine the weather information yourself; therefore, you choose to call a Web Service to provide this information in your application. You know the URL of the asmx file published by the Web Service, but you do not know any details of the Web Service’s interface. Which of the following action should you take first to get information about the Web Service? ❍ A. Run the Web Service Discovery tool. ❍ B. Open the asmx file in a Web browser. ❍ C. Run the XML Schema Definition tool. ❍ D. Copy the .asmx file to your client project. 416 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 24 You create an ASP.NET Web Service project using Visual Studio .NET. The project includes a class named RefLibrary. The RefLibrary class contains this method: public String Version() { return “1.6”; } You note that you are able to instantiate the RefLibrary class from a Web Service client project, but the Version method is not available. What could be the problem? ❍ A. Only properties can be part of the public interface of a Web service. ❍ B. You must mark the method with the WebService attribute. ❍ C. The methods of a Web Service can return only Object data. ❍ D. You must mark the method with the WebMethod attribute. Question 25 The customer service representatives in your company often receive calls from customers inquiring about the shipping status of their orders. You have been assigned to create an application that assists the customer service representatives with easily finding the shipping status. You decide to create a Windowsbased application that calls the XML Web services provided by the shipping and logistic company to retrieve the latest shipping status. When you test the application, the user of the application complains that the user interface of the application is very slow. You find that your program is waiting for the Web Service call to execute. You need to design a solution that is most efficient. What should you do to make your application responsive? ❍ A. Use the WaitHande.WaitAll method of the IAsyncResult.AsyncWaitHandle object. ❍ B. Call the End method of the XML Web Service. ❍ C. Use the WaitHande.WaitAny method of the IAsyncResult.AsyncWaitHandle object. ❍ D. Supply a callback delegate to the Begin method of the XML Web Service. When the XML Web Service returns, a thread will invoke the callback method from the thread pool. 417 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 26 Your company intends to ship a text-editing application to a variety of locales, including the United States, France, Israel, China, and Japan. One of the features of the application is searching for text within longer text passages. You have been assigned to implement this feature using Visual C# .NET. What should you use to perform this search? ❍ A. CultureInfo.CompareInfo ❍ B. Array.Sort ❍ C. String.IndexOf ❍ D. String.IndexOfAny Question 27 You design a Windows service application using Visual Studio .NET. The service stores information related to computer uptime and page faults. Computers in many countries will use this Windows service. When storing this information for future analysis, which culture should you use? ❍ A. The Invariant culture ❍ B. The en-US culture ❍ C. The culture specified by Thread.CurrentThread.CurrentCulture ❍ D. A culture selected by the user 418 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 28 Your application contains the following resource files containing string resources: MyApp.resx MyApp.fr.resx MyApp.fr-FR.resx MyApp.en.resx MyApp.en-US.resx The user executes the application on a computer running French (Canadian) software, so the CurrentUICulture property is set to fr-CA. What will be the result? ❍ A. The resources from MyApp.fr.resx will be used. ❍ B. The resources from MyApp.fr-FR.resx will be used. ❍ C. The resources from MyApp.en-US.resx will be used. ❍ D. An exception will be thrown. Question 29 Your application performs various mathematical calculations. You are beginning to sell this application in multiple countries. How should you ensure that the correct numeric formatting is used in all cases? ❍ A. Allow the user to select a culture from a list. Create a CultureInfo object based on the user’s selection, and assign it to the Thread.CurrentThread.CurrentCulture property. Use the ToString method to format numeric amounts. ❍ B. Accept the Thread.CurrentThread.CurrentCulture property, as it is set when you run your application. Use the ToString method to format numeric amounts. ❍ C. Prompt the user for a numeric format and store it in the Registry. ❍ D. Allow the user to select a numeric format from a list of supported formats. 419 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 30 You need to develop a graphics application using Visual C# .NET. Your application needs to draw images on the screen, and you are looking for a solution that gives you the best performance. You have created several variations of a method that draws an image. Which of the following methods would you choose for your application? ❍ A. public void DrawSampleImage(PaintEventArgs e) { Image newImage = Image.FromFile(“SampImag.jpg”); Point ulCorner = new Point(100, 100); e.Graphics.DrawImage(newImage, ulCorner); } ❍ B. public void DrawSampleImage(PaintEventArgs e) { Image newImage = Image.FromFile(“SampImag.jpg”); int x = 100; int y = 100; e.Graphics.DrawImage(newImage, x, y); } ❍ C. public void DrawSampleImage(PaintEventArgs e) { Image newImage = Image.FromFile(“SampImag.jpg”); Rectangle destRect = new Rectangle(100, 100, 450, 150); e.Graphics.DrawImage(newImage, destRect); } ❍ D. public void DrawSampleImage(PaintEventArgs e) { Image newImage = Image.FromFile(“SampImag.jpg”); float x = 100.0F; float y = 100.0F; e.Graphics.DrawImage(newImage, x, y); } 420 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 31 Your application requires the capability to read and write to the Windows event log to function properly. Which .NET security feature should you use to ensure that your code has this capability? ❍ A. Role-based security ❍ B. Code access security ❍ C. Type safety ❍ D. Encryption Question 32 Your Visual Studio .NET project contains the following API declaration: [DllImport(“kernel32.dll”)] public static extern int GetComputerName(String buffer, ref uint size); The project also contains code to use this API to display the computer name: public static void ShowName() { String buf = “”; UInt32 intLen=128; Int32 intRet; // Call the Win API method intRet = GetComputerName(buf, ref intLen); Console.WriteLine(“This computer is named “ + buf.ToString()); } Users report that no computer name is displayed. What should you do? ❍ A. Use the ref keyword with the variable buf in the call to the GetComputerName function. ❍ B. Tell the user that the computers have no name set in their network properties. ❍ C. Replace the use of the String object with a StringBuilder object in the code. ❍ D. Use the out keyword with the variable buf in the call to the GetComputerName function. 421 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 33 You are responsible for maintaining a COM component that numerous applications throughout your company use. You are not yet ready to migrate this COM component to .NET–managed code, but you need to make it available to an increasing number of other projects that are being developed under the .NET Framework. You want to create the most efficient solution. What should you do? ❍ A. Set a direct reference to the existing COM component from each .NET project. ❍ B. Use the Type Library Importer tool to create and sign an assembly that will use the COM component. Place the COM component in the Global Assembly Cache. ❍ C. Obtain a Primary Interop Assembly for the COM component. ❍ D. Set a direct reference from a single .NET project to the COM component. Include this project in each solution that must use the component. Question 34 You are using the PrintDocument class to print a graphical banner that should span multiple printed pages. However, only the first page of the banner prints. What is the most likely cause of this problem? ❍ A. You have neglected to set PrintPageEventArgs.HasMorePages to true when there are more pages to print. ❍ B. You have neglected to set a sufficiently large value for PrintPageEventArgs.MarginBounds.Height. ❍ C. You have neglected to set a sufficiently large value for PrintPageEventArgs.PageBounds.Height. ❍ D. You have called the Print method only once instead of once per page. 422 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 35 You are developing a Windows application that presents history lessons to the students. If students who use this application have low vision, they will use the application through a screen reader. You use a TextBox control to get the user’s name. When the textbox control gets the focus, the screen reader must be able to identify it and aid the user by speaking the word Name. Which property of the control should you configure to fulfill this requirement? ❍ A. Name ❍ B. Text ❍ C. AccessibleName ❍ D. AccessibleRole Question 36 You use Visual Studio .NET to develop a Windows application that queries data from a SQL Server database. You use the SqlConnetion object to connect to the database. As soon as the database operation is completed, you want to make sure that any pending database transactions are rolled back and that connection is returned to the connection pool. You need to reuse the same SqlConnection object when your program needs to query the database again. Which of the following actions should you take? ❍ A. Call the Dispose method on the SqlConnection object. ❍ B. Call the destructor of the SqlConnection object. ❍ C. Call the Close method on the SqlConnection object. ❍ D. Set the SqlConnection object to null. 423 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 37 You use Visual Studio .NET to develop a Windows-based application. Your application is used to create and maintain product catalogs. You use a DataSet object named dsCatalog to store the product data as users edit the information. When the users save the catalog, you need to store the catalog in an XML file. The root element of the resulting XML file should be <ProductInformation>. You intend to use the DataSet.WriteXml method to save the catalog to an XML file. Which of the following statements should you use to ensure that the correct XML root element is written to the XML file? ❍ A. dsCatalog.NameSpace = “ProductInformation”; ❍ B. dsCatalog.Locale = “ProductInformation”; ❍ C. dsCatalog.Prefix = “ProductInformation”; ❍ D. dsCatalog.DataSetName = “ProductInformation”; Question 38 You develop a Windows-based application that enables users to view and modify recently placed orders. Your application needs to display data from the OrderHeader and OrderDetails data tables. Information from OrderHeader is displayed in a set of controls grouped in a GroupBox control; the information from OrderDetails is displayed in a DataGrid. Your program must ensure that as soon as a different order is selected in the GroupBox control, the DataGrid control displays the details corresponding to that order. Which of the following actions will you take to implement this functionality? ❍ A. Define primary keys on the OrderHeader and OrderDetails tables. ❍ B. Create a foreign key constraint in the OrderDetails table. ❍ C. Add a DataRelation object to the Relations collection of the DataSet object. ❍ D. Use the DataSet.Merge method. 424 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 39 You need to develop a Windows-based application named ProcessOrders. This application receives XML data files from various customers, reads the files, and stores them in a SQL Server database for further processing. The ProcessOrder application uses an XML schema file to define the format and data types of the XML data files. However, not all customers send the XML data file using the same schema. Your application should parse the incoming data files to ensure that they conform to the XML schema. Which of the following actions should you take to accomplish this requirement? ❍ A. Implement an XmlDocument object to load the document. Pass the schema file to this object to validate and parse the XML document. ❍ B. Implement an XmlValidatingReader object and program an event handler for the ValidationEventHandler event to parse the data file that does not conform to the XML schema. ❍ C. Read the XML file into a DataSet object and set its EnforceConstraints property to true. ❍ D. Read the XML file and schema into a DataSet object. Program the DataSet.MergeFailed event handler to parse the data file that does not conform to the XML schema. Question 40 You are developing a Windows-based application to query product information from a SQL Server database. The application specification requires that the users of your application be able to search for a product by entering just the first few characters. You store the characters entered by the user in a variable named ProdName. Which of the following SQL statements should you use to retrieve the data from the database? ❍ A. sqlStatement = “SELECT Name, Description, Price FROM “ + “Product WHERE Name IN ‘“ + ProdName + “%’”; ❍ B. sqlStatement = “SELECT Name, Description, Price FROM “ + “Product WHERE Name LIKE ‘“ + ProdName + “%’”; ❍ C. sqlStatement = “SELECT Name, Description, Price FROM “ + “Product WHERE Name IN ‘“ + ProdName + “*’”; ❍ D. sqlStatement = “SELECT Name, Description, Price FROM “ + “Product WHERE Name LIKE ‘“ + ProdName + “*’”; 425 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 41 Your Visual C# .NET application needs to read data from a SQL Server 6.5 database and write it to a flat file once every 12 hours. A legacy application accesses this file to update its data. Because the data that you will read from the database is huge, you want to retrieve the data with the least impact on the server resources and optimize the performance as much as possible. Which object should you use to load the data from the database? ❍ A. DataSet ❍ B. DataTable ❍ C. SqlDataReader ❍ D. OleDbDataReader Question 42 Assembly CalculateTax is a member of the following code groups (and only the following code groups): Level Code Group Permission Set Exclusive LevelFinal Property Enterprise All Code Everything No No Enterprise Company Code Internet No No Machine Restricted Code LocalIntranet No Yes User Restricted Components Nothing No No What permission does the CLR assign to Assembly CalculateTax? ❍ A. Everything ❍ B. Internet ❍ C. LocalIntranet ❍ D. Nothing 426 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 43 You allow users to edit product information on a DataGrid control that is bound to a DataSet object. When the user clicks the Update button on the form, you call the SqlDataAdapter.Update method to cause the changes from the DataSet object to persist to the underlying database. Users report that new records and updated rows are saved properly but that deleted rows are reappearing the next time they run the application. What could be the problem? ❍ A. The users do not have permission to update the underlying table. ❍ B. The Update method does not delete rows. ❍ C. Someone is restoring an old version of the database between the two executions of the program. ❍ D. You have failed to set the DeleteCommand property of the SqlDataAdapter object. Question 44 Your Visual C# .NET application reads an XML file from disk into an XmlDocument object, and then it modifies some of the nodes in the document. You need to write minimum code. Which object should you use to write the modified XmlDocument object back to disk? ❍ A. XmlTextWriter ❍ B. XmlWriter ❍ C. StreamWriter ❍ D. BinaryWriter ❍ E. TextWriter 427 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 45 Your SQL Server database contains a table named Sales, with these columns: SalesID (int, identity) StoreNumber (int) Sales (int) You want to create a stored procedure that accepts as inputs the store number and sales, inserts a new row in the table with this information, and returns the new identity value. Which SQL statement should you use? ❍ A. CREATE PROCEDURE procInsertSales @StoreNumber int, @Sales int, @SalesID int AS INSERT INTO Sales (StoreNumber, Sales) VALUES (@StoreNumber, @Sales) SELECT @SalesID = @@IDENTITY ❍ B. CREATE PROCEDURE procInsertSales @StoreNumber int, @Sales int, @SalesID int OUTPUT AS INSERT INTO Sales (SalesID, StoreNumber, Sales) VALUES (@SalesID, @StoreNumber, @Sales) ❍ C. CREATE PROCEDURE procInsertSales @StoreNumber int, @Sales int, @SalesID int OUTPUT AS INSERT INTO Sales (SalesID, StoreNumber, Sales) VALUES (0, @StoreNumber, @Sales) SELECT @SalesID = @@IDENTITY ❍ D. CREATE PROCEDURE procInsertSales @StoreNumber int, @Sales int, @SalesID int OUTPUT AS INSERT INTO Sales (StoreNumber, Sales) VALUES (@StoreNumber, @Sales) SELECT @SalesID = @@IDENTITY 428 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 46 Your application has two FileStream objects. The fsIn object is open for reading, and the fsOut object is open for writing. Which code snippet would copy the contents of fsIn to fsOut using a 2KB buffer? ❍ A. Int32[] buf = new Int32[2048]; Int32 intBytesRead; while((intBytesRead = fsIn.Read(buf, 0, 2048)) > 0) { fsOut.Write(buf, 0, intBytesRead); } //Clean up fsOut.Flush(); fsOut.Close(); fsIn.Close(); ❍ B. Int32[] buf = new Int32[2048]; Int32 intBytesRead; while((intBytesRead = fsIn.Read(buf, 0, 2048)) > 1) { fsOut.Write(buf, 0, intBytesRead); } //Clean up fsOut.Flush(); fsOut.Close(); fsIn.Close(); ❍ C. Byte[] buf = new Byte[2048]; Int32 intBytesRead; while((intBytesRead = fsIn.Read(buf, 0, 2048)) > 0) { fsOut.Write(buf, 0, intBytesRead); } //Clean up fsOut.Flush(); fsOut.Close(); fsIn.Close(); ❍ D. Byte[] buf = new Byte[2048]; Int32 intBytesRead; while((intBytesRead = fsIn.Read(buf, 0, 2048)) > 1) { fsOut.Write(buf, 0, intBytesRead); } //Clean up fsOut.Flush(); fsOut.Close(); fsIn.Close(); 429 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 47 You have designed a Windows application that will help users plan, manage, and file their income taxes. Because this market is competitive, you want to list the application in the Microsoft Windows catalog. Which of the following requirements must the application satisfy to be listed in the Windows catalog? (Select all that apply.) ❑ A. Install to Program Files by default. ❑ B. Properly support Add/Remove Programs. ❑ C. Support AutoPlay for CDs and DVDs. ❑ D. Fix all known bugs in the software. Question 48 You write a Windows-based application to search customer information from an XML file. Your application recursively calls the FirstChild and NextChild methods of XmlNode objects to visit every node in an XML file. When you find a node that includes customer name information, you display the information on the form. The application is not returning all the customer names from the file. What could be the problem? ❍ A. The XML file is not well formed. ❍ B. The XML file has more than one root node. ❍ C. The customer name information is stored in XML attributes. ❍ D. The HasChildNodes property is not properly set on all nodes. 430 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 49 You are developing a Windows-based application for the purchasing department of your company. The department needs to view, add, edit, and update the supplier information that is stored in a SQL Server database. You must make sure that when the user updates a supplier record, the information is successfully written to the database. Which of the following pairs of method calls should you choose to update the database? ❍ A. SqlDataTable.AcceptChanges(); SqlDataAdapter.Update(DataTable); ❍ B. SqlDataAdapter.Update(DataTable); SqlDataTable.AcceptChanges(); ❍ C. SqlDataTable.Reset(); SqlDataAdapter.Update(DataTable); ❍ D. SqlDataAdapter.Update(DataTable); SqlDataTable.Reset(); Question 50 You are developing a Windows-based application that retrieves data from a SQL Server database to perform analysis of sales history. A large number of users will use your application. The size of the sales history data is huge, and your application needs to retrieve this data very quickly. Which of the following techniques would you use to get the maximum performance when retrieving data from the SQL Server database in your Visual C# .NET application? ❍ A. Use the classes from the System.Data.OleDb namespace. ❍ B. Use the classes from the System.Data.SqlClient namespace. ❍ C. Use the XML Web Services to connect with the SQL Server database. ❍ D. Use COM components to retrieve the data from the SQL Server database. 431 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 51 You develop a Windows application named OrderManager that enables users to enter new orders and make changes to the existing orders. The application involves a DataTable named OrdersTable. The column OrderNumber defines a primary key for the OrdersTable table. Which of the following segments of code should you use to define a primary key for the OrdersTable in your Visual C# .NET program? ❍ A. DataColumn[] c = new DataColumn[1]; c[0] = t.Columns[“OrderNumber”]; OrdersTable.PrimaryKey = c; ❍ B. OrdersTable.PrimaryKey = “OrdersNumber”; ❍ C. OrdersTable.PrimaryKey.Add(t.Columns[“OrderNumber”]); ❍ D. OrdersTable.PrimaryKey = t.Columns[“OrderNumber”]; Question 52 You develop a component using Visual C# .NET. Other applications will call this component from the Internet. You want to minimize the chances of unintentional damage that the component can do to the local computer. As a result, you want to ensure that your code is not granted File I/O permissions. Which SecurityAction action should you use with the FileIOPermissionAttribute declaration? ❍ A. SecurityAction.RequestMinimum ❍ B. SecurityAction.RequestOptional ❍ C. SecurityAction.Demand ❍ D. SecurityAction.RequestRefuse 432 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 53 You design a Visual C# .NET application that uses the following code to check for membership in the Developers group: private void frmSecure_Load(object sender, System.EventArgs ➥e) { // Get the current principal object Windows Principal prin = Thread.CurrentPricipal; // Determine whether the user is a developer Boolean developer = prin.IsInRole(“Developers”); // Display the results on the UI if(developer) lblMembership.Text = “You are in the Developers ➥group”; else lblMembership.Text = “You are not in the Developers ➥group”; } Users complain that the code erroneously reports that they are not in the Developers group. What must you do to fix this problem? ❍ A. Use imperative security to make sure that your code has access to the Windows environment variables. ❍ B. Create a WindowsIdentity object by using the WindowsIdentity.GetCurrent method, and then use this object to construct the WindowsPrincipal object. ❍ C. Use the WindowsPrincipal.Name property to retrieve the user’s name, and use that name to call the IsInRole method. ❍ D. Call AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy. WindowsPrincipal) to specify the authentication mode. 433 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 54 You are using code access security to verify that your application has permission to perform file I/O operations. As part of your testing procedure, you have created a permission set that denies file I/O permissions. You have also created a code group that uses a hash code membership condition to select your application’s executable assembly and assign the permission set to this code group. You have set this code group to be an exclusive code group, and you have verified that your program cannot obtain file I/O permissions. To continue development, you change the code group to use the Everything permission set and continue adding new code to your application. When you’re ready to test the security features, you change back to the permission set without file I/O permissions. However, you find that your application cannot access files, even though you have not changed the declarative security within the application. Why is your code capable of performing file I/O even though the code group denies file I/O permissions? ❍ A. Changing code within your application changes its hash code, so it is no longer a member of the code group. ❍ B. After you’ve assigned the Everything permission set to a code group, the code group ignores attempts to set more restrictive permissions. ❍ C. The Exclusive property on a code group applies only when the code group is first created. ❍ D. You must reboot your development computer to update the membership records of the code group. Question 55 You have converted your application’s assembly files to native images using the Native Image Generation tool (ngen.exe). Which of the following statement holds true for your assemblies? (Select all that apply.) ❑ A. An application that uses a native assembly will run faster for the initial run. ❑ B. An application using a native assembly will have consistently faster performance compared to a JIT-compiled assembly. ❑ C. The native assemblies are portable. You should be able to use them on any machine that has the CLR installed on it. ❑ D. The native assemblies can be used in debugging scenarios. 434 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 56 One of your colleagues is designing a Changed event for his control. He complains to you that his code behaves quite abnormally; it runs fine sometimes and generates exceptions at other times. Part of his event-handling code is listed here (line numbers are for reference purpose only): 01: public delegate void ChangedEventHandler( object sender, ColorMixerEventArgs args); 02: public event ChangedEventHandler Changed; 03: protected virtual void OnChanged( ColorMixerEventArgs e) 04: { 05: //notify the object 06: Changed(this, e); 07:} Which of the following suggestions will solve his problem? ❍ A. The code in Line 6 should be replaced with the following: if (ChangedEventHandler != null) { //notify that object ChangedEventHandler(this, e); } ❍ B. The code in Line 6 should be replaced with the following: if (ChangedEventHandler != null) { //notify that object Changed(this, e); } ❍ C. The code in Line 6 should be replaced with the following: if (Changed != null) { //notify that object ChangedEventHandler(this, e); } ❍ D. The code in Line 6 should be replaced with the following: if (Changed != null) { //notify that object Changed(this, e); } 435 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample . . . . Test . . .#2. Question 57 You are a programmer for a popular gaming software publishing company. The company has recently designed a series of games using the .NET Framework. All these new game applications share some components. Some of these components are shipped in the box with the application, and others are deployed over the Internet. Which of the following commands will you use for these components before packaging them for deployment? ❍ A. Use sn.exe to sign the components. ❍ B. Use signcode.exe to sign the components. ❍ C. Use sn.exe followed by signcode.exe to sign your components ❍ D. Use signcode.exe followed by sn.exe to sign your components. Question 58 When you install a Windows application on a target machine, you want to store the Readme.txt file in the directory selected by the user to install the application. You also want to create a shortcut for the Readme.txt file on the desktop of the target machine. While creating a Setup project, which of the following actions will you take in the File System Editor to achieve this? (Select all that apply.) ❑ A. Move the shortcut to the Readme.txt file from the application folder to the user’s desktop in the file system on the target machine. ❑ B. Add the Readme.txt file to the Application Folder node of the file system on the target machine. ❑ C. Create a shortcut to the Readme.txt file in the Application Folder node of the file system on the target machine. ❑ D. Add the Readme.txt file to the user’s desktop in the file system on the target machine. ❑ E. Move the shortcut to the Readme.txt file from the user’s desktop to the application folder in the file system on the target machine. 436 Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Question 59 You have developed a Windows application that assists users in maintaining their timesheets. After successfully testing the application, you decide to deploy the application on the users’ computers. You ask four users to install the application on their computers and provide feedback. Three users report that they are able to create timesheets and are happy with the application’s performance. However, the fourth user reports that she is getting an error message similar to “The dynamic link library mscoree.dll could not be found.” Which of the following steps should you suggest that the user take to resolve this error message? ❍ A. Ask the user to copy all assemblies from the \bin folder to the Global Assembly Cache. ❍ B. Ask the user to install the application after installing Internet Explorer 6.0. ❍ C. Ask the user to install the application after installing MDAC 2.7. ❍ D. Ask the user to install the application after installing the .NET Framework. Question 60 You use Visual C# .NET to develop a component named ReplicateWarehouseData. This component replicates the data used by the Warehousing application that is developed by the Warehouse Development team of your company. The Warehouse Development team needs to deploy the Warehousing application to its first three customers. How should it deploy the application? ❍ A. The team should create a Merge module for the ReplicateWarehouseData component. ❍ B. The team should create a Setup project to deploy the application and should include the Merge module containing the component in the Setup project. ❍ C. The team should copy the ReplicateWarehouseData component into the directory of the Warehousing application. ❍ D. The team should create a Setup project to deploy the application that contains the code for the component. 19 Answer Key for Sample Test #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438 Chapter 19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer Key 19. C 40. B 20. B 41. D 21. C 42. C 1. A and D 22. D 43. D 2. B 23. A 44. A 3. D 24. D 45. D 4. A 25. D 46. C 5. B 26. A 47. A, B, and C 6. A, B, and E 27. A 48. C 7. C 28. A 49. B 8. C 29. A 50. B 9. D 30. C 51. A 10. A 31. B 52. D 11. A 32. C 53. D 12. D 33. B 54. A 13. D 34. A 55. A and D 14. B 35. C 56. D 15. A 36. C 57. C 16. C 37. D 58. A, B, and C 17. A 38. C 59. D 18. D 39. B 60. C and D Detailed Answers 1. The correct answers are A and D. The Debug and Trace classes share the same Listeners collection. Therefore, you should add a listener object either to the Trace.Listeners collection or to the Debug.Listeners collection. Answer B is not correct because this solution will generate double entries in the event log. Answer C is not correct because the newly created listener object is not attached to the Listeners collection of the Trace and Debug classes. 439 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer . . . . .Key . . for . .Sample . . . . Test . . .#2. 2. The correct answer is B. The Assert method checks for the given con- dition and generates an error when the condition evaluates to false. Answer A is not correct because this code segment will generate an error only when the value of TotalShipments is not equal to 0. Answers C and D are not correct because the Debug.Assert method is invoked only when the program is compiled using the Debug configuration. 3. The correct answer is D. You need to first create a filtered DataView object from the Suppliers table and bind the DataView object to the DataGrid. Answers A and C are not correct because they do not give you objects that can be bound to the DataGrid control. Answer B is not correct because although the solution works, retrieving the data from the database for the second time is slower than filtering it from the existing DataTable object. 4. The correct answer is A. The ApplyDefaultSort property is used to automatically create a sort order, in ascending order, based on the primary key of the table. The ApplyDefaultSort property applies only when the table has a primary key defined and the Sort property is a null reference or an empty string. Answer B is not correct because you want to sort using the primary key, and for that you should set the ApplyDefaultSort property to true. Answer C is not correct because you need to sort the data instead of filtering the data. Answer D is not correct because the given code segment is incorrect; you must specify the name of a column in the Sort property along with ASC (ascending) or DESC (descending). 5. The correct answer is B. The XML file has the value for the TraceLevelSwitch as 3, which sets the Level property as TraceLevel.Info. Answers A, C, and D are incorrect because setting the Level property as TraceLevel.Info will cause TraceError, TraceWarning, and TraceInfo properties of the traceSwitch to be true. Only the TraceVerbose property will evaluate to false. Also, the third parameter to the WriteLineIf method is used to categorize the output by placing its value after a colon (:) and then the trace message. 6. The correct answers are A, B, and E. Because multiple applications are using this assembly, you need to install the assembly in the Global Assembly Cache (GAC). To install the assembly into the GAC, you also need to sign the assembly with a strong name. Finally, to enable COM applications to use the assembly, you need to register the assembly in the Windows Registry. Answer C is not correct because the COM applications need not be compiled. Answer D is not correct because you do not need to use a COM DLL in a .NET application. 440 Chapter 19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answers F and G are not correct because shared assemblies should be deployed in the GAC. When an assembly is registered in the Windows Registry, COM applications can locate shared assemblies from the GAC. 7. The correct answer is C. When you release a bug-fix type upgrade of an assembly and you want calls to a particular version of an assembly to be redirected to another version of the assembly, you should deploy a publisher policy file with appropriate redirection information. Answer A is not correct because configuring all existing application configuration files in each machine requires a lot of work. Answer B is not correct because modifying the machine configuration file for each machine also requires a significant amount of effort. Answer D is not correct because if you delete Version 1.0.0 of PieChart.dll, all the existing applications that refer to that DLL will fail to execute. 8. The correct answer is C. Setting the RowStateFilter property of the DataView object to DataViewRowState.Deleted specifies that you want to view the deleted rows from the original data. Answers A and B are not correct because the RowFilter property is used to filter rows based on an expression rather than their state. Answer D is not correct because setting the RowStateFilter property to DataViewRowState.OriginalRows displays the original data of all the rows, including deleted rows. 9. The correct answer is D. If you get a DCOM configuration error while debugging, you might not be a member of the Debugger Users group on the remote machine. To resolve this, add your account on the remote machine to the Debugger Users group. Answers A, B, and C are not correct because to debug a program remotely using Visual Studio .NET, you should be a member of the Debugger Users group rather than the Power Users group on the remote computer, not the local computer. 10. The correct answer is A. The UserPreferenceChanged event is raised whenever the user changes display properties. You can check the SystemInformation.HighContrast property in this event to determine whether the user has selected High Contrast mode. Answer B is not correct because the Paint event is fired whenever the form is redrawn. Answer C is not correct because the SystemEvents.PaletteChanged event occurs when the user switches to an application that uses a different palette. Answer D is not correct because the user might change the display settings after loading the form. 441 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer . . . . .Key . . for . .Sample . . . . Test . . .#2. 11. The correct answer is A. The MaxLength property has an effect only on user input. It is not checked when you programmatically set the value of a control. Answers B, C, and D are not correct because these values allow users to enter more than three characters in the textbox. 12. The correct answer is D. To display values from an array in a ListBox or a ComboBox, you set the DisplayMember property of the control to a string containing the name of the field. Answers A and C are not correct because they use the ValueMember property instead of the DisplayMember property. The ValueMember property is used to set the value associated with the items in the ListBox or a ComboBox, but this property is not displayed in the control. Answer B is not correct because the property name of the data source must be specified as a string. 13. The correct answer is D. Using a class derived from EventArgs to pass event parameters is preferable to using individual arguments because it’s more readily extended in case you need to pass additional parameters in the future. Answers A and C are not correct because eventrelated data should be passed as an argument to the event handler. Answer B is not correct because, by convention, event handlers accept only two arguments. The first event handler is the object that received the event, and the second event handler is the object that contains the event argument. According to good programming practices, classes for event data should derive from the EventArgs class and should have names ending with the suffix EventArgs. 14. The correct answer is B. Because the Graphics object is so frequently needed during the Paint event, it is automatically passed to that event’s handler. Therefore, the easiest way to retrieve a Graphics object from the Paint event handler is through the Graphics property of the PaintEventArgs argument. Answers A, C, and D are not correct because you already have a Graphics object available through the Paint event handler. Therefore, you need not write any additional code to create another Graphics object. 15. The correct answer is A. When you run the application, the BackColor of Form2 will be Blue. Answer B is not correct because when you assign a value directly to the BackColor property of Form2, it overrides the inheritance from Form1. Answer C is not correct because changes to the same property on Form1 do not have any effect on Form2. Answer D is not correct because you have already modified the BackColor property, and the default values of a form are no longer applicable. 442 Chapter 19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16. The correct answer is C. The filters in OpenFileDialog are numbered starting at 1, rather than 0. Answers A and B are not correct because setting the FilterIndex property to 0 or 1 will select the first filter from the Filter property; therefore, it will set all image files as the default setting. Answer D is not correct because this setting will set GIF files as the default setting. 17. The correct answer is A. Answer B is not correct because to pause the rest of the application while the user makes a choice, you should use the ShowDialog method rather than the Show method to display the form. Answers C and D are not correct because when the user clicks a button on the form, the value of the DialogResult property of that button is assigned to the DialogResult property of the form. Therefore, you should use the DialogResult property of the form to retrieve the user’s choice. 18. The correct answer is D. The TraceSwitch class provides a multilevel switch to control tracing output without recompiling your code. Answer A is not correct because the /d:TRACE option just enables the tracing; it does not allow multilevel control over tracing output. Answer B is not correct because modifying environmental variables requires much more administrative efforts when compared to a configuration file. Answer C is not correct because this option requires the program to be recompiled each time the value of TRACE is modified. 19. The correct answer is C. The Locals window gives you the most con- venient access because it automatically displays the names and values of all the variables local to the current method under execution. Answer A is not correct because the This window enables you to examine the members associated with the current object. Answer B is not correct because the Autos window displays only names and values of all variables in the current statement and the previous statement rather than the current method. Answer D is not correct because you need to add variables explicitly to the Watch window. 20. The correct answer is B. Breakpoints and other debugging features are not enabled in the default Release configuration. Answer A is not correct because selecting a value from the combo box does fire the SelectedIndexChanged event. Answer C is not correct because the Conditional attribute will include or exclude the method from compilation but as stated in the question, the method does get executed. Answer D is not correct because no data type needs to be specified with the #const declaration to enable debugging. 443 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer . . . . .Key . . for . .Sample . . . . Test . . .#2. 21. The correct answer is C. Answers A, B, and D are incorrect because the TRACE symbol is defined in both the default Debug configuration and the default Release configuration. Only the DEBUG symbol is defined in the default Debug configuration. 22. The correct answer is D. When a control is docked to an edge of its container, it is always repositioned against that edge when the container is resized. Answers A and C are not correct because anchoring the control will not resize the toolbar and reposition it to the top edge of the form. Answer B is not correct because the question does not require other developers to set the Dock property. 23. The correct answer is A. The Web Service Discovery tool uses the information in the asmx file to locate the other important files for the Web Service, including the WSDL file that specifies the Web Service’s interface. Answer B is not correct because opening the file in the Web browser enables you only to test the Web Service providing information about simple data types. The Web browser cannot provide the full interface of the Web service. Answer C is not correct because the XML Schema Definition tool is used to generate schema or classes from the XML and XSD files. Therefore, this tool is of no help for the .asmx file. Answer D is not correct because you need to know the interface of the Web Service to call its Web methods; copying the .asmx file to your client project will not be of any help. 24. The correct answer is D. Adding the WebMethod attribute to a public method makes it callable from remote Web clients. Answer A is not correct because methods can be part of the public interface of a Web Service. Answer B is not correct because the WebService attribute is applied to the Web Service class, not Web methods. Answer C is not correct because Web Service methods can return any data type. 25. The correct answer is D. Using the callback is the most efficient way to manage use of your threads because the callback methods do not block threads while waiting for the response. Answers A and C are not correct because the WaitHandle.WaitAll or WaitAny methods will block the thread until the Web service calls have completed. Answer B is not correct because the End method will not return until the asynchronous operation is complete because this method uses the IAsyncResult.AsyncWaitHandle to check for Web Service completion. 26. The correct answer is A. Only the CompareInfo object will correctly handle the search in all character sets, including those that use 2 bytes per character. Answer B is not correct because Array.Sort does not locate substrings. Answers C and D are not correct because the 444 Chapter 19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . String.IndexOf and String.IndexOfAny methods can find substrings but are not culture-aware. 27. The correct answer is A. The Invariant culture provides a culture-neu- tral storage format for information that will not be directly displayed to an end user but that might need to be used in many different locales. Answers B, C, and D are not correct because these answers are specific to a particular culture. 28. The correct answer is A. The application will use resources from the MyApp.fr.resx file. Answers B and C are not correct because the application specifically searches for the fr-CA culture instead of the fr-FR or en-US cultures. Answer D is not correct because if resources from a specific culture are not found, the .NET Framework will fall back to using resources from the appropriate neutral culture—in this case, the fr culture. 29. The correct answer is A. You should allow the user to select a culture from a list. Answer B is not correct; allowing the user to choose a culture is better than accepting the existing culture of the application because the user might be running on a version of Windows that’s not appropriate for his culture. Answers C and D are not correct because there’s no need to prompt for or store a numeric format when all necessary formats are stored in the .NET Framework. 30. The correct answer is C. Answer C gives the best performance because it specifies the destination size of the image, thereby avoiding any autoscaling of the image. Answers A, B, and D are not correct because, in the absence of information about the destination size of the image, the DrawImage method needs to perform extra processing; therefore, the image is drawn slowly. 31. The correct answer is B. When you want to check whether a code has a particular privilege, you need to perform code access security. Answer A is not correct because the application requires access to the event log regardless of who is using the application. Answers C and D are not correct because type safety and encryption do not relate to the event log. 32. The correct answer is C. In the PInvoke calls, you should use a StringBuilder object instead of the String object to hold the return value. Answers A and D are not correct because the declaration of the method does not include the ref or out keywords. Answer B is not correct because all computers are identified by a name on the network. 445 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer . . . . .Key . . for . .Sample . . . . Test . . .#2. 33. The correct answer is B. Using the Type Library Importer tool enables you to place the RCW assembly in the GAC so that all projects on the computer can share it. Answers A and D are not correct because the component is being used by multiple projects and, therefore, should be placed in the GAC. Answer C is not correct because a Primary Interop Assembly is used for code from other vendors, not for your own code. 34. The correct answer is A. You need to set PrintPageEventArgs.HasMorePages to true in the PrintPage event when there are more pages to be printed in the current print job. Answers B and C are not correct because if this had been the case, all printed pages would have been affected instead of only the first page. Answer D is not correct because there is no need to call a separate Print method to print every page of the document. 35. The correct answer is C. The AccessibleName property is used to set the name that is used by accessibility applications such as a screen reader. Answers A and B are not correct because they are not used by the accessibility applications. Answer D is not correct because the AccessibleRole property is used to specify a role for an accessible object instead of the name. 36. The correct answer is C. When you use the Close method of a SqlConnection object, the connection is closed, all pending database transactions are rolled back, and the connection is returned back to the connection pool. Answer A is not correct because reusing an instance after you have called the Dispose method can result in undesirable effects. In general, you should use Close rather than Dispose if you might want to reuse the connection instance. Answer B is not correct because you should generally call the destructor only when you need to release unmanaged resources. Answer D is not correct because setting the SqlConnection object to null will not actually close the connection; the object will continue to exist in memory, waiting for garbage collection. 37. The correct answer is D. The DataSetName property of a DataSet object sets the name of the DataSet. The value of this property is rendered as the root element of the XML file. Answer A is not correct because the Namespace property specifies the namespace of the DataSet object. Answer B is not correct because the Locale property specifies the culture information to be used for string comparison within the tables. Answer C is not correct because the Prefix property specifies an XML prefix that is used as an alias for the namespace of the DataSet object. 446 Chapter 19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38. The correct answer is C. A DataRelation is used to relate two DataTable objects to each other. Answers A and B are not correct because just defining primary keys or foreign keys on the table will not relate the tables. Answer D is not correct because the DataSet.Merge method is used to merge two DataSet objects, which is not a requirement in this case. 39. The correct answer is B. The XmlValidatingReader object enables you to validate an XML document. You use its ValidationEventHandler event to set an event handler for receiving information about the schema validation errors. Answer A is not correct because the XmlDocument object cannot validate the XML document on its own. Answer C is not correct because the EnforeceConstraints property of the DataSet is used to specify whether the database constraint rules are followed when attempting any update operation. Answer D is not correct because the DataSet.MergeFailed event occurs only when a target and source DataRow have the same primary key value, and EnforceConstraints is set to true. 40. The correct answer is B. The LIKE clause determines whether a given character string matches a specified pattern. You use the % character to work as the wildcard character. Answer A is not correct because you need to use the LIKE clause instead of the IN clause for pattern searching. Answers C and D are not correct because you need to use % as the wildcard character for matching instead of the * character. 41. The correct answer is D. OleDbDataReader enables you to read the data one row at a time in a forward-only fashion; therefore, it occupies less memory and improves performance of your application. The question requires you to read the data in a sequential fashion and write it to the flat file; the OldDbDataReader object is the best option. Answer A is not correct because a DataSet object loads all of the retrieved data in the memory. Answer B is not correct because you cannot retrieve the data directly in a DataTable object. Answer C is not correct because the SqlDataReader object is optimized to work with SQL Server 7.0 and later versions. 42. The correct answer is C. Within the Enterprise level, the permission set granted to the CalculateTax assembly is the union of all the permission sets of code groups on the Enterprise level to which it belongs— that is, the All Code and Company Code groups. Therefore, CalculateTax receives the Everything permission at the Enterprise level. At the Machine level, the assembly is a member of only the Restricted Code group and thus receives the LocalIntranet permission. 447 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer . . . . .Key . . for . .Sample . . . . Test . . .#2. Because the code group on the Machine level is marked with the LevelFinal property, the code group on the User level is not taken into account when determining the permission set for this assembly. Now to determine the permission set granted to the CalculateTax assembly, you need to determine the intersection of all the permission sets of the levels applicable to the assembly. Therefore, the assembly is granted LocalIntranet permission, the intersection of Everything and LocalIntranet permissions. Answer A is not correct because Everything is the permission set for only the Enterprise level. Answer B is not correct because Inter is the permission set for the code originating from the Internet. Answer D is not correct because the User level is not taken into account because the LevelFinal property is Yes for the Machine level. 43. The correct answer is D. Because other operations on the database, such as add and update, are working fine, chances are good that the DeleteCommand property is not set. The DeleteCommand property should be set to a command that deletes rows from the database. Answers A and C are not correct because if that was the case, none of the changes would be saved. Answer B is not correct because the Update method updates the underlying database with the changes made to the DataSet. 44. The correct answer is A. The XmlTextWriter object is specially designed to write XML files. Answer B is not correct because the XmlWriter is an abstract class and must be implemented before you call methods from it. Answers C, D, and E are not correct because when you use these objects, you have to write additional code for the XML structure. 45. The correct answer is D. Answer A is not correct because it does not indicate that @SalesID is an output parameter. Answers B and C are not correct because they attempt to insert values into the identity column rather than let SQL Server assign the new value. 46. The correct answer is C. The Read method returns the number of bytes read, so answers B and D fail when there is 1 byte in the file. The Read method reads to a byte array, so answers A and B fail because the buffer has the wrong data type. 47. The correct answers are A, B, and C. To be listed in the Windows cat- alog, an application must meet the requirements mentioned in the specifications of the Windows logo program. Answer D is not correct because you are not required to fix all known bugs to be listed in the Windows catalog. 448 Chapter 19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48. The correct answer is C. By default, XML attributes do not appear as part of the XmlNodes collections that are traversed by the FirstChild and NextChild methods. Answers A and B are not correct because if that was the case, you would not be able to load the file into an XmlDocument object. Answer D is incorrect because HasChildNodes is automatically set by the .NET Framework. 49. The correct answer is B. When an application calls the Update method, the SqlDataAdapter object examines the RowState property and executes the required InsertCommand, UpdateCommand, or DeleteCommand statements iteratively for each row of the data. After the changes are written to the database, you need to call the DataTable.AcceptChanges method to remove the deleted rows and set the RowState property of the added and modified rows to Unchanged. Answer A is not correct because if you first call the AcceptChanges method, the RowState for all the added and modified rows will be marked Unchanged and all the deleted rows will be removed. Later, when you call the Update method, the SqlDataAdapter object will not be capable of updating the database because the RowState property of the rows will be Unchanged. Answers C and D are not correct because the Reset method restores the DataTable to its original state and the updates made to the table are lost in the DataTable object. 50. The correct answer is B. The classes in the System.Data.SqlClient namespace provide the best performance when working with SQL Server data because these classes can communicate with the SQL Server database directly using the SQL Server tabular data stream (TDS) packets. Answer A is not correct because the classes in the System.Data.OleDb namespace call a set of COM components (an OLE DB provider), which constructs the TDS packets to communicate with the SQL Server. Answer C is not correct because XML Web Services will have a lot of additional overhead when compared to a direct connection to the SQL Server database. Answer D is not correct because calling COM components involves an extra COM-Interop layer and slows down the operation. 51. The correct answer is A. The PrimaryKey property of the DataTable object specifies an array of column(s) that function as primary keys for the data table. Answer B is not correct because the data type of the PrimaryKey property is not String. Answer C is not correct because the PrimaryKey property does not provide an Add method. Answer D is not correct because even if the PrimaryKey is a single column, an array of DataColumn must be used with the PrimaryKey property. 449 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Answer . . . . .Key . . for . .Sample . . . . Test . . .#2. 52. The correct answer is D. SecurityAction.RequestRefuse ensures that permissions that might be misused will not be granted to the calling code. Answers A, B, and C are not correct because these settings are used to request permissions instead of refuse permissions. 53. The correct answer is D. You must tell the CLR how users are authen- ticated, even when you are using a Windows application that automatically employs Windows authentication. Answers A, B, and C are not correct because they do not specify the authentication mode. 54. The correct answer is A. The hash codes are calculated from the MSIL code of an assembly, so changing the assembly’s content changes its hash code. Answers B, C, and D are simply incorrect. 55. The correct answers are A and D. The native assemblies will load faster for the first time because the ngen.exe has already done the work that the JIT compiler will do when executing the application for the first time. The ngen.exe tool also provides a /debug switch that can be used to generate native assemblies for debugging scenarios. Answer B is not correct because, for subsequent execution, the native assemblies would show the same performance as the JIT-compiled equivalent. Answer C is not correct because the natively generated assemblies are processor specific and are not portable across different processor architectures. 56. The correct answer is D. The OnChange method invokes the Changed event to notify all registered objects about the event. If the Changed object is null, no delegate objects have been registered with this event. On the other hand, if the Changed object is not null, the call to Changed event will invoke the registered event handlers. Answers A, B, and C are not correct because the name of the event is Changed rather than ChangedEventHandler. 57. The correct answer is C. Because the components are being used among several games published by your company, they are good candidates to be placed in the Global Assembly Cache of the target machine. Before a component can be placed in the GAC, however, it must be signed using a Strong Name tool (sn.exe). Your company is also deploying software over the Internet; in this case, it is a good idea to digitally sign your code with a software publisher’s certificate obtained by a respected certification authority. When you obtain the certificate, you can use signcode.exe to sign your component. When you are using both sn.exe and signcode.exe with your assembly, you should always use sn.exe before using signcode.exe. Answers A and B are not correct because you need to use both of the tools instead of just 450 Chapter 19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . one of them. Answer D is not correct because sn.exe should be used before signcode.exe. 58. The correct answers are A, B, and C. To copy the Readme.txt file to the installation directory selected by the user at install time, you would add it to the application folder in the file system on the target machine. To create a shortcut, you first create a shortcut to the Readme.txt file stored in the application folder in the file system on the target machine. Then you move this shortcut from the application folder to the user’s desktop in the file system on the target machine. Answer D is not correct because you need to place a shortcut on the user’s desktop instead of the file itself. Answer E is not correct because the Readme.txt file is originally present in the application folder instead of the user’s desktop. 59. The correct answer is D. The mscoree.dll file is the core file of the Common Language Runtime. If the user is getting the specified error message, the most likely reason is that the .NET Framework is not installed or is not properly installed on the user’s computer. Answer A is not correct because a similar installation is working on other computers. Answers B and C are not correct because mscoree.dll is not a part of Internet Explorer 6.0 or MDAC 2.7, and reinstalling those applications will not resolve the problem. 60. The correct answers are C and D. The Warehousing application is the only application using the component. Therefore, you should copy the component to the Warehousing application. You can now create a Setup project to deploy the application and component. Answers A and B are not correct because the Merge Module projects are used to create reusable setup components. A Microsoft Certification Exams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Taking an exam is not something that most people anticipate eagerly, no matter how well prepared they might be. In most cases, familiarity helps offset test anxiety. In plain English, this means that 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 that 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 a Microsoft Certified Application Developer (MCAD) or Microsoft Certified Solution Developer (MCSD) for Microsoft .NET certification, and it will also help you identify parts of your background or experience that need improvement, enhancement, or further learning. If you get the right set of basics under your belt, obtaining Microsoft certification will be that much easier. 452 Appendix A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . After you’ve gone through the Self-Assessment, you can remedy topical areas in which your background or experience is 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, 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 75% 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. 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. When your time slot arrives, you’ll be asked to deposit any books, bags, cell phones, and 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 few blank sheets of paper and a pen (in some cases, an erasable plastic sheet and a marker). 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 your thoughts and write down information on the paper you’re given. When you are ready, the exam coordinator will load the appropriate Microsoft certification exam (such as, Exam 70-316), and you’ll be permitted to start. 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 453 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . . like). All Microsoft certification exams are computer-generated. In addition to multiple-choice questions, you may encounter select–and-place (dragand-drop), create-a-tree (categorization and prioritization), drag-andconnect, and build-list-and-reorder (list-prioritization) questions on many exams. The questions are constructed to check your development skills using Microsoft Visual C# .NET and Visual Studio .NET. Often you’ll be asked to give more than one answer to a question. You also might 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: New Case Study Format 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 might have the same six types of questions but no complex multiquestion case studies. For the Design exams, each case study presents a detailed problem that you must read and analyze. Figure A.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 A.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 six 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. 454 Appendix A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . After you complete a case study, you can review all of the questions and your answers. However, when you move on to the next case study, you cannot return to the previous case study or make any changes. Following are the six types of question formats: ➤ Multiple choices, single answer ➤ Multiple choices, multiple answers ➤ Build, list, and reorder (list prioritization) ➤ Create a tree ➤ Drag and connect ➤ Select and place (drag and drop) Exam formats could vary by test center location. You might want to call the test center to see if you can find out which type of test you’ll encounter. Some exams are offered in both forms on a random basis, which cannot be predetermined. 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. 1 ❍ B. 2 ❍ C. 3 ❍ D. 4 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 455 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . . are led to believe that Schema Masters may be in each domain or that you should have one for each contiguous domain namespace. 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 the answer. Let’s examine a question in which 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? (Check all correct answers.) ❑ A. The ntdsutil.exe utility ❑ B. The Replication Monitor ❑ C. The secedit.exe utility ❑ D. 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 are 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 reordered into a specific order. These questions are usually in the form, “From the following list of choices, pick the choices that answer the question. Arrange the list in a certain order.” 456 Appendix A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 a sample of how they appear on the test, see Figure A.2. Figure A.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 The correct answer is: George Washington Thomas Jefferson Andrew Jackson Abe Lincoln 457 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . . 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 might 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). After 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 a sample of how they appear on the test, see Figure A.3. Question 4 The calendar year is divided into four seasons: Winter Spring Summer Fall 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 458 Appendix A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 of the items in the list were used. However, this might 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 + 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 A.3). 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. 459 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . . Figure A.3 This is how create-a-tree questions appear. Question 5 The following objects represent the different states of water: Ice Water Vapor Water Steam Use items from the following list to connect the objects so that they are scientifically correct. Sublimates to form Freezes to form Evaporates to form Boils to form Condenses to form Melts to form The correct answer is: 460 Appendix A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 may not be used at all. 1. [Place here] 5. All requirements are met; a dial-up connection is allowed for the client. Yes No Access Denied Deny Allow 2. [Place here] Deny 3. [Place here] Allow Policy Conditions Account Conditions Policy Permissions Account Profile Account Permissions Policy Profile The correct answer is: 4. [Place here] 461 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . . Microsoft’s Testing Formats Currently, Microsoft uses four different testing formats: ➤ Case study ➤ Fixed length ➤ Adaptive ➤ Short form 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. Other Microsoft exams employ advanced testing capabilities that might 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 www.microsoft.com/TRAINCERT/mcpexams/faq/ innovations.asp includes a downloadable series of demonstrations and samples. 462 Appendix A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 high levels of knowledge or ability are presented with a smaller set of more difficult questions, whereas individuals with lower levels of knowledge are presented with a larger set of easier questions. Two individuals may answer the same percentage of 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 might answer more questions than more knowledgeable 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 (also raising the test software’s estimate of the test-taker’s knowledge and ability level). An incorrect answer leads to a less difficult question (also lowering 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 testtaker’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 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 testtaker’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 might contain a combination of adaptive and fixedlength questions. 463 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . . Because you won’t know in which form the Microsoft exam will 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 into the test itself on an adaptive exam, whereas the layout remains the same for a fixedlength or short-form test, no matter how many questions you answer incorrectly. The biggest difference between adaptive tests and fixed-length or short-form tests is that you can mark and revisit questions on fixed-length or 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. You can return to these questions if you want. ➤ Short-form tests have 25 to 30 questions with a check box. You can return to these questions if you want. ➤ Adaptive tests are identified in the introductory material of the test. They have no check box and can be visited (and answered) only once. Some tests contain a variety of testing formats. For example, a test might start with a set of adaptive questions, followed by fixed-length questions. 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 or 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 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 464 Appendix A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . approach each case study as a standalone test. The biggest challenge you’ll encounter is that you’ll feel that you won’t have enough time to get through all of the cases that are presented. Each case provides a lot of material that 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 might 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 fixed-length or short-form exams 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 more 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 completely before answering the trickier questions: Sometimes information supplied in later questions sheds more light on earlier questions. At other times, information that you read in later questions jogs your memory about facts, figures, or behavior that helps 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. 465 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . . 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 might provide the missing details, or you might 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 that 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 five 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 might 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. Adaptive Exam Strategy 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 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 466 Appendix A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . through the test. Sometimes information supplied in earlier questions might 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 if a test is fixed length, short form, adaptive, or a combination, 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 might suffer for your guess on the next question if you guess correctly because the software will give you a more difficult question next!) Question-Handling Strategies For 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. 467 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . . 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 that 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 when you leave a testlet, you might 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” actions might be critical as well. If a utility must be restarted before proposed changes take effect, a correct answer might 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 of the practice questions at the end of each chapter, you should become aware of those areas in which additional learning and study are required. After you’ve worked your way through the book, take the practice exam in the back of the book. Taking this test 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 exam 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 468 Appendix A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . practice exam. You should score 80% or better on the practice exam before proceeding to the real thing (otherwise, obtain some additional practice tests so you can keep trying until you hit this magic number). 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. If you haven’t already visited the Microsoft Certified Professional site, do so right now. The MCP home page resides at www.microsoft.com/traincert (see Figure A.4). Figure A.4 The Microsoft Certified Professional Training and Certification home page. 469 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Microsoft . . . . . .Certification . . . . . . Exams . . . . Coping with Change on the Web Sooner or later, all of 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 might 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 facility. On all of Microsoft’s Web pages, a Search button appears along the top edge of the page. You can also use search engines such as www.google.com to quickly find the information that you are looking for. In fact, Google has a special page (www.google.com/ microsoft) that enables you to search Microsoft-related resources on the Web. B What’s on the CD-ROM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472 Appendix B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 C, “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), several utility and application programs, and a complete listing of test objectives and where they are covered in the book. Finally, a pointer list to online pointers and references are added to this CD. You will need a computer with Internet access and a relatively recent browser installed to use this feature. PrepLogic Practice Tests, Preview Edition PrepLogic is a leading provider of certification training tools. Trusted by certification students worldwide, we believe PrepLogic is the best practice exam software available. In addition to providing a means of evaluating your knowledge of the Exam Cram 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. Again, for a more detailed description of the PrepLogic Practice Tests, Preview Edition features, see Appendix C. Exclusive Electronic Version of Text The CD-ROM also contains the electronic version of this book in Portable Document Format (PDF). The electronic version comes complete with all figures as they appear in the book. You will find that the search capabilities of the reader comes in handy for study and review purposes. 473 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .What’s . . . .on. the . . CD-ROM . . . . . Easy Access to Online Pointers and References The Suggested Reading section at the end of each chapter in this Exam Cram contains numerous pointers to Web sites, newsgroups, mailing lists, and other online resources. To make this material as easy to use as possible, we include all this information in an HTML document entitled “Online Pointers” on the CD. Open this document in your favorite Web browser to find links you can follow through any Internet connection to access these resources directly. C Using the PrepLogic Practice Tests, Preview Edition Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476 Appendix C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . This Exam Cram 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 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 is designed to offer the most effective exam simulation available. 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 chapters and help you to 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 yourself for taking the actual exam by making the test experience a familiar one. Using this test simulation can help to 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 477 . . . . . . . . . . . . . . . .Using . . . the . . PrepLogic . . . . . .Practice . . . . Tests, . . . .Preview . . . . Edition . . . . Software . . . . . 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 per- formance ➤ 10MB of hard drive space 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. Follow these instructions to install the software on your computer: 1. Insert the CD into your CD-ROM drive. The Autorun feature of Windows should launch the software. If you have Autorun disabled, click the Start button 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 478 Appendix C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . is removed from your system 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 currently installed on your com- puter. Select the appropriate PrepLogic Practice Tests, Preview Edition title you wish to remove. Click the Add/Remove button. The software is then removed from you computer. Using PrepLogic Practice Tests, Preview Edition PrepLogic is designed to be user friendly and intuitive. Because the software has a smooth learning curve, your time is maximized, as you will start practicing almost immediately. PrepLogic 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 reveal 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 a full explanation for each question during the exam. When not enabled, you must wait until after your exam has been graded to view the correct answer(s) and explanation(s). 479 . . . . . . . . . . . . . . . .Using . . . the . . PrepLogic . . . . . .Practice . . . . Tests, . . . .Preview . . . . Edition . . . . Software . . . . . ➤ Enable Item Review Button—Activates the Item Review button, allowing you to view your answer choices, marked questions, and facilitating navigation between questions. ➤ Randomize Choices—Randomize answer choices from one exam session to the next; makes memorizing question choices more difficult, therefore 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 will enable the options detailed above. To your left, you are presented with the options of selecting the pre-configured Practice Test or creating your own Custom Test. The pre-configured 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 includes a single pre-configured 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. 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 pre-configured 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 accessible are active. The buttons are as follows: 480 Appendix C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ➤ 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 leaves the question window and opens the Item Review screen. From this screen you will see all 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—This option allows you to view the previous question. ➤ Next Item—This option allows you 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 if you would like to continue taking your exam or view your exam report. Time Remaining If the test is timed, the time remaining is displayed on 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 if you want to continue taking the test or if you want to 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, 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. 481 . . . . . . . . . . . . . . . .Using . . . the . . PrepLogic . . . . . .Practice . . . . Tests, . . . .Preview . . . . Edition . . . . Software . . . . . The PrepLogic Exam Competency Score reflects the level of subject competency required to pass this vendor’s exam. While 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. Review Your Exam From Your Score Report screen, you can review the exam that you just completed by clicking on 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 Each PrepLogic Practice Tests, Preview Edition that accompanies your Exam Cram 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 all new challenging Practice Tests for this exam. PrepLogic Practice Tests—Because You Want to Pass the First Time. 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 http://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] 482 Appendix C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . access control The process of restricting access to functionality based on role or assigned permissions. accessibility Coding that makes your application usable by those with disabling conditions. ActiveX controls Components developed using earlier Microsoft development languages such as Visual Basic and Visual C++, designed to run in the Web browser and in desktop applications. ad-hoc query An SQL query that is executed immediately. ADO.NET A set of classes, which are part of the .NET Framework, for integrating .NET applications and Web services with relational databases and other data sources. Anchor property A control property used to link the control to a position on its form. Application class A class that provides static methods and properties for managing an application. assembly A logical grouping of files sharing a single Assembly Manifest. Assembly Manifest File that includes the metadata for an assembly. Authenticode A type of digital signature supported by a thirdparty certificate authority (CA) such as VeriSign or Thawte. Autos One of the program state windows used during debugging to provide information on the variables within the current and previous statements. aximp.exe The Windows Forms ActiveX Control Importer (aximp.exe), a command-line utility that can be used to encapsulate ActiveX components within objects of the AxHost wrapper class. 484 backing store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . backing store A place where you can store a file. BeginPrint event Occurs before the first page of a print job is printed by invoking the Print method of the PrintDocument. BinaryReader class A class from the System.IO namespace that reads primitive data types as binary values, using a specified encoding. BinaryWriter class A class within the System.IO namespace that allows writing the primitive data types to the output stream in binary format. bootstrapper An element that can be used to preinstall the Windows Installer utility before installing a deployed .msi package. bottom-up testing A testing approach that begins testing at the unit level and then tests increasing levels of integration. breakpoint Causes code execution to pause when encountered. Brush class A class used with the Fill methods of the Graphics class to specify the pattern or color used to fill the shapes. CAB (cabinet files) A redistributable file that can be used to deploy an application. An application can be broken into several cabinet files to limit the maximum size per file, allowing distribution using small-capacity media such as floppy disks. Call Stack window One of the program state windows used during debugging to display the path through which program execution reached the current point within the code. catch block Block used to provide error-handling capability over the defined region of code within a try block. catch blocks are evaluated until a matching condition is reached. Unhandled exceptions fire an UnhandledException event. CausesValidation property When set to false, this property allows a control to act without firing the Validating and Validated event of the control that currently has focus, so that user assistance controls can act to provide information without requiring the user to leave the control that currently has the focus. character encodings A set of characters and their associated numerical values. CheckBox control A control that allows basic selection of on/off (two-state) or on/off/indeterminate (three-state) status. CheckedListBox control An extension of the ListBox and CheckBox controls, allowing selection to be performed using check boxes for each item. class A construct that has associated attributes and methods. 485 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CurrentCulture . . . . . . . . property . . . . . CloseMainWindow method Method that can be used with applications that have a user interface, equivalent to clicking the Close button. component An object that encapsulates both data and code, and provides a well-specified set of publicly available services. code group A set of assemblies that share a security context. container Can contain other objects, such as controls or components. code-access security Manages the security of .NET source code itself, ensuring that permissions are verified before the code executes. Code-access security involves permissions for code group access. control A reusable object that provides visual interface. Each type of control has its own set of properties, methods, and events that make it suitable for a particular purpose. ColorDialog dialog box A dialog box that displays a list of colors and returns a property containing the selected color. CreateEventSource method Method that creates an event source for an application, creating the log if it does not yet exist. COM/COM+ components Technologies used in earlier Microsoft development languages to allow components to communicate with one another. CLR (Common Language Runtime) A 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. ComboBox control A control that allows selection of a single value from a provided list, as well as the input of a new value, if allowed. Common Language Runtime (CLR) See CLR. complex data binding The process of connecting a user interface control to an entire collection of data rather than to a single data item. For example, binding a DataGrid or ListBox object with a DataTable object. culture Specifies local settings, including language, alphabet, sort order, direction of information presentation, and other localespecific details. CultureInfo class Class that provides various items of information about a particular culture. CurrentCulture property Property that dictates the format used for dates, times, currency, numbers, and string comparison and casing rules. 486 CurrentUICulture property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CurrentUICulture property Property that specifies the culture to use when selecting resources for the user interface. Custom Actions Editor A deployment editor used to run DLL, EXE, assemblies, or script files that will be called during the install, commit, rollback, or uninstall phases of package installation. data binding The creation of a link between the data model and the user interface. Data Form Wizard A utility within Visual Studio .NET that is used to automate many databinding tasks. data provider An object used to access and manage data stored within DataSet objects. DataAdapter A two-way transfer conduit between data provider and DataSet objects. DataColumn A single element (field) of data values within a DataTable. DataReader A read-only conduit through which a result set can be rapidly read, but which is accessible only in sequence from first to last. DataRelation A relationship object in a DataSet object that represents a relationship between the key values stored in two DataTable objects. DataRow A single line (record) of data within a DataTable. DataSet A server-independent store that can hold multiple tables and their relationships. DataTable object An ADO.NET object that represents one table of in-memory data. DataView A filtered view of data derived from one or more related DataTable objects within a DataSet object. DateTimePicker control A control that allows selection of date and time values using a variety of formats. Debug mode The default compilation mode when using Visual Studio .NET. This mode includes both the TRACE and DEBUG symbol sets. DEBUG symbol One of the symbol sets used to instrument a program for tracing, included only when an application is compiled in Debug mode. delay signing A process used during application testing in which a strong name is created by signing the assembly using the public key rather than the private key (which is later used for final signing before distribution). delegate A reference type that stores references to a method that has a specific signature. A delegate object can be used to dynamically invoke a method at runtime. 487 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .FCL . . (Framework . . . . . . .Class . . .Library) . . . . DELETE statement The TSQL statement used to delete one or more records from a table within a database. dialog boxes Boxes used to prompt user input within an application. Default dialog boxes include the ColorDialog, FontDialog, OpenFileDialog, PageSetupDialog, PrintDialog, PrintPreviewDialog, and SaveFileDialog dialog boxes. disco.exe The Web Services Discovery tool (disco.exe), a command-line tool used to discover a Web service. Disco A Microsoft standard for the creation of Web Service discovery documentation that contains paths and URLs for the documentation and WSDL file describing the service. Dock property Specifies the edge of the parent container to which a control is docked. DomainUpDown control A control that returns a string value selected from an indexed list of values, navigated using up and down buttons on the control. Draw method A method that can be used to draw graphics on a form. dynamic properties Properties managed at runtime by the System.Configuration.AppSettings Reader class. element A single data value within a record, also called a field. EndPrint event Event that fires once after the last page of the job has printed. ErrorProvider component Component that allows the display of a small icon that provides a mouseover ToolTip detailing a validation error’s details. event handler A method that executes in response to an event. event handling The act of responding to an event by executing event handlers. See also event handler. EventLog class Class that provides the capability to read from or write to a Windows event log. exception An unexpected problem that occurs during the normal execution of a program such as a missing file, invalid data, or operations. Exceptions must be handled in an application’s code to prevent the application’s default behavior, which is termination. Extensible Markup Language (XML) See XML. FCL (Framework Class Library) 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 designed to be the foundation on which the .NET Framework applications, components, and controls are built. 488 field . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . field A single data value within a record, also called an element. File System Editor A deployment editor used to customize the system configuration that will be used during package installation. File Types Editor A deployment editor used to specify file type associations that will be created during installation. FileStream class A class within the System.IO namespace that treats data as a stream of bytes. filtering The presentation of only a useful or target subset of data from the data model. finally block Block used in conjunction with try block of code. It executes whether or not an exception is raised. FontDialog dialog box A dialog box that enables the user to select a font and its properties. Form class A container class within the System.Windows.Forms namespace that can be used to create an application that provides a visual user interface. Framework Class Library The shared class library that allows code developed using .NET languages to inherit class types transparently. Global Assembly Cache A code cache of assemblies that are supposed to be shared by multiple applications in a computer. globalization The phase in the localization process in which all localizable resources are identified separately from the fixed-code portions of an application. GroupBox control A container control that includes a caption. HelpProvider component A component that can be used to link an application with its HTML Help files or pop-up help text. high-contrast mode Mode used to support users who have visually disabling conditions who require a greater level of contrast than the normal Windows default settings. HScrollBar control A control that provides horizontal scrolling capability. HTML Help Multipaned HTML Help files that can be cross-linked using hyperlinks. This is the standard Windows form of help file. IDE (integrated development environment) A set of Windows-based tools for building, testing, debugging and deploying an application using a single integrated environment. Immediate window One of the program state windows used during debugging for real-time evaluation of variables and expressions within the Command window. inheritance The capability of one class to inherit the members of its parent class or classes. 489 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . logo . . .programs . . . . . INSERT statement The TSQL statement used to insert one or more records into a table within a database. Integrated development environment See IDE. internal modifier A class member with an internal modifier is accessible to all classes within the current project. Invalidate method A method used to invalidate a specified region and trigger a Paint event. Invariant culture A special culture that can be used to interact directly with system services. IsInRole method Method that enables you to test the role membership of the current user. KeyPress event Event that can be used to intercept user keyboard input characters for validation testing. Kill method Method that terminates a local process immediately without saving data or performing resource cleanup. Label control A control that displays read-only data to the user. Launch Conditions Editor A deployment editor used to specify conditions that must be met before package installation can begin. LinkLabel control A control that provides read-only data with a hyperlink capability. ListBox control A control used to allow selection of one or multiple values from a list of options. listener Classes derived from the TraceListener class that handle the reporting of data provided by the Trace and Debug classes. ListView control A control that provides navigation through a series of values, including icons, names, and associated text. localizability The phase in the localization process in which checks are made to ensure that localization will not require design changes for different cultures. localization The process of customizing an application to support different locales through culturespecific settings. Locals window One of the program state windows used during debugging to show all of the variables that are local to the current method being executed. Location property A control property used to specify the absolute location of the upper-left corner of a control. logo programs Program in which Microsoft allows developers to include a logo reflecting the degree to which a new application conforms to the guidelines for Windows development if all of the requirements for the particular program are met. 490 Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Lookup A view used to transform data into a human-readable form, often by providing a translation between a stored numerical key value and its human-readable text equivalent. one-way data binding Binding form in which changes to the underlying data are reflected in the user interface, but changes to data within the user interface are not propagated back to the data model. Merge Module A package used to deploy redistributable packages that include shared components and assemblies. OpenFileDialog dialog box A dialog box used to browse for a particular file. mirroring Changing control layout and text input direction to accommodate cultures that read and write from right to left. MonthCalendar control A control that allows selection of a date using a calendar-formatted display. namespace A logical naming scheme for grouping related classes. The .NET Framework uses a hierarchical naming scheme for grouping classes into logical categories of related functionality, for example System.Windows is a namespace for grouping classes related to Windows-based applications and System.Data is a namespace for grouping data manipulation classes. .NET Framework A platform for building, deploying, and running XML Web services and applications. The .NET Framework consists of three main parts: the CLR, the FCLs, and a set of language compilers. NumericUpDown control A control that returns a numeric value, navigated using up and down buttons on the control. PageSettings class Class used to manipulate settings that involve the size and layout of a printed page. PageSetupDialog dialog box A dialog box that allows a user to select page layout settings. panel control A container control that includes basic scrolling capability. Pen class A class used with the Draw method to draw lines and curves. PerformanceCounter class Class that provides access to performance data about running processes, as well as the publication of performance data over a network. permission sets Contain one or more permissions that are assigned as a unit. permissions Grant or deny access to a resource. PictureBox control A control used to display graphical images, including icon (.ico), bitmap (.bmp), metafile (.wmf), JPEG/JPG, PNG, and GIF files. 491 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . RadioButton . . . . . . . control . . . . PInvoke (Platform Invoke) Platform Invocation, used to call functions from unmanaged Windows API libraries. Platform Invoke See PInvoke. pop-up help Help that enables a user to click the Help button and then a target control to display help information for that control. PrincipalPermission class Class that can be used to determine the group membership of the current user. Print method Method of a PrintDocument object that fires its PrintPage event, sending data output to the target device. PrintDialog dialog box A dialog box used to select print options and submit a print job to the selected printer. PrintDocument class Class that provides support for printed output. preview a document within the application before printing. PrintPreviewDialog dialog box A dialog box that allows viewing of printed output before it submits the job to the printer. private member A class member accessible only to its containing type. Process class Class that provides information about processes running on a system, local or remote, and that also allows control over starting and stopping processes on the local system. ProgressBar control A control used to display progress across a scaled bar. protected member A class member accessible to the containing type and all classes derived from the containing type. public member A globally accessible member of a class. PrinterSettngs class Class used to access and manipulate properties of the target printer. Publisher The class that informs the occurrence of an event to its subscribers. PrintPage event An event that fires once for each page to be printed. QueryPageSettings event Occurs immediately before each PrintPage event of a print job. PrintPageEventArgs class Class used to expose properties of the printed page, such as its margins. RadioButton control An extension of the CheckBox control, allowing a group of check boxes to be used to select a single value from the group of check boxes. PrintPreviewControl control A control that includes the basic functionality to enable a user to 492 record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . record A single line of data within a table, containing one or more elements (or fields). Registry Editor A deployment editor used to specify Registry keys, subkeys, and values that will be registered to the target computer’s Registry during package installation. regression testing Retesting using all previous tests after a change or addition to existing code. relational database Database that stores related data grouped into tables, related by primary key/foreign key relationships. resource file A storage location for culture-specific localized resources, such as strings and bitmap images. RichTextBox control A control that allows single-line or multiline textual input, including support for Rich Text Format (.rtf) input. role-based security Security that manages the logon account’s access rather than the application code itself, allowing control of application access based on user or group membership. sampling The process of reading the value of a performance counter. satellite assembly Assembly used to include resource files within an assembly, such as those used for a particular localized culture. SaveFileDialog dialog box A dialog box that enables the user to browse for the location and specify the name to be used when saving a file. SELECT INTO statement A special form of the SELECT statement used to create a new table from the data resulting from the SELECT statement. SELECT statement The TSQL statement used to retrieve data from one or more tables within a database. Show method A method used to display a Graphics object. simple data binding The connection of a single data value to a single property of a control. SOAP (Simple Object Access Protocol) SOAP is an XMLcompliant protocol for exchanging structured and type information via the Internet, typically over HTTP. SOAP is the primary protocol used for communication between Web services and Web service clients. stored procedure A precompiled collection of Transact-SQL statements stored under a name and processed as a unit. SQL Server supplies stored procedures for managing SQL Server and displaying information about databases and users. stream A flow of raw data. 493 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .this . .window . . . . StreamReader class A class within the System.IO namespace that implements a TextReader for reading characters from a byte stream in a particular encoding. StreamWriter class A class within the System.IO namespace that implements a TextWriter for writing characters into a byte stream in a particular encoding. string indexing Parsing an input string character by character for validation, taking into account the fact that some characters are 16-bit and others are 32-bit. strong name A name that consists of an assembly’s identity—its name, version, and culture, as well as a unique digital signature generated over the assembly. Assemblies with the same strong name are expected to be identical. stub A replacement code segment that automatically returns the correct response when called by the module being tested. Stubs are mostly used in the case when the actual code is not yet available. Subscriber A class that receives notification about an event from an event publisher class. System.Drawing namespace Namespace that includes classes used in creating graphical elements. System.IO namespace Namespace used to access filebased data storage. System.Xml namespace Namespace used to access and manipulate XML data files. TabControl control A container control that allows the grouping of controls within tabbed pages for rapid navigation. TabIndex The order in which a control receives focus when a user tabs through the controls on a form. table of contents Element supported by HTML Help that helps users rapidly identify and navigate to a desired topic. TabStop property A control property used to specify whether the control can receive focus as a user tabs through controls on a form. testing Application testing must be performed to ensure that an application is capable of proper function, even if presented with invalid or conflicting data, and as a simple measure of base functionality within the expected operational environment. TextBox control A control that allows single-line or multiline textual input, including the capability to mask passwords using a default character such as the asterisk (*). this window One of the program state windows used during debugging to show all of the members associated with the current object. 494 Throw method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Throw method Method used to explicitly raise an exception, allowing the use of custom errorhandling code. Timer control A control used to fire an event after a specific interval of time. tlbimp.exe The Type Library Importer (tlbimp.exe), a commandline utility used to import the metadata of a COM component for use within a .NET application. toolbar A component used to provide access to clickable tool buttons, typically docked along the top edge of an application. ToolTip A component that extends the properties of other controls on a form to allow the display of mouseover ToolTip text. top-down testing A testing approach that involves testing overall functionality using code stubs for modules not yet developed. After root-level functionality is verified, testing extends down to the unit level. topic files HTML Help files that are designed to assist the user in a particular situation. Each situation has its own topic file. trace One of the symbol sets used during diagnostics, included when an application is compiled in Debug or Release modes. TrackBar control A control used to select a value from a range by sliding the scrollbar across a displayed scale. Transact-SQL See T-SQL. transforming Translating machine-stored information within the data model to a more humanreadable form. TreeView control A control that allows navigation and selection within a hierarchical node structure. Try block Block that is used in conjunction with one or more Catch blocks for error handling within the defined region of code. T-SQL Microsoft’s implementation of the Structured Query Language (SQL standard), also referred to as Transact-SQL. two-way data binding Binding form in which changes to the data in the data model are reflected in the user interface, and changes to data within the user interface are reflected back to the data model. Type Library Importer tlbimp.exe. See UDDI (Universal Description, Discovery, and Integration) Provides a method for locating Web services through the use of a central searchable directory. umbrella testing A testing approach that focuses on testing user interface modules prior to the business logic modules. Unicode The default encoding used by .NET applications that uses a 2-byte (16-bit) character set to handle roughly 65,000 495 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Windows . . . . . API . . characters from the world’s most common languages. Universal Description, Discovery, and Integration (UDDI) See UDDI. UPDATE statement The TSQL statement used to update the values of one or more records of a table within a database. URL remoting A zero-touch deployment method that allows the installation of an application simply by navigating to the proper URL for the application’s executable (.exe) file within Internet Explorer. user assistance The process of providing help within an application. User Interface Editor A deployment editor used to specify dialog boxes that will be displayed during the start, progress, and end stages of an installation. UserControl control Composite controls derived from the UserControl class, which can include one or more standard user interface controls as well as defined business logic. validation The process of ensuring that input values are valid and that all required values are present before performing a procedure on the input data. view A filtered set of data derived from one or more tables within a database. visual inheritance The process of inheriting visual user interface members from a parent class. VscrollBar control A control that provides vertical scrolling capability. Watch window One of the program state windows used during debugging to monitor the value of a particular associated variable. WebMethod attribute The attribute used in an .asmx file to expose a method provided by a Web service. WebService attribute The attribute used in an .asmx file to describe and specify a namespace for a Web service. Web Services Allow objects to interact even when located on systems in widely distributed networks connected only by the Internet. Web Services Description Language (WSDL) See WSDL. Web Services Description Language tool (wsdl.exe) A command-line tool that can use a WSDL file to create a proxy class that can be used to access the web service. Web Services Discovery Tool A command-line tool used to discover and make available a Web service. Windows API Can be used to access inherent functionality provided by the Windows environment. 496 Windows Forms ActiveX Control Importer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Windows Forms ActiveX Control Importer See aximp.exe. WindowsIdentity object Object that represents the current user running the code and includes information such as the username and authentication method. WindowsPrincipal object Object that adds functionality to the WindowsIdentity object, representing the entire security context of the user running the code, including the roles to which that user belongs. wrapper A software container component that encapsulates legacy components to provide a translation interface between the .NET Framework and the component’s requirements for an interface. WriteEntry method Method that writes an entry to an event log. WSDL Provides details on the SOAP messages that a Web service can send and receive. XCOPY A Windows commandline utility that can be used to copy files from one location to another. XML A text-based humanreadable format that provides a uniform method for describing and exchanging structured data that is independent of applications or vendors. Also referred to as the Extensible Markup Language. Z-order A property that specifies the relative positioning of a control in a stack of overlapping controls. Each control has a unique z-order position. Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Symbols & (ampersand), 38, 244 ’ (apostrophe), 163 * (asterisk), 41, 143, 294 += code, 15 = code, 15 -= code, 15 /? command-line option (wsdl.exe), 179 && (double ampersand), 38 … (ellipsis) button, 36, 327 = (equals sign), 144 /? option (Type Library Importer Tool), 222 + (plus sign), 7, 158, 327 # (pound sign), 158 ‘’ (single quotes), 157 [ ] (square brackets), 144, 157 - (substract sign), 7 @ symbol, 148 % (wildcards), 144, 158 A AcceptChanges method, 156 AcceptsReturn property, TextBox class, 41 access modifiers, classes, 3 access. See data access accessibility, 242-244 AccessibleDescription property, 243 AccessibleName property, 243 AccessibleRole property, 243 accessing backing stores, 151 controls, 39 event logs, 314 relational databases, 156 resources, 330 streams, 151 accessors, properties, 12 actions, controls, 43 Activation property, ListView class, 51 ActiveLinkColor property, LinkLabel class, 41 ActiveMdiChild property, 61 ActiveX controls, 214-219 ActiveX Properties hyperlink, 218 ad-hoc queries, 146-148 adaptive exams, 461-462 fixed-length exams, compared, 463 short-form exams, compared, 463 strategies, 463-466 Add a Child Code Group link, 335 Add Existing Item command (File menu), 179 Add Inherited Control command (Add menu), 104 Add Inherited Form command (Add menu), 13 Add menu commands Add Inherited Control, 104 Add Inherited Form, 13 Add New Item, 95 Add Property, 100 Add method, parameters, 162 Add New Item command (Add menu), 95 Add New Item dialog box, 13, 95 Add Property command (Add menu), 100 Add Reference button, 176 498 Add Reference dialog box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Add Reference dialog box, 96, 215, 222 Add Web References dialog box, 176 Add/Remove Programs Wizard, 296 Added value (DataViewRowState), 158 AddNew method, 123, 159 administrative installation (deployment method), 299 ADO.NET Object Model data provider objects, 153-155 DataSet object, 156, 161-162 DataColumn object, 160 DataRelation object, 158 DataRow object, 160 DataTable object, 157-158 DataView object, 159 AfterCheck event, TreeView class, 51 AfterCollapse event, TreeView class, 51 AfterExpand event, TreeView class, 51 AfterSelect event, TreeView class, 51 agents, code-based, 270 aggregate functions, 144, 158 al.exe (Assembly Generation tool), 107, 110 Alignment property, 22 StatusBarPanel class, 59 TabControl class, 55 All Code code group, 335 AllowDbNull * property, 160 AllowDelete property, 159 AllowEdit property, 159 AllowMargins property, PageSetupDialog component, 258 AllowNew property, 159 AllowOrientation property, PageSetupDialog component, 258 AllowPaper property, PageSetupDialog component, 259 AllowPrinter property, PageSetupDialog component, 259 alphabetic characters, changing case, 81 Alt property, 82 AlternatingBackColor property, 128 American National Standards Institute (ANSI), 142 ampersand (&), 38, 244 ampersand, double (&&), 38 Anchor, control property, 35 AND keyword, 158 animation files, 235 ANSI (American National Standard Institute), 142 AntiAlias member (SmoothingMode property), 23 antialiasing, 22 APIs, SetProcessDefaultLayout Windows, 203 apostrophe (’), 163 app.config file, 327 AppDomain class, 79 Application class, 9 Application directory code group, 334 Application event log, 313 Application folder, 292 application settings, managing, 329 application testing, 270-272 ApplicationException, 72 applications CloseMainWindow method, 308-312 compiling, 272 data-bound, creating, 130 deploying, 288 .NET Framework, 291 Setup Projects, 289-293 international, testing, 272 Kill method, 308-312 MDI (multiple-document interface) applications, 60-61 .NET, 147 process information, 312 single-document interface applications, 60-61 Start method, 308-312 states, debugging, 279 troubleshooting, 288 Windows event logs, 313-314 Process class, 308 <appname>.exe.config file, 327-328 architecture, data binding, 122-124 arguments DrawString() method, 20 event handlers, 14, 102 IsInRole method, 338-339 PaintEventArgs, 18 ArithmeticException catch block, 74 Array.Sort method, 205 ASCIIEncoding subclass, 202 /asmversion:versionNumber option (Type Library Importer Tool), 221 .asmx extension, 180 assemblies Authenticode, 295 code groups, 333 delay, 294 immediate, 293-294 machine-wise configured, managing, 329 . . . . . . . . . . . . . . . . . . . . . . . . . . . . btnCloseAllCalculators . . . . . . . . . . . . Button . . . . control . . . . .NET, 105-110 shared, 293-296 Assembly Cache Viewer Shell Extension (shfusion.dll), 295 Assembly Generation tool (al.exe), 107, 110 Assembly Manifest, 105-107 assembly resource files, 201 AssemblyKeyFile attributes, 294 AssemblyVersion attribute, 294 Assert method, 272 AssociateIndex value, 240 asterisk (*), 41, 143, 294 asynchronous calls, queued components (COM+ components), 223 Attach button, 278 attributes AssemblyKeyFile, 294 AssemblyVersion, 294 browsable (custom properties), 12 category (custom properties), 12 Conditional, 275 custom properties, 12 description (custom properties), 12 editorbrowsable (custom properties), 12 PrincipalPermisssionAttribute, 339 WebMethod, 180 WebService, 180 audio. See sound authentication, 337 Authenticode Signature option, 292 Authenticode signing, shared assemblies, 295 authorization, role-based security, 337-339 Auto window, 279 AutoCheck property, 44 AutoFlush property, 272 AutoFormat, 127 AutoIncrement property, 160 automated alpha-phase testing, 270 AutomaticDelay property, 241 AutoPopDelay property, 241 AutoScroll property, Panel class, 39 AutoSize property, StatusBarPanel class, 59 AutoZoom property, PrintPreviewControl control, 261 Avg aggregate function, 158 Avg function, 144 AxHost class, Windows Forms ActiveX Control Importer (aximp.exe), 215 aximp.exe (Windows Forms ActiveX Control Importer), 215-217 az-AZ-Cyrl (culture code), 194 B BackColor property, 10, 128, 243 Background Color property, 128 BackgroundImage property, 10, 243 backing stores, 151-153 base classes, 3, 16-17 base functionality, 270 BeginEdit method, 160 BeginPrint event, 252 BeginTransaction method, 154 BinaryReader class, 151-153 BinaryWriter class, 151-153 binding controls, 120 Binding class, 120 Binding objects, 120 binding. See data binding BindingContext class, 122-124 object, 122 property, 127 BindingManagerBase class, 122-123 Bindings property, 123 blank forms, creating, 6 BlinkRate property, 84 BlinkStyle property, 84 blocks catch, 74-76 finally, 76-77 try, 73-74, 77 try-catch, code, 75 body, SOAP (Simple Object Access Protocols) messages, 175 Boolean values Enabled property, 35 Visible property, 38 BooleanSwitch object, 274 Bootstrapper option, 292 BorderStyle property, 59, 128 bottom-up integration testing, 271 Bounds property, PageSettings class, 255 boxes, Label, 37. See also check boxes; dialog boxes Breakpoint Condition dialog box, 277 Breakpoint Hit Count dialog box, 277 breakpoints, conditional, creating, 277 Breakpoints window, 277 browsable attribute (custom properties), 12 browsing disk files, 150-151 Brush class, 24 Brush objects, 23-24 Brush property, 22 btnCloseAllCalculators Button control, 310 How can we make this index more useful? Email us at [email protected] 499 500 btnCloseRecentCalculator Button control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . btnCloseRecentCalculator Button control, 310 btnGetInfo Button control, 194 btnLaunchCalculator Button control, 310 btnOpenForm Button control, 199 btnPageSetup button control, 258 btnPreview button control, 259 btnPrinter button control, 261 buffers, string, 223 Build Type of a Project’s Properties as Content option, 109 Build Type to Embedded Resource option, 109 build-list-and-reorder questions, exam format, 455-457 Button class, 44 Button control, 43-44, 199 Button controls btnCloseAllCalculators, 310 btnCloseRecentCalculator, 310 btnGetInfo, 194 btnLaunchCalculator, 310 btnPageSetup, 258 btnPreview, 259 btnPrinter, 261 Button property, 16, 59 ButtonBase control, 43 ButtonClick event, ToolBar class, 59 buttons Add References, 176 Attach, 278 Close, 6 Close All Calculators, 311 Close Most Recent, 311 Condition, 277 ellipsis (…), 36, 327 Help, displaying, 241 Hit Count, 277 Import, 335 Invoke, 182 Launch, 311 New Project, 6 Open, 104 Options, 238-239 Page Setup, 258 Preview, 259-260 Printer, 261 Search, 469 Show All files, 105 View Compiled File, 239 C C#, 2 C# Property Wizard, 100 Cab Projects, 289 .cab (cabinet) files, 289, 298 CalendarDimensions property, MonthCalendar class, 49 Call Stack window, 279 calls, asynchronous (COM+ components), 223 Cancel property, 83, 255 CancelCurrentEdit method, 123 CancelEdit method, 160 CancelEventArgs object, 83 CanDuplex property, PrinterSettings class, 256 CanRead property, 152 CanSeek property, 152 CanWrite property, 152 CaptionBackColor property, 128 CaptionFont property, 128 CaptionText property, 128 CaptionVisible property, 128 case, alphabetic characters, 81 case studies, 461-462 layout, 453-454 strategies, 463-464 catch blocks, 74-76 catching exceptions, CLS (Common Language Specification), 75 category attribute (custom properties), 12 CategoryName property, 315 CausesValdiation property, 83 cboCulture ComboBox control, 199 cboSelectCulture ComboBox control, 196 certification, logo, 299 certification exams adaptive exams, strategies, 465-466 build-list-and-reorder questions, 455-457 case studies, 453-454, 463-464 create-a-tree questions, 457-459 drag-and-connect questions, 458-460 fixed-length, strategies, 464-465 formats, 461-463 multiple-choice questions, 454-455 practice exams, taking, 467-468 question handling, strategies, 466-467 readiness, assessing, 451-452 resources, 468 select-and-place questions, 460 501 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . classes . . . . short-form, strategies, 464-465 testing centers, 452 Certified for Windows, 299 Changed event, 103 channels, remoting, 329 character encodings, 201 CharacterCasing property, 41, 81 CharacterRange structure (System.Drawing namespace), 19 characters, alphabetic, 81 check boxes ShowInTaskbar, 327 Text, 327 CheckBox class, 44 CheckBox control, 43-44, 80 CheckBoxes property, 51-52 CheckeChanged event, CheckBox class, 44 checked keywords, 76 Checked property, 44, 58 CheckedChanged event, RadioButton class, 44 CheckedIndices property, 46, 52 CheckedItems property, 46, 52 CheckedListBox class, 46 CheckedListBox control, 44-46 CheckState property, CheckBox class, 44 child table columns, 158 child windows, 60 ChildColumns property, 159 ChildKeyConstraint property, 159 ChildRelations property, 157 ChildTable property, 159 .chm files, 240 Choose a Project Type screen, 289 Choose Files to Include screen, 290 Choose Project Outputs to Include screen, 289 class AppDomain, 79 BindingContext, 122 PrintDocument, 252-256 Class Library template, 95 Class View command (View menu), 100 classes access modifiers, 3 Application class, 9 AxHost, Windows Forms ActiveX Control Importer (aximp.exe), 215 base classes, 3 BinaryReader, 151-153 BinaryWriter, 151-153 Binding, 120 BindingContext, 124 BindingManagerBase, 122-123 Brush object, 24 Brush, 24 Button, 44 C#, 2 CheckBox, 44 CheckedListbox, 46 ColorMixer, 100 ComboBox, 47 CommonDialog, 57 Component class, .NET components, 94-97 ContainerControl, 34, 94 ContextMenu, 57 Control class, .NET components, 94, 98-99 CultureInfo, 194-195 CurrencyManager, 122-123 custom properties, 11-12 DateTimePicker, 50 Debug, 272-273 DefaultTraceListener, 273 derived classes, 3 DomainUpDown, 48 Encoding, 201 ErrorProvider, 84 EventLog, 80, 313-314 EventLogTraceListener, 273 exceptions, 72-73 FileStream, 151 Form class, 10-11 Graphics, 18, 253 grouping, 4 HatchBrush, 24 Help, 240 inheritance, 3 Installer, methods, 296 KeyEventArgs, properties, 82 KeyPressEventArgs, properties, 81 Label, properties, 40 LinearGradientBrush, 24 LinkLabel, 41 Listbox, 45 ListControl, 44-46 ListView, 51-52 MainMenu, 57 MenuItem, 57-58 MonthCalendar, 49-50 namespaces, 4 .NET Framework, 2 NumericUpDown, 48 How can we make this index more useful? Email us at [email protected] 502 classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . OpenFileDialog, 150 overriding (event handling), 16-17 PageSettings, properties, 255 Pen object, 22 PerformanceCounter, 315-316 PictureBox, 43 PrincipalPermission, 339 PrinterSettings, properties, 256 PrintPageEventArgs, properties, 255 Process CloseMainWindow method, 308-312 events, 309-310 Kill method, 308-312 methods, 309-310 process information, 312 properties, 309-312 Start method, 308-312 ProgressBar, properties, 54 ProjectInstaller, 296 properties, 3 proxy, 176-178 publishers, 102 RadioButton, 44 ResourceManager, 110, 200 ResourceReader, 110 resources, 110 ResourceWriter, 110 ResXResourceWriter, 110 ResXResoureReader, 110 RichTextBox, properties, 42 ScrollBar, 55 SolidBrush, 24 SqlException, 165 static members, 3 StatusBarPanel, properties, 59 StreamReader, 151 StreamWriter, 151 StringInfo, 204 subclasses, 202 subscribers, 102 Switch, 274 System.Configuration.AppSettingsReader, 326 System.IO namespace, 151 System.Windows.Forms.UpDownBase class, inheritance, 47 SystemBrushes, 24 SystemPens, 22 TabControl, 55 TextBox, 41-42 TextBoxBase, 41 TextureBrush, 24 TextWriterTraceListener, 273 Timer, 53 ToolBar, 59-60 trace listeners, 273 Trace, 272-273 TraceLevel, enumeration, 274 TraceListener, 273 TraceSwitch, properties, 274 TrackBar, 54 TreeView, 51 UnhandledExceptionEventArgs, properties, 79 unit testing, 271 UserControl, 98-101 visual inheritance, 13 Visual Studio .NET, 2 XmlDataDocument, 164-165 XmlDocument, 163-164 clauses FROM, 143 GROUP BY, aggregate functions, 144 HAVING, 144 WHERE, 144, 157 Clear method, 156-157 Click event, 260 Button class, 44 MenuItem class, 58 PictureBox class, 43 Clicks property, 16 client-side filtering, 132 client-side user interfaces, 94 ClientSize property, 10 Close All Calculators button, 311 Close button, 6 Close method, 152-154, 272-273, 315 Close Most Recent button, 311 Close() method, 11 CloseMainWindow method, 308-312 CLR (Common Language Runtime), 2, 105, 196, 219, 336 CLS (Common Language Specification), exception catching, 75 code. See also legacy code +=, 15 -=, 15 =, 15 breakpoints, 277 developing, .NET Framework, 2 ErrorProvider component, 84-85 finally blocks, 76 forms, adding controls, 63-64 managed, 219 step-by-step execution (debugging), 276 try blocks, 73-74 503 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . components . . . . . . . try-catch blocks, 75 unmanaged. See legacy code code access permissions, 330 code access security, 329 code groups, 333-334 final permissions, 336 granting permissions, 334-336 minimum permissions, 332-333 permission sets, 334 permissions, 330-332 code block, 7 code groups, 333-335 Code Groups node, 335 code modules, 336 Code view, 6-8, 98, 221 code-based agents, automated alpha-phase testing, 270 collapsing code blocks, 7 Collate property, PrinterSettings class, 256 color, accessibility, 242 Color property, 22, 255 Color structure (System.Drawing namespace), 19 ColorDialog dialog box, 56 ColorMixer class, 100 ColorMixer control, 102-103 ColorMixerEventArgs control, 103 ColorMixerWithEvents1 control, 103 ColumnChanged event, 157 ColumnChanging event, 157 ColumnHeadersVisible property, 128 ColumnName property, 160 columns, tables, 158 Columns property, 157, 261 ColumnWidth property, ListBox class, 45 COM (Component Object Model), 174 components, 219-222 tab, 215, 222 COM Components tab, 217 COM+ components, 222 ComboBox class, 47 ComboBox control, 46-47, 80, 124 cboCulture, 199 cboSelectCulture, 196 Command object, 154-155 command prompts, Visual Studio .NET, 178 command-line options, wsdl.exe, 179 command-line utilities, OSQL, 146 commands Add menu Add Inherited Control, 104 Add Inherited Form, 13 Add New Item, 95 Add Property, 100 Debug menu Start, 6 Step Into, 276 Step Out, 276 Step Over, 276 Windows, 279 Windows, Breakpoints, 277 Edit menu Insert Keyword, 238 Insert Topic, 238 File menu Add Existing Item, 179 Compile, 239 New, HTML File, 236 New, Index, 238 New, Project, 6, 236 New, Table of Contents, 237 MSIEXEC, 299 Tools menu, Debug Processes, 278 View menu, Class View, 100 CommandText property, 154 CommandType property, 154 Commit method, 296 Common Files folder, 292 Common Language Runtime (CLR), 2, 105, 196, 219, 336 Common Language Specification (CLS), exception catching, 75 CommonDialog class, 57 CompanyName static property, 9 comparing data, 205 compilation, conditional, 275 Compile command (File menu), 239 compiling applications, 272 forms, 8 HTML Help files, 239 complex data binding, user interfaces controls, 124-127 DataGrid control, 127-128 Component class, .NET components, 94-97 Component Object Model. See COM components COM, 219-222 COM+, 222 ErrorProvider, 83-85 HelpProvider, 240-241 installation, 296-297 .NET Component class, creating, 94-97 Control class, creating, 94, 98-99 How can we make this index more useful? Email us at [email protected] 504 components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . creating, 94-95 UserControl class, creating, 94, 99-105 PageSetupDialog, 258-259 PrintDialog, 261 PrintPreviewDialog, 259-260 queued, asynchronous calls (COM+ components), 223 RandomNumberGenerator, 97 Timer, 95 toolbox, adding, 97 ToolTip, 241 troubleshooting, 288 user assistance, 239 Windows Forms dialog components. See dialog boxes Compression option, 292 Condition buttons, 277 Condition property, 293 Conditional attribute, 275 conditional breakpoints, creating, 277 conditional compilation, 275 Configuration tool, 298 configurations dynamic runtime configurations, 326-329 role-based security, authorization, 337 PrincipalPermission class, 339 security code access security, 329-336 role-based security, 330 WindowsIdentity object, 337-339 WindowsPrincipal object, 337-339 UpdateCommand property, 165-166 Connection object, 154 Connection property, 155 connections, data (Server Explorer), 130 ConnectionString property, 154 consistency, accessibility, 242 constraints, 148 Constraints property, 157 ContainerControl class, 34, 94 ContainerControl property, 84 Contains method, 124 contents files, 235 ContextMenu class, 57 Control class, .NET components, 94, 98-99 control properties, accessibility, 243-244 Control property, 82 control-access restriction, user input, 81 control-based validation, user input, 80 ControlBox property, 10 ControlObject.Property, 34 controls. See also TextBox controls accessing, 39 actions, initiating, 43 ActiveX, 214-219 binding, 120 ButtonBase, 43 CheckBox, 43-44, 80 CheckedListBox, 44-46 ColorMixer, 102-103 ColorMixerEventArgs, 103 ColorMixerWithEvents1, 103 ComboBox, 46-47, 80, 124 cboCulture, 199 cboSelectCulture, 196 complex data binding, 124-127 custom, event responses, adding, 101-103 DataGrid, 127 data, filtering, 131-132 properties, 128 DateTimePicker, 49-50 dialog boxes ColorDialog, 56 displaying, 57 FontDialog, 56 modal, 57 modeless, 57 OpenFileDialog, 56 PageSetupDialog, 56 PrintDialog, 56 PrintPreviewDialog, 56 SaveFileDialog, 56 displaying, 244 DomainUpDown, 47-48 forms, adding, 61 Windows Forms Designer, 61-64 GroupBox, 38-40, 103 grouping, 38-39 HScrollBar, 54-55 Label, 40-41, 310 LinkLabel, 40-41 ListBox, 44-46, 80, 124, 194 ListView, 50-52 MDI (multiple-document interface) applications, 60-61 menus, 57-60 MonthCalendar, 49-50 multiple data sources, complex data binding, 125-127 NumericUpDown, 47-48 ordering, Z-order, 34 Panel, 38-40 Picturebox, 43, 54 505 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CustomFormat . . . . . . . . property . . . . . printing, 257 PageSetupDialog component, 258-259 PrintDialog component, 261 PrintPreviewControl control, 260-261 PrintPreviewDialog component, 259-260 PrintPreviewControl, properties, 261 ProgressBar, 53-54 properties Anchor, 35 Dock, 35 Enabled, 35 Font, 36 Height, 37 Location, 37 modifying, 34 Name, 37 Size, 37 TabIndex, 37 TabStop, 37 Text, 37 Visible, 38 Width, 37 RadioButton, 43-44, 80 RichTextBox, 41-42 satellite assemblies, 200 scrollbars, 39 single-document interface applications, 60-61 states, 43 SysInfo, 217 TabControl, 55 TextBox, 41-42, 194-196 Timer, 53-54 ToolTip, 56 TrackBar, 53-54 TreeView, 50-52 UserControl class, creating, 100-101 visual inheritance, extending, 103-105 VScrollBar, 54-55 Controls property, 39 CONVERT function, 158 converting character encodings, 201 Copies property, PrinterSettings class, 256 correctness, application testing, 271 Count aggregate function, 158 Count function, 144 Count property, 123, 159 CounterHelp property, 315 CounterName property, 315 counters, performance, 315-316 CounterType property, 315 Create a Compiled File dialog box, 239 Create a Setup for a Windows Application option, 289 Create Code Group dialog box, 335 Create method, 316 Create New Category option, 317 Create Permission Set dialog box, 335 CREATE PROC statement, 148 create-a-tree questions, exam format, 457-459 CreateAttribute method, 164 CreateCommand method, 154 CreateElement method, 164 CreateEventSource method, 313-314 CreateGraphics() method, 18 CreateNode method, 164 CreateParameter method, 155 cross-product result-set, queries, 143 Cryptographic ash code group, 334 Crystal Services, 130 cues, visual, 244 culture codes, 194 culture-aware sorting, 205 CultureInfo class, 194-195 CultureInfo objects, 195 CultureInfo.CompareInfo object, 205 cultures CultureInfo class, 194-195 CurrentCulture property, 196 Invariant, 196 localized information, displaying, 196-197 localized settings, storing, 200 CurrencyManager class, 122-123 CurrencyManager object, 122 Current property, 123 CurrentChanged event, 123 CurrentCulture property, 196 CurrentCulture static property, 9 CurrentInputLanguage static property, 9 CurrentRows value (DataViewRowState), 158 CurrentUICulture property, 196 Custom Actions Editor, 293, 296 custom authentication, 337 custom controls, event responses, 101-103 custom exceptions, creating, 78 custom properties, 11-12 custom symbol, 275 custom trace listeners, 273 CustomFormat property, DateTimePicker class, 50 How can we make this index more useful? Email us at [email protected] 506 Customize Toolbox dialog box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Customize Toolbox dialog box, 217 Customize Toolbox option, 97 customizing Setup Projects, 292-293 D DashCap property, 22 DashPattern property, 22 DashStyle property, 22 data comparing/sorting, 205 filtering, 129-132 metadata, COM components, 220 performance, 315-316 transforming, 129-132 XML, 162-165 data access ADO.NET Object Model data provider objects, 153-155 DataSet object, 156-162 disk files, 150-153 file-based data storage, 150 relational database storage, 150 XML data, 162-165 XML data files, 150 data binding architecture, 122-124 complex, user interfaces, 124 controls, 124-127 Data Form Wizard, 129 DataGrid control, 127-128 entities, 121-122 one-way, user interfaces, 129 properties, 121-122 simple, user interfaces, 120 two-way, user interfaces, 129 user interfaces, 120 data connections, Server Explorer, 130 Data Connections node, 130-131, 147-149 data files, XML, 150 Data Form Wizard, 129 data models, data sources, 129 data provider objects, 153-154 data providers, 153 data sources, 125-129 data-bound applications, creating, 130 DataAdapter object, 155 databases errors, 165-166 Northwind, 131 relational, 129, 156 values, modifying, 145 DataBinding property, 120 DataColumn object, 160 DataGrid control, 127 data, filtering, 131-132 properties, 128 DataReader object, 155 DataReader.Close method, 155 DataRelation object, 131, 158 DataRow object, 159-160 DataSet creating, 131-132 synchronization, 164 DataSet object, 161-162 DataColumn object, 160 DataRelation object, 158 DataRow object, 160 DataTable object, 157-158 DataView object, 159 methods, 156 properties, 156 DataTable object, 131, 157-159 DataType property, 160 DataView, client-side filtering, 132 DataView object, 131, 159 DataViewRowState enumerated values, 158 date values, 49 DateChanged event, MonthCalendar class, 49 DateSelected event, MonthCalendar class, 49 DateTimePicker class, 50 DateTimePicker control, 49-50 DCOM (Distributed Component Object Model), 174 de (culture code), 194 Debug class, 272-273 Debug menu commands Start, 6 Step Into, 276 Step Out, 276 Step Over, 276 Windows, 279 Windows, Breakpoints, 277 Debug mode, 275-276 Debug Processes command (Tools menu), 278 DEBUG symbol, 275 Debugger Users group, 278 debugging application states, 279 breakpoints, 277 code, step-by step execution, 276 errors, JIT (Just In Time), 329 remote, 279 507 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . DOM . . . (Document . . . . . . .Object . . . Model) . . . . running processes, 278-279 statements, 272 thrown exceptions, 278 declarations, XML, 163 declarative security, 336 Decrement method, 315 Default member (SmoothingMode property), 23 DefaultPageSettings property, PrinterSettings class, 256 DefaultTraceListener class, 273 DefaultValue property, 160 #define directive, 275 /delaysign option (Type Library Importer Tool), 221 delay signing, shared assemblies, 294 delegates, attaching, 14-16 Delete method, 159-160, 313 DELETE statement, 146 DeleteCommand property, 155 Deleted value (DataViewRowState), 158 DeleteEventSource method, 313 Delta property, 16 Demand value, 333 deploying applications, 288 .NET Framework, 291 Setup Projects, 289-292 customizing, 289-293 installation components, 296-297 .NET assemblies, 107-108 deployment ActiveX controls, 219 methods, 298-299 URL remoting, 297-298 deployment tools Microsoft Windows Installer, 288, 291 XCOPY utility, 288 derived classes, 3 description attribute (custom properties), 12 description files, WSDL, 178 Description property, 274 Design view, 6, 98 Designed for Microsoft Windows XP, 299 DesktopLocation property, 10 DetectUrls property, RichTextBox class, 42 dialog boxes Add New Item, 13, 95 Add Reference, 96, 215, 222 Add Web References, 176 Breakpoint Condition, 277 Breakpoint Hit Counter, 277 ColorDialog, 56 Create a Compiled File, 239 Create Code Group, 335 Create Permission Set, 335 Customize Toolbox, 217 displaying, 57 Dynamic Properties, 327 Exceptions, 278 File Open, 151, 165 FontDialog, 56 Inheritance Picker, 13, 104 Keyword, 238 modal, 57 modeless, 57 New Breakpoint, 277 Open With, 105 OpenFileDialog, 56 Page Setup, 258 PageSetupDialog, 56 PrintDialog, 56 PrintPreviewDialog, 56 Processes, 278 Property Pages, 291-292 SaveFileDialog, 56 diChildActivate property, 61 digital signatures, 292-294 directives, 275 DirectoryServicesPermission, 331 DisabledLinkColor property, LinkLabel class, 41 Disco, 175 disco.exe utility, 178 discovery, Web Services, 176 disk files, 150-153 disks, accessibility, 242 displaying controls, 244 dialog boxes, 57 forms, 6 Help, 240 Help buttons, 241 localized information, cultures, 196-197 DisplayName property, 274 Distributed Component Object Model (DCOM), 174 DivideByZeroException, 74 .dll files, 293, 326 DnsPermission, 331 Dock, control property, 35 Document Object Model (DOM), 164 DocumentElement property, 164 DoEvents static method, 9 DOM (Document Object Model), 164 How can we make this index more useful? Email us at [email protected] 508 /domain:DomainName command-line option (wsdl.exe) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /domain:DomainName command-line option (wsdl.exe), 179 DomainUpDown class, 48 DomainUpDown control, 47-48 double ampersand (&&), 38 drag-and-connect questions, exam format, 458-460 Draw methods, 21-23 DrawArc method, 21 DrawBezier method, 21 DrawBeziers method, 21 DrawCloseCurve method, 21 DrawCurve method, 21 DrawEllipse method, 21 DrawIcon method, 21 DrawImage method, 21 drawing shapes, forms, 21-23 text, forms, 19-21 DrawItem event, MenuItem class, 58 DrawLine method, 21 DrawLines method, 21 DrawMode property, ComboBox class, 47 DrawPath method, 21 DrawPie method, 21 DrawPolygon method, 21 DrawRectangle method, 21 DrawRectangles method, 21 DrawString method, 21, 253 DrawString() method, 19-20 DropDownStyle property, ComboBox class, 47 DropDownWidth property, ComboBox class, 47 Duplex property, PrinterSettings class, 256 dynamic .NET assemblies, 107 dynamic properties, configuring, 326-328 Dynamic Properties dialog box, 327 dynamic runtime configuration dynamic properties, 326-328 .NET Framework Configuration tool, 328-329 E Edit menu commands Insert Keyword, 238 Insert Topic, 238 editorbrowsable attribute (custom properties), 12 editors Custom Actions Editor, 293, 296 File System Editor, 292 File Types, 292 Launch Conditions Editor, 293 Registry Editor, 292 User Interface Editor, 293 viewing, 293 Visual Studio .NET IDE, 292-293 elements, 129 #elif directive, 275 ellipsis (…) button, 36, 327 #else directive, 275 en-GB (culture code), 194 Enabled property, 10, 35 MenuItem class, 58 Timer class, 53 EnableRaisingEvents property, 309, 313 encoding, character, 201 Encoding class, 201 Encoding subclasses, 202 encryption, public key, 294 EndCap property, 22 EndCurrentEdit method, 123 EndEdit method, 160 #endif directive, 275 #endregion, code block, 7 #endregion directive, 275 entities, simple data binding, 121-122 Entries property, 313-314 EntryWritten event, 313-314 enumerated values DataViewRowState, 158 EventLogEntryType, 314 enumeration, TraceLevel class, 274 envelopes, SOAP (Simple Object Access Protocols), 175 EnvironmentPermission, 331 equal sign (=), 144 ErrorProvider class, 84 ErrorProvider component, 83-85 errors ActiveX controls, 219 databases, 165-166 debugging, JIT (Just In Time), 329 forms, 9 Errors property, 165 event handling, 13, 102 arguments, 14 base classes, overriding protected methods, 16-17 delegates, attaching, 14-16 Paint, 20 Event Logs, 130 accessing, 314 Application, 313 509 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .exams . . . EntryWritten, 314 Security, 313 System, 313 Windows, 79 event responses, custom controls, 101-103 event sources, 314 event wiring, 14 EventLog class, 80, 313-314 EventLog object, 314 EventLogEntryCollection object, 314 EventLogEntryType enumerated values, 314 EventLogPermission, 331 EventLogTraceListener class, 273 events AfterCheck, Treeview class, 51 AfterCollapse, Treeview class, 51 AfterExpand, Treeview class, 51 AfterSelect, Treeview class, 51 BeginPrint, 252 BindingManagerBase class, 123 Button class, 44 ButtonClick, ToolBar class, 59 Changed, 103 CheckBox class, 44 CheckedChanged, 44 CheckedListBox class, 46 Click, 260 Button class, 44 MenuItem class, 58 PictureBox class, 43 ColumnChanged, 157 ColumnChanging, 157 ComboBox class, 47 CurrentChanged, 123 DataTable objects, 157 DateChanged, MonthCalender class, 49 DateSelected, MonthCalender class, 49 DateTimePicker class, 50 DomainUpDown class, 48 DrawItem, MenuItem class, 58 EntryWritten, 313 EventLog class, 313-314 Exited, 309 FormatChanged, DateTimePicker class, 50 ItemActivate, ListView class, 52 ItemChanged, 123 ItemCheck CheckedListBox class, 46 ListView class, 52 KeyDown, 82 KeyPress, 81-82 KeyUp, 81-82 LinkClicked, LinkLabel class, 41 LinkLabel class, 41 ListBox class, 45 ListView class, 51-52 Load, 223 logging, 79 MenuItem class, 58 MonthCalendar class, 49-50 MouseDown, 14 NumericUpDown class, 48 Paint, 98 PictureBox class, 43 Popup, MenuItem class, 58 PositionChanged, 123 PrintPage, 252 Process class, 309-310 QueryPageSettings, 252 RadioButton class, 44 Resize, 98 RowChanged, 157 RowChanging, 157 RowDeleted, 157 RowDeleting, 157 Scroll, ScrollBar class, 55 Scrollbar, TrackBar class, 54 ScrollBar class, 55 Select, MenuItem class, 58 SelectedIndexChanged, 45-47, 52, 55 SelectedItemChanged, 48 TabControl class, 55 TextBox class, 41-42 TextChanged, TextBox class, 42 Tick, Timer class, 53 Timer class, 53 ToolBar class, 59-60 TrackBar class, 54 TreeView class, 51 UnhandledException, 79 Validating, 83 ValueChanged, 48-50, 55 Events icon, 15 events logs, managing, 313 events models, publisher/subscriber (COM+ components), 223 Everything permission set, 334 ExamName property, 127 exams adaptive exams, strategies, 465-466 build-list-and-reorder questions, 455-457 How can we make this index more useful? Email us at [email protected] 510 exams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . case studies, 453-454, 463-464 create-a-tree questions, 457-459 drag-and-connect questions, 458-460 fixed-length exams, strategies, 464-465 formats, 461-463 multiple-choice questions, 454-455 practice exams, taking, 467-468 question handling, strategies, 466-467 readiness, assessing, 451-452 resources, 468 select-and-place questions, 460 short-form exams, strategies, 464-465 testing centers, 452 Exception catch block, 74 exception class, 72-73 ExceptionObject property, 79 exceptions, 72 ArithmeticException catch block, 74 catching, CLS (Common Language Specification), 75 DivideByZeroException, 74 handling, 73-78 SystemException catch block, 74 throwing, 77 thrown, 278 user input, validating, 80-85 Exceptions dialog box, 278 .exe files, 293, 326 ExectueNonQuery method, 155 executable files, 326 Executable Path static property, 9 ExecuteNonQuery method, 149 ExecuteReader method, 155 ExecuteScalar method, 155 ExecuteXmlReader method, 155 Execution permission set, 334 exhibits, 453 Existing Files page, 236 Exists method, 313 Exit static method, 9 ExitCode property, 309 Exited event, 309 ExitThread static method, 9 ExitTime property, 309 expanding code blocks, 7 expressions creating, 158 unhandled, 79-80 Extensible Markup Language. See XML extensions, .asmx, 180 F F5 key, 6 Fail method, 273 FCL (Framework Class Library), 2, 9, 72 field-level validation, user input, 82-85 fields, 129, 143 File menu commands Add Existing Item, 179 Compile, 239 New, HTML File, 236 New, Index, 238 New, Project, 6, 236 New, Table of Contents, 237 File Open dialog box, 151, 165 File Signing tool (signcode.exe), 295 File System Editor, 292 File Transfer Protocol (FTP), 175 File Types Editor, 292 file-based data storage, 150 FileDialogPermission, 331 FileDialogPermissionAttribute request, 333 FileIOPermission, 331 files animation, 235 app.config, 327 <appname>.exe.config, 327-328 .cab (cabinet), 289, 298 .chm, 240 contents, 235 data, XML, 150 description, WSDL, 178 disk files, 150-153 .dll, 293, 326 .exe, 293 executable, 326 flat. See disk files graphics, 235 grouping. See assemblies .hhc, 238 .hhp, 238 .htm, 238 HTML Help, 239 index, 235 multimedia, 235 project, Help, 235-236 resource, 194 assembly, 201 .NET assemblies, 109-110 runtime resources, 200-201 Visual Studio .NET IDE, 198, 200 511 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . GAC . . .(Global . . . .Assembly . . . . . Cache) . . . . rich-text, 293 .rtf, 293 Setup.exe, 291 sound, 235 topic, 235-237 Files tab, 239 FileStream class, 151 FileStream object, 152 Fill methods, 23-24, 155 FillClosedCurve method, 23 filled shapes, forms, 23-24 FillEllipse method, 23 FillPath method, 23 FillPie method, 23 FillPolygon method, 23 FillRectangle method, 23 FillRectangles method, 23 FillRegion method, 23 filtering client-side, 132 cross-product result-set, queries, 143 data, 129-132 DataView object, 159 final permissions, 336 finally block, 76-77 Find method, 159 Find value, 240 FindRows method, 159 FindString method, ListBox class, 45 FindStringExact method, ListBox class, 45 FirstDayOfWeek property, MonthCalendar class, 49 fixed-length exams, 461-465 flags, SecurityAction.RequestMinimum, 333 flat files. See disk files FlatMode property, 128 flexibility, accessibility, 242 Flush method, 152, 273 Focus method, 83 folders Application, 292 Common Files, 292 Program Files, 292 References, 176 Release, 291 Runtime Security Policy, 298 Startup, 292 System, 292 Font, control property, 36 Font dialog box, 36 Font objects, 36 Font property, 40, 128 Font-Size property, 243 FontDialog dialog box, 56 ForeColor property, 128, 243 foreign key values, 129 Form class, 10-11 Format property, DateTimePicker class, 50 FormatChanged event, DateTimePicker class, 50 formats adaptive exams, strategies, 465-466 case studies, strategies, 463-464 exams, 461-463 fixed-length exams, strategies, 464-465 short-form exams, strategies, 464-465 FormBorderStyle property, 10 forms blank, creating, 6 closing, 83 compiling, 8 controls, adding, 61-64 customizations, storing, 8 displaying, 6 errors, 9 filled shapes, 23-24 methods, 10 multitable, creating, 129 properties, modifying, 6 shapes, drawing, 21-23 single-table, creating, 129 size, measuring, 19 text, drawing, 19-21 forms-based authentication, 337 Framework Class Library (FCL), 2, 9, 72 French translations, 199 FROM clause, 143 FromPage property, PrinterSettings class, 256 FTP (File Transfer Protocol), 175 FullTrust permission, 297, 334 functions aggregate, 144, 158 Avg, 144 Group, 144 Max, 144 Min, 144 Sum, 144 G GAC (Global Assembly Cache), 107, 222, 288, 293, 329 shared assemblies, adding, 295-296 viewing, 108-109 How can we make this index more useful? Email us at [email protected] 512 GacUtil.exe (Global Assembly Cache tool) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . GacUtil.exe (Global Assembly Cache tool), 296 GDI+ (Graphics Device Interface), namespaces, 17 General User Interface, 242 get accessors, 12 GetChanges method, 156 GetComputerName method, 223 GetCurrent method, 338 GetElementsByTagName method, 164 GetError method, 84 GetEventLogs method, 313 GetItemProperties method, 123 GetObject method, 200 GetProcessById method, 309 GetProcesses method, 309 GetProcessesByName method, 309 GetRandomNumber() method, 96 GetString method, 200 GetTextElementEnumerator() method, 204 GetXml method, 156 GetXmlSchema method, 156 Global Assembly Cache (GAC), 107, 222, 288, 293, 329 shared assemblies, adding, 295-296 viewing, 108-109 Global Assembly Cache tool (GacUtil.exe), 296 globalization, 110 character encodings, 201 localization, 192-194, 198 localization process, 192-193 user input, managing, 203-205 user interface mirroring, 202-203 granting permissions, code access security, 334-336 Graphics class DrawString method, 253 Graphics object, 18 Graphics Device Interface (GDI+), namespaces, 17 graphics files, 235 Graphics object retrieving, 18 System.Drawing namespace, 17-18 forms, drawing shapes, 21-23 forms, drawing text, 19-21 forms, filled shapes, 23-24 Graphics property, PrintPageEventArgs class, 255 Graphics.FromHwnd() method, 18 Graphics.FromImage() method, 18 GridlineColor property, 128 GridlineStyle property, 128 GROUP BY clause, aggregate functions, 144 GroupBox class, properties, 39 GroupBox control, 38-40, 103 grouping classes, 4 controls, 38-39 files. See assemblies groups code groups, 333-335 Debugger Users, 278 H Handle property, 10 Handled properties, 81-82 handling exceptions, 73-78 HasExited property, 309 HasMorePages property, PrintPageEventArgs class, 255 HatchBrush class, 24 HAVING clause, 144 HeaderBackColor property, 128 HeaderFont property, 128 HeaderForeColor property, 128 Height, control property, 37 Help displaying, 240 pop-up help, 241 Robohelp, 235 Help buttons, displaying, 241 Help class, 240 /help option (Type Library Importer Tool), 221 Help project files, 235-236 Help topic files, 236-237 HelpButton property, 10, 241 HelpLink property, 73 HelpNamespace property, 240 HelpNavigator property, values, 240 HelpProvider component, 240-241 HelpString property, 241 .hhc file, 238 .hhp file, 238 Hide() method, 11 hierarchies, nodes, 50 High Contrast mode, 244 HighQuality member (SmoothingMode property), 23 HighSpeed member (SmoothingMode property), 23 Hit Count buttons, 277 513 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .interfaces . . . . . HScrollBar control, 54-55 .htm file, 238 HTML Help, 234 files, 239 HTML Help project files, 236 HTML Help topic files, 236-237 indexes, creating, 238 SDK (Software Development Kit), 235 solution, 235 table of contents, creating, 237 HTML Help ActiveX Control, 235 HTML Help Authoring Guide, 235 HTML Help Compiler, 235 HTML Help file (.hhp) project, 238 HTML Help Image Editor, 235 HTML Help Java Applet, 235 HTML Help Viewer, 235 HTML Help Workshop, 235-236 HTTP (Hypertext Transfer Protocol), 175 human-interaction testing, 270 hyperlinks ActiveX Properties, 218 Help topic files, 237 Hypertext Transfer Protocol (HTTP), 175 I IBindingList interface, 121 Icon property, 10, 59, 84 icons Events, 15 Show All Files, 176 Id property, 309 IDE (integrated development environment), 2, 275 IDENTITY constraint, 148 identity permissions, 330 #if directive, 275 IIF function, 158 IList interface, 121 Image property, 40, 43-44 ImageList property TabControl class, 55 ToolBar class, 60 TreeView class, 51 immediate signing, shared assemblies, 294 Immediate window, 279 imperative security, 336 implementing printing (PrintDocument class), 252 Import button, 335 importing metadata, COM components, 220 IN keyword, 158 Increment method, 315 Increment property, NumericUpDown class, 48 IncrementBy method, 316 Indent method, 273 IndentLevel property, 273 IndentSize property, 273 index files, 235 Index value, 240 indexes, 238-239 indexing string, 203-204 information, processes, 312 inheritance .NET Framework, 3 System.Windows.Forms.UpDownBase class, 47 visual, 13, 103-105 Visual Studio .NET, 3 Inheritance Picker dialog box, 13, 104 InitialDisplay property, 241 InitializeComponent method, 104 InitializeComponent() method, 8 InnerException property, 73 input keyboards, accessibility, 243 methods, 242 mouse, accessibility, 243 user, managing, 203-205 Insert Keyword command (Edit menu), 238 INSERT statement, 145 Insert Topic command (Edit menu), 238 InsertCommand property, 156 Install method, 296 installations administrative installation (deployment method), 299 components, 296-297 rolling back, 288 InstalledPrinters property, PrinterSettings class, 256 Installer class, methods, 296 Installer tool (InstallUtil.exe), 297 InstallUtil.exe (Installer tool), 297 InstanceName property, 316 integrated development environment (IDE), 2, 275 integration testing, 271-272 IntelliSense, 8 interfaces. See also UI (user interface) General User Interface, 242 IBindingList, 121 IList, 121 How can we make this index more useful? Email us at [email protected] 514 interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ITypedList, 121 preview, 259 users, 94 complex data binding, 124-128 data binding, 120, 129 one-way data binding, 129 simple data binding, 120-124 two-way data binding, 129 internal access modifier, 4 international applications, testing, 272 Internet permission, 297, 334 Internet_Zone, 297 Interval property, Timer class, 53 Invalid member (SmoothingMode property), 23 Invalidate() method, 20 Invariant culture, 196 Invoke button, 182 invoking Web Services, 178 IsDefaultPrinter property, PrinterSettings class, 256 IsInRole method, arguments, 338-339 IsInRole(Integer) argument, 339 IsInRole(String) argument, 338 IsInRole(WindowsBuiltInRole) argument, 338 IsMdiContainer property, 61 ISNULL function, 158 IsNull method, 160 IsolatedStorageFilePermission, 331 IsolatedStoragePermission, 331 IsPlotter property, PrinterSettings class, 256 IsTerminating property, 79 IsValid property, PrinterSettings class, 256 Item property, 159 ItemActivate event, ListView class, 52 ItemChanged event, 123 ItemCheck event CheckedListBox class, 46 ListView class, 52 ItemHeight property, ListBox class, 45 Items property, 124 ComboBox class, 47 DomainUpDown class, 48 ListBox class, 45 ListView class, 52 ITypedList interface, 121 J-K JIT (Just In Time) debugging error, 329 JIT-Compiled (Just-In-Time) .NET assemblies, 108 keyboard focus, accessibility, 242 keyboard input, accessibility, 243 keyboard shortcuts, Text property, 38 keyboards, On-Screen Keyboard, 242 KeyChar properties, 81 KeyCode property, 82 /keycontainer:containerName option (Type Library Importer Tool), 221 KeyData property, 82 KeyDown event, 82 KeyEventArgs class, properties, 82 /keyfile:filename option (Type Library Importer Tool), 221 KeyPress event, 81-82 KeyPressEventArgs class, properties, 81 keys F5, 6 private, shared assemblies, 294 public, shared assemblies, 294 Tab, 37 keystroke-level validation, user input, 81-82 KeyUp event, 81-82 KeyValue property, 82 Keyword dialog box, 238 KeywordIndex value, 240 keywords checked/unchecked, 76 expressions, creating, 158 LIKE, 144 searching, 239 Kill method, 308-312 L Label box, 37 Label class, properties, 40 Label control, 40-41, 310 Landscape property, PageSettings class, 255 LandscapeAngle property, PrinterSettings class, 256 /language:LanguageCode command-line option (wsdl.exe), 179 languages. See also T-SQL (Transact-SQL) C#, 2 WSDL (Web Services Description Language), 175 LargeChange property, 54-55 LargeImageList property, ListView class, 52 Last one wins concurrency control, 165 Launch button, 311 Launch Conditions Editor, 293 layout, accessibility, 243 515 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MaximumPage . . . . . . . . property . . . . . LayoutMdi property, 61 lbInfo ListBox control, 194 lblLiveCalculators Label control, 310 legacy code ActiveX controls, 214-219 COM components, 219-222 COM+ components, 222 PInvoke (Platform Invoke), 223-224 LEN function, 158 Length property, 152 Level property, 274 LevelFinal property, 336 levels, final permissions, 336 libraries, MyCustomer, 222 LicenseProvider object, 326 LIKE keyword, 144, 158 #line directive, 275 LinearGradientBrush class, 24 LineJoin property, 22 LinkArea property, LinkLabel class, 41 LinkBehavior property, LinkLabel class, 41 LinkClicked event, LinkLabel class, 41 LinkColor property, 41, 128 linking Help topic files, 237 LinkLabel class, 41 LinkLabel control, 40-41 links Add a Child Code Group, 335 method, 181 Links property, LinkLabel class, 41 List property, 123 ListBox class, 45 ListBox control, 44-46, 80, 124, 194 ListControl class, 44-46 listener objects, 273 listeners, trace, 273 Listeners property, 273 ListView class, 51-52 ListView control, 50-52 Load event, 223 Load method, 164 LoadXml method, 164 local systems event logs, 314 processes, starting/stopping, 309 LocalIntranet permission, 297, 334 LocalIntranet_Zone, 297 localizability, 193 localization localizability, 193 process, 192-193 thread-by-thread, 196 UI (user interface), 193 cultures, 194-197 resource files, 194, 198-201 localized information, cultures, 196-197 localized settings, cultures, 200 Locals window, 279 Location, control property, 37 Log property, 313 LogDisplayName property, 313 logging events, 79 logic, storing, 83 LogNameFromSourceName method, 313 logo certification, 299 logs, Event Logs, 130 accessing, 314 Application, 313 EntryWritten, 314 managing, 313 Security, 313 System, 313 Window, 79 M machine-wide configured assemblies, managing, 329 MachineName property, 312-313, 316 Magnifier, 242 Main method, 204, 257 MainMenu class, 57 MainModule property, 312 MainWindowTitle property, 312 managed code, 219 managing, user input, 203-205 manifest, assemblies, 294 MarginBounds property, PrintPageEventArgs class, 255 Margins property, PageSettings class, 255 Max aggregate function, 158 Max function, 144 MaxDate property, 49-50 MaxDropDownItems property, ComboBox class, 47 MaximizeBox property, 10, 241 Maximum property NumericUpDown class, 48 ProgressBar class, 54 ScrollBar class, 55 TrackBar class, 54 MaximumCopes property, PrinterSettings class, 256 MaximumPage property, PrinterSettings class, 256 How can we make this index more useful? Email us at [email protected] 516 MaximumSize property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MaximumSize property, 10 MaxLength property, 47, 81, 160 MaxSelectionCount property, MonthCalendar class, 49 MDI (multiple-document interface) applications, 60-61 MdiChildren property, 61 MdiParent property, 61 measuring form size, 19 members SmoothingMode property, 23 static, classes, 3 MenuItem class, 57-58 MenuItems property, MenuItem class, 58 menus, 57-60 Merge method, 156 Merge Module Projects, 289 Message property, 73 message queues, 130 MessageQueuePermission, 331 messages, SOAP (Simple Object Access Protocols), 175 metadata assemblies, 105 COM components, 220 method links, 181 methods AcceptChanges, 156 Add, parameters, 162 AddNew, 123, 159 Array.Sort, 205 Assert, 272 BeginEdit, 160 BeginTransaction, 154 BindingManagerBase class, 123 CancelCurrentEdit, 123 CancelEdit, 160 Clear, 156-157 Close, 152-154, 272-273, 315 Close(), 11 CloseMainWindow, 308-312 Commit, 296 Contains, 124 Create, 316 CreateAttribute, 164 CreateCommand, 154 CreateElement, 164 CreateEventsource, 313-314 CreateGraphics(), 18 CreateNode, 164 CreateParameter, 155 DataReader.Close, 155 DataRow object, 160 DataSet object, 156 DataTable objects, 157 DataView object, 159 Debug methods, 272-273 Decrement, 315 Delete, 159-160, 313 DeleteEventSource, 313 deployment, 298-299 Draw, 21-23 DrawArc, 21 DrawBezier, 21 DrawBeziers, 21 DrawCloseCurve, 21 DrawCurve, 21 DrawEllipse, 21 DrawIcon, 21 DrawImage, 21 DrawLine, 21 DrawLines, 21 DrawPath, 21 DrawPie, 21 DrawPolygon, 21 DrawRectangle, 21 DrawRectangles, 21 DrawString, 21, 253 DrawString(), 19-20 EndCurrentEdit, 123 EndEdit, 160 ErrorProvider class, 84 event handlers, 102 EventLog class, 313-314 ExecuteNonQuery, 149, 155 ExecuteReader, 155 ExecuteScalar, 155 ExecuteXmlReader, 155 Exists, 313 Fail, 273 FileStream object, 152 Fill, 23-24, 155 FillClosedCurve, 23 FillEllipse, 23 FillPath, 23 FillPie, 23 FillPolygon, 23 FillRectangles, 23 FillRegion, 23 Find, 159 FindRows, 159 FindString, ListBox class, 45 FindStringExact, ListBox class, 45 Flush, 152, 273 Focus, 83 forms, 10 517 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Microsoft . . . . . certification . . . . . . .exams . . . GetChanges, 156 GetComputerName, 223 GetCurrent, 338 GetElementsByTagName, 164 GetError, 84 GetEventLogs, 313 GetItemProperties, 123 GetObject, 200 GetProcessById, 309 GetProcesses, 309 GetProcessesByName, 309 GetRandomNumber(), 96 GetString, 200 GetTextElementEnumerator(), 204 GetXml, 156 GetXmlSchema, 156 Graphics.FromHwnd(), 18 Graphics.FromImage(), 18 Hide(), 11 Increment, 315 IncrementBy, 316 Indent, 273 InitializeComponent(), 8 InitializeComponent, 104 input, 242 Install, 296 Installer class, 296 Invalidate(), 20 IsInRole, arguments, 338-339 IsNull, 160 Kill, 308-312 ListBox class, 45 Load, 164 LoadXml, 164 LogNameFromSourceName, 313 Main, 204, 257 MenuItem class, 58 Merge, 156 MoveNext(), 204 NewRow, 157 NextSample, 316 NextValue, 316 Open, 154 output, 242 Paint, 94 PerformanceCounter class, 315-316 PerformClick, MenuItem class, 58 Position, 127 Print, 252 Process class, 309-310 protected, base classes (event handling), 16-17 Read, 152 ReadByte, 152 ReadXml, 156 ReadXmlSchema, 156 Refresh, 123 RemoveAt, 123 RemoveInstance, 316 ResumeBinding, 123 Rollback, 296 Save, 164 Seek, 152 Select, 157-158 SendToBack, ToolBar class, 60 SetError, 84 SetIconAlignment, 84 SetIconPadding, 84 Show(), 10, 20 ShowDialog, 57 ShowHelp, 240 ShowHelpIndex, 240 SortKey.Compare, 205 SourceExists, 314 SqlCommand, 154-155 SqlConnection object, 154 SqlDataAdapter object, 155-156 Start, 53, 308-312 static methods, 9 Stop, Timer class, 53 String.Compare, 205 SuspendBinding, 123 Timer class, 53 ToolBar class, 59-60 Trace methods, 272-273 Unindent, 273 Uninstall, 296 Update, 156 WaitForExit, 310 WaitForInputIdle, 310 Web, 180 Write, 152, 273 WriteByte, 152 WriteEntry, 314 WriteIf, 273 WriteLine, 273 WriteLineIf, 273 WriteTo, 164 WriteXml, 156 WriteXmlSchema, 156 XmlDocument class, 164 Microsoft certification exams adaptive exams, strategies, 465-466 build-list-and-reorder questions, 455-457 case studies, 453-454, 463-464 How can we make this index more useful? Email us at [email protected] 518 Microsoft certification exams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . create-a-tree questions, 457-459 drag-and-connect questions, 458-460 fixed-length exams, strategies, 464-465 formats, 461-463 multiple-choice questions, 454-455 practice exams, taking, 467-468 question handling, strategies, 466-467 readiness, assessing, 451-452 resources, 468 select-and-place questions, 460 short-form exams, strategies, 464-465 testing centers, 452 Microsoft Certified Professional pages, 468-469 Microsoft Intermediate Language (MSIL) Disassembler, 105-106 Microsoft Management Console (MMC) utility, 328 Microsoft Passport, 337 Microsoft Web site, 299, 468 Microsoft Windows Explorer, 295 Microsoft Windows Installer, 288, 291, 295 Min aggregate function, 158 Min function, 144 MinDate property, 49-50 MinimizeBox property, 10, 241 minimum permissions, code access security, 332-333 Minimum property, 48, 54-55 MinimumPage property, PrinterSettings class, 256 MinimumSize property, 10 mirroring user interfaces, 202-203 MMC (Microsoft Management Console) utility, 328 modal dialog boxes, 57 Modal property, 10 modeless dialog boxes, 57 models ADO.NET Object Model data provider objects, 153-155 DataSet object, 156-162 data, data sources, 129 events, publisher/subscriber (COM+ components), 223 publisher-subscriber, 102 security, zones, 297-298 modes Debug, 275-276 High Contrast, 244 Release, compiled applications, 272 ModifiedCurrent value (DataViewRowState), 158 ModifiedOriginal value (DataViewRowState), 158 modifiers, access, 3 Modifiers property, 82 modifying form properties, 6 modules code, 336 unit testing, 271 Modules property, 312 monitoring performance, 315-316 MonthCalendar class, 49-50 MonthCalendar control, 49-50 mouse input, accessibility, 243 MouseDown event, 14 MouseEventArgs type, properties, 16 MoveNext() method, 204 .msi (Microsoft Windows Installer), 288 MSIEXEC command, 299 MSIL (Microsoft Intermediate Language) Dissassembler, 105-106 MultiColumn property, ListBox class, 45 multifile .NET assemblies, 107 MultiLine property TabControl class, 55 TextBox class, 42 multimedia files, 235 multiple catch blocks, 74 multiple data sources, controls, 125-127 multiple records, statements, 145 multiple-choice questions, exam format, 454-455 multiple-document interface (MDI) applications, 60-61 MultiSelect property, ListView class, 52 multitable forms, creating, 129 multitasking, accessibility, 243 MyCustomer library, 222 My_Computer_Zone, 297 N Name property, 10, 37 names, properties (ActiveX controls), 219 /namespace:Namespace command-line option (wsdl.exe), 179 /namespace:namespace option (Type Library Importer Tool), 221 namespaces classes, 4 drawing shapes (forms), 21-23 drawing text (forms), 19-21 filled shapes (forms), 19, 23-24 GDI+ (Graphics Device Interface), 17 519 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . objects . . . . naming, 4 .NET Framework, 4-5 System.ComponentModel, 94 System.Drawing, Graphics object, 17-19 System.IO, classes, 151 System.Reflection.Emit, 107 System.Text, Encoding subclasses, 202 System.Windows.Forms, 94 Systems.Diagnostics, 308 Visual Studio .NET, 4-5 naming namespaces, 4 .NET assemblies, 108 XML tags, 163 native .NET assemblies, 108 .NET application, 147 .NET assemblies, 105-110 .NET components Component class, creating, 94-97 Control class, creating, 94, 98-99 creating, 94-95 UserControl class, creating, 94, 99-105 .NET Connected, 299 .NET Framework, 291 classes, 2 code development, 2 inheritance, 3 namespaces, 4-5 objects, 2 .NET Framework Components tab, 97 .NET Framework Configuration tool, 295, 328-329, 334 network download (deployment method), 298 neutral culture codes, 194 New Breakpoint dialog box, 277 New Breakpoint option, 277 New Project button, 6 New Project Wizard, 236 New, HTML File command (File menu), 236 New, Index command (File menu), 238 New, Project command (File menu), 6, 236 New, Table of Contents command (File menu), 237 NewRow method, 157 NextSample method, 316 NextValue method, 316 No FileDialog permission, 335 nodes Code Groups, 335 Data Connections, 130-131, 147-149 hierarchies, 50 Performance Counters, 317 Permission Sets, 335 References, 215, 221-222 Runtime Security, 336 Runtime Security Policy, 335 User, 335 Nodes property, TreeView class, 51 /nologo option (Type Library Importer Tool), 221 None member (SmoothingMode property), 23 None value (DataViewRowState), 158 Northwind database, 131 NOT keyword, 158 Nothing permission set, 334 NumericUpDown class, 48 NumericUpDown control, 47-48 O object pooling (COM+ components), 222 object reusability (COM+ components), 222 objects Binding, 120 BindingContext, 122 BooleanSwitch, 274 Brush, 23-24 C#, 2 CancelEventArgs, 83 Command, 154-155 Connection, 154 CultureInfo, 195 CultureInfo.CompareInfo, 205 CurrencyManager, 122 data provider, 153-155 DataAdapter, 155 DataColumn, 160 DataReader, 155 DataRelation, 131, 158 DataRow, 159-160 DataSet, 156-162 DataTable, 131, 157-159 DataView, 131, 159 EventLog, 314 EventLogEntryCollection, 314 FileStream, 152 Font, 36 Graphics retrieving, 18 System.Drawing namespace, 17-24 LicenseProvider, 326 How can we make this index more useful? Email us at [email protected] 520 objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . listener, 273 .NET Framework, 2 PageSettings, 255 Parameter, 154-155 Pen, 21-22 PlaceFacts, 178 SqlCommand, 149, 154-155 SqlConnection, 130, 154 SqlDataAdapter, 130, 155-156, 165 SqlError, 165 StringBuilder, 223 TerraService, 178 TraceSwitch, 274 Visual Studio .NET, 2 WindowsIdentity, 337-339 WindowsPrincipal, 337-339 OLEDB data provider, 153 OleDbPermission, 331 On-Screen Keyboard, 242 one-way data binding, user interfaces, 129 Opacity property, 10 Open button, 104 Open method, 154 Open With dialog box, 105 OpenFileDialog class, 150 OpenFileDialog dialog box, 56 Optimistic concurrency control, 166 Options button, 238-239 OR keyword, 158 ordering controls, Z-order, 34 Orientation property, TrackBar class, 54 OriginalRows value (DataViewRowState), 158 OSQL, 146 /out:Filename command-line option (wsdl.exe), 179 /out:filename option (Type Library Importer Tool), 221 Output Filename option, 292 output methods, 242 overriding protected methods, base classes (event handling), 16-17 OwnerDraw property, MenuItem class, 58 P Package Files option, 292 Page Setup button, 258 Page Setup dialog box, 258 PageBounds property, PrintPageEventArgs class, 255 pages, Existing Files, 236 PageSettings class, properties, 255 PageSettings object, 255 PageSettings property, PrintPageEventArgs class, 255 PageSetupDialog component, 258-259 PageSetupDialog dialog box, 56 Paint event, 98 Paint event handler, 20 Paint method, 94 PaintEventArgs argument, 18 Panel class, properties, 39 Panel control, 38-40 Panels property, StatusBar control, 59 PaperSize property, PageSettings class, 255 PaperSizes property, PrinterSettings class, 256 PaperSource property, PageSettings class, 255 PaperSources property, PrinterSettings class, 256 Parameter object, 154-155 parameters, Add method, 162 Parameters property, 155 parent container control, forms, 61 Parent property, MenuItem class, 58 parent windows, 60 ParentColumns property, 159 ParentKeyConstraint property, 159 ParentRelations property, 157 ParentRowsForeColor property, 128 ParentRowsLabelStyle property, 128 ParentRowsVisible property, 128 ParentTable property, 159 Passport, 337 /password:Password command-line option (wsdl.exe), 179 PasswordChar property, TextBox class, 42 Pen class, 22 Pen object, 21-22 PenType property, 22 perfmon.exe utility, 316 performance ActiveX controls, 219 monitoring, 315-316 Performance Counters, 130, 315-317 Performance Monitor, 316 PerformanceCounter class, 315-316 PerformanceCounterCategory, 316 PerformanceCounterPermission, 331 PerformClick method, MenuItem class, 58 permission sets, code access security, 334 Permission Sets node, 335 521 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Process . . . . class . . . permissions code access, 330-336 DirectoryServicesPermission, 331 DnsPermission, 331 EnvironmentPermission, 331 EventLogPermission, 331 FileDialogPermission, 331 FileIOPermission, 331 final, 336 FullTrust, 297 identity, 330 Internet, 297 IsolatedStorageFilePermission, 331 IsolatedStoragePermission, 331 LocalIntranet, 297 MessageQueuePermission, 331 minimum, code access security, 332-333 No FileDialog, 335 OleDbPermission, 331 PerformanceCounterPermission, 331 PrincipalPermission, 332 PrintingPermission, 331 PublisherIdentityPermission, 332 ReflectionPermission, 331 RegistryPermission, 331 role-based, 330 Security, 331 ServiceControllerPermission, 331 SiteIdentityPermission, 332 SocketPermission, 331 SqlClientPermission, 332 StrongNameIdentityPermission, 332 UIPermission, 332 URLIdentityPermission, 332 WebPermission, 332 ZoneIdentityPermission, 332 PictureBox class, 43 PictureBox control, 43, 54 PID (process identifier), 308 PInvoke (Platform Invoke), 223-224 PlaceFacts object, 178 Platform Invoke (PInvoke), 223-224 plus sign (+), 7, 158, 327 Point structure (System.Drawing namespace), 19 PointF structure (System.Drawing namespace), 19 pooling, object pooling (COM+ components), 222 pop-up help, 241 Popup event, MenuItem class, 58 Position method, 127 Position property, 123, 152 PositionChanged event, 123 pound sign (#), 158 practice exams, taking, 467-468 PreferredColumnWidth property, 128 PreferredRowHeight property, 128 preprocessing directives, 275 Preview button, 259-260 preview interface, PrintPreviewDialog component, 259 PRIMARY KEY constraint, 148 /primary option (Type Library Importer Tool), 221 PrimaryKey property, 157 PrincipalPermission, 332, 339 PrincipalPermissionAttribute attribute, 339 Print method, 252 PrintDialog component, 261 PrintDialog dialog box, 56 PrintDocument class, 252-256 Printer button, 261 PrinterName property, PrinterSettings class, 256 PrinterResolution property, PageSettings class, 255 PrinterResolutions property, PrinterSettings class, 256 PrinterSettings class, properties, 256 PrinterSettings property, PageSettings class, 255 printing implementing (PrintDocument class), 252 PrintDocument class, 252-256 PrintPageEventArgs class, properties, 255 printing controls, 257-261 PrintingPermission, 331 PrintPage event, 252 PrintPageEventArgs class, 255 PrintPreviewControl control, 260-261 PrintPreviewDialog component, 259-260 PrintPreviewDialog dialog box, 56 PrintRange property, PrinterSettings class, 256 PrintToFile property, PrinterSettings class, 256 PriorityClass property, 312 private .NET assemblies, 107-109 private access modifier, 3 private keys, shared assemblies, 294 private UDDI registries, 175 Process class, 308-312 How can we make this index more useful? Email us at [email protected] 522 process identifier (PID) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . process identifier (PID), 308 processes, running, 278-279 Processes dialog box, 278 processing, transactional (COM+ components), 223 ProcessName property, 312 ProcessorAffinity property, 312 ProductName static property, 9 ProductVersion static property, 9 Program Files folder, 292 ProgressBar class, properties, 54 ProgressBar control, 53-54 project files, Help, 235-236 Project Summary screen, 290 Project tab, 239 Project Types tree, 289 ProjectInstaller class, 296 projects Cab Projects, 289 HTML Help file (.hhp), 238 Merge Module Projects, 289 Setup and Deployment, 288-289 Setup Projects, 289-293 Web Setup Projects, 289 Projects tab, 238 prompts, command prompts, 178 properties AcceptsReturn, TextBox class, 41 AccessibleDescription, 243 AccessibleName, 243 AccessibleRole, 243 accessors, 12 Activation, ListView class, 51 ActiveLinkColor, LinkLabel class, 41 ActiveMdiChild, 61 Alignment, 22, 55, 59 AllowDbNull*, 160 AllowDelete, 159 AllowEdit, 159 AllowMargins, 258 AllowNew, 159 AllowOrientation, 258 AllowPaper, 259 AllowPrinter, 259 Alt, 82 AlternatingBackColor, 128 AutoCheck, 44 AutoFlush, 272 AutoIncrement, 160 AutomaticDelay, 241 AutoPopDelay, 241 AutoScroll, 39 AutoSize, 59 AutoZoom, 261 BackColor, 10, 128, 243 Background Color, 128 BackgroundImage, 10, 243 BindingContext, 127 BindingManagerBase class, 123 Bindings, 123 BlinkRate, 84 BlinkStyle, 84 BorderStyle, 59, 128 Bounds, 255 Brush, 22 Button class, 44 Button, 16 Buttons, 59 CalendarDimensions, 49 Cancel, 83, 255 CanDuplex, 256 CanRead, 152 CanSeek, 152 CanWrite, 152 CaptionBackColor, 128 CaptionFont, 128 CaptionText, 128 CaptionVisible, 128 CategoryName, 315 CausesValidation, 83 CharacterCasing, 41, 81 CheckBox class, 44 CheckBoxes, 51-52 Checked, 44, 58 CheckedIndices, 46, 52 CheckedItems, 46 CheckedListBox class, 46 CheckItems, 52 CheckState, 44 ChildColumns, 159 ChildKeyConstraint, 159 ChildRelations, 157 ChildTable, 159 classes, 3 Clicks, 16 ClientSize, 10 Collate, 256 Color, 22, 255 ColumnHeadersVisible, 128 ColumnName, 160 Columns, 157, 264 ColumnWidth, 45 ComboBox class, 47 CommandText, 154 CommandType, 154 523 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .properties . . . . . Condition, 293 Connection, 155 ConnectionString, 154 Constraints, 157 ContainerControl, 84 Control, 82 Control.Object, 34 control-based validation (user input), 80 ControlBox, 10 controls accessibility, 243-244 Anchor, 35 Dock, 35 Enabled, 35 Font, 36 GroupBox class, 39 Height, 37 Location, 37 modifying, 34 Name, 37 Panel class, 39 Size, 37 TabIndex, 37 TabStop, 37 Text, 37 Visible, 38 Width, 37 Copies, 256 Count, 123, 159 CounterHelp, 315 CounterName, 315 CounterType, 315 Current, 123 CurrentCulture, 196 CurrentUICulture, 196 custom, 11-12 CustomFormat, 50 DashCap, 22 DashPattern, 22 DashStyle, 22 DataBinding, 120 DataColumn object, 160 DataGrid control, 128 DataRelation object, 159 DataRow object, 160 DataSet object, 156 DataTable object, 157 DataType, 160 DataView object, 159 DateTimePicker class, 50 Debug methods, 272-273 DefaultPageSettings, 256 DefaultValue, 160 DeleteCommand, 155 Delta, 16 description, 274 DesktopLocation, 10 DetectUrls, 42 DisabledLinkColor, 41 DisplayName, 274 DocumentElement, 164 DomainUpDown class, 48 DrawMode, 47 DropDownStyle, 47 DropDownWidth, 47 Duplex, 256 dynamic, configuring, 326-328 Enabled, 10, 53, 58 EnableRaisingEvents, 309, 313 EndCap, 22 Entries, 313-314 Error, 165 ErrorProvider class, 84 EventLog class, 313-314 ExamName, 127 exception class, 73 ExceptObject, 79 ExitCode, 309 ExitTime, 309 FileStream object, 152 FirstDayOfWeek, 49 FlatMode, 128 Font, 40, 128 Font-Size, 243 ForeColor, 128, 243 Form class, 10 Format, 50 FormBorderStyle, 10 forms, modifying, 6 FromPage, 256 Graphics, 255 GridlineColor, 128 GridlineStyle, 128 GroupBox class, 39 Handle, 10 Handled, 81-82 HasExited, 309 HasMorePages, 255 HeaderBackColor, 128 HeaderFont, 128 HeaderForeColor, 128 HelpButton, 10, 241 HelpLink, 73 HelpNamespace, 240 How can we make this index more useful? Email us at [email protected] 524 properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . HelpNavigator, values, 240 HelpString, 241 Icon, 10, 59, 84 Id, 309 Image, 40, 43-44 ImageList, 51, 55, 60 Increment, 48 IndentLevel, 273 IndentSize, 273 InitialDisplay, 241 InnerException, 73 InsertCommand, 156 InstalledPrinters, 256 InstanceName, 316 Interval, Timer class, 53 IsDefaultPrinter, 256 IsMdiContainer, 61 IsPlotter, 256 IsTerminating, 79 IsValid, 256 Item, 159 Items, 124 ComboBox class, 47 DomainUpDown class, 48 ListBox class, 45 ListView class, 52 ItemHeight, ListBox class, 45 KeyChar, 81 KeyCode, 82 KeyData, 82 KeyEventArgs class, 82 KeyPressEventArgs class, 81 KeyValue, 82 Label class, 40 Landscape, 255-256 LargeChange, 54-55 LargeItemList, ListView class, 52 LayoutMdi, 61 Length, 152 Level, 274 LevelFinal, 336 LineJoin, 22 LinkArea, 41 LinkBehavior, 41 LinkColor, 41, 128 LinkLabel class, 41 Links, 41 List, 123 ListBox class, 45 Listeners, 273 ListView class, 51-52 Log, 313 LogDisplayName, 313 MachineName, 313, 316 MainWindowTitle, 312 MarginBounds, 255 Margins, 255 MaxDate, 49-50 MaxDropDownItems, 47 MaximizeBox, 10, 241 Maximum, 48, 54-55 MaximumCopies, 256 MaximumPage, 256 MaximumSize, 10 MaxLength, 47, 81, 160 MaxSelectionCount, 49 MdiChildActivate, 61 MdiChildren, 61 MdiParent, 61 Menuitems, 58 Message, 73 MinDate, 49-50 MinimizeBox, 10, 241 Minimum, 48, 54-55 MinimumPage, 256 MinimumSize, 10 Modal, 10 Modifiers, 82 Modules, 312 MonthCalendar class, 49-50 MouseEventArgs type, 16 MultiColumn, 45 MultiLine, 42, 55 MultiSelect, 52 Name, 10 names, ActiveX controls, 219 Nodes, 51 NumericUpDown class, 48 Opacity, 10 Orientation, 54 OwnerDraw, 58 PageBounds, 255 PageSettings, 255 PageSetupDialog component, 258 Panel class, 39, 59 PaperSize, 255-256 PaperSource, 255-256 Parameters, 155 Parent, 58 ParentColumns, 159 ParentKeyConstraint, 159 ParentRelations, 157 ParentRowsForeColor, 128 ParentRowsLabelStyle, 128 525 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .properties . . . . . ParentRowsVisible, 128 ParentTable, 159 PasswordChar, 42 Pen object, 22 PenType, 22 PerformanceCounter class, 315-316 PictureBox class, 43 Position, 123, 152 PreferredColumnWidth, 128 PreferredRowHeight, 128 PrimaryKey, 157 PrinterName, 256 PrinterResolution, 255-256 PrinterSettings, 255-256 PrintPageEventArgs class, 255 PrintPreviewControl control, 261 PrintRange, 256 PrintToFile, 256 PriorityClass, 312 Process class, 309-312 ProcessName, 312 ProcessorAffinity, 312 ProgressBar class, 54 RadioButton class, 44 RadioCheck, MenuItem class, 58 RawValue, 316 ReadOnly, 42, 48, 316 RelationName, 159 Relations, 156 ReshowDelay, 241 ResizeRedraw, 21 Responding, 312 RichTextBox class, 42 RightToLeft, 203 RowHeadersVisible, 128 RowHeaderWidth, 128 Rows, 157, 261 RowState, 160 Rtf, 42 Scrollable, 51-52 ScrollBar class, 42, 55 SelectedIndex, 45-48, 55 SelectedIndices, 45, 52 SelectedItem, 45-48 SelectedItems, 45, 52 SelectedNode, 51 SelectedRtf, 42 SelectedTab, 55 SelectedText, 47 SelectionBackColor, 128 SelectionColor, 42 SelectionEnd, 49 SelectionFont, 42 SelectionForeColor, 128 SelectionMode, 45-46 SelectionRange, 49 SelectionStart, 49 Shift, 82 Shortcut, 58 ShowCheckBox, 50 ShowInTaskbar, 10 ShowToday, 50 ShowTodayCircle, 50 ShowToolTips, 60 ShowUpDown, 50 ShowWeekNumbers, 50 simple data binding, 121-122 simple, 327 Size, 10 SizeMode, 43 SmallChange, 54-55 SmallImageList, 52 SmoothingMode, 22-23 Sort, 159 Sorted, 45-48, 51-52 Sorting, 52 Source, 73, 314 SqlCommand, 154-155 SqlConnection object, 154 SqlDataAdapter object, 155-156 StackTrace, 73 StandardError, 312 StandardInput, 312 StandardOutput, 312 StartCap, 22 StartInfo, 309 StartPage, 261 StartPosition, 10 StartTime, 312 static properties, 9 StatusBarPanel class, 59 Style, 59 SupportsColor, 256 TabControl class, 55 TabCount, 55 TabIndex, 244 TableName, 157 Tables, 156 TabPages, 55 TargetSite, 73 Text, 244 Button class, 44 CheckBox class, 44 GroupBox class, 39 How can we make this index more useful? Email us at [email protected] 526 properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Label class, 40 MenuItem class, 58 RadioButton class, 44 TextBox class, 42 TextAlign, 40 TextBox class, 41-42 TextChanged, 42 ThousandsSeparator, 48 Threads, 312 ThreeState, 44 TickFrequency, 54 TickStyle, 54 Timer class, 53 TodayDate, 50 ToolBar class, 59-60 ToolTipText, 59 ToPage, 256 TopMost, 10 TotalProcessorTime, 312 Trace methods, 272-273 TraceError, 274 TraceInfo, 274 TraceSwitch class, 274 TraceVerbose, 274 TraceWarning, 274 TrackBar class, 54 TreeView class, 51 UnhandledExceptionEventArgs class, 79 Unique, 160 UpdateCommand, 156, 165-166 UseAntiAlias, 261 UserProcessorTime, 312 Value, 48-50, 54-55 ValueChanged, 54 View, 52 VirtualMemorySize, 312 VisitedLinkColor, 41 Width, 22 WordWrap, 42 WorkingSet, 312 Wrap, 48 X, 16 XmlDocument class, 164 Y, 16 Zoom, 261 ZoomFactor, 42 Properties window, 34 Property Pages dialog box, 291-292 protected access modifier, 4 protected methods, base classes (event handling), 16-17 protocols FTP (File Transfer Protocol), 175 HTTP (Hypertext Transfer Protocol), 175 SMTP (Simple Mail Transfer Protocol), 175 SOAP (Simple Object Access Protocol), 174 proxy classes, 176-178 public access modifier, 3 public key encryption, 294 public keys, shared assemblies, 294 public UDDI registries, 175 /publickey:filename option (Type Library Importer Tool), 221 publisher-subscriber model, 102 publisher/subscriber events model (COM+ components), 223 PublisherIdentityPermission, 332 publishers, 102 publishing performance data, 316 Q queries ad-hoc, 146-148 cross-product result set, 143 SQL, 144-150 QueryPageSettings event, 252 question-handling strategies, 466-467 queued components, asynchronous calls (COM+ components), 223 queues, message, 130 R RadioButton class, 44 RadioButton control, 43-44, 80 RadioCheck property, MenuItem class, 58 RandomNumberGenerator component, 97 RawValue property, 316 Read method, 152 ReadByte method, 152 readiness, exams, 451-452 reading performance data, 315-316 ReadOnly property, 316 DomainUpDown class, 48 NumericUpDown class, 48 TextBox class, 42 ReadXml method, 156 ReadXmlSchema method, 156 527 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .runtime . . . . records elements, 129 statements, inserting, 145 tables, adding, 145 Rectangle structure (System.Drawing namespace), 19 RectangleF structure (System.Drawing namespace), 19 /reference:filename option (Type Library Importer Tool), 221 references, Web, adding (Web Services), 176-178 References folder, 176 References node, 215, 221-222 ReflectionPermission, 331 Refresh method, 123 #region, code block, 7 #region directive, 275 registering event sources, 314 registries, UDDI (Universal Description, Discovery, and Integration), 175 Registry Editor, 292 RegistryPermission, 331 regression testing, 272 relational databases, 129, 150, 156 RelationName property, 159 Relations property, 156 Release folder, 291 Release mode, compiled applications, 272 reliability, application testing, 271 remote debugging, 279 remote systems, processes, 309 remoting channels, managing, 329 removable media (deployment method), 298 RemoveAt method, 123 RemoveInstance method, 316 rendering shapes, 22 RequestMinimum value, 333 RequestOptional value, 333 RequestRefuse value, 333 requests, FileDialogPermissionAttribute, 333 resgen.exe (Resource File Generator tool), 110 ReshowDelay property, 241 Resize event, 98 ResizeRedraw property, 21 Resource File Generator tool (resgen.exe), 110 resource files, 194 assembly, 201 .NET assemblies, 109-110 runtime resources, 200-201 Visual Studio .NET IDE, 198-200 resource-only .NET assemblies, 109-110 ResourceManager class, 110, 200 ResourceReader class, 110 resources accessing, 330 classes, 110 exam strategies, 468 Server Explorer, 130 ResourceWriter class, 110 Responding property, 312 responses, event (custom controls), 101-103 Restricted Sites Zone, 298 result sets, cross-product, 143 ResumeBinding method, 123 ResXResourceReader class, 110 ResXResourceWriter class, 110 reusability, objects (COM+ components), 222 Rich Text Format (RTF), 41 rich-text files, 293 RichTextBox class, properties, 42 RichTextBox control, 41-42 RID (role identifier), 339 RightToLeft property, 203 Robohelp, 235 robustness, application testing, 271 role identifier (RID), 339 role-based permissions, 330 role-based security COM+ components, 222 authorization, 330, 337-339 Rollback method, 296 rolling back (installations), 288 root elements XML, 163 RowChanged event, 157 RowChanging event, 157 RowDeleted event, 157 RowDeleting event, 157 RowHeadersVisible property, 128 RowHeaderWidth property, 128 Rows property, 157, 261 RowState property, 160 RTF (Rich Text Format), 41 Rtf property, RichTextBox class, 42 .rtf files, 293 Rumtime Security settings, 298 Run static method, 9 running processes, debugging, 278-279 runtime, dynamic runtime configurations, 326-329 How can we make this index more useful? Email us at [email protected] 528 runtime resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . runtime resources, localizing, 200-201 Runtime Security node, 336 Runtime Security Policy, 298, 335 runtime user interface, 94 runtime-callable wrappers, 219-220 S sampling performance counters, 316 satellite .NET assemblies, 109-110 satellite assemblies, controls, 200 Save method, 164 SaveFileDialog dialog box, 56 screens Choose a Project Type, 289 Choose Files to Include, 290 Choose Project Outputs to Include, 289 Project Summary, 290 Scroll event, 54-55 Scrollable property, 51-52 ScrollBar class, 55 scrollbars, controls, 39 ScrollBars property, TextBox class, 42 scrolling, PrintPreviewDialog component, 259 SDK (Software Development Kit), 178, 235, 294 Search button, 469 searching, keywords, 239 security code access, 329 code groups, 333-334 permissions, 330-336 configuring code access security, 329-336 role-based security, 330 declarative, 336 imperative, 336 role-based, 330 authorization, 337-339 COM+ components, 222 Security event log, 313 security model, zones, 297-298 security policy settings, managing, 329 SecurityAction.RequestMinimum flag, values, 333 SecurityPermission, 331 Seek method, 152 Select event, MenuItem class, 58 SELECT INTO, 145 Select method, 157-158 SELECT statement, 142-145 select-and-place questions, exam format, 460 SelectedIndex property, 45-48, 55 SelectedIndexChanged event, 45-47, 52, 55 SelectedIndices property, 45, 52 SelectedItem property, 45-48 SelectedItemChanged event, DomainUpDown class, 48 SelectedItems property, 45, 52 SelectedNode property, TreeView class, 51 SelectedRtf property, RichTextBox class, 42 SelectedTab property, TabControl class, 55 SelectedText property, ComboBox class, 47 SelectionBackColor property, 128 SelectionColor property, RichTextBox class, 42 SelectionEnd property, MonthCalendar class, 49 SelectionFont property, RichTextBox class, 42 SelectionForeColor property, 128 SelectionMode property, 45-46 SelectionRange property, MonthCalendar class, 49 SelectionStart property, MonthCalendar class, 49 SendToBack method, ToolBar class, 60 /server command-line option (wsdl.exe), 179 Server Explorer, resources, 130 servers, SQL, 130, 146-150 Service Pack 1 (SP-1), 297 ServiceControllerPermission, 331 Services, Server Explorer, 130. See also Web Services set accessors, 12 SetError method, 84 SetIconAlignment method, 84 SetIconPadding method, 84 SetProcessDefaultLayout Windows API, 203 sets, permission 334 Setup and Deployment projects, 288-289 Setup Projects, 289-293 Setup Wizard, 289 Setup.exe file, 291 shapes, 21-24 shared .NET assemblies, 107-109 shared assemblies, 293-296 shfusion.dll (Assembly Cache Viewer Shell Extension), 295 Shift property, 82 short-form exams, 461-465 529 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .StartCap . . . . property . . . . . Shortcut property, MenuItem class, 58 shortcuts. See keyboard shortcuts Show All Files button, 105 Show All Files icon, 176 Show() method, 10, 20 ShowCheckBox property, DateTimePicker class, 50 ShowDialog method, 57 ShowHelp method, 240 ShowHelpIndex method, 240 ShowInTaskbar check box, 327 ShowInTaskbar property, 10 ShowToday property, MonthCalendar class, 50 ShowTodayCircle property, MonthCalendar class, 50 ShowToolTips property, ToolBar class, 60 ShowUpDown property, DateTimePicker class, 50 ShowWeekNumbers property, MonthCalendar class, 50 signatures, digital, 292-294 signcode.exe (File Signing tool), 295 signing shared assemblies, 294-295 /silent option (Type Library Importer Tool), 221 simple data binding, user interfaces, 120-124 Simple Mail Transfer Protocol (SMTP), 175 Simple Object Access Protocol (SOAP), 174 simple properties, 327 simulations, 461 single quotes (‘’), 157 Single Threaded Apartment (STA), 8 single-document interface applications, 60-61 single-file .NET assemblies, 107 single-table forms, creating, 129 Site code group, 334 SiteIdentityPermission, 332 size accessibility, 243 forms, measuring, 19 Size property, 10, 37 Size structure (System.Drawing namespace), 19 SizeF structure (System.Drawing namespace), 19 SizeMode property, PictureBox class, 43 SkipVerification permission set, 334 SmallChange property, 54-55 SmallImageList property, ListView class, 52 SmoothingMode property, 22-23 SMTP (Simple Mail Transfer Protocol), 175 sn.exe (Strong Name utility), 294-295 SOAP (Simple Object Access Protocol), 174-175 SocketPermission, 331 Software Development Kit (SDK), 178, 235, 294 Software publisher code group, 334 SolidBrush class, 24 Solution Explorer, 95-96, 105, 176 Solution Explorer window, 327 solutions, HTML Help, 235 Sort property, 159 Sorted property, 45-48, 51 sorting culture-aware, 205 data, 205 Sorting property, ListView class, 52 SortKey.Compare method, 205 sound accessibility, 243 files, 235 Source property, 73, 314 SourceExists method, 314 sources data sources, 125-129 event, 314 SP-1 (Service Pack 1), 297 SQL (Structured Query Language) queries, wildcards, 144 servers, 130, 146-150 view, 131-132 SQL Query Analyzer, 147 SQL Server data provider, 153 SqlClientPermission, 332 SqlCommand object, 149, 154-155 SqlConnection object, 130, 154 SqlDataAdapter object, 130, 155-156, 165 SqlError object, 165 SqlException class, 165 square brackets ([]), 144, 157 STA (Single Threaded Apartment), 8 StackTrace property, 73 StandardError property, 312 StandardInput property, 312 StandardOutput property, 312 Start command (Debug menu), 6 Start method, 53, 308-312 StartCap property, 22 How can we make this index more useful? Email us at [email protected] 530 StartInfo property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . StartInfo property, 309 StartPage property, PrintPreviewControl control, 261 StartPosition property, 10 StartTime property, 312 Startup folder, 292 statements CREATE PROC, 148 debugging, 272 DELETE, 146 INSERT, 145 records, inserting, 145 SELECT, 142-145 throw, 77-78 UPDATE, 145 states, controls, 43 static .NET assemblies, 107 static members classes, 3 static methods, 9 static properties, 9 StatusBar control, 58-59 StatusBarPanel class, properties, 59 StDev aggregate function, 158 Step Into command (Debug menu), 276 Step Out command (Debug menu), 276 Step Over command (Debug menu), 276 step-by-step execution, code (debugging), 276 Stop method, Timer class, 53 storage file-based data storage, 150 relational database, 150 stored procedures, 146-150 storing cultures, localized settings, 200 form customizations, 8 .NET assemblies, 107-108 shared assemblies, 293 validating logic, fields, 83 StreamReader class, 151 streams, 151-153 StreamWriter class, 151 /strictref option (Type Library Importer Tool), 221 string buffers, 223 string indexing, 203-204 String.Compare method, 205 StringBuilder objects, 223 StringInfo class, 204 Strong name code group, 334 Strong Name utility (sn.exe), 294-295 StrongNameIdentityPermission, 332 structures, System.Drawing namespace, 19 stubs, unit testing, 270 Style property, StatusBarPanel class, 59 subclasses, 202 subculture codes, 194 subscribers, 102 subtract sign (-), 7 SUBSTRING function, 158 Sum aggregate function, 158 Sum function, 144 SupportsColor property, PrinterSettings class, 256 SuspendBinding method, 123 Switch class, 274 switches, trace, 274 symbols @, 148 custom, 275 DEBUG, 275 TRACE, 275 synchronization, DataSet, 164 syntax. See code /sysarray option (Type Library Importer Tool), 222 SysInfo control, 217 System event logs, 313 System folder, 292 System.ComponentModel namespace, 94 System.Configuration.AppSettingsReader class, 326 System.Drawing namespace Graphics object, 17-19 drawing shapes, 21-23 drawing text, 19-21 filled shapes, 23-24 structures, 19 System.Drawing namespace (GDI+), 17 System.Drawing.Drawing2D namespace (GDI+), 17 System.Drawing.Imaging namespace (GDI+), 18 System.Drawing.Text namespace (GDI+), 18 System.IO namespace, classes, 151 System.Object type, 14 System.Reflection.Emit namespace, 107 System.Text namespace, Encoding subclasses, 202 System.Windows.Forms namespace, 94 System.Windows.Forms.UpDownBase class, inheritance, 47 SystemBrushes class, 24 531 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . tools . . . SystemException, 72 SystemException catch block, 74 SystemPens class, 22 Systems.Diagostics namespace, 308 T T-SQL (Transact-SQL) DELETE statement, 146 INSERT statement, 145 SELECT statement, 142-144 UPDATE statement, 145 Tab key, 37 TabControl class, 55 TabControl control, 55 TabCount property, TabControl class, 55 TabIndex property, 37, 244 table columns, child, 158 table of contents, 237-239 TableName property, 157 TableOfContents value, 240 tables DataSet objects, 157 fields, selecting, 143 records, 129, 145 Tables property, 156 TabPages property, TabControl class, 55 tabs COM, 215, 222 COM Components, 217 Files, 239 .NET Framework Components, 97 Project, 238-239 TabStop, control property, 37 tags, XML, 163 TargetSite property, 73 templates Class Library, 95 User Control, 98 Windows Control Library, 100, 104 TerraService object, 178 testing application testing, 270-271 automated alpha-phase, 270 bottom-up, 271 HTML Help files, 239 human-interaction, 270 international applications, 272 stubs, 270 top-down, 271 umbrella, 271-272 Web Services, 181 testing centers, environment, 452 tests. See exams text forms, drawing, 19-21 printing, PrintDocument class, 253-254 Text check box, 327 Text property, 37, 244 Button class, 44 CheckBox class, 44 GroupBox class, 39 Label class, 40 MenuItem class, 58 RadioButton class, 44 TextBox class, 42 TextAlign property, Label class, 40 TextBox class, 41-42 TextBox control, 41-42, 194-196 TextBoxBase class, 41 TextChanged event, TextBox class, 42 TextChanged property, RichTextBox class, 42 TextureBrush class, 24 TextWriterTraceListener class, 273 This window, 280 ThousandsSeparator property, NumericUpDown class, 48 thread-by-thread localization, 196 Threads property, 312 ThreeState property, CheckBox class, 44 throw statement, 77-78 throwing exceptions, 77, 278 Tick event, Timer class, 53 TickFrequency property, TrackBar class, 54 TickStyle property, TrackBar class, 54 time values, 49 Timer class, 53 Timer component, 95 Timer control, 53-54 timing, accessibility, 243 tlbimp.exe (Type Library Importer Tool), 220-222 TodayDate property, MonthCalendar class, 50 tool, .NET Framework Configuration, 295 ToolBar class, 59-60 ToolBar control, 59-60 toolbox, components, 97 tools Assembly Generation (al.exe), 107, 110 Configuration, 298 deployment tools, 288, 291 File Signing (signcode.exe), 295 How can we make this index more useful? Email us at [email protected] 532 tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Global Assembly Cache tool (GacUtil.exe), 296 Installer (InstallUtil.exe), 297 .NET Framework Configuration, 328-329, 334 Resource File Generator (resgen.exe), 110 Type Library Importer Tool (tlbimp.exe), 220-222 wsdl.exe, 178-179 Tools menu commands, Debug Processes, 278 ToolTip component, 241 ToolTip control, 56 ToolTipText property, StatusBarPanel class, 59 top-down integration testing, 271 ToPage property, PrinterSettings class, 256 topic files, 235-237 Topic value, 240 TopMost property, 10 TotalProcessorTime property, 312 Trace class, 272-273 trace listeners, 273 trace switches, 274 TRACE symbol, 275 TraceError property, 274 TraceInfo property, 274 TraceLevel class, enumeration, 274 TraceListener class, 273 TraceSwitch class, properties, 274 TraceSwitch object, 274 TraceVerbose property, 274 TraceWarning property, 274 tracing, 272-275 TrackBar class, 54 TrackBar control, 53-54 Transact-SQL. See T-SQL transactional processing (COM+ components), 223 transforming data, 129-132 translations, French, 199 trees, Project Types, 289 TreeView class, 51 TreeView control, 50-52 troubleshooting, 288. See also exceptions Trusted Sites Zone, 298 try blocks, 73-74, 77 try-catch blocks, code, 75 two-way data binding, user interfaces, 129 txtCulture TextBox control, 194-196 txtCurrency TextBox control, 196 txtDate TextBox control, 196 txtNumber TextBox control, 196 Type Library Importer Tool (tlbimp.exe), 220-222 U UDDI (Universal Description, Discovery, and Integration), 175 UI (user interface), localization, 193 cultures, 194-197 resource files, 194, 198-201 UIPermission, 332 umbrella integration testing, 272 Unchanged value (DataViewRowState), 158 unchecked keywords, 76 #undef directive, 275 unhandled expressions, 79-80 UnhandledException event, 79 UnhandledExceptionEventArgs class, properties, 79 Unicode, 201 UnicodeEncoding subclass, 202 Unindent method, 273 Uninstall method, 296 Unique property, 160 unit testing, 270-271 Universal Description, Discovery, and Integration (UDDI), 175 unmanaged code. See legacy code /unsafe option (Type Library Importer Tool), 222 Update method, 156 UPDATE statement, 145 UpdateCommand property, 156, 165-166 URL code group, 334 URL remoting, 297-298 URLIdentityPermission, 332 UseAntiAlias property, PrintPreviewControl control, 261 user assistance, 239-241 User Control template, 98 user input comparing/storing, 203-205 managing, 203 validating, 80-85 user interface (UI), localization, 193 cultures, 194-197 resource files, 194, 198-201 User Interface Editor, 293 user interface mirroring, 202-203 533 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Web . . Services . . . . . user interfaces client-side, 94 complex data binding, 124-128 data binding, 120, 129 one-way data binding, 129 runtime, 94 simple data binding, 120-124 two-way data binding, 129 User node, 335 UserControl class, 98 controls, creating, 100-101 .NET components, creating, 94, 99-105 /username:Username command-line option (wsdl.exe), 179 UserProcessorTime property, 312 UTF7Encoding subclass, 202 UTF8Encoding subclass, 202 utilities command-line, OSQL, 146 disco.exe, 178 MMC (Microsoft Management Console), 328 perfmon.exe, 316 Strong Name (sn.exe), 294-295 XCOPY, 288 V validating user input, 80-85 Validating event, 83 validating logic, fields, 83 value, RequestOptional, 333 Value property, 48-50, 54-55 ValueChanged event, 48-50, 55 ValueChanged property, TrackBar class, 54 values AssociateIndex, 240 Boolean, 35, 38 databases, modifying, 145 date, 49 Demand, 333 enumerated, 158, 314 Find, 240 foreign key, 129 HelpNavigator property, 240 Index, 240 KeywordIndex, 240 RequestMinimum, 333 RequestRefuse, 333 SecurityAction.RequestMinimum flat, 333 TableOfContents, 240 time, 49 Topic, 240 Var aggregate function, 158 /verbose option (Type Library Importer Tool), 222 view, Code, 98 View Compiled File button, 239 View menu commands, Class View, 100 View property, ListView class, 52 viewing Assembly Manifest, 105-106 editors, 293 GAS (Global Assembly Cache), 108-109 views Code, 6-8, 221 Design, 6, 98 SQL, 131-132 VirtualMemorySize property, 312 Visible, control property, 38 VisitedLinkColor property, LinkLabel class, 41 Visual C# .NET, classes, 3 visual cues, adding, 244 visual inheritance, 13, 103-105 Visual Studio .NET classes, 2 command prompt, 178 IDE (integrated development environment), 2 inheritance, 3 namespaces, 4-5 objects, 2 Web Services, Web references, 176-178 Visual Studio .NET IDE, 34, 146, 198-200, 292-293 Visual Studio .NET toolbox, 217-218 VScrollBar control, 54-55 W WaitForExit method, 310 WaitForInputIdle method, 310 #warning directive, 275 Watch window, 280 Web methods, 180 Web references, adding (Web Services), 176-178 Web Services creating, 180-181 Disco, 175 disco.exe, 178 discovery, 176 How can we make this index more useful? Email us at [email protected] 534 Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . invoking, 178 proxy classes, 176 SOAP (Simple Object Access Protocol), 174 UDDI (Universal Description, Discovery, and Integration), 175 Web references, adding, 176-178 wsdl.exe, 178-179 Web Services Description Language (WSDL), 175 Web Setup Projects, 289 Web sites, Microsoft, 299, 468 Web-based distribution (deployment method), 299 Web-based resources, 468-469 WebMethod attribute, 180 WebPermission, 332 WebService attribute, 180 WHERE clause, 144, 157 Width, control property, 37 Width property, 22 wildcards (%), 144, 158 windows Auto, 279 Breakpoints, 277 Call Stack, 279 child, 60 Immediate, 279 Locals, 279 logo certification, 299 parent, 60 Properties, 34 Solution Explorer, 327 This, 280 Watch, 280 Windows applications event logs, 313-314 performance, 315-316 Process class, 308-312 Windows authentication, 337 Windows command (Debug menu), 279 Windows Control Library template, 100, 104 Windows event log, 79 Windows Explorer (Microsoft), 295 Windows Form Designer, 5 blank forms, creating, 6 Code view, 7-8 controls, managing, 200 forms, 6-8 Windows Forms ActiveX Control Importer (aximp.exe), 215-217 Windows Forms Designer, 61-63 Windows Forms dialog components. See dialog boxes Windows Installer (Microsoft), 288, 291, 295 Windows, Breakpoints command (Debug menu), 277 WindowsIdentity object, 337-339 WindowsPrincipal object, 337-339 wizards Add/Remove Programs Wizard, 296 C# Property Wizard, 100 Data Form Wizard, 129 New Project Wizard, 236 Setup, 289 WordWrap property, 42 WorkingSet property, 312 Wrap property, DomainUpDown class, 48 wrappers ActiveX controls, 214 runtime-callable, 219-220 Write method, 152, 273 WriteByte method, 152 WriteEntry method, 314 WriteIf method, 273 WriteLine method, 273 WriteLineIf method, 273 WriteTo method, 164 WriteXml method, 156 WriteXmlSchema method, 156 WSDL (Web Services Description Language), 175, 178 wsdl.exe tool, 178-179 X-Z X property, 16 XCOPY utility, 288 XML (Extensible Markup Language) data, 162-165 data files, 150 declarations, 163 root elements, 163 SOAP messages, 175 tags, naming, 163 WSDL (Web Services Description Language), 175 XmlDataDocument class, 164-165 XmlDocument class, 163-164 Y property, 16 535 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .ZoomFactor . . . . . . property . . . . . Z-order, control order, 34 Zone code group, 334 ZoneIdentityPermission, 332 zones, security model, 297-298 zoom, PrintPreviewDialog component, 259 Zoom property, PrintPreviewControl control, 261 ZoomFactor property, RichTextBox class, 42 How can we make this index more useful? Email us at [email protected]