1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft visual c 2008 step by step

673 289 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 673
Dung lượng 13,89 MB

Nội dung

www.it-ebooks.info PUBLISHED BY Microsoft Press A Division of Microsoft Corporation One Microsoft Way Redmond, Washington 98052-6399 Copyright © 2008 by John Sharp 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: 2007939305 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/mspress Send comments to mspinput@microsoft.com Microsoft, Microsoft Press, MSDN, SQL Server, Excel, Intellisense, Internet Explorer, Jscript, Silverlight, Visual Basic, Visual C#, Visual Studio, Win32, Windows, Windows Server, and Windows Vista 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 7KLVERRNH[SUHVVHVWKHDXWKRU¶VYLHZVDQGRSLQLRQV7KHLQIRUPDWLRQFRQWDLQHGLQWKLVERRNLVSURYLGHG 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 Developmental and Project Editor: Lynn Finnel Editorial Production: Waypoint Press Technical Reviewer: Kurt Meyer; Technical Review services provided by Content Master, a member of CM Group, Ltd Body Part No X14-22686  www.it-ebooks.info Contents at a Glance Part I Part II 10 11 12 13 14 Part III 15 16 17 18 19 20 21 Introducing Microsoft Visual C# and Microsoft Visual Studio 2008 Welcome to C# Working with Variables, Operators, and Expressions 29 Writing Methods and Applying Scope 49 Using Decision Statements 67 Using Compound Assignment and Iteration Statements 85 Managing Errors and Exceptions 103 Understanding the C# Language Creating and Managing Classes and Objects Understanding Values and References Creating Value Types with Enumerations and Structures Using Arrays and Collections Understanding Parameter Arrays Working with Inheritance Creating Interfaces and Defining Abstract Classes Using Garbage Collection and Resource Management 123 145 167 185 207 217 239 257 Creating Components Implementing Properties to Access Fields Using Indexers Interrupting Program Flow and Handling Events Introducing Generics Enumerating Collections Querying In-Memory Data by Using Query Expressions Operator Overloading 275 295 311 333 355 371 395 iii www.it-ebooks.info iv Contents at a Glance Part IV 22 23 24 Part V 25 26 Part VI 27 28 29 30 Working with Windows Applications Introducing Windows Presentation Foundation 415 Working with Menus and Dialog Boxes 451 Performing Validation 473 Managing Data Querying Information in a Database 499 Displaying and Editing Data by Using Data Binding 529 Building Web Applications Introducing ASP.NET Understanding Web Forms Validation Controls Protecting a Web Site and Accessing Data with Web Forms Creating and Using a Web Service Index www.it-ebooks.info 559 587 597 623 645 Table of Contents Acknowledgments xvii Introduction xix Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008 Welcome to C# Beginning Programming with the Visual Studio 2008 Environment Writing Your First Program Using Namespaces 14 Creating a Graphical Application 17 Chapter Quick Reference 28 Working with Variables, Operators, and Expressions 29 Understanding Statements 29 Using Identifiers 30 Identifying Keywords 30 Using Variables 31 Naming Variables 32 Declaring Variables 32 Working with Primitive Data Types 33 Displaying Primitive Data Type Values 34 Using Arithmetic Operators 38 Operators and Types 39 Examining Arithmetic Operators 40 Controlling Precedence 43 Using Associativity to Evaluate Expressions 44 Associativity and the Assignment Operator 45 What you think of this book? We want to hear from you! Microsoft is interested in hearing your feedback so we can continually improve our books and learning resources for you To participate in a brief online survey, please visit: www.microsoft.com/learning/booksurvey v www.it-ebooks.info vi Table of Contents Incrementing and Decrementing Variables 45 Prefix and Postfix 46 Declaring Implicitly Typed Local Variables 47 Chapter Quick Reference 48 Writing Methods and Applying Scope 49 Declaring Methods 49 Specifying the Method Declaration Syntax 50 Writing return Statements 51 Calling Methods 53 Specifying the Method Call Syntax 53 Applying Scope 56 Defining Local Scope 56 Defining Class Scope 56 Overloading Methods 57 Writing Methods 58 Chapter Quick Reference 66 Using Decision Statements 67 Declaring Boolean Variables 67 Using Boolean Operators 68 Understanding Equality and Relational Operators 68 Understanding Conditional Logical Operators 69 Summarizing Operator Precedence and Associativity 70 Using if Statements to Make Decisions 71 Understanding if Statement Syntax 71 Using Blocks to Group Statements 73 Cascading if Statements 73 Using switch Statements 78 Understanding switch Statement Syntax 79 Following the switch Statement Rules 80 Chapter Quick Reference 84 Using Compound Assignment and Iteration Statements 85 Using Compound Assignment Operators 85 Writing while Statements 87 Writing for Statements 91 Understanding for Statement Scope 92 www.it-ebooks.info Table of Contents Writing Statements 93 Chapter Quick Reference 102 Managing Errors and Exceptions 103 Coping with Errors 103 Trying Code and Catching Exceptions 104 Handling an Exception 105 Using Multiple catch Handlers 106 Catching Multiple Exceptions 106 Using Checked and Unchecked Integer Arithmetic 111 Writing Checked Statements 112 Writing Checked Expressions 113 Throwing Exceptions 114 Using a finally Block 118 Chapter Quick Reference 120 Part II Understanding the C# Language Creating and Managing Classes and Objects 123 Understanding Classification 123 The Purpose of Encapsulation 124 Defining and Using a Class 124 Controlling Accessibility 126 Working with Constructors 127 Overloading Constructors 128 Understanding static Methods and Data 136 Creating a Shared Field 137 Creating a static Field by Using the const Keyword 137 Chapter Quick Reference 142 Understanding Values and References 145 Copying Value Type Variables and Classes 145 Understanding Null Values and Nullable Types 150 Using Nullable Types 151 Understanding the Properties of Nullable Types 152 Using ref and out Parameters 152 Creating ref Parameters 153 Creating out Parameters 154 www.it-ebooks.info vii viii Table of Contents How Computer Memory Is Organized 156 Using the Stack and the Heap 157 The System.Object Class 158 Boxing 159 Unboxing 159 Casting Data Safely 161 The is Operator 161 The as Operator 162 Chapter Quick Reference 164 Creating Value Types with Enumerations and Structures 167 Working with Enumerations 167 Declaring an Enumeration 167 Using an Enumeration 168 Choosing Enumeration Literal Values 169 Choosing an Enumeration’s Underlying Type 170 Working with Structures 172 Declaring a Structure 174 Understanding Structure and Class Differences 175 Declaring Structure Variables 176 Understanding Structure Initialization 177 Copying Structure Variables 179 Chapter Quick Reference 183 10 Using Arrays and Collections 185 What Is an Array? 185 Declaring Array Variables 185 Creating an Array Instance 186 Initializing Array Variables 187 Creating an Implicitly Typed Array 188 Accessing an Individual Array Element 189 Iterating Through an Array 190 Copying Arrays 191 What Are Collection Classes? 192 The ArrayList Collection Class 194 The Queue Collection Class 196 The Stack Collection Class 197 The Hashtable Collection Class 198 The SortedList Collection Class 199 www.it-ebooks.info Table of Contents Using Collection Initializers 200 Comparing Arrays and Collections 200 Using Collection Classes to Play Cards 201 Chapter 10 Quick Reference 206 11 Understanding Parameter Arrays 207 Using Array Arguments 208 Declaring a params Array 209 Using params object[ ] 211 Using a params Array 212 Chapter 11 Quick Reference 215 12 Working with Inheritance 217 What Is Inheritance? 217 Using Inheritance 218 Base Classes and Derived Classes 218 Calling Base Class Constructors 220 Assigning Classes 221 Declaring new Methods 222 Declaring Virtual Methods 224 Declaring override Methods 225 Understanding protected Access 227 Understanding Extension Methods 233 Chapter 12 Quick Reference 237 13 Creating Interfaces and Defining Abstract Classes 239 Understanding Interfaces 239 Interface Syntax 240 Interface Restrictions 241 Implementing an Interface 241 Referencing a Class Through Its Interface 243 Working with Multiple Interfaces 244 Abstract Classes 244 Abstract Methods 245 Sealed Classes 246 Sealed Methods 246 Implementing an Extensible Framework 247 Summarizing Keyword Combinations 255 Chapter 13 Quick Reference 256 www.it-ebooks.info ix x Table of Contents 14 Using Garbage Collection and Resource Management 257 The Life and Times of an Object 257 Writing Destructors 258 Why Use the Garbage Collector? 260 How Does the Garbage Collector Work? 261 Recommendations 262 Resource Management 262 Disposal Methods 263 Exception-Safe Disposal 263 The using Statement 264 Calling the Dispose Method from a Destructor 266 Making Code Exception-Safe 267 Chapter 14 Quick Reference 270 Part III 15 Creating Components Implementing Properties to Access Fields 275 Implementing Encapsulation by Using Methods 276 What Are Properties? 278 Using Properties 279 Read-Only Properties 280 Write-Only Properties 280 Property Accessibility 281 Understanding the Property Restrictions 282 Declaring Interface Properties 284 Using Properties in a Windows Application 285 Generating Automatic Properties 287 Initializing Objects by Using Properties 288 Chapter 15 Quick Reference 292 16 Using Indexers 295 What Is an Indexer? 295 An Example That Doesn’t Use Indexers 295 The Same Example Using Indexers 297 Understanding Indexer Accessors 299 Comparing Indexers and Arrays 300 Indexers in Interfaces 302 Using Indexers in a Windows Application 303 Chapter 16 Quick Reference 308 www.it-ebooks.info Chapter 30 Creating and Using a Web Service 631 Define the contracts for the ProductsService Web service Display the IProductsService.cs file in the Code and Text Editor window Change the name of the IService interface to IProductsService, as shown here in bold type: [ServiceContract] public interface IProductsService { } In the IProductsService interface, remove the definitions of the GetData and GetDataUsingDataContract methods, and replace them with the HowMuchWillItCost and GetProductInfo methods, shown in the following code Make sure you retain the OperationContract attribute for each Web method [ServiceContract] public interface IProductsService { [OperationContract] decimal HowMuchWillItCost(int productID, int howMany); [OperationContract] ProductInfo GetProductInfo(int productID); } The HowMuchWillItCost method takes a product ID and a quantity and returns a decimal value specifying the amount this quantity will cost The GetProductInfo method takes a product ID and returns a ProductInfo object containing the details of the specified product You will define the ProductInfo class in the next step Remove the CompositeType class from the IProductsService.cs file, and add the ProductInfo class, including the DataContract attribute, like this: [DataContract] public class ProductInfo { } Add the following public properties to the ProductInfo class There is one property for each of the columns in the Products table in the database Mark each property with the DataMember attribute: [DataContract] public class ProductInfo { [DataMember] public int ProductID {get; set;} [DataMember] public string ProductName {get; set;} www.it-ebooks.info 632 Part VI Building Web Applications [DataMember] public int? SupplierID {get; set;} [DataMember] public int? CategoryID {get; set;} [DataMember] public string QuantityPerUnit {get; set;} [DataMember] public decimal? UnitPrice {get; set;} [DataMember] public short? UnitsInStock {get; set;} [DataMember] public short? UnitsOnOrder {get; set;} [DataMember] public short? ReorderLevel {get; set;} [DataMember] public bool? Discontinued {get; set;} } Notice that the properties that correspond to columns that allow null values in the database are defined by using nullable types (apart from QuantityPerUnit, which is a reference type that allows null values automatically because it is a string) Also, you should ensure that all properties support read and write access The serialization mechanism used by WCF is automatic and largely transparent as long as you follow a few simple rules when defining the class In particular, serialization can be used only when the runtime transmits objects that contain public fields and properties; private members will not be serialized Also note that all properties must have both get and set accessors This is because the XML serialization process must be able to write this data back to the object after it has been transferred Additionally, the class must provide a default (with no parameters) constructor It is common to design classes used for SOAP purely as containers for transmitting data If necessary, you can define additional functional classes that act as faỗades, providing the business logic for these data structures Users and applications can gain access to the data by using these business faỗades Note You can customize the serialization mechanism using the various SOAP attribute classes of the System.Xml.Serialization namespace or define your own XML serialization mechanism by implementing the ISerializable interface of the System.Runtime.Serialization namespace www.it-ebooks.info Chapter 30 Creating and Using a Web Service 633 The next stage is to define the ProductsService class that implements the IProductsService interface The methods in this class will retrieve product information from the Northwind database, so you will start by adding an entity class and data context for retrieving this information Implement the IProductsService interface On the Website menu, click Add New Item In the Add New Item dialog box, click the LINQ to SQL Classes template, type Product dbml in the Name text box, select Visual C# in the Language drop-down list, and then click Add If you are using Visual Studio 2008 Professional Edition or Enterprise Edition, on the View menu, click Server Explorer If you are using Visual Web Developer 2008 Express Edition, on the View menu, click Database Explorer In Server Explorer (if you are using Visual Studio 2008) or Database Explorer (if you are using Visual Web Developer 2008 Express Edition), expand the data connection for the Northwind database (YourComputer\sqlexpress.Northwind.dbo or Northwind.mdf), and then expand Tables Click the Products table, and drag it onto the Object Relational Designer window On the File menu, click Save All Display the ProductsService.cs file in the Code and Text Editor window Remove the Service class from this file Add the ProductsService class to the file, and specify that it should implement the IProductsService interface, as shown here: public class ProductsService : IProductsService { } 10 Add the HowMuchWillItCost method to the Service class, as follows: public class ProductsService : IProductsService { public decimal HowMuchWillItCost(int productID, int howMany) { ProductDataContext pdc = new ProductDataContext(); decimal? cost = pdc.Products.Single( p => p.ProductID == productID).UnitPrice; decimal totalCost = 0; if (cost.HasValue) www.it-ebooks.info 634 Part VI Building Web Applications { totalCost = cost.Value * howMany; } return totalCost; } } This method connects to the database and executes a DLINQ query to retrieve the cost of the product matching the supplied product ID from the Northwind database If the cost returned is not null, the method calculates the total cost of the request and returns it; otherwise, the method returns the value Note This method performs no validation of the input parameters For example, you can specify a negative value for the howMany parameter In a production Web service, you would trap errors such as this, log them, and return an exception However, transmitting meaningful reasons for an exception back to a client application has security implications in a WCF service The details are beyond the scope of this book For more information, see Microsoft Windows Communication Foundation Step by Step 11 Add the GetProductInfo method shown below in bold type to the Service class: public class ProductsService : IProductsService public ProductInfo GetProductInfo(int productID) { ProductDataContext pdc = new ProductDataContext(); Product product = pdc.Products.Single(p => p.ProductID == productID); ProductInfo prodInfo = null; if (product != null) { prodInfo = new ProductInfo(); prodInfo.CategoryID = product.CategoryID; prodInfo.Discontinued = product.Discontinued; prodInfo.ProductID = product.ProductID; prodInfo.ProductName = product.ProductName; prodInfo.QuantityPerUnit = product.QuantityPerUnit; prodInfo.ReorderLevel = product.ReorderLevel; prodInfo.SupplierID = product.SupplierID; prodInfo.UnitPrice = product.UnitPrice; prodInfo.UnitsInStock = product.UnitsInStock; prodInfo.UnitsOnOrder = product.UnitsOnOrder; } return prodInfo; } } These statements use DLINQ to connect to the Northwind Traders database and retrieve the details for the specified product from the database Note that like the HowMuchWillItCost method, this method does not handle exceptions www.it-ebooks.info Chapter 30 Creating and Using a Web Service 635 Before you can use the Web service, you must update the configuration in the Service.svc file to refer to the ProductsService class in the ProductsService.cs file You must also modify the Web.config file to reflect the new name of the Web service Configure the Web service In Solution Explorer, double-click the Service.svc file to display it in the Code and Text Editor window Update the Service and CodeBehind attributes of the ServiceHost directive, as shown here in bold type: Note The Error List window for the Service.svc file might display the same errors as before Again, these errors should disappear when you rebuild the application, so you can safely ignore them In Solution Explorer, double-click the Web.config file In the Code and Text Editor window, locate the element This element contains the following element, specifying the endpoint binding information for the Web service implemented by this solution (You can ignore the service that implements the IMetadataExchange contract in this chapter.) Service Endpoints > WCF uses the notion of endpoints to associate a network address with a specific Web service If you are hosting a Web service by using IIS or the ASP.NET Development Server, you should leave the address property of your endpoint blank because IIS listens for incoming requests on an address specified by its own configuration information Note You can build your own custom host applications if you don’t want to use IIS or the ASP.NET Development Server In these situations, you must specify an address for the service as part of the endpoint definition For more information about endpoints and custom hosts, see Microsoft Windows Communication Foundation Step by Step www.it-ebooks.info 636 Part VI Building Web Applications In the Web.config file, change the name attribute of the Service element and the contract attribute of the endpoint element to refer to the ProductsService service and the IProductsService contract, as shown here in bold type: Service Endpoints > On the File menu, click Save All In Solution Explorer, right-click Service.svc, and then click View in Browser Internet Explorer starts and displays the following page, confirming that you have successfully created and deployed the Web service and providing helpful information describing how to create a simple client application that can access the Web service Note If you click the link shown on the Web page (http://localhost:4500/ NorthwindServices/Service.svc?wsdl), Internet Explorer displays a page containing the WSDL description of the Web service This is a long and complicated piece of XML, but Visual Studio 2008 can take the information in this description and use it to generate a class that a client application can use to communicate with the Web service Close Internet Explorer, and return to Visual Studio 2008 www.it-ebooks.info Chapter 30 Creating and Using a Web Service 637 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—SOAP, HTTP, and XML are well understood (in theory anyway) and are the subjects of several standards committees Any client application that “talks” SOAP can communicate with a Web service 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 performs a number of steps It must the following: 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 You saw how to this by using Internet Explorer in the preceding exercise Parse the WSDL document, convert each operation to a Web request, and serialize each parameter into the format described by the WSDL document Submit the request, along with the serialized data, to the URL by using HTTP Wait for the Web service to reply Using the formats specified by the WSDL document, deserialize the data returned by the Web service into meaningful values that your application can then process This is a lot of work just to invoke a method, and it is potentially error-prone 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 As mentioned earlier, many vendors, including Microsoft, supply tools that can generate a proxy class 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 to SOAP requests and sends them to the Web service The proxy waits for the reply, deserializes the data, and then passes it back to the client just like the return from any simple method call This is the approach you will take in the exercises in this section www.it-ebooks.info 638 Part VI Building Web Applications Consuming the ProductsService 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 GetProductInfo method Open a Web service client application Start another instance of Visual Studio 2008 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 if you are running Visual Studio 2008 and not Visual Web Developer 2008 Express Edition 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 of Visual Studio 2008 Important If you have been using Visual Web Developer 2008 Express Edition for the exercises in this part of the book, start Visual C# 2008 Express Edition rather than a second instance of Visual Web Developer 2008 Express Edition (leave Visual Web Developer 2008 Express Edition running) In the second instance of Microsoft Visual Studio 2008, open the ProductClient solution in the \Microsoft Press\Visual CSharp Step By Step\Chapter 30\ProductClient folder in your Documents folder In Solution Explorer, double-click the file ProductClient.xaml to display the form in the Design View window The form looks like this: www.it-ebooks.info Chapter 30 Creating and Using a Web Service 639 The form enables the user to specify a product ID and retrieve the details of the product from the Northwind database The user can also provide a quantity and retrieve a price for buying that quantity of the product Currently, the buttons on the form nothing In the following steps, you will add the necessary code to invoke the methods from the ProductsService Web service to obtain the data and then display it Add code to call the Web service in the client application On the Project menu, click Add Service Reference The Add Service Reference dialog box opens In this dialog box, you can browse for Web services and examine the Web methods that they provide In the Address text box, type http://localhost:4500/NorthwindServices/Service.svc, and then click Go The ProductsService service appears in the Services box Expand the ProductsService service, and then click the IProductsService interface that appears In the Operations list box, verify that the two operations, GetProductInfo and HowMuchWillItCost, appear, as shown in the following image Change the value in the Namespace text box to NorthwindServices, and then click OK A new folder called Service References appears in Solution Explorer This folder contains an item called NorthwindServices Click the Show All Files button on the Solution Explorer toolbar Expand the NorthwindServices folder, and then expand the Reference.svcmap folder Double-click the Reference.cs file and examine its contents in the Code and Text Editor window www.it-ebooks.info 640 Part VI Building Web Applications This file contains several classes and interfaces, including a class called ProductsServiceClient in a namespace called ProductClient.NorthwindServices The ProductsServiceClient is the proxy class generated by Visual Studio 2008 from the WSDL description of the ProductsService Web service It contains a number of constructors, as well as methods called HowMuchWillItCost and GetProductInfo The client application can instantiate the ProductsServiceClient class and call these methods When this happens, these methods invoke code that packages up the information supplied as parameters into a SOAP message that they transmit to the Web service When the Web service replies, the information returned is unpacked from the SOAP response and passed back to the client application In this way, the client application can call a method in a Web service in exactly the same way as it would call a local method Display the ProductClient.xaml form in the Design View window Double-click the Get Product button to generate the getProduct_Click event handler method for this button In the Code and Text Editor window, add the following using statement to the list at the top of the ProductClient.xaml.cs file: using ProductClient.NorthwindServices; In the getProduct_Click method, create the variable shown here in bold type: private void getProduct_Click(object sender, RoutedEventArgs e) { ProductsServiceClient proxy = new ProductsServiceClient(); } This statement creates an instance of the ProductsServiceClient class that your code will use to call the GetProductInfo Web method Add the code shown here in bold type to extract the product ID entered by the user on the form, execute the GetProductInfo Web method by using the proxy object, and then display the details of the product in the labels on the form private void getProduct_Click(object sender, RoutedEventArgs e) { ProductsServiceClient proxy = new ProductsServiceClient(); try { int prodID = Int32.Parse(this.productID.Text); ProductInfo product = proxy.GetProductInfo(prodID); this.productName.Content = product.ProductName; this.supplierID.Content = product.SupplierID; this.categoryID.Content = product.CategoryID; this.quantityPerUnit.Content = product.QuantityPerUnit; this.unitPrice.Content = String.Format(“{0:C}”, product.UnitPrice); this.unitsInStock.Content = product.UnitsInStock; this.unitsOnOrder.Content = product.UnitsOnOrder; this.reorderLevel.Content = product.ReorderLevel; this.discontinued.IsChecked = product.Discontinued; } www.it-ebooks.info Chapter 30 Creating and Using a Web Service 641 catch (Exception ex) { MessageBox.Show(“Error fetching product details: “ + ex.Message, “Error”, MessageBoxButton.OK, MessageBoxImage.Error); } finally { if (proxy.State == System.ServiceModel.CommunicationState.Faulted) proxy.Abort(); else proxy.Close(); } } You are probably aware of how unpredictable networks are, and this applies doubly to the Internet The try/catch block ensures that the client application catches any network exceptions that might occur It is also possible that the user might not enter a valid integer into the ProductID text box on the form The try/catch block also handles this exception The finally block examines the state of the proxy object If an exception occurred in the Web service (which could be caused by the user supplying a nonexistent product ID, for example), the proxy will be in the Faulted state In this case, the finally block calls the Abort method of the proxy to acknowledge the exception and close the connection; otherwise, it calls the Close method The Abort and Close methods both close the communications channel with the Web service and release the resources associated with this instance of the ProductsServiceClient object 10 Display the ProductClient.xaml form in the Design View window again Double-click the Calculate Cost button to generate the calcCost_Click event handler method for this button 11 In the calcCost_Click method, add the code shown here in bold type: private void calcCost_Click(object sender, RoutedEventArgs e) { ProductsServiceClient proxy = new ProductsServiceClient(); try { int prodID = Int32.Parse(this.productID.Text); int number = Int32.Parse(this.howMany.Text); decimal cost = proxy.HowMuchWillItCost(prodID, number); this.totalCost.Content = String.Format(“{0:C}”, cost); } catch (Exception ex) { MessageBox.Show(“Error obtaining cost: “ + ex.Message, “Error”, MessageBoxButton.OK, MessageBoxImage.Error); } finally www.it-ebooks.info 642 Part VI Building Web Applications { if (proxy.State == System.ServiceModel.CommunicationState.Faulted) proxy.Abort(); else proxy.Close(); } } This code follows a similar pattern to the getProduct_Click method It creates an instance of the ProductsServiceClient class and calls the HowMuchWillItCost method using this instance, passing the product ID and the quantity required as parameters The return value is displayed on the form The exception handler traps any errors, and the finally block ensures that the network connection is closed when the method finishes Test the application Build and run the project When the Product Details form appears, type in the Product ID text box, and then click Get Product After a short delay while the client instantiates the proxy and builds a SOAP request containing the product ID, the proxy sends the request to the Web service The Web service deserializes the SOAP request to extract the product ID, reads the database, creates a Product object, serializes it as XML, and then sends it back to the proxy The proxy deserializes the XML data and creates a ProductInfo object and then passes this object to your code in the getButton_Click method The details for Aniseed Syrup then appear in the form as shown in the following graphic: Tip If you get an exception with the message “Could not connect to http://localhost:4500/ NorthwindServices/Service.svc TCP error code 10061: No connection could be made because the target machine actively refused it,” the ASP.NET Development Server has probably stopped running (It shuts down if it is inactive for a time.) To restart it, switch to the Visual Studio 2008 instance for the ProductsService Web service, right-click Service.svc in Solution Explorer, and then click View in Browser Close Internet Explorer when it appears www.it-ebooks.info Chapter 30 Creating and Using a Web Service 643 Type 24 in the Product ID text box, and then click Get Product For reasons that are outside the scope of this book to explain, you will probably find that the details are displayed more quickly this time Type 10 in the How Many text box, and then click Calculate Cost Verify that the value displayed in the Total Cost field on the form is 10 times the value shown in the Unit Price field Experiment by typing the IDs of other products Notice that if you enter an ID for a product that does not exist, the Web service returns an exception As described earlier, the error message returned does not contain any information that could be useful to an attacker, although it does describe how you can enable meaningful error messages and log exceptions When you have finished, close the form and return to Visual Studio 2008 Congratulations You have now built your first WCF service together with a client application that calls its methods You have also completed all the exercises in this book You should now be thoroughly conversant with the C# language and understand how to use Visual Studio 2008 to build professional applications However, this is not the end of the story You have jumped the first hurdle, but the best C# programmers learn from continued experience, and you can gain this experience only by building C# applications As you so, you will discover new ways to use the C# language and the many features available in Visual Studio 2008 that I have not had space to cover in this book Also, remember that C# is an evolving language Back in 2001, when we wrote the first edition of this book, C# introduced the syntax and semantics necessary for you to build applications that made use of NET Framework 1.0 Some enhancements were added to Visual Studio and NET Framework 1.1 in 2003, and then in 2005, C# 2.0 emerged with support for generics and NET Framework 2.0 As you have seen in this book, C# 3.0, the latest release of the language aligned with Visual Studio 2008 and NET Framework 3.5, has added numerous features such as anonymous types, lambda expressions, and most significantly, LINQ What will the next version of C# bring? Watch this space! www.it-ebooks.info 644 Part VI Building Web Applications Chapter 30 Quick Reference To Do this Create a Web service Use the WCF Service template Define a service contract that specifies the Web methods exposed by the Web service by creating an interface with the ServiceContract attribute Tag each method with the OperationContract attribute Create a class that implements this interface Display the description of a Web service Right-click the svc file in Solution Explorer, and click View in Browser Internet Explorer runs, moves to the Web service URL, and displays a page describing how to create a client application that can access the Web service Click the WSDL link to display the WSDL description of the Web service Pass complex data as Web method parameters and return values Define a class to hold the data and tag it with the DataContract attribute 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 service reference to a client application and create a proxy class On the Project menu, click Add Service Reference Type the URL of the Web service in the Address text box at the top of the dialog box, and then click Go Specify the namespace for the proxy class, and then click OK Invoke a Web method Create an instance of the proxy class Call the Web method using the proxy class www.it-ebooks.info John Sharp John Sharp is a Principal Technologist at Content Master (www.contentmaster.com), part of CM Group, a technical authoring company in the United Kingdom He researches and develops technical content for training courses, seminars, and white papers John is deeply involved with Microsoft NET Framework application development and interoperability He has written papers and courses, built tutorials, and delivered conference presentations covering distributed systems and Web services, application migration and interoperability between Microsoft Windows/.NET Framework and UNIX/Linux/Java, as well as development using the C# and J# languages John has also authored Microsoft Windows Communication Foundation Step by Step and Microsoft Visual J# Core Reference, both published by Microsoft Press www.it-ebooks.info ... addresses www.it-ebooks.info Microsoft Visual C# 2008 Step by Step Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2008 In this part: Chapter Welcome to C# ... in which Windows Vista manages security Microsoft Visual Studio 2008 Standard Edition, Visual Studio 2008 Enterprise Edition, or Microsoft Visual C# 2008 Express Edition and Microsoft Visual. .. made to ensure the accuracy of this book and the contents of the companion CD As corrections or changes are collected, they will be added to a Microsoft Knowledge Base article Microsoft Press provides

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