How To: Consume Web Services in ASP.NET

I've been meaning to write this tutorial for a month now and finally i found time to write it. As you may have noticed, I have been blogging about accessing files (here, here and here), reading XML, and loading XML data to a GridView lately. The reason behind this is that I am preping you guys up for a much larger article that would span to 5 articles with different demos for each post... something that needs to spend a little bit of time on the lower end of the grid to make the whole thing easier to explain once we start building the big picture... but I won't spill the details about the post yet ;) so better keep up with the site to learn what I've been brewing since early March.

In the meantime let's talk about how to consume XML Web Services in ASP.NET. I don't want to bore you with explanations on what an XML Web Service means so I'll just lead you to a document written by Roger Wolter in 2001 that explains the whole enselada about Web Services. Below is an excerpt from that document:

XML Web services are the fundamental building blocks in the move to distributed computing on the Internet. Open standards and the focus on communication and collaboration among people and applications have created an environment where XML Web services are becoming the platform for application integration. Applications are constructed using multiple XML Web services from various sources that work together regardless of where they reside or how they were implemented.

There are probably as many definitions of XML Web Service as there are companies building them, but almost all definitions have these things in common:

  • XML Web Services expose useful functionality to Web users through a standard Web protocol. In most cases, the protocol used is SOAP.
  • XML Web services provide a way to describe their interfaces in enough detail to allow a user to build a client application to talk to them. This description is usually provided in an XML document called a Web Services Description Language (WSDL) document.
  • XML Web services are registered so that potential users can find them easily. This is done with Universal Discovery Description and Integration (UDDI).

Now that we have nailed the basic definition let's build a simple application that consumes a publicly available web service. There are a lot of sites that list useful public web services and one of those sites is WebServiceX. WebServiceX's website contains 70+ freely available web service that you can use and utilize in your projects. For this demo I've decided to use the StockQuote service which is a web service that allows you to query stock information by using the symbol of the stock. Here's some information about the service taken from their website:

Summary: Get Stock quote for a company symbol by using this web service
Endpoint:
http://www.webservicex.net/stockquote.asmx
Disco: http://www.webservicex.net/stockquote.asmx?Disco
WSDL Location: http://www.webservicex.net/stockquote.asmx?wsdl

Let's begin building!

First, let's start by creating a new ASP.NET Website Project

Once that's done we need to add a Web Reference to our project that would point to the StockQuote service hosted on the WebServiceX website. We can do this by right-clicking on our solution and then selecting the Web Reference menu item.

A new screen will appear that will enable you to specify the URL of the web service. Input http://www.webservicex.net/stockquote.asmx on the URL dropdownlist to create reference to the StockQuote service.

Click "Add Reference" to add the reference to the project. You'll notice that the folder structure of your project has been updated and a new folder called "App_WebReferences" has been added to the project.

Ok, now let's build our UI. My idea for this sample application is to have a TextBox that allows users to enter the symbol, a Button control that will trigger the lookup to the web service via it's Click event and a Label control that will used to display the values returned by the web service. Below is how I envisioned our form to look-like:

And here's the accompanying HTML source for our form

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Keith Rull's Consuming Web Services Sample</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <strong>Symbol</strong><br />
            <asp:TextBox ID="symbolTextBox" 
                         runat="server" />
            <asp:Button ID="executeButton" 
                        runat="server" 
                        Text="Execute"
                        OnClick="executeButton_Click" />
            <br />
            <br />
            <strong>Result</strong>
            <br />
            <asp:Label ID="xmlResultLabel" 
                        runat="server" />
        </div>
    </form>
</body>
</html>

Now that we have the infrastructure in place it's time to write some code. The first thing that we need to do on the code-behind level is to add the using declaration to include the web service class in our page.

This enables us to create objects from our web service. The class that we would be using in this exercise is the StockQuote object which has the StockQuote.GetQuote method that returns the XML data containing the information for a specified symbol. Below is the method I wrote to show you how to use this class:

    /// <summary>
    /// A function that retrieves the stock information
    /// from the StockQuote web service
    /// </summary>
    /// <param name="executionSymbol">the execution symbol to lookup</param>
    /// <returns>The string containing the XML information regarding the symbol</returns>
    private string GetStockQuoteInformation(string executionSymbol)
    {
        string quoteInfo = String.Empty;

        //check if the executionSymbol is not blank
        if (String.IsNullOrEmpty(executionSymbol)) {
            //stop the processing
            return quoteInfo;
        }

        try
        {
            //create a StockQuote object
            StockQuote quote = new StockQuote();

            //get the stock quote information for the specified symbol
            quoteInfo = quote.GetQuote(executionSymbol);
        }
        catch (Exception ex) {
            //raise the error
            string errorMessage = String.Format("Error while trying to connect to the Web Service. {0}", ex.Message);
            throw new Exception(errorMessage);
        }

        //return the quote information
        return quoteInfo;
    }

Now that we have the function that will call our web service it's time to hook up our method to the Click event of our button.

    protected void executeButton_Click(object sender, EventArgs e)
    {
        //get the execution symbol entered in the TextBox
        string executionSymbol = symbolTextBox.Text;

        //get the stock quote information
        string quoteInfo = GetStockQuoteInformation(executionSymbol);

        //HtmlEncode the string to properly render it on the page
        string htmlEncodedResult = System.Web.HttpUtility.HtmlEncode(quoteInfo);
        
        //assign the HtmlEncoded string to our Label control
        xmlResultLabel.Text = htmlEncodedResult;
    }

As you can see the whole process was built with little code. Run the application and see how the easy it is to connect to a web service, call a web service method and use it's returned value.

I hope you learned something from this tutorial. On our next article i'll show you howto display the XML returned by the web service to a GridView.

Later ;)


Posted Apr 08 2008, 03:13 PM by keithrull

Comments

marl wrote re: How To: Consume Web Services in ASP.NET
on 04-09-2008 12:07 AM

Tamang-tama makakatulong sa akin ito. This will help me more understand what Lynn Langit has presented about Web Services at Heroes happen {here} event in Anaheim, CA (I will blog about this event some other time)

trashVin wrote re: How To: Consume Web Services in ASP.NET
on 04-11-2008 8:47 PM

hi keith , ive been using web services in VS2005 but VS2008 now makes use of the Service Reference , but if you dig dipper to the dialog box  you could still add Web reference for compatibility with 2.0 apps . Does it mean that some web services made before the  VS2008 era may be incompatible with the Add Service Reference method that is why they kept the Add Web Reference for compatibility?

web service companies wrote re: How To: Consume Web Services in ASP.NET
on 04-16-2008 4:14 AM

You can dig more information about the web services here....

private label soap wrote private label soap
on 04-26-2008 3:44 PM

Pingback from  private label soap

kran wrote re: How To: Consume Web Services in ASP.NET
on 11-23-2008 1:03 PM

this was really useful,thanks!

keithrull wrote re: How To: Consume Web Services in ASP.NET
on 11-24-2008 9:22 AM

@trashvin: Nope, web services created prior to VS2008 are still compatible. The difference is how you use them. Add Web reference is designed for legacy services while Service Reference is use for newer service types more specifically WCF. You can use Service Reference for older services but you wont be able to use Add Reference for WCF unless the service binding is basichttpbinding.

Add a Comment

(required)  
(optional)
(required)  
Remember Me?

Enter the numbers above:

Copyright DevPinoy 2005-2008