Web
services return XML documents. An XML document is just a string, so you
can use any programming language to modify an XML document. In fact,
people use all kinds of languages — from Python and PHP to JavaScript —
to work with XML.
Of course, the .NET Framework provides extensive support for consuming XML and Web services, including the following:
Visual Studio generates proxy classes that allow you to use any Web service, like a local class.
ASP.NET generates the communication infrastructure necessary for accessing Web services.
1. Communicating with a Web service
Web services typically use a
special message format — SOAP — that allows you to send and receive Web
service requests over HTTP (the protocol of the Internet). Using SOAP
is important because it's independent of both language and platform.
You aren't limited to sending SOAP messages over HTTP. You can use SOAP with any transport protocol.
|
|
SOAP encapsulates the messages that you send to and get from your Web service in a SOAP
envelope. The SOAP request and response travels via a transport
protocol, such as HTTP. As long as you have access to HTTP, you can use
Web services. Think of SOAP as a delivery truck and HTTP as the
highway. The contents of the SOAP delivery truck is your XML document.
The SOAP
platform and language independence makes Web services great choices for
creating interfaces between disparate systems. For example, a
Linux-based application can offer data access via a Web service that's
consumed by an ASP.NET Web application.
ASP.NET takes care of
writing SOAP requests and responses and creating the XML messages for
you when working with simple requests. Complex requests will require
that you know how to work with SOAP. You don't need to learn any new
technical skills to start using Web services right away. To see an
example of the SOAP responses and requests generated by ASP.NET, just
run your Web service. Figure 8 shows an example of the SOAP messages generated for the HelloWorld method of the HelloWebService.
Web services aren't limited to using just SOAP messages. They can also use GET and POST requests, as explained in the earlier section "Testing Web services." GET and POST requests are part of the HTTP protocol. ASP.NET uses POST or SOAP,
depending on which protocol it thinks works best. To ensure that your
messages are always sent by using SOAP, add the following code to your
Web service's web.config file:
<webServices>
<protocols>
<remove name="HttpPost" />
<remove name="HttpGet" />
</protocols>
</webServices>
2. Finding Web services
You might not always be
consuming your own Web services. On the Web, you can find plenty of Web
services. Web services, including the ones you create with ASP.NET, use
two technologies to announce themselves to the world:
WSDL
is an XML document that describes the Web service, whereas UDDI is like
the Web services yellow pages. You don't have to list your Web service
with a UDDI directory, but you can if you want.
The WSDL tells the world (or
another developer, at least) what's needed to know to use your Web
service. Among other things, the WSDL provides information about the
following elements:
Namespaces:
List the services available in the namespace. The namespace
encapsulates the Web service's details by using the tags shown in the
following:
<wsdl:definitions targetNamespace=
"http://mycompany.com/webservices">
<wsdl:documentation>A web service that returns a Hello
World message</wsdl:documentation>
</wsdl:definitions>
Operations: Use the <portType> element to define the Web methods available in the service. The <message> element defines the Web methods parameters:
<wsdl:portType name="HelloWebServiceHttpGet">
<wsdl:operation name="HelloWorld">
<wsdl:documentation>
Returns a Hello message using the name supplied,
otherwise Hello World if name is null.
</wsdl:documentation>
<wsdl:input message="tns:HelloWorldHttpGetIn"/>
<wsdl:output message="tns:HelloWorldHttpGetOut"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:message name="HelloWorldHttpGetIn">
<wsdl:part name="name" type="s:string"/>
</wsdl:message>
<wsdl:message name="HelloWorldHttpGetOut">
<wsdl:part name="Body" element="tns:string"/>
</wsdl:message>
Types: Identify the data types used by the Web service with the <types> element, as shown in the following:
<wsdl:types>
<s:schema elementFormDefault=
"qualified" targetNamespace="http://mycompany.
com/webservices">
<s:element name="HelloWorld">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="name"
type="s:string"/>
</s:sequence>
</s:complexType>
</s:element>
<s:element name="HelloWorldResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1"
name="HelloWorldResult" type="s:string"/>
</s:sequence>
</s:complexType>
</s:element>
<s:element name="string" nillable="true" type=
"s:string"/>
</s:schema>
</wsdl:types>
Protocols: Use the <binding> element to define the message format, such as SOAP, and to set details for the port:
<wsdl:binding name="HelloWebServiceHttpGet" type="tns:
HelloWebServiceHttpGet">
<http:binding verb="GET"/>
<wsdl:operation name="HelloWorld">
<http:operation location="/HelloWorld"/>
<wsdl:input>
<http:urlEncoded/>
</wsdl:input>
<wsdl:output>
<mime:mimeXml part="Body"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
Services: Identify the collection of protocols available for use with the service:
<wsdl:service name="HelloWebService">
<wsdl:documentation>A web service that returns a Hello
World message</wsdl:documentation>
<wsdl:port name="HelloWebServiceSoap" binding="tns:
HelloWebServiceSoap">
<soap:address location="http://localhost:
4251/HelloWebService/HelloWebService.asmx"/>
</wsdl:port>
<wsdl:port name="HelloWebServiceSoap12" binding="tns:
HelloWebServiceSoap12">
<soap12:address location="http://localhost:4251/
HelloWebService/HelloWebService.asmx"/>
</wsdl:port>
<wsdl:port name="HelloWebServiceHttpGet" binding="tn
s:HelloWebServiceHttpGet">
<http:address location="http://localhost:4251/
HelloWebService/HelloWebService.asmx"/>
</wsdl:port>
</wsdl:service>
ASP.NET automatically creates a WSDL document for your Web service. To view the WSDL for your Web service, as shown in Figure 1, click Service Description on your Web service's test page.
UDDI provides a directory listing for your Web service. These are the three UDDI directories:
Green Pages: Lists services offered by the registrant
White Pages: Lists basic address information
Yellow Pages: Categorizes businesses based on standard industrial classifications
Many companies set
up UDDI directories within their organizations for internal consumption
only. This allows developers and other consumers of Web services to
easily see what services are available. Using Web services within your
organization is a great way to reuse code.
|
|
You can access a public UDDI directory at
http://soapclient.com/uddisearch.html
3. Using a Web service in your application
Visual Studio
provides excellent support for using a Web service in your application.
It doesn't matter what language was used to create the Web service.
When you reference the Web service in your application, Visual Studio
places a wrapper around the Web service that allows you to access the
Web service like it was your own code.
3.1. Adding a Web reference
To access a Web service in
your projects, you must add a Web reference. When you add a Web
reference, Visual Studio generates code — a proxy class — that you can use to access the Web reference.
To add a Web reference to a Web service, follow these steps:
Right-click the project and choose Add Web Reference.
The Add Web Reference window appears.
Type or paste the URL for a Web service in the URL text box.
Click the Go button.
The Web service appears in the window, as shown in Figure 2.
Click the Add Reference button.
The reference appears in Solution Explorer.
3.2. Binding with BindingSource
The BindingSource component is the preferred way to data-bind in Windows applications. You can use a Web service as a data source for a BindingSource component.
Here's how to use a Web service with a BindingSource:
Add a Web Reference to your Web service in your Windows project.
If
you're working with a Windows Form application, add the Web reference
as a Service Reference by right-clicking the solution and choosing Add
Service Reference. The process works precisely the same as the Web
reference discussed earlier.
Create a new instance of your Web service.
For example, to create a new instance of the HelloWebService, use the following in a Web application:
private localhost.HelloWebService ws = new localhost.
HelloWebService();
When working with a desktop application, use this following code instead:
private localhost.HelloWebServiceSoapClient ws = new localhost.
HelloWebServiceSoapClient();
Drag and drop a BindingSource component from the Data tab of the Toolbox onto your Windows Form.
Add your Web service as a data source for the BindingSource component by using the component's Add method.
For example, the following code adds HelloWebService to a BindingSource component:
this.bindingSource1.Add(ws.HelloWorld(this.txtEnterName.Text));
Set the BindingSource component as the source for a control's data binding.
For example, the following code data binds the BindingSource component to a label control's text property:
this.lblDisplayMessage.DataBindings.Add("Text", this.bindingSource1, "");
You can use the preceding code in a button's Click event to call the Web service. Listing 1 shows the entire code sample in a button's Click event.
Listing 1. Calling a Web Service in a Button's Click Event
private void button1_Click(object sender, EventArgs e) { this.bindingSource1.Add(ws.HelloWorld(this.txtEnterName.Text)); this.lblDisplayMessage.DataBindings.Add("Text", this.bindingSource1, ""); }
|
When a user clicks the button, the code calls the HelloWorld method of the HelloWebService. The name parameter is passed by using the value entered by a user in the txtEnterName text box. The return value appears in a label control called lblDisplayMessage.
3.3. Putting your Web service in a Web application
You can use Web services
in a Web application. Because ASP.NET creates a proxy class, you can
call your Web service just like you'd call any other bit of code.
To use a Web service in a Web application, follow these steps:
Add a Web reference to the Web service you wish to consume.
Create an instance of your Web service:
localhost.HelloWebService ws = new localhost.HelloWebService();
Call your Web service.
For example, the following code calls the HelloWebService and returns the results to a text box:
this.TextBox1.Text = ws.HelloWorld("Andrew");
You can see the results of this example in Figure 3.
3.4. Getting on the client side
You aren't limited to
just accessing Web services via server-side code. You can also use
client-side scripting languages, such as JScript, to call Web services.
Web services return an XML document, for which JScript provides excellent support. Listing 2 is a simple script and HTML page that tests the HelloWebService.
Listing 2. Simple Script and HTML Page That Tests the HelloWebService
<html> <head> <title>Test Web Service</title> <script type="text/jscript"> function callService() { var xmlDoc; var url;
xmlDoc = new ActiveXObject ("Msxml2.DOMDocument"); xmlDoc.onreadystatechange = function () { if (xmlDoc.readyState == 4) { displayText(xmlDoc); } }
url = "http://<servername>/HelloWebService/" + "HelloWebService.asmx/HelloWorld?name=" + document.getElementById("text1").value;
xmlDoc.load(url);
}
function displayText(xmlDoc) {
var currentNode; currentNode = xmlDoc.selectSingleNode("string");
document.getElementById("displayMessage"). innerHTML = currentNode.text;
}
</script> </head> <body> <form> Enter your name: <input id="Text1" type="text" name="name" /> <input id="Button1" type="button" value="button" onclick="callService()" /> <div id="displayMessage"></div> </form> </body> </html>
|
The script works only in
Internet Explorer because it uses an ActiveX control, which other
browsers don't support. You can find lots of scripts on the Web for
manipulating XML with JScript.
You should definitely take a closer look at the XMLHTTPRequest object. This object allows you to send GET and POST requests to a Web server. Best of all, it works without causing the browser to refresh. The XMLHTTPRequest object is at the heart of the Web development methodology called AJAX.
|
|