Retrieving Weather Information

Each day millions of web users look up weather information. Across the Web, some of the fastest growing websites provide specifics about weather. The HTML file ShowWeather.html, which you can find at this book’s companion website, creates a form that prompts the user to enter a zip code, city and state, or an Internet protocol (IP) address. After the user enters the data and clicks the Submit button, the user’s browser sends the user input to an ASP.NET page that uses a Web service residing on the ServiceObjects website. The FastWeather web service will provide the ASP.NET page with weather data for a specific location. After the ASP.NET page receives the data from the service, it will display the result, as shown in Figure 1.3.

click to expand
Figure 1.3: Using a web service to obtain weather data


The ServiceObjects website provides several powerful web services you can immediately integrate into your applications. Take time now to visit the site at

Looking Behind the Scenes at the FastWeather Web Service

To use the FastWeather web service, programs can call one of three methods (functions), passing to the methods the corresponding parameters:

string GetWeatherByIP(string IP, string LicenseKey) string GetWeatherByCityState(string City, string State, string LicenseKey) string GetWeatherByZip(string Zip, string LicenseKey)

Each of the functions, if successful (meaning the program provided a valid IP address, zip code, or city and state combination), will return a structure of type Weather that contains the following fields:

Weather    string LastUpdated    string TemperatureF    string WindChill    string HeatIndex    string Humidity    string Dewpoint    string Wind    string Pressure    string Conditions    string Visibility    string Sunrise    string Sunset    string City    string State    string Moonrise    string Moonset    string Error

Note also that each of the FastWeather web service methods requires that you pass a parameter that specifies your license key. If you visit the ServiceObjects website, you can download a trial key that lets you use the service for a specific period of time. If you need unlimited use of the service, you must purchase a license for service from ServiceObjects. The GetWeather.aspx ASP.NET page uses the license key 0, which provides limited use of the service.

The source code in Listing 1.1 implements the ASP.NET page GetWeather.aspx.

Listing 1.1 GetWeather.aspx

start example
Public Class WebForm1     Inherits System.Web.UI.Page #Region " Web Form Designer Generated Code "     ' Code not shown. #End Region Private Sub Page_Load(ByVal sender As System.Object, _ Ä   ByVal e As System.EventArgs) Handles MyBase.Load   Dim Zip, City, State, IP As String   Dim WebError As Boolean = False   Dim QueryPerformed As Boolean = True   Zip = Request.Form("ZipCode")   City = Request.Form("City")   State = Request.Form("State")   IP = Request.Form("IP")   Dim WeatherRequest As New   Dim Weather As   Try     If (Zip <> "") Then       Response.Write("Weather conditions for " & Zip)       Weather = WeatherRequest.GetWeatherByZip(Zip, 0)     ElseIf (City <> "") And (State <> "") Then       Response.Write("Weather conditions for " & City & _ Ä          " " & State)       Weather = WeatherRequest.GetWeatherByCityState(City, _ Ä           State, 0)     ElseIf (IP <> "") Then       Response.Write("Weather conditions for " & IP)         Weather = WeatherRequest.GetWeatherByIP(IP, 0)     Else       Response.Write("Must specify valid location")         QueryPerformed = False     End If    Catch Ex As Exception      Response.Write("Web service error: " & Ex.Message)      WebError = True    End Try    If (Not WebError And QueryPerformed) Then      If (Weather.Error = "") Then        Response.Write("<br/>")        Response.Write("Temperature (F): " & _        Weather.TemperatureF & "<br/>")        Response.Write("Conditions: " & Weather.Conditions)      Else        Response.Write("<br/>")        Response.Write("Web service returned an error: " & _ Ä         Weather.Error)      End If    End If End Sub End Class
end example

As you can see, the code first uses the Request object to determine the values the user assigned to the zip code, city, state, or IP fields. To use a web service, a program must create an object specific to the service. The following statement creates a variable named WeatherRequest that corresponds to the FastWeather service:

Dim WeatherRequest As New

Throughout this chapter, you will create similar objects for the different web services. The object name, in this case, identifies the web service. As you will see when you create a C# program that uses the FastWeather web service, Visual Studio .NET makes it easy for you to determine the object name.

As discussed, the FastWeather web service returns a value of type Weather that contains the individual weather fields. The following statement defines a variable to store the Weather structure:

Dim Weather As

To use a web service, you simply call one of the methods the service provides. In this case, the code uses an If-Else statement to determine which method to call based on whether the user specified a zip code, city and state, or IP address. The following statement, for example, calls the service’s GetWeatherByZipCode method:

Weather = WeatherRequest.GetWeatherByZip(Zip, 0)

Note that the code calls the web service methods within a Try-Catch block. Most web services will generate an exception when an error occurs. When your programs call a web service, they should always do so within a Try-Catch block so your code can detect and respond to an exception generated by the service.

The application uses an ASP.NET page, as opposed to an active server page, because of the ease with which Visual Studio .NET lets developers integrate a web service.

Retrieving Weather Information within a C# Program

Web services exist to help programmers integrate web-based operations into their programs. The Visual Basic .NET program, TexasWeather.vb, displays a form that contains buttons corresponding to Texas cities. After the user clicks a button, the program displays the corresponding weather data, as shown in Figure 1.4.

Figure 1.4: Using the FastWeather web service within a Visual Basic .NET program

In this case, the program uses only the FastWeather service’s GetWeatherByCityState method. To create the TexasWeather.vb program, perform these steps:

  1. Within Visual Studio .NET, select the File menu New Project option. Visual Studio .NET will display the New Project dialog box.

  2. Within the New Project dialog box Project Types list, click Visual C# Projects. Then, within the Templates field, click Windows Application. Finally, within the Location field, specify the folder within which you want to store the program and the program name TexasWeather. Select OK. Visual Studio .NET will display a form onto which you can drag and drop the program’s controls (label, buttons, and text box).

  3. Using the Toolbox, drag and drop the label, buttons, and text box previously shown in Figure 1.4 onto the form.

  4. To use a web service, you must assign a Web Reference to the program that corresponds to the object. To do so, select the Project menu Add Web Reference option. Visual Studio .NET will display the Add Web Reference dialog box, as shown in Figure 1.5.


    Over time, the URLs this book uses (such as the one in Step 5) for the WSDL (web service definition language) files that describe a web service may change. See the section “Using a Web Service 101” to determine the URL you should enter for a service’s WSDL file within the Add Web Reference dialog box.

    click to expand
    Figure 1.5: The Add Web Reference dialog box

  5. Within the Address field, you must type the URL of a special file (called the WSDL file) that describes the web service. In this case, type and press Enter. The dialog box will load the file’s contents. Click the Add Reference button.

  6. Select the View menu Code option. Visual Studio .NET will display the program’s source code. Within the source code (near the bottom of the GetWeather class definition), add the following program statements:

    private void GetWeather(String City, String State) {    Boolean WebError = false; WeatherRequest; Weather = null;    WeatherRequest = new;    try    {      Weather = WeatherRequest.GetWeatherByCityState(City, _ Ä              State, "0");    }    catch (Exception Ex)    {      textBox1.Text = "Web service error: " + Ex.Message;      WebError = true;    }    if (! WebError)    {      if (Weather.Error == null)      {        textBox1.Text = "Location: " + Weather.City + "\r\n";        textBox1.Text = "Temperature (F): " + _ Ä          Weather.TemperatureF + "\r\n";        textBox1.Text += "Conditions: " + _ Ä       Weather.Conditions + "\r\n";        textBox1.Text += "Dewpoint: " + Weather.Dewpoint + "\r\n";        textBox1.Text += "Heat Index: " + _ Ä          Weather.HeatIndex + "\r\n";        textBox1.Text += "Humidity: " + Weather.Humidity + "\r\n";        textBox1.Text += "Moon rise: " + Weather.Moonrise + _ Ä          "\r\n";        textBox1.Text += "Moon set: " + Weather.Moonset + "\r\n";        textBox1.Text += "Pressure: " + Weather.Pressure + "\r\n";        textBox1.Text += "Sun rise: " + Weather.Sunrise + "\r\n";        textBox1.Text += "Sun set: " + Weather.Sunset + "\r\n";        textBox1.Text += "Visibility: " + Weather.Visibility + _ Ä          "\r\n";        textBox1.Text += "Wind: " + Weather.Wind + "\r\n";        textBox1.Text += "Wind chill: " + Weather.Windchill;      }      else        textBox1.Text = "Web service returned an error: " + _ Ä          Weather.Error;    } } private void Form1_Load(object sender, System.EventArgs e) { } private void button1_Click(object sender, System.EventArgs e) {    GetWeather("Dallas", "TX"); } private void button2_Click(object sender, System.EventArgs e) {    GetWeather("Houston", "TX"); } private void button3_Click(object sender, System.EventArgs e) {    GetWeather("San Antonio", "TX"); } private void button4_Click(object sender, System.EventArgs e) {    GetWeather("Waco", "TX"); } } }

The program provides an event handler that responds to each user button click. Within each handler, the code calls the GetWeather function, passing to the function the name of a specific city and the TX state abbreviation. Within the GetWeather function, the following statements create an object named WeatherRequest that the program will use to access the FastWeather web service: WeatherRequest; WeatherRequest = new;

Again, the FastWeather web service returns a value of type Weather. The following statement creates a variable that will hold the specific weather fields: Weather = null; 

The program calls the web service method GetWeatherByCityState within a try-catch block to detect any exceptions the web service may generate:

try {   Weather = WeatherRequest.GetWeatherByCityState(City, _ Ä     State, "0"); }  catch (Exception Ex) {   textBox1.Text = "Web service error: " + Ex.Message;      WebError = true; }

Finally, if the web service is successful, the code displays the various weather elements within a text box.

. NET Web Services Solutions
.NET Web Services Solutions
ISBN: 0782141722
EAN: 2147483647
Year: 2005
Pages: 161
Authors: Kris Jamsa © 2008-2017.
If you may any questions please contact us: