Tài liệu Module 5: Implementing a Simple Web Service pdf

78 375 0
Tài liệu Module 5: Implementing a Simple Web Service pdf

Đ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

Module 5: Implementing a Simple Web Service Contents Overview Creating a Web Service Project Implementing Web Service Methods 13 Managing State in an ASP.NET Web Service 33 Debugging Web Services 41 Lab 5: Implementing a Simple Web Service 59 Review 73 Information in this document, including URL and other Internet Web site references, is subject to change without notice Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, places or events is intended or should be inferred Complying with all applicable copyright laws is the responsibility of the user Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property  2001 Microsoft Corporation All rights reserved Microsoft, MS-DOS, Windows, Windows NT, Active Directory, Authenticode, Biztalk, Intellisense, Jscript, MSDN, PowerPoint, Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A and/or other countries The names of actual companies and products mentioned herein may be the trademarks of their respective owners Module 5: Implementing a Simple Web Service Instructor Notes Presentation: 150 Minutes Lab: 75 Minutes This module provides students with the skills that are required to implement a Web Service using Microsoft® Visual Studio® NET and debug it They will also modify the solution to Lab 4, “Implementing a Web Service Consumer Using Visual Studio NET,” in Course 2524A, Developing XML Web Services Using Microsoft Visual C# NET Beta 2, to communicate with the Web Service they will create in the lab exercises for this module After completing this module, students will be able to: ! Create a Web Service project ! Implement Web Service methods, expose them, and control their behavior ! Manage state in a Microsoft ASP.NET-based Web Service ! Debug Web Services Materials and Preparation This section provides the materials and preparation tasks that you need to teach this module Required Materials To teach this module, you need the Microsoft PowerPoint® file 2524A_05.ppt Preparation Tasks To prepare for this module: ! Read all of the materials for this module ! Try the walkthroughs and demonstrations in this module ! Complete the lab iii iv Module 5: Implementing a Simple Web Service Module Strategy Use the following strategy to present this module: ! Creating a Web Service Project This section provides an overview of the mechanics of implementing a simple Web Service using the ASP.NET Web Service project template It also explains the purpose of each of the files generated for the default Web Service project ! Implementing Web Service Methods This section is intended to help students understand: • How the various properties of the WebMethod attribute affect a Web Service method • How to implement Web Service methods with parameter lists of varying complexity Do not get drawn into a discussion of the tradeoffs between the various options for representing parameter lists This discussion should be deferred until Module 8, “Designing Web Services,” in Course 2524A, Developing XML Web Services Using Microsoft Visual C# NET Beta Be sure to practice the Component Designer and XML Designer demonstrations ! Managing State in an ASP.NET Web Service This section discusses application and session state management in Web Services It covers the mechanics of using application and session state, and not the advantages and disadvantages of using these state services For students who are familiar with ASP programming, emphasize the similarity in the mechanics of using the application and session state services Once again, defer any in-depth discussion of issues relating to performance or scaling to Module 8, “Designing Web Services,” in Course 2524A, Developing XML Web Services Using Microsoft Visual C# NET Beta ! Debugging Web Services This topic is intended to familiarize students with various tools and techniques available for debugging Web Services The simplest debugging tools covered are the Trace and Debug classes The use of Simple Object Access Protocol (SOAP) extensions to provide more sophisticated tracing is also covered Do not explain all the details of the TraceExtension implementation Just cover the concepts of hooking the serialization process and the mechanics of associating a SOAP extension with a method through a custom attribute The last topic of this section provides a brief overview of application- and page-level tracing using trace.axd, using an event log, and performance counters Focus on the mechanics and not about the issues related to performance, scaling, and deployment Module 5: Implementing a Simple Web Service Overview Topic Objective To provide an overview of the module topics and objectives ! Creating a Web Service Project Lead-in ! Implementing Web Service Methods ! Managing State in an ASP.NET Web Service ! Debugging Web Services Web Services can be implemented in several ways using any language *****************************ILLEGAL FOR NON-TRAINER USE****************************** Web Services can be implemented in several ways using any programming language For example, you can implement a Web Service using Microsoft® Visual C#™, Microsoft Visual Basic®, or Managed Extensions to Microsoft Visual C++® You can also implement a Web Service using the Microsoft Active Template Library (ATL) Server, and deploy it as dynamic-link libraries (DLLs) In general, Course 2524A, Developing XML Web Services Using Microsoft Visual C# NET Beta 2, explains how to implement Web Services using ASP.NET and Visual C#, and in particular, this module teaches you how to implement a simple Web Service using these technologies To implement Web Services you must understand the components of a Microsoft ASP.NET Web Service project and how to expose C# class methods as Web Service operations You must also understand how state can be managed in ASP.NET Web Services and some of the issues related to state management and Web Services Debugging distributed applications is not easy, and Web Services are not any different in that respect Therefore, you need to be familiar with some of the techniques that you can use to debug Web Services After completing this module, you will be able to: ! Create a Web Service project ! Implement Web Service methods, expose them, and control their behavior ! Manage state in an ASP.NET-based Web Service ! Debug Web Services Module 5: Implementing a Simple Web Service " Creating a Web Service Project Topic Objective To introduce the topics in this section Lead-in In this section, you will look at the first step in implementing a Web Service, which is creating the base project ! Demonstration: Creating a Web Service Project ! Examining the Parts of a Web Service Project *****************************ILLEGAL FOR NON-TRAINER USE****************************** In this section, you will look at the first step in implementing a Web Service, which is creating the base project You will also examine the results of generating a project using the Web Service project template Module 5: Implementing a Simple Web Service Demonstration: Creating a Web Service Project Topic Objective To demonstrate how to create a Web Service project in Visual Studio NET Lead-in In this demonstration, you will see how to create a Visual C#-based ASP.NET Web Service project in Visual Studio NET *****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In Visual Studio NET, create a Visual C#-based ASP.NET Web Service project Point out the project location The next slide could be presented as the rest of this demonstration Tell the students not to try out the steps while you are performing the demonstration, because they will get a chance to this activity in the lab for this module In this demonstration, you will see how to create a Visual C#-based ASP.NET Web Service project in Visual Studio NET Module 5: Implementing a Simple Web Service Examining the Parts of a Web Service Project Topic Objective To explain the references and asmx file of a Web Service project ! References # # ASP.NET Web Services are ASP.NET applications and therefore there are many elements that are common between them System.Data namespace # Lead-in System namespace System.Web namespace # # ! System.Web.Services namespace System.XML namespace The asmx File # Service Help page # Service Method Help page # Service Description Page *****************************ILLEGAL FOR NON-TRAINER USE****************************** ASP.NET Web Services are ASP.NET applications and therefore there are many elements that are common between them Let us look at the various parts of the base project References By default, references to a list of Microsoft NET Framework namespaces are included in the base project Let us look at this list System namespace The System namespace contains classes that define commonly-used values and reference data types, events and event handlers, interfaces, attributes, and processing exceptions System.Data namespace The System.Data namespace consists primarily of the classes that constitute the Microsoft ADO.NET architecture The DataSet class plays a central role in the ADO.NET architecture A DataSet is an in-memory cache of data obtained from many possible data sources such as databases or Extensible Markup Language (XML) documents A DataSet reads and writes data and schema as XML documents Both the data and schema can be sent over the Hypertext Transfer Protocol (HTTP) and can be used by any application, on any platform that supports XML You will learn about DataSets in detail in the next section Module 5: Implementing a Simple Web Service System.Web namespace The System.Web namespace supplies classes and interfaces that facilitate communication between a browser and a server This namespace includes the HTTPRequest and HTTPResponse classes that are discussed in Module 3, “The Underlying Technologies of Web Services,” in Course 2524A, Developing XML Web Services Using Microsoft Visual C# NET Beta System.Web also includes classes for cookie manipulation, file transfer, exception information, and output cache control You will revisit this namespace later in this module when you look at improving Web Service performance using caching, and cookie-based and cookieless authentication System.Web.Services namespace The System.Web.Services namespace consists of classes that help you to build and use Web Services One of the most important classes in this namespace is the WebService class If a Web Service needs access to the ASP.NET intrinsic (built-in) objects, then the class which implements the Web Service operations must be derived from the WebService class System.XML namespace The System.XML namespace exposes the XML classes that provide standardsbased support for processing XML The supported standards are: ! XML 1.0 The XmlTextReader class provides a parser for documents in XML 1.0 ! XML namespaces The NET Framework supports the use of namespaces in both XML streams and the Document Object Model (DOM) ! XML schemas The NET Framework supports schema mapping and XML serialization However, it does not support validation using XML Schema Definition language (XSD) ! XML Path Language (XPath) expressions The XPathNavigator class provides read-only, random access to XML documents using XPath expressions ! Extensible Stylesheet Language Transformations (XSLT) XSLT allows you to transform XML data using XSLT stylesheets ! DOM The XmlDocument class implements the World Wide Web Consortium (W3C) DOM Level Core and DOM Level Core specifications ! Simple Object Access Protocol (SOAP) 1.1 The classes that encapsulate SOAP support in the NET Framework can be found in the System.Web.Services.Protocols namespace Module 5: Implementing a Simple Web Service The asmx File The asmx file is the front end for a Web Service implemented using ASP.NET The way you access this file through HTTP determines the type of response you receive By default, the asmx file contains a class that is similar to the following example class: public class Service1 : System.Web.Services.WebService { The class contains a sample WebMethod implementation that is similar to the following: [WebMethod] public string HelloWorld() { return "Hello World"; } Delivery Tip From your browser, navigate to the following URL: http://localhost/ contoso/Micropayment asmx Explain the conscepts in the student notes using this page The Service Help page When you request an asmx file from a Web browser without supplying a recognized query string, the file returns an automatically generated service help page for the Web Service If you performed an HTTP-GET request for the asmx page without supplying a query string, the results would be the same A Service Help page provides a list of the methods of the Web Service that can be accessed programmatically The page contains links for each method, and each of these links will take you to a Service Method Help page for the corresponding method 60 Module 5: Implementing a Simple Web Service Exercise Creating the Contoso Micropayment Web Service In this exercise, you will implement the skeleton code for the Contoso Micropayment Web Service using Visual Studio NET You will also configure a SQL Server connection string application setting in the Web.config file for the Web Service ! To create the Contoso Web Service Open Visual Studio NET On the File menu, point to New, and click Project Select the ASP.NET Web Service project template Name the project as Contoso and create the project in the default location Click OK to begin Rename the default implementation file: a In Solution Explorer, right-click Service1.asmx b On the shortcut menu, click Rename c In the textbox, type Micropayment.asmx Open the Micropayment.asmx.cs file: a In Solution Explorer, right-click Micropayment.asmx b On the shortcut menu, click View Code Rename the Service1 class to MicroPaymentService Rename the constructor in the class to MicroPaymentService Add a WebService attribute to the MicroPaymentService class Set the following attribute properties Properties Values Name Contoso Micropayment Service Description Contoso Micropayment Services ! To add the skeleton code for the Web Service methods • Add the stubs for the GetAccount and GetTransactionHistory methods in the Contoso Micropayment Web Service The stubs are as follows: [WebMethod] public AccountDataSet GetAccount() { } [WebMethod] public TransactionDataSet GetTransactionHistory(DateTime startDate, DateTime endDate) { } At this point, you can ignore the undefined types AccountDataSet and TransactionDataSet You will define these types in Exercise Module 5: Implementing a Simple Web Service 61 ! To use temporary authentication information Add the following class definition, before the MicroPaymentService class: public class ContosoAuthInfo : SoapHeader { public string Username; public string Password; } Add a private data member called authInfo of type ContosoAuthInfo to the MicroPaymentService class In the constructor of the MicroPaymentService class, test the value of the authInfo field If the value is null, then: a Create an instance of ContosoAuthInfo and set the authInfo data member to this instance b Set the UserName and Password fields to John and password respectively This user name and password corresponds to a preconfigured database user Note In real-world applications, you should not specify hardcoded values for authentication information Add a using statement for the System.Web.Services.Protocols namespace, to Micropayment.asmx.cs This namespace defines the SoapHeader class ! To add SQL connect string configuration information Open Web.config Create an appSettings element directly following the configuration tag Add a child element named add to the appSettings element a Set the value of the key attribute to connectStringContoso b Set the value attribute to the following connection string data source=.;initial catalog=Contoso;user id=sa;pwd=Course_2524 62 Module 5: Implementing a Simple Web Service Exercise Accessing the Database In this exercise, you will add functionality to the GetAccount and GetTransactionHistory methods to call the existing SQL Server Contoso database stored procedures that return account data and transactions, respectively You will use the SqlDataAdapter class to generate a typed DataSet ! To add and configure a SqlDataAdapter to get account data In Solution Explorer, right-click Micropayment.asmx and then click View Designer On the View menu, click Toolbox On the Toolbox, click the Data tab Drag a SqlDataAdapter object from the Data tab to the Design view of the asmx file The Data Adapter Configuration Wizard is displayed Complete the Data Adapter Configuration Wizard by using the information in the following table On this wizard page Do this Welcome To The Data Adapter Configuration Wizard Click Next Choose Your Data Connection Click New Connection Connection tab of the Data Link Properties Dialog box For the numbered fields, type the following values: The name of your computer User name: sa Password: Course_2524 Select the Allow saving password check box Contoso To verify that the connection information is correct, click Test Connection Microsoft Datalink Click OK Connection tab of the Data Link Properties Dialog box Click OK Microsoft Development Environment Click OK Choose Your Data Connection Click Next Module 5: Implementing a Simple Web Service 63 (continued) On this wizard page Do this Choose A Query Type Click Use existing stored procedures, and then click Next Bind Commands to Existing Stored Procedures In the Select list, click _GetAccount Leave the Insert, Update and Delete lists empty Click Next View Wizard Results Click Finish to complete the wizard Notice that controls named sqlDataAdapter1 and sqlConnection1 have been added to the Design view Next, you need to generate a typed DataSet to associate it with the data returned from the _GetAccount stored procedure ! To generate a typed DataSet Right-click the sqlDataAdapter1 control and click Generate Dataset In the Generate Dataset dialog box, the following: a Click the New radio button b Double-click DataSet1 and type AccountDataSet c Leave the other dialog box options with their default settings and click OK to generate the AccountDataSet typed DataSet Notice in the Visual Studio NET Class View that the AccountDataSet typed DataSet has been added to the project ! To use the adapter and the DataSet Open Micropayment.asmx.cs The following data members have been added to the MicroPaymentService class: private System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1; private System.Data.SqlClient.SqlCommand sqlSelectCommand1; private System.Data.SqlClient.SqlConnection sqlConnection1; Code has also been added to the InitializeComponent method to initialize the data adapter, command, and connection objects To view the InitializeComponent method, you might need to click the Component Designer Generated Code region To execute the adapter code only when the Web Service GetAccount method is invoked, move the code into the GetAccount method To this: a Cut the declarations of the data members sqlDataAdapter1, sqlCommand1, sqlConnection1, and paste them into the GetAccount method b Because sqlDataAdapter1, sqlCommand1, and sqlConnection1 are no longer class data members, remove the private modifier prefixing each of these members 64 Module 5: Implementing a Simple Web Service c Cut the code from the InitializeComponent method that configures the data adapter, command, and connection objects, and paste it into the GetAccount method d Because sqlDataAdapter1, sqlCommand1, and sqlConnection1 are no longer class data members, remove the this keyword prefix Set the stored procedure input parameters To this, you must modify the following lines of wizard-generated code: sqlSelectCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@userID", System.Data.SqlDbType.NChar, 16, System.Data.ParameterDirection.Input, true, ((System.Byte)(0)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null)); sqlSelectCommand1.Parameters.Add(new System.Data.SqlClient.SqlParameter("@password", System.Data.SqlDbType.NChar, 16, System.Data.ParameterDirection.Input, true, ((System.Byte)(0)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null)); a Set the last argument of the SqlParameter constructor for the @userID parameter to the value in authInfo.Username b Set the last argument of the SqlParameter constructor for the @password parameter to the value in authInfo.Password To invoke the stored procedure: a Open the connection b Create an AccountDataSet object c Call the Fill method on the SqlDataAdapter, and pass the AccountDataSet object to this method d Store the result, which specifies the number of records returned in the DataSet, in a local variable AccountDataSet ds = new AccountDataSet(); int nRecords = sqlDataAdapter1.Fill(ds); e Close the connection A record count of indicates that the account is invalid Throw a System.Exception if records are returned Return the AccountDataSet to complete the method ! To use the configured connection string Add a using statement to use the System.Configuration namespace This namespace defines the ConfigurationSettings class Modify the assignment of the ConnectionString property in the GetAccount Web method to refer to the application setting sqlConnection1.ConnectionString = (string)ConfigurationSettings.AppSettings["connectStringCon toso"]; Module 5: Implementing a Simple Web Service 65 ! To add and configure a SqlDataAdapter to retrieve transaction information Drag a SqlDataAdapter from the Toolbox to the Design view of the asmx file This will invoke the Data Adapter Configuration Wizard Complete the Data Adapter Configuration Wizard by using the information in the following table On this wizard page Do this Welcome To The Data Adapter Configuration Wizard Click Next Choose Your Data Connection Verify that the existing connection for the Contoso database will be used and then click Next Choose A Query Type Click Use existing stored procedures, and then click Next Bind Commands to Existing Stored Procedures In the Select list, choose _GetTransactionLog Leave the Insert, Update and Delete lists empty Click Next View Wizard Results Click Finish to complete the wizard ! To generate a typed DataSet Right-click the sqlDataAdapter1 control, and click Generate Dataset In the Generate Dataset dialog box, the following: a Create a New DataSet b Double-click DataSet1 and type TransactionDataSet c To generate the TransactionDataSet typed DataSet, leave the other dialog box options at the default settings and click OK Notice that the TransactionDataSet typed DataSet has been added to the project Tip If for some reason Visual Studio NET fails to generate the DataSet code, then the following: ! Delete the xxxx.xsd file, and the sqlDataAdapter1 and the SqlCommand1 objects ! Save your project ! Shutdown and restart Visual Studio NET ! Repeat the steps to generate the DataSet 66 Module 5: Implementing a Simple Web Service ! To use the adapter and the DataSet and use the configured connection string Move the wizard-generated code for sqlConnection1, sqlCommand1, and sqlDataAdapter1 to the GetTransactionHistory method, by following the steps described in step of the To use the adapter and the DataSet procedure in this exercise Set the stored procedure parameters by following step of the To use the adapter and the DataSet procedure in this exercise The _GetTransactionLog stored procedure takes two additional parameters, the @startDate and @endDate parameters Set these to the values of the startDate and endDate method parameters To invoke the stored procedure: a Open the connection b Create a TransactionDataSet object c Call the Fill method on the SqlDataAdapter object, and pass the TransactionDataSet object to this method d Store the result, which specifies the number of records returned in the dataset, in a local variable e Close the connection Because it is valid for an account to have no associated transactions, not throw an exception if the returned recordset count is Modify the method to use the connection string in Web.config instead of the hard-coded connection string Return the TransactionDataSet to complete the method implementation ! To test the Contoso Web Service Build the Contoso Web Service To invoke the help test page, press F5 Verify that you see the GetAccount and GetTransactionHistory methods Module 5: Implementing a Simple Web Service 67 Exercise Using the Contoso Web Service in the Woodgrove and Contoso Account Manager In this exercise, you will add a Contoso Web reference to the Woodgrove and Contoso Account Manager client application, and add code to invoke the Contoso Micropayment Service proxy class methods ! To add a Web Reference Open the Woodgrove and Contoso Account Manager project that you worked on in Lab 4, Implementing a Web Service Consumer Using Visual Studio NET, in Module 4, “Consuming Web Services” in Course 2524A, Developing XML Web Services Using Microsoft Visual C# NET Beta Note If you did not start or complete Lab 4, use the Woodgrove and Contoso Account Manager project found in the \Labfiles\Lab05\Starter\Woodgrove and Contoso Account Manager folder Otherwise, continue to use the Woodgrove and Contoso Account Manager project that you worked on in Lab (in the \Labfiles\Lab04\Starter\Woodgrove and Contoso Account Manager folder) In Solution Explorer, right-click the References node and click Add Web Reference In the Add Web Reference dialog box, click the Web References on Local Web Server link In the Available References box, under Linked reference groups, click the http://localhost/Contoso/Contoso.vsdisco link You should see a Disco description of the Contoso Micropayment Web Service on the left pane and links to View Contract and View Documentation on the right pane, which is named Available References At this point, in the discovery process the Add Reference button becomes enabled Click this button to complete adding a Web reference Expand the Web References node in the project tree in Solution Explorer Rename the localhost namespace to Micropayment To this, right-click localhost and then click Rename Type Micropayment ! To retrieve Contoso account information In WebServiceClientForm.cs, add a using directive to reference the namespace WebServiceClient.Micropayment In WebServiceClientForm.cs, set the Enabled property of the buttonContosoGetAccount to true To retrieve the transactions: a Locate the following method: private void GetContosoAccountInfo() b Create an instance of the ContosoMicropaymentService proxy class 68 Module 5: Implementing a Simple Web Service c Call the GetAccount method of the proxy class Save the returned AccountDataSet typed DataSet d Call the DataSetToXMLString helper method to obtain a string representation of the AccountDataSet e Assign the string returned from DataSetToXMLString to the Text property of the textBoxContosoAccount text box In the Form1 Load event handler, call to the GetContosoAccountInfo method ! To retrieve Contoso transactions In WebServiceClientForm.cs, set the Enabled property of the buttonContosoGetTransactions to true To retrieve the transactions: a Locate the following method: private void buttonContosoGetTransactions_Click(object sender, System.EventArgs e) b Create an instance of the ContosoMicropaymentService proxy class c Call the GetTransactionHistory method The GetTransactionHistory method also returns a typed DataSet, also named TransactionDataSet d To distinguish Contoso TransactionDataSet from the Woodgrove TransactionDataSet, prefix the Contoso TransactionDataSet with the WebService.Micropayment namespace e Check the number of transactions If there are more than transactions, then display them, otherwise display the message "No transactions" ! To test the modified client application Build and run the application Notice that the Contoso account information is displayed Click an account number in the Accounts for Customer list Click Get Transaction History for the Woodgrove Web Service Existing transactions are displayed Click Get Transaction History for the Contoso Web Service If there are no recent transactions, a message that indicates that there have been no recent transactions is displayed Otherwise, a form that lists the recent transactions is displayed Module 5: Implementing a Simple Web Service Exercise Debugging the Contoso Micropayment Service In this exercise, you write code to output debug statements and add performance counters to a Web Service ! To write debug information using the Trace class Open the Contoso Micropayment Web Service project with Visual Studio NET Open the Micropayment.asmx.cs file and locate the GetTransactionHistory method At the top of the method implementation, output a debug statement by: a Create a string that indicates the beginning of the GetTransactionHistory method and displays the value of the authInfo.Username field b Call the Context.Trace.Write method Pass the string as the message parameter Immediately before the return statement in the method, call the Context.Trace.Warn method Set the message parameter to a string that indicates the record count of the returned DataSet Build the application ! To enable tracing in Web.config Open Web.config and locate the element Set the enabled attribute to true Do not change the default values for the requestLimit, pageOutput, traceMode and localOnly attributes ! To view trace output Run the Woodgrove and Contoso Account Manager Retrieve the Contoso transaction history a couple of times To view trace output, in Internet Explorer open http://localhost/Contoso/trace.axd Notice that the page displays a line for each request to the Micropayment.asmx page Click the associated View Details link for each of the requests At each Request Details page, locate the SOAPAction header listed in the Headers Collection table The value associated with the SOAPAction specifies the Web Service method invoked for this request Locate a request for which the SOAPAction shows the value http://tempuri.org/GetTransactionHistory 69 70 Module 5: Implementing a Simple Web Service Locate the Trace Information table on this Request Detail page In the Trace Information table, you should see the two trace messages that you output within the GetTransaction method These messages should resemble the following: GetTransactionHistory for John GetTransactionHistory returns records The second message should be displayed in red, because it was output using the Context.Trace.Warn method Note Tracing impacts performance and therefore it should be used only when debugging Before deploying a Web Service, remember to disable tracing by setting the enabled attribute of the element to false in Web.config ! To add performance counters Open the Contoso Micropayment Web Service project with Visual Studio NET Open Server Explorer and expand the node for your server Right-click the Performance Counters node and click Create New Category In the Performance Counter Builder dialog box, set the following information: Field Value Category name Contoso Category description Contoso Micropayment Web Service Click New to add a new performance counter to the Contoso category Set the following information: Field Value Name NumberOfActiveRequests Type NumberOfItems32 Description Number of active GetAccount requests Click OK Open global.asax.cs Add a using statement that references the System.Diagnostics namespace Module 5: Implementing a Simple Web Service 71 Within the Application_Start method, create an instance of the PerformanceCounter class Store the object reference in the Application object for later use, using the key perfCtr // global.asax protected void Application_Start(Object sender, EventArgs e) { // false on the last argument means we want // read/write access to this counter PerformanceCounter perf = new PerformanceCounter( "Contoso","NumberOfActiveRequests", "Contoso Web Service",false); Application.Add("perfCtr",perf); } 10 Locate the GetAccount method At the beginning of this method, declare a reference to a PerformanceCounter Retrieve the PerformanceCounter reference from the Application object Cast this reference to thePerformanceCounter class 11 Call the Increment method on the performance counter This will cause the performance counter to be incremented whenever this method is invoked 12 Call the Decrement method on the performance counter immediately after closing the database connection This will give a count of the number of clients that are concurrently executing the GetAccount method 13 Build the application ! To view performance counters To open the Performance utility, on the Start menu, point to Administrative Tools, and then click Performance In the tree view, click System Monitor On the toolbar, click the Add button to add a performance counter to the chart In the Add Counter dialog box, the following: a Click Use local computer counters b In the Performance object list, click Contoso c Click All counters d Click Add e Click Close To chart the NumberOfActiveRequestsCounters counter at a non-zero value, you must invoke the GetAccount method To this: a Within the Contoso Micropayment Service project, set a breakpoint in the GetAccount method b Start the application from within Visual Studio NET to debug c In the browser, open the GetAccount test page and invoke the method Click Invoke d When the application stops at the breakpoint in the GetAccount method, step beyond the line that increments the performance counter 72 Module 5: Implementing a Simple Web Service Switch to the Performance utility Notice that the NumberOfActiveRequestsCounters now charts the value Within Visual Studio NET, press F5 to continue execution Notice that the NumberOfActiveRequestsCounters again charts the value because the Decrement method was called at the end of the GetAccount method Module 5: Implementing a Simple Web Service 73 Review Topic Objective To reinforce module objectives by reviewing key points ! Creating a Web Service Project Lead-in ! Implementing Web Service Methods ! Managing State in an ASP.NET Web Service ! Debugging Web Services The review questions cover some of the key concepts taught in the module *****************************ILLEGAL FOR NON-TRAINER USE****************************** If you want to expose a C# method as a Web Service operation, what must you do? Apply the WebMethod attribute to the method, and make sure that the method is public If a Web Service method returns a stream that is megabyte in size, which property of the WebMethod attribute should you modify to minimize the amount of time a client would wait for the arrival of the first set of data? BufferResponse Which properties and fields of a class are serialized when an instance of a class is returned by a Web Service method? All public, read/write properties and all public, read/write fields If your Web Service will be deployed on a Web Farm, what kind of data can be stored appropriately in Application state? Read only data that can be restored exactly in the event of a Web Service being restarted 74 Module 5: Implementing a Simple Web Service You deploy a Web Service in production, and want to store trace information in a disk file on the server hosting the Web Service Which two classes could you use to this? • Trace to emit trace output • TextWriterTraceListener to write the trace output to disk Which NET Framework class is provided to allow you to hook into various stages of SOAP message processing? SoapExtension ... represents a set of commands and a connection to a database SqlDataAdapter is a class derived from DataAdaptor SqlDataAdapter is used to populate a DataSet ! To add and configure a SqlDataAdapter Create... creating a typed DataSet is as follows: Generate a SqlDataAdapter Create a typed DataSet using the data adaptor that you created in the previous step Note The SqlDataAdapter is a class in ADO.NET,... generated DataSet Module 5: Implementing a Simple Web Service 33 " Managing State in an ASP.NET Web Service Topic Objective To explain how state is managed in a Web Service using ASP.NET state management

Ngày đăng: 21/12/2013, 05:17

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan