Copyright © 2002 by Microsoft Corporation PUBLISHED BY Microsoft Press A Division of Microsoft Corporation One Microsoft Way Redmond, Washington 98052-6399 Copyright © 2002 by Microsoft Corporation All rights reserved No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of the publisher Library of Congress Cataloging-in-Publication Data Williams, Mickey Microsoft Visual C# (core reference) / Mickey Williams p cm Includes index ISBN 0-7356-1290-0 1 Microsoft Visual C# C# (Computer program language) I Title QA76.736.C153 W55235 2002 005.26'8 dc21 Printed and bound in the United States of America QWE Distributed in Canada by Penguin Books Canada Limited A CIP catalogue record for this book is available from the British Library Microsoft Press books are available through booksellers and distributors worldwide For further information about international editions, contact your local Microsoft Corporation office or contact Microsoft Press International directly at fax (425) 936-7329 Visit our Web site at www.microsoft.com/mspress Send comments to mspinput@microsoft.com ActiveX, Authenticode, Encarta, FrontPage, IntelliMouse, IntelliSense, JScript, Microsoft, Microsoft Press, MSDN, NET logo, OpenType, Verdana, Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, Windows, Windows NT, and Xbox are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries Other product and company names mentioned herein may be the trademarks of their respective owners The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious No association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred Acquisitions Editor: Danielle Bird Project Editor: Dick Brown Technical Editors: Donnie Cameron and Julie Xiao Body Part No X08-06141 Acknowledgments No author can create a book of this scope working alone—the number of people who come together on a project like this is amazing An author agrees to write a book, and as the process begins, people start coming out of the woodwork to help It’s a lot like the Microsoft Office Assistant: “Hey! It looks like you’re writing a book! Want some help? How about some great graphics for the part openers in your book? This heading would be great if it was in a gerund form!” At Microsoft Press, I’d like to thank Danielle Bird for asking me to write this book Danielle, I promise to stop hounding you for an Xbox console I’d also like to thank Dick Brown, who is doomed to a life of trying to get authors like me to hit deadlines I’m sure Dick is happy to see the last bits of this book cross his desk Jennifer Harris was responsible for turning my geeky text into readable English sentences Jennifer, I’m sorry about forcing you to read my long-winded digression on the significance of the Battle of Agincourt Thanks to Donnie Cameron and Julie Xiao for their excellent work as technical editors I’ve never been so thoroughly reviewed and cross-checked Thanks for your diligence and support A big thank you to the other authors, who provided me some much-needed help: Brad Jones, Brad Wist, Mike Pope, and Christoph Wille Thanks, guys Thanks to the people I work with at Interactive Software Engineering and NET Experts in Santa Barbara: Bertrand and Annie Meyer, Raphaël Simon, Manu Stapf, and Bill Navickas Thanks for working around my schedule and for providing a great place for me to train and consult with other developers Special thanks to Hal Webre, my training cohort at NET Experts Hal kept me well supplied with CDs and cookbooks While we were at the ACM SIGCSE conference recently, Hal took me out for Cincinnati-style chili, which was interesting, but why it’s called chili is beyond me And it’s not just to the people who deal with me professionally that I owe thanks Thanks to my sister, Jennifer, and her husband, Mitch, for providing a base where I could write while I was in San Diego, as well as for scheduling new additions to their family around my book writing timetable And finally, thanks to my daughters, Ali and Mackenzie, for remembering what I look like And thanks to my wife, René for being far more patient than I deserve Next year we’re definitely going to Banff For my racing buddies Ali and Mackenzie, and for my wife René, who has been waiting for a trip to Banff for 10 years now Introduction When I first started working with Microsoft Visual C# NET, I was immediately struck by how productive my coding sessions became Even though I was working with the pre-Beta release, the development environment and the NET Framework simplified much of the work that I was doing The increased productivity was due to four factors: The C# programming language, which is well-suited for component-based development The simplified programming and deployment model offered by the common language runtime The NET Framework and its associated class library The developer automation features included in the Microsoft Visual Studio NET environment The tools for development that are realized today with Visual C# NET are lightyears ahead of the tools I was using in the mid-1980s when I started developing for Microsoft Windows When I was asked to write a book about Visual C# NET, I just couldn’t refuse I’m sure that you’ll find working with Visual C# NET a rewarding experience, and I’m pleased that you’ve selected this book to help get you started I enjoy talking to readers, and I’m happy to answer any questions you might have after reading my books If you have any feedback or questions about this text, feel free to contact me at mickey.williams@codevtech.com I can’t always respond immediately, but I try to answer all of my e-mail Who Should Read This Book This book is intended for developers who want to learn the C# programming language using Microsoft Visual C# NET The book is intended to provide a broad overview of programming with Visual C# NET, so it explores a wide variety of topics In addition to a discussion of the C# programming language, this book covers the more commonly used classes in the NET Framework, including Windows Forms programming, ASP.NET, Extensible Markup Language (XML), Web services, and more System Requirements To use this book, you’ll need to have Visual C# NET or Visual Studio NET installed on your computer Any computer that satisfies the minimum requirements for Visual C# NET will work effectively with most of the examples in this book Be aware that Microsoft Windows XP Home Edition and Microsoft Win-dows NT 4 don’t support the hosting of XML Web services or ASP.NET Web applications with the NET Framework Although you can build these projects on these operating systems, you’ll need to upload the projects to a properly configured host to execute them I recommend that development be done on the Microsoft Windows XP Professional or Microsoft Windows 2000 Profes-sional operating systems For Chapter 20, you need IIS version 4 or later in order to run the sample code Organization This book is arranged in five parts, with each part covering a different aspect of programming using Visual C# NET: Part I Introduces the Visual C# NET environment and examines the core portions of the C# programming language Part II Describes the more advanced aspects of the C# programming language and the NET Framework In addition to chapters on delegates and exception handling, we’ll cover topics such as collection classes, debugging, and writing multithreaded code Part III Here you’ll learn how to write graphical user interface (GUI) applications using Visual C# NET The NET Framework includes extensive support for writing Windows Forms–based applications, and you’ll see that many advanced controls are very easy to use Part IV Examines ADO.NET and XML You’ll learn how to use ADO.NET for data access to databases such as SQL Server We’ll also look at the NET Framework classes that implement a new model for manipulating XML, in which data is pulled from an XML stream With the NET Framework and Visual C# NET, it’s easy to manage data using either ADO.NET or XML Part V The book wraps up with a discussion of creating Web applications using ASP.NET and Visual C# NET and shows you how to use XML Web services Sample Files Supplemental content for this book, including sample files, can be found at the Microsoft Press Web site, at http://www.microsoft.com/mspress/books/5029.asp Clicking the Companion Content link takes you to a page from which you can download the samples The sample files can also be found on the book’s companion CD, along with other supplemental content To access those files, insert the companion CD in your computer’s CD-ROM drive and make a selection from the menu that appears If the AutoRun feature is not enabled on your system (if a menu doesn’t appear when you insert the disc in your computer’s CD-ROM drive), run StartCD.exe in the root folder of the companion CD Installing the sample files on your hard disk requires approximately 7.8 MB of disk space If you have trouble running any of these files, refer to the text in the book that describes these programs Aside from the sample files that this book discusses, the book’s supple-mental content includes two eBook installations: a stand-alone eBook installa-tion, and a Visual Studio Help eBook installation The stand-alone eBook installation will allow you to access an electronic version of the print book directly from your desktop The Visual Studio Help eBook installation will allow you to access a second electronic version of the print book directly from the Visual Studio NET help system Visual Studio NET Professional Trial Version In addition to the companion CD, this book includes a DVD with an evaluation copy of Microsoft Visual Studio NET Professional This evaluation copy can help you follow the examples in this book and get you started learning Microsoft Visual C# NET, but the software must be activated and it will expire and stop working 60 days after you install it Also, your computer must have a DVDROM drive You can learn more about this evaluation copy and its system requirements at http://msdn.microsoft.com/vstudio/productinfo/trial.asp Support Every effort has been made to ensure the accuracy of this book and the con-tents of the companion CD Microsoft Press provides corrections for books through the World Wide Web at the following address: http://www.microsoft.com/mspress/support To connect directly to the Microsoft Press Knowledge Base and enter a query regarding a question or an issue that you may have, go to: http://www.microsoft.com/mspress/support/search.asp If you have comments, questions, or ideas regarding this book or the com-panion content, or questions that are not answered by querying the Knowledge Base, please send them to Microsoft Press via e-mail to: mspinput@microsoft.com Or via postal mail to: Microsoft Press Attn: Microsoft Visual C# NET (Core Reference) Editor One Microsoft Way Redmond, WA 98052-6399 Please note that product support is not offered through the above addresses For product support information, please visit the Microsoft Support Web site at: http://support.microsoft.com You can get more information about UDDI, register your Web services, or search for other Web services at http://www.uddi.org or http://uddi.microsoft.com Understanding WSDL Microsoft and IBM jointly developed WSDL to provide a standard way of documenting the messages that a Web service will send and receive These messages define the methods and outputs of the Web services These methods are known as the contract that’s offered by the service The contract specifies the message schemas that will be accepted and returned from the service WSDL is explained in detail in the Microsoft Developer Network (MSDN) article “Web Services Description Language (WSDL) Explained,” by Carlos Tapang, which can be found at http://msdn.microsoft.com/library/default.asp?url=/library/enus/dnwebsrv/html/wsdlexplained.asp Browsing a Web Service Once you’ve created and built a Web service, you can easily browse the contents of the service through a Web browser by navigating to the URL of the Web service page When you browse to a page without providing any parameters, the Web service will display its discovery information and other documentation if you provided it in the WebService attribute, as shown in Figure 21-5 Figure 21-5 Browsing a Web service by browsing to the asmx file This page will give you a quick look at the public methods of the Web service that have been exposed as Web methods Further, if you’ve provided a Description property for the WebMethod attribute, that information will be displayed here By clicking the link to any of these methods, you’ll load a page that displays the details of the particular method, as shown in Figure 21-6 Figure 21-6 Displaying the details for a Web service method This page is divided into four sections labeled Test, SOAP, HTTP GET, and HTTP POST In the Test section, you’ll find input boxes that can be used to pass any required parameters to the Web service method Click the Invoke button to call the method and display the results in a second browser window, as shown in Figure 21-7 Figure 21-7 The results of the Web service method, displayed in a second browser window In addition, the Web service method page displays the XML schemas used to send and receive data from the Web service via the SOAP, HTTP GET, and HTTP POST protocols (See the next section for more information about these protocols.) Consuming a Web Service After a Web service has been created, you can access and make use of it You can consume the Web service using one of three protocols that the service is configured to respond to, as follows: HTTP GET HTTP POST SOAP This section examines accessing a Web service method using these protocols Using the HTTP GET Protocol The HTTP GET protocol is the simplest of the protocols To consume the page, you simply make a call to the Web service name and pass the required parameters to the service as parameters in the query string, as shown here: http://localhost/WebService1/Service1.asmx/Add?x=5&y=2 This call will return an XML document that includes the results of the service The schema that’s returned will depend on the particular method that’s called The Web service supplies a contract that identifies how each protocol will be used to access the service The contract for the HTTP GET method is shown here: HTTP GET The following is a sample HTTP GET request and response The placeholders shown need to be replaced with actual values GET /webservice1/service1.asmx/Add?x=string&y=string HTTP/1.1 Host: localhost HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length long This is the same process that was used to browse the Web service, as described earlier in this chapter, in the section “Browsing a Web Service.” Using the HTTP POST Protocol The HTTP POST protocol is similar to the HTTP GET protocol—with both protocols, you call the Web service page and post the parameters to the page as required The following HTML code creates a Web page that allows you to access the Add Web service method described earlier in this chapter, in the section “Creating Web Methods”: The Web service method will write the results back to the page as an XML document, as shown here: 5 The Web service supplies a contract that identifies how each protocol will be used to access the service The contract for the HTTP POST method is shown here: HTTP POST The following is a sample HTTP POST request and response The placeholders shown need to be replaced with actual values POST /webservice1/service1.asmx/Add HTTP/1.1 Host: localhost Content-Type: application/x-www-form-urlencoded Content-Length: length x=string&y=string HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length long Using the SOAP Protocol More than likely, you’ll most often access the Web service using SOAP SOAP allows you to directly call components and execute methods The Web service will return the data as an XML document, with the results passed back through the SOAP return function The Web service supplies a contract that identifies how each protocol will be used to access the service The contract for the SOAP method is shown here: SOAP The following is a sample SOAP request and response The placeholders shown need to be replaced with actual values POST /webservice1/service1.asmx HTTP/1.1 Host: localhost Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://www.mysite.com/Add" int int HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length long Referencing a Web Service in the Visual Studio NET IDE To make use of a Web service in an application, you start by creating a reference to the Web service To do so, choose Add Web Reference from the Project menu to open the Add Web Reference dialog box, in which you can search for the Web service, as shown in Figure 21-8 To search your local server, click the Web References On Local Web Server link To search the UDDI services at Microsoft, click the appropriate links Or you can type the URL of the Web service’s discovery file in the Address bar Figure 21-8 The Add Web Reference dialog box If you click the Web References On Local Web Server link, the IDE will start a dynamic discovery of the Web services on your local machine, based on the http://localhost/default.vsdisco page A list of the existing Web services on your system will be displayed in the right pane of the Add Web Reference dialog box, as shown in Figure 21-9 If you click one of the Web service links, you’ll see detailed information about the Web service and you’ll be able to view the Web service contract and documentation, as shown in Figure 21-10 If this is the Web service you want to reference and use in your application, you can add the reference to your project by clicking the Add Reference button Figure 21-9 Browsing the local server to display the available Web services Figure 21-10 Displaying detailed information about the Web service Generating a Web Service Proxy If you want to make calls to an application other than one that you have on the local server, you’ll need to generate a proxy class for the Web service This proxy is used to identify the Web service and its methods You can also specify the means by which you’ll connect to and communicate with the service Fortunately, you can generate this proxy class automatically, using the Wsdl.exe tool included in the NET Framework SDK, which is a part of Visual Studio NET To build the proxy, simply run the following command: wsdl http://localhost/webservice1/service1.asmx?wsdl Of course, you’ll want to replace the URL shown here with the particular URL for the Web service you’ll be accessing on the remote host This command will create a proxy class file with the name of the Web service and with the extension cs (indicating that it’s a C# file) To specify other details about the proxy, you can use optional command-line parameters, including the following: /language: Language of the proxy class Use cs, vb, or js for C#, Visual Basic, or JScript C# is the default /protocol: Protocol to use in accessing the service Use SOAP, HTTP-GET, or HTTP-POST SOAP is the default /username: User name to use when accessing the service to get WSDL information /password: Password to use when accessing the service to get WSDL information /domain: Domain to use when accessing the service to get WSDL information /namespace: Namespace of the generated proxy class The global namespace is the default /out: Output file name for the proxy class The name of the Web service is used as the default Based on the optional parameters, you could generate a Web service proxy class that communicates with a service using the HTTP POST protocol and authenticates itself using the username bob and the password opensesame by using the following command line: wsdl /protocol:HTTP-POST /username:bob /password:opensesame http://localhost/webservice2/service1.asmx?wsdl After the proxy class has been created, you can add it to your project and call it just like any other class in the project Within the proxy class is the code required to access the Web service, call the desired methods with the needed parameters, and retrieve the necessary results Deploying Web Services After you’ve created a Web service, you might need to deploy it from your development system onto production machines Fortunately, in the NET Framework, deploying applications, including Web services, is a simple process To do so, you’ll copy the following Web service files from your development system to a directory on the production machine: The asmx files The Web service access point files The disco or vsdisco files Optional discovery files The web.config file Optional Web configuration files for the Web service The \bin directory The compiled Web service application Securing Web Services Because Web services are hosted within Internet Information Services (IIS) as ASP.NET applications, you can use ASP.NET to provide security This means that securing a Web service application requires the same thought and configuration as securing any other ASP.NET application And you can take advantage of either the ASP.NET Web configuration files or the IIS configuration settings to apply some basic security to the Web service As calling applications attempt to access your service, you might want to authenticate them to identify the user This will enable you to restrict access to just those users that you want to allow The basic techniques for authenticating your Web service users include the following: Standard IIS authentication (basic authentication, digest authentication, and Windows integrated security) Client digital certificates Internet protocol security Custom authentication We’ll look at each of these techniques in the following subsections Configuring IIS Authentication You can easily configure IIS to include any of the authentication options by following these steps: Open the Internet Information Services Manager Select the Web site and application that you want to secure Right-click on the application, and choose Properties from the shortcut menu In the Properties dialog box, click the Directory Security tab Click the Edit button in the Anonymous Access Authentication Control area This will open the Authentication Methods dialog box, shown in Figure 21-11 Figure 21-11 Managing directory security with the Authentication Methods dialog box, which is accessible from the Internet Information Services Manager Clear the Anonymous Access check box Select any of the other authentication methods you want to support, and click OK This authentication technique will require fewer programmatic changes in your Web service, but it will require some additional planning Users should all map to users on the local server, in the local domain, or in the local active directory This probably doesn’t lend itself easily to a site with an extremely large number of users The calling application will need to be responsible for passing the proper user authentication information to your service If you’re writing the calling application, you should generate a Web service proxy class, as described earlier in this chapter, in the section “Generating a Web Service Proxy.” After the proxy class has been added to your application, you can perform the following tasks: Create NetworkCredential objects to hold your credentials Add the NetworkCredential objects to a CredentialCache object Save the CredentialCache object to the Credentials property of the Web service proxy class From there, you can proceed to call the Web service as usual The following code illustrates how to implement these steps: private void btnAddNumbers_Click(object sender, System.EventArgs e) { MyWebService ws = new MyWebService(); //Establish credentials to log on to Web service CredentialCache credCache = new CredentialCache(); NetworkCredential creds = new NetworkCredential("myusername", "mypassword", "mydomain"); credCache.Add(new Uri(math.Url), "Basic", credentials); ws.Credentials = creds; //Call Web service method txtResult.Text = ws.Add(5, 2).ToString(); } Using Digital Certificates Another authentication technique that might work nicely if your Web service is to be used in a business-to-business scenario that requires relatively few client users is to issue each of the clients a digital client certificate This certificate can be used by IIS to automatically authenticate the user The user can then also be mapped to a local machine or domain user if necessary If you’re developing the calling application, you’ll want to ensure that you send the client certificate as part of your call to the Web service Assuming that you have a client certificate stored in a file named Clientcert.cer, follow these steps in your application code to use the certificate: Create an instance of the X509Certificate class Use the CreateFromCertFile method to load the client certificate Add the client certificate to the ClientCertificates property of the Web service proxy class From there, you’ll be able to call the Web service methods as usual The following example illustrates how to implement these steps: private void btnAddNumbers_Click(object sender, System.EventArgs e) { MyWebService ws = new MyWebService(); X509Certificate x509 = X509Certificate.CreateFromCertFile(@"C:\Clientcert.cer"); ws.ClientCertificates.Add(x509); txtResult.Text = ws.Add(5, 2).ToString(); } Setting Internet Protocol Security Additionally, you can restrict access to your Web services by restricting the IP addresses that can gain access to your site This is accomplished through IIS, by configuring the Directory Security tab of the Properties dialog box Click the Edit button in the IP Address And Domain Name Restrictions area to specify the particular IP addresses that will be allowed to access your site This technique lends itself to services that will be used by a small and welldefined set of calling applications This could be useful for services you’re establishing for your corporate users or for business partners, where the IP addresses or IP address ranges are known Providing Custom Authentication Another option is to provide a custom authentication scheme For example, you might require the calling application to pass in a user name and password to authenticate the user Or you might simply identify the user by placing a cookie on his or her system There are a myriad of other options, all of which will require custom coding and implementation in your Web service Many will also require that you establish a database of users Conclusion Creating a Web service involves many of the same concepts and tasks you face when building any kind of application You define the functionality and provide the logic necessary to create the service You create classes, access other components, and utilize resources to complete the tasks The code resembles the code within other applications However, by making the few modifications we’ve examined in this chapter, you can create a component that can be accessed remotely from anywhere on your local network or the Internet Your Web service won’t know anything about the calling application It will simply provide a function and return a result The Web service can be accessed using several of the standards-based protocols, such as SOAP or HTTP Likewise, building the consuming application that will make use of the Web service is similar to building any other application The consuming application can treat the Web service as though it were a local component with which the application will communicate The NET Framework allows you to establish a proxy that can be referenced within the project This accessibility creates additional concerns, such as securing the Web service for your users Using the tools provided by the operating system, IIS, and the NET Framework, you’ll be able to apply the desired level of security to your service to ensure that only those users that you authorize will gain access to your services About the Author Mickey Williams is the founder of Codev Technologies, which provides tools for Windows developers and consulting services for mission-critical systems Active with object-oriented development since the 1980s, he has written many books about Windows programming tools and frequently speaks at conferences in the United States and Europe An expert in Microsoft NET development technologies, Williams is an instructor for NET Experts, where he teaches courses on the NET Framework, XML, and SOAP He also writes the biweekly “.NET Nuts and Bolts” column for CodeGuru.com ... NET and Visual C# NET Creating Applications for the NET Platform Overview of Visual Studio NET Creating Visual C# Solutions Layout of a Typical Visual C# Program This chapter introduces you to Microsoft Visual Studio... Send comments to mspinput@microsoft.com ActiveX, Authenticode, Encarta, FrontPage, IntelliMouse, IntelliSense, JScript, Microsoft, Microsoft Press, MSDN, NET logo, OpenType, Verdana, Visual Basic, Visual C+ +, Visual C# , Visual Studio, Win32, Windows, Windows NT,... Other programming languages supplied by Microsoft that use Visual Studio NET include Visual Basic NET and Visual C+ + NET In addition, companies other than Microsoft are supplying compilers for Visual Studio NET, which will enable you to develop solutions that include