Ryan Harrison My blog, portfolio and technology related ramblings

C# - The Google Weather API


UPDATE - Google no longer offers a weather API. The url’s and code in this post will no longer function correctly

As you may or may not know Google has announced over the last couple of months that they plan to bring an end to a load of their services, perhaps the biggest being iGoogle.

Unfortunately one of the services they have already brought an end to is their weather API that I made of use of in this post

The code in the post now no longer works as the request URL is met with this error message

"404. That's an error"

I hope to post another update soon with examples on how to use alternative API’s.




This API will no longer function correctly as the API from Google is no longer available. The code is kept here for reference

You can obtain the current and forecast weather conditions in a user specified city with C# through the free weather API provided by Google. The main concept behind the API is to produce a URL, with a specified city, which then corresponds to an XML file that includes the weather forecast. Handily C# makes it easy to obtain this XML file, parse it, and finally print out the weather on a large variety of cities.

The URL we will be using, and modifying is -

http://www.google.com/ig/api?weather=YOUR_CITY_NAME

For example -

http://www.google.com/ig/api?weather=London

will return an XML file with the weather for London.

Now in C#, we will start by creating a Conditions class that will simply contain a bunch of properties that represent the weather in the city at a point in time -

  
class Conditions  
{  
    public string City { get; set; }  
    public string Condition { get; set; }  
    public string TempF { get; set; }  
    public string TempC { get; set; }  
    public string Humidity { get; set; }  
    public string Wind { get; set; }  
    public string Day { get; set; }  
    public string High { get; set; }  
    public string Low { get; set; }  
}  

Now we will move on to the main Weather class that will hold two methods - GetCurrentConditions, and GetForecastConditions. The GetCurrentConditions method will return one Conditions object - representing the current day, and the GetForecastedConditions method will return a List of conditions - one for each day of the forecast. Before we begin, make sure to put the following using statement at the top of the file so that we can use the various classes and methods inside the System.Xml namespace -

  
using System.Xml;  

Now we can create the public static GetCurrentConditions method that takes one string parameter representing the city -

  
public static Conditions GetCurrentConditions(string city)  
{  
    Conditions cond = new Conditions();  
    XmlDocument doc = new XmlDocument();  
    XmlTextReader reader = null;

    try  
    {  
        reader = new XmlTextReader(string.Format("http://www.google.com/ig/api?weather={0}", city));  
        doc.Load(reader);

        if (doc.SelectSingleNode("xml_api_reply/weather/problem_cause") != null)  
        {  
            cond = null;
        }  
        else  
        {  
            cond.City = doc.SelectSingleNode("/xml_api_reply/weather/forecast_information/city").Attributes["data"].InnerText;  
            cond.Condition = doc.SelectSingleNode("/xml_api_reply/weather/current_conditions/condition").Attributes["data"].InnerText;  
            cond.TempC = doc.SelectSingleNode("/xml_api_reply/weather/current_conditions/temp_c").Attributes["data"].InnerText;  
            cond.TempF = doc.SelectSingleNode("/xml_api_reply/weather/current_conditions/temp_f").Attributes["data"].InnerText;  
            cond.Humidity = doc.SelectSingleNode("/xml_api_reply/weather/current_conditions/humidity").Attributes["data"].InnerText;  
            cond.Wind = doc.SelectSingleNode("/xml_api_reply/weather/current_conditions/wind_condition").Attributes["data"].InnerText;  
        }  
    }  
    catch (Exception)  
    {  
        cond = null;
    }  
    finally  
    {  
        if (reader != null)  
            reader.Close();  
    }

    return cond;  
}  

The first thing we do is create the Conditions object, XMLDocument object (representing the returned XML file), and the XMLTextReader (which will be used to obtain the XML file and put it in our XMLDocument object).

Next, we construct the URL, adding the city string to the end of URL, and load the document into our XMLDocument object. We then do a check to see if the XML document was successfully downloaded (i.e the city is valid). If not we set the conditions object to null, which can be used as error checking in our implementation later on.

If the document is valid, we set each property of the Conditions object to the relevant portion of the XML document. The SelectSingleNode method moves to each element of the file and the data attribute and .InnerText property are used to parse the data from the document into our object. Again, if an exception is thrown, we set the Conditions object to null for error checking. Finally, we close the XMLTextReader and return the Conditions object.

The GetForecastConditions method is very similar. The only difference is the foreach loop that goes through each forecast in the forecast_conditions node, adds the conditions to a new Conditions object, and adds it to the List which is then returned at the end.

  
public static List<Conditions> GetForecastConditions(string city)  
{  
    Conditions cond = new Conditions();  
    XmlDocument doc = new XmlDocument();  
    XmlTextReader reader = null;  
    List<Conditions> conditions = new List<Conditions>();

    try  
    {  
        reader = new XmlTextReader(string.Format("http://www.google.com/ig/api?weather={0}", city));  
        doc.Load(reader);

        if (doc.SelectSingleNode("xml_api_reply/weather/problem_cause") != null)  
        {  
            conditions = null;  
        }  
        else  
        {  
            foreach (XmlNode node in doc.SelectNodes("/xml_api_reply/weather/forecast_conditions"))  
            {  
                cond = new Conditions();  
                cond.City = doc.SelectSingleNode("/xml_api_reply/weather/forecast_information/city").Attributes["data"].InnerText;  
                cond.Condition = node.SelectSingleNode("condition").Attributes["data"].InnerText;  
                cond.High = node.SelectSingleNode("high").Attributes["data"].InnerText;  
                cond.Low = node.SelectSingleNode("low").Attributes["data"].InnerText;  
                cond.Day = node.SelectSingleNode("day_of_week").Attributes["data"].InnerText;  
                conditions.Add(cond);  
            }  
        }  
    }  
    catch (Exception)  
    {  
        conditions = null;
    }  
    finally  
    {  
        if (reader != null)  
            reader.Close();  
    }

    return conditions;  
}  
Read More

Intel demonstrates 1 teraflop from a single chip

Intel has recently showcased the new ‘Knights Ferry’ processor at a supercomputing conference in Seattle. The new chip was demonstrated running in a test machine and is capable of crossing the 1 teraflop mark, or a trillion floating point operations barrier -; something previously restricted to tens of cabinets filled with processors.

To put that into perspective, Intel unveiled the first supercomputer to cross the 1 teraflop mark in 1997. That system was comprised of 9,298 Pentium II processors that filled 72 full-sized cabinets. In comparison, the new 22nm processor, called ‘Knights Ferry’, is about the size of a matchbook and can achieve the same level of performance.

Don’t expect to see these new chips anywhere anytime soon however.  Intel and its partners hope to deliver said systems by 2018.

Read More

'Tsunami' Trojan ported to Mac's

According to this post from TechSpot, researchers have discovered that hackers have now managed to port an old Linux trojan to work on Apple’s Mac OS X platform.

“Once it is running on the host machine, it connects to an IRC channel and awaits further commands from the hackers. They can then use the combined connections of the all the computers in the botnet to flood servers with requests, bringing them down in DDoS attacks. Hackers are able to download files to the infected computer for it to update itself or install additional malware, and gives complete control of the host machine to execute any command they choose.”

Mac users seem to think that their machines are immune to any form of infection. It’s good to know that the platform really isn’t as secure as many people think. Could this be the start of a new demand of anti - virus programs for Max OS X?

Read More

Java Yahtzee Game

Here is a small game of Yahtzee I have been recently working on in Java. At the moment it takes the form of a standalone swing application, although I may port it to a Java applet for in browsers games. Full source code can be found on the GitHub repository

Game screenshot

Rules for Yahtzee

Download the game (.jar)

Read More

Windows 8 Developer Preview Released

Microsoft has now released the developers preview for Windows 8, which includes -

  • A 64-bit Windows Developer Preview
  • Windows SDK for Metro style apps
  • Microsoft Visual Studio 11 Express for Windows Developer Preview
  • 28 Metro style applications including the BUILD Conference app

It’s available here.

Although I haven’t personally installed the release, here are a couple of screenshots from a user running it in a Virtual Machine.

Metro UI

This shows the new ‘Metro’ UI in Windows 8. It consists of a series of tiles and widgets that link to the most common applications. I can’t really see anyone using this on a desktop computer, but I suppose it’s meant to be for mobile devices with touchscreens, which will benefit hugely from the large icons.

Start Menu

Here is the new desktop and start menu in the developer release. Although most of the desktop is similar to that of Windows 7, huge changes can be seen in the new start menu which has been completely revamped to fit in with the new Metro style.

Ribbon in Explorer

One of the main changes in the new release is the new Ribbon in Windows Explorer. For more basic skilled users this could be a real time saver, as it stops people from trawling through the edit menu in order to find ‘Copy’. However on the other hand, on smaller resolutions the Ribbon can take up a lot of real estate, and won’t leave much room for the actual files to be displayed. I can see most advanced users instantly hiding the Ribbon, as most of it’s features can be accomplished with simple keyboard shortcuts.

Task Manager

The task manager has also been given a much needed face lift. It’s now much more graphic, and offers the user more information than in previous versions. This will also apparently be a window that many users will see, as Microsoft have recently said that most people use the task manager on a day to day basis to ‘kill’ programs. This doesn’t really say much for the developers.

Control Panel (Metro)

Metro Apps 

Finally there is the new Metro Control Panel and a possible Metro equivalent to ‘All Programs’. I hope that Microsoft still include the old versions however, as I can see trying to navigate the control panel on a desktop computer taking twice as long as it should do.

Of course this is a very early build of Windows 8, but shows a taster of what’s to come. I find it surprising that Microsoft have made such large changes from Windows 7. Obviously Microsoft are trying to integrate the new release with Windows Phone devices, and Metro will look and feel great on a touchscreen device, but I don’t really think that it offers any use whatsoever to the majority of users sitting at their desks.  Plus considering that Microsoft’s clients are mostly corporate, I can’t see the new changes being that popular with them. It will probably decrease productivity and will confuse many users, especially considering that many businesses have only just made the leap from Windows XP to Windows 7, and from Office 2003 to 2010. The leap has just been made at my college, but not without major problems. Many have had problems using Libraries, and the whole network has been down for hours at a time. Of course the problems will be fixed soon, but it doesn’t bode well for Windows 8 considering that it took the best part 8 years to upgrade to Windows 7.

Expect to see a lot more about the new release in the near future.

Read More