Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 8 docx

90 301 0
Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 8 docx

Đ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

When you use Web services within your ASP.NET logic, SOAP is used as the default protocol. Although it seems a little more bulky than the other options, it's the only mechanism that makes it possible to use Web methods directly, in a flexible manner , and seamlessly from within the code. Building an ASP.NET Web Service Let's take a more detailed look at putting a Web service together. We'll also begin to explore the possible uses for Web services. You can define a Web service by simply writing a few lines of code and placing them inside a file with a .asmx extension. This extension tells Web Matrix that a Web service is being defined. You can create a Web service just like a standard ASP.NET page, using Web Matrix (as we did earlier in the chapter) or any text editor. A Web service must contain four essential parts: ❑ Processing directive. ❑ Namespaces. ❑ Public class. ❑ Web methods. Let's look at each of these in turn. Processing Directive Within the empty ASMX file (the required file type for an ASP.NET Web service page), you must let the Web server know that you're creating a Web service. To do this, enter a directive at the top of your page with the following syntax (in fact, Web Matrix creates this automatically based on the information submitted in the startup dialog): <%@ WebService Language="language" Class="classname"%> This statement appears at the top of an ASP.NET source file to tell the .NET Framework about any settings or constraints that should be applied to whatever object is generated from the file. In this case, the directive tells the compiler the language in which the Web service is written, and the name of the class in which it is defined. This class might reside in the same file, or within a separate file (which must be in the \bin directory, immediately beneath the Web application root in which the Web service lives). Namespaces You can make use of other file's logic within your ASMX page by specifying appropriate namespaces. In this case, you can use the C# using command: using System; using System.Web.Services; using System.Xml.Serialization; Web services require importing these namespaces as an absolute minimum, because they contain the classes needed for Web services to handle network connection issues and other OS-related tasks. 603 Web Services Public Class A public class acts as a container for the methods in our Web service: public class ClassName { } Essentially, we're just defining an object whose methods will be exposed over the Web. This will ultimately allow us to make remote method calls over the Internet. To our server, these calls look like method calls to the same machine where the consuming application resides. Web Methods The methods exposed for consumption over the Internet are known as Web-callable methods or simply Web methods. By definition, a Web service will expose one or more Web methods – of course it can have other non-Web methods as well, and these can be protected as needed so that consumers cannot use them directly. The syntax varies slightly depending upon the language used, but they all tend to follow a similar structure. In C#, it is as follows: [WebMethod] public string Hello(string strName) WebMethod attribute can take parameters of its own. Thus you can set various properties that modify the activity of the attribute. This allows us to customize our Web methods in various ways; for example, we can use CacheDuration to set the number of seconds for which the WebMethod will cache its results. If a consumer requests a result from the Web Service within the time specified in this attribute, WebMethod will retrieve the cached copy of these values instead of retrieving them from the original source: [WebMethod(CacheDuration:= 5)] public string Hello(string strName) { For more information on WebMethod attributes, such as CacheDuration, please visit: www.microsoft.com/library/default.asp. When you build a Web service, a lot of time will be spent creating a Web method for the Web service. It is possible to include more than one Web method in an ASMX file, as you'll see in the next example. We only place the WebMethod declaration before the functions that we wish to expose to consumers. Those without this declaration cannot be seen. The name of this class is effectively the name of the Web service. Therefore, it should correspond to the Class value specified in the processing directive. 604 Chapter 16 Try It Out Creating a Web Service with Multiple Web Methods This Web service contains four Web methods that convert inches to centimeters, centimeters to inches, miles to kilometers, and kilometers to miles. 1. Create an XML Web service in Web Matrix called measurementconversions.asmx and enter MeasurementConversions as the class, Ch16 as the namespace, and add the following code: <%@ WebService language="C#" class="MeasurementsConversions" %> using System; using System.Web.Services; using System.Xml.Serialization; public class MeasurementsConversions { [WebMethod(Description="Convert Inches To Centimeters")] public decimal InchesToCentimeters(decimal decInches) { return decInches * 2.54m; } [WebMethod(Description="Convert Centimeters to Inches")] public decimal CentimetersToInches(decimal decCentimeters) { return decCentimeters / 2.54m; } [WebMethod(Description="Convert Miles to Kilometers")] public decimal MilesToKilometers(decimal decMiles) { return decMiles * 1.61m; } [WebMethod(Description="Convert Kilometers to Miles")] public decimal KilometersToMiles(decimal decKilometers) { return decKilometers / 1.61m; } } 2. Call it up in your browser and you should see something like Figure 16-6: Figure 16-6 605 Web Services Let's look at the code for a moment. We'll get back to the testing of our Web service after this. How It Works In this example, we created a Web service that converts between Imperial (English) measurements and Metric measurements. The first line tells us that the file is a Web service written in C#. We have a class name of MeasurementConversions that will be used by consumers to make references to the Web service: <%@ WebService language="C#" class="MeasurementsConversions" %> Next, we import the namespace that allows us to refer to Web service objects without using fully qualified names: using System; using System.Web.Services; using System.Xml.Serialization; We then name our class to match the processing directive class name. We'll need to know this when we are ready to make remote calls to the Web service through a consumer: public class MeasurementConversions Finally, consider the actual Web methods. These are separate functions that can be called within a Web service to return a result. The first Web method receives a Decimal value in inches and converts it to a Decimal value in centimeters using the standard conversion formula. The second receives a Decimal in centimeters and converts it to inches in the same manner: [WebMethod(Description="Convert Inches To Centimeters")] public decimal InchesToCentimeters(decimal decInches) { return decInches * 2.54m; } [WebMethod(Description="Convert Centimeters to Inches")] public decimal CentimetersToInches(decimal decCentimeters) { return decCentimeters / 2.54m; } The third and fourth Web methods perform similar conversions from miles to kilometers and kilometers to miles respectively: [WebMethod(Description="Convert Miles to Kilometers")] public decimal MilesToKilometers(decimal decMiles) { return decMiles * 1.61m; } [WebMethod(Description="Convert Kilometers to Miles")] public decimal KilometersToMiles(decimal decKilometers) { return decKilometers / 1.61m; } We've now created a complete Web service by using the processing directive, adding namespaces, and creating Web methods. Now the big question is 'How do we know it works?' It's time to put it through its paces. 606 Chapter 16 Testing Your Web Service To test Web services, all you need is an Internet connection and a browser. In the browser address bar, just enter the URL of the Web service in the following format: http://[path]/[webservice].asmx The first time the Web service is accessed, the code will compile on the Web server, and a new browser window will appear containing some very helpful diagnostic information. This Web service Description page allows us to impersonate a consumer and enter input values to send to the Web service. The page contains the following information about the Web service: ❑ Web method names: Names of the Web service's Web-callable functions. ❑ Request parameters: The names of all the inputs that the Web service expects a consumer to supply. ❑ Response Type: The data type of the result sent by the Web service to a consumer (such as integer, string, float, and object). ❑ Fields: These can be used to enter test values. You'll also see the following message at the top of the test page: The following operations are supported. For a formal definition, please review the Service Description. The Service Description is a comprehensive technical description of all the functionality exposed by the Web service. You'll be taking a closer look at it later on in the chapter. For the time being, we're only interested in testing our Web service. Let's now go back and see what happens when we test our measurementconversions Web service. Try It Out Conversions Test Page 1. Assuming your browser is still open, just click on the MilesToKilometers hyperlink and enter a test value of 60 in the decMiles value field, as shown in Figure 16-7: Figure 16-7 607 Web Services 2. Click Invoke, and a new browser window appears, containing our result in kilometers in XML format. This is shown in Figure 16-8: Figure 16-8 3. In the original .asmx page, click on the word here at the top of the test page, and you'll return to the original test screen. You can now repeat this procedure for the other methods shown on the page. How It Works When we browse to the test page, we see a screen containing the name of our Web service and underneath it, a list of the methods that it exposes. These method names are hyperlinks. When we click on MilesToKilometers, the Web method test section will appear in the browser window. We are given the name of the parameter ( decMiles), and an associated field to enter the test value. Once the value is entered, we can press the Invoke button to execute the Web method. By doing this, we are impersonating a consuming application. The entered test value ( 60) is passed using HTTP as a request, to the MilesToKilometers Web method. The value will be multiplied by 1.61 and returned as a decimal. The result is in XML. You might say, "Sure, our test page tells us what the Web service's expectations are. But how would a consumer know what they are?" This consumer might not necessarily be another user, it could be an application and then the expectations need to be explicitly defined. The next section discusses how to know what a Web service requires, what it produces, and how a consumer can communicate with it. Using Your Web Service As you've learned, it's essential for consumers to know what parameters to send to a Web service and what values to expect it to return. To accomplish this, a Web service Description Language (WSDL) file is used. This is an XML file that defines how the interaction between a Web service and its consumer will occur. WSDL is a standard managed by the W3 standards organization, and you can find more details about it at http://www.w3.org/TR/wsdl. The impact of this WSDL standard is enormous. WSDL is able to define all the interactions of a Web service regardless of whether the service is running in ASP.NET or Java, and regardless of whether it is running on Windows or UNIX. The data type for MilesToKilometers is a decimal. This is the value that our measurementconversions Web service expects from a consumer. 608 Chapter 16 It means that in future you won't need to be concerned with whether our services, or languages, are compatible across platforms. This would allow us to concentrate on the real issue of writing robust and functional code. WSDL will take care of declaring the interaction for us. For instance, if a Web service expects two specific parameters and returns a single value, the WSDL defines the names, order, and data types of each input and output value. Since we know where to find the Web service using its URL, we don't need to know the physical location or the internal logic of the Web service. With WSDL, we have all the information necessary to begin making use of the Web service functionality within our applications. It's really that simple! Let's take a quick look at what a WSDL contract looks like using our MeasurementConversion Web service. Try It Out Viewing the WSDL Contract 1. Enter the path http://localhost/measurementconversions.asmx in your browser's address bar and click on the Service Description hyperlink at the top of the page. You should see a screen similar to Figure 16-9: Figure 16-9 How It Works As you can see, there's a lot of information in here and this is just the collapsed view! Our Web method message names along with the various HTTP GET, HTTP POST, and SOAP message structures are displayed. These message formats contain the requirements for a consumer to know what parameters are needed to communicate with a Web service using each message structure. 609 Web Services At the top, the following declaration indicates that the WSDL file is in XML format: <?xml version="1.0" encoding="utf-8" ?> Below that declaration is the <definitions> element, which contains various namespaces. Most of these namespaces make a reference to SOAP, which we discussed earlier. These must be included in the file for SOAP to work correctly: <definitions xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:s0="http://tempuri.org/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" targetNamespace="http://tempuri.org/" xmlns="http://schemas.xmlsoap.org/wsdl/"> Next, the <types> element defines each of the data types that the Web service expects to receive and return after completion. This is very complex, and almost a science in itself. It is written in XML Schema Definition (XSD) language. You can't see the definitions in the screenshot as its section is collapsed (like the others). All you need to do is click on the node in Internet Explorer in order to view them. After this are the various one-way transmissions from a consumer to the Web service and back again. Our Web method message names are in here, and the various SOAP message structures are laid out. For example, on expanding the <message> element, we can see the InchesToCentimeters Web method message structures for SOAP: <message name="InchesToCentimetersSoapIn"> <part name="parameters" element="s0:InchesToCentimeters" /> </message> <message name="InchesToCentimetersSoapOut"> <part name="parameters" element="s0:InchesToCentimetersResponse" /> </message>: In short, this file contains all of the information necessary to communicate with our Web service. Now that you've seen the process of building and communicating with XML Web services in detail, let's create something a bit more complex. The next example will accept a value, and return a result using ADO.NET to retrieve data from an Access database. Try It Out ISBN Search Web Service Let's create a Web service that returns the title of a book, based on an ISBN that the consumer provides. This will allow our librarian to add a function on the library's Web page that enables users to search by consuming this Web service. This particular service will access a database of books. The database contains information on ISBN and book titles. Once the details are received from the database, the results will be inserted into a DataReader and returned to the consumer in XML. 610 Chapter 16 This example uses the Library.mdb Access database, which you can download along with the code samples for this book from www.wrox.com. You should ensure that the file is in the same location as the Web service that you create. 1. Create an XML Web service called ISBN.asmx in Web Matrix, entering ISBN as the class name and Ch16 as the Namespace. 2. Add the following using statements to the beginning of the file: <%@ WebService Language="C#" Class="ISBN" %> using System; using System.Web.Services; using System.Xml.Serialization; using System.Data; using System.Data.OleDb; 3. Add the following code to enable the Web service: public class ISBN : System.Web.Services.WebService { [WebMethod] public string BookDetail(string strIsbn) { return GetBookDetails(strIsbn); } 4. Enter the following code directly after the BookDetail Web method. This function performs the database lookup and returns the book title string: private string GetBookDetails(string strIsbn) { OleDbDataReader objLibraryDR = null; OleDbConnection objLibraryConn = null; OleDbCommand objLibraryCmd = null; string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("Library.mdb") + ";"; string strSQL = "SELECT Title FROM Books WHERE ISBN = '" + strIsbn + "'"; string strBookTitle; objLibraryConn = new OleDbConnection(strConn); objLibraryCmd = new OleDbCommand(strSQL, objLibraryConn); objLibraryConn.Open(); objLibraryDR = objLibraryCmd.ExecuteReader(CommandBehavior.CloseConnection); if (objLibraryDR.Read()) { strBookTitle = objLibraryDR[0].ToString(); } else { strBookTitle = "Book not found in the database"; } objLibraryDR.Close(); return strBookTitle; } } 611 Web Services [...]... in your ASP.NET code ❑ Language: The language the proxy class should be generated in ❑ OutputDirectory: The place where both the proxy class and the assembly should be placed ❑ SourceFile: The name of the proxy class ❑ GenerateAssembly: The name of the DLL These options ensured that we create the DLL so that it works correctly, and can be added to our ASP.NET page 617 Chapter 16 In our ASP.NET page,... that we have a proxy class and a DLL We're ready to make use of the ISBN Web service from within an ASP.NET page We'll call the BookInfo.aspx page, and use it to call the Webcallable function BookDetail in ISBN.asmx By using a proxy, the reference to the function's namespace will appear as if it was a function within the same page So, create a new ASPX file called BookInfo.aspx in Web Matrix, in the... types To make use of a Web service from an ASP.NET page, your proxy must be created and compiled appropriately You can create a proxy to a Web service using either Web Matrix or a command line tool called WSDL.exe provided in the NET Framework SDK Both of these methods make use of WSDL to create a proxy, built in the language of your choice We'll create a new ASP.NET application, which will access our... registration key) with others However, when the data provided by the Web service is not sensitive or proprietary in nature, this security method provides us with a quick and effective option Let's examine how you might apply this type of security to the ISBN Web service Try It Out Securing a Web Service with Username and Password You will be using the security.mdb database (provided with the code for... the distance between two cities, and then move on with our code When the DistanceBetween object completes its calculation, it fires the DistanceBetween_CalculationComplete event, which allows us to handle the returned value without making the rest of the application wait Because we can call a remote function without the need for an immediate response (without breaking an application), our applications... services For the developer, ASP.NET Web services will make the Internet a programmer's toolbox, with a greater assortment of tools than ever before Exercises 1 2 3 4 Explain the role of the Simple Object Access Protocol (SOAP) in Web services What is the purpose of the WSDL file? How would you locate a Web service that provides the functions you require? Create a Web service with a class name of circles,... 4/3(Pi)r3.) 5 6 Create an ASP.NET page containing a drop-down listbox in which a user can select names of Northwind employees to return their addresses 7 634 Create a Web service that connects to the Northwind database and returns employee's addresses based on their last names Secure the Northwind employee Addresses Web service so that no unauthorized users have access to it 17 ASP.NET Security As soon... database"; } objLibraryDR.Close(); return strBookTitle; For more information on working with data sources, please refer to Chapters 8 and 9 Consuming a Web Service You've created some Web services from start to finish using a variety of technologies The next step is to understand how to include this functionality within a consumer application To do this, you must first create an interface that will... the proxy class in C#, and defined the ISBNService namespace By selecting a namespace, you will be able to reference your proxy class from within your consuming application The proxy is contained in a file called ISBNProxy.cs At the same time, Web Matrix has also performed the second stage It has taken the ISBNProxy.cs and compiled it to create a DLL file that can be referenced within the code Once... forum; many people out there could be interested in what your ASP.NET pages have to offer You need to take considered action to prevent your pages and Web services being used and consumed by people who have not been authorized to do so Fortunately, there are many ways of controlling who's looking at your information However, security doesn't stop with access policies; it's equally important that the applications . 16 -14 : Figure 16 -14 8. Enter an ISBN that we know is in the Books table, like the ISBN for this book (0764557 084 ) and you'll see something like Figure 16 -15 : 616 Chapter 16 Figure 16 -15 9 function's namespace will appear as if it was a function within the same page. So, create a new ASPX file called BookInfo.aspx in Web Matrix, in the folder C:BegASPNET 11 Ch16. 6. Click on the All window and enter. part of the consumer application itself. Figure 16 -11 illustrates this process: 613 Web Services Figure 16 -11 The function works as follows: 1. The application executes a function in the proxy

Ngày đăng: 13/08/2014, 04:21

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

Tài liệu liên quan