weather viewer application introducing microsoft silverlight, xml, linq to xml and web services
DESCRIPTION
32. Weather Viewer Application Introducing Microsoft Silverlight, XML, LINQ to XML and Web Services. Outline. 32.1 Platform Overview 32.2 Silverlight 2 Runtime and Tools Installation 32.3 Test-Driving the Weather Viewer Application 32.4 Overviewing the Weather Viewer Application - PowerPoint PPT PresentationTRANSCRIPT
T U T O R I A L
2009 Pearson Education, Inc. All rights reserved.
1
32Weather Viewer
ApplicationIntroducing Microsoft Silverlight,
XML, LINQ to XML and Web Services
2009 Pearson Education, Inc. All rights reserved.
2
Outline
32.1 Platform Overview
32.2 Silverlight 2 Runtime and Tools Installation
32.3 Test-Driving the Weather Viewer Application
32.4 Overviewing the Weather Viewer Application
32.5 Creating the Weather Viewer Application
2009 Pearson Education, Inc. All rights reserved.
3
Outline
32.6 Calling a Web Service and Using LINQ to XML to Process the Results
32.7 Customizing the Data Presentation
32.8 Creating a Customized Silverlight Control
32.9 Final Weather Viewer Application Code
2009 Pearson Education, Inc. All rights reserved.
4
In this tutorial you will learn: ■ Use Silverlight to create a rich Internet application.■ Create Silverlight user interfaces in XAML.■ Use LINQ to XML to convert XML into a collection
of Visual Basic objects.■ Use XML Axis properties to manipulate XML
content in Visual Basic.■ Customize the appearance of existing Silverlight
controls.■ Create a custom Silverlight control.
Objectives
Application Requirements
2009 Pearson Education, Inc. All rights reserved.
5
32.3 Test-Driving the Weather Viewer Application
You have been asked to create a web-based application that allows the user to enter a zip code and displays the weather forecast for the corresponding United States city. To obtain the weather forecast, you must use a web service. The application should display the days of the week returned by the web service and the image that represents the weather for each day. The user should then be able to click the appropriate day to see the high and low temperatures for that day in both Fahrenheit and Celsius.
2009 Pearson Education, Inc. All rights reserved.
6
■ SilverlightTM is Microsoft’s platform for Rich Internet Applications
– These applications that offer the responsiveness and rich GUI features of desktop applications.
■ Silverlight runs as a browser plug-in compatible with most browsers and operating systems.
■ The user interface is described in XAML and acode-behind file contains the program logic.
32.1 Platform Overview
2009 Pearson Education, Inc. All rights reserved.
7
Silverlight 2’s .NET Platform Subset■ Silverlight is a robust, cross-platform, cross-browser
subset of the .NET platform.
■ Silverlight supports .NET collections, input/output, generics, multithreading, globalization, XML and LINQ.
■ Silverlight also includes APIs for interacting with other elements in a web page.
32.1 Platform Overview (Cont.)
2009 Pearson Education, Inc. All rights reserved.
8
Graphics and GUI Capabilities
■ Silverlight’s graphics are a subset of the WPF framework.
■ Figure 32.1 shows the default list of controls thatyou can use in Silverlight.
Figure 32.1 | Default controls listed in the IDE’s Toolbox for Silverlight applications.
32.1 Platform Overview
Silverlight 2 controls
Border Button Calendar Canvas
CheckBox ContentControl DataGrid DatePicker
Ellipse Grid GridSplitter HyperlinkButton
Image Line ListBox MediaElement
MultiScaleImage RadioButton Rectangle RepeatButton
ScrollBar ScrollViewer Slider StackPanel
TextBlock TextBox ToggleButton ToolTip
2009 Pearson Education, Inc. All rights reserved.
9
■ Data Binding– Silverlight’s data-binding model makes it easy for you to
display data from objects, collections, databases, and XML.
■ Networking– Silverlight’s networking support allows you to write
browser-based applications that invoke web services and other networking technologies.
32.1 Platform Overview (Cont.)
2009 Pearson Education, Inc. All rights reserved.
10
■ Download and install the following software:– Silverlight 2 Runtime
– Silverlight Tools Beta 1 for Visual Studio 2008
■ Silverlight is not currently available for Visual Studio Express Edition.
32.2 Silverlight 2 Runtime and Tools Installation
2009 Pearson Education, Inc. All rights reserved.
11
Test-Driving the WeatherViewer Application
■ Run the completed Weather Viewer application (Fig. 32.2).
Figure 32.2 | Weather Viewer application before the user enters a zip code.
Note that the screen capturesin this tutorial were taken inInternet Explorer 8 beta, but
the application runs in anybrowser with the Silverlight 2
runtime installed
TextBox in which the userenters the zip code
2009 Pearson Education, Inc. All rights reserved.
12
Test-Driving the WeatherViewer Application (Cont.)
■ Enter a US zip code in the TextBox (Fig. 32.3), then press the Get Weather Button to obtain the weather forecast.
Figure 32.3 | Displaying the weather forecast for the specified zip code.
User selects a day to see the detailed forecast for that day
2009 Pearson Education, Inc. All rights reserved.
13
Test-Driving the WeatherViewer Application (Cont.)
■ Click one of the days in the forecast to see the complete details for that day (Fig. 32.4).
Figure 32.4 | Complete weather details for the selected day.
Customized control displaysthe detailed forecast and
blocks the user from accessingthe rest of the GUI until the
Close Button is clicked
2009 Pearson Education, Inc. All rights reserved.
14
When the user presses the Get Weather Button:
Obtain the US zip code from the Zip Code… TextBox
Use a WebClient object to invoke the WeatherForecast web service fromw www.webservicex.net
When the response data is received from the web service:
Convert the XML weather forecast into WeatherData objects
Use data binding to display the Weather Data objects in a ListBox
32.4 Overviewing the Weather Viewer Application
2009 Pearson Education, Inc. All rights reserved.
15
When the user selects a particular day in the weather forecast:
Display the complete details of the forecast for that day
When the user clicks the Close Button in details view:
Close the details view
When the user changes the text in the Zip Code… TextBox:
Clear the contents of the ListBox
32.4 Overviewing the Weather Viewer Application (Cont.)
2009 Pearson Education, Inc. All rights reserved.
16
Action Control/Object/Class Event
submitButton Click
Obtain the zip code from the Zip
Code...TextBox
inputTextBox
Use a WebClient object to invoke
the GetWeatherByZipCode web
service from www.webservicex.net
weatherService
weatherService DownloadString-Completed
Convert the XML weather forecast
into WeatherData objects
XDocument, WeatherData
■ Use an ACE table to convert the pseudocodeinto Visual Basic (Fig. 32.5).
Figure 32.5 | Weather Viewer application’s ACE table. (Part 1 of 2.)
Action/Control/Event (ACE) Table forthe Weather Viewer Application
2009 Pearson Education, Inc. All rights reserved.
17
Action Control/Object/Class Event
Use data binding to display the
Weather Data objects in a ListBox
forecastList DownloadString-Completed
forecastList SelectionChanged
Display the complete details of the
forecast for that day
forecastList, completeDetails
closeButton Click
Close the details view completeDetails
inputTextBox TextChanged
Clear the contents of the ListBox
Figure 32.5 | Weather Viewer application’s ACE table. (Part 2 of 2.)
Action/Control/Event (ACE) Table forthe Weather Viewer Application (Cont.)
2009 Pearson Education, Inc. All rights reserved.
18
■ In Visual Studio, select File > New Project(Fig 28.6).
■ Under Visual Basic Silverlight project types, select Silverlight Application.
■ Name your project WeatherViewer.
Creating a Silverlight Application
Figure 32.6 | Creating a new Silverlight Application project.
Silverlight Application project template
2009 Pearson Education, Inc. All rights reserved.
19
■ Select Add a new Web to the solution for hosting the control and choose Web Application Project.
■ Your IDE should now appear similar to Figure 32.7.
Creating a Silverlight Application (Cont.)
Figure 32.7 | New Silverlight application in Visual Studio.
Design view split into adesigner and XAML editor
2009 Pearson Education, Inc. All rights reserved.
20
Basics of a Silverlight Application Project
■ A basic Silverlight application has two XAML files:– Page.xaml defines the application’s GUI.
– App.xaml declares your application’s shared resources, such as styles for GUI elements.
■ It also has two code-behind files.– Page.xaml.vb declares the GUI event handlers and
other methods.
– App.xaml.vb defines application-level event handlers.
32.5 Creating the Weather Viewer Application
2009 Pearson Education, Inc. All rights reserved.
21
■ The Page.xaml file is similar to the default XAML for a WPF application.
■ In Silverlight, the main element is a UserControl.
■ A Silverlight application is packaged as a .xap file.
■ The web page in which the Silverlight application will be hosted references the application’s .xap file to launch the Silverlight Runtime.
32.5 Creating the Weather Viewer Application (Cont.)
2009 Pearson Education, Inc. All rights reserved.
22
Laying Out and Building the GUI■ There are three types of layout containers in Silverlight
—Canvas, StackPanel and Grid.– A Canvas enables you to precisely control positioning.
– A StackPanel enables you to place a set of controls horizontally or vertically.
– A Grid enables you to specify rows and columns with fixed sizes or with auto-size.
32.5 Creating the Weather Viewer Application (Cont.)
2009 Pearson Education, Inc. All rights reserved.
23
■ Remove White from the Background attribute (Fig. 32.8), then type Ctrl + Space to display an IntelliSense window.
– Specify any color you wish as a hexadecimal value of the form #RRGGBB.
■ Insert the ShowGridLines attribute so that you can see the grid layout better as you design.
Defining the Layout Using Grids
Figure 32.8 | Changing the background color of the Grid and displaying grid lines.
Grid layout container with Background of LightSkyBlue and
gridlines displayed
2009 Pearson Education, Inc. All rights reserved.
24
■ Split the Grid into two rows and one column (Fig. 32.9).
– The first row’s height should be 35 pixels.
– The asterisk (*) indicates that the row should occupy all remaining space.
Defining the Layout Using Grids (Cont.)
Figure 32.9 | Defining the rows and column in the main Grid.
Defines two rows in the Grid
Defines two rows in the Grid
2009 Pearson Education, Inc. All rights reserved.
25
■ The first row of the GUI contains three elements.– Lines 16–26 of Fig. 32.10 define the Grid element that
manages the GUI controls in the first row.
– Lines 21–25 create a Grid.ColumnDefinitions element containing three ColumnDefinitions.
Defining the Layout Using Grids (Cont.)
Figure 32.10 | Defining a Grid that will contain the first row of elements in the GUI.
Defines a nested Grid withone row and three columns
2009 Pearson Education, Inc. All rights reserved.
26
■ The Border element (Fig. 32.11) contains a TextBlock element.
– The Grid.Row and Grid.Column attributes indicate the row and column in which the Border is placed.
– The Border has a CornerRadius of 10 (which rounds its corners).
Defining the Layout Using Grids (Cont.)
Figure 32.11 | Inserting controls into the nested Grid.
Defines a Border containing a TextBlock in row 0 and
column 0 of the nested Grid
Defines a TextBox in row 0 and column 1 of the
nested Grid
Defines a Button in row 0 and column 2 of the nested Grid
2009 Pearson Education, Inc. All rights reserved.
27
■ A TextBlock (Fig. 32.12) is used here just to show you that there is a second row.
Defining the Layout Using Grids (Cont.)
Figure 32.12 | Inserting an element in the second row of the main Grid.
Defines a TextBlock in row 1 of the main Grid
2009 Pearson Education, Inc. All rights reserved.
28
■ Run the application (Fig. 32.13).
■ Notice that the application does not resize automatically.
Defining the Layout Using Grids (Cont.)
Figure 32.13 | Weather Viewer running in a browser.
2009 Pearson Education, Inc. All rights reserved.
29
■ Remove the main UserControl’s Width and Height attributes.
■ The application now occupies the entire browser window (Fig. 32.14).
Defining the Layout Using Grids (Cont.)
Figure 32.14 | Resizable Weather Viewer running in a browser.
Removing the Width and Height attributes from the UserControlenables the application to resize
with the browser window
2009 Pearson Education, Inc. All rights reserved.
30
■ A web service is a software component stored on one computer that can be accessed via method calls over a network.
■ Web services have important implications for business-to-business transactions.
– They enable businesses to conduct transactions via standardized, web services rather than relying on proprietary applications.
– Web services typically are platform and language independent, so companies can collaborate without worrying about compatibility.
32.6 Calling a Web Service and UsingLINQ to XML to Process the Results
2009 Pearson Education, Inc. All rights reserved.
31
■ Web services can be invoked directly from a web browser using a technique called Representational State Transfer (REST).
– Each operation is identified by a unique URL.
32.6 Calling a Web Service and UsingLINQ to XML to Process the Results (Cont.)
2009 Pearson Education, Inc. All rights reserved.
32
■ Remove the TextBlock at lines 40–41, then double click the DataGrid control in the Toolbox to insert a DataGrid control (Fig. 32.15).
Adding a DataGrid to the GUI and Creating the submitButton’s Click Event Handler
Figure 32.15 | Inserted DataGrid element.
Defines a DataGrid control
2009 Pearson Education, Inc. All rights reserved.
33
■ The DataGrid control (Fig. 32.16) is in a separate library (known as an assembly) from the other Silverlight controls.
■ An assembly (represented as a .dll file) is the mechanism used to package compiled .NET code for reuse.
Adding a DataGrid to the GUI and Creating the submitButton’s Click Event Handler (Cont.)
Figure 32.16 | Reformatting the UserControl start tag for readability.
2009 Pearson Education, Inc. All rights reserved.
34
■ The DataGrid’s x:Name attribute (Fig. 32.17) indicates the control’s name for use in Visual Basic code.
■ The attribute AutoGenerateColumns indicates that the DataGrid should determine its columns from the source of its data.
Adding a DataGrid to the GUI and Creating the submitButton’s Click Event Handler (Cont.)
Figure 32.17 | Configuring the DataGrid.
DataGrid control configured toappear in row 1 of the main Grid
2009 Pearson Education, Inc. All rights reserved.
35
■ Right click Page.xaml in the Solution Explorer and selecting View Code.
■ At the top of the Code view, the Class Name ComboBox (Fig. 32.18) lists classes and objects.
Adding a DataGrid to the GUI and Creating the submitButton’s Click Event Handler (Cont.)
Figure 32.18 | Selecting submitButton from the Class Name ComboBox.
Selecting submitButton from theClass Name ComboBox
2009 Pearson Education, Inc. All rights reserved.
36
■ Select submitButton from the Class Name ComboBox, then select Click from the Method Name ComboBox (Fig. 32.19).
■ This generates a Click event handler for the Button.
Adding a DataGrid to the GUI and Creating the submitButton’s Click Event Handler (Cont.)
Figure 32.19 | Selecting the Click event in the Method Name ComboBox.
Selecting Click event from theMethod Name ComboBox
2009 Pearson Education, Inc. All rights reserved.
37
■ When the user presses the Get Weather Button, the application should use the zip code to invoke the web service (Fig. 32.20).
Adding a DataGrid to the GUI and Creating the submitButton’s Click Event Handler (Cont.)
Figure 32.20 | Get Weather Button’s event handling code.
Changing the Cursor to the Waitcursor to indicate that the
application is awaiting a response
Defining the web service URL
Asynchronously calling the web service
2009 Pearson Education, Inc. All rights reserved.
38
■ You must import the System.Net namespace (Fig. 32.21).
Creating a WebClient Object and UsingIt to Invoke a Web Service
Figure 32.21 | Importing the System.Net namespace.
Importing namespaceSystem.Net
2009 Pearson Education, Inc. All rights reserved.
39
■ A WebClient object must be used an instance variable (Fig. 32.22).
– The keyword WithEvents indicates that events are associated with the object.
– When the DownloadStringCompleted event occurs, the application processes and displays the information.
Creating a WebClient Object and UsingIt to Invoke a Web Service (Cont.)
Figure 32.22 | Creating a WebClient object.
Creating a WebClient object to invoke the web service
2009 Pearson Education, Inc. All rights reserved.
40
Figure 32.23 | Calling DisplayWeatherForecast in response to the WebClient’s DownloadStringCompleted event.
Display the results if there are results to process
Creating a WebClient Object and UsingIt to Invoke a Web Service (Cont.)
■ In Code view, select the weatherService object for the Class Name and select DownloadStringCompleted for the Method Name (Figure 32.23).
Changing the Cursor to the Arrow cursor to indicate that the
response has been received
2009 Pearson Education, Inc. All rights reserved.
41Creating a WebClient Object and Using
It to Invoke a Web Service (Cont.)
■ The property Error is used to determine whether an error occurred.
■ If the Result property (a String) contains the substring "Day" there is information you can display, and you call method DisplayWeather Forecast.
2009 Pearson Education, Inc. All rights reserved.
42
■ Right click the project in Solution Explorer and select Add > Existing Item.
– Navigate to C:\Examples\Tutorial32\ and select WeatherData.vb.
■ Add line 2 (Fig. 32.24) to the Page.xaml.vb code-behind file. Notice that the IDE reports an error, indicating that the namespace cannot be found.
Using LINQ to XML to Convert XML Datainto a Collection of Objects
Figure 32.24 | Importing the System.Xml.Linq namespace.
Importing namespace System.Xml.Linq
2009 Pearson Education, Inc. All rights reserved.
43
■ Right click the project in Solution Explorer and select Add Reference .
– In the .NET tab, select the assembly System.Xml.Linq (Fig. 32.25) and click OK.
Using LINQ to XML to Convert XML Datainto a Collection of Objects (Cont.)
Figure 32.25 | Adding a reference to the System.Xml.Linq assembly.
Selecting the System.Xml.Linq assembly to add to your project
2009 Pearson Education, Inc. All rights reserved.
44
■ XML uses namespaces in a manner similar to Visual Basic applications.
■ To enable XML data processing of weather data, you must import the namespace contained in the XML (Fig. 32.26).
Using LINQ to XML to Convert XML Datainto a Collection of Objects (Cont.)
Figure 32.26 | Importing the XML namespace for the weather-forecast information.
Importing the XML namespace used in the XML data
2009 Pearson Education, Inc. All rights reserved.
45
■ This method (Fig. 32.27) receives the String containing the XML returned by the web service.
■ Line 52 creates an XDocument variable and uses method XDocument.Parse to convert the String object into XML.
Using LINQ to XML to Convert XML Datainto a Collection of Objects (Cont.)
Figure 32.27 | Adding the DisplayWeatherForecast method.
Parsing the XML response String to prepare it for use with LINQ to XML
2009 Pearson Education, Inc. All rights reserved.
46
■ This LINQ query (Fig. 32.28) converts the XML data into a collection of WeatherData objects.
Using LINQ to XML to Convert XML Datainto a Collection of Objects (Cont.)
Figure 32.28 | Converting XML to WeatherData objects with LINQ to XML.
Selecting the XML’s WeatherData elements that are
Creating a new object of class WeatherData from each XML
WeatherData element
Using XML property syntax to access the XML elements within each WeatherData element and assign their values to properties of the new WeatherData object
2009 Pearson Education, Inc. All rights reserved.
47
■ The From clause indicates that we are selecting items from the weatherXML XDocument object.
– The ellipsis notation (...) represents the new XML descendants property that is used to select XML elements.
– In this case, <WeatherData> indicates that all the WeatherData elements in the XML document should be selected.
■ The Select clause creates a new WeatherData object for each WeatherData element in the XML.
Using LINQ to XML to Convert XML Datainto a Collection of Objects (Cont.)
2009 Pearson Education, Inc. All rights reserved.
48
■ The With keyword indicates that the new WeatherData object should be used implicitly to access the object’s properties.
■ The notation <Day> uses Visual Basic’s new XML child property syntax to access the child element of the WeatherData element.
Using LINQ to XML to Convert XML Datainto a Collection of Objects (Cont.)
2009 Pearson Education, Inc. All rights reserved.
49
■ Save your files to ensure that the forecastList is recognized by IntelliSense, then insert lines 72–73 (Fig. 32.29).
■ WPF’s powerful data-binding capabilities make it easy for you to display the weather data in the DataGrid.
Using LINQ to XML to Convert XML Datainto a Collection of Objects (Cont.)
Figure 32.29 | Binding the DataGrid’s ItemsSource property tothe collection of WeatherData objects.
Specifying the DataGrid’s ItemsSource from which it will
extract data to display
2009 Pearson Education, Inc. All rights reserved.
50
■ Run the application (Fig. 32.30).
■ Enter a zip code and press the Get Weather Button to invoke the web service.
Using LINQ to XML to Convert XML Datainto a Collection of Objects (Cont.)
Figure 32.30 | Displaying the weather forecast in a DataGrid.
DataGrid showing the data from a collection of WeatherData
objects
2009 Pearson Education, Inc. All rights reserved.
51
Replacing the DataGrid with a ListBox
■ Replace lines 41–42 in Page.xaml with lines 41–42 of Fig. 32.31.
■ Once you’ve added the ListBox, remove the xmlns:my declaration in line 2—it is no longer needed.
Figure 32.31 | Replacing the DataGrid with a ListBox.
Replacing the DataGridwith a ListBox
2009 Pearson Education, Inc. All rights reserved.
52
■ Run the application (Fig. 32.32). Enter a zip code and press the Get Weather button to invoke the web service.
■ By default, a ListBox shows the String representation of each item in its ItemsSource.
■ Since we did not define a ToString method for the WeatherData class, the ListBox shows the name of the class.
Replacing the DataGrid with a ListBox (Cont.)
2009 Pearson Education, Inc. All rights reserved.
53
Figure 32.32 | Showing the String representation of WeatherDataobjects in the ListBox.
ListBox rendering itsitems as Strings
Replacing the DataGrid with a ListBox (Cont.)
2009 Pearson Education, Inc. All rights reserved.
54
■ The ListBox.ItemTemplate element (Fig. 32.33) customizes the ListBox’s appearance.
■ The DataTemplate element binds data from a data source to the ListBox’s items.
■ The Image control’s Source attribute specifies the location of the image to display.
– This uses Binding markup extension to obtain the attribute’s value from the WeatherImage property of an object.
Changing the ListBox’s ItemTemplate toDisplay the Date and the Weather Image
2009 Pearson Education, Inc. All rights reserved.
55
Figure 32.33 | Changing the ListBox’s ItemTemplate.
Creating a custom ListBox ItemTemplate that displays the
weather image and date for each WeatherData object
Changing the ListBox’s ItemTemplate toDisplay the Date and the Weather Image (Cont.)
2009 Pearson Education, Inc. All rights reserved.
56
■ Run the application (Fig. 32.34).
■ Enter a zip code and press the Get Weather Button to invoke the web service.
Changing the ListBox’s ItemTemplate toDisplay the Date and the Weather Image (Cont.)
Figure 32.34 | Displaying an image and the day of the week foreach day in the weather forecast.
ListBox items rendered with a custom ItemTemplate
2009 Pearson Education, Inc. All rights reserved.
57Changing the ListBox’s ItemsPanel
to Arrange the Items Horizontally
■ The ListBox.ItemsPanel element (Fig. 32.35) specifies how the items in the ListBox should be organized.
■ The ItemsPanelTemplate specifies theorientation of the ListBox’s elements.
Figure 32.35 | Changing the ListBox’s ItemsPanel.
Creating a custom ListBox ItemsPanel that arranges the ListBox items horizontally in a
StackPanel
2009 Pearson Education, Inc. All rights reserved.
58Changing the ListBox’s ItemsPanelto Arrange the Items Horizontally (Cont.)
■ Run the application (Fig. 32.36).
■ Enter a zip code and press the Get Weather Button.
Figure 32.36 | Displaying the ListBox items horizontally.
ListBox items rendered horizontally with a custom
ItemsPanel
2009 Pearson Education, Inc. All rights reserved.
59
Adding a UserControl to the Application
■ Right click the WeatherViewer project in the Solution Explorer and select Add > New Item….
■ Select the Silverlight User Control template and name the file WeatherDetailsView.xaml (Fig. 32.37).
Figure 32.37 | Adding a new UserControl to a Silverlight application.
Silverlight User Control template
2009 Pearson Education, Inc. All rights reserved.
60
■ Remove the new UserControl’s Width and Height attributes so that the control fits thelayout container.
■ Replace the Grid element with the XAMLshown in lines 4–34 of Figure 32.38.
Adding a UserControl to the Application (Cont.)
2009 Pearson Education, Inc. All rights reserved.
61
Adding a UserControl to the Application
Figure 32.38 | Adding controls to a new UserControl.
2009 Pearson Education, Inc. All rights reserved.
62
■ The Rectangle control has its HorizontalAlignment and VerticalAlignment attributes set to Stretch, so the Rectangle fills the entire Grid cell.
– The Rectangle’s Fill attribute specifies its fill color and its Opacity attribute specifies that the Rectangle should be semitransparent.
■ The Border element encloses all the other elements inthe custom control.
– The BorderBrush attribute specifies the color of the Border, and the BorderThickness attribute controls the thickness of the Border.
■ A Binding markup extension is used to specify the WeatherData property that is bound to the control.
Adding a UserControl to the Application (Cont.)
2009 Pearson Education, Inc. All rights reserved.
63
■ Right click in the XAML for the WeatherDetailsView and select View Code.
■ In the Class Name ComboBox, select closeButton, then select Click for the Method Name (Fig. 32.39).
Adding a UserControl to the Application (Cont.)
Figure 32.39 | Click event handler for the Close Button.
Hides the custom control when the user clicks the Close Button
2009 Pearson Education, Inc. All rights reserved.
64Displaying the Complete Weather
Details for the Selected Day
■ The XML namespace called Weather (Fig. 32.40) represents the WeatherViewer namespace in the project.
■ Save your project so that it becomes aware of the new namespace.
Figure 32.40 | Adding a custom control’s namespace to the application’s Page.xaml file.
XML namespace that enables youto use the new WeatherDetailsView
in the GUI
2009 Pearson Education, Inc. All rights reserved.
65Displaying the Complete Weather
Details for the Selected Day (Cont.)
■ The Visibility attribute (Fig. 32.41) is set to Collapsed—it is not currently displayed.
■ The Grid.RowSpan attribute is set to 2—when this control is displayed, it will occupy both rowsof the Grid.
Figure 32.41 | Adding a WeatherDetailsView custom control to the GUI.
WeatherDetailsView is initially hidden and will span both rows of
the main Grid when it is displayed
2009 Pearson Education, Inc. All rights reserved.
66
■ In Page.xaml.vb, select forecastListBox from the Class Name ComboBox, then select SelectionChanged for the Method Name (Fig. 32.42).
Displaying the Complete WeatherDetails for the Selected Day (Cont.)
Figure 32.42 | forecastListBox’s SelectionChanged event handler.
Specifies that the currently selected ListBox item will supply the data for
the WeatherDetailsView
Shows the WeatherDetailsView
2009 Pearson Education, Inc. All rights reserved.
67
■ Select inputTextBox from the Class Name ComboBox, then select TextChanged for the Method Name (Fig. 32.43).
■ When a ListBox’s ItemsSource property is set to Nothing, no items will display.
Displaying the Complete WeatherDetails for the Selected Day (Cont.)
Figure 32.43 | TextChanged event handler for the inputTextBox.
Clears the ListBox when the user changes the text in the TextBox
2009 Pearson Education, Inc. All rights reserved.
68
■ Run the application.
■ Enter a zip code and press the Get Weather Button.
■ Once the weather forecast displays, click a dayin the forecast (Fig. 32.44).
Displaying the Complete WeatherDetails for the Selected Day (Cont.)
Figure 32.44 | Displaying the WeatherDetailsView for a specific day.
WeatherDetailsView displayedafter the user selected a specific
day from the ListBox
2009 Pearson Education, Inc. All rights reserved.
69
1 <UserControl
2 xmlns:Weather="clr-namespace:WeatherViewer"
3 x:Class="WeatherViewer.Page"
4 xmlns="http://schemas.microsoft.com/client/2007"
5 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
6 <Grid x:Name="LayoutRoot" Background="LightSkyBlue">
7 <Grid.RowDefinitions>
8 <RowDefinition Height="35" />
9 <RowDefinition Height="*" />
10 </Grid.RowDefinitions>
11
12 <Grid.ColumnDefinitions>
13 <ColumnDefinition Width="*" />
14 </Grid.ColumnDefinitions>
15
■ Figures 32.45–32.48 present thesource code for the application.
Outline
(1 of 4 )
XML namespace for custom WeatherDetailsView control
Defining rows in the main Grid
2009 Pearson Education, Inc. All rights reserved.
70
16 <Grid>
17 <Grid.RowDefinitions>
18 <RowDefinition Height="*" />
19 </Grid.RowDefinitions>
20
21 <Grid.ColumnDefinitions>
22 <ColumnDefinition Width="*" />
23 <ColumnDefinition Width="110" />
24 <ColumnDefinition Width="110" />
25 </Grid.ColumnDefinitions>
26
27 <Border Grid.Row="0" Grid.Column="0" CornerRadius="10"
28 Background="LightGray" Margin="2">
29 <TextBlock Text="Weather Viewer" Padding="6" />
30 </Border>
31
Outline
(2 of 4 )
Defining rows in the nested Grid
Defining a Border containing a TextBlock
2009 Pearson Education, Inc. All rights reserved.
71
32 <TextBox x:Name="inputTextBox" Grid.Row="0"
33 Grid.Column="1" FontSize="18"
34 Margin="4"/>
35
36 <Button x:Name="submitButton" Content="Get Weather"
37 Grid.Row="0" Grid.Column="2" Margin="4" />
38 </Grid>
39
40 <ListBox x:Name="forecastList" Grid.Row="1" Margin="10">
41 <ListBox.ItemsPanel>
42 <ItemsPanelTemplate>
43 <StackPanel Orientation="Horizontal" />
44 </ItemsPanelTemplate>
45 </ListBox.ItemsPanel>
46 <ListBox.ItemTemplate>
47 <DataTemplate>
48 <StackPanel Width="120" Orientation="Vertical"
49 HorizontalAlignment="Center">
Outline
(3 of 4 )
Defining a TextBoxfor user input
Defining a Button to invoke the web service
Defining a ListBox with a custom look-and-feel to display the weather forecast
2009 Pearson Education, Inc. All rights reserved.
72
50 <Image Source="{Binding WeatherImage}"
51 Margin="5" Width="55" Height="58"/>
52 <TextBlock Text="{Binding DayOfWeek}"
53 TextAlignment="Center" FontSize="12"
54 Margin="5" TextWrapping="Wrap"/>
55 </StackPanel>
56 </DataTemplate>
57 </ListBox.ItemTemplate>
58 </ListBox>
59
60 <Weather:WeatherDetailsView x:Name="completeDetails"
61 Visibility="Collapsed" Grid.RowSpan="2"/>
62 </Grid>
63 </UserControl>
Outline
(4 of 4 )
Defining a WeatherDetailsView to display the complete details view for a selected day
2009 Pearson Education, Inc. All rights reserved.
73
1 Imports System.Net ' to access the Uri class
2 Imports System.Xml.Linq ' to access LINQ to XML features
3
4 ' import the namespace for the XML returned by webservicex.net's
5 ' web service; required to access the data properly
6 Imports <xmlns="http://www.webservicex.net">
7
8 Partial Public Class Page
9 Inherits UserControl
10
11 ' object to invoke weather forecast web service
12 Dim WithEvents weatherService As New WebClient()
13
14 ' constructor
15 Public Sub New()
16 InitializeComponent()
17 End Sub ' New
18
Outline
System.Net
(1 of 6 )
Importing namespaces for class WebClient and for LINQ to XML
Importing the XML namespace used in the XML returned by the web service
Creating a WebClient toinvoke the web service
2009 Pearson Education, Inc. All rights reserved.
74
19 ' process submitButton's Click event
20 Private Sub submitButton_Click(ByVal sender As System.Object, _
21 ByVal e As System.Windows.RoutedEventArgs) _
22 Handles submitButton.Click
23
24 Dim zipcode As String = inputTextBox.Text ' get zipcode
25 Me.Cursor = System.Windows.Input.Cursors.Wait ' wait cursor
26
27 ' webserviceX.net's WeatherForecast web service URL
28 Dim forecastURL As String = _
29 "http://www.webservicex.net/WeatherForecast.asmx/" & _
30 "GetWeatherByZipCode?ZipCode=" & zipcode
31
32 ' asynchronously invoke the web service
33 weatherService.DownloadStringAsync(New Uri(forecastURL))
34 End Sub ' submitButton_Click
35
Outline
Defining the URL for invoking the web service
Invoking the web service asynchronously via the WebClient object
System.Net
(2 of 6 )
2009 Pearson Education, Inc. All rights reserved.
75
36 ' event handler to process weather forecast
37 Private Sub weatherService_DownloadStringCompleted( _
38 ByVal sender As Object, _
39 ByVal e As DownloadStringCompletedEventArgs) _
40 Handles weatherService.DownloadStringCompleted
41
42 If e.Error Is Nothing AndAlso e.Result.Contains("Day") Then
43 DisplayWeatherForecast(e.Result)
44 End If
45
46 Me.Cursor = System.Windows.Input.Cursors.Arrow ' arrow cursor
47 End Sub ' weatherService_DownloadStringCompleted
48
49 ' display weather forecast
50 Private Sub DisplayWeatherForecast(ByVal xmlData As String)
51 ' parse the XML data for use with LINQ
52 Dim weatherXML As XDocument = XDocument.Parse(xmlData)
53
Outline
Indicates that this event handler responds to the WebClient’s DownloadStringCompleted event
Uses class XDocument to parse the results of the web service for processing with LINQ to XML
System.Net
(3 of 6 )
2009 Pearson Education, Inc. All rights reserved.
76
54 ' convert XML into WeatherData objects using XML literals
55 Dim weatherInformation = _
56 From item In weatherXML...<WeatherData> _
57 Where Not item.IsEmpty _
58 Select New WeatherData With _
59 { _
60 .DayOfWeek = item.<Day>.Value, _
61 .WeatherImage = item.<WeatherImage>.Value, _
62 .MaxTemperatureF = Convert.ToInt32( _
63 item.<MaxTemperatureF>.Value), _
64 .MinTemperatureF = Convert.ToInt32( _
65 item.<MinTemperatureF>.Value), _
66 .MaxTemperatureC = Convert.ToInt32( _
67 item.<MaxTemperatureC>.Value), _
68 .MinTemperatureC = Convert.ToInt32( _
69 item.<MinTemperatureC>.Value) _
70 } ' end LINQ to XML that creates WeatherData objects
Outline
Uses LINQ to XML and XML property syntax to select all of the non-empty WeatherData elements from the XML and convert them to WeatherData objects
System.Net
(4 of 6 )
2009 Pearson Education, Inc. All rights reserved.
77
71
72 ' bind forecastList.ItemsSource to the weatherInformation
73 forecastList.ItemsSource = weatherInformation
74 End Sub ' DisplayWeatherForecast
75
76 ' Show details of the selected day
77 Private Sub forecastList_SelectionChanged( _
78 ByVal sender As Object, ByVal e As _
79 System.Windows.Controls.SelectionChangedEventArgs) _
80 Handles forecastList.SelectionChanged
81
82 If forecastList.SelectedItem IsNot Nothing Then
83 ' specify the WeatherData object containing the details
84 completeDetails.DataContext = forecastList.SelectedItem
85
86 ' show the complete weather details
87 completeDetails.Visibility = Windows.Visibility.Visible
88 End If
89 End Sub ' forecastList_SelectionChanged
Outline
Specifying that the ListBox should be populated from the collection of WeatherData objects
Specifying that the WeatherDetailsView should obtain its data from the selected item in the ListBox
Showing the WeatherDetailsView
System.Net
(5 of 6 )
2009 Pearson Education, Inc. All rights reserved.
78
90
91 ' clear the Grid when the text in inputTextBox changes
92 Private Sub inputTextBox_TextChanged(ByVal sender As Object, _
93 ByVal e As System.Windows.Controls.TextChangedEventArgs) _
94 Handles inputTextBox.TextChanged
95
96 forecastList.ItemsSource = Nothing ' clear the ListBox
97 End Sub ' inputTextBox_TextChanged
98 End Class ' Page
Outline
Clearing the ListBox when the user begins typing a new zip code
System.Net
(6 of 6 )
2009 Pearson Education, Inc. All rights reserved.
79
1 <UserControl x:Class="WeatherViewer.WeatherDetailsView"
2 xmlns="http://schemas.microsoft.com/client/2007"
3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
4 <Grid>
5 <Rectangle HorizontalAlignment="Stretch" Fill="Aquamarine"
6 VerticalAlignment="Stretch" Opacity="0.8" />
7 <Border CornerRadius="20" Background="AliceBlue"
8 BorderBrush="Blue" BorderThickness="4"
9 Width="400" Height="175">
10 <StackPanel>
11 <Image Source="{Binding WeatherImage}"
12 Margin="5" Width="55" Height="58" />
13 <TextBlock Text="{Binding DayOfWeek}" Margin="5"
14 TextAlignment="Center" FontSize="12"
15 TextWrapping="Wrap" />
Outline
(1 of 2 )
Creating a Rectangle to hide the other controls on the GUI when a WeatherDetailsView is displayed
Using data binding to display WeatherData properties in the WeatherDetailsView
2009 Pearson Education, Inc. All rights reserved.
80
16 <StackPanel HorizontalAlignment="Center"
17 Orientation="Horizontal">
18 <TextBlock Text="Max F:" Margin="5" FontSize="16"/>
19 <TextBlock Text="{Binding MaxTemperatureF}"
20 Margin="5" FontSize="16" FontWeight="Bold"/>
21 <TextBlock Text="Min F:" Margin="5" FontSize="16"/>
22 <TextBlock Text="{Binding MinTemperatureF}"
23 Margin="5" FontSize="16" FontWeight="Bold"/>
24 <TextBlock Text="Max C:" Margin="5" FontSize="16"/>
25 <TextBlock Text="{Binding MaxTemperatureC}"
26 Margin="5" FontSize="16" FontWeight="Bold"/>
27 <TextBlock Text="Min C:" Margin="5" FontSize="16"/>
28 <TextBlock Text="{Binding MinTemperatureC}"
29 Margin="5" FontSize="16" FontWeight="Bold"/>
30 </StackPanel>
31 <Button x:Name="closeButton" Content="Close" Width="80"/>
32 </StackPanel>
33 </Border>
34 </Grid>
35 </UserControl>
Outline
(2 of 2 )
2009 Pearson Education, Inc. All rights reserved.
81
1 Partial Public Class WeatherDetailsView
2 Inherits UserControl
3
4 Public Sub New()
5 InitializeComponent()
6 End Sub ' New
7
8 ' close the details view
9 Private Sub closeButton_Click(ByVal sender As Object, _
10 ByVal e As System.Windows.RoutedEventArgs) _
11 Handles closeButton.Click
12
13 Me.Visibility = Windows.Visibility.Collapsed
14 End Sub ' closeButton_Click
15 End Class ' WeatherDetailsView
Outline
Hiding the WeatherDetailsView when its Close Button is pressed