WEBSITE

Consuming a Web Service

9/27/2010 5:44:29 PM
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: Web Services Description Language

  • UDDI: Universal Discovery Description and Integration

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.

Figure 1. Click Service Description to view the WSDL document for your Web service.

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:

  1. Right-click the project and choose Add Web Reference.

    The Add Web Reference window appears.

  2. Type or paste the URL for a Web service in the URL text box.

  3. Click the Go button.

    The Web service appears in the window, as shown in Figure 2.

  4. Click the Add Reference button.

    The reference appears in Solution Explorer.

Figure 2. Use the Add Web Reference window to add a Web service to your project.

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:

  1. 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.

  2. 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();

  3. Drag and drop a BindingSource component from the Data tab of the Toolbox onto your Windows Form.

  4. 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));

  5. 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:

  1. Add a Web reference to the Web service you wish to consume.

  2. Create an instance of your Web service:

    localhost.HelloWebService ws = new localhost.HelloWebService();

  3. 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.

Figure 3. Consuming a Web service in a Web application.

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.


Other  
 
Most View
Windows Sever 2003 : Implementing a DNS Name Resolution Strategy
The New ASUS ET2300INTI All-In-One (AIO) PC - The Next Level
Apply Filters In Twitter
ASP.NET 4 in VB 2010 : The XML Classes (part 2) - The XML Text Reader
Naim Unitilite One Box System - Lite source (Part 2)
VocaLive For iOS - Sing Like You're Winning
Samsung Galaxy Camera - An Android Compact 21X Shooter (Part 3)
Grouptest Headphones: $150-$210 - Phone Home (Part 2) - DT - 440
Multimedia: Tips and Tricks – Feb 2013 (Part 2)
GeForce GTX 680 v.s Radeon HD 7970: The Final, Silent Showdown (Part 1)
Top 10
Sharepoint 2013 : Farm Management - Disable a Timer Job,Start a Timer Job, Set the Schedule for a Timer Job
Sharepoint 2013 : Farm Management - Display Available Timer Jobs on the Farm, Get a Specific Timer Job, Enable a Timer Job
Sharepoint 2013 : Farm Management - Review Workflow Configuration Settings,Modify Workflow Configuration Settings
Sharepoint 2013 : Farm Management - Review SharePoint Designer Settings, Configure SharePoint Designer Settings
Sharepoint 2013 : Farm Management - Remove a Managed Path, Merge Log Files, End the Current Log File
SQL Server 2012 : Policy Based Management - Evaluating Policies
SQL Server 2012 : Defining Policies (part 3) - Creating Policies
SQL Server 2012 : Defining Policies (part 2) - Conditions
SQL Server 2012 : Defining Policies (part 1) - Management Facets
Microsoft Exchange Server 2010 : Configuring Anti-Spam and Message Filtering Options (part 4) - Preventing Internal Servers from Being Filtered