1. Trang chủ
  2. » Khoa Học Tự Nhiên

Ms visual c sharp 2005 step by step (2005)

971 143 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 971
Dung lượng 8,77 MB

Nội dung

PUBLISHED BY Microsoft Press A Division of Microsoft Corporation One Microsoft Way Redmond, Washington 98052-6399 Copyright © 2006 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 Control Number 2005933123 Printed and bound in the United States of America QWT Distributed in Canada by H.B Fenn and Company Ltd 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/learning/ Send comments to mspinput@microsoft.com Microsoft, ActiveX, Excel, IntelliSense, JScript, Microsoft Press, MSDN, Visual Basic, Visual C#, Visual J#, Visual Studio, Windows, and Windows Server 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, email address, logo, person, place, or event is intended or should be inferred This book expresses the author's views and opinions The information contained in this book is provided without any express, statutory, or implied warranties Neither the authors, Microsoft Corporation, nor its resellers, or distributors will be held liable for any damages caused or alleged to be caused either directly or indirectly by this book Acquisitions Editor: Ben Ryan Project Editor: Lynn Finnel Technical Editors: Steve Lambert and Jon Kenoyer Editorial and Production: Online Training Solutions, Inc Body Part No X11-44955 Companion Content This title includes references to electronic content, such as sample files, sample code, beta software, tools, and other content This content is provided as an additional learning tool to accompany the text Although the references to this content might mention a CD or CD-ROM where these files are available, you can access selected portions of this content online by going to http://www.microsoft.com/mspress/products/mell To view the companion content for a title at this Web site, type in the product ISBN (International Standard Book Number) of the title in the text box and click Go The ISBN for this title is listed below and can also be found on the LOC (Library of Congress) page listed in the Table of Contents ISBN: 0-7356-2129-2 Introduction Microsoft Visual C# is a powerful but simple language aimed primarily at developers creating applications by using the Microsoft NET Framework It inherits many of the best features of C++ and Microsoft Visual Basic, but few of the inconsistencies and anachronisms, resulting in a cleaner and more logical language The advent of C# 2.0 has seen several important new features added to the language, including Generics, Iterators, and anonymous methods The development environment provided by Microsoft Visual Studio 2005 makes these powerful features easy to use, and the many new wizards and enhancements included in Visual Studio 2005 can greatly improve your productivity as a developer The aim of this book is to teach you the fundamentals of programming with C# by using Visual Studio 2005 and the NET Framework You will learn the features of the C# language, and then use them to build applications running on the Microsoft Windows operating system By the time you complete this book, you will have a thorough understanding of C# and will have used it to build Windows Forms applications, access Microsoft SQL Server databases, develop ASP.NET Web applications, and build and consume a Web service Finding Your Best Starting Point in This Book This book is designed to help you build skills in a number of essential areas You can use this book if you are new to programming or if you are switching from another programming language such as C, C++, Sun Microsystems Java, or Visual Basic Use the following table to find your best starting point If you are New to objectoriented programming Follow these steps Install the practice files as described in the next section, “Installing and Using the Practice Files.” Work through the chapters in Parts I, II, and III sequentially Complete Parts IV, V, and VI as your level of experience and interest dictates New to C# Install the practice files as described in the next section, “Installing and Using the Practice Files.” Skim the first five chapters to get an overview of C# and Visual Studio 2005, and then concentrate on Chapters 6 through 19 Complete Parts IV, V, and VI as your level of experience and interest dictates Migrating from C, C++, or Java Install the practice files as described in the next section, “Installing and Using the Practice Files.” Skim the first seven chapters to get an overview of C# and Visual Studio 2005, and then concentrate on Chapters 8 through 19 For information about building Windows applications and using a database, read Parts IV and V For information about building Web applications and Web services, read Part VI Switching from Visual Basic 6 Install the practice files as described in the next section, “Installing and Using the Practice Files.” Work through the chapters in Parts I, II, and III sequentially For information about building Windows applications, read Part IV For information about accessing a database, read Part V For information about creating Web applications and Web services, read Part VI Read the Quick Reference sections at the end of the chapters for information about specific C# and Visual Studio 2005 constructs Referencing the book after working through the exercises Use the index or the Table of Contents to find information about particular subjects Read the Quick Reference sections at the end of each chapter to find a brief review of the syntax and techniques presented in the chapter Conventions and Features in This Book This book presents information by using conventions designed to make the information readable and easy to follow Before you start the book, read the following list, which explains conventions you'll see throughout the book and points out helpful features in the book that you might want to use Conventions Each exercise is a series of tasks Each task is presented as a series of numbered steps (1, 2, and so on) A round bullet (•) indicates an exercise that has only one step Notes labeled “tip” provide additional information or alternative methods for completing a step successfully Notes labeled “important” alert you to information you need to check before continuing A plus sign (+) between two key names means that you must press those keys at the same time For example, “Press Alt+Tab” means that you hold down the Alt key while you press the Tab key Other Features Sidebars throughout the book provide more in-depth information about the exercise The sidebars might contain background information, design tips, or features related to the information being discussed Each chapter ends with a Quick Reference section The Quick Reference section contains quick reminders of how to perform the tasks you learned in the chapter Online Companion Content The online companion content page has content and links related to this book http://www.microsoft.com/mspress/companion/0-7356-2129-2/ Technology Updates As technologies related to this book are updated, links to additional information will be added to the Microsoft Press Technology Updates Web page Visit this page periodically for updates on Visual Studio 2005 and other technologies http://www.microsoft.com/mspress/updates/ NOTE Practice files for this book are on the companion CD System Requirements You'll need the following hardware and software to complete the exercises in this book: Microsoft Windows XP Professional Edition with Service Pack 2, Microsoft Windows Server 2003 with Service Pack 1, or Windows 2000 with Service Pack 4 (Microsoft Windows 2000 Datacenter Server is not supported.) Microsoft Visual Studio 2005 Standard or Professional Edition, including SQL Server 2005 Express 766 MHz Pentium or compatible processor (1.5 GHz Pentium recommended) 256 MB RAM (512 MB or more recommended) Video monitor (800 × 600 or higher resolution) with at least 256 colors (1024 × 768 High Color 16-bit recommended) CD-ROM or DVD-ROM drive Microsoft Mouse or compatible pointing device You will also need to have Administrator access to your computer to configure SQL Server 2005 Express Edition and to modify the Windows Registry in Chapter 28, “Creating and Using a Web Service.” Prerelease Software This book was reviewed and tested against the August 2005 Community Technical Preview (CTP) of Visual Studio 2005 The August CTP was the last preview before the final release of Visual Studio 2005 This book is expected to be fully compatible with the final release of Visual Studio 2005 If there are any changes or corrections for this book, they will be collected and added to a Microsoft Knowledge Base article See the “Support for this Book” section in this Introduction for more information Close the Internet Explorer windows Web Services, Clients, and Proxies You have seen that a Web service uses SOAP to provide a mechanism for receiving requests and sending back results SOAP uses XML to format the data being transmitted, which rides on top of the HTTP protocol used by Web servers and browsers This is what makes Web services so powerful— HTTP and XML are well understood (in theory anyway) and are the subjects of several standards committees SOAP itself is going through the standardization process and has been adopted by most companies that want to make their services available over the Web A client that “talks” SOAP can communicate with a Web service The client and the Web service can be implemented in totally different languages, running on otherwise incompatible systems For example, a Microsoft Visual Basic client running on a handheld device can communicate with a Web service being hosted on an IBM 390 mainframe running UNIX So how does a client “talk” SOAP? There are two ways: the difficult way and the easy way Talking SOAP: The Difficult Way In the difficult way, the client application must perform a number of steps: Determine the URL of the Web service running the Web method Perform a Web Services Description Language (WSDL) inquiry using the URL to obtain a description of the Web methods available, the parameters used, and the values returned This is an XML document (You saw an example in the previous chapter.) Convert each Web method call into the appropriate URL and serialize each parameter into the format described by the WSDL document Submit the request, along with the serialized data, to the URL using HTTP Wait for the Web service to reply Using the formats specified by the WSDL document, de-serialize the data returned by the Web service into meaningful values that your application can then process This is a lot of work to just invoke a method, and it is potentially errorprone Talking SOAP: The Easy Way The bad news is that the easy way to use SOAP is not much different from the difficult way The good news is that the process can be automated because it is largely mechanical Many vendors supply tools that can generate proxy classes based on a WSDL description The proxy hides the complexity of using SOAP and exposes a simple programmatic interface based on the methods published by the Web service The client application calls Web methods by invoking methods with the same name in the proxy The proxy converts these local method calls into SOAP requests and sends them to the Web service The proxy waits for the reply, de-serializes the data, and then passes it back to the client just like the return from any simple method call Consuming the ProductService Web Service You have created a Web service call that exposes two Web methods: GetProductInfo to return the details of a specified product, and HowMuchWillItCost to determine the cost of buying n items of product x from Northwind Traders In the following exercises, you will use this Web service and create an application that consumes these methods You'll start with the Get- ProductInfo method Create a Web service client application Start another instance of Visual Studio 2005 This is important The ASP.NET Development server stops if you close the NorthwindServices Web service project, meaning that you won't be able to access it from the client (an alternative approach you can use is to create the client application as a project in the same solution as the Web service) When you host a Web service in a production environment by using IIS, this problem does not arise because IIS runs independently from Visual Studio 2005 In the second instance of Microsoft Visual Studio 2005, create a new project using the Windows Application template Name the project ProductInfo and save it in the \Microsoft Press\Visual CSharp Step By Step\Chapter 28 folder in your My Documents folder Change the filename of the Form1.cs file to ProductForm.cs Change the size of the form to 392, 400 Set its Text property to Product Details Add 10 labels to the form, evenly spaced down the left side From top to bottom, set the Text property of each label using the following values: Product Name, Product ID, Supplier ID, Category ID, Quantity Per Unit, Unit Price, Units In Stock, Units On Order, Reorder Level, and Discontinued Add nine text boxes to the form adjacent to the first nine labels Clear the Text property for each text box Set the Name property of each text box from top to bottom using the following values: productName, productID, supplierID, categoryID, quantityPerUnit, unitPrice, unitsInStock, unitsOnOrder, and reorderLevel Add a check box to the form next to the Discontinued label and below the reorderLevel text box Set its Name property to discontinued, and then clear its Text property Add a button to the form, to the right of the productName text box Change the name of the button to getProduct, and then set its Text property to Get Product The completed form should look like the following graphic: Add a reference to the Web service On the Project menu, click Add Web Reference The Add Web Reference dialog box opens This dialog box allows you to browse for Web services and examine the WSDL descriptions Type the URL of the NorthwindServices Web service in the Address text box at the top of the dialog box: http://localhost:4500/NorthwindServices/Service.asmx Click Go TIP If the Web service is hosted by IIS on your computer, you can click the “Web services on the local machine” hyperlink in the left pane of the dialog box rather than typing the address in manually In our case, the Web service is hosted by the ASP.NET Development server and won't appear if you click this hyperlink The Web service test page displaying the GetProductInfo and HowMuchWillItCost methods appears Change the value in the Web reference name text box to NorthwindServices, as shown in the following graphic: Click Add Reference Look at the Solution Explorer A new folder called Web References is added that contains an item called NorthwindServices Click the NorthwindServices Web reference and examine its properties in the Properties window You will notice the Web Reference URL property, which contains the URL of the Web service Execute a Web method Display ProductForm.cs in the Code and Text Editor window Add the following using statement to the list at the top of the file: using ProductInfo.NorthwindServices; When you add a Web reference to a project, the proxy generated by the Web service is placed in a namespace that is named after the Web service reference—in this case, NorthwindServices Create an event method for the Click event of the getProduct button called getProduct_Click In the getProduct_Click method, create the following variable: Service northwindService = new Service(); Service is the proxy class that provides access to the Web service (the proxy will always be named after the Web service) It resides in the NorthwindServices namespace To use the Web service, you must create an instance of the proxy, which is what this code does Add code to execute the GetProductInfo Web method to the getProduct_Click method You are probably aware of how unpredictable networks are, and this applies doubly to the Internet Create a try/catch block below the statement that creates the northwind Service variable Remember that the Web service will also throw an exception if you try to access a non-existent product try { // Code goes here in the next steps } catch (Exception ex) { MessageBox.Show("Error fetching product details ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } Add the following statement to the try block: Product prod = northwindService.GetProductInfo(prod The proxy object (northwindService) makes the call to the GetProductInfo Web method look like an ordinary local method call The information returned by the GetProductInfo method is assembled into an instance of the Product class The WSDL description of the Web service provides enough information to define the structure of this class, and you can use it in your client application as shown here Add the following statements, which extract the details from the Product object and display them on the form, to the try block: productID.Text = prod.ProductID.ToString(); supplierID.Text = prod.SupplierID.ToString(); categoryID.Text = prod.CategoryID.ToString(); quantityPerUnit.Text = prod.QuantityPerUnit; unitPrice.Text = prod.UnitPrice.ToString(); unitsInStock.Text = prod.UnitsInStock.ToString(); unitsOnOrder.Text = prod.UnitsOnOrder.ToString(); reorderLevel.Text = prod.ReorderLevel.ToString(); discontinued.Checked = prod.Discontinued; Test the application Build and run the project When the Product Details form appears, type Aniseed Syrup in the Product Name text box and click Get Product After a short delay while the client instantiates the proxy, the proxy marshals the parameter and sends the request to the Web service The Web service reads the database, creates a Product object, marshals it as XML, and then sends it back to the proxy The proxy unmarshals the XML data and creates a copy of the Product object, and then passes this copy to your code in the getButtonClick method The details for Aniseed Syrup then appear in the form as shown by the following graphic: Type Tofu in the Product Name text box, and then click Get Product You will probably find that the details are displayed more quickly this time Type Sticky Toffee in the Product Name text box, and then click Get once more Because this product does not exist, the Web service will throw an exception that is passed back to your application If you look closely, you will see the “No such product Sticky Toffee” message Click OK to acknowledge the error Close the Product Details form and return to the Visual Studio 2005 programming environment Web Services, Anonymous Access, and Authentication When you create a Web service client using Visual Studio 2005, the client application executes Web services using anonymous access by default This might be fine when building and testing Web services in a development environment using the ASP.NET Development Web server, but in a production environment using IIS you might want to restrict access to authenticated clients only You can configure the authentication mechanism for a Web service hosted by IIS using the Internet Information Services console, available from the Administrative Tools folder in the Control Panel If you expand the Default Web Site node, select your Web service, and click Properties from the Action menu, you can change the Directory Security settings by clicking the Edit button under Anonymous Access And Authentication Control Make sure the Anonymous Access box is checked to permit unauthenticated access—the accepted convention is to use the local IUSR account for such access; the Web service will execute using this identity, which must be granted access to any resources used by the Web service, such as a SQL Server database The alternative to using anonymous access is using authenticated access If you clear the Anonymous access check box and select one or more of the authenticated mechanisms (Digest, Basic, Integrated Windows), you can restrict access to clients that supply a valid user name and password For more information on the differences between the authenticated access modes, consult the Internet Information Services documentation (click Help in the Authentication Methods dialog box) You can supply the information needed to authenticate the client application by setting the Credentials property of the Web service proxy at run time This property is a NetworkCredential object (the NetworkCredential class is located in the System.Net namespace) The following code creates a NetworkCredential object for the user “John,” with the password “JohnsPassword” and sets the Credentials property of the productService Web service proxy: using System.Net; … private void getProduct_Click( ) { Service northwindService = new Service(); try { NetworkCredential credentials = new NetworkCredential("John", "JohnsPassw productService.Credentials = credentials; Product prod = productService.GetProductInfo( … } … } The user name and password must be valid for the Windows domain (a different Windows domain can be specified as an optional third parameter to the NetworkCredential constructor), and the specified account must be granted access to the various resources used by the Web service if it is to function correctly Chapter 28 Quick Reference To Do this Create a Web service Use the ASP.NET Web Service template Use the WebService attribute to specify the namespace used to uniquely identify the Web service to the outside world Tag each method you want to expose with the WebMethod attribute Test a Web service Right-click the asmx file in the Solution Explorer and click View in Browser Internet Explorer runs, moves to the Web service URL, and displays the test page Click the link corresponding to the Web method you wish to run On the Web method test page, enter values for the parameters and click Invoke The Web method will run and generate a SOAP response that will be displayed in Internet Explorer Pass complex data as Web method parameters and return values Define a class to hold the data Ensure that each item of data is accessible either as a public field or through a public property that provides get and set access Ensure that the class has a default constructor (which might be empty) Add a Web reference to an application and create a proxy class On the Project menu, click Add Web Reference Either type the URL of the Web service in the Address text box at the top of the dialog box, or click the “Web References on local Web server” link and locate the Web service Click Add Reference to create the Web service proxy Invoke a Web Create an instance of the proxy class; it will reside in a method namespace named after the Web server hosting the Web synchronously service unless you changed it when adding the Web reference Run the Web method using the proxy class About the Author John Sharp is a Principal Technologist at Content Master, part of CM Group Ltd, a technical authoring and consulting company in the United Kingdom There he researches and develops technical content for technical training courses, seminars, workshops, guidance, books, and white papers Throughout his development career, John has been active in training, developing, and delivering courses, and he currently writes full time He writes on subjects ranging from UNIX Systems Programming to SQL Server Administration to Enterprise Java Development He has used his experience to create a broad range of training materials covering many subjects John is deeply involved with NET development, writing courses, building tutorials, and delivering conference presentations covering Visual C# NET development and ASP.NET He lives in Tetbury, Gloucestershire in the United Kingdom ... Create a C# console application Use namespaces Create a C# Windows Forms application Microsoft Visual C# is Microsoft's powerful, component-oriented language C# plays an important role in the architecture of the Microsoft... but that is beyond the scope of this book 4 In the Templates pane, click the Console Application icon In the Location field, type C: Documents and SettingsYourNameMy DocumentsMicrosoft Press Visual CSharp Step by Step Chapter 1... Introducing Microsoft Visual C# and Microsoft Visual Studio 2005 Chapter 1 Welcome to C# After completing this chapter, you will be able to: Use the Visual Studio 2005 programming environment Create a C# console application

Ngày đăng: 25/03/2019, 16:40

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN