Weather Application for Windows Phone 7

Posted by: Shoban Kumar , on 3/28/2010, in Category Windows Phone
Views: 62986
Abstract: In this article we will learn how you can build a Weather application for Windows Phone 7. If this is the first time you are developing for Windows Phone 7, then I strongly suggest you to read this tutorial by ScottGu. The tutorial also talks about the tools required for developing Windows Phone 7 applications.
Weather Application for Windows Phone 7
 
In this article we will learn how you can build a Weather application for Windows Phone 7. If this is the first time you are developing for Windows Phone 7, then I strongly suggest you to read this tutorial by ScottGu. The tutorial also talks about the tools required for developing Windows Phone 7 applications.
In one my earlier article, you learnt how you can develop a Weather Application for Windows 7. We will be using the same logic to develop this application, however this time for Windows Phone
Below is the screenshot of the application which we will be developing.





Chennai-1
Let’s get started. Fire up ‘Visual Studio 2010 Express for Windows Phone’
Step 1: Click ‘New Project’and enter a name for your application.
NewProject
Step 2: Add the following controls to MainPage.xaml
a.    TextBlock
                                          i.    txtWeather : To display current weather
                                         ii.    txtCity : To display selected city name
                                        iii.    txtDay1 : To display weather forecast for day 1
                                       iv.    txtDay2 : To display weather forecast for day 2
b.    Image Control : imgWeather
c.    ListBox : LstCity : List to display the list of cities.
 
Step 3: Add the following code to the list box to populate the cities
<ListBoxItem Content="Bangalore" />
<ListBoxItem Content="Chennai" />
<ListBoxItem Content="Cochin" />
<ListBoxItem Content="Delhi" />
<ListBoxItem Content="Hyderabad" />
<ListBoxItem Content="Kolkata" />
<ListBoxItem Content="Mumbai" />
<ListBoxItem Content="Pune" />
<ListBoxItem Content="Trivandrum" />
<ListBoxItem Content="Visakhapatnam" />
 
Step 4: Add the following code to ‘SelectionChangedevent of the ListBox
 
C#
private void LstCity_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBoxItem currentCity = LstCity.SelectedItem as ListBoxItem;
            txtCity.Text = currentCity.Content.ToString();
            string strWOEID = string.Empty;
            switch (txtCity.Text)
            {
                case "Trivandrum" :
                    strWOEID = "2295426";
                    break;
                case "Bangalore":
                    strWOEID = "2295420";
                    break;
                case "Chennai":
                    strWOEID = "2295424";
                    break;
                case "Cochin":
                    strWOEID = "2295423";
                    break;
                case "Delhi":
                    strWOEID = "20070458";
                    break;
                case "Pune":
                    strWOEID = "2295412";
                    break;
                case "Kolkata":
                    strWOEID = "2295386";
                    break;
                case "Hyderabad":
                    strWOEID = "2295414";
                    break;
                case "Visakhapatnam":
                    strWOEID = "2295418";
                    break;
                case "Mumbai":
                    strWOEID = "2295411";
                    break;
            }
GetTodaysWeather(strWOEID);
        }
 
VB.NET
 
Private Sub LstCity_SelectionChanged(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
                  Dim currentCity As ListBoxItem = TryCast(LstCity.SelectedItem, ListBoxItem)
                  txtCity.Text = currentCity.Content.ToString()
                  Dim strWOEID As String = String.Empty
                  Select Case txtCity.Text
                        Case "Trivandrum"
                              strWOEID = "2295426"
                        Case "Bangalore"
                              strWOEID = "2295420"
                        Case "Chennai"
                              strWOEID = "2295424"
                        Case "Cochin"
                              strWOEID = "2295423"
                        Case "Delhi"
                              strWOEID = "20070458"
                        Case "Pune"
                              strWOEID = "2295412"
                        Case "Kolkata"
                              strWOEID = "2295386"
                        Case "Hyderabad"
                              strWOEID = "2295414"
                        Case "Visakhapatnam"
                              strWOEID = "2295418"
                        Case "Mumbai"
                              strWOEID = "2295411"
                  End Select
             GetTodaysWeather(strWOEID)
End Sub
 
In the above code, we change the txtCity’s text property to display the selected city, we assign the WEOID (Where on Earth ID) based on the selected city and finally call the function GetTodaysWeather which gets the weather forecast.
Note: Please read my earlier article about Weather Application for Windows 7 to learn about WEOID and how to get the WEOID for a location.
Step 5: Add the below code to GetTodaysWeather Function.
 
C#
 
private void GetTodaysWeather(string strWOEID)
{
   try
      {
        Uri url = new Uri("http://weather.yahooapis.com/forecastrss?w=" + strWOEID + "&u=c");
        WebClient client = new WebClient();
        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        client.DownloadStringAsync(url);
      }
   catch (Exception ex)
      {
          Messagebox.show(ex.Message);
      }
}
 
VB.NET
 
Private Sub GetTodaysWeather(ByVal strWOEID As String)
   Try
            Dim url As New Uri("http://weather.yahooapis.com/forecastrss?w=" & strWOEID & "&u=c")
            Dim client As New WebClient()
            AddHandler client.DownloadStringCompleted, AddressOf client_DownloadStringCompleted
            client.DownloadStringAsync(url)
   Catch ex As Exception
             Messagebox.show(ex.Message)
   End Try
End Sub
 
In the above code, we request the weather report for a location from Yahoo. The response from Yahoo is an XML file. We also add an event handler which will be called when the download is complete.
Step 6: Add the following code to your application which populates the Temperature, 2 days forecast and Weather Image.
C#
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                StringReader stream = new StringReader(e.Result);
                XmlReader reader = XmlReader.Create(stream);
                reader.ReadToFollowing("yweather:condition");
                //Populate Temperature
                reader.MoveToAttribute("temp");
                txtWeather.Text = reader.Value;
 
                //Set Image based on the code
                reader.MoveToAttribute("code");
                Uri url;
                url = new Uri("http://l.yimg.com/a/i/us/nws/weather/gr/" + reader.Value + "d.png");
 
                BitmapImage img = new BitmapImage(url);
                imgWeather.Source = new BitmapImage(url);
 
                //Forecast
 
                reader.ReadToFollowing("yweather:forecast");
                reader.MoveToAttribute("day");
                txtDay1.Text = reader.Value;
                reader.MoveToAttribute("low");
                txtDay1.Text += " Low: " + reader.Value;
                reader.MoveToAttribute("high");
                txtDay1.Text += " High: " + reader.Value;
 
                reader.ReadToNextSibling("yweather:forecast");
                reader.MoveToAttribute("day");
                txtDay2.Text = reader.Value;
                reader.MoveToAttribute("low");
                txtDay2.Text += " Low: " + reader.Value;
                reader.MoveToAttribute("high");
                txtDay2.Text += " High: " + reader.Value;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
 
        }
VB.NET
Private Sub client_DownloadStringCompleted(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
                  Try
                        Dim stream As New StringReader(e.Result)
                        Dim reader As XmlReader = XmlReader.Create(stream)
                        reader.ReadToFollowing("yweather:condition")
                        'Populate Temperature
                        reader.MoveToAttribute("temp")
                        txtWeather.Text = reader.Value
 
                        'Set Image based on the code
                        reader.MoveToAttribute("code")
                        Dim url As Uri
                        url = New Uri("http://l.yimg.com/a/i/us/nws/weather/gr/" & reader.Value & "d.png")
 
                        Dim img As New BitmapImage(url)
                        imgWeather.Source = New BitmapImage(url)
 
                        'Forecast
 
                        reader.ReadToFollowing("yweather:forecast")
                        reader.MoveToAttribute("day")
                        txtDay1.Text = reader.Value
                        reader.MoveToAttribute("low")
                        txtDay1.Text &= " Low: " & reader.Value
                        reader.MoveToAttribute("high")
                        txtDay1.Text &= " High: " & reader.Value
 
                        reader.ReadToNextSibling("yweather:forecast")
                        reader.MoveToAttribute("day")
                        txtDay2.Text = reader.Value
                        reader.MoveToAttribute("low")
                        txtDay2.Text &= " Low: " & reader.Value
                        reader.MoveToAttribute("high")
                        txtDay2.Text &= " High: " & reader.Value
                  Catch ex As Exception
                        MessageBox.Show(ex.Message)
                  End Try
 
End Sub
 
In the above code, we navigate to different elements of the xml file and populate Today’s weather and two days forecast. 
forecast1-1
You can learn more about the response XML file from Yahoo’s Developer page.
Silverlight Image control does not support gif files so unlike my previous article we will be using a different url for the image.
That’s it. Compile and run the application in Windows Phone 7 Emulator. Below are some screenshots for different cities.
Cochin_Pune
The entire source code of this article can be downloaded over here
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email  
ShobanKumar, Client App Dev MVP from Trivandrum is mainly working on ASP, ASP.NET, VB, VB.NET and PHP. You can also find him blogging at www.codegeeks.net. Follow him on twitter @ http://twitter.com/shobankr
 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Zoom H2 Handy on Friday, April 9, 2010 4:29 AM
Thanks for sharing such a best information with us all.
Comment posted by Raul MAyo on Tuesday, September 7, 2010 8:35 AM
Access to the data you get from Yahoo, are performed through a Web Services or Rest. Thank you
Comment posted by ali on Monday, July 11, 2011 2:03 PM
not working man
Comment posted by Farah on Tuesday, January 7, 2014 8:49 AM
Amazing article!! Thank you!

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel