WP7: Checking Weather Forecast Using YQL

I touched upon yahoo query language (YQL) interface in my last post. Today, I will show some quick practical uses of YQL and demonstrate how easy it is for the programmers to tap into this information.

For today’s example, we will examine the table named ‘weather.forecast’, which is available in the YQL interface.

Head over to the YQL Console to examine the parameters to be used for ‘weather.forecast’.

yql_weather_forecast_1

As shown in the screenshot, there is one parameter named ‘location’ that is required for querying data from this table.

The complete URL would look like below:

http://query.yahooapis.com/v1/public/yql?q=%20SELECT%20*%20FROM%20weather.forecast%20WHERE%20location%3D%2263126%22%20%20&diagnostics=true

Windows Phone Application

Create a new ‘Windows Phone Application’ project in Visual Studio.

New_Windows_Phone_Application

Preparing the User Interface

The user will provide the location for which the weather forecast is to be displayed as input.

For this, I added a horizontal StackPanel with a TextBox and a Button into the MainPage.xaml.

For displaying the results, I used a WebBrowser control, as some of the data for ‘weather.forecast’ is returned as HTML.

The XAML listing for the UI is here:

Getting data from YQL

The user enters the zip code for which weather forecast has to be displayed and press on ‘GO’ button.

The program takes this location, construct the correct URL and make a web request to retrieve the data from the internet.

WeatherWatch_1

Windows Phone SDK provides two options to make a web request and get data from the internet, WebClient and HTTPWebRequest. See here for more information.

For this example, I used the WebClient API for it’s inherent simplicity as this is a post more to demonstrate the YQL than about performance.

Since the program did not specify a output format, JQL returns XML by default. The output format can be specified as JSON by adding  parameter to the original URL.

http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20weather.forecast%20WHERE%20location%3D%2263126%22%20%20&format=json&diagnostics=true

Parsing the XML is made simpler by the XDocument class provided in the System.Xml.Linq namespace.

Displaying the results

WebClient returns data on the same thread, so it can directly access the UI elements. On the other hand, HTTPWebRequest returns data on a different thread and the result has to be marshaled back to the UI thread. Since data is returned on a different thread, HTTPWebRequest has the advantage of not locking up the UI thread when it is processing.

WeatherWatch_2

The complete MainPage.xaml.cs code behind: