Microsoft Visual C# 2005 Express Edition: Build a Program Now! (43 page)

Read Microsoft Visual C# 2005 Express Edition: Build a Program Now! Online

Authors: Patrice Pelland

Tags: #General, #Computers, #C♯ (Computer program language), #Programming Languages, #C#, #Microsoft .NET Framework, #Computer Books: Languages, #Computer Graphics, #Application software, #C# (Computer program language), #Programming, #Microsoft Visual C# .NET, #Microsoft Visual C♯ .NET, #Electronic books, #Game Programming & Design, #Computing: Professional & Programming, #C (Computer program language), #Computers - Languages, #Programming Languages - C#, #Programming & scripting languages: general

BOOK: Microsoft Visual C# 2005 Express Edition: Build a Program Now!
6.86Mb size Format: txt, pdf, ePub

1 At the very top of Main.cs, add the following using statements.

1 using System.Net;

2 using System.Runtime.InteropServices;

2 At the top of the class, add the following lines just below Options optionsForm = new Options();. 3 public static double currentTemperature;

4 public static string currentZipCode = Settings.Default.CurrentZipCode; The first line of code is declared as a public static field named currentTemperature. A static field simply means that it doesn’t belong to any particular instance of that class, but that there is only one for the entire class. The currentZipCode code found in the next line is also a static field. It’s initialized from the user settings, but it will change once you complete the Options form. 3 Add the following ExtractTemperature method.

5 private Double ExtractTemperature()

6 {

7 if ((this.lblTemperatureCurrent.Text.Length == 0))

8 {

9 return int.MinValue;

190

Microsoft Visual C# 2005 Express Edition: Build a Program Now!

CSX_Chapter 9.indd 190

CSX_Chapter 9.indd 190

10/24/05 6:59:31 PM

10/24/05 6:59:31 PM

10 }

11 else

12 {

13 // Returning only the number portion ignoring the

14 // the F.

15 return Double.Parse(

16 this.lblTemperatureCurrent.Text.Substring(0,

17 this.lblTemperatureCurrent.Text.IndexOf(“°”)));

18 }

19 }

The ExtractTemperature method extracts the temperature from the lblTemperatureCurrent label and returns it as a number.

4 Add the following UpdateWeather method.

20 public void UpdateWeather()

21 {

22 try

23 {

24 this.tsmiRefresh.Enabled = false;

25 this.tsmiOptions.Enabled = false;

26 this.startBackgroundTaskCurrentDay();

27 this.tsmiRefresh.Enabled = true;

28 this.tsmiOptions.Enabled = true;

29 }

30 catch (WebException)

31 {

32 MessageBox.Show(

33 “Web service currently unavailable.\n” +

34 “Retry later using the Refresh Weather Info menu.”,

35 “Web Exception”);

36 this.tsmiRefresh.Enabled = true;

37 }

38 catch (Exception ex)

39 {

40 MessageBox.Show(

41 “Unknown problem. Error message:\n” +

42 ex.Message + “please, retry later!”, “Unknown error”);

43 this.tsmiRefresh.Enabled = true;

44 }

45 }

Chapter 9: Build Your Own Weather Tracker Application Now!

191

CSX_Chapter 9.indd 191

CSX_Chapter 9.indd 191

10/24/05 6:59:31 PM

10/24/05 6:59:31 PM

The UpdateWeather method initiates the update of the weather data by calling the startBackgroundTaskCurrentDay method you added earlier. The weather data needs to be updated when the ZIP code is changed or when the Refresh Weather Info menu choice is selected on the context menu of the notify icon. The UpdateWeather method also enables or disables menu choices on the context menu as appropriate.
Completing the Core Weather Tracker Functionality

In the next sections, you will add more code to obtain a working version of the Weather Tracker application. This includes creating the icon, verifying connectivity, verifying weather Web service availability, and other tasks.

In this section, you will add code to create and destroy the icon in the notification area. You can review the code, but I won’t discuss it in much detail because GDI+ and COM

“interop” are subjects that are too advanced for this book. However, you may want to refer to the comments within the code.

TO ADD CREATE AND DESTROY NOTIFICATION ICON CODE

1 In Main.cs, add the following CreateIcon method.

1 private void CreateIcon(int temperature)

2 {

3 string displayString;

4 Bitmap drawnIcon;

5 SolidBrush brushToDrawString;

6 Color iconColor;

7 Graphics iconGraphic;

8 FontFamily fontFamily = new FontFamily(“Arial”);

9 Font IconFont = new Font(fontFamily, 11,

10 FontStyle.Regular, GraphicsUnit.Pixel);

11

12 if ((temperature == int.MinValue))

13 {

14 displayString = “NA”;

15 iconColor = Color.Red;

16 }

17 else if ((temperature > 100))

18 {

192

Microsoft Visual C# 2005 Express Edition: Build a Program Now!

CSX_Chapter 9.indd 192

CSX_Chapter 9.indd 192

10/24/05 6:59:32 PM

10/24/05 6:59:32 PM

19 iconColor = Color.Red;

20 displayString = ((temperature - 100)).ToString();

21 }

22 else if ((temperature < 0))

23 {

24 iconColor = Color.Blue;

25 displayString = ((temperature * -1)).ToString();

26 }

27 else

28 {

29 iconColor = Color.Black;

30 displayString = temperature.ToString();

31 }

32

33 // Start by creating a new bitmap the size of an icon

34 drawnIcon = new Bitmap(16, 16);

35

36 // To draw the string we need a brush

37 brushToDrawString = new SolidBrush(iconColor);

38

39 // Creating a new graphic object so that we

40 // can call the drawstring method with our

41 // temperature or NA if there is no temp.

42 iconGraphic = Graphics.FromImage(drawnIcon);

43

44 // Now we are drawing the temperature string onto

45 // graphic and therefore on the bitmap.

46 iconGraphic.DrawString(displayString, IconFont,

47 brushToDrawString, 0, 0);

48

49 // We are getting ready to convert the bitmap into

50 // an icon and to set the notifyWeather.Icon with

51 // this newly created icon

52 IntPtr hIcon = drawnIcon.GetHicon();

53 Icon customMadeIcon = System.Drawing.Icon.FromHandle(hIcon);

54 notifyWeather.Icon = customMadeIcon;

55

56 // Now that we’re done manipulating the new icon

57 // we need to destroy the unmanaged resource,

58 // otherwise we’ll have a handle leak.

59 DestroyIcon(hIcon);

60 }

Chapter 9: Build Your Own Weather Tracker Application Now!

193

CSX_Chapter 9.indd 193

CSX_Chapter 9.indd 193

10/24/05 6:59:33 PM

10/24/05 6:59:33 PM

2 Add the following DestroyIcon method.

61 // The GetIcon method generated an unmanaged handle

62 // that we need to take care of otherwise there

63 // will be a handle leak.

64 [DllImport(“User32.dll”)]

65 public static extern bool DestroyIcon(IntPtr hIcon);

Once the application starts to load, you’ll verify that the user has a valid and established Internet connection. To verify this, you’ll make a simple HTTP request to the Microsoft Web site. If you receive an HTTP OK (e.g., 200) code back from the Web server, it means that you successfully accessed the Web page you requested. If an exception is raised, it’s because you have encountered a problem or the Microsoft.com Web site is down, which is quite rare. If a valid Internet connection is not detected, a message will be displayed. You’ll also verify that the weather Web service is up and running even before making a call to it. Again, if the Web service is not up and running, a message will be displayed.
TO ADD VERIFICATION CODE

1 In Main.cs, add the following VerifyConnectedToInternet method.

1 private Boolean VerifyConnectedToInternet()

2 {

3 try

4 {

5 WebRequest request =

6 WebRequest.Create(“http://www.microsoft.com/”);

7 HttpWebResponse response =

8 (HttpWebResponse)request.GetResponse();

9 if (response.StatusCode == HttpStatusCode.OK)

10 return true;

11 else

12 return false;

13 }

14 catch (Exception)

15 {

16 return false;

17 }

18 }

194

Microsoft Visual C# 2005 Express Edition: Build a Program Now!

CSX_Chapter 9.indd 194

CSX_Chapter 9.indd 194

10/24/05 6:59:34 PM

10/24/05 6:59:34 PM

2 Add the following VerifyWebService method.

19 private Boolean VerifyWebService()

20 {

21 try

22 {

23 WebRequest request = WebRequest.Create(

24 “http://www.ejse.com/WeatherService/Service.asmx?op=GetWeatherInfo2”); 25 HttpWebResponse response =

26 (HttpWebResponse)request.GetResponse();

27 if (response.StatusCode == HttpStatusCode.OK)

28 return true;

29 else

30 return false;

31 }

32 catch (Exception)

33 {

34 return false;

35 }

36 }

TO FINISH THE MAIN FORM

1 In Main.cs, locate the existing Main_Load event handler.

2 Modify Main_Load to look like the following.

1 private void Main_Load(object sender, EventArgs e)

2 {

3 // Splash screen business.

4 Thread.Sleep(2000);

5 splashScreen.Close();

6

7 //Changing the title of our main form with the

8 //application name and the version

9 this.Text = aboutScreen.AssemblyTitle + “ “ +

10 aboutScreen.AssemblyVersion;

11

12 //Creating temporarily the NA icon.

Chapter 9: Build Your Own Weather Tracker Application Now!

195

CSX_Chapter 9.indd 195

CSX_Chapter 9.indd 195

10/24/05 6:59:35 PM

10/24/05 6:59:35 PM

13 this.CreateIcon(int.MinValue);

14

15 if (!VerifyConnectedToInternet())

16 {

17 MessageBox.Show(

18 “Your computer doesn’t seem to be connected “ +

19 “to the Internet or your Internet connection “ +

20 “is not working properly!”);

21 this.tsmiOptions.Enabled = false;

22 this.tsmiRefresh.Enabled = false;

23 }

24 else if (!VerifyWebService())

25 {

26 MessageBox.Show(

27 “Web service is currently unavailabled.\n” +

28 “Retry later using the Refresh Weather Info menu.”,

29 “Web Service Not available”);

30 if ((currentZipCode == String.Empty))

31 this.tsmiRefresh.Enabled = false;

32 else

33 this.tsmiRefresh.Enabled = true;

34 }

35 else

36 {

37 tsmiRefresh.Enabled = false;

38 this.UpdateWeather();

39 }

40 }

The Main_Load event handler is the starting point for Weather Tracker. In this code, the My construct is used to build the title of the application by using its name and the version stored in the assembly parameters in the same manner that the About dialog box uses this information. Next, a red NA (not available) icon is drawn in the notification area that will remain until the Web service returns with positive results, in which case the temperature will be drawn as an icon. If a connection to the Internet cannot be verified or the weather Web service cannot be verified, a message is displayed and the appropriate menu choices in the notify icon context menu are disabled. If everything is working as expected, the process for obtaining the weather data is started.

In Design view, select
cmsNotify
in the component tray. In the context menu strip, double-click the 3
Refresh Weather Info
menu choice.

196

Microsoft Visual C# 2005 Express Edition: Build a Program Now!

CSX_Chapter 9.indd 196

CSX_Chapter 9.indd 196

10/24/05 6:59:36 PM

10/24/05 6:59:36 PM

Add the following code to the tsmiRefresh_Click event handler. This code initiates an update of the 4 weather data when the Refresh Weather Info menu choice in the context menu is selected. 41 private void tsmiRefresh_Click(object sender, EventArgs e)

42 {

43 this.tsmiRefresh.Enabled = false;

44 this.UpdateWeather();

45 }

In Design view, select all of the controls on the Main form. Set the BorderStyle property to
None
. 5 (You might need to click the
Properties
button at the top of the Properties window to see the list of properties.)

All of the weather forecast images need to be copied from your companion content to the same folder where the Weather Tracker application is located. You need to create a folder called Images and copy all of the *.gif weather image files into this folder.
TO ADD WEATHER ICONS

In the Solution Explorer, right-click the
Weather Tracker
project, select
Add
, and then
New Folder
. 1 Name the folder
Images
.

Using Windows Explorer, copy the *.gif images (1.gif through 47.gif) from the companion content to 2 the Images folder you just created. (The default location is \My Documents\Visual Studio 2005\

Projects\Weather Tracker\Weather Tracker\Images.)

Other books

Daylight on Iron Mountain by David Wingrove
Faith of the Fallen by Terry Goodkind
Vanity by Jane Feather
Girls' Night Out by Jenna Black
Love Never Dies by Christina Dodd
The Seven Gifts by John Mellor
Fulfilled by Allyson Young
Wanted by the Devil by Joanna Blake, Pincushion Press