Go Back   CodeCall Programming Forum > Software Development > Tutorials > CSharp Tutorials
Register Blogs Search Today's Posts Mark Forums Read

CSharp Tutorials Tutorials for C#

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 09-01-2009, 04:13 PM
Parabola's Avatar
Programming Professional
 
Join Date: Jul 2009
Location: Texas
Age: 25
Posts: 299
Parabola will become famous soon enoughParabola will become famous soon enough
Send a message via AIM to Parabola Send a message via MSN to Parabola Send a message via Yahoo to Parabola Send a message via Skype™ to Parabola
C# Tutorial: Creating a personal weather app

Today's project is to create an app that will display weather information from a city, including the forecast. We will be using an extra API, the animaonline weather API using google weather, which is included with the source code.
Tasks demonstrated:
  • Populating text and image fields
  • Saving user input / settings (finally figured this one out)
  • Automatically refreshing data at a specified interval
This is not a quick project, it does take a little bit of time, but it is also a project anyone should be able to do and learn something from.
For an example of the finished product, download mine here:
http://jmangum.codecall.net/weather/setup.exe

OK, let's begin
Download the source file (attached, or go to: cweather - Project Hosting on Google Code) Included in this source is of course the code, but also the animaonline Weather API, and an icon.

Step 1: Create our project, and reference the needed API
1. Create a new project, a winforms app of course. Name it Weather.
2. Rename Form1 to weatherForm
3. Go ahead and copy the API.dll and the icon into the root folder of your project, just to make things easier.
4. Go to the references for your project, and add the animaonline weather api.
5. Add the following code to the top of the source for your weatherForm:
Code:
using Animaonline.WeatherAPI;
using System.Threading;
using Weather.Properties;
Step 2: Create user settings
1. Right click on your project, and go to properties. Then select the settings tab.
2. Create the following settings:

windowPosition is of type System.Drawing.Point
3. Save.
Step 3: Start declaring some variables
1. Open the code for weatherForm.designer.cs
2. Add these line in right after #endregion:
Code:
        private Animaonline.WeatherAPI.WeatherData wD;
        private string City;
        private int delay;
Now before we can go much further, we have to design our form. This part takes a little more time, since we have to create all of our labels and imageboxes.
Step 4: Design the form
1. Resize the form itself. Make it 696, 231
2. This picture will show you how to make the form look, but don't actually put the text into the label's and the textbox: that's there so you know what to NAME them. leave the text blank on all of them EXCEPT Current Conditions and AutoUpdate: (name those whatever you want, they are static)
The Boxes are PictureBox's.. name them icnCurrent, icnToday, icnTomorrow, icnDay2, and icnDay3
For your comboBox, name it comboBoxEdit1. I'll give you the list items after the picture.

3. The comboBox:
list items are:
  • Never
  • 1 Minute
  • 2 Minutes
  • 5 Minutes
  • 10 Minutes
  • 30 Minutes
  • 1 Hour
  • 2 Hours
  • 4 Hours
Go into the properties for it, and under application settings, property binding, change the Text option to intervalText. Change dropdown style (near the top of properties) to DropDownList.
4. txtCity: Once again, application settings, property bindings: Text = defaultCity
5. Under components, add a timer. You can leave this named timer1. However, once again, go to the property bindings, and set interval to intervalTime, enabled to timerOn.
6. The form itself: data binding again, set the location to windowLocation
Step 5: Let's start coding
1. First, lets tell the program when to load and save our settings.
Under initialize component, add the following code:
Code:
            delay = Settings.Default.intervalTime;
            txtCity.Text = Settings.Default.defaultCity;
            this.Location = Settings.Default.windowPosition;
            comboBoxEdit1.Text = Settings.Default.intervalText;
            timer1.Enabled = Settings.Default.timerOn;
This loads our settings.
2. We need to write a function to get the weather data and populate the fields. Here's the code:
Code:
private void getWeather(string City)
        {
            try
            {
                //Get the data
                wD = WeatherAPI.GetWeather(LanguageCode.en_US, City);

                //Set image locations
                string baseURL = "http://www.google.com";
                string iconToday = baseURL + wD.iconTODAY;
                string icon = baseURL + wD.icon;
                string iconTOMORROW = baseURL + wD.iconTOMORROW;
                string iconDAY2 = baseURL + wD.iconDAY2;
                string iconDAY3 = baseURL + wD.iconDAY3;

                //Set images
                icnCurrent.ImageLocation = icon;
                icnDay2.ImageLocation = iconDAY2;
                icnDay3.ImageLocation = iconDAY3;
                icnToday.ImageLocation = iconToday;
                icnTomorrow.ImageLocation = iconTOMORROW;

                //Current Conditions
                lblCity.Text = wD.city;
                lblCurrentCond.Text = wD.condition;
                lblCurrentF.Text = "Temperature: " + wD.temp_f.ToString() + "°F";
                lblWind.Text = wD.wind_condition;

                //Day 2's Conditions
                lblDay2.Text = wD.day_of_weekDAY2;
                lblDay2Cond.Text = wD.conditionDAY2;
                lblDay2High.Text = "High:  " + wD.highDAY2.ToString() + "°F";
                lblDay2Low.Text = "Low:  " + wD.lowDAY2.ToString() + "°F";

                //Day 3's Conditions
                lblDay3.Text = wD.day_of_weekDAY3;
                lblDay3Cond.Text = wD.conditionDAY3;
                lblDay3High.Text = "High:  " + wD.highDAY3.ToString() + "°F";
                lblDay3Low.Text = "Low:  " + wD.lowDAY3.ToString() + "°F";

                //Today's Conditions
                lblToday.Text = wD.day_of_weekTODAY;
                lblTodayCond.Text = wD.conditionTODAY;
                lblTodayHigh.Text = "High:  " + wD.highTODAY.ToString() + "°F";
                lblTodayLow.Text = "Low:  " + wD.lowTODAY.ToString() + "°F";

                //Tomorrow's Conditions
                lblTomorrow.Text = wD.day_of_weekTOMORROW;
                lblTomorrowCond.Text = wD.conditionTOMORROW;
                lblTomorrowHigh.Text = "High:  " + wD.highTOMORROW.ToString() + "°F";
                lblTomorrowLow.Text = "Low:  " + wD.lowTOMORROW.ToString() + "°F";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
Notice we use a try / catch statement. This way, if there is an error, the program won't crash, it will just tell us what happened.
3. Now go back to where we loaded the settings, and add this:
Code:
            //Get Initial Weather
            City = txtCity.Text;
            getWeather(City);
Now, when the app loads, it will automatically get the weather data.
4. Now we need a function to handle the intervals
Code:
        private void getDelay(string Selection)
        {
            //Set the delay based on User Selection
            if (Selection == "Never")
                delay = 1;
            if (Selection == "1 Minute")
                delay = 1;
            if (Selection == "2 Minutes")
                delay = 2;
            if (Selection == "5 Minutes")
                delay = 5;
            if (Selection == "10 Minute")
                delay = 10;
            if (Selection == "30 Minutes")
                delay = 30;
            if (Selection == "1 Hour")
                delay = 1 * 60;
            if (Selection == "2 Hours")
                delay = 2 * 60;
            if (Selection == "4 Hours")
                delay = 4 * 60;
            if (Selection == "Select AutoUpdate Interval")
                delay = 1;
            delay = (delay * 60000);
            
        }
5. Now go back and doubleclick on the button named getW.
Add the following code to that button:
Code:
//Set delay from minutes to milliseconds
            getDelay(comboBoxEdit1.Text);
            
            //Get Weather
            City = txtCity.Text;
            getWeather(City);

            //Set timer1
            if (comboBoxEdit1.Text == "Never")
            {
                timer1.Enabled = false;
            }
            else
            {
                timer1.Interval = delay;
                timer1.Enabled = true;
            }
6. Now double click on timer1 and add this code to it:
Code:
            //Refresh Weather Data
            getWeather(City);
7. Now, we need the program to save the users settings.
Under the design of the form, go to the forms events, double click where it says FormClosed, and add this code to the new section:
Code:
            //Save Settings
            Settings.Default.defaultCity = txtCity.Text;
            Settings.Default.intervalText = comboBoxEdit1.Text;
            Settings.Default.windowPosition = this.Location;
            Settings.Default.timerOn = timer1.Enabled;
            Settings.Default.intervalTime = delay;
            Settings.Default.Save();
Step 6: Finishing Touches
1. Form Properties: MaximizeBox and MinimizeBox need to both be False
2. SizeGrip should be set to Hide.
3. Set the icon to the provided icon.


Just to recap, here's what your code should look like:
Code:
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 Animaonline.WeatherAPI;
using System.Threading;
using Weather.Properties;

namespace Weather
{
    public partial class weatherForm : Form
    {
        public weatherForm()
        {
            InitializeComponent();

            //Load settings
            delay = Settings.Default.intervalTime;
            txtCity.Text = Settings.Default.defaultCity;
            this.Location = Settings.Default.windowPosition;
            comboBoxEdit1.Text = Settings.Default.intervalText;
            timer1.Enabled = Settings.Default.timerOn;

            //Get Initial Weather
            City = txtCity.Text;
            getWeather(City);
            
        }

        private void weatherForm_Load(object sender, EventArgs e)
        {

        }

        private void getWeather(string City)
        {
            try
            {
                //Get the data
                wD = WeatherAPI.GetWeather(LanguageCode.en_US, City);

                //Set image locations
                string baseURL = "http://www.google.com";
                string iconToday = baseURL + wD.iconTODAY;
                string icon = baseURL + wD.icon;
                string iconTOMORROW = baseURL + wD.iconTOMORROW;
                string iconDAY2 = baseURL + wD.iconDAY2;
                string iconDAY3 = baseURL + wD.iconDAY3;

                //Set images
                icnCurrent.ImageLocation = icon;
                icnDay2.ImageLocation = iconDAY2;
                icnDay3.ImageLocation = iconDAY3;
                icnToday.ImageLocation = iconToday;
                icnTomorrow.ImageLocation = iconTOMORROW;

                //Current Conditions
                lblCity.Text = wD.city;
                lblCurrentCond.Text = wD.condition;
                lblCurrentF.Text = "Temperature: " + wD.temp_f.ToString() + "°F";
                lblWind.Text = wD.wind_condition;

                //Day 2's Conditions
                lblDay2.Text = wD.day_of_weekDAY2;
                lblDay2Cond.Text = wD.conditionDAY2;
                lblDay2High.Text = "High:  " + wD.highDAY2.ToString() + "°F";
                lblDay2Low.Text = "Low:  " + wD.lowDAY2.ToString() + "°F";

                //Day 3's Conditions
                lblDay3.Text = wD.day_of_weekDAY3;
                lblDay3Cond.Text = wD.conditionDAY3;
                lblDay3High.Text = "High:  " + wD.highDAY3.ToString() + "°F";
                lblDay3Low.Text = "Low:  " + wD.lowDAY3.ToString() + "°F";

                //Today's Conditions
                lblToday.Text = wD.day_of_weekTODAY;
                lblTodayCond.Text = wD.conditionTODAY;
                lblTodayHigh.Text = "High:  " + wD.highTODAY.ToString() + "°F";
                lblTodayLow.Text = "Low:  " + wD.lowTODAY.ToString() + "°F";

                //Tomorrow's Conditions
                lblTomorrow.Text = wD.day_of_weekTOMORROW;
                lblTomorrowCond.Text = wD.conditionTOMORROW;
                lblTomorrowHigh.Text = "High:  " + wD.highTOMORROW.ToString() + "°F";
                lblTomorrowLow.Text = "Low:  " + wD.lowTOMORROW.ToString() + "°F";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void getDelay(string Selection)
        {
            //Set the delay based on User Selection
            if (Selection == "Never")
                delay = 1;
            if (Selection == "1 Minute")
                delay = 1;
            if (Selection == "2 Minutes")
                delay = 2;
            if (Selection == "5 Minutes")
                delay = 5;
            if (Selection == "10 Minute")
                delay = 10;
            if (Selection == "30 Minutes")
                delay = 30;
            if (Selection == "1 Hour")
                delay = 1 * 60;
            if (Selection == "2 Hours")
                delay = 2 * 60;
            if (Selection == "4 Hours")
                delay = 4 * 60;
            if (Selection == "Select AutoUpdate Interval")
                delay = 1;
            delay = (delay * 60000);

        }

        private void getW_Click(object sender, EventArgs e)
        {
            //Set delay from minutes to milliseconds
            getDelay(comboBoxEdit1.Text);

            //Get Weather
            City = txtCity.Text;
            getWeather(City);

            //Set timer1
            if (comboBoxEdit1.Text == "Never")
            {
                timer1.Enabled = false;
            }
            else
            {
                timer1.Interval = delay;
                timer1.Enabled = true;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //Refresh Weather Data
            getWeather(City);
        }

        private void weatherForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Save Settings
            Settings.Default.defaultCity = txtCity.Text;
            Settings.Default.intervalText = comboBoxEdit1.Text;
            Settings.Default.windowPosition = this.Location;
            Settings.Default.timerOn = timer1.Enabled;
            Settings.Default.intervalTime = delay;
            Settings.Default.Save();
        }
    }
}
go ahead and give it a run, it should work fine.
Attached Files
File Type: rar Weather.rar (536.0 KB, 294 views)
__________________
Programmer (n): An organism that can turn caffeine into code.
Programming would be so much easier without all the users.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 09-02-2009, 08:09 AM
Jordan's Avatar
Administrator
 
Join Date: Nov 2005
Location: Hendersonville, NC
Posts: 24,556
Jordan is a name known to allJordan is a name known to allJordan is a name known to allJordan is a name known to allJordan is a name known to allJordan is a name known to all
Send a message via ICQ to Jordan Send a message via AIM to Jordan Send a message via MSN to Jordan Send a message via Yahoo to Jordan
Re: C# Tutorial: Creating a personal weather app

Wow, very cool tutorial/project! +rep
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 09-02-2009, 05:07 PM
WingedPanther's Avatar
Super Moderator
 
Join Date: Jul 2006
Age: 36
Posts: 11,435
WingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud of
Re: C# Tutorial: Creating a personal weather app

Very well done. +rep
__________________
CodeCall Blog | CodeCall Wiki | Shareware
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes


Similar Threads
Thread Thread Starter Forum Replies Last Post
Tutorial: Storing Images in MySQL with PHP Jordan PHP Tutorials 43 01-16-2010 11:35 AM
C# Tutorial: Creating a report using a Date Picker Parabola CSharp Tutorials 5 08-05-2009 02:21 PM
Beginning PHP-GTK: Creating a Simple Interface [Tutorial] Jordan PHP Tutorials 6 07-20-2009 06:27 PM
CodeCall Tutorial Contest #4 Jordan Announcements 29 02-25-2008 12:25 PM
John's Java Tutorial Index John Java Tutorials 0 01-11-2007 04:05 PM


All times are GMT -5. The time now is 11:19 AM.


vBulletin v3.8.0 ©2010, Jelsoft Enterprises Ltd.


no new posts

LinkBacks Enabled by vBSEO 3.1.0