Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
194
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 13: Remoting and XML Web Services

37

 

 

 

ASP.NET XML Web Services Overview

Topic Objective

To provide an overview of ASP.NET XML Web services.

Lead-in

ASP.NET provides support for XML Web services with the .asmx file, which is a text file that is similar to an

.aspx file.

!ASP.NET Files with .asmx Extensions Are Web Services

!Example of HelloWorld .asmx File

<%@ WebService Language="C#" Class="HelloWorld" %> <%@ WebService Language="C#" Class="HelloWorld" %> using System;

using System;

using System.Web.Services; using System.Web.Services;

public class HelloWorld : WebService { public class HelloWorld : WebService {

[WebMethod] public String SayHelloWorld() { [WebMethod] public String SayHelloWorld() {

}}

}}

return "Hello World"; return "Hello World";

! If File Is Placed on Server Foo Inside a Virtual Directory Bar

# Access service by using:

http://Foo/Bar/HelloWorld.asmx

http://Foo/Bar/HelloWorld.asmx

# Access WSDL of service by using:

http://Foo/Bar/HelloWorld.asmx?wsdl

http://Foo/Bar/HelloWorld.asmx?wsdl

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Delivery Tip

You can demonstrate the SayHelloWorld service by cutting and pasting the HelloWorld.asmx code into Notepad and saving it as a file named HelloWorld.asmx in the source directory for an existing IIS virtual directory. You then type the appropriate URL in the Internet Explorer Address bar. To make the Address bar visible, click the View menu, point to Toolbars, and then click Address Bar.

This section introduces some of the basic features of ASP.NET that enable developers to host and use XML Web services. The Internet is quickly evolving from its present stage where Web sites deliver user interface (UI) pages to Web browsers to a next generation of programmable Web sites that directly link organizations, applications, services, and devices. These programmable Web sites are more than passively accessed sites; they are reusable, intelligent XML Web services.

Using .asmx Files

ASP.NET provides support for XML Web services with the .asmx file. An

.asmx file is a text file that is similar to an .aspx file. An .asmx file can be part of an ASP.NET application that includes .aspx files. Like .aspx files, .asmx files are automatically compiled by the ASP.NET runtime when a request to the service is made. Subsequent requests are serviced by a cached pre-compiled type object. Like .aspx files, .asmx files are then Uniform Resource Identifieraddressable.

The following example shows the code that is contained in the HelloWorld.asmx file. It is a simple example of a ASP.NET-hosted XML Web service.

<%@ WebService Language="C#" Class="HelloWorld" %>

using System;

using System.Web.Services;

public class HelloWorld : WebService {

[WebMethod] public String SayHelloWorld() { return "Hello World";

}

}

38

Module 13: Remoting and XML Web Services

The HelloWorld.asmx file starts with an ASP.NET directive, WebService, and sets the language to C#. You can also set the language to Microsoft

Visual Basic®.

The class HelloWorld contains the XML Web service and therefore is derived from the base class WebService in the System.Web.Services namespace. All of the methods that will be accessible as part of the service must have the custom attribute, [WebMethod], in front of their signatures. In the preceding example, the SayHelloWorld method is the service’s only method.

Using a Virtual Directory

To create an ASP.NET application, you can use an existing virtual directory or create a new one. For example, if you installed Microsoft Windows 2000 Server and Internet Information Server (IIS) on a computer, that computer probably now has the directory C:\InetPub\WWWRoot.

To configure IIS, start the Internet Information Services tool. Click Start, click Control Panel, Performance and Maintenance, Administrative Tools, and then click Internet Information Services. In the Internet Information Services tool, you can create a new virtual directory or promote an existing directory.

!To create a new virtual directory, right-click an existing directory, and then click New.

!To promote an existing directory, right-click a virtual directory, click

Properties and then set the Local Path.

If you place the HelloWorld.asmx file on a server called Foo inside a virtual directory called Bar, you can use a URL in Internet Explorer to test the application. For example, if you type http://Foo/Bar/HelloWorld.asmx in the Address bar, the resulting page shows the public methods for this XML Web service and the protocols, such as SOAP or HTTP GET, that you can use to invoke these methods.

The public methods for the XML Web service are marked with the

[WebMethod] attribute.

The Web Services Description Language XML file for this service is produced when you type http://Foo/Bar/HelloWorld.asmx?WSDL in the

Internet Explorer Address bar. This WSDL file is important and can be used by clients to access the service.

Module 13: Remoting and XML Web Services

39

 

 

 

ASP.NET Features

Topic Objective

To explain how to create an XML Web service by exposing a .NET class that inherits from the WebService class, and to introduce advanced ASP.NET features.

Lead-in

In ASP.NET, you can create an XML Web service by simply exposing a .NET class that inherits from the

WebService class.

!ASP.NET Can Expose Web Services Defined in a .NET Class

#Class derives from WebService, method attribute [WebMethod]

 

namespace MyNameSpace {

 

 

 

 

namespace MyNameSpace {

 

 

 

public class HelloWorld : WebService {

 

 

 

public class HelloWorld : WebService {

 

 

 

 

[WebMethod] public String SayHelloWorld() {

 

 

 

 

[WebMethod] public String SayHelloWorld() {

 

 

 

 

return "Hello World"; }

 

 

 

}}

return "Hello World"; }

 

 

}}

#

 

 

 

 

 

 

 

 

 

 

# Class source file is compiled into a library DLL and placed in \Bin

 

csc /out:bin\helloworld.dll /t:library helloworld.cs csc /out:bin\helloworld.dll /t:library helloworld.cs

# The .asmx file contains a single line that names the class

<%@ WebService Class="MyNameSpace.HelloWorld" %> <%@ WebService Class="MyNameSpace.HelloWorld" %>

!Advanced ASP.NET Features

#Data sets, Global.asax, Session and Application objects, pattern matching

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In ASP.NET, you can create an XML Web service by simply exposing a .NET class that inherits from the WebService class. You compile the class’s source file into a library DLL and place this DLL in the ASP.NET application’s \Bin subdirectory. You then create in the ASP.NET application’s directory an .asmx file that contains only the following single line of code:

<%@ WebService Class="<namespace>.<classname>" %>

The HelloWorld.cs source code defines a HelloWorld service with an exported SayHelloWorld method in the MyNameSpace namespace, as shown in the following example:

using System;

using System.Web.Services;

namespace MyNameSpace {

public class HelloWorld : WebService { [WebMethod] public String SayHelloWorld() {

return "Hello World";

}

}

}

To compile this HelloWorld.cs file in the ASP.NET application directory, you type the following command in a Visual Studio .NET Command Prompt window:

>csc /out:bin\helloworld.dll /t:library helloworld.cs

40

Module 13: Remoting and XML Web Services

You then create the file named HelloWorld.asmx in the ASP.NET application directory. HelloWorld.asmx contains the following single line of code:

<%@ WebService Class="MyNameSpace.HelloWorld" %>

The only methods that are exposed from a service are those class methods that are flagged with a [WebMethod] custom attribute. Without this attribute, the method is not exposed from the service. Not exposing a method from a service is useful when you want to hide implementation details that are called by public XML Web service methods or when the WebService class is also used in local applications.

Note A local application can use any public method, but only [WebMethod] methods are remotely accessible through SOAP.

Advanced ASP.NET Features

ASP.NET is also useful for building complex XML Web services. Advanced

ASP.NET features include:

!Data sets

Data sets are a powerful new XML-based technique to represent disconnected data. Data sets can be returned from an XML Web service method. Because Data sets can store complex information and relationships in an intelligent structure, they enable you to take full advantage of XML Web services. When you expose Data sets through a service, you can limit the database connections to your data server.

!Global.asax file

The Global.asax file adds application-level logic and event-handling code to Web applications.

!Session and Application objects

You can use ASP.NET intrinsics, such as the Session and Application objects, to manage an ASP.NET application’s state.

!Text Pattern Matching

Text Pattern Matching is a technology that can be used to address any Uniform Resource Identifier that returns text as if it were an XML Web service.

Further discussion of these and other advanced ASP.NET features is beyond the scope of this course.

Module 13: Remoting and XML Web Services

41

 

 

 

Demonstration: Using Visual Studio .NET to Create an XML Web Service

Topic Objective

To demonstrate how to use Visual Studio .NET to create an XML Web service.

Lead-in

In this demonstration, you will learn how to create a service called MathService that has a single method named SalesTax.

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Delivery Tip

Although this demonstration includes detailed instructions, it is not a guided practice. Present the demonstration and suggest that students try the demonstration for themselves later.

In this section, you have learned how to create an XML Web service by using ASP.NET. Visual Studio .NET provides an even easier way to build ASP.NEThosted XML Web services.

In this demonstration, you will see how to create a service called MathService that has a single method named SalesTax. The SalesTax method takes two parameters: The first parameter represents the sales amount; and the second parameter represents the fractional sales tax rate. For example, a sales tax rate of 8.5 percent is represented as .085. SalesTax returns a total amount that is equal to the sales amount plus the sales tax.

!To create a service called MathService that has a single method named SalesTax

1.Start Visual Studio, and create a new project.

a.In the New Project dialog box, select Visual C# Projects as the type.

b.Select ASP.NET Web Service as the template. You may need to scroll down to see ASP.NET Web Service.

c.In the Location box, type the name of the Web server, http://localhost/MathService. The grayed out Name box will now contain the text MathService. Then click OK.

2.On the View menu, click Code.

3.Because the XML Web service in this demonstration is simple, you can work on the code directly. For more complex XML Web services, you can use the Service1.asmx.cs Design palette that is displayed when you create a new project of type XML Web service. The Service1.asmx.cs Design palette enables the drag-and-drop operation of rapid application development that can make complex services easier to set up.

4.In the Service1 class, examine the HelloWorld method in the commentedout WEB SERVICE EXAMPLE.

42Module 13: Remoting and XML Web Services

5.In Service1.asmx.cs, implement the SalesTax method by inserting the following code after the comments for the HelloWorld method. You should leave the HelloWorld code commented out.

[WebMethod] public float SalesTax(

float salesAmount, float fractionalTaxRate) { return salesAmount +

(salesAmount * fractionalTaxRate);

}

6.On the Build menu, click Build Solution to create the XML Web service.

7.Use Internet Explorer to access the XML Web service at the following URL:

http://localhost/MathService/Service1.asmx

Tip To use Internet Explorer to view an XML Web service from within the

Visual Studio environment, right-click the .asmx file in the Solution

Explorer window, and then click View in Browser.

8.In the Internet Explorer page that is returned in step 7, click the link for the Service1 operation labeled SalesTax.

9.In the Internet Explorer page that is returned in step 8, enter some parameters, and then click Invoke to verify that the correct value is returned and displayed in SOAP/XML format.

10.Use Internet Explorer to access and verify that the XML Web service’s description is obtained from the following URL:

http://localhost/MathService/Service1.asmx?wsdl

Module 13: Remoting and XML Web Services

43

 

 

 

Consuming an XML Web Service

Topic Objective

To explain how XML Web services are consumed and how to use the Web Services Description Language tool.

Lead-in

In addition to providing technology that enables you to create XML Web services, the .NET Framework provides a sophisticated set of tools and code to consume XML Web services.

!To Consume a Web Service, Use Wsdl.exe

#Identify the object or service URI to be used

http://localhost/MathService/Service1.asmx

http://localhost/MathService/Service1.asmx

# Run Wsdl.exe on the service’s URI

wsdl http://localhost/MathService/Service1.asmx?wsdl wsdl http://localhost/MathService/Service1.asmx?wsdl

# Write the client code that calls the remote object

Service1 salesTaxService = new Service1(); Service1 salesTaxService = new Service1(); float totalAmount = salesTaxService.SalesTax( float totalAmount = salesTaxService.SalesTax(

amount,taxRate);

amount,taxRate);

# Build the client and proxy code

csc salestaxclient.cs service1.cs csc salestaxclient.cs service1.cs

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In addition to providing technology that enables you to create XML Web services, the .NET Framework provides a sophisticated set of tools and code to consume XML Web services. Consuming an XML Web service means accessing it as a client. Because XML Web services are based on open protocols, such as SOAP and HTTP, this client technology can also be used to consume XML Web services that are not built by using the .NET Framework.

Using the Web Services Description Language Tool

The .NET Framework SDK provides a tool that is called the Web Services Description Language tool (Wsdl.exe). You can use this tool to download the WSDL description of an XML Web service and create a proxy class that addresses this service. For XML Web services that are created by using ASP.NET, the proxy class is similar to the class that is defined in the .asmx file. However, the proxy class contains only methods with the [WebMethod] custom attribute.

An application that uses an XML Web service creates an instance of the service’s proxy class and invokes the service’s methods as it would with any local object. You compile and build your code with this proxy class included.

Alternatively, you can use features of the Visual Studio environment to build applications that consume XML Web services. These Visual Studio features are beyond the scope of this course.

44

Module 13: Remoting and XML Web Services

Delivery Tip

The use of the Web Services Description Language tool (Wsdl.exe) is covered in detail because the students will need this information to do Lab 13.2, Using an XML Web service. If you feel that students may benefit from a full demonstration, you can demonstrate the steps here.

The following process shows how to create a simple application that uses the XML Web service that is created in the Using Visual Studio to Create an XML Web service demonstration in this module.

!To use the Service1 Web Service

1.Identify the object and the service that should be used.

The Salestaxclient application will use the SalesTax method of the Service1 service whose URL is:

http://localhost/MathService/Service1.asmx

Note Typically a client uses an XML Web service that is located on a remote computer. If Service1 were located in a MathService virtual directory on a Web server named foo, the URL for the service would be:

http://foo/MathService/Service1.asmx

2.Run the WSDL tool, Wsdl.exe, and point it at the URL where the server object is located.

You can request that the Web Service Utility retrieves the schema and, from it, generates a source file that contains a proxy for the service’s class.

To generate a proxy for the Service1 class in a file named Service1.cs, type the following command in a Visual Studio .NET Command Prompt window:

wsdl http://localhost/MathService/service1.asmx?wsdl

Module 13: Remoting and XML Web Services

45

 

 

 

The proxy, Service1.cs, contains code similar to the following:

//...

using System.Diagnostics;

using System.Xml.Serialization; using System;

using System.Web.Services.Protocols; using System.ComponentModel;

using System.Web.Services; //...

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute! (Name="Service1Soap", Namespace="http://tempuri.org/")] public class Service1 : System.Web.Services.Protocols.SoapHttpClientProtocol { //...

public Service1() { this.Url =

"http://localhost/mathservice/service1.asmx";

}

//...

[System.Web.Services.Protocols.SoapDocumentMethodAttribute

!

("http://tempuri.org/SalesTax",

Use=System.Web.Services.Description.SoapBindingUse.Literal,

ParameterStyle=

System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Single SalesTax(System.Single salesAmount,

System.Single fractionalTaxRate) { object[] results =

this.Invoke("SalesTax",

new object[] {salesAmount, fractionalTaxRate});

return ((System.Single)(results[0]));

}

//...

46Module 13: Remoting and XML Web Services

3.Write the client code that calls the remote object. Create a text file named Salestaxclient.cs in the folder <install folder>\DemoCode\Mod13\ Demo13.2 containing the following code:

using System;

public class Class1 { public Class1() {}

public static int Main(string[] args) { Console.WriteLine("Enter Sales Amount:");

float amount = Single.Parse(Console.ReadLine()); Console.WriteLine(

"Enter Fractional Sales Tax Rate:");

float taxRate = Single.Parse(Console.ReadLine()); Service1 salesTaxService = new Service1();

float totalAmount = salesTaxService.SalesTax(amount,taxRate);

Console.WriteLine(

"Total: {0}",totalAmount.ToString()); return 0;

}

}

4.Build the client executable file by using the client code and proxy code. You must include references to the assemblies that are used by the client and proxy code.

5.To build Salestaxclient.exe, type the following command in a Visual Studio

.NET Command Prompt window:

csc salestaxclient.cs service1.cs

6. Run the client, and enter parameters as prompted.

Running Salestaxclient.exe produces output that should be similar to the following:

salestaxclient Enter Sales Amount: 100

Enter Fractional Sales Tax Rate:

.08

Total: 108

Соседние файлы в папке c#