Monday 11 May 2015

C# : Making a desktop weather application.


Weather application

It is an application which gives you the details of the present weather such as temperature conditions, wind speed, humidity etc. It also provides a brief forecast for the weather ahead.

How to proceed 

Prerequisite :
Basics for making form based application in C# . 

Step 1
Get through any API, which provides weather details either in JSON or XML format. (for ex Yahoo Weather API ,OpenWeatherAPI etc).
This application uses the yahoo weather API. Here we are retrieving an XML sheet from yahoo demanding the weather and conditions . XML sheet of Yahoo weather can be accessed though the following link 
http://weather.yahooapis.com/forecastrss?w=2294864 
where 2294864 is woeid number of the city assigned by Yahoo. You can find out woeid of your own city from the woeid lookup . In this project I am using the same link as give above.

Step 2 : 
Write program to read the required details from JSON or XML file and store the values for the further use in your application. In this application we are using XMLReader class of C# for collecting the information from the XML sheet. 


String st = String.Format(@"http://weather.yahooapis.com/forecastrss?w=2294864"); //URL string. In this string 2294864 is woeid of city.
XmlDocument wData = new XmlDocument();        //creating new XML document
wData.Load(st);  //laoding XML file from URL                   
XmlNamespaceManager manager = new XmlNamespaceManager(wData.NameTable); // loading namespace manager
manager.AddNamespace("yweather", @"http://xml.weather.yahoo.com/ns/rss/1.0");
XmlNode channel = wData.SelectSingleNode("rss").SelectSingleNode("channel");  //selecting a particular node
string temperature = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition",manager).Attributes["temp"].Value; //selecting an Attribue


Step 3
Retrive the stored data and display it on your GUI(Graphical User Interface) by  formatting.

Project and Code 

Set Up GUI
You may prefer developing your own GUI. Given below is a demo GUI layout which is being used by my program. If you want to copy the code then you should develop the same GUI as given in the layout.


Items in GUI
1. comboBox1  - for selecting city from a list or to enter woeid.
2. button1 - for refreshing the screen.
3. button2 - for closing the application.
4. label2, label20 - for displaying name of city and country.
5. pictureBox1 - displaying icon for present weather condition.
6. label1, label10, label9 - displaying present temperature.
7. label3 to label8 - displaying various parameters of weather
8. pictureBox1, pictureBox3 to pictureBox5 - displaying icons for weather forecast of                                                                                     consecutive days
9. label12 to label27 - displaying various parameters for weather condition of consecutive                                       days
10. label11 - displaying the last updated time.

Extra Include Files
using System.Web;          //for connecting to web
using System.Xml.Linq;     //for XML
using System.Xml;


Icons
You may download any set of icons which you want to display in your GUI. In this project I am using VClouds Weather Icons set form Deviantart. You may also download the same. Note the name of the icons must be in accordance to the weather codes (Alternative Link)
Weather codes are different weather conditions assigned as a number which is given by Yahoo in the XML sheet according to the weather condition , such as 32 for sunny day 36 for hot day. Like this there are 47 weather condition codes and 3200 is returned when data is not available and you should have 47 icons for each weather condition + 1 icon for not available :P.

Final Code

//In the given program ../Pics/ is the folder where weather icons are stored

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Xml.Linq;
using System.Xml;

namespace WeatherApp
{
    public partial class Form1 : Form
    {

        string Temperature;
        string Condition;
        string Humidity;
        string Windspeed;
        string Town;
        string Region;
        string Country;
        string Code;
        string Local;
        string woeid;
        string LastUpdate;
        string[] next_day=new string[10];
        string[] next_cond = new string[10];
        string[] next_condt = new string[10];
        string[] next_high = new string[10];
        string[] next_low = new string[10];

        public Form1()
        {
            InitializeComponent();
            woeid = "2294864";
            getWeather();
            label1.Text = Temperature;
            label2.Text = Town+", "+Region;
            label6.Text = Condition;
            label7.Text = Humidity;
            label8.Text = Windspeed;
            label10.Text = string.Format("\u00B0")+ "F";
            label12.Text = next_day[1];
            label15.Text = next_day[2];
            label17.Text = next_day[3];
            label19.Text = next_day[4];
            label20.Text = Country;
            label13.Text = next_condt[1];
            label14.Text = next_condt[2];
            label16.Text = next_condt[3];
            label18.Text = next_condt[4];

            label21.Text = next_high[1] + string.Format("\u00B0") + "F";
            label24.Text = next_high[2] + string.Format("\u00B0") + "F";
            label26.Text = next_high[3] + string.Format("\u00B0") + "F";
            label28.Text = next_high[4] + string.Format("\u00B0") + "F";
            label22.Text = next_low[1] + string.Format("\u00B0") + "F";
            label23.Text = next_low[2] + string.Format("\u00B0") + "F";
            label25.Text = next_low[3] + string.Format("\u00B0") + "F";
            label27.Text = next_low[4] + string.Format("\u00B0") + "F";
            setIcons();
            setIcon();

            comboBox1.Items.Add("Berhampur");
            comboBox1.Items.Add("Bhubaneshwar");
            comboBox1.Items.Add("Delhi");
            comboBox1.Items.Add("Kolkata");
            comboBox1.Items.Add("Mumbai");
            comboBox1.Items.Add("Chennai");
            comboBox1.Items.Add("Rourkela");
            comboBox1.Items.Add("New York");
            comboBox1.Items.Add("Los Angeles");
            comboBox1.Items.Add("London");
            comboBox1.Items.Add("Paris");
        }

        private void setIcons()
        {
            pictureBox1.Image = Image.FromFile(getString(next_cond[1]));
            pictureBox3.Image = Image.FromFile(getString(next_cond[2]));
            pictureBox4.Image = Image.FromFile(getString(next_cond[3]));
            pictureBox5.Image = Image.FromFile(getString(next_cond[4]));
        }

        private string getString(string code)
        {
            if(code.Equals("3200"))
            {
                return "../Pics/na.png";
            }
            else
            {
                return "../Pics/" + code + ".png";
            }
        }
        private void setIcon()
        {
            if(Code.Equals("3200"))
            {
                pictureBox2.Image = Image.FromFile("../Pics/na.png");
            }
            else
            {
                string st = "../Pics/"+Code+".png";
                pictureBox2.Image = Image.FromFile(st);
            }
        }
        private void getWeather()
        {
            String st = String.Format(@"http://weather.yahooapis.com/forecastrss?w=");
            st = st + woeid;
            XmlDocument wData = new XmlDocument();
            wData.Load(st);
            XmlNamespaceManager manager = new XmlNamespaceManager(wData.NameTable);
            manager.AddNamespace("yweather", @"http://xml.weather.yahoo.com/ns/rss/1.0");
            XmlNode channel = wData.SelectSingleNode("rss").SelectSingleNode("channel");
            Temperature = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition",manager).Attributes["temp"].Value;
            Condition = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition",manager).Attributes["text"].Value;
            Code = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["code"].Value;
            Humidity = channel.SelectSingleNode("yweather:atmosphere", manager).Attributes["humidity"].Value;
            Windspeed = channel.SelectSingleNode("yweather:wind", manager).Attributes["speed"].Value;
            Town = channel.SelectSingleNode("yweather:location", manager).Attributes["city"].Value;
            Region = channel.SelectSingleNode("yweather:location", manager).Attributes["region"].Value;
            Country = channel.SelectSingleNode("yweather:location", manager).Attributes["country"].Value;
            Local = channel.SelectSingleNode("item").SelectSingleNode("title", manager).InnerXml;
            LastUpdate = channel.SelectSingleNode("item").SelectSingleNode("pubDate", manager).InnerXml;
            XmlNodeList forecast = channel.SelectSingleNode("item").SelectNodes("yweather:forecast", manager);

            for(int i=0;i<forecast.Count;i++)
            {
                next_day[i] = forecast[i].Attributes["day"].Value;
                next_cond[i] = forecast[i].Attributes["code"].Value;
                next_condt[i] = forecast[i].Attributes["text"].Value;
                next_high[i] = forecast[i].Attributes["high"].Value;
                next_low[i] = forecast[i].Attributes["low"].Value;
            }
            
            label11.Text = "Last Updated on : " + LastUpdate ;
            double x = (Double.Parse(Temperature)-32) * 5.0/9.0;
            x = (int)x;
            label9.Text = x.ToString() +" "+ string.Format("\u00B0") + "C";
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            switch(comboBox1.Text)
            {
                case "Berhampur": woeid = "2295220"; break;
                case "Bhubaneshwar": woeid = "2294941"; break;
                case "Delhi": woeid = "2295019"; break;
                case "Chennai": woeid = "2295424"; break;
                case "Kolkata": woeid = "2295386"; break;
                case "Rourkela": woeid = "2294864"; break;
                case "Los Angeles": woeid = "2442047"; break;
                case "London": woeid = "44418"; break;
                case "Paris": woeid = "615702"; break;
                case "New York": woeid = "2459115"; break;
                default: woeid = comboBox1.Text; break;
            }
            getWeather();
            label1.Text = Temperature;
            label2.Text = Town + ", " + Region;
            label6.Text = Condition;
            label7.Text = Humidity;
            label8.Text = Windspeed;
            label10.Text = string.Format("\u00B0") + "F";
            label12.Text = next_day[1];
            label15.Text = next_day[2];
            label17.Text = next_day[3];
            label19.Text = next_day[4];
            label20.Text = Country;
            label13.Text = next_condt[1];
            label14.Text = next_condt[2];
            label16.Text = next_condt[3];
            label18.Text = next_condt[4];
            setIcons();
            setIcon();
        }
    }


}


Demo Screen Shot of the completed Application. You can customize GUI according to your own choice.
For queries feel free to comment or mail me.

53 comments:

  1. there are some warnings of exception through of NullReferenceException on this method first line:: how do i go about it

    private void setIcons()
    {
    pictureBox1.Image = Image.FromFile(getString(next_cond[1]));
    pictureBox3.Image = Image.FromFile(getString(next_cond[2]));
    pictureBox4.Image = Image.FromFile(getString(next_cond[3]));
    pictureBox5.Image = Image.FromFile(getString(next_cond[4]));
    }

    ReplyDelete
    Replies
    1. 1st of all you have to design GUI as given in above diagram and all the components should be named same as given in the frame diagram.
      Try it. If you still face problems I will share the competed project with you in my Dropbox :P

      Delete
    2. dude i tried it and designed as like as your gui but i am using openweathermap api so i need some change would u please send me own project

      Delete
  2. the main problem is the section of display images via a string class as also pass FileNotFoundException on the first line of method:

    private string getString(string code)
    {
    if(code.Equals("3200"))
    {
    return "../Pics/na.png";
    }
    else
    {
    return "../Pics/" + code + ".png";
    }
    }

    ReplyDelete
  3. You have to download all the weather icons from the given link http://harwenzhang.deviantart.com/art/VClouds-Weather-Icons-179152045
    Make a folder called Pics in you program directory and extract all the icons there. You would notice that the name of the icons are like 1.png , 2.png .... Above code assigns image box with the name of the file. Make sure all files are available.
    If problem still persists then replace ../Pics/ to /Pics/

    ReplyDelete
  4. thanks,but have made it out. the problem was the true directory file of the. my pics directoery is
    C:\\Users\\computer link\\Documents\\Visual Studio 2013\\Projects\\WindowsFormsWeather\\WindowsFormsWeather\\Pics\\na.png and now access images. and work very well. but the results for label 3, label 4 and label 5 are not set. they as they are of the form display..

    ReplyDelete
  5. this line in your statement is not right.: Code = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["code"].Value; with this expect a NullReferenceException, because
    the weather condition code is in the ("yweather:conditio:forecast") class.

    ReplyDelete
  6. private void setIcon()
    {
    if (Code.Equals("3200"))
    {
    pictureBox2.Image = Image.FromFile("C:\\Users\\computer link\\Documents\\Visual Studio 2013\\Projects\\WindowsFormsWeather\\WindowsFormsWeather\\Pics\\na.png");
    }
    else
    {
    string st = "C:\\Users\\computer link\\Documents\\Visual Studio 2013\\Projects\\WindowsFormsWeather\\WindowsFormsWeather\\Pics\\" + Code + ".png";
    try
    {
    pictureBox2.Image = Image.FromFile(st);
    }
    catch (FileNotFoundException b) {
    //MessageBox.Show(b.Source + "--" + b.Message);
    }
    }
    }

    ReplyDelete
  7. private void setIcons()
    {
    try
    {

    pictureBox1.Image = Image.FromFile(getString(next_cond[1]));
    pictureBox3.Image = Image.FromFile(getString(next_cond[2]));
    pictureBox4.Image = Image.FromFile(getString(next_cond[3]));
    pictureBox5.Image = Image.FromFile(getString(next_cond[4]));
    }
    catch (Exception bb)
    {
    // MessageBox.Show(bb.Source + "--" + bb.Message);
    }

    }

    ReplyDelete
  8. private void getWeather()
    {
    try
    {
    String st = String.Format(@"http://weather.yahooapis.com/forecastrss?w=");
    st = st + woeid;
    XmlDocument wData = new XmlDocument();
    wData.Load(st);
    XmlNamespaceManager manager = new XmlNamespaceManager(wData.NameTable);
    manager.AddNamespace("yweather", @"http://xml.weather.yahoo.com/ns/rss/1.0");
    XmlNode channel = wData.SelectSingleNode("rss").SelectSingleNode("channel");
    Temperature = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["temp"].Value;
    Condition = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["text"].Value;
    Code = channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", manager).Attributes["code"].Value;
    Humidity = channel.SelectSingleNode("yweather:atmosphere", manager).Attributes["humidity"].Value;
    Windspeed = channel.SelectSingleNode("yweather:wind", manager).Attributes["speed"].Value;
    Town = channel.SelectSingleNode("yweather:location", manager).Attributes["city"].Value;
    SubRegion = channel.SelectSingleNode("yweather:location", manager).Attributes["region"].Value;
    Country = channel.SelectSingleNode("yweather:location", manager).Attributes["country"].Value;
    Local = channel.SelectSingleNode("item").SelectSingleNode("title", manager).InnerXml;
    LastUpdate = channel.SelectSingleNode("item").SelectSingleNode("pubDate", manager).InnerXml;
    XmlNodeList forecast = channel.SelectSingleNode("item").SelectNodes("yweather:forecast", manager);

    for (int i = 0; i < forecast.Count; i++)
    {
    next_day[i] = forecast[i].Attributes["day"].Value;
    next_cond[i] = forecast[i].Attributes["code"].Value;
    next_condt[i] = forecast[i].Attributes["text"].Value;
    next_high[i] = forecast[i].Attributes["high"].Value;
    next_low[i] = forecast[i].Attributes["low"].Value;
    }

    label11.Text = "Last Updated on : " + LastUpdate;
    double x = (Double.Parse(Temperature) - 32) * 5.0 / 9.0;
    x = (int)x;
    label9.Text = x.ToString() + " " + string.Format("\u00B0") + "C";
    }
    catch (WebException) { }
    catch (NullReferenceException){ }

    }

    ReplyDelete
  9. thanks so much.. got what i need as a start...

    ReplyDelete
  10. Please send this complete code on yogesh.sind@gmail.com

    ReplyDelete
    Replies
    1. Download the project from this link : https://github.com/suman95/WeatherApp

      Delete
    2. http://weather.yahooapis.com/forecastrss?w=2294864
      is not working any more , is there any other suggestion
      thanks

      Delete
  11. Hi, can i get the code sent to ekfamail@gmail.com? Thanks

    ReplyDelete
    Replies
    1. Download the complete project from this link : https://github.com/suman95/WeatherApp

      Delete
  12. Hi, can i get the complete project link plz

    ReplyDelete
    Replies
    1. Download the complete project from this link : https://github.com/suman95/WeatherApp

      Delete
  13. This comment has been removed by the author.

    ReplyDelete
  14. Please send this complete code on cindynovianty98@gmail.com

    ReplyDelete
    Replies
    1. Download the complete project from this link : https://github.com/suman95/WeatherApp

      Delete


  15. Please provide valid credentials. OAuth oauth_problem="OST_OAUTH_PARAMETER_ABSENT_ERROR", realm="yahooapis.com"


    Please provide valid credentials. OAuth oauth_problem="OST_OAUTH_PARAMETER_ABSENT_ERROR", realm="yahooapis.com"



    Why??

    ReplyDelete
  16. i get this error:

    WebException was unhandler:
    An unhandled exception of type 'System.Net.WebException' occurred in System.Xml.dll

    Additional information: The remote server returned an error: (401) Unauthorized.

    ReplyDelete
  17. That's what I was looking for, thank you so much!!!

    ReplyDelete
  18. this error comming pease help me "An unhandled exception of type 'System.Net.WebException' occurred in System.Xml.dll"

    ReplyDelete
  19. http://weather.yahooapis.com/forecastrss?w=2294864
    is not working any more , is there any other suggestion
    thanks

    ReplyDelete
  20. Im getting the same exception error

    ReplyDelete
  21. This app is not functional, How do I get it to work.

    An unhandled exception of type 'System.Net.WebException' occurred in System.Xml.dll

    Additional information: The remote server returned an error: (401) Unauthorized.

    ReplyDelete
  22. Great post! I am actually getting ready to across this information, It's very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.


    AWS Training in HRBR Layout
    AWS Training in Kalyan Nagar
    Best AWS Training Institute in kalyan Nagar Bangalore

    ReplyDelete
  23. Really Good blog post.provided a helpful information.I hope that you will post more updates like this.
    AWS Training in HRBR Layout
    AWS Training in Kalyan Nagar
    Best AWS Training Institute in kalyan Nagar Bangalore

    ReplyDelete
  24. After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    python course in pune
    python course in chennai
    python Training in Bangalore

    ReplyDelete
  25. Nice post. Thanks for sharing the valuable information. it’s really helpful. Who want to learn this blog most helpful. Keep sharing on updated posts…
    Data Science Training in Indira nagar
    Data Science Training in btm layout
    Python Training in Kalyan nagar
    Data Science training in Indira nagar
    Data Science Training in Marathahalli

    ReplyDelete
  26. Really you have done great job,There are may person searching about that now they will find enough resources by your post
    Data Science course in Chennai
    Data science course in bangalore
    Data science course in pune
    Data science online course

    ReplyDelete
  27. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    Best Devops Training in pune
    Microsoft azure training in Bangalore
    Power bi training in Chennai

    ReplyDelete
  28. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    rpa training in bangalore
    best rpa training in bangalore
    rpa training in pune | rpa course in bangalore
    rpa training in chennai

    ReplyDelete
  29. All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.

    Data Science Course in Indira nagar
    Data Science Course in btm layout
    Python course in Kalyan nagar
    Data Science course in Indira nagar
    Data Science Course in Marathahalli
    Data Science Course in BTM Layout
    Data science course in bangalore

    ReplyDelete
  30. Informative post indeed, I’ve being in and out reading posts regularly and I see alot of engaging people sharing things and majority of the shared information is very valuable and so, here’s my fine read.
    click here button
    click here image
    click here for more details
    click here for new registration
    click here to login

    ReplyDelete
  31. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...data science courses

    ReplyDelete
  32. I like the helpful info you supply in your articles. I’ll bookmark your weblog and take a look at once more here regularly. I am relatively certain I will learn a lot of new stuff right here! Good luck for the following!


    sap training in chennai

    sap training in velachery

    azure training in chennai

    azure training in velachery

    cyber security course in chennai

    cyber security course in velachery

    ethical hacking course in chennai

    ethical hacking course in velachery

    ReplyDelete
  33. JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm. It has curly-bracket syntax, dynamic typing, prototype-based object-orientation, and first-class functions.Java training in chennai

    python training in chennai

    web designing and development training in chennai

    selenium training in chennai

    digital-marketing training in chennai

    ReplyDelete
  34. send me your project please , ahmedmumtaz3210@gmail.com

    ReplyDelete
  35. I really thank you for the valuable info on this great subject and look forward to more great posts
    data scientist training in hyderabad

    ReplyDelete

  36. Great blog found to be well written in a simple manner that everyone will understand and gain the enough knowledge from your blog

    DevOps Training in Hyderabad

    ReplyDelete
  37. Title:
    Best Oracle DBA Training in Chennai | Infycle Technologies

    Description:
    Did you want to set your career towards Oracle? Then Infycle is with you to make this into reality. Infycle Technologies offers the best Oracle DBA training in Chennai, which offers various stages of Oracle such as Oracle PL/SQL, etc., along with 100% hands-on training guided by experienced trainers in the field. Once after the training, the interviews will be arranged in the MNC's and firms for the placement. To have the Oracle with the best future, call 7502633633 and make this happen for your happy life.

    Best training in Chennai

    ReplyDelete
  38. Want to set your career towards Big Data? Then Infycle is with you to make this into your life. Infycle Technologies gives the combined and best Big Data Hadoop training in Chennai, along with the 100% hands-on training guided by professional teachers in the field. In addition to this, the mock interviews for the placement will be guided to the candidates, so that, they can face the interviews with full confidence. Once after the mock interview, the candidates will be placed in the top MNC's with a great salary package. To get it all, call 7502633633 and make this happen for your happy life.
    Best software training in chennai

    ReplyDelete
  39. Great post. keep sharing such a worthy information.RR Technosoft is the Devops training institute in hyderabad and it provides Class room & Online Training by real time faculty with course material and Lab Facility.

    ReplyDelete
  40. This blog was really great, never seen a great blog like this before.RR Technosoft is the Snowflake training in hyderabad and it provides Class room & Online Training by real time faculty with course material and Lab Facility.

    ReplyDelete