"Knowledge has to be improved, challenged, and increased constantly, or it vanishes."

Include weather information in ASP.Net site from weather.com services

In this article, I am going to demonstrate how you can use the XMLOAP services (referred as XOAP from here onwards) provided by weather.com to display the weather information in your website. The XOAP services are available to be used for free of charge, provided you are comply with requirements from weather.com. I am writing this article from a technical point of view. If you are planning to use weather.com XOAP services in your application, please refer to the terms and conditions from weather.com website.

In order to start using the XOAP services, you need to sign up the XOAP datafeed. The signing process is simple, you simply browse the url http://www.weather.com/services/xmloap.html. The URL looks similar to the following.

clip_image002

Click on the sign up button, you will reach the registration page. Here you need to specify the site name you need to use this feed for. The form looks similar to the following.

clip_image003

Once you fill all the mandatory information, click on save and continue button. That’s it. The registration is over. You will receive an email that contains your partner id, license key and SDK. The SDK available in a zipped format, contains the terms of use and documentation about the services available. Other than this the SDK includes the logos and icons required to display the weather information.

As per the SDK, currently there are 2 types of information available through XOAP. These services are

  1. Current Conditions for over 30,000 U.S. and over 7,900 international Location IDs
    • Updated at least Hourly
  2. Five-Day Forecast (today + 4 additional forecast days in consecutive order beginning with tomorrow) for over 30,000 U.S. and over 7,900 international Location IDs
    • Updated at least Three Times Daily

The SDK provides detailed information about the fields included in response of each service. Additionally there is a refresh rate that you need to comply with. As per the SDK, the refresh rate means the following

“Refresh Rate” shall mean the maximum frequency with which you may call the XML Feed for a given LocID requesting a data set for that LocID. During the time period in between refresh periods the data must be cached by you either in the memory on your servers or in Your Desktop Application.

About the Services

Weather.com will provide you with access to the XML Feed over the Internet through the hostname xoap.weather.com. The weather data from the XML feed must be requested for a specific location. So you need a location ID (LOC ID). The XML feed work with 2 types of location IDs. First one is with City Identifiers and second one is using 5 Digit US postal codes. If you do not know your location ID, don’t worry, there is a location id search service available for you to retrieve the location id from city name. Since I am a resident in the Kingdom of Bahrain, I am going to retrieve the weather information for Manama(the capital of Bahrain) . In order to get the location ID for Manama, type the following URL in your address bar.

http://xoap.weather.com/search/search?where=manama

I got the following XML output.

<?xml version="1.0" encoding="UTF-8"?>
<!-- This document is intended only for use by authorized licensees of The –>
<!-- Weather Channel. Unauthorized use is prohibited. Copyright 1995-2011, –>
<!-- The Weather Channel Interactive, Inc. All Rights Reserved. –>
<search ver="3.0">
      <loc id="BAXX0001" type="1">Al Manama, Bahrain</loc>
</search>

You can try this with any city name, if the city is available, it will return the location id, and otherwise, it will return nothing.

In order to get the weather information, from XOAP,  you need to pass certain parameters to the XOAP service. A brief about the parameters are as follows. Please refer SDK for more details.

Parameter name

Possible Value

cc

Optional, if you include this, the current condition will be returned. Value can be anything, as it will be ignored

e.g. cc=*

dayf

If you want the forecast for 5 days, specify dayf=5

This is optional

iink

Value should be XOAP

par

Your partner id. You can find this in your registration email from weather.com

prod

Value should be XOAP

key

The license key assigned to you. This will be available in the registration email

unit

s or m (standard or matric or you can think of Celsius/Fahrenheit)

this is optional field, if not specified the unit will be standard(s)

The URL host for the XOAP service is http://xoap.weather.com.

So for my purpose, I need the following request to be made to access the XOAP services.

http://xoap.weather.com/weather/local/BAXX0001?cc=*&link=xoap&prod=xoap&par=*********&key=**************

(The ***** to be replaced with the corresponding alternatives)

The response XML have a root element “weather”. Under the root element, it has the following sections

<head> - the meta data information about the weather results returned.

<loc> - the location data block that provides, the information about the location for which the wheather data is retrieved.

<lnks> - the 4 promotional links you need to place along with the weather display. Additional to these 4 links, there should be another link with weather channel logo to the home page of weather.com.

<cc> - the current condition data. This element will be there only if you specify the cc element in the request.

<dayf> - the forcast data as you specified. This element will be there only if you specify the dayf in the request.

In this walkthrough, I am going to capture the weather information for Manama (Location ID: BAXX0001). You need 2 applications to display weather information in your website.

  • A Console application that retrieves data from the XMLOAP and store in the SQL Server database (or any data store as you prefer).This application will be scheduled to execute in every 25 minutes using windows task scheduler, so that we can comply with the refresh rate.
  • A web application that display data from the SQL Server database

Retrieve the Weather from XOAP

I have created a console application named, Weather Service. I created a SQL server database, with the following columns. I named the table as tblweather. You are free to choose any name.

Column name

Description

lastUpdated

Datetime, this is the last time when the weather data is updated. This is the time of the service running

TemparatureDateTime

The date and time returned by XML feed

Temparature

The temperature returned by the XML feed.

TemparatureUnit

The unit of the temperature returned by the XML feed

iconId

The id of the icon to be used. Currently 48 icons from 0 to 47 are available.

WeatherDescription

The Weather Description Phrase returned by the feed.

Link1url

The url to the first promo link

Link1Text

The text for the first promo link

Link2url

The url to the second promo link

Link2Text

The text for the second promo link

Link3url

The url to the third promo link

Link3Text

The text for the third promo link

Link4url

The url to the fourth promo link

Link4Text

The text for the fourth promo link

Every time when the service runs, the application will update the database columns from the XOAP data feed. When the application starts, It is going to get the data as XML from the url. This demonstration uses LINQ to extract the necessary data from the fetched XML. The following are the code segment for extracting data from the weather XML using LINQ.

// first, create an instance of the XDocument class with the XOAP URL. replace **** with the corresponding values.

XDocument weather = XDocument.Load("http://xoap.weather.com/weather/local/BAXX0001?cc=*&link=xoap&prod=xoap&par=***********&key=c*********");

// construct a query using LINQ

var feedResult = from item in weather.Descendants()

select new

{

unit = item.Element("head").Element("ut").Value,

temp = item.Element("cc").Element("tmp").Value,

tempDate = item.Element("cc").Element("lsup").Value,

iconId = item.Element("cc").Element("icon").Value,

description = item.Element("cc").Element("t").Value,

links = from link in item.Elements("lnks").Elements("link")

select new

{

url = link.Element("l").Value,

text = link.Element("t").Value

}

};

// Load the root node to a variable, you may use foreach construct instead.

var item1 = feedResult.First();

*If you want to learn more about LINQ and XML, read this nice blog from Scott GU.

http://weblogs.asp.net/scottgu/archive/2007/08/07/using-linq-to-xml-and-how-to-build-a-custom-rss-feed-reader-with-it.aspx

Now you have all the required values in item1. For e.g. if you want to get the temperature, use item1.temp;

Now I just need to execute an SQL query against the database. See the connection part.

using (SqlConnection conn = new SqlConnection(@"Data Source=sreeju\sqlexpress;Initial Catalog=Sample;Integrated Security=True"))

{

string strSql = @"update tblweather set lastupdated=getdate(), temparatureDateTime = @temparatureDateTime,

temparature=@temparature, temparatureUnit=@temparatureUnit, iconId = @iconId,

description=@description, link1url=@link1url, link1text=@link1text,

link2url=@link2url, link2text=@link2text,link3url=@link3url,

link3text=@link3text,link4url=@link4url, link4text=@link4text";

SqlCommand comm = new SqlCommand(strSql, conn);

comm.Parameters.AddWithValue("temparatureDateTime", item1.tempDate);

comm.Parameters.AddWithValue("temparature", item1.temp);

comm.Parameters.AddWithValue("temparatureUnit", item1.unit);

comm.Parameters.AddWithValue("description", item1.description);

comm.Parameters.AddWithValue("iconId", item1.iconId);

var lstLinks = item1.links;

comm.Parameters.AddWithValue("link1url", lstLinks.ElementAt(0).url);

comm.Parameters.AddWithValue("link1text", lstLinks.ElementAt(0).text);

comm.Parameters.AddWithValue("link2url", lstLinks.ElementAt(1).url);

comm.Parameters.AddWithValue("link2text", lstLinks.ElementAt(1).text);

comm.Parameters.AddWithValue("link3url", lstLinks.ElementAt(2).url);

comm.Parameters.AddWithValue("link3text", lstLinks.ElementAt(2).text);

comm.Parameters.AddWithValue("link4url", lstLinks.ElementAt(3).url);

comm.Parameters.AddWithValue("link4text", lstLinks.ElementAt(3).text);

conn.Open();

comm.ExecuteNonQuery();

conn.Close();

Console.WriteLine("database updated");

}

Now click ctrl + f5 to run the service. I got the following output

clip_image004

Check your database and make sure, the data is updated with the latest information from the service. (Make sure you inserted one row in the database by entering some values before executing the service. Otherwise you need to modify your application code to count the rows and conditionally perform insert/update query)

Display the Weather information in ASP.Net page

Now you got all the data in the database. You just need to create a web application and display the data from the database. I created a new ASP.Net web application with a default.aspx page.

In order to comply with the terms of weather.com, You need to use Weather.com logo along with the weather display. You can find the necessary logos to use under the folder “logos” in the SDK. Additionally copy any of the icon set from the folder “icons” to your web application. I used the 93x93 icon set. You are free to use any other sizes available.

The design view of the page in VS2010 looks similar to the following.

clip_image005

The page contains a heading, an image control (for displaying the weather icon), 2 label controls (for displaying temperature and weather description), 4 hyperlinks (for displaying the 4 promo links returned by the XOAP service) and weather.com logo with hyperlink to the weather.com home page. I am going to write code that will update the values of these controls from the values stored in the database by the service application as mentioned in the previous step.

Go to the code behind file for the webpage, enter the following code under Page_Load event handler.

using (SqlConnection conn = new SqlConnection(@"Data Source=sreeju\sqlexpress;Initial Catalog=Sample;Integrated Security=True"))

{

SqlCommand comm = new SqlCommand("select top 1 * from tblweather", conn);

conn.Open();

SqlDataReader reader = comm.ExecuteReader();

if (reader.Read())

{

lblTemparature.Text = reader["temparature"].ToString() + "&deg;" + reader["temparatureUnit"].ToString();

lblWeatherDescription.Text = reader["description"].ToString();

imgWeather.ImageUrl = "icons/" + reader["iconId"].ToString() + ".png";

lnk1.Text = reader["link1text"].ToString();

lnk1.NavigateUrl = reader["link1url"].ToString();

lnk2.Text = reader["link2text"].ToString();

lnk2.NavigateUrl = reader["link2url"].ToString();

lnk3.Text = reader["link3text"].ToString();

lnk3.NavigateUrl = reader["link3url"].ToString();

lnk4.Text = reader["link4text"].ToString();

lnk4.NavigateUrl = reader["link4url"].ToString();

}

conn.Close();

}

Press ctrl + f5 to run the page. You will see the following output.

clip_image006

That’s it. You need to configure the console application to run every 25 minutes so that the database is updated.

Also you can fetch the forecast information and store those in the database, and then retrieve it later in your web page. Since the data resides in your database, you have the full control over your display. You need to make sure your website comply with weather.com license requirements.

If you want to get the source code of this walkthrough through the application, post your email address below.

Hope you enjoy the reading.

16 Comments

Comments have been disabled for this content.