Wednesday, October 19, 2011

Consuming a Simple Web Services

This blog leads you through the process of consuming a simple web service. In it we will find a web service that provides global weather reports based on city and country and we will reference that web service in our own ASP.Net form and create our own little app that uses it.

Go to this url to get Free web services: http://www.webservicex.net/WS/wscatlist.aspx

Click on global weather

Click on get weather

Copy WSDL Schema Location http://www.webservicex.net/globalweather.asmx?WSDL

Open Visual Studio

Create a new website

Go to the Website menu, And select add web reference

Paste the schema location in the URL text box

Change the name of the web service name to net.globalweather.www

Add the web service add a labels and textboxes for city name and country and a button and a label to the web 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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Global Weather</h1>
      <p> 
         <asp:Label ID="Label2" runat="server" Text="Enter City"> 
        </asp:Label><asp:TextBox ID="txtCity" runat="server"></asp:TextBox> 
      </p>
      <p>
        <asp:Label ID="Label3" runat="server" Text="Enter Country">
        </asp:Label><asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
      </p>
      <p>
        <asp:Button ID="Button1" runat="server" Text="Get Weather" />
       </p>
       <p>
        <asp:Label ID="lblWeather" runat="server" Text="Label"></asp:Label>
        </p>
    </div>
    </form>
</body>
</html>

Double click the buttom in design mode to get to the C# code window

In the buttonI_click method enter the following code

 protected void Button1_Click(object sender, EventArgs e)
 {
     GlobalWeather gw = new GlobalWeather();
     string weather = gw.GetWeather(txtCity.Text, txtCountry.Text);
     lblWeather.Text = weather;
 }

Note how little code it takes to process this. The web service tells you when you add it that this method requires two string arguments (city and country) and that it returns a string. Some webservices can be more complex, but most are fairly straight forward to use

Here is a picture of the form running

2 comments: